dpif-netdev: Unwildcard entire odp_port in dpif_netdev_mask_from_nlattrs().
[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 const char *
399 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
400 {
401     return strcmp(type, "internal") ? type
402                   : dpif_netdev_class_is_dummy(class) ? "dummy"
403                   : "tap";
404 }
405
406 static struct dpif *
407 create_dpif_netdev(struct dp_netdev *dp)
408 {
409     uint16_t netflow_id = hash_string(dp->name, 0);
410     struct dpif_netdev *dpif;
411
412     ovs_refcount_ref(&dp->ref_cnt);
413
414     dpif = xmalloc(sizeof *dpif);
415     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
416     dpif->dp = dp;
417     dpif->last_port_seq = seq_read(dp->port_seq);
418
419     return &dpif->dpif;
420 }
421
422 /* Choose an unused, non-zero port number and return it on success.
423  * Return ODPP_NONE on failure. */
424 static odp_port_t
425 choose_port(struct dp_netdev *dp, const char *name)
426     OVS_REQ_RDLOCK(dp->port_rwlock)
427 {
428     uint32_t port_no;
429
430     if (dp->class != &dpif_netdev_class) {
431         const char *p;
432         int start_no = 0;
433
434         /* If the port name begins with "br", start the number search at
435          * 100 to make writing tests easier. */
436         if (!strncmp(name, "br", 2)) {
437             start_no = 100;
438         }
439
440         /* If the port name contains a number, try to assign that port number.
441          * This can make writing unit tests easier because port numbers are
442          * predictable. */
443         for (p = name; *p != '\0'; p++) {
444             if (isdigit((unsigned char) *p)) {
445                 port_no = start_no + strtol(p, NULL, 10);
446                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
447                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
448                     return u32_to_odp(port_no);
449                 }
450                 break;
451             }
452         }
453     }
454
455     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
456         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
457             return u32_to_odp(port_no);
458         }
459     }
460
461     return ODPP_NONE;
462 }
463
464 static int
465 create_dp_netdev(const char *name, const struct dpif_class *class,
466                  struct dp_netdev **dpp)
467     OVS_REQUIRES(dp_netdev_mutex)
468 {
469     struct dp_netdev *dp;
470     int error;
471
472     dp = xzalloc(sizeof *dp);
473     shash_add(&dp_netdevs, name, dp);
474
475     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
476     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
477     ovs_refcount_init(&dp->ref_cnt);
478     atomic_flag_clear(&dp->destroyed);
479
480     ovs_mutex_init(&dp->flow_mutex);
481     classifier_init(&dp->cls, NULL);
482     hmap_init(&dp->flow_table);
483
484     fat_rwlock_init(&dp->queue_rwlock);
485
486     ovsthread_stats_init(&dp->stats);
487
488     ovs_rwlock_init(&dp->port_rwlock);
489     hmap_init(&dp->ports);
490     dp->port_seq = seq_create();
491     latch_init(&dp->exit_latch);
492
493     ovs_rwlock_wrlock(&dp->port_rwlock);
494     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
495     ovs_rwlock_unlock(&dp->port_rwlock);
496     if (error) {
497         dp_netdev_free(dp);
498         return error;
499     }
500
501     *dpp = dp;
502     return 0;
503 }
504
505 static int
506 dpif_netdev_open(const struct dpif_class *class, const char *name,
507                  bool create, struct dpif **dpifp)
508 {
509     struct dp_netdev *dp;
510     int error;
511
512     ovs_mutex_lock(&dp_netdev_mutex);
513     dp = shash_find_data(&dp_netdevs, name);
514     if (!dp) {
515         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
516     } else {
517         error = (dp->class != class ? EINVAL
518                  : create ? EEXIST
519                  : 0);
520     }
521     if (!error) {
522         *dpifp = create_dpif_netdev(dp);
523     }
524     ovs_mutex_unlock(&dp_netdev_mutex);
525
526     return error;
527 }
528
529 static void
530 dp_netdev_purge_queues(struct dp_netdev *dp)
531     OVS_REQ_WRLOCK(dp->queue_rwlock)
532 {
533     int i;
534
535     for (i = 0; i < dp->n_handlers; i++) {
536         struct dp_netdev_queue *q = &dp->handler_queues[i];
537
538         ovs_mutex_lock(&q->mutex);
539         while (q->tail != q->head) {
540             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
541             ofpbuf_uninit(&u->upcall.packet);
542             ofpbuf_uninit(&u->buf);
543         }
544         ovs_mutex_unlock(&q->mutex);
545     }
546 }
547
548 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
549  * through the 'dp_netdevs' shash while freeing 'dp'. */
550 static void
551 dp_netdev_free(struct dp_netdev *dp)
552     OVS_REQUIRES(dp_netdev_mutex)
553 {
554     struct dp_netdev_port *port, *next;
555     struct dp_netdev_stats *bucket;
556     int i;
557
558     shash_find_and_delete(&dp_netdevs, dp->name);
559
560     dp_netdev_set_pmd_threads(dp, 0);
561     free(dp->pmd_threads);
562
563     dp_netdev_flow_flush(dp);
564     ovs_rwlock_wrlock(&dp->port_rwlock);
565     HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
566         do_del_port(dp, port->port_no);
567     }
568     ovs_rwlock_unlock(&dp->port_rwlock);
569
570     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
571         ovs_mutex_destroy(&bucket->mutex);
572         free_cacheline(bucket);
573     }
574     ovsthread_stats_destroy(&dp->stats);
575
576     fat_rwlock_wrlock(&dp->queue_rwlock);
577     dp_netdev_destroy_all_queues(dp);
578     fat_rwlock_unlock(&dp->queue_rwlock);
579
580     fat_rwlock_destroy(&dp->queue_rwlock);
581
582     classifier_destroy(&dp->cls);
583     hmap_destroy(&dp->flow_table);
584     ovs_mutex_destroy(&dp->flow_mutex);
585     seq_destroy(dp->port_seq);
586     hmap_destroy(&dp->ports);
587     latch_destroy(&dp->exit_latch);
588     free(CONST_CAST(char *, dp->name));
589     free(dp);
590 }
591
592 static void
593 dp_netdev_unref(struct dp_netdev *dp)
594 {
595     if (dp) {
596         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
597          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
598         ovs_mutex_lock(&dp_netdev_mutex);
599         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
600             dp_netdev_free(dp);
601         }
602         ovs_mutex_unlock(&dp_netdev_mutex);
603     }
604 }
605
606 static void
607 dpif_netdev_close(struct dpif *dpif)
608 {
609     struct dp_netdev *dp = get_dp_netdev(dpif);
610
611     dp_netdev_unref(dp);
612     free(dpif);
613 }
614
615 static int
616 dpif_netdev_destroy(struct dpif *dpif)
617 {
618     struct dp_netdev *dp = get_dp_netdev(dpif);
619
620     if (!atomic_flag_test_and_set(&dp->destroyed)) {
621         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
622             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
623             OVS_NOT_REACHED();
624         }
625     }
626
627     return 0;
628 }
629
630 static int
631 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
632 {
633     struct dp_netdev *dp = get_dp_netdev(dpif);
634     struct dp_netdev_stats *bucket;
635     size_t i;
636
637     fat_rwlock_rdlock(&dp->cls.rwlock);
638     stats->n_flows = hmap_count(&dp->flow_table);
639     fat_rwlock_unlock(&dp->cls.rwlock);
640
641     stats->n_hit = stats->n_missed = stats->n_lost = 0;
642     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
643         ovs_mutex_lock(&bucket->mutex);
644         stats->n_hit += bucket->n[DP_STAT_HIT];
645         stats->n_missed += bucket->n[DP_STAT_MISS];
646         stats->n_lost += bucket->n[DP_STAT_LOST];
647         ovs_mutex_unlock(&bucket->mutex);
648     }
649     stats->n_masks = UINT32_MAX;
650     stats->n_mask_hit = UINT64_MAX;
651
652     return 0;
653 }
654
655 static void
656 dp_netdev_reload_pmd_threads(struct dp_netdev *dp)
657 {
658     int i;
659
660     for (i = 0; i < dp->n_pmd_threads; i++) {
661         struct pmd_thread *f = &dp->pmd_threads[i];
662         int id;
663
664         atomic_add(&f->change_seq, 1, &id);
665    }
666 }
667
668 static int
669 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
670             odp_port_t port_no)
671     OVS_REQ_WRLOCK(dp->port_rwlock)
672 {
673     struct netdev_saved_flags *sf;
674     struct dp_netdev_port *port;
675     struct netdev *netdev;
676     enum netdev_flags flags;
677     const char *open_type;
678     int error;
679     int i;
680
681     /* XXX reject devices already in some dp_netdev. */
682
683     /* Open and validate network device. */
684     open_type = dpif_netdev_port_open_type(dp->class, type);
685     error = netdev_open(devname, open_type, &netdev);
686     if (error) {
687         return error;
688     }
689     /* XXX reject non-Ethernet devices */
690
691     netdev_get_flags(netdev, &flags);
692     if (flags & NETDEV_LOOPBACK) {
693         VLOG_ERR("%s: cannot add a loopback device", devname);
694         netdev_close(netdev);
695         return EINVAL;
696     }
697
698     port = xzalloc(sizeof *port);
699     port->port_no = port_no;
700     port->netdev = netdev;
701     port->rxq = xmalloc(sizeof *port->rxq * netdev_n_rxq(netdev));
702     port->type = xstrdup(type);
703     for (i = 0; i < netdev_n_rxq(netdev); i++) {
704         error = netdev_rxq_open(netdev, &port->rxq[i], i);
705         if (error
706             && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
707             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
708                      devname, ovs_strerror(errno));
709             netdev_close(netdev);
710             return error;
711         }
712     }
713
714     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
715     if (error) {
716         for (i = 0; i < netdev_n_rxq(netdev); i++) {
717             netdev_rxq_close(port->rxq[i]);
718         }
719         netdev_close(netdev);
720         free(port->rxq);
721         free(port);
722         return error;
723     }
724     port->sf = sf;
725
726     if (netdev_is_pmd(netdev)) {
727         dp->pmd_count++;
728         dp_netdev_set_pmd_threads(dp, NR_THREADS);
729         dp_netdev_reload_pmd_threads(dp);
730     }
731     ovs_refcount_init(&port->ref_cnt);
732
733     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
734     seq_change(dp->port_seq);
735
736     return 0;
737 }
738
739 static int
740 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
741                      odp_port_t *port_nop)
742 {
743     struct dp_netdev *dp = get_dp_netdev(dpif);
744     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
745     const char *dpif_port;
746     odp_port_t port_no;
747     int error;
748
749     ovs_rwlock_wrlock(&dp->port_rwlock);
750     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
751     if (*port_nop != ODPP_NONE) {
752         port_no = *port_nop;
753         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
754     } else {
755         port_no = choose_port(dp, dpif_port);
756         error = port_no == ODPP_NONE ? EFBIG : 0;
757     }
758     if (!error) {
759         *port_nop = port_no;
760         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
761     }
762     ovs_rwlock_unlock(&dp->port_rwlock);
763
764     return error;
765 }
766
767 static int
768 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
769 {
770     struct dp_netdev *dp = get_dp_netdev(dpif);
771     int error;
772
773     ovs_rwlock_wrlock(&dp->port_rwlock);
774     error = port_no == ODPP_LOCAL ? EINVAL : do_del_port(dp, port_no);
775     ovs_rwlock_unlock(&dp->port_rwlock);
776
777     return error;
778 }
779
780 static bool
781 is_valid_port_number(odp_port_t port_no)
782 {
783     return port_no != ODPP_NONE;
784 }
785
786 static struct dp_netdev_port *
787 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
788     OVS_REQ_RDLOCK(dp->port_rwlock)
789 {
790     struct dp_netdev_port *port;
791
792     HMAP_FOR_EACH_IN_BUCKET (port, node, hash_int(odp_to_u32(port_no), 0),
793                              &dp->ports) {
794         if (port->port_no == port_no) {
795             return port;
796         }
797     }
798     return NULL;
799 }
800
801 static int
802 get_port_by_number(struct dp_netdev *dp,
803                    odp_port_t port_no, struct dp_netdev_port **portp)
804     OVS_REQ_RDLOCK(dp->port_rwlock)
805 {
806     if (!is_valid_port_number(port_no)) {
807         *portp = NULL;
808         return EINVAL;
809     } else {
810         *portp = dp_netdev_lookup_port(dp, port_no);
811         return *portp ? 0 : ENOENT;
812     }
813 }
814
815 static void
816 port_ref(struct dp_netdev_port *port)
817 {
818     if (port) {
819         ovs_refcount_ref(&port->ref_cnt);
820     }
821 }
822
823 static void
824 port_unref(struct dp_netdev_port *port)
825 {
826     if (port && ovs_refcount_unref(&port->ref_cnt) == 1) {
827         int i;
828
829         netdev_close(port->netdev);
830         netdev_restore_flags(port->sf);
831
832         for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
833             netdev_rxq_close(port->rxq[i]);
834         }
835         free(port->type);
836         free(port);
837     }
838 }
839
840 static int
841 get_port_by_name(struct dp_netdev *dp,
842                  const char *devname, struct dp_netdev_port **portp)
843     OVS_REQ_RDLOCK(dp->port_rwlock)
844 {
845     struct dp_netdev_port *port;
846
847     HMAP_FOR_EACH (port, node, &dp->ports) {
848         if (!strcmp(netdev_get_name(port->netdev), devname)) {
849             *portp = port;
850             return 0;
851         }
852     }
853     return ENOENT;
854 }
855
856 static int
857 do_del_port(struct dp_netdev *dp, odp_port_t port_no)
858     OVS_REQ_WRLOCK(dp->port_rwlock)
859 {
860     struct dp_netdev_port *port;
861     int error;
862
863     error = get_port_by_number(dp, port_no, &port);
864     if (error) {
865         return error;
866     }
867
868     hmap_remove(&dp->ports, &port->node);
869     seq_change(dp->port_seq);
870     if (netdev_is_pmd(port->netdev)) {
871         dp_netdev_reload_pmd_threads(dp);
872     }
873
874     port_unref(port);
875     return 0;
876 }
877
878 static void
879 answer_port_query(const struct dp_netdev_port *port,
880                   struct dpif_port *dpif_port)
881 {
882     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
883     dpif_port->type = xstrdup(port->type);
884     dpif_port->port_no = port->port_no;
885 }
886
887 static int
888 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
889                                  struct dpif_port *dpif_port)
890 {
891     struct dp_netdev *dp = get_dp_netdev(dpif);
892     struct dp_netdev_port *port;
893     int error;
894
895     ovs_rwlock_rdlock(&dp->port_rwlock);
896     error = get_port_by_number(dp, port_no, &port);
897     if (!error && dpif_port) {
898         answer_port_query(port, dpif_port);
899     }
900     ovs_rwlock_unlock(&dp->port_rwlock);
901
902     return error;
903 }
904
905 static int
906 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
907                                struct dpif_port *dpif_port)
908 {
909     struct dp_netdev *dp = get_dp_netdev(dpif);
910     struct dp_netdev_port *port;
911     int error;
912
913     ovs_rwlock_rdlock(&dp->port_rwlock);
914     error = get_port_by_name(dp, devname, &port);
915     if (!error && dpif_port) {
916         answer_port_query(port, dpif_port);
917     }
918     ovs_rwlock_unlock(&dp->port_rwlock);
919
920     return error;
921 }
922
923 static void
924 dp_netdev_flow_free(struct dp_netdev_flow *flow)
925 {
926     struct dp_netdev_flow_stats *bucket;
927     size_t i;
928
929     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &flow->stats) {
930         ovs_mutex_destroy(&bucket->mutex);
931         free_cacheline(bucket);
932     }
933     ovsthread_stats_destroy(&flow->stats);
934
935     cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
936     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
937     ovs_mutex_destroy(&flow->mutex);
938     free(flow);
939 }
940
941 static void
942 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
943     OVS_REQ_WRLOCK(dp->cls.rwlock)
944     OVS_REQUIRES(dp->flow_mutex)
945 {
946     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
947     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
948
949     classifier_remove(&dp->cls, cr);
950     hmap_remove(&dp->flow_table, node);
951     ovsrcu_postpone(dp_netdev_flow_free, flow);
952 }
953
954 static void
955 dp_netdev_flow_flush(struct dp_netdev *dp)
956 {
957     struct dp_netdev_flow *netdev_flow, *next;
958
959     ovs_mutex_lock(&dp->flow_mutex);
960     fat_rwlock_wrlock(&dp->cls.rwlock);
961     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
962         dp_netdev_remove_flow(dp, netdev_flow);
963     }
964     fat_rwlock_unlock(&dp->cls.rwlock);
965     ovs_mutex_unlock(&dp->flow_mutex);
966 }
967
968 static int
969 dpif_netdev_flow_flush(struct dpif *dpif)
970 {
971     struct dp_netdev *dp = get_dp_netdev(dpif);
972
973     dp_netdev_flow_flush(dp);
974     return 0;
975 }
976
977 struct dp_netdev_port_state {
978     uint32_t bucket;
979     uint32_t offset;
980     char *name;
981 };
982
983 static int
984 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
985 {
986     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
987     return 0;
988 }
989
990 static int
991 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
992                            struct dpif_port *dpif_port)
993 {
994     struct dp_netdev_port_state *state = state_;
995     struct dp_netdev *dp = get_dp_netdev(dpif);
996     struct hmap_node *node;
997     int retval;
998
999     ovs_rwlock_rdlock(&dp->port_rwlock);
1000     node = hmap_at_position(&dp->ports, &state->bucket, &state->offset);
1001     if (node) {
1002         struct dp_netdev_port *port;
1003
1004         port = CONTAINER_OF(node, struct dp_netdev_port, node);
1005
1006         free(state->name);
1007         state->name = xstrdup(netdev_get_name(port->netdev));
1008         dpif_port->name = state->name;
1009         dpif_port->type = port->type;
1010         dpif_port->port_no = port->port_no;
1011
1012         retval = 0;
1013     } else {
1014         retval = EOF;
1015     }
1016     ovs_rwlock_unlock(&dp->port_rwlock);
1017
1018     return retval;
1019 }
1020
1021 static int
1022 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1023 {
1024     struct dp_netdev_port_state *state = state_;
1025     free(state->name);
1026     free(state);
1027     return 0;
1028 }
1029
1030 static int
1031 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1032 {
1033     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1034     uint64_t new_port_seq;
1035     int error;
1036
1037     new_port_seq = seq_read(dpif->dp->port_seq);
1038     if (dpif->last_port_seq != new_port_seq) {
1039         dpif->last_port_seq = new_port_seq;
1040         error = ENOBUFS;
1041     } else {
1042         error = EAGAIN;
1043     }
1044
1045     return error;
1046 }
1047
1048 static void
1049 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1050 {
1051     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1052
1053     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1054 }
1055
1056 static struct dp_netdev_flow *
1057 dp_netdev_flow_cast(const struct cls_rule *cr)
1058 {
1059     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1060 }
1061
1062 static struct dp_netdev_flow *
1063 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct flow *flow)
1064     OVS_EXCLUDED(dp->cls.rwlock)
1065 {
1066     struct dp_netdev_flow *netdev_flow;
1067
1068     fat_rwlock_rdlock(&dp->cls.rwlock);
1069     netdev_flow = dp_netdev_flow_cast(classifier_lookup(&dp->cls, flow, NULL));
1070     fat_rwlock_unlock(&dp->cls.rwlock);
1071
1072     return netdev_flow;
1073 }
1074
1075 static struct dp_netdev_flow *
1076 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1077     OVS_REQ_RDLOCK(dp->cls.rwlock)
1078 {
1079     struct dp_netdev_flow *netdev_flow;
1080
1081     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1082                              &dp->flow_table) {
1083         if (flow_equal(&netdev_flow->flow, flow)) {
1084             return netdev_flow;
1085         }
1086     }
1087
1088     return NULL;
1089 }
1090
1091 static void
1092 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1093                     struct dpif_flow_stats *stats)
1094 {
1095     struct dp_netdev_flow_stats *bucket;
1096     size_t i;
1097
1098     memset(stats, 0, sizeof *stats);
1099     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1100         ovs_mutex_lock(&bucket->mutex);
1101         stats->n_packets += bucket->packet_count;
1102         stats->n_bytes += bucket->byte_count;
1103         stats->used = MAX(stats->used, bucket->used);
1104         stats->tcp_flags |= bucket->tcp_flags;
1105         ovs_mutex_unlock(&bucket->mutex);
1106     }
1107 }
1108
1109 static int
1110 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1111                               const struct nlattr *mask_key,
1112                               uint32_t mask_key_len, const struct flow *flow,
1113                               struct flow *mask)
1114 {
1115     if (mask_key_len) {
1116         enum odp_key_fitness fitness;
1117
1118         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1119         if (fitness) {
1120             /* This should not happen: it indicates that
1121              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1122              * disagree on the acceptable form of a mask.  Log the problem
1123              * as an error, with enough details to enable debugging. */
1124             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1125
1126             if (!VLOG_DROP_ERR(&rl)) {
1127                 struct ds s;
1128
1129                 ds_init(&s);
1130                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1131                                 true);
1132                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1133                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1134                 ds_destroy(&s);
1135             }
1136
1137             return EINVAL;
1138         }
1139     } else {
1140         enum mf_field_id id;
1141         /* No mask key, unwildcard everything except fields whose
1142          * prerequisities are not met. */
1143         memset(mask, 0x0, sizeof *mask);
1144
1145         for (id = 0; id < MFF_N_IDS; ++id) {
1146             /* Skip registers and metadata. */
1147             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1148                 && id != MFF_METADATA) {
1149                 const struct mf_field *mf = mf_from_id(id);
1150                 if (mf_are_prereqs_ok(mf, flow)) {
1151                     mf_mask_field(mf, mask);
1152                 }
1153             }
1154         }
1155     }
1156
1157     /* Force unwildcard the in_port.
1158      *
1159      * We need to do this even in the case where we unwildcard "everything"
1160      * above because "everything" only includes the 16-bit OpenFlow port number
1161      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1162      * port number mask->in_port.odp_port. */
1163     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1164
1165     return 0;
1166 }
1167
1168 static int
1169 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1170                               struct flow *flow)
1171 {
1172     odp_port_t in_port;
1173
1174     if (odp_flow_key_to_flow(key, key_len, flow)) {
1175         /* This should not happen: it indicates that odp_flow_key_from_flow()
1176          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1177          * flow.  Log the problem as an error, with enough details to enable
1178          * debugging. */
1179         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1180
1181         if (!VLOG_DROP_ERR(&rl)) {
1182             struct ds s;
1183
1184             ds_init(&s);
1185             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1186             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1187             ds_destroy(&s);
1188         }
1189
1190         return EINVAL;
1191     }
1192
1193     in_port = flow->in_port.odp_port;
1194     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1195         return EINVAL;
1196     }
1197
1198     return 0;
1199 }
1200
1201 static int
1202 dpif_netdev_flow_get(const struct dpif *dpif,
1203                      const struct nlattr *nl_key, size_t nl_key_len,
1204                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1205 {
1206     struct dp_netdev *dp = get_dp_netdev(dpif);
1207     struct dp_netdev_flow *netdev_flow;
1208     struct flow key;
1209     int error;
1210
1211     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1212     if (error) {
1213         return error;
1214     }
1215
1216     fat_rwlock_rdlock(&dp->cls.rwlock);
1217     netdev_flow = dp_netdev_find_flow(dp, &key);
1218     fat_rwlock_unlock(&dp->cls.rwlock);
1219
1220     if (netdev_flow) {
1221         if (stats) {
1222             get_dpif_flow_stats(netdev_flow, stats);
1223         }
1224
1225         if (actionsp) {
1226             struct dp_netdev_actions *actions;
1227
1228             actions = dp_netdev_flow_get_actions(netdev_flow);
1229             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1230         }
1231      } else {
1232         error = ENOENT;
1233     }
1234
1235     return error;
1236 }
1237
1238 static int
1239 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1240                    const struct flow_wildcards *wc,
1241                    const struct nlattr *actions,
1242                    size_t actions_len)
1243     OVS_REQUIRES(dp->flow_mutex)
1244 {
1245     struct dp_netdev_flow *netdev_flow;
1246     struct match match;
1247
1248     netdev_flow = xzalloc(sizeof *netdev_flow);
1249     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1250
1251     ovs_mutex_init(&netdev_flow->mutex);
1252
1253     ovsthread_stats_init(&netdev_flow->stats);
1254
1255     ovsrcu_set(&netdev_flow->actions,
1256                dp_netdev_actions_create(actions, actions_len));
1257
1258     match_init(&match, flow, wc);
1259     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1260                   &match, NETDEV_RULE_PRIORITY);
1261     fat_rwlock_wrlock(&dp->cls.rwlock);
1262     classifier_insert(&dp->cls,
1263                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1264     hmap_insert(&dp->flow_table,
1265                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1266                 flow_hash(flow, 0));
1267     fat_rwlock_unlock(&dp->cls.rwlock);
1268
1269     return 0;
1270 }
1271
1272 static void
1273 clear_stats(struct dp_netdev_flow *netdev_flow)
1274 {
1275     struct dp_netdev_flow_stats *bucket;
1276     size_t i;
1277
1278     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1279         ovs_mutex_lock(&bucket->mutex);
1280         bucket->used = 0;
1281         bucket->packet_count = 0;
1282         bucket->byte_count = 0;
1283         bucket->tcp_flags = 0;
1284         ovs_mutex_unlock(&bucket->mutex);
1285     }
1286 }
1287
1288 static int
1289 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1290 {
1291     struct dp_netdev *dp = get_dp_netdev(dpif);
1292     struct dp_netdev_flow *netdev_flow;
1293     struct flow flow;
1294     struct flow_wildcards wc;
1295     int error;
1296
1297     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1298     if (error) {
1299         return error;
1300     }
1301     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1302                                           put->mask, put->mask_len,
1303                                           &flow, &wc.masks);
1304     if (error) {
1305         return error;
1306     }
1307
1308     ovs_mutex_lock(&dp->flow_mutex);
1309     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1310     if (!netdev_flow) {
1311         if (put->flags & DPIF_FP_CREATE) {
1312             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1313                 if (put->stats) {
1314                     memset(put->stats, 0, sizeof *put->stats);
1315                 }
1316                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1317                                            put->actions_len);
1318             } else {
1319                 error = EFBIG;
1320             }
1321         } else {
1322             error = ENOENT;
1323         }
1324     } else {
1325         if (put->flags & DPIF_FP_MODIFY
1326             && flow_equal(&flow, &netdev_flow->flow)) {
1327             struct dp_netdev_actions *new_actions;
1328             struct dp_netdev_actions *old_actions;
1329
1330             new_actions = dp_netdev_actions_create(put->actions,
1331                                                    put->actions_len);
1332
1333             old_actions = dp_netdev_flow_get_actions(netdev_flow);
1334             ovsrcu_set(&netdev_flow->actions, new_actions);
1335
1336             if (put->stats) {
1337                 get_dpif_flow_stats(netdev_flow, put->stats);
1338             }
1339             if (put->flags & DPIF_FP_ZERO_STATS) {
1340                 clear_stats(netdev_flow);
1341             }
1342
1343             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
1344         } else if (put->flags & DPIF_FP_CREATE) {
1345             error = EEXIST;
1346         } else {
1347             /* Overlapping flow. */
1348             error = EINVAL;
1349         }
1350     }
1351     ovs_mutex_unlock(&dp->flow_mutex);
1352
1353     return error;
1354 }
1355
1356 static int
1357 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1358 {
1359     struct dp_netdev *dp = get_dp_netdev(dpif);
1360     struct dp_netdev_flow *netdev_flow;
1361     struct flow key;
1362     int error;
1363
1364     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1365     if (error) {
1366         return error;
1367     }
1368
1369     ovs_mutex_lock(&dp->flow_mutex);
1370     fat_rwlock_wrlock(&dp->cls.rwlock);
1371     netdev_flow = dp_netdev_find_flow(dp, &key);
1372     if (netdev_flow) {
1373         if (del->stats) {
1374             get_dpif_flow_stats(netdev_flow, del->stats);
1375         }
1376         dp_netdev_remove_flow(dp, netdev_flow);
1377     } else {
1378         error = ENOENT;
1379     }
1380     fat_rwlock_unlock(&dp->cls.rwlock);
1381     ovs_mutex_unlock(&dp->flow_mutex);
1382
1383     return error;
1384 }
1385
1386 struct dp_netdev_flow_state {
1387     struct dp_netdev_actions *actions;
1388     struct odputil_keybuf keybuf;
1389     struct odputil_keybuf maskbuf;
1390     struct dpif_flow_stats stats;
1391 };
1392
1393 struct dp_netdev_flow_iter {
1394     uint32_t bucket;
1395     uint32_t offset;
1396     int status;
1397     struct ovs_mutex mutex;
1398 };
1399
1400 static void
1401 dpif_netdev_flow_dump_state_init(void **statep)
1402 {
1403     struct dp_netdev_flow_state *state;
1404
1405     *statep = state = xmalloc(sizeof *state);
1406     state->actions = NULL;
1407 }
1408
1409 static void
1410 dpif_netdev_flow_dump_state_uninit(void *state_)
1411 {
1412     struct dp_netdev_flow_state *state = state_;
1413
1414     free(state);
1415 }
1416
1417 static int
1418 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **iterp)
1419 {
1420     struct dp_netdev_flow_iter *iter;
1421
1422     *iterp = iter = xmalloc(sizeof *iter);
1423     iter->bucket = 0;
1424     iter->offset = 0;
1425     iter->status = 0;
1426     ovs_mutex_init(&iter->mutex);
1427     return 0;
1428 }
1429
1430 /* XXX the caller must use 'actions' without quiescing */
1431 static int
1432 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *iter_, void *state_,
1433                            const struct nlattr **key, size_t *key_len,
1434                            const struct nlattr **mask, size_t *mask_len,
1435                            const struct nlattr **actions, size_t *actions_len,
1436                            const struct dpif_flow_stats **stats)
1437 {
1438     struct dp_netdev_flow_iter *iter = iter_;
1439     struct dp_netdev_flow_state *state = state_;
1440     struct dp_netdev *dp = get_dp_netdev(dpif);
1441     struct dp_netdev_flow *netdev_flow;
1442     int error;
1443
1444     ovs_mutex_lock(&iter->mutex);
1445     error = iter->status;
1446     if (!error) {
1447         struct hmap_node *node;
1448
1449         fat_rwlock_rdlock(&dp->cls.rwlock);
1450         node = hmap_at_position(&dp->flow_table, &iter->bucket, &iter->offset);
1451         if (node) {
1452             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1453         }
1454         fat_rwlock_unlock(&dp->cls.rwlock);
1455         if (!node) {
1456             iter->status = error = EOF;
1457         }
1458     }
1459     ovs_mutex_unlock(&iter->mutex);
1460     if (error) {
1461         return error;
1462     }
1463
1464     if (key) {
1465         struct ofpbuf buf;
1466
1467         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1468         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1469                                netdev_flow->flow.in_port.odp_port);
1470
1471         *key = ofpbuf_data(&buf);
1472         *key_len = ofpbuf_size(&buf);
1473     }
1474
1475     if (key && mask) {
1476         struct ofpbuf buf;
1477         struct flow_wildcards wc;
1478
1479         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1480         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1481         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1482                                odp_to_u32(wc.masks.in_port.odp_port),
1483                                SIZE_MAX);
1484
1485         *mask = ofpbuf_data(&buf);
1486         *mask_len = ofpbuf_size(&buf);
1487     }
1488
1489     if (actions || stats) {
1490         state->actions = NULL;
1491
1492         if (actions) {
1493             state->actions = dp_netdev_flow_get_actions(netdev_flow);
1494             *actions = state->actions->actions;
1495             *actions_len = state->actions->size;
1496         }
1497
1498         if (stats) {
1499             get_dpif_flow_stats(netdev_flow, &state->stats);
1500             *stats = &state->stats;
1501         }
1502     }
1503
1504     return 0;
1505 }
1506
1507 static int
1508 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *iter_)
1509 {
1510     struct dp_netdev_flow_iter *iter = iter_;
1511
1512     ovs_mutex_destroy(&iter->mutex);
1513     free(iter);
1514     return 0;
1515 }
1516
1517 static int
1518 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1519 {
1520     struct dp_netdev *dp = get_dp_netdev(dpif);
1521     struct pkt_metadata *md = &execute->md;
1522     struct flow key;
1523
1524     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
1525         ofpbuf_size(execute->packet) > UINT16_MAX) {
1526         return EINVAL;
1527     }
1528
1529     /* Extract flow key. */
1530     flow_extract(execute->packet, md, &key);
1531
1532     ovs_rwlock_rdlock(&dp->port_rwlock);
1533     dp_netdev_execute_actions(dp, &key, execute->packet, false, md,
1534                               execute->actions, execute->actions_len);
1535     ovs_rwlock_unlock(&dp->port_rwlock);
1536
1537     return 0;
1538 }
1539
1540 static void
1541 dp_netdev_destroy_all_queues(struct dp_netdev *dp)
1542     OVS_REQ_WRLOCK(dp->queue_rwlock)
1543 {
1544     size_t i;
1545
1546     dp_netdev_purge_queues(dp);
1547
1548     for (i = 0; i < dp->n_handlers; i++) {
1549         struct dp_netdev_queue *q = &dp->handler_queues[i];
1550
1551         ovs_mutex_destroy(&q->mutex);
1552         seq_destroy(q->seq);
1553     }
1554     free(dp->handler_queues);
1555     dp->handler_queues = NULL;
1556     dp->n_handlers = 0;
1557 }
1558
1559 static void
1560 dp_netdev_refresh_queues(struct dp_netdev *dp, uint32_t n_handlers)
1561     OVS_REQ_WRLOCK(dp->queue_rwlock)
1562 {
1563     if (dp->n_handlers != n_handlers) {
1564         size_t i;
1565
1566         dp_netdev_destroy_all_queues(dp);
1567
1568         dp->n_handlers = n_handlers;
1569         dp->handler_queues = xzalloc(n_handlers * sizeof *dp->handler_queues);
1570
1571         for (i = 0; i < n_handlers; i++) {
1572             struct dp_netdev_queue *q = &dp->handler_queues[i];
1573
1574             ovs_mutex_init(&q->mutex);
1575             q->seq = seq_create();
1576         }
1577     }
1578 }
1579
1580 static int
1581 dpif_netdev_recv_set(struct dpif *dpif, bool enable)
1582 {
1583     struct dp_netdev *dp = get_dp_netdev(dpif);
1584
1585     if ((dp->handler_queues != NULL) == enable) {
1586         return 0;
1587     }
1588
1589     fat_rwlock_wrlock(&dp->queue_rwlock);
1590     if (!enable) {
1591         dp_netdev_destroy_all_queues(dp);
1592     } else {
1593         dp_netdev_refresh_queues(dp, 1);
1594     }
1595     fat_rwlock_unlock(&dp->queue_rwlock);
1596
1597     return 0;
1598 }
1599
1600 static int
1601 dpif_netdev_handlers_set(struct dpif *dpif, uint32_t n_handlers)
1602 {
1603     struct dp_netdev *dp = get_dp_netdev(dpif);
1604
1605     fat_rwlock_wrlock(&dp->queue_rwlock);
1606     if (dp->handler_queues) {
1607         dp_netdev_refresh_queues(dp, n_handlers);
1608     }
1609     fat_rwlock_unlock(&dp->queue_rwlock);
1610
1611     return 0;
1612 }
1613
1614 static int
1615 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1616                               uint32_t queue_id, uint32_t *priority)
1617 {
1618     *priority = queue_id;
1619     return 0;
1620 }
1621
1622 static bool
1623 dp_netdev_recv_check(const struct dp_netdev *dp, const uint32_t handler_id)
1624     OVS_REQ_RDLOCK(dp->queue_rwlock)
1625 {
1626     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1627
1628     if (!dp->handler_queues) {
1629         VLOG_WARN_RL(&rl, "receiving upcall disabled");
1630         return false;
1631     }
1632
1633     if (handler_id >= dp->n_handlers) {
1634         VLOG_WARN_RL(&rl, "handler index out of bound");
1635         return false;
1636     }
1637
1638     return true;
1639 }
1640
1641 static int
1642 dpif_netdev_recv(struct dpif *dpif, uint32_t handler_id,
1643                  struct dpif_upcall *upcall, struct ofpbuf *buf)
1644 {
1645     struct dp_netdev *dp = get_dp_netdev(dpif);
1646     struct dp_netdev_queue *q;
1647     int error = 0;
1648
1649     fat_rwlock_rdlock(&dp->queue_rwlock);
1650
1651     if (!dp_netdev_recv_check(dp, handler_id)) {
1652         error = EAGAIN;
1653         goto out;
1654     }
1655
1656     q = &dp->handler_queues[handler_id];
1657     ovs_mutex_lock(&q->mutex);
1658     if (q->head != q->tail) {
1659         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1660
1661         *upcall = u->upcall;
1662
1663         ofpbuf_uninit(buf);
1664         *buf = u->buf;
1665     } else {
1666         error = EAGAIN;
1667     }
1668     ovs_mutex_unlock(&q->mutex);
1669
1670 out:
1671     fat_rwlock_unlock(&dp->queue_rwlock);
1672
1673     return error;
1674 }
1675
1676 static void
1677 dpif_netdev_recv_wait(struct dpif *dpif, uint32_t handler_id)
1678 {
1679     struct dp_netdev *dp = get_dp_netdev(dpif);
1680     struct dp_netdev_queue *q;
1681     uint64_t seq;
1682
1683     fat_rwlock_rdlock(&dp->queue_rwlock);
1684
1685     if (!dp_netdev_recv_check(dp, handler_id)) {
1686         goto out;
1687     }
1688
1689     q = &dp->handler_queues[handler_id];
1690     ovs_mutex_lock(&q->mutex);
1691     seq = seq_read(q->seq);
1692     if (q->head != q->tail) {
1693         poll_immediate_wake();
1694     } else {
1695         seq_wait(q->seq, seq);
1696     }
1697
1698     ovs_mutex_unlock(&q->mutex);
1699
1700 out:
1701     fat_rwlock_unlock(&dp->queue_rwlock);
1702 }
1703
1704 static void
1705 dpif_netdev_recv_purge(struct dpif *dpif)
1706 {
1707     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1708
1709     fat_rwlock_wrlock(&dpif_netdev->dp->queue_rwlock);
1710     dp_netdev_purge_queues(dpif_netdev->dp);
1711     fat_rwlock_unlock(&dpif_netdev->dp->queue_rwlock);
1712 }
1713 \f
1714 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1715  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1716  * 'ofpacts'. */
1717 struct dp_netdev_actions *
1718 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1719 {
1720     struct dp_netdev_actions *netdev_actions;
1721
1722     netdev_actions = xmalloc(sizeof *netdev_actions);
1723     netdev_actions->actions = xmemdup(actions, size);
1724     netdev_actions->size = size;
1725
1726     return netdev_actions;
1727 }
1728
1729 struct dp_netdev_actions *
1730 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
1731 {
1732     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
1733 }
1734
1735 static void
1736 dp_netdev_actions_free(struct dp_netdev_actions *actions)
1737 {
1738     free(actions->actions);
1739     free(actions);
1740 }
1741 \f
1742
1743 static void
1744 dp_netdev_process_rxq_port(struct dp_netdev *dp,
1745                           struct dp_netdev_port *port,
1746                           struct netdev_rxq *rxq)
1747 {
1748     struct ofpbuf *packet[NETDEV_MAX_RX_BATCH];
1749     int error, c;
1750
1751     error = netdev_rxq_recv(rxq, packet, &c);
1752     if (!error) {
1753         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
1754         int i;
1755
1756         for (i = 0; i < c; i++) {
1757             dp_netdev_port_input(dp, packet[i], &md);
1758         }
1759     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1760         static struct vlog_rate_limit rl
1761             = VLOG_RATE_LIMIT_INIT(1, 5);
1762
1763         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1764                     netdev_get_name(port->netdev),
1765                     ovs_strerror(error));
1766     }
1767 }
1768
1769 static void
1770 dpif_netdev_run(struct dpif *dpif)
1771 {
1772     struct dp_netdev_port *port;
1773     struct dp_netdev *dp = get_dp_netdev(dpif);
1774
1775     ovs_rwlock_rdlock(&dp->port_rwlock);
1776
1777     HMAP_FOR_EACH (port, node, &dp->ports) {
1778         if (!netdev_is_pmd(port->netdev)) {
1779             int i;
1780
1781             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1782                 dp_netdev_process_rxq_port(dp, port, port->rxq[i]);
1783             }
1784         }
1785     }
1786
1787     ovs_rwlock_unlock(&dp->port_rwlock);
1788 }
1789
1790 static void
1791 dpif_netdev_wait(struct dpif *dpif)
1792 {
1793     struct dp_netdev_port *port;
1794     struct dp_netdev *dp = get_dp_netdev(dpif);
1795
1796     ovs_rwlock_rdlock(&dp->port_rwlock);
1797
1798     HMAP_FOR_EACH (port, node, &dp->ports) {
1799         if (!netdev_is_pmd(port->netdev)) {
1800             int i;
1801
1802             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1803                 netdev_rxq_wait(port->rxq[i]);
1804             }
1805         }
1806     }
1807     ovs_rwlock_unlock(&dp->port_rwlock);
1808 }
1809
1810 struct rxq_poll {
1811     struct dp_netdev_port *port;
1812     struct netdev_rxq *rx;
1813 };
1814
1815 static int
1816 pmd_load_queues(struct pmd_thread *f,
1817                 struct rxq_poll **ppoll_list, int poll_cnt)
1818 {
1819     struct dp_netdev *dp = f->dp;
1820     struct rxq_poll *poll_list = *ppoll_list;
1821     struct dp_netdev_port *port;
1822     int id = f->id;
1823     int index;
1824     int i;
1825
1826     /* Simple scheduler for netdev rx polling. */
1827     ovs_rwlock_rdlock(&dp->port_rwlock);
1828     for (i = 0; i < poll_cnt; i++) {
1829          port_unref(poll_list[i].port);
1830     }
1831
1832     poll_cnt = 0;
1833     index = 0;
1834
1835     HMAP_FOR_EACH (port, node, &f->dp->ports) {
1836         if (netdev_is_pmd(port->netdev)) {
1837             int i;
1838
1839             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1840                 if ((index % dp->n_pmd_threads) == id) {
1841                     poll_list = xrealloc(poll_list, sizeof *poll_list * (poll_cnt + 1));
1842
1843                     port_ref(port);
1844                     poll_list[poll_cnt].port = port;
1845                     poll_list[poll_cnt].rx = port->rxq[i];
1846                     poll_cnt++;
1847                 }
1848                 index++;
1849             }
1850         }
1851     }
1852
1853     ovs_rwlock_unlock(&dp->port_rwlock);
1854     *ppoll_list = poll_list;
1855     return poll_cnt;
1856 }
1857
1858 static void *
1859 pmd_thread_main(void *f_)
1860 {
1861     struct pmd_thread *f = f_;
1862     struct dp_netdev *dp = f->dp;
1863     unsigned int lc = 0;
1864     struct rxq_poll *poll_list;
1865     unsigned int port_seq;
1866     int poll_cnt;
1867     int i;
1868
1869     f->name = xasprintf("pmd_%u", ovsthread_id_self());
1870     set_subprogram_name("%s", f->name);
1871     poll_cnt = 0;
1872     poll_list = NULL;
1873
1874     pmd_thread_setaffinity_cpu(f->id);
1875 reload:
1876     poll_cnt = pmd_load_queues(f, &poll_list, poll_cnt);
1877     atomic_read(&f->change_seq, &port_seq);
1878
1879     for (;;) {
1880         unsigned int c_port_seq;
1881         int i;
1882
1883         for (i = 0; i < poll_cnt; i++) {
1884             dp_netdev_process_rxq_port(dp,  poll_list[i].port, poll_list[i].rx);
1885         }
1886
1887         if (lc++ > 1024) {
1888             ovsrcu_quiesce();
1889
1890             /* TODO: need completely userspace based signaling method.
1891              * to keep this thread entirely in userspace.
1892              * For now using atomic counter. */
1893             lc = 0;
1894             atomic_read_explicit(&f->change_seq, &c_port_seq, memory_order_consume);
1895             if (c_port_seq != port_seq) {
1896                 break;
1897             }
1898         }
1899     }
1900
1901     if (!latch_is_set(&f->dp->exit_latch)){
1902         goto reload;
1903     }
1904
1905     for (i = 0; i < poll_cnt; i++) {
1906          port_unref(poll_list[i].port);
1907     }
1908
1909     free(poll_list);
1910     free(f->name);
1911     return NULL;
1912 }
1913
1914 static void
1915 dp_netdev_set_pmd_threads(struct dp_netdev *dp, int n)
1916 {
1917     int i;
1918
1919     if (n == dp->n_pmd_threads) {
1920         return;
1921     }
1922
1923     /* Stop existing threads. */
1924     latch_set(&dp->exit_latch);
1925     dp_netdev_reload_pmd_threads(dp);
1926     for (i = 0; i < dp->n_pmd_threads; i++) {
1927         struct pmd_thread *f = &dp->pmd_threads[i];
1928
1929         xpthread_join(f->thread, NULL);
1930     }
1931     latch_poll(&dp->exit_latch);
1932     free(dp->pmd_threads);
1933
1934     /* Start new threads. */
1935     dp->pmd_threads = xmalloc(n * sizeof *dp->pmd_threads);
1936     dp->n_pmd_threads = n;
1937
1938     for (i = 0; i < n; i++) {
1939         struct pmd_thread *f = &dp->pmd_threads[i];
1940
1941         f->dp = dp;
1942         f->id = i;
1943         atomic_store(&f->change_seq, 1);
1944
1945         /* Each thread will distribute all devices rx-queues among
1946          * themselves. */
1947         xpthread_create(&f->thread, NULL, pmd_thread_main, f);
1948     }
1949 }
1950
1951 \f
1952 static void *
1953 dp_netdev_flow_stats_new_cb(void)
1954 {
1955     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1956     ovs_mutex_init(&bucket->mutex);
1957     return bucket;
1958 }
1959
1960 static void
1961 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1962                     const struct ofpbuf *packet,
1963                     const struct flow *key)
1964 {
1965     uint16_t tcp_flags = ntohs(key->tcp_flags);
1966     long long int now = time_msec();
1967     struct dp_netdev_flow_stats *bucket;
1968
1969     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
1970                                         dp_netdev_flow_stats_new_cb);
1971
1972     ovs_mutex_lock(&bucket->mutex);
1973     bucket->used = MAX(now, bucket->used);
1974     bucket->packet_count++;
1975     bucket->byte_count += ofpbuf_size(packet);
1976     bucket->tcp_flags |= tcp_flags;
1977     ovs_mutex_unlock(&bucket->mutex);
1978 }
1979
1980 static void *
1981 dp_netdev_stats_new_cb(void)
1982 {
1983     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1984     ovs_mutex_init(&bucket->mutex);
1985     return bucket;
1986 }
1987
1988 static void
1989 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type)
1990 {
1991     struct dp_netdev_stats *bucket;
1992
1993     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
1994     ovs_mutex_lock(&bucket->mutex);
1995     bucket->n[type]++;
1996     ovs_mutex_unlock(&bucket->mutex);
1997 }
1998
1999 static void
2000 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
2001                      struct pkt_metadata *md)
2002 {
2003     struct dp_netdev_flow *netdev_flow;
2004     struct flow key;
2005
2006     if (ofpbuf_size(packet) < ETH_HEADER_LEN) {
2007         ofpbuf_delete(packet);
2008         return;
2009     }
2010     flow_extract(packet, md, &key);
2011     netdev_flow = dp_netdev_lookup_flow(dp, &key);
2012     if (netdev_flow) {
2013         struct dp_netdev_actions *actions;
2014
2015         dp_netdev_flow_used(netdev_flow, packet, &key);
2016
2017         actions = dp_netdev_flow_get_actions(netdev_flow);
2018         dp_netdev_execute_actions(dp, &key, packet, true, md,
2019                                   actions->actions, actions->size);
2020         dp_netdev_count_packet(dp, DP_STAT_HIT);
2021     } else if (dp->handler_queues) {
2022         dp_netdev_count_packet(dp, DP_STAT_MISS);
2023         dp_netdev_output_userspace(dp, packet,
2024                                    flow_hash_5tuple(&key, 0) % dp->n_handlers,
2025                                    DPIF_UC_MISS, &key, NULL);
2026         ofpbuf_delete(packet);
2027     }
2028 }
2029
2030 static int
2031 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
2032                            int queue_no, int type, const struct flow *flow,
2033                            const struct nlattr *userdata)
2034 {
2035     struct dp_netdev_queue *q;
2036     int error;
2037
2038     fat_rwlock_rdlock(&dp->queue_rwlock);
2039     q = &dp->handler_queues[queue_no];
2040     ovs_mutex_lock(&q->mutex);
2041     if (q->head - q->tail < MAX_QUEUE_LEN) {
2042         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
2043         struct dpif_upcall *upcall = &u->upcall;
2044         struct ofpbuf *buf = &u->buf;
2045         size_t buf_size;
2046
2047         upcall->type = type;
2048
2049         /* Allocate buffer big enough for everything. */
2050         buf_size = ODPUTIL_FLOW_KEY_BYTES;
2051         if (userdata) {
2052             buf_size += NLA_ALIGN(userdata->nla_len);
2053         }
2054         buf_size += ofpbuf_size(packet);
2055         ofpbuf_init(buf, buf_size);
2056
2057         /* Put ODP flow. */
2058         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
2059         upcall->key = ofpbuf_data(buf);
2060         upcall->key_len = ofpbuf_size(buf);
2061
2062         /* Put userdata. */
2063         if (userdata) {
2064             upcall->userdata = ofpbuf_put(buf, userdata,
2065                                           NLA_ALIGN(userdata->nla_len));
2066         }
2067
2068         ofpbuf_set_data(&upcall->packet,
2069                         ofpbuf_put(buf, ofpbuf_data(packet), ofpbuf_size(packet)));
2070         ofpbuf_set_size(&upcall->packet, ofpbuf_size(packet));
2071
2072         seq_change(q->seq);
2073
2074         error = 0;
2075     } else {
2076         dp_netdev_count_packet(dp, DP_STAT_LOST);
2077         error = ENOBUFS;
2078     }
2079     ovs_mutex_unlock(&q->mutex);
2080     fat_rwlock_unlock(&dp->queue_rwlock);
2081
2082     return error;
2083 }
2084
2085 struct dp_netdev_execute_aux {
2086     struct dp_netdev *dp;
2087     const struct flow *key;
2088 };
2089
2090 static void
2091 dp_execute_cb(void *aux_, struct ofpbuf *packet,
2092               struct pkt_metadata *md,
2093               const struct nlattr *a, bool may_steal)
2094     OVS_NO_THREAD_SAFETY_ANALYSIS
2095 {
2096     struct dp_netdev_execute_aux *aux = aux_;
2097     int type = nl_attr_type(a);
2098     struct dp_netdev_port *p;
2099
2100     switch ((enum ovs_action_attr)type) {
2101     case OVS_ACTION_ATTR_OUTPUT:
2102         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
2103         if (p) {
2104             netdev_send(p->netdev, packet, may_steal);
2105         }
2106         break;
2107
2108     case OVS_ACTION_ATTR_USERSPACE: {
2109         const struct nlattr *userdata;
2110
2111         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2112
2113         dp_netdev_output_userspace(aux->dp, packet,
2114                                    flow_hash_5tuple(aux->key, 0)
2115                                        % aux->dp->n_handlers,
2116                                    DPIF_UC_ACTION, aux->key,
2117                                    userdata);
2118
2119         if (may_steal) {
2120             ofpbuf_delete(packet);
2121         }
2122         break;
2123     }
2124
2125     case OVS_ACTION_ATTR_RECIRC: {
2126         const struct ovs_action_recirc *act;
2127
2128         act = nl_attr_get(a);
2129         md->recirc_id = act->recirc_id;
2130         md->dp_hash = 0;
2131
2132         if (act->hash_alg == OVS_RECIRC_HASH_ALG_L4) {
2133             struct flow flow;
2134
2135             flow_extract(packet, md, &flow);
2136             md->dp_hash = flow_hash_symmetric_l4(&flow, act->hash_bias);
2137         }
2138
2139         dp_netdev_port_input(aux->dp, packet, md);
2140         break;
2141     }
2142
2143     case OVS_ACTION_ATTR_PUSH_VLAN:
2144     case OVS_ACTION_ATTR_POP_VLAN:
2145     case OVS_ACTION_ATTR_PUSH_MPLS:
2146     case OVS_ACTION_ATTR_POP_MPLS:
2147     case OVS_ACTION_ATTR_SET:
2148     case OVS_ACTION_ATTR_SAMPLE:
2149     case OVS_ACTION_ATTR_UNSPEC:
2150     case __OVS_ACTION_ATTR_MAX:
2151         OVS_NOT_REACHED();
2152     }
2153
2154 }
2155
2156 static void
2157 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
2158                           struct ofpbuf *packet, bool may_steal,
2159                           struct pkt_metadata *md,
2160                           const struct nlattr *actions, size_t actions_len)
2161 {
2162     struct dp_netdev_execute_aux aux = {dp, key};
2163
2164     odp_execute_actions(&aux, packet, may_steal, md,
2165                         actions, actions_len, dp_execute_cb);
2166 }
2167
2168 const struct dpif_class dpif_netdev_class = {
2169     "netdev",
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
2208 static void
2209 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2210                               const char *argv[], void *aux OVS_UNUSED)
2211 {
2212     struct dp_netdev_port *port;
2213     struct dp_netdev *dp;
2214     odp_port_t port_no;
2215
2216     ovs_mutex_lock(&dp_netdev_mutex);
2217     dp = shash_find_data(&dp_netdevs, argv[1]);
2218     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2219         ovs_mutex_unlock(&dp_netdev_mutex);
2220         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2221         return;
2222     }
2223     ovs_refcount_ref(&dp->ref_cnt);
2224     ovs_mutex_unlock(&dp_netdev_mutex);
2225
2226     ovs_rwlock_wrlock(&dp->port_rwlock);
2227     if (get_port_by_name(dp, argv[2], &port)) {
2228         unixctl_command_reply_error(conn, "unknown port");
2229         goto exit;
2230     }
2231
2232     port_no = u32_to_odp(atoi(argv[3]));
2233     if (!port_no || port_no == ODPP_NONE) {
2234         unixctl_command_reply_error(conn, "bad port number");
2235         goto exit;
2236     }
2237     if (dp_netdev_lookup_port(dp, port_no)) {
2238         unixctl_command_reply_error(conn, "port number already in use");
2239         goto exit;
2240     }
2241     hmap_remove(&dp->ports, &port->node);
2242     port->port_no = port_no;
2243     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
2244     seq_change(dp->port_seq);
2245     unixctl_command_reply(conn, NULL);
2246
2247 exit:
2248     ovs_rwlock_unlock(&dp->port_rwlock);
2249     dp_netdev_unref(dp);
2250 }
2251
2252 static void
2253 dpif_dummy_register__(const char *type)
2254 {
2255     struct dpif_class *class;
2256
2257     class = xmalloc(sizeof *class);
2258     *class = dpif_netdev_class;
2259     class->type = xstrdup(type);
2260     dp_register_provider(class);
2261 }
2262
2263 void
2264 dpif_dummy_register(bool override)
2265 {
2266     if (override) {
2267         struct sset types;
2268         const char *type;
2269
2270         sset_init(&types);
2271         dp_enumerate_types(&types);
2272         SSET_FOR_EACH (type, &types) {
2273             if (!dp_unregister_provider(type)) {
2274                 dpif_dummy_register__(type);
2275             }
2276         }
2277         sset_destroy(&types);
2278     }
2279
2280     dpif_dummy_register__("dummy");
2281
2282     unixctl_command_register("dpif-dummy/change-port-number",
2283                              "DP PORT NEW-NUMBER",
2284                              3, 3, dpif_dummy_change_port_number, NULL);
2285 }