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