ovs-atomic: Delete atomic, atomic_flag, ovs_refcount destroy functions.
[sliver-openvswitch.git] / lib / dpif-netdev.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "dpif.h"
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <netinet/in.h>
25 #include <sys/socket.h>
26 #include <net/if.h>
27 #include <stdint.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/ioctl.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33
34 #include "classifier.h"
35 #include "csum.h"
36 #include "dpif.h"
37 #include "dpif-provider.h"
38 #include "dummy.h"
39 #include "dynamic-string.h"
40 #include "flow.h"
41 #include "hmap.h"
42 #include "latch.h"
43 #include "list.h"
44 #include "meta-flow.h"
45 #include "netdev.h"
46 #include "netdev-vport.h"
47 #include "netlink.h"
48 #include "odp-execute.h"
49 #include "odp-util.h"
50 #include "ofp-print.h"
51 #include "ofpbuf.h"
52 #include "packets.h"
53 #include "poll-loop.h"
54 #include "random.h"
55 #include "seq.h"
56 #include "shash.h"
57 #include "sset.h"
58 #include "timeval.h"
59 #include "unixctl.h"
60 #include "util.h"
61 #include "vlog.h"
62
63 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
64
65 /* By default, choose a priority in the middle. */
66 #define NETDEV_RULE_PRIORITY 0x8000
67
68 /* Configuration parameters. */
69 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
70
71 /* Enough headroom to add a vlan tag, plus an extra 2 bytes to allow IP
72  * headers to be aligned on a 4-byte boundary.  */
73 enum { DP_NETDEV_HEADROOM = 2 + VLAN_HEADER_LEN };
74
75 /* Queues. */
76 enum { N_QUEUES = 2 };          /* Number of queues for dpif_recv(). */
77 enum { MAX_QUEUE_LEN = 128 };   /* Maximum number of packets per queue. */
78 enum { QUEUE_MASK = MAX_QUEUE_LEN - 1 };
79 BUILD_ASSERT_DECL(IS_POW2(MAX_QUEUE_LEN));
80
81 /* Protects against changes to 'dp_netdevs'. */
82 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
83
84 /* Contains all 'struct dp_netdev's. */
85 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
86     = SHASH_INITIALIZER(&dp_netdevs);
87
88 struct dp_netdev_upcall {
89     struct dpif_upcall upcall;  /* Queued upcall information. */
90     struct ofpbuf buf;          /* ofpbuf instance for upcall.packet. */
91 };
92
93 /* A queue passing packets from a struct dp_netdev to its clients.
94  *
95  *
96  * Thread-safety
97  * =============
98  *
99  * Any access at all requires the owning 'dp_netdev''s queue_mutex. */
100 struct dp_netdev_queue {
101     struct dp_netdev_upcall upcalls[MAX_QUEUE_LEN] OVS_GUARDED;
102     unsigned int head OVS_GUARDED;
103     unsigned int tail OVS_GUARDED;
104 };
105
106 /* Datapath based on the network device interface from netdev.h.
107  *
108  *
109  * Thread-safety
110  * =============
111  *
112  * Some members, marked 'const', are immutable.  Accessing other members
113  * requires synchronization, as noted in more detail below.
114  *
115  * Acquisition order is, from outermost to innermost:
116  *
117  *    dp_netdev_mutex (global)
118  *    port_rwlock
119  *    flow_mutex
120  *    cls.rwlock
121  *    queue_mutex
122  */
123 struct dp_netdev {
124     const struct dpif_class *const class;
125     const char *const name;
126     struct ovs_refcount ref_cnt;
127     atomic_flag destroyed;
128
129     /* Flows.
130      *
131      * Readers of 'cls' and 'flow_table' must take a 'cls->rwlock' read lock.
132      *
133      * Writers of 'cls' and 'flow_table' must take the 'flow_mutex' and then
134      * the 'cls->rwlock' write lock.  (The outer 'flow_mutex' allows writers to
135      * atomically perform multiple operations on 'cls' and 'flow_table'.)
136      */
137     struct ovs_mutex flow_mutex;
138     struct classifier cls;      /* Classifier.  Protected by cls.rwlock. */
139     struct hmap flow_table OVS_GUARDED; /* Flow table. */
140
141     /* Queues.
142      *
143      * Everything in 'queues' is protected by 'queue_mutex'. */
144     struct ovs_mutex queue_mutex;
145     struct dp_netdev_queue queues[N_QUEUES];
146     struct seq *queue_seq;      /* Incremented whenever a packet is queued. */
147
148     /* Statistics.
149      *
150      * ovsthread_counter is internally synchronized. */
151     struct ovsthread_counter *n_hit;    /* Number of flow table matches. */
152     struct ovsthread_counter *n_missed; /* Number of flow table misses. */
153     struct ovsthread_counter *n_lost;   /* Number of misses not passed up. */
154
155     /* Ports.
156      *
157      * Any lookup into 'ports' or any access to the dp_netdev_ports found
158      * through 'ports' requires taking 'port_rwlock'. */
159     struct ovs_rwlock port_rwlock;
160     struct hmap ports OVS_GUARDED;
161     struct seq *port_seq;       /* Incremented whenever a port changes. */
162
163     /* Forwarding threads. */
164     struct latch exit_latch;
165     struct dp_forwarder *forwarders;
166     size_t n_forwarders;
167 };
168
169 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
170                                                     odp_port_t)
171     OVS_REQ_RDLOCK(dp->port_rwlock);
172
173 /* A port in a netdev-based datapath. */
174 struct dp_netdev_port {
175     struct hmap_node node;      /* Node in dp_netdev's 'ports'. */
176     odp_port_t port_no;
177     struct netdev *netdev;
178     struct netdev_saved_flags *sf;
179     struct netdev_rx *rx;
180     char *type;                 /* Port type as requested by user. */
181 };
182
183 /* A flow in dp_netdev's 'flow_table'.
184  *
185  *
186  * Thread-safety
187  * =============
188  *
189  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
190  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
191  *
192  * Motivation
193  * ----------
194  *
195  * The thread safety rules described here for "struct dp_netdev_flow" are
196  * motivated by two goals:
197  *
198  *    - Prevent threads that read members of "struct dp_netdev_flow" from
199  *      reading bad data due to changes by some thread concurrently modifying
200  *      those members.
201  *
202  *    - Prevent two threads making changes to members of a given "struct
203  *      dp_netdev_flow" from interfering with each other.
204  *
205  *
206  * Rules
207  * -----
208  *
209  * A flow 'flow' may be accessed without a risk of being freed by code that
210  * holds a read-lock or write-lock on 'cls->rwlock' or that owns a reference to
211  * 'flow->ref_cnt' (or both).  Code that needs to hold onto a flow for a while
212  * should take 'cls->rwlock', find the flow it needs, increment 'flow->ref_cnt'
213  * with dpif_netdev_flow_ref(), and drop 'cls->rwlock'.
214  *
215  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
216  * flow from being deleted from 'cls' (that's 'cls->rwlock') and it doesn't
217  * protect members of 'flow' from modification (that's 'flow->mutex').
218  *
219  * 'flow->mutex' protects the members of 'flow' from modification.  It doesn't
220  * protect the flow from being deleted from 'cls' (that's 'cls->rwlock') and it
221  * doesn't prevent the flow from being freed (that's 'flow->ref_cnt').
222  *
223  * Some members, marked 'const', are immutable.  Accessing other members
224  * requires synchronization, as noted in more detail below.
225  */
226 struct dp_netdev_flow {
227     /* Packet classification. */
228     const struct cls_rule cr;   /* In owning dp_netdev's 'cls'. */
229
230     /* Hash table index by unmasked flow. */
231     const struct hmap_node node; /* In owning dp_netdev's 'flow_table'. */
232     const struct flow flow;      /* The flow that created this entry. */
233
234     /* Number of references.
235      * The classifier owns one reference.
236      * Any thread trying to keep a rule from being freed should hold its own
237      * reference. */
238     struct ovs_refcount ref_cnt;
239
240     /* Protects members marked OVS_GUARDED.
241      *
242      * Acquire after datapath's flow_mutex. */
243     struct ovs_mutex mutex OVS_ACQ_AFTER(dp_netdev_mutex);
244
245     /* Statistics.
246      *
247      * Reading or writing these members requires 'mutex'. */
248     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
249     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
250     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
251     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
252
253     /* Actions.
254      *
255      * Reading 'actions' requires 'mutex'.
256      * Writing 'actions' requires 'mutex' and (to allow for transactions) the
257      * datapath's flow_mutex. */
258     struct dp_netdev_actions *actions OVS_GUARDED;
259 };
260
261 static struct dp_netdev_flow *dp_netdev_flow_ref(
262     const struct dp_netdev_flow *);
263 static void dp_netdev_flow_unref(struct dp_netdev_flow *);
264
265 /* A set of datapath actions within a "struct dp_netdev_flow".
266  *
267  *
268  * Thread-safety
269  * =============
270  *
271  * A struct dp_netdev_actions 'actions' may be accessed without a risk of being
272  * freed by code that holds a read-lock or write-lock on 'flow->mutex' (where
273  * 'flow' is the dp_netdev_flow for which 'flow->actions == actions') or that
274  * owns a reference to 'actions->ref_cnt' (or both). */
275 struct dp_netdev_actions {
276     struct ovs_refcount ref_cnt;
277
278     /* These members are immutable: they do not change during the struct's
279      * lifetime.  */
280     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
281     unsigned int size;          /* Size of 'actions', in bytes. */
282 };
283
284 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
285                                                    size_t);
286 struct dp_netdev_actions *dp_netdev_actions_ref(
287     const struct dp_netdev_actions *);
288 void dp_netdev_actions_unref(struct dp_netdev_actions *);
289
290 /* A thread that receives packets from some ports, looks them up in the flow
291  * table, and executes the actions it finds. */
292 struct dp_forwarder {
293     struct dp_netdev *dp;
294     pthread_t thread;
295     char *name;
296     uint32_t min_hash, max_hash;
297 };
298
299 /* Interface to netdev-based datapath. */
300 struct dpif_netdev {
301     struct dpif dpif;
302     struct dp_netdev *dp;
303     uint64_t last_port_seq;
304 };
305
306 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
307                               struct dp_netdev_port **portp)
308     OVS_REQ_RDLOCK(dp->port_rwlock);
309 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
310                             struct dp_netdev_port **portp)
311     OVS_REQ_RDLOCK(dp->port_rwlock);
312 static void dp_netdev_free(struct dp_netdev *)
313     OVS_REQUIRES(dp_netdev_mutex);
314 static void dp_netdev_flow_flush(struct dp_netdev *);
315 static int do_add_port(struct dp_netdev *dp, const char *devname,
316                        const char *type, odp_port_t port_no)
317     OVS_REQ_WRLOCK(dp->port_rwlock);
318 static int do_del_port(struct dp_netdev *dp, odp_port_t port_no)
319     OVS_REQ_WRLOCK(dp->port_rwlock);
320 static int dpif_netdev_open(const struct dpif_class *, const char *name,
321                             bool create, struct dpif **);
322 static int dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *,
323                                     int queue_no, const struct flow *,
324                                     const struct nlattr *userdata)
325     OVS_EXCLUDED(dp->queue_mutex);
326 static void dp_netdev_execute_actions(struct dp_netdev *dp,
327                                       const struct flow *, struct ofpbuf *,
328                                       struct pkt_metadata *,
329                                       const struct nlattr *actions,
330                                       size_t actions_len)
331     OVS_REQ_RDLOCK(dp->port_rwlock);
332 static void dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
333                                  struct pkt_metadata *)
334     OVS_REQ_RDLOCK(dp->port_rwlock);
335 static void dp_netdev_set_threads(struct dp_netdev *, int n);
336
337 static struct dpif_netdev *
338 dpif_netdev_cast(const struct dpif *dpif)
339 {
340     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
341     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
342 }
343
344 static struct dp_netdev *
345 get_dp_netdev(const struct dpif *dpif)
346 {
347     return dpif_netdev_cast(dpif)->dp;
348 }
349
350 static int
351 dpif_netdev_enumerate(struct sset *all_dps)
352 {
353     struct shash_node *node;
354
355     ovs_mutex_lock(&dp_netdev_mutex);
356     SHASH_FOR_EACH(node, &dp_netdevs) {
357         sset_add(all_dps, node->name);
358     }
359     ovs_mutex_unlock(&dp_netdev_mutex);
360
361     return 0;
362 }
363
364 static bool
365 dpif_netdev_class_is_dummy(const struct dpif_class *class)
366 {
367     return class != &dpif_netdev_class;
368 }
369
370 static const char *
371 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
372 {
373     return strcmp(type, "internal") ? type
374                   : dpif_netdev_class_is_dummy(class) ? "dummy"
375                   : "tap";
376 }
377
378 static struct dpif *
379 create_dpif_netdev(struct dp_netdev *dp)
380 {
381     uint16_t netflow_id = hash_string(dp->name, 0);
382     struct dpif_netdev *dpif;
383
384     ovs_refcount_ref(&dp->ref_cnt);
385
386     dpif = xmalloc(sizeof *dpif);
387     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
388     dpif->dp = dp;
389     dpif->last_port_seq = seq_read(dp->port_seq);
390
391     return &dpif->dpif;
392 }
393
394 /* Choose an unused, non-zero port number and return it on success.
395  * Return ODPP_NONE on failure. */
396 static odp_port_t
397 choose_port(struct dp_netdev *dp, const char *name)
398     OVS_REQ_RDLOCK(dp->port_rwlock)
399 {
400     uint32_t port_no;
401
402     if (dp->class != &dpif_netdev_class) {
403         const char *p;
404         int start_no = 0;
405
406         /* If the port name begins with "br", start the number search at
407          * 100 to make writing tests easier. */
408         if (!strncmp(name, "br", 2)) {
409             start_no = 100;
410         }
411
412         /* If the port name contains a number, try to assign that port number.
413          * This can make writing unit tests easier because port numbers are
414          * predictable. */
415         for (p = name; *p != '\0'; p++) {
416             if (isdigit((unsigned char) *p)) {
417                 port_no = start_no + strtol(p, NULL, 10);
418                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
419                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
420                     return u32_to_odp(port_no);
421                 }
422                 break;
423             }
424         }
425     }
426
427     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
428         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
429             return u32_to_odp(port_no);
430         }
431     }
432
433     return ODPP_NONE;
434 }
435
436 static int
437 create_dp_netdev(const char *name, const struct dpif_class *class,
438                  struct dp_netdev **dpp)
439     OVS_REQUIRES(dp_netdev_mutex)
440 {
441     struct dp_netdev *dp;
442     int error;
443     int i;
444
445     dp = xzalloc(sizeof *dp);
446     shash_add(&dp_netdevs, name, dp);
447
448     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
449     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
450     ovs_refcount_init(&dp->ref_cnt);
451
452     ovs_mutex_init(&dp->flow_mutex);
453     classifier_init(&dp->cls, NULL);
454     hmap_init(&dp->flow_table);
455
456     ovs_mutex_init(&dp->queue_mutex);
457     ovs_mutex_lock(&dp->queue_mutex);
458     for (i = 0; i < N_QUEUES; i++) {
459         dp->queues[i].head = dp->queues[i].tail = 0;
460     }
461     ovs_mutex_unlock(&dp->queue_mutex);
462     dp->queue_seq = seq_create();
463
464     dp->n_hit = ovsthread_counter_create();
465     dp->n_missed = ovsthread_counter_create();
466     dp->n_lost = ovsthread_counter_create();
467
468     ovs_rwlock_init(&dp->port_rwlock);
469     hmap_init(&dp->ports);
470     dp->port_seq = seq_create();
471     latch_init(&dp->exit_latch);
472
473     ovs_rwlock_wrlock(&dp->port_rwlock);
474     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
475     ovs_rwlock_unlock(&dp->port_rwlock);
476     if (error) {
477         dp_netdev_free(dp);
478         return error;
479     }
480     dp_netdev_set_threads(dp, 2);
481
482     *dpp = dp;
483     return 0;
484 }
485
486 static int
487 dpif_netdev_open(const struct dpif_class *class, const char *name,
488                  bool create, struct dpif **dpifp)
489 {
490     struct dp_netdev *dp;
491     int error;
492
493     ovs_mutex_lock(&dp_netdev_mutex);
494     dp = shash_find_data(&dp_netdevs, name);
495     if (!dp) {
496         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
497     } else {
498         error = (dp->class != class ? EINVAL
499                  : create ? EEXIST
500                  : 0);
501     }
502     if (!error) {
503         *dpifp = create_dpif_netdev(dp);
504     }
505     ovs_mutex_unlock(&dp_netdev_mutex);
506
507     return error;
508 }
509
510 static void
511 dp_netdev_purge_queues(struct dp_netdev *dp)
512 {
513     int i;
514
515     ovs_mutex_lock(&dp->queue_mutex);
516     for (i = 0; i < N_QUEUES; i++) {
517         struct dp_netdev_queue *q = &dp->queues[i];
518
519         while (q->tail != q->head) {
520             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
521             ofpbuf_uninit(&u->upcall.packet);
522             ofpbuf_uninit(&u->buf);
523         }
524     }
525     ovs_mutex_unlock(&dp->queue_mutex);
526 }
527
528 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
529  * through the 'dp_netdevs' shash while freeing 'dp'. */
530 static void
531 dp_netdev_free(struct dp_netdev *dp)
532     OVS_REQUIRES(dp_netdev_mutex)
533 {
534     struct dp_netdev_port *port, *next;
535
536     shash_find_and_delete(&dp_netdevs, dp->name);
537
538     dp_netdev_set_threads(dp, 0);
539     free(dp->forwarders);
540
541     dp_netdev_flow_flush(dp);
542     ovs_rwlock_wrlock(&dp->port_rwlock);
543     HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
544         do_del_port(dp, port->port_no);
545     }
546     ovs_rwlock_unlock(&dp->port_rwlock);
547     ovsthread_counter_destroy(dp->n_hit);
548     ovsthread_counter_destroy(dp->n_missed);
549     ovsthread_counter_destroy(dp->n_lost);
550
551     dp_netdev_purge_queues(dp);
552     seq_destroy(dp->queue_seq);
553     ovs_mutex_destroy(&dp->queue_mutex);
554
555     classifier_destroy(&dp->cls);
556     hmap_destroy(&dp->flow_table);
557     ovs_mutex_destroy(&dp->flow_mutex);
558     seq_destroy(dp->port_seq);
559     hmap_destroy(&dp->ports);
560     latch_destroy(&dp->exit_latch);
561     free(CONST_CAST(char *, dp->name));
562     free(dp);
563 }
564
565 static void
566 dp_netdev_unref(struct dp_netdev *dp)
567 {
568     if (dp) {
569         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
570          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
571         ovs_mutex_lock(&dp_netdev_mutex);
572         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
573             dp_netdev_free(dp);
574         }
575         ovs_mutex_unlock(&dp_netdev_mutex);
576     }
577 }
578
579 static void
580 dpif_netdev_close(struct dpif *dpif)
581 {
582     struct dp_netdev *dp = get_dp_netdev(dpif);
583
584     dp_netdev_unref(dp);
585     free(dpif);
586 }
587
588 static int
589 dpif_netdev_destroy(struct dpif *dpif)
590 {
591     struct dp_netdev *dp = get_dp_netdev(dpif);
592
593     if (!atomic_flag_test_and_set(&dp->destroyed)) {
594         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
595             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
596             OVS_NOT_REACHED();
597         }
598     }
599
600     return 0;
601 }
602
603 static int
604 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
605 {
606     struct dp_netdev *dp = get_dp_netdev(dpif);
607
608     fat_rwlock_rdlock(&dp->cls.rwlock);
609     stats->n_flows = hmap_count(&dp->flow_table);
610     fat_rwlock_unlock(&dp->cls.rwlock);
611
612     stats->n_hit = ovsthread_counter_read(dp->n_hit);
613     stats->n_missed = ovsthread_counter_read(dp->n_missed);
614     stats->n_lost = ovsthread_counter_read(dp->n_lost);
615     stats->n_masks = UINT32_MAX;
616     stats->n_mask_hit = UINT64_MAX;
617
618     return 0;
619 }
620
621 static int
622 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
623             odp_port_t port_no)
624     OVS_REQ_WRLOCK(dp->port_rwlock)
625 {
626     struct netdev_saved_flags *sf;
627     struct dp_netdev_port *port;
628     struct netdev *netdev;
629     struct netdev_rx *rx;
630     enum netdev_flags flags;
631     const char *open_type;
632     int error;
633
634     /* XXX reject devices already in some dp_netdev. */
635
636     /* Open and validate network device. */
637     open_type = dpif_netdev_port_open_type(dp->class, type);
638     error = netdev_open(devname, open_type, &netdev);
639     if (error) {
640         return error;
641     }
642     /* XXX reject non-Ethernet devices */
643
644     netdev_get_flags(netdev, &flags);
645     if (flags & NETDEV_LOOPBACK) {
646         VLOG_ERR("%s: cannot add a loopback device", devname);
647         netdev_close(netdev);
648         return EINVAL;
649     }
650
651     error = netdev_rx_open(netdev, &rx);
652     if (error
653         && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
654         VLOG_ERR("%s: cannot receive packets on this network device (%s)",
655                  devname, ovs_strerror(errno));
656         netdev_close(netdev);
657         return error;
658     }
659
660     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
661     if (error) {
662         netdev_rx_close(rx);
663         netdev_close(netdev);
664         return error;
665     }
666
667     port = xmalloc(sizeof *port);
668     port->port_no = port_no;
669     port->netdev = netdev;
670     port->sf = sf;
671     port->rx = rx;
672     port->type = xstrdup(type);
673
674     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
675     seq_change(dp->port_seq);
676
677     return 0;
678 }
679
680 static int
681 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
682                      odp_port_t *port_nop)
683 {
684     struct dp_netdev *dp = get_dp_netdev(dpif);
685     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
686     const char *dpif_port;
687     odp_port_t port_no;
688     int error;
689
690     ovs_rwlock_wrlock(&dp->port_rwlock);
691     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
692     if (*port_nop != ODPP_NONE) {
693         port_no = *port_nop;
694         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
695     } else {
696         port_no = choose_port(dp, dpif_port);
697         error = port_no == ODPP_NONE ? EFBIG : 0;
698     }
699     if (!error) {
700         *port_nop = port_no;
701         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
702     }
703     ovs_rwlock_unlock(&dp->port_rwlock);
704
705     return error;
706 }
707
708 static int
709 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
710 {
711     struct dp_netdev *dp = get_dp_netdev(dpif);
712     int error;
713
714     ovs_rwlock_wrlock(&dp->port_rwlock);
715     error = port_no == ODPP_LOCAL ? EINVAL : do_del_port(dp, port_no);
716     ovs_rwlock_unlock(&dp->port_rwlock);
717
718     return error;
719 }
720
721 static bool
722 is_valid_port_number(odp_port_t port_no)
723 {
724     return port_no != ODPP_NONE;
725 }
726
727 static struct dp_netdev_port *
728 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
729     OVS_REQ_RDLOCK(dp->port_rwlock)
730 {
731     struct dp_netdev_port *port;
732
733     HMAP_FOR_EACH_IN_BUCKET (port, node, hash_int(odp_to_u32(port_no), 0),
734                              &dp->ports) {
735         if (port->port_no == port_no) {
736             return port;
737         }
738     }
739     return NULL;
740 }
741
742 static int
743 get_port_by_number(struct dp_netdev *dp,
744                    odp_port_t port_no, struct dp_netdev_port **portp)
745     OVS_REQ_RDLOCK(dp->port_rwlock)
746 {
747     if (!is_valid_port_number(port_no)) {
748         *portp = NULL;
749         return EINVAL;
750     } else {
751         *portp = dp_netdev_lookup_port(dp, port_no);
752         return *portp ? 0 : ENOENT;
753     }
754 }
755
756 static int
757 get_port_by_name(struct dp_netdev *dp,
758                  const char *devname, struct dp_netdev_port **portp)
759     OVS_REQ_RDLOCK(dp->port_rwlock)
760 {
761     struct dp_netdev_port *port;
762
763     HMAP_FOR_EACH (port, node, &dp->ports) {
764         if (!strcmp(netdev_get_name(port->netdev), devname)) {
765             *portp = port;
766             return 0;
767         }
768     }
769     return ENOENT;
770 }
771
772 static int
773 do_del_port(struct dp_netdev *dp, odp_port_t port_no)
774     OVS_REQ_WRLOCK(dp->port_rwlock)
775 {
776     struct dp_netdev_port *port;
777     int error;
778
779     error = get_port_by_number(dp, port_no, &port);
780     if (error) {
781         return error;
782     }
783
784     hmap_remove(&dp->ports, &port->node);
785     seq_change(dp->port_seq);
786
787     netdev_close(port->netdev);
788     netdev_restore_flags(port->sf);
789     netdev_rx_close(port->rx);
790     free(port->type);
791     free(port);
792
793     return 0;
794 }
795
796 static void
797 answer_port_query(const struct dp_netdev_port *port,
798                   struct dpif_port *dpif_port)
799 {
800     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
801     dpif_port->type = xstrdup(port->type);
802     dpif_port->port_no = port->port_no;
803 }
804
805 static int
806 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
807                                  struct dpif_port *dpif_port)
808 {
809     struct dp_netdev *dp = get_dp_netdev(dpif);
810     struct dp_netdev_port *port;
811     int error;
812
813     ovs_rwlock_rdlock(&dp->port_rwlock);
814     error = get_port_by_number(dp, port_no, &port);
815     if (!error && dpif_port) {
816         answer_port_query(port, dpif_port);
817     }
818     ovs_rwlock_unlock(&dp->port_rwlock);
819
820     return error;
821 }
822
823 static int
824 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
825                                struct dpif_port *dpif_port)
826 {
827     struct dp_netdev *dp = get_dp_netdev(dpif);
828     struct dp_netdev_port *port;
829     int error;
830
831     ovs_rwlock_rdlock(&dp->port_rwlock);
832     error = get_port_by_name(dp, devname, &port);
833     if (!error && dpif_port) {
834         answer_port_query(port, dpif_port);
835     }
836     ovs_rwlock_unlock(&dp->port_rwlock);
837
838     return error;
839 }
840
841 static void
842 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
843     OVS_REQ_WRLOCK(dp->cls.rwlock)
844     OVS_REQUIRES(dp->flow_mutex)
845 {
846     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
847     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
848
849     classifier_remove(&dp->cls, cr);
850     hmap_remove(&dp->flow_table, node);
851     dp_netdev_flow_unref(flow);
852 }
853
854 static struct dp_netdev_flow *
855 dp_netdev_flow_ref(const struct dp_netdev_flow *flow_)
856 {
857     struct dp_netdev_flow *flow = CONST_CAST(struct dp_netdev_flow *, flow_);
858     if (flow) {
859         ovs_refcount_ref(&flow->ref_cnt);
860     }
861     return flow;
862 }
863
864 static void
865 dp_netdev_flow_unref(struct dp_netdev_flow *flow)
866 {
867     if (flow && ovs_refcount_unref(&flow->ref_cnt) == 1) {
868         cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
869         ovs_mutex_lock(&flow->mutex);
870         dp_netdev_actions_unref(flow->actions);
871         ovs_mutex_unlock(&flow->mutex);
872         ovs_mutex_destroy(&flow->mutex);
873         free(flow);
874     }
875 }
876
877 static void
878 dp_netdev_flow_flush(struct dp_netdev *dp)
879 {
880     struct dp_netdev_flow *netdev_flow, *next;
881
882     ovs_mutex_lock(&dp->flow_mutex);
883     fat_rwlock_wrlock(&dp->cls.rwlock);
884     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
885         dp_netdev_remove_flow(dp, netdev_flow);
886     }
887     fat_rwlock_unlock(&dp->cls.rwlock);
888     ovs_mutex_unlock(&dp->flow_mutex);
889 }
890
891 static int
892 dpif_netdev_flow_flush(struct dpif *dpif)
893 {
894     struct dp_netdev *dp = get_dp_netdev(dpif);
895
896     dp_netdev_flow_flush(dp);
897     return 0;
898 }
899
900 struct dp_netdev_port_state {
901     uint32_t bucket;
902     uint32_t offset;
903     char *name;
904 };
905
906 static int
907 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
908 {
909     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
910     return 0;
911 }
912
913 static int
914 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
915                            struct dpif_port *dpif_port)
916 {
917     struct dp_netdev_port_state *state = state_;
918     struct dp_netdev *dp = get_dp_netdev(dpif);
919     struct hmap_node *node;
920     int retval;
921
922     ovs_rwlock_rdlock(&dp->port_rwlock);
923     node = hmap_at_position(&dp->ports, &state->bucket, &state->offset);
924     if (node) {
925         struct dp_netdev_port *port;
926
927         port = CONTAINER_OF(node, struct dp_netdev_port, node);
928
929         free(state->name);
930         state->name = xstrdup(netdev_get_name(port->netdev));
931         dpif_port->name = state->name;
932         dpif_port->type = port->type;
933         dpif_port->port_no = port->port_no;
934
935         retval = 0;
936     } else {
937         retval = EOF;
938     }
939     ovs_rwlock_unlock(&dp->port_rwlock);
940
941     return retval;
942 }
943
944 static int
945 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
946 {
947     struct dp_netdev_port_state *state = state_;
948     free(state->name);
949     free(state);
950     return 0;
951 }
952
953 static int
954 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
955 {
956     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
957     uint64_t new_port_seq;
958     int error;
959
960     new_port_seq = seq_read(dpif->dp->port_seq);
961     if (dpif->last_port_seq != new_port_seq) {
962         dpif->last_port_seq = new_port_seq;
963         error = ENOBUFS;
964     } else {
965         error = EAGAIN;
966     }
967
968     return error;
969 }
970
971 static void
972 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
973 {
974     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
975
976     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
977 }
978
979 static struct dp_netdev_flow *
980 dp_netdev_flow_cast(const struct cls_rule *cr)
981 {
982     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
983 }
984
985 static struct dp_netdev_flow *
986 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct flow *flow)
987     OVS_EXCLUDED(dp->cls.rwlock)
988 {
989     struct dp_netdev_flow *netdev_flow;
990
991     fat_rwlock_rdlock(&dp->cls.rwlock);
992     netdev_flow = dp_netdev_flow_cast(classifier_lookup(&dp->cls, flow, NULL));
993     dp_netdev_flow_ref(netdev_flow);
994     fat_rwlock_unlock(&dp->cls.rwlock);
995
996     return netdev_flow;
997 }
998
999 static struct dp_netdev_flow *
1000 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1001     OVS_REQ_RDLOCK(dp->cls.rwlock)
1002 {
1003     struct dp_netdev_flow *netdev_flow;
1004
1005     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1006                              &dp->flow_table) {
1007         if (flow_equal(&netdev_flow->flow, flow)) {
1008             return dp_netdev_flow_ref(netdev_flow);
1009         }
1010     }
1011
1012     return NULL;
1013 }
1014
1015 static void
1016 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1017                     struct dpif_flow_stats *stats)
1018     OVS_REQ_RDLOCK(netdev_flow->mutex)
1019 {
1020     stats->n_packets = netdev_flow->packet_count;
1021     stats->n_bytes = netdev_flow->byte_count;
1022     stats->used = netdev_flow->used;
1023     stats->tcp_flags = netdev_flow->tcp_flags;
1024 }
1025
1026 static int
1027 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1028                               const struct nlattr *mask_key,
1029                               uint32_t mask_key_len, const struct flow *flow,
1030                               struct flow *mask)
1031 {
1032     if (mask_key_len) {
1033         enum odp_key_fitness fitness;
1034
1035         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1036         if (fitness) {
1037             /* This should not happen: it indicates that
1038              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1039              * disagree on the acceptable form of a mask.  Log the problem
1040              * as an error, with enough details to enable debugging. */
1041             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1042
1043             if (!VLOG_DROP_ERR(&rl)) {
1044                 struct ds s;
1045
1046                 ds_init(&s);
1047                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1048                                 true);
1049                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1050                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1051                 ds_destroy(&s);
1052             }
1053
1054             return EINVAL;
1055         }
1056         /* Force unwildcard the in_port. */
1057         mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1058     } else {
1059         enum mf_field_id id;
1060         /* No mask key, unwildcard everything except fields whose
1061          * prerequisities are not met. */
1062         memset(mask, 0x0, sizeof *mask);
1063
1064         for (id = 0; id < MFF_N_IDS; ++id) {
1065             /* Skip registers and metadata. */
1066             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1067                 && id != MFF_METADATA) {
1068                 const struct mf_field *mf = mf_from_id(id);
1069                 if (mf_are_prereqs_ok(mf, flow)) {
1070                     mf_mask_field(mf, mask);
1071                 }
1072             }
1073         }
1074     }
1075
1076     return 0;
1077 }
1078
1079 static int
1080 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1081                               struct flow *flow)
1082 {
1083     odp_port_t in_port;
1084
1085     if (odp_flow_key_to_flow(key, key_len, flow)) {
1086         /* This should not happen: it indicates that odp_flow_key_from_flow()
1087          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1088          * flow.  Log the problem as an error, with enough details to enable
1089          * debugging. */
1090         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1091
1092         if (!VLOG_DROP_ERR(&rl)) {
1093             struct ds s;
1094
1095             ds_init(&s);
1096             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1097             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1098             ds_destroy(&s);
1099         }
1100
1101         return EINVAL;
1102     }
1103
1104     in_port = flow->in_port.odp_port;
1105     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1106         return EINVAL;
1107     }
1108
1109     return 0;
1110 }
1111
1112 static int
1113 dpif_netdev_flow_get(const struct dpif *dpif,
1114                      const struct nlattr *nl_key, size_t nl_key_len,
1115                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1116 {
1117     struct dp_netdev *dp = get_dp_netdev(dpif);
1118     struct dp_netdev_flow *netdev_flow;
1119     struct flow key;
1120     int error;
1121
1122     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1123     if (error) {
1124         return error;
1125     }
1126
1127     fat_rwlock_rdlock(&dp->cls.rwlock);
1128     netdev_flow = dp_netdev_find_flow(dp, &key);
1129     fat_rwlock_unlock(&dp->cls.rwlock);
1130
1131     if (netdev_flow) {
1132         struct dp_netdev_actions *actions = NULL;
1133
1134         ovs_mutex_lock(&netdev_flow->mutex);
1135         if (stats) {
1136             get_dpif_flow_stats(netdev_flow, stats);
1137         }
1138         if (actionsp) {
1139             actions = dp_netdev_actions_ref(netdev_flow->actions);
1140         }
1141         ovs_mutex_unlock(&netdev_flow->mutex);
1142
1143         dp_netdev_flow_unref(netdev_flow);
1144
1145         if (actionsp) {
1146             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1147             dp_netdev_actions_unref(actions);
1148         }
1149     } else {
1150         error = ENOENT;
1151     }
1152
1153     return error;
1154 }
1155
1156 static int
1157 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1158                    const struct flow_wildcards *wc,
1159                    const struct nlattr *actions,
1160                    size_t actions_len)
1161     OVS_REQUIRES(dp->flow_mutex)
1162 {
1163     struct dp_netdev_flow *netdev_flow;
1164     struct match match;
1165
1166     netdev_flow = xzalloc(sizeof *netdev_flow);
1167     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1168     ovs_refcount_init(&netdev_flow->ref_cnt);
1169
1170     ovs_mutex_init(&netdev_flow->mutex);
1171     ovs_mutex_lock(&netdev_flow->mutex);
1172
1173     netdev_flow->actions = dp_netdev_actions_create(actions, actions_len);
1174
1175     match_init(&match, flow, wc);
1176     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1177                   &match, NETDEV_RULE_PRIORITY);
1178     fat_rwlock_wrlock(&dp->cls.rwlock);
1179     classifier_insert(&dp->cls,
1180                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1181     hmap_insert(&dp->flow_table,
1182                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1183                 flow_hash(flow, 0));
1184     fat_rwlock_unlock(&dp->cls.rwlock);
1185
1186     ovs_mutex_unlock(&netdev_flow->mutex);
1187
1188     return 0;
1189 }
1190
1191 static void
1192 clear_stats(struct dp_netdev_flow *netdev_flow)
1193     OVS_REQUIRES(netdev_flow->mutex)
1194 {
1195     netdev_flow->used = 0;
1196     netdev_flow->packet_count = 0;
1197     netdev_flow->byte_count = 0;
1198     netdev_flow->tcp_flags = 0;
1199 }
1200
1201 static int
1202 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1203 {
1204     struct dp_netdev *dp = get_dp_netdev(dpif);
1205     struct dp_netdev_flow *netdev_flow;
1206     struct flow flow;
1207     struct flow_wildcards wc;
1208     int error;
1209
1210     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1211     if (error) {
1212         return error;
1213     }
1214     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1215                                           put->mask, put->mask_len,
1216                                           &flow, &wc.masks);
1217     if (error) {
1218         return error;
1219     }
1220
1221     ovs_mutex_lock(&dp->flow_mutex);
1222     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1223     if (!netdev_flow) {
1224         if (put->flags & DPIF_FP_CREATE) {
1225             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1226                 if (put->stats) {
1227                     memset(put->stats, 0, sizeof *put->stats);
1228                 }
1229                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1230                                            put->actions_len);
1231             } else {
1232                 error = EFBIG;
1233             }
1234         } else {
1235             error = ENOENT;
1236         }
1237     } else {
1238         if (put->flags & DPIF_FP_MODIFY
1239             && flow_equal(&flow, &netdev_flow->flow)) {
1240             struct dp_netdev_actions *new_actions;
1241             struct dp_netdev_actions *old_actions;
1242
1243             new_actions = dp_netdev_actions_create(put->actions,
1244                                                    put->actions_len);
1245
1246             ovs_mutex_lock(&netdev_flow->mutex);
1247             old_actions = netdev_flow->actions;
1248             netdev_flow->actions = new_actions;
1249             if (put->stats) {
1250                 get_dpif_flow_stats(netdev_flow, put->stats);
1251             }
1252             if (put->flags & DPIF_FP_ZERO_STATS) {
1253                 clear_stats(netdev_flow);
1254             }
1255             ovs_mutex_unlock(&netdev_flow->mutex);
1256
1257             dp_netdev_actions_unref(old_actions);
1258         } else if (put->flags & DPIF_FP_CREATE) {
1259             error = EEXIST;
1260         } else {
1261             /* Overlapping flow. */
1262             error = EINVAL;
1263         }
1264         dp_netdev_flow_unref(netdev_flow);
1265     }
1266     ovs_mutex_unlock(&dp->flow_mutex);
1267
1268     return error;
1269 }
1270
1271 static int
1272 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1273 {
1274     struct dp_netdev *dp = get_dp_netdev(dpif);
1275     struct dp_netdev_flow *netdev_flow;
1276     struct flow key;
1277     int error;
1278
1279     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1280     if (error) {
1281         return error;
1282     }
1283
1284     ovs_mutex_lock(&dp->flow_mutex);
1285     fat_rwlock_wrlock(&dp->cls.rwlock);
1286     netdev_flow = dp_netdev_find_flow(dp, &key);
1287     if (netdev_flow) {
1288         if (del->stats) {
1289             ovs_mutex_lock(&netdev_flow->mutex);
1290             get_dpif_flow_stats(netdev_flow, del->stats);
1291             ovs_mutex_unlock(&netdev_flow->mutex);
1292         }
1293         dp_netdev_remove_flow(dp, netdev_flow);
1294         dp_netdev_flow_unref(netdev_flow);
1295     } else {
1296         error = ENOENT;
1297     }
1298     fat_rwlock_unlock(&dp->cls.rwlock);
1299     ovs_mutex_unlock(&dp->flow_mutex);
1300
1301     return error;
1302 }
1303
1304 struct dp_netdev_flow_state {
1305     struct dp_netdev_actions *actions;
1306     struct odputil_keybuf keybuf;
1307     struct odputil_keybuf maskbuf;
1308     struct dpif_flow_stats stats;
1309 };
1310
1311 struct dp_netdev_flow_iter {
1312     uint32_t bucket;
1313     uint32_t offset;
1314     int status;
1315     struct ovs_mutex mutex;
1316 };
1317
1318 static void
1319 dpif_netdev_flow_dump_state_init(void **statep)
1320 {
1321     struct dp_netdev_flow_state *state;
1322
1323     *statep = state = xmalloc(sizeof *state);
1324     state->actions = NULL;
1325 }
1326
1327 static void
1328 dpif_netdev_flow_dump_state_uninit(void *state_)
1329 {
1330     struct dp_netdev_flow_state *state = state_;
1331
1332     dp_netdev_actions_unref(state->actions);
1333     free(state);
1334 }
1335
1336 static int
1337 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **iterp)
1338 {
1339     struct dp_netdev_flow_iter *iter;
1340
1341     *iterp = iter = xmalloc(sizeof *iter);
1342     iter->bucket = 0;
1343     iter->offset = 0;
1344     iter->status = 0;
1345     ovs_mutex_init(&iter->mutex);
1346     return 0;
1347 }
1348
1349 static int
1350 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *iter_, void *state_,
1351                            const struct nlattr **key, size_t *key_len,
1352                            const struct nlattr **mask, size_t *mask_len,
1353                            const struct nlattr **actions, size_t *actions_len,
1354                            const struct dpif_flow_stats **stats)
1355 {
1356     struct dp_netdev_flow_iter *iter = iter_;
1357     struct dp_netdev_flow_state *state = state_;
1358     struct dp_netdev *dp = get_dp_netdev(dpif);
1359     struct dp_netdev_flow *netdev_flow;
1360     int error;
1361
1362     ovs_mutex_lock(&iter->mutex);
1363     error = iter->status;
1364     if (!error) {
1365         struct hmap_node *node;
1366
1367         fat_rwlock_rdlock(&dp->cls.rwlock);
1368         node = hmap_at_position(&dp->flow_table, &iter->bucket, &iter->offset);
1369         if (node) {
1370             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1371             dp_netdev_flow_ref(netdev_flow);
1372         }
1373         fat_rwlock_unlock(&dp->cls.rwlock);
1374         if (!node) {
1375             iter->status = error = EOF;
1376         }
1377     }
1378     ovs_mutex_unlock(&iter->mutex);
1379     if (error) {
1380         return error;
1381     }
1382
1383     if (key) {
1384         struct ofpbuf buf;
1385
1386         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1387         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1388                                netdev_flow->flow.in_port.odp_port);
1389
1390         *key = buf.data;
1391         *key_len = buf.size;
1392     }
1393
1394     if (key && mask) {
1395         struct ofpbuf buf;
1396         struct flow_wildcards wc;
1397
1398         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1399         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1400         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1401                                odp_to_u32(wc.masks.in_port.odp_port),
1402                                SIZE_MAX);
1403
1404         *mask = buf.data;
1405         *mask_len = buf.size;
1406     }
1407
1408     if (actions || stats) {
1409         dp_netdev_actions_unref(state->actions);
1410         state->actions = NULL;
1411
1412         ovs_mutex_lock(&netdev_flow->mutex);
1413         if (actions) {
1414             state->actions = dp_netdev_actions_ref(netdev_flow->actions);
1415             *actions = state->actions->actions;
1416             *actions_len = state->actions->size;
1417         }
1418         if (stats) {
1419             get_dpif_flow_stats(netdev_flow, &state->stats);
1420             *stats = &state->stats;
1421         }
1422         ovs_mutex_unlock(&netdev_flow->mutex);
1423     }
1424
1425     dp_netdev_flow_unref(netdev_flow);
1426
1427     return 0;
1428 }
1429
1430 static int
1431 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *iter_)
1432 {
1433     struct dp_netdev_flow_iter *iter = iter_;
1434
1435     ovs_mutex_destroy(&iter->mutex);
1436     free(iter);
1437     return 0;
1438 }
1439
1440 static int
1441 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1442 {
1443     struct dp_netdev *dp = get_dp_netdev(dpif);
1444     struct pkt_metadata *md = &execute->md;
1445     struct flow key;
1446
1447     if (execute->packet->size < ETH_HEADER_LEN ||
1448         execute->packet->size > UINT16_MAX) {
1449         return EINVAL;
1450     }
1451
1452     /* Extract flow key. */
1453     flow_extract(execute->packet, md, &key);
1454
1455     ovs_rwlock_rdlock(&dp->port_rwlock);
1456     dp_netdev_execute_actions(dp, &key, execute->packet, md, execute->actions,
1457                               execute->actions_len);
1458     ovs_rwlock_unlock(&dp->port_rwlock);
1459
1460     return 0;
1461 }
1462
1463 static int
1464 dpif_netdev_recv_set(struct dpif *dpif OVS_UNUSED, bool enable OVS_UNUSED)
1465 {
1466     return 0;
1467 }
1468
1469 static int
1470 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1471                               uint32_t queue_id, uint32_t *priority)
1472 {
1473     *priority = queue_id;
1474     return 0;
1475 }
1476
1477 static struct dp_netdev_queue *
1478 find_nonempty_queue(struct dp_netdev *dp)
1479     OVS_REQUIRES(dp->queue_mutex)
1480 {
1481     int i;
1482
1483     for (i = 0; i < N_QUEUES; i++) {
1484         struct dp_netdev_queue *q = &dp->queues[i];
1485         if (q->head != q->tail) {
1486             return q;
1487         }
1488     }
1489     return NULL;
1490 }
1491
1492 static int
1493 dpif_netdev_recv(struct dpif *dpif, struct dpif_upcall *upcall,
1494                  struct ofpbuf *buf)
1495 {
1496     struct dp_netdev *dp = get_dp_netdev(dpif);
1497     struct dp_netdev_queue *q;
1498     int error;
1499
1500     ovs_mutex_lock(&dp->queue_mutex);
1501     q = find_nonempty_queue(dp);
1502     if (q) {
1503         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1504
1505         *upcall = u->upcall;
1506
1507         ofpbuf_uninit(buf);
1508         *buf = u->buf;
1509
1510         error = 0;
1511     } else {
1512         error = EAGAIN;
1513     }
1514     ovs_mutex_unlock(&dp->queue_mutex);
1515
1516     return error;
1517 }
1518
1519 static void
1520 dpif_netdev_recv_wait(struct dpif *dpif)
1521 {
1522     struct dp_netdev *dp = get_dp_netdev(dpif);
1523     uint64_t seq;
1524
1525     ovs_mutex_lock(&dp->queue_mutex);
1526     seq = seq_read(dp->queue_seq);
1527     if (find_nonempty_queue(dp)) {
1528         poll_immediate_wake();
1529     } else {
1530         seq_wait(dp->queue_seq, seq);
1531     }
1532     ovs_mutex_unlock(&dp->queue_mutex);
1533 }
1534
1535 static void
1536 dpif_netdev_recv_purge(struct dpif *dpif)
1537 {
1538     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1539
1540     dp_netdev_purge_queues(dpif_netdev->dp);
1541 }
1542 \f
1543 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1544  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1545  * 'ofpacts'. */
1546 struct dp_netdev_actions *
1547 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1548 {
1549     struct dp_netdev_actions *netdev_actions;
1550
1551     netdev_actions = xmalloc(sizeof *netdev_actions);
1552     ovs_refcount_init(&netdev_actions->ref_cnt);
1553     netdev_actions->actions = xmemdup(actions, size);
1554     netdev_actions->size = size;
1555
1556     return netdev_actions;
1557 }
1558
1559 /* Increments 'actions''s refcount. */
1560 struct dp_netdev_actions *
1561 dp_netdev_actions_ref(const struct dp_netdev_actions *actions_)
1562 {
1563     struct dp_netdev_actions *actions;
1564
1565     actions = CONST_CAST(struct dp_netdev_actions *, actions_);
1566     if (actions) {
1567         ovs_refcount_ref(&actions->ref_cnt);
1568     }
1569     return actions;
1570 }
1571
1572 /* Decrements 'actions''s refcount and frees 'actions' if the refcount reaches
1573  * 0. */
1574 void
1575 dp_netdev_actions_unref(struct dp_netdev_actions *actions)
1576 {
1577     if (actions && ovs_refcount_unref(&actions->ref_cnt) == 1) {
1578         free(actions->actions);
1579         free(actions);
1580     }
1581 }
1582 \f
1583 static void *
1584 dp_forwarder_main(void *f_)
1585 {
1586     struct dp_forwarder *f = f_;
1587     struct dp_netdev *dp = f->dp;
1588     struct ofpbuf packet;
1589
1590     f->name = xasprintf("forwarder_%u", ovsthread_id_self());
1591     set_subprogram_name("%s", f->name);
1592
1593     ofpbuf_init(&packet, 0);
1594     while (!latch_is_set(&dp->exit_latch)) {
1595         bool received_anything;
1596         int i;
1597
1598         ovs_rwlock_rdlock(&dp->port_rwlock);
1599         for (i = 0; i < 50; i++) {
1600             struct dp_netdev_port *port;
1601
1602             received_anything = false;
1603             HMAP_FOR_EACH (port, node, &f->dp->ports) {
1604                 if (port->rx
1605                     && port->node.hash >= f->min_hash
1606                     && port->node.hash <= f->max_hash) {
1607                     int buf_size;
1608                     int error;
1609                     int mtu;
1610
1611                     if (netdev_get_mtu(port->netdev, &mtu)) {
1612                         mtu = ETH_PAYLOAD_MAX;
1613                     }
1614                     buf_size = DP_NETDEV_HEADROOM + VLAN_ETH_HEADER_LEN + mtu;
1615
1616                     ofpbuf_clear(&packet);
1617                     ofpbuf_reserve_with_tailroom(&packet, DP_NETDEV_HEADROOM,
1618                                                  buf_size);
1619
1620                     error = netdev_rx_recv(port->rx, &packet);
1621                     if (!error) {
1622                         struct pkt_metadata md
1623                             = PKT_METADATA_INITIALIZER(port->port_no);
1624
1625                         dp_netdev_port_input(dp, &packet, &md);
1626                         received_anything = true;
1627                     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1628                         static struct vlog_rate_limit rl
1629                             = VLOG_RATE_LIMIT_INIT(1, 5);
1630
1631                         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1632                                     netdev_get_name(port->netdev),
1633                                     ovs_strerror(error));
1634                     }
1635                 }
1636             }
1637
1638             if (!received_anything) {
1639                 break;
1640             }
1641         }
1642
1643         if (received_anything) {
1644             poll_immediate_wake();
1645         } else {
1646             struct dp_netdev_port *port;
1647
1648             HMAP_FOR_EACH (port, node, &f->dp->ports)
1649                 if (port->rx
1650                     && port->node.hash >= f->min_hash
1651                     && port->node.hash <= f->max_hash) {
1652                     netdev_rx_wait(port->rx);
1653                 }
1654             seq_wait(dp->port_seq, seq_read(dp->port_seq));
1655             latch_wait(&dp->exit_latch);
1656         }
1657         ovs_rwlock_unlock(&dp->port_rwlock);
1658
1659         poll_block();
1660     }
1661     ofpbuf_uninit(&packet);
1662
1663     free(f->name);
1664
1665     return NULL;
1666 }
1667
1668 static void
1669 dp_netdev_set_threads(struct dp_netdev *dp, int n)
1670 {
1671     int i;
1672
1673     if (n == dp->n_forwarders) {
1674         return;
1675     }
1676
1677     /* Stop existing threads. */
1678     latch_set(&dp->exit_latch);
1679     for (i = 0; i < dp->n_forwarders; i++) {
1680         struct dp_forwarder *f = &dp->forwarders[i];
1681
1682         xpthread_join(f->thread, NULL);
1683     }
1684     latch_poll(&dp->exit_latch);
1685     free(dp->forwarders);
1686
1687     /* Start new threads. */
1688     dp->forwarders = xmalloc(n * sizeof *dp->forwarders);
1689     dp->n_forwarders = n;
1690     for (i = 0; i < n; i++) {
1691         struct dp_forwarder *f = &dp->forwarders[i];
1692
1693         f->dp = dp;
1694         f->min_hash = UINT32_MAX / n * i;
1695         f->max_hash = UINT32_MAX / n * (i + 1) - 1;
1696         if (i == n - 1) {
1697             f->max_hash = UINT32_MAX;
1698         }
1699         xpthread_create(&f->thread, NULL, dp_forwarder_main, f);
1700     }
1701 }
1702 \f
1703 static void
1704 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1705                     const struct ofpbuf *packet)
1706     OVS_REQUIRES(netdev_flow->mutex)
1707 {
1708     netdev_flow->used = time_msec();
1709     netdev_flow->packet_count++;
1710     netdev_flow->byte_count += packet->size;
1711     netdev_flow->tcp_flags |= packet_get_tcp_flags(packet, &netdev_flow->flow);
1712 }
1713
1714 static void
1715 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
1716                      struct pkt_metadata *md)
1717     OVS_REQ_RDLOCK(dp->port_rwlock)
1718 {
1719     struct dp_netdev_flow *netdev_flow;
1720     struct flow key;
1721
1722     if (packet->size < ETH_HEADER_LEN) {
1723         return;
1724     }
1725     flow_extract(packet, md, &key);
1726     netdev_flow = dp_netdev_lookup_flow(dp, &key);
1727     if (netdev_flow) {
1728         struct dp_netdev_actions *actions;
1729
1730         ovs_mutex_lock(&netdev_flow->mutex);
1731         dp_netdev_flow_used(netdev_flow, packet);
1732         actions = dp_netdev_actions_ref(netdev_flow->actions);
1733         ovs_mutex_unlock(&netdev_flow->mutex);
1734
1735         dp_netdev_execute_actions(dp, &key, packet, md,
1736                                   actions->actions, actions->size);
1737         dp_netdev_actions_unref(actions);
1738         dp_netdev_flow_unref(netdev_flow);
1739         ovsthread_counter_inc(dp->n_hit, 1);
1740     } else {
1741         ovsthread_counter_inc(dp->n_missed, 1);
1742         dp_netdev_output_userspace(dp, packet, DPIF_UC_MISS, &key, NULL);
1743     }
1744 }
1745
1746 static int
1747 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
1748                            int queue_no, const struct flow *flow,
1749                            const struct nlattr *userdata)
1750     OVS_EXCLUDED(dp->queue_mutex)
1751 {
1752     struct dp_netdev_queue *q = &dp->queues[queue_no];
1753     int error;
1754
1755     ovs_mutex_lock(&dp->queue_mutex);
1756     if (q->head - q->tail < MAX_QUEUE_LEN) {
1757         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
1758         struct dpif_upcall *upcall = &u->upcall;
1759         struct ofpbuf *buf = &u->buf;
1760         size_t buf_size;
1761
1762         upcall->type = queue_no;
1763
1764         /* Allocate buffer big enough for everything. */
1765         buf_size = ODPUTIL_FLOW_KEY_BYTES;
1766         if (userdata) {
1767             buf_size += NLA_ALIGN(userdata->nla_len);
1768         }
1769         ofpbuf_init(buf, buf_size);
1770
1771         /* Put ODP flow. */
1772         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
1773         upcall->key = buf->data;
1774         upcall->key_len = buf->size;
1775
1776         /* Put userdata. */
1777         if (userdata) {
1778             upcall->userdata = ofpbuf_put(buf, userdata,
1779                                           NLA_ALIGN(userdata->nla_len));
1780         }
1781
1782         /* Steal packet data. */
1783         ovs_assert(packet->source == OFPBUF_MALLOC);
1784         upcall->packet = *packet;
1785         ofpbuf_use(packet, NULL, 0);
1786
1787         seq_change(dp->queue_seq);
1788
1789         error = 0;
1790     } else {
1791         ovsthread_counter_inc(dp->n_lost, 1);
1792         error = ENOBUFS;
1793     }
1794     ovs_mutex_unlock(&dp->queue_mutex);
1795
1796     return error;
1797 }
1798
1799 struct dp_netdev_execute_aux {
1800     struct dp_netdev *dp;
1801     const struct flow *key;
1802 };
1803
1804 static void
1805 dp_execute_cb(void *aux_, struct ofpbuf *packet,
1806               const struct pkt_metadata *md OVS_UNUSED,
1807               const struct nlattr *a, bool may_steal)
1808     OVS_NO_THREAD_SAFETY_ANALYSIS
1809 {
1810     struct dp_netdev_execute_aux *aux = aux_;
1811     int type = nl_attr_type(a);
1812     struct dp_netdev_port *p;
1813
1814     switch ((enum ovs_action_attr)type) {
1815     case OVS_ACTION_ATTR_OUTPUT:
1816         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
1817         if (p) {
1818             netdev_send(p->netdev, packet);
1819         }
1820         break;
1821
1822     case OVS_ACTION_ATTR_USERSPACE: {
1823         const struct nlattr *userdata;
1824
1825         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
1826
1827         /* Make a copy if we are not allowed to steal the packet's data. */
1828         if (!may_steal) {
1829             packet = ofpbuf_clone_with_headroom(packet, DP_NETDEV_HEADROOM);
1830         }
1831         dp_netdev_output_userspace(aux->dp, packet, DPIF_UC_ACTION, aux->key,
1832                                    userdata);
1833         if (!may_steal) {
1834             ofpbuf_uninit(packet);
1835         }
1836         break;
1837     }
1838     case OVS_ACTION_ATTR_PUSH_VLAN:
1839     case OVS_ACTION_ATTR_POP_VLAN:
1840     case OVS_ACTION_ATTR_PUSH_MPLS:
1841     case OVS_ACTION_ATTR_POP_MPLS:
1842     case OVS_ACTION_ATTR_SET:
1843     case OVS_ACTION_ATTR_SAMPLE:
1844     case OVS_ACTION_ATTR_UNSPEC:
1845     case __OVS_ACTION_ATTR_MAX:
1846         OVS_NOT_REACHED();
1847     }
1848 }
1849
1850 static void
1851 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
1852                           struct ofpbuf *packet, struct pkt_metadata *md,
1853                           const struct nlattr *actions, size_t actions_len)
1854     OVS_REQ_RDLOCK(dp->port_rwlock)
1855 {
1856     struct dp_netdev_execute_aux aux = {dp, key};
1857
1858     odp_execute_actions(&aux, packet, md, actions, actions_len, dp_execute_cb);
1859 }
1860
1861 const struct dpif_class dpif_netdev_class = {
1862     "netdev",
1863     dpif_netdev_enumerate,
1864     dpif_netdev_port_open_type,
1865     dpif_netdev_open,
1866     dpif_netdev_close,
1867     dpif_netdev_destroy,
1868     NULL,                       /* run */
1869     NULL,                       /* wait */
1870     dpif_netdev_get_stats,
1871     dpif_netdev_port_add,
1872     dpif_netdev_port_del,
1873     dpif_netdev_port_query_by_number,
1874     dpif_netdev_port_query_by_name,
1875     NULL,                       /* port_get_pid */
1876     dpif_netdev_port_dump_start,
1877     dpif_netdev_port_dump_next,
1878     dpif_netdev_port_dump_done,
1879     dpif_netdev_port_poll,
1880     dpif_netdev_port_poll_wait,
1881     dpif_netdev_flow_get,
1882     dpif_netdev_flow_put,
1883     dpif_netdev_flow_del,
1884     dpif_netdev_flow_flush,
1885     dpif_netdev_flow_dump_state_init,
1886     dpif_netdev_flow_dump_start,
1887     dpif_netdev_flow_dump_next,
1888     NULL,
1889     dpif_netdev_flow_dump_done,
1890     dpif_netdev_flow_dump_state_uninit,
1891     dpif_netdev_execute,
1892     NULL,                       /* operate */
1893     dpif_netdev_recv_set,
1894     dpif_netdev_queue_to_priority,
1895     dpif_netdev_recv,
1896     dpif_netdev_recv_wait,
1897     dpif_netdev_recv_purge,
1898 };
1899
1900 static void
1901 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
1902                               const char *argv[], void *aux OVS_UNUSED)
1903 {
1904     struct dp_netdev_port *port;
1905     struct dp_netdev *dp;
1906     odp_port_t port_no;
1907
1908     ovs_mutex_lock(&dp_netdev_mutex);
1909     dp = shash_find_data(&dp_netdevs, argv[1]);
1910     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
1911         ovs_mutex_unlock(&dp_netdev_mutex);
1912         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
1913         return;
1914     }
1915     ovs_refcount_ref(&dp->ref_cnt);
1916     ovs_mutex_unlock(&dp_netdev_mutex);
1917
1918     ovs_rwlock_wrlock(&dp->port_rwlock);
1919     if (get_port_by_name(dp, argv[2], &port)) {
1920         unixctl_command_reply_error(conn, "unknown port");
1921         goto exit;
1922     }
1923
1924     port_no = u32_to_odp(atoi(argv[3]));
1925     if (!port_no || port_no == ODPP_NONE) {
1926         unixctl_command_reply_error(conn, "bad port number");
1927         goto exit;
1928     }
1929     if (dp_netdev_lookup_port(dp, port_no)) {
1930         unixctl_command_reply_error(conn, "port number already in use");
1931         goto exit;
1932     }
1933     hmap_remove(&dp->ports, &port->node);
1934     port->port_no = port_no;
1935     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
1936     seq_change(dp->port_seq);
1937     unixctl_command_reply(conn, NULL);
1938
1939 exit:
1940     ovs_rwlock_unlock(&dp->port_rwlock);
1941     dp_netdev_unref(dp);
1942 }
1943
1944 static void
1945 dpif_dummy_register__(const char *type)
1946 {
1947     struct dpif_class *class;
1948
1949     class = xmalloc(sizeof *class);
1950     *class = dpif_netdev_class;
1951     class->type = xstrdup(type);
1952     dp_register_provider(class);
1953 }
1954
1955 void
1956 dpif_dummy_register(bool override)
1957 {
1958     if (override) {
1959         struct sset types;
1960         const char *type;
1961
1962         sset_init(&types);
1963         dp_enumerate_types(&types);
1964         SSET_FOR_EACH (type, &types) {
1965             if (!dp_unregister_provider(type)) {
1966                 dpif_dummy_register__(type);
1967             }
1968         }
1969         sset_destroy(&types);
1970     }
1971
1972     dpif_dummy_register__("dummy");
1973
1974     unixctl_command_register("dpif-dummy/change-port-number",
1975                              "DP PORT NEW-NUMBER",
1976                              3, 3, dpif_dummy_change_port_number, NULL);
1977 }