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