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