netdev: Add n_txq to 'struct netdev'.
[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-netdev.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 "cmap.h"
36 #include "csum.h"
37 #include "dpif.h"
38 #include "dpif-provider.h"
39 #include "dummy.h"
40 #include "dynamic-string.h"
41 #include "fat-rwlock.h"
42 #include "flow.h"
43 #include "cmap.h"
44 #include "latch.h"
45 #include "list.h"
46 #include "meta-flow.h"
47 #include "netdev.h"
48 #include "netdev-dpdk.h"
49 #include "netdev-vport.h"
50 #include "netlink.h"
51 #include "odp-execute.h"
52 #include "odp-util.h"
53 #include "ofp-print.h"
54 #include "ofpbuf.h"
55 #include "ovs-rcu.h"
56 #include "packet-dpif.h"
57 #include "packets.h"
58 #include "poll-loop.h"
59 #include "random.h"
60 #include "seq.h"
61 #include "shash.h"
62 #include "sset.h"
63 #include "timeval.h"
64 #include "unixctl.h"
65 #include "util.h"
66 #include "vlog.h"
67
68 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
69
70 /* By default, choose a priority in the middle. */
71 #define NETDEV_RULE_PRIORITY 0x8000
72
73 #define FLOW_DUMP_MAX_BATCH 50
74 /* Use per thread recirc_depth to prevent recirculation loop. */
75 #define MAX_RECIRC_DEPTH 5
76 DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
77
78 /* Configuration parameters. */
79 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
80
81 /* Protects against changes to 'dp_netdevs'. */
82 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
83
84 /* Contains all 'struct dp_netdev's. */
85 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
86     = SHASH_INITIALIZER(&dp_netdevs);
87
88 static struct vlog_rate_limit upcall_rl = VLOG_RATE_LIMIT_INIT(600, 600);
89
90 /* Stores a miniflow */
91
92 /* There are fields in the flow structure that we never use. Therefore we can
93  * save a few words of memory */
94 #define NETDEV_KEY_BUF_SIZE_U32 (FLOW_U32S                 \
95                                  - MINI_N_INLINE           \
96                                  - FLOW_U32_SIZE(regs)     \
97                                  - FLOW_U32_SIZE(metadata) \
98                                 )
99 struct netdev_flow_key {
100     struct miniflow flow;
101     uint32_t buf[NETDEV_KEY_BUF_SIZE_U32];
102 };
103
104 /* Exact match cache for frequently used flows
105  *
106  * The cache uses a 32-bit hash of the packet (which can be the RSS hash) to
107  * search its entries for a miniflow that matches exactly the miniflow of the
108  * packet. It stores the 'cls_rule'(rule) that matches the miniflow.
109  *
110  * A cache entry holds a reference to its 'dp_netdev_flow'.
111  *
112  * A miniflow with a given hash can be in one of EM_FLOW_HASH_SEGS different
113  * entries. The 32-bit hash is split into EM_FLOW_HASH_SEGS values (each of
114  * them is EM_FLOW_HASH_SHIFT bits wide and the remainder is thrown away). Each
115  * value is the index of a cache entry where the miniflow could be.
116  *
117  *
118  * Thread-safety
119  * =============
120  *
121  * Each pmd_thread has its own private exact match cache.
122  * If dp_netdev_input is not called from a pmd thread, a mutex is used.
123  */
124
125 #define EM_FLOW_HASH_SHIFT 10
126 #define EM_FLOW_HASH_ENTRIES (1u << EM_FLOW_HASH_SHIFT)
127 #define EM_FLOW_HASH_MASK (EM_FLOW_HASH_ENTRIES - 1)
128 #define EM_FLOW_HASH_SEGS 2
129
130 struct emc_entry {
131     uint32_t hash;
132     struct netdev_flow_key mf;
133     struct dp_netdev_flow *flow;
134 };
135
136 struct emc_cache {
137     struct emc_entry entries[EM_FLOW_HASH_ENTRIES];
138 };
139
140 /* Iterate in the exact match cache through every entry that might contain a
141  * miniflow with hash 'HASH'. */
142 #define EMC_FOR_EACH_POS_WITH_HASH(EMC, CURRENT_ENTRY, HASH)                 \
143     for (uint32_t i__ = 0, srch_hash__ = (HASH);                             \
144          (CURRENT_ENTRY) = &(EMC)->entries[srch_hash__ & EM_FLOW_HASH_MASK], \
145          i__ < EM_FLOW_HASH_SEGS;                                            \
146          i__++, srch_hash__ >>= EM_FLOW_HASH_SHIFT)
147
148 /* Datapath based on the network device interface from netdev.h.
149  *
150  *
151  * Thread-safety
152  * =============
153  *
154  * Some members, marked 'const', are immutable.  Accessing other members
155  * requires synchronization, as noted in more detail below.
156  *
157  * Acquisition order is, from outermost to innermost:
158  *
159  *    dp_netdev_mutex (global)
160  *    port_mutex
161  *    emc_mutex
162  *    flow_mutex
163  */
164 struct dp_netdev {
165     const struct dpif_class *const class;
166     const char *const name;
167     struct dpif *dpif;
168     struct ovs_refcount ref_cnt;
169     atomic_flag destroyed;
170
171     /* Flows.
172      *
173      * Writers of 'flow_table' must take the 'flow_mutex'.  Corresponding
174      * changes to 'cls' must be made while still holding the 'flow_mutex'.
175      */
176     struct ovs_mutex flow_mutex;
177     struct classifier cls;
178     struct cmap flow_table OVS_GUARDED; /* Flow table. */
179
180     /* Statistics.
181      *
182      * ovsthread_stats is internally synchronized. */
183     struct ovsthread_stats stats; /* Contains 'struct dp_netdev_stats *'. */
184
185     /* Ports.
186      *
187      * Protected by RCU.  Take the mutex to add or remove ports. */
188     struct ovs_mutex port_mutex;
189     struct cmap ports;
190     struct seq *port_seq;       /* Incremented whenever a port changes. */
191
192     /* Protects access to ofproto-dpif-upcall interface during revalidator
193      * thread synchronization. */
194     struct fat_rwlock upcall_rwlock;
195     upcall_callback *upcall_cb;  /* Callback function for executing upcalls. */
196     void *upcall_aux;
197
198     /* Forwarding threads. */
199     struct latch exit_latch;
200     struct pmd_thread *pmd_threads;
201     size_t n_pmd_threads;
202     int pmd_count;
203
204     /* Exact match cache for non-pmd devices.
205      * Pmd devices use instead each thread's flow_cache for this purpose.
206      * Protected by emc_mutex */
207     struct emc_cache flow_cache OVS_GUARDED;
208     struct ovs_mutex emc_mutex;
209 };
210
211 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
212                                                     odp_port_t);
213
214 enum dp_stat_type {
215     DP_STAT_HIT,                /* Packets that matched in the flow table. */
216     DP_STAT_MISS,               /* Packets that did not match. */
217     DP_STAT_LOST,               /* Packets not passed up to the client. */
218     DP_N_STATS
219 };
220
221 /* Contained by struct dp_netdev's 'stats' member.  */
222 struct dp_netdev_stats {
223     struct ovs_mutex mutex;          /* Protects 'n'. */
224
225     /* Indexed by DP_STAT_*, protected by 'mutex'. */
226     unsigned long long int n[DP_N_STATS] OVS_GUARDED;
227 };
228
229
230 /* A port in a netdev-based datapath. */
231 struct dp_netdev_port {
232     struct cmap_node node;      /* Node in dp_netdev's 'ports'. */
233     odp_port_t port_no;
234     struct netdev *netdev;
235     struct netdev_saved_flags *sf;
236     struct netdev_rxq **rxq;
237     struct ovs_refcount ref_cnt;
238     char *type;                 /* Port type as requested by user. */
239 };
240
241 /* A flow in dp_netdev's 'flow_table'.
242  *
243  *
244  * Thread-safety
245  * =============
246  *
247  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
248  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
249  *
250  * Motivation
251  * ----------
252  *
253  * The thread safety rules described here for "struct dp_netdev_flow" are
254  * motivated by two goals:
255  *
256  *    - Prevent threads that read members of "struct dp_netdev_flow" from
257  *      reading bad data due to changes by some thread concurrently modifying
258  *      those members.
259  *
260  *    - Prevent two threads making changes to members of a given "struct
261  *      dp_netdev_flow" from interfering with each other.
262  *
263  *
264  * Rules
265  * -----
266  *
267  * A flow 'flow' may be accessed without a risk of being freed during an RCU
268  * grace period.  Code that needs to hold onto a flow for a while
269  * should try incrementing 'flow->ref_cnt' with dp_netdev_flow_ref().
270  *
271  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
272  * flow from being deleted from 'cls' and it doesn't protect members of 'flow'
273  * from modification.
274  *
275  * Some members, marked 'const', are immutable.  Accessing other members
276  * requires synchronization, as noted in more detail below.
277  */
278 struct dp_netdev_flow {
279     bool dead;
280     /* Packet classification. */
281     const struct cls_rule cr;   /* In owning dp_netdev's 'cls'. */
282
283     /* Hash table index by unmasked flow. */
284     const struct cmap_node node; /* In owning dp_netdev's 'flow_table'. */
285     const struct flow flow;      /* The flow that created this entry. */
286
287     /* Number of references.
288      * The classifier owns one reference.
289      * Any thread trying to keep a rule from being freed should hold its own
290      * reference. */
291     struct ovs_refcount ref_cnt;
292
293     /* Statistics.
294      *
295      * Reading or writing these members requires 'mutex'. */
296     struct ovsthread_stats stats; /* Contains "struct dp_netdev_flow_stats". */
297
298     /* Actions. */
299     OVSRCU_TYPE(struct dp_netdev_actions *) actions;
300 };
301
302 static void dp_netdev_flow_unref(struct dp_netdev_flow *);
303 static bool dp_netdev_flow_ref(struct dp_netdev_flow *);
304
305 /* Contained by struct dp_netdev_flow's 'stats' member.  */
306 struct dp_netdev_flow_stats {
307     struct ovs_mutex mutex;         /* Guards all the other members. */
308
309     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
310     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
311     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
312     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
313 };
314
315 /* A set of datapath actions within a "struct dp_netdev_flow".
316  *
317  *
318  * Thread-safety
319  * =============
320  *
321  * A struct dp_netdev_actions 'actions' is protected with RCU. */
322 struct dp_netdev_actions {
323     /* These members are immutable: they do not change during the struct's
324      * lifetime.  */
325     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
326     unsigned int size;          /* Size of 'actions', in bytes. */
327 };
328
329 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
330                                                    size_t);
331 struct dp_netdev_actions *dp_netdev_flow_get_actions(
332     const struct dp_netdev_flow *);
333 static void dp_netdev_actions_free(struct dp_netdev_actions *);
334
335 /* PMD: Poll modes drivers.  PMD accesses devices via polling to eliminate
336  * the performance overhead of interrupt processing.  Therefore netdev can
337  * not implement rx-wait for these devices.  dpif-netdev needs to poll
338  * these device to check for recv buffer.  pmd-thread does polling for
339  * devices assigned to itself thread.
340  *
341  * DPDK used PMD for accessing NIC.
342  *
343  * A thread that receives packets from PMD ports, looks them up in the flow
344  * table, and executes the actions it finds.
345  **/
346 struct pmd_thread {
347     struct dp_netdev *dp;
348     struct emc_cache flow_cache;
349     pthread_t thread;
350     int id;
351     atomic_uint change_seq;
352 };
353
354 #define PMD_INITIAL_SEQ 1
355
356 /* Interface to netdev-based datapath. */
357 struct dpif_netdev {
358     struct dpif dpif;
359     struct dp_netdev *dp;
360     uint64_t last_port_seq;
361 };
362
363 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
364                               struct dp_netdev_port **portp);
365 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
366                             struct dp_netdev_port **portp);
367 static void dp_netdev_free(struct dp_netdev *)
368     OVS_REQUIRES(dp_netdev_mutex);
369 static void dp_netdev_flow_flush(struct dp_netdev *);
370 static int do_add_port(struct dp_netdev *dp, const char *devname,
371                        const char *type, odp_port_t port_no)
372     OVS_REQUIRES(dp->port_mutex);
373 static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
374     OVS_REQUIRES(dp->port_mutex);
375 static int dpif_netdev_open(const struct dpif_class *, const char *name,
376                             bool create, struct dpif **);
377 static void dp_netdev_execute_actions(struct dp_netdev *dp,
378                                       struct dpif_packet **, int c,
379                                       bool may_steal, struct pkt_metadata *,
380                                       struct emc_cache *flow_cache,
381                                       const struct nlattr *actions,
382                                       size_t actions_len);
383 static void dp_netdev_input(struct dp_netdev *, struct emc_cache *,
384                             struct dpif_packet **, int cnt,
385                             struct pkt_metadata *);
386
387 static void dp_netdev_set_pmd_threads(struct dp_netdev *, int n);
388 static void dp_netdev_disable_upcall(struct dp_netdev *);
389
390 static void emc_clear_entry(struct emc_entry *ce);
391
392 static void
393 emc_cache_init(struct emc_cache *flow_cache)
394 {
395     int i;
396
397     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
398         flow_cache->entries[i].flow = NULL;
399         flow_cache->entries[i].hash = 0;
400         miniflow_initialize(&flow_cache->entries[i].mf.flow,
401                             flow_cache->entries[i].mf.buf);
402     }
403 }
404
405 static void
406 emc_cache_uninit(struct emc_cache *flow_cache)
407 {
408     int i;
409
410     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
411         emc_clear_entry(&flow_cache->entries[i]);
412     }
413 }
414
415 static struct dpif_netdev *
416 dpif_netdev_cast(const struct dpif *dpif)
417 {
418     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
419     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
420 }
421
422 static struct dp_netdev *
423 get_dp_netdev(const struct dpif *dpif)
424 {
425     return dpif_netdev_cast(dpif)->dp;
426 }
427
428 static int
429 dpif_netdev_enumerate(struct sset *all_dps,
430                       const struct dpif_class *dpif_class)
431 {
432     struct shash_node *node;
433
434     ovs_mutex_lock(&dp_netdev_mutex);
435     SHASH_FOR_EACH(node, &dp_netdevs) {
436         struct dp_netdev *dp = node->data;
437         if (dpif_class != dp->class) {
438             /* 'dp_netdevs' contains both "netdev" and "dummy" dpifs.
439              * If the class doesn't match, skip this dpif. */
440              continue;
441         }
442         sset_add(all_dps, node->name);
443     }
444     ovs_mutex_unlock(&dp_netdev_mutex);
445
446     return 0;
447 }
448
449 static bool
450 dpif_netdev_class_is_dummy(const struct dpif_class *class)
451 {
452     return class != &dpif_netdev_class;
453 }
454
455 static const char *
456 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
457 {
458     return strcmp(type, "internal") ? type
459                   : dpif_netdev_class_is_dummy(class) ? "dummy"
460                   : "tap";
461 }
462
463 static struct dpif *
464 create_dpif_netdev(struct dp_netdev *dp)
465 {
466     uint16_t netflow_id = hash_string(dp->name, 0);
467     struct dpif_netdev *dpif;
468
469     ovs_refcount_ref(&dp->ref_cnt);
470
471     dpif = xmalloc(sizeof *dpif);
472     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
473     dpif->dp = dp;
474     dpif->last_port_seq = seq_read(dp->port_seq);
475
476     return &dpif->dpif;
477 }
478
479 /* Choose an unused, non-zero port number and return it on success.
480  * Return ODPP_NONE on failure. */
481 static odp_port_t
482 choose_port(struct dp_netdev *dp, const char *name)
483     OVS_REQUIRES(dp->port_mutex)
484 {
485     uint32_t port_no;
486
487     if (dp->class != &dpif_netdev_class) {
488         const char *p;
489         int start_no = 0;
490
491         /* If the port name begins with "br", start the number search at
492          * 100 to make writing tests easier. */
493         if (!strncmp(name, "br", 2)) {
494             start_no = 100;
495         }
496
497         /* If the port name contains a number, try to assign that port number.
498          * This can make writing unit tests easier because port numbers are
499          * predictable. */
500         for (p = name; *p != '\0'; p++) {
501             if (isdigit((unsigned char) *p)) {
502                 port_no = start_no + strtol(p, NULL, 10);
503                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
504                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
505                     return u32_to_odp(port_no);
506                 }
507                 break;
508             }
509         }
510     }
511
512     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
513         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
514             return u32_to_odp(port_no);
515         }
516     }
517
518     return ODPP_NONE;
519 }
520
521 static int
522 create_dp_netdev(const char *name, const struct dpif_class *class,
523                  struct dp_netdev **dpp)
524     OVS_REQUIRES(dp_netdev_mutex)
525 {
526     struct dp_netdev *dp;
527     int error;
528
529     dp = xzalloc(sizeof *dp);
530     shash_add(&dp_netdevs, name, dp);
531
532     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
533     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
534     ovs_refcount_init(&dp->ref_cnt);
535     atomic_flag_clear(&dp->destroyed);
536
537     ovs_mutex_init(&dp->flow_mutex);
538     classifier_init(&dp->cls, NULL);
539     cmap_init(&dp->flow_table);
540
541     ovsthread_stats_init(&dp->stats);
542
543     ovs_mutex_init(&dp->port_mutex);
544     cmap_init(&dp->ports);
545     dp->port_seq = seq_create();
546     latch_init(&dp->exit_latch);
547     fat_rwlock_init(&dp->upcall_rwlock);
548
549     /* Disable upcalls by default. */
550     dp_netdev_disable_upcall(dp);
551     dp->upcall_aux = NULL;
552     dp->upcall_cb = NULL;
553
554     ovs_mutex_lock(&dp->port_mutex);
555     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
556     ovs_mutex_unlock(&dp->port_mutex);
557     if (error) {
558         dp_netdev_free(dp);
559         return error;
560     }
561
562     ovs_mutex_init_recursive(&dp->emc_mutex);
563     emc_cache_init(&dp->flow_cache);
564
565     *dpp = dp;
566     return 0;
567 }
568
569 static int
570 dpif_netdev_open(const struct dpif_class *class, const char *name,
571                  bool create, struct dpif **dpifp)
572 {
573     struct dp_netdev *dp;
574     int error;
575
576     ovs_mutex_lock(&dp_netdev_mutex);
577     dp = shash_find_data(&dp_netdevs, name);
578     if (!dp) {
579         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
580     } else {
581         error = (dp->class != class ? EINVAL
582                  : create ? EEXIST
583                  : 0);
584     }
585     if (!error) {
586         *dpifp = create_dpif_netdev(dp);
587         dp->dpif = *dpifp;
588     }
589     ovs_mutex_unlock(&dp_netdev_mutex);
590
591     return error;
592 }
593
594 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
595  * through the 'dp_netdevs' shash while freeing 'dp'. */
596 static void
597 dp_netdev_free(struct dp_netdev *dp)
598     OVS_REQUIRES(dp_netdev_mutex)
599 {
600     struct dp_netdev_port *port;
601     struct dp_netdev_stats *bucket;
602     int i;
603
604     shash_find_and_delete(&dp_netdevs, dp->name);
605
606     dp_netdev_set_pmd_threads(dp, 0);
607     free(dp->pmd_threads);
608
609     dp_netdev_flow_flush(dp);
610     ovs_mutex_lock(&dp->port_mutex);
611     CMAP_FOR_EACH (port, node, &dp->ports) {
612         do_del_port(dp, port);
613     }
614     ovs_mutex_unlock(&dp->port_mutex);
615
616     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
617         ovs_mutex_destroy(&bucket->mutex);
618         free_cacheline(bucket);
619     }
620     ovsthread_stats_destroy(&dp->stats);
621
622     classifier_destroy(&dp->cls);
623     cmap_destroy(&dp->flow_table);
624     ovs_mutex_destroy(&dp->flow_mutex);
625     seq_destroy(dp->port_seq);
626     cmap_destroy(&dp->ports);
627     fat_rwlock_destroy(&dp->upcall_rwlock);
628     latch_destroy(&dp->exit_latch);
629
630     emc_cache_uninit(&dp->flow_cache);
631     ovs_mutex_destroy(&dp->emc_mutex);
632
633     free(CONST_CAST(char *, dp->name));
634     free(dp);
635 }
636
637 static void
638 dp_netdev_unref(struct dp_netdev *dp)
639 {
640     if (dp) {
641         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
642          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
643         ovs_mutex_lock(&dp_netdev_mutex);
644         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
645             dp_netdev_free(dp);
646         }
647         ovs_mutex_unlock(&dp_netdev_mutex);
648     }
649 }
650
651 static void
652 dpif_netdev_close(struct dpif *dpif)
653 {
654     struct dp_netdev *dp = get_dp_netdev(dpif);
655
656     dp_netdev_unref(dp);
657     free(dpif);
658 }
659
660 static int
661 dpif_netdev_destroy(struct dpif *dpif)
662 {
663     struct dp_netdev *dp = get_dp_netdev(dpif);
664
665     if (!atomic_flag_test_and_set(&dp->destroyed)) {
666         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
667             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
668             OVS_NOT_REACHED();
669         }
670     }
671
672     return 0;
673 }
674
675 static int
676 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
677 {
678     struct dp_netdev *dp = get_dp_netdev(dpif);
679     struct dp_netdev_stats *bucket;
680     size_t i;
681
682     stats->n_flows = cmap_count(&dp->flow_table);
683
684     stats->n_hit = stats->n_missed = stats->n_lost = 0;
685     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
686         ovs_mutex_lock(&bucket->mutex);
687         stats->n_hit += bucket->n[DP_STAT_HIT];
688         stats->n_missed += bucket->n[DP_STAT_MISS];
689         stats->n_lost += bucket->n[DP_STAT_LOST];
690         ovs_mutex_unlock(&bucket->mutex);
691     }
692     stats->n_masks = UINT32_MAX;
693     stats->n_mask_hit = UINT64_MAX;
694
695     return 0;
696 }
697
698 static void
699 dp_netdev_reload_pmd_threads(struct dp_netdev *dp)
700 {
701     int i;
702
703     for (i = 0; i < dp->n_pmd_threads; i++) {
704         struct pmd_thread *f = &dp->pmd_threads[i];
705         int old_seq;
706
707         atomic_add_relaxed(&f->change_seq, 1, &old_seq);
708     }
709 }
710
711 static uint32_t
712 hash_port_no(odp_port_t port_no)
713 {
714     return hash_int(odp_to_u32(port_no), 0);
715 }
716
717 static int
718 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
719             odp_port_t port_no)
720     OVS_REQUIRES(dp->port_mutex)
721 {
722     struct netdev_saved_flags *sf;
723     struct dp_netdev_port *port;
724     struct netdev *netdev;
725     enum netdev_flags flags;
726     const char *open_type;
727     int error;
728     int i;
729
730     /* XXX reject devices already in some dp_netdev. */
731
732     /* Open and validate network device. */
733     open_type = dpif_netdev_port_open_type(dp->class, type);
734     error = netdev_open(devname, open_type, &netdev);
735     if (error) {
736         return error;
737     }
738     /* XXX reject non-Ethernet devices */
739
740     netdev_get_flags(netdev, &flags);
741     if (flags & NETDEV_LOOPBACK) {
742         VLOG_ERR("%s: cannot add a loopback device", devname);
743         netdev_close(netdev);
744         return EINVAL;
745     }
746
747     port = xzalloc(sizeof *port);
748     port->port_no = port_no;
749     port->netdev = netdev;
750     port->rxq = xmalloc(sizeof *port->rxq * netdev_n_rxq(netdev));
751     port->type = xstrdup(type);
752     for (i = 0; i < netdev_n_rxq(netdev); i++) {
753         error = netdev_rxq_open(netdev, &port->rxq[i], i);
754         if (error
755             && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
756             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
757                      devname, ovs_strerror(errno));
758             netdev_close(netdev);
759             free(port->type);
760             free(port->rxq);
761             free(port);
762             return error;
763         }
764     }
765
766     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
767     if (error) {
768         for (i = 0; i < netdev_n_rxq(netdev); i++) {
769             netdev_rxq_close(port->rxq[i]);
770         }
771         netdev_close(netdev);
772         free(port->type);
773         free(port->rxq);
774         free(port);
775         return error;
776     }
777     port->sf = sf;
778
779     if (netdev_is_pmd(netdev)) {
780         dp->pmd_count++;
781         dp_netdev_set_pmd_threads(dp, NR_PMD_THREADS);
782         dp_netdev_reload_pmd_threads(dp);
783     }
784     ovs_refcount_init(&port->ref_cnt);
785
786     cmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
787     seq_change(dp->port_seq);
788
789     return 0;
790 }
791
792 static int
793 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
794                      odp_port_t *port_nop)
795 {
796     struct dp_netdev *dp = get_dp_netdev(dpif);
797     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
798     const char *dpif_port;
799     odp_port_t port_no;
800     int error;
801
802     ovs_mutex_lock(&dp->port_mutex);
803     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
804     if (*port_nop != ODPP_NONE) {
805         port_no = *port_nop;
806         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
807     } else {
808         port_no = choose_port(dp, dpif_port);
809         error = port_no == ODPP_NONE ? EFBIG : 0;
810     }
811     if (!error) {
812         *port_nop = port_no;
813         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
814     }
815     ovs_mutex_unlock(&dp->port_mutex);
816
817     return error;
818 }
819
820 static int
821 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
822 {
823     struct dp_netdev *dp = get_dp_netdev(dpif);
824     int error;
825
826     ovs_mutex_lock(&dp->port_mutex);
827     if (port_no == ODPP_LOCAL) {
828         error = EINVAL;
829     } else {
830         struct dp_netdev_port *port;
831
832         error = get_port_by_number(dp, port_no, &port);
833         if (!error) {
834             do_del_port(dp, port);
835         }
836     }
837     ovs_mutex_unlock(&dp->port_mutex);
838
839     return error;
840 }
841
842 static bool
843 is_valid_port_number(odp_port_t port_no)
844 {
845     return port_no != ODPP_NONE;
846 }
847
848 static struct dp_netdev_port *
849 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
850 {
851     struct dp_netdev_port *port;
852
853     CMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
854         if (port->port_no == port_no) {
855             return port;
856         }
857     }
858     return NULL;
859 }
860
861 static int
862 get_port_by_number(struct dp_netdev *dp,
863                    odp_port_t port_no, struct dp_netdev_port **portp)
864 {
865     if (!is_valid_port_number(port_no)) {
866         *portp = NULL;
867         return EINVAL;
868     } else {
869         *portp = dp_netdev_lookup_port(dp, port_no);
870         return *portp ? 0 : ENOENT;
871     }
872 }
873
874 static void
875 port_ref(struct dp_netdev_port *port)
876 {
877     if (port) {
878         ovs_refcount_ref(&port->ref_cnt);
879     }
880 }
881
882 static bool
883 port_try_ref(struct dp_netdev_port *port)
884 {
885     if (port) {
886         return ovs_refcount_try_ref_rcu(&port->ref_cnt);
887     }
888
889     return false;
890 }
891
892 static void
893 port_destroy__(struct dp_netdev_port *port)
894 {
895     int n_rxq = netdev_n_rxq(port->netdev);
896     int i;
897
898     netdev_close(port->netdev);
899     netdev_restore_flags(port->sf);
900
901     for (i = 0; i < n_rxq; i++) {
902         netdev_rxq_close(port->rxq[i]);
903     }
904     free(port->rxq);
905     free(port->type);
906     free(port);
907 }
908
909 static void
910 port_unref(struct dp_netdev_port *port)
911 {
912     if (port && ovs_refcount_unref_relaxed(&port->ref_cnt) == 1) {
913         ovsrcu_postpone(port_destroy__, port);
914     }
915 }
916
917 static int
918 get_port_by_name(struct dp_netdev *dp,
919                  const char *devname, struct dp_netdev_port **portp)
920     OVS_REQUIRES(dp->port_mutex)
921 {
922     struct dp_netdev_port *port;
923
924     CMAP_FOR_EACH (port, node, &dp->ports) {
925         if (!strcmp(netdev_get_name(port->netdev), devname)) {
926             *portp = port;
927             return 0;
928         }
929     }
930     return ENOENT;
931 }
932
933 static void
934 do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
935     OVS_REQUIRES(dp->port_mutex)
936 {
937     cmap_remove(&dp->ports, &port->node, hash_odp_port(port->port_no));
938     seq_change(dp->port_seq);
939     if (netdev_is_pmd(port->netdev)) {
940         dp_netdev_reload_pmd_threads(dp);
941     }
942
943     port_unref(port);
944 }
945
946 static void
947 answer_port_query(const struct dp_netdev_port *port,
948                   struct dpif_port *dpif_port)
949 {
950     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
951     dpif_port->type = xstrdup(port->type);
952     dpif_port->port_no = port->port_no;
953 }
954
955 static int
956 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
957                                  struct dpif_port *dpif_port)
958 {
959     struct dp_netdev *dp = get_dp_netdev(dpif);
960     struct dp_netdev_port *port;
961     int error;
962
963     error = get_port_by_number(dp, port_no, &port);
964     if (!error && dpif_port) {
965         answer_port_query(port, dpif_port);
966     }
967
968     return error;
969 }
970
971 static int
972 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
973                                struct dpif_port *dpif_port)
974 {
975     struct dp_netdev *dp = get_dp_netdev(dpif);
976     struct dp_netdev_port *port;
977     int error;
978
979     ovs_mutex_lock(&dp->port_mutex);
980     error = get_port_by_name(dp, devname, &port);
981     if (!error && dpif_port) {
982         answer_port_query(port, dpif_port);
983     }
984     ovs_mutex_unlock(&dp->port_mutex);
985
986     return error;
987 }
988
989 static void
990 dp_netdev_flow_free(struct dp_netdev_flow *flow)
991 {
992     struct dp_netdev_flow_stats *bucket;
993     size_t i;
994
995     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &flow->stats) {
996         ovs_mutex_destroy(&bucket->mutex);
997         free_cacheline(bucket);
998     }
999     ovsthread_stats_destroy(&flow->stats);
1000
1001     cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
1002     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
1003     free(flow);
1004 }
1005
1006 static void dp_netdev_flow_unref(struct dp_netdev_flow *flow)
1007 {
1008     if (ovs_refcount_unref_relaxed(&flow->ref_cnt) == 1) {
1009         ovsrcu_postpone(dp_netdev_flow_free, flow);
1010     }
1011 }
1012
1013 static void
1014 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
1015     OVS_REQUIRES(dp->flow_mutex)
1016 {
1017     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
1018     struct cmap_node *node = CONST_CAST(struct cmap_node *, &flow->node);
1019
1020     classifier_remove(&dp->cls, cr);
1021     cmap_remove(&dp->flow_table, node, flow_hash(&flow->flow, 0));
1022     flow->dead = true;
1023
1024     dp_netdev_flow_unref(flow);
1025 }
1026
1027 static void
1028 dp_netdev_flow_flush(struct dp_netdev *dp)
1029 {
1030     struct dp_netdev_flow *netdev_flow;
1031
1032     ovs_mutex_lock(&dp->flow_mutex);
1033     CMAP_FOR_EACH (netdev_flow, node, &dp->flow_table) {
1034         dp_netdev_remove_flow(dp, netdev_flow);
1035     }
1036     ovs_mutex_unlock(&dp->flow_mutex);
1037 }
1038
1039 static int
1040 dpif_netdev_flow_flush(struct dpif *dpif)
1041 {
1042     struct dp_netdev *dp = get_dp_netdev(dpif);
1043
1044     dp_netdev_flow_flush(dp);
1045     return 0;
1046 }
1047
1048 struct dp_netdev_port_state {
1049     struct cmap_position position;
1050     char *name;
1051 };
1052
1053 static int
1054 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
1055 {
1056     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
1057     return 0;
1058 }
1059
1060 static int
1061 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
1062                            struct dpif_port *dpif_port)
1063 {
1064     struct dp_netdev_port_state *state = state_;
1065     struct dp_netdev *dp = get_dp_netdev(dpif);
1066     struct cmap_node *node;
1067     int retval;
1068
1069     node = cmap_next_position(&dp->ports, &state->position);
1070     if (node) {
1071         struct dp_netdev_port *port;
1072
1073         port = CONTAINER_OF(node, struct dp_netdev_port, node);
1074
1075         free(state->name);
1076         state->name = xstrdup(netdev_get_name(port->netdev));
1077         dpif_port->name = state->name;
1078         dpif_port->type = port->type;
1079         dpif_port->port_no = port->port_no;
1080
1081         retval = 0;
1082     } else {
1083         retval = EOF;
1084     }
1085
1086     return retval;
1087 }
1088
1089 static int
1090 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1091 {
1092     struct dp_netdev_port_state *state = state_;
1093     free(state->name);
1094     free(state);
1095     return 0;
1096 }
1097
1098 static int
1099 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1100 {
1101     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1102     uint64_t new_port_seq;
1103     int error;
1104
1105     new_port_seq = seq_read(dpif->dp->port_seq);
1106     if (dpif->last_port_seq != new_port_seq) {
1107         dpif->last_port_seq = new_port_seq;
1108         error = ENOBUFS;
1109     } else {
1110         error = EAGAIN;
1111     }
1112
1113     return error;
1114 }
1115
1116 static void
1117 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1118 {
1119     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1120
1121     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1122 }
1123
1124 static struct dp_netdev_flow *
1125 dp_netdev_flow_cast(const struct cls_rule *cr)
1126 {
1127     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1128 }
1129
1130 static bool dp_netdev_flow_ref(struct dp_netdev_flow *flow)
1131 {
1132     return ovs_refcount_try_ref_rcu(&flow->ref_cnt);
1133 }
1134
1135 static inline bool
1136 emc_entry_alive(struct emc_entry *ce)
1137 {
1138     return ce->flow && !ce->flow->dead;
1139 }
1140
1141 static void
1142 emc_clear_entry(struct emc_entry *ce)
1143 {
1144     if (ce->flow) {
1145         dp_netdev_flow_unref(ce->flow);
1146         ce->flow = NULL;
1147     }
1148 }
1149
1150 static inline void
1151 emc_change_entry(struct emc_entry *ce, struct dp_netdev_flow *flow,
1152                  const struct miniflow *mf, uint32_t hash)
1153 {
1154     if (ce->flow != flow) {
1155         if (ce->flow) {
1156             dp_netdev_flow_unref(ce->flow);
1157         }
1158
1159         if (dp_netdev_flow_ref(flow)) {
1160             ce->flow = flow;
1161         } else {
1162             ce->flow = NULL;
1163         }
1164     }
1165     if (mf) {
1166         miniflow_clone_inline(&ce->mf.flow, mf, count_1bits(mf->map));
1167         ce->hash = hash;
1168     }
1169 }
1170
1171 static inline void
1172 emc_insert(struct emc_cache *cache, const struct miniflow *mf, uint32_t hash,
1173            struct dp_netdev_flow *flow)
1174 {
1175     struct emc_entry *to_be_replaced = NULL;
1176     struct emc_entry *current_entry;
1177
1178     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, hash) {
1179         if (current_entry->hash == hash
1180             && miniflow_equal(&current_entry->mf.flow, mf)) {
1181
1182             /* We found the entry with the 'mf' miniflow */
1183             emc_change_entry(current_entry, flow, NULL, 0);
1184             return;
1185         }
1186
1187         /* Replacement policy: put the flow in an empty (not alive) entry, or
1188          * in the first entry where it can be */
1189         if (!to_be_replaced
1190             || (emc_entry_alive(to_be_replaced)
1191                 && !emc_entry_alive(current_entry))
1192             || current_entry->hash < to_be_replaced->hash) {
1193             to_be_replaced = current_entry;
1194         }
1195     }
1196     /* We didn't find the miniflow in the cache.
1197      * The 'to_be_replaced' entry is where the new flow will be stored */
1198
1199     emc_change_entry(to_be_replaced, flow, mf, hash);
1200 }
1201
1202 static inline struct dp_netdev_flow *
1203 emc_lookup(struct emc_cache *cache, const struct miniflow *mf, uint32_t hash)
1204 {
1205     struct emc_entry *current_entry;
1206
1207     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, hash) {
1208         if (current_entry->hash == hash && emc_entry_alive(current_entry)
1209             && miniflow_equal(&current_entry->mf.flow, mf)) {
1210
1211             /* We found the entry with the 'mf' miniflow */
1212             return current_entry->flow;
1213         }
1214     }
1215
1216     return NULL;
1217 }
1218
1219 static struct dp_netdev_flow *
1220 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct miniflow *key)
1221 {
1222     struct dp_netdev_flow *netdev_flow;
1223     struct cls_rule *rule;
1224
1225     classifier_lookup_miniflow_batch(&dp->cls, &key, &rule, 1);
1226     netdev_flow = dp_netdev_flow_cast(rule);
1227
1228     return netdev_flow;
1229 }
1230
1231 static struct dp_netdev_flow *
1232 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1233 {
1234     struct dp_netdev_flow *netdev_flow;
1235
1236     CMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1237                              &dp->flow_table) {
1238         if (flow_equal(&netdev_flow->flow, flow)) {
1239             return netdev_flow;
1240         }
1241     }
1242
1243     return NULL;
1244 }
1245
1246 static void
1247 get_dpif_flow_stats(const struct dp_netdev_flow *netdev_flow,
1248                     struct dpif_flow_stats *stats)
1249 {
1250     struct dp_netdev_flow_stats *bucket;
1251     size_t i;
1252
1253     memset(stats, 0, sizeof *stats);
1254     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1255         ovs_mutex_lock(&bucket->mutex);
1256         stats->n_packets += bucket->packet_count;
1257         stats->n_bytes += bucket->byte_count;
1258         stats->used = MAX(stats->used, bucket->used);
1259         stats->tcp_flags |= bucket->tcp_flags;
1260         ovs_mutex_unlock(&bucket->mutex);
1261     }
1262 }
1263
1264 static void
1265 dp_netdev_flow_to_dpif_flow(const struct dp_netdev_flow *netdev_flow,
1266                             struct ofpbuf *buffer, struct dpif_flow *flow)
1267 {
1268     struct flow_wildcards wc;
1269     struct dp_netdev_actions *actions;
1270
1271     minimask_expand(&netdev_flow->cr.match.mask, &wc);
1272     odp_flow_key_from_mask(buffer, &wc.masks, &netdev_flow->flow,
1273                            odp_to_u32(wc.masks.in_port.odp_port),
1274                            SIZE_MAX, true);
1275     flow->mask = ofpbuf_data(buffer);
1276     flow->mask_len = ofpbuf_size(buffer);
1277
1278     actions = dp_netdev_flow_get_actions(netdev_flow);
1279     flow->actions = actions->actions;
1280     flow->actions_len = actions->size;
1281
1282     get_dpif_flow_stats(netdev_flow, &flow->stats);
1283 }
1284
1285 static int
1286 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1287                               const struct nlattr *mask_key,
1288                               uint32_t mask_key_len, const struct flow *flow,
1289                               struct flow *mask)
1290 {
1291     if (mask_key_len) {
1292         enum odp_key_fitness fitness;
1293
1294         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1295         if (fitness) {
1296             /* This should not happen: it indicates that
1297              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1298              * disagree on the acceptable form of a mask.  Log the problem
1299              * as an error, with enough details to enable debugging. */
1300             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1301
1302             if (!VLOG_DROP_ERR(&rl)) {
1303                 struct ds s;
1304
1305                 ds_init(&s);
1306                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1307                                 true);
1308                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1309                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1310                 ds_destroy(&s);
1311             }
1312
1313             return EINVAL;
1314         }
1315     } else {
1316         enum mf_field_id id;
1317         /* No mask key, unwildcard everything except fields whose
1318          * prerequisities are not met. */
1319         memset(mask, 0x0, sizeof *mask);
1320
1321         for (id = 0; id < MFF_N_IDS; ++id) {
1322             /* Skip registers and metadata. */
1323             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1324                 && id != MFF_METADATA) {
1325                 const struct mf_field *mf = mf_from_id(id);
1326                 if (mf_are_prereqs_ok(mf, flow)) {
1327                     mf_mask_field(mf, mask);
1328                 }
1329             }
1330         }
1331     }
1332
1333     /* Force unwildcard the in_port.
1334      *
1335      * We need to do this even in the case where we unwildcard "everything"
1336      * above because "everything" only includes the 16-bit OpenFlow port number
1337      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1338      * port number mask->in_port.odp_port. */
1339     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1340
1341     return 0;
1342 }
1343
1344 static int
1345 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1346                               struct flow *flow)
1347 {
1348     odp_port_t in_port;
1349
1350     if (odp_flow_key_to_flow(key, key_len, flow)) {
1351         /* This should not happen: it indicates that odp_flow_key_from_flow()
1352          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1353          * flow.  Log the problem as an error, with enough details to enable
1354          * debugging. */
1355         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1356
1357         if (!VLOG_DROP_ERR(&rl)) {
1358             struct ds s;
1359
1360             ds_init(&s);
1361             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1362             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1363             ds_destroy(&s);
1364         }
1365
1366         return EINVAL;
1367     }
1368
1369     in_port = flow->in_port.odp_port;
1370     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1371         return EINVAL;
1372     }
1373
1374     return 0;
1375 }
1376
1377 static int
1378 dpif_netdev_flow_get(const struct dpif *dpif, const struct dpif_flow_get *get)
1379 {
1380     struct dp_netdev *dp = get_dp_netdev(dpif);
1381     struct dp_netdev_flow *netdev_flow;
1382     struct flow key;
1383     int error;
1384
1385     error = dpif_netdev_flow_from_nlattrs(get->key, get->key_len, &key);
1386     if (error) {
1387         return error;
1388     }
1389
1390     netdev_flow = dp_netdev_find_flow(dp, &key);
1391
1392     if (netdev_flow) {
1393         dp_netdev_flow_to_dpif_flow(netdev_flow, get->buffer, get->flow);
1394      } else {
1395         error = ENOENT;
1396     }
1397
1398     return error;
1399 }
1400
1401 static int
1402 dp_netdev_flow_add(struct dp_netdev *dp, struct match *match,
1403                    const struct nlattr *actions, size_t actions_len)
1404     OVS_REQUIRES(dp->flow_mutex)
1405 {
1406     struct dp_netdev_flow *netdev_flow;
1407
1408     netdev_flow = xzalloc(sizeof *netdev_flow);
1409     *CONST_CAST(struct flow *, &netdev_flow->flow) = match->flow;
1410
1411     ovs_refcount_init(&netdev_flow->ref_cnt);
1412
1413     ovsthread_stats_init(&netdev_flow->stats);
1414
1415     ovsrcu_set(&netdev_flow->actions,
1416                dp_netdev_actions_create(actions, actions_len));
1417
1418     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1419                   match, NETDEV_RULE_PRIORITY);
1420     cmap_insert(&dp->flow_table,
1421                 CONST_CAST(struct cmap_node *, &netdev_flow->node),
1422                 flow_hash(&match->flow, 0));
1423     classifier_insert(&dp->cls,
1424                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1425
1426     if (OVS_UNLIKELY(VLOG_IS_DBG_ENABLED())) {
1427         struct ds ds = DS_EMPTY_INITIALIZER;
1428
1429         ds_put_cstr(&ds, "flow_add: ");
1430         match_format(match, &ds, OFP_DEFAULT_PRIORITY);
1431         ds_put_cstr(&ds, ", actions:");
1432         format_odp_actions(&ds, actions, actions_len);
1433
1434         VLOG_DBG_RL(&upcall_rl, "%s", ds_cstr(&ds));
1435
1436         ds_destroy(&ds);
1437     }
1438
1439     return 0;
1440 }
1441
1442 static void
1443 clear_stats(struct dp_netdev_flow *netdev_flow)
1444 {
1445     struct dp_netdev_flow_stats *bucket;
1446     size_t i;
1447
1448     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1449         ovs_mutex_lock(&bucket->mutex);
1450         bucket->used = 0;
1451         bucket->packet_count = 0;
1452         bucket->byte_count = 0;
1453         bucket->tcp_flags = 0;
1454         ovs_mutex_unlock(&bucket->mutex);
1455     }
1456 }
1457
1458 static int
1459 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1460 {
1461     struct dp_netdev *dp = get_dp_netdev(dpif);
1462     struct dp_netdev_flow *netdev_flow;
1463     struct miniflow miniflow;
1464     struct match match;
1465     int error;
1466
1467     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &match.flow);
1468     if (error) {
1469         return error;
1470     }
1471     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1472                                           put->mask, put->mask_len,
1473                                           &match.flow, &match.wc.masks);
1474     if (error) {
1475         return error;
1476     }
1477     miniflow_init(&miniflow, &match.flow);
1478
1479     ovs_mutex_lock(&dp->flow_mutex);
1480     netdev_flow = dp_netdev_lookup_flow(dp, &miniflow);
1481     if (!netdev_flow) {
1482         if (put->flags & DPIF_FP_CREATE) {
1483             if (cmap_count(&dp->flow_table) < MAX_FLOWS) {
1484                 if (put->stats) {
1485                     memset(put->stats, 0, sizeof *put->stats);
1486                 }
1487                 error = dp_netdev_flow_add(dp, &match, put->actions,
1488                                            put->actions_len);
1489             } else {
1490                 error = EFBIG;
1491             }
1492         } else {
1493             error = ENOENT;
1494         }
1495     } else {
1496         if (put->flags & DPIF_FP_MODIFY
1497             && flow_equal(&match.flow, &netdev_flow->flow)) {
1498             struct dp_netdev_actions *new_actions;
1499             struct dp_netdev_actions *old_actions;
1500
1501             new_actions = dp_netdev_actions_create(put->actions,
1502                                                    put->actions_len);
1503
1504             old_actions = dp_netdev_flow_get_actions(netdev_flow);
1505             ovsrcu_set(&netdev_flow->actions, new_actions);
1506
1507             if (put->stats) {
1508                 get_dpif_flow_stats(netdev_flow, put->stats);
1509             }
1510             if (put->flags & DPIF_FP_ZERO_STATS) {
1511                 clear_stats(netdev_flow);
1512             }
1513
1514             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
1515         } else if (put->flags & DPIF_FP_CREATE) {
1516             error = EEXIST;
1517         } else {
1518             /* Overlapping flow. */
1519             error = EINVAL;
1520         }
1521     }
1522     ovs_mutex_unlock(&dp->flow_mutex);
1523     miniflow_destroy(&miniflow);
1524
1525     return error;
1526 }
1527
1528 static int
1529 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1530 {
1531     struct dp_netdev *dp = get_dp_netdev(dpif);
1532     struct dp_netdev_flow *netdev_flow;
1533     struct flow key;
1534     int error;
1535
1536     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1537     if (error) {
1538         return error;
1539     }
1540
1541     ovs_mutex_lock(&dp->flow_mutex);
1542     netdev_flow = dp_netdev_find_flow(dp, &key);
1543     if (netdev_flow) {
1544         if (del->stats) {
1545             get_dpif_flow_stats(netdev_flow, del->stats);
1546         }
1547         dp_netdev_remove_flow(dp, netdev_flow);
1548     } else {
1549         error = ENOENT;
1550     }
1551     ovs_mutex_unlock(&dp->flow_mutex);
1552
1553     return error;
1554 }
1555
1556 struct dpif_netdev_flow_dump {
1557     struct dpif_flow_dump up;
1558     struct cmap_position pos;
1559     int status;
1560     struct ovs_mutex mutex;
1561 };
1562
1563 static struct dpif_netdev_flow_dump *
1564 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
1565 {
1566     return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
1567 }
1568
1569 static struct dpif_flow_dump *
1570 dpif_netdev_flow_dump_create(const struct dpif *dpif_)
1571 {
1572     struct dpif_netdev_flow_dump *dump;
1573
1574     dump = xmalloc(sizeof *dump);
1575     dpif_flow_dump_init(&dump->up, dpif_);
1576     memset(&dump->pos, 0, sizeof dump->pos);
1577     dump->status = 0;
1578     ovs_mutex_init(&dump->mutex);
1579
1580     return &dump->up;
1581 }
1582
1583 static int
1584 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
1585 {
1586     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1587
1588     ovs_mutex_destroy(&dump->mutex);
1589     free(dump);
1590     return 0;
1591 }
1592
1593 struct dpif_netdev_flow_dump_thread {
1594     struct dpif_flow_dump_thread up;
1595     struct dpif_netdev_flow_dump *dump;
1596     struct odputil_keybuf keybuf[FLOW_DUMP_MAX_BATCH];
1597     struct odputil_keybuf maskbuf[FLOW_DUMP_MAX_BATCH];
1598 };
1599
1600 static struct dpif_netdev_flow_dump_thread *
1601 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1602 {
1603     return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
1604 }
1605
1606 static struct dpif_flow_dump_thread *
1607 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1608 {
1609     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1610     struct dpif_netdev_flow_dump_thread *thread;
1611
1612     thread = xmalloc(sizeof *thread);
1613     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1614     thread->dump = dump;
1615     return &thread->up;
1616 }
1617
1618 static void
1619 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1620 {
1621     struct dpif_netdev_flow_dump_thread *thread
1622         = dpif_netdev_flow_dump_thread_cast(thread_);
1623
1624     free(thread);
1625 }
1626
1627 static int
1628 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1629                            struct dpif_flow *flows, int max_flows)
1630 {
1631     struct dpif_netdev_flow_dump_thread *thread
1632         = dpif_netdev_flow_dump_thread_cast(thread_);
1633     struct dpif_netdev_flow_dump *dump = thread->dump;
1634     struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
1635     struct dp_netdev_flow *netdev_flows[FLOW_DUMP_MAX_BATCH];
1636     struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
1637     int n_flows = 0;
1638     int i;
1639
1640     ovs_mutex_lock(&dump->mutex);
1641     if (!dump->status) {
1642         for (n_flows = 0; n_flows < MIN(max_flows, FLOW_DUMP_MAX_BATCH);
1643              n_flows++) {
1644             struct cmap_node *node;
1645
1646             node = cmap_next_position(&dp->flow_table, &dump->pos);
1647             if (!node) {
1648                 dump->status = EOF;
1649                 break;
1650             }
1651             netdev_flows[n_flows] = CONTAINER_OF(node, struct dp_netdev_flow,
1652                                                  node);
1653         }
1654     }
1655     ovs_mutex_unlock(&dump->mutex);
1656
1657     for (i = 0; i < n_flows; i++) {
1658         struct odputil_keybuf *maskbuf = &thread->maskbuf[i];
1659         struct odputil_keybuf *keybuf = &thread->keybuf[i];
1660         struct dp_netdev_flow *netdev_flow = netdev_flows[i];
1661         struct dpif_flow *f = &flows[i];
1662         struct dp_netdev_actions *dp_actions;
1663         struct flow_wildcards wc;
1664         struct ofpbuf buf;
1665
1666         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1667
1668         /* Key. */
1669         ofpbuf_use_stack(&buf, keybuf, sizeof *keybuf);
1670         odp_flow_key_from_flow(&buf, &netdev_flow->flow, &wc.masks,
1671                                netdev_flow->flow.in_port.odp_port, true);
1672         f->key = ofpbuf_data(&buf);
1673         f->key_len = ofpbuf_size(&buf);
1674
1675         /* Mask. */
1676         ofpbuf_use_stack(&buf, maskbuf, sizeof *maskbuf);
1677         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1678                                odp_to_u32(wc.masks.in_port.odp_port),
1679                                SIZE_MAX, true);
1680         f->mask = ofpbuf_data(&buf);
1681         f->mask_len = ofpbuf_size(&buf);
1682
1683         /* Actions. */
1684         dp_actions = dp_netdev_flow_get_actions(netdev_flow);
1685         f->actions = dp_actions->actions;
1686         f->actions_len = dp_actions->size;
1687
1688         /* Stats. */
1689         get_dpif_flow_stats(netdev_flow, &f->stats);
1690     }
1691
1692     return n_flows;
1693 }
1694
1695 static int
1696 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1697 {
1698     struct dp_netdev *dp = get_dp_netdev(dpif);
1699     struct dpif_packet packet, *pp;
1700     struct pkt_metadata *md = &execute->md;
1701
1702     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
1703         ofpbuf_size(execute->packet) > UINT16_MAX) {
1704         return EINVAL;
1705     }
1706
1707     packet.ofpbuf = *execute->packet;
1708     pp = &packet;
1709
1710     ovs_mutex_lock(&dp->emc_mutex);
1711     dp_netdev_execute_actions(dp, &pp, 1, false, md,
1712                               &dp->flow_cache, execute->actions,
1713                               execute->actions_len);
1714     ovs_mutex_unlock(&dp->emc_mutex);
1715
1716     /* Even though may_steal is set to false, some actions could modify or
1717      * reallocate the ofpbuf memory. We need to pass those changes to the
1718      * caller */
1719     *execute->packet = packet.ofpbuf;
1720
1721     return 0;
1722 }
1723
1724 static void
1725 dpif_netdev_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1726 {
1727     size_t i;
1728
1729     for (i = 0; i < n_ops; i++) {
1730         struct dpif_op *op = ops[i];
1731
1732         switch (op->type) {
1733         case DPIF_OP_FLOW_PUT:
1734             op->error = dpif_netdev_flow_put(dpif, &op->u.flow_put);
1735             break;
1736
1737         case DPIF_OP_FLOW_DEL:
1738             op->error = dpif_netdev_flow_del(dpif, &op->u.flow_del);
1739             break;
1740
1741         case DPIF_OP_EXECUTE:
1742             op->error = dpif_netdev_execute(dpif, &op->u.execute);
1743             break;
1744
1745         case DPIF_OP_FLOW_GET:
1746             op->error = dpif_netdev_flow_get(dpif, &op->u.flow_get);
1747             break;
1748         }
1749     }
1750 }
1751
1752 static int
1753 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1754                               uint32_t queue_id, uint32_t *priority)
1755 {
1756     *priority = queue_id;
1757     return 0;
1758 }
1759
1760 \f
1761 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1762  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1763  * 'ofpacts'. */
1764 struct dp_netdev_actions *
1765 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1766 {
1767     struct dp_netdev_actions *netdev_actions;
1768
1769     netdev_actions = xmalloc(sizeof *netdev_actions);
1770     netdev_actions->actions = xmemdup(actions, size);
1771     netdev_actions->size = size;
1772
1773     return netdev_actions;
1774 }
1775
1776 struct dp_netdev_actions *
1777 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
1778 {
1779     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
1780 }
1781
1782 static void
1783 dp_netdev_actions_free(struct dp_netdev_actions *actions)
1784 {
1785     free(actions->actions);
1786     free(actions);
1787 }
1788 \f
1789
1790 static void
1791 dp_netdev_process_rxq_port(struct dp_netdev *dp,
1792                            struct emc_cache *flow_cache,
1793                            struct dp_netdev_port *port,
1794                            struct netdev_rxq *rxq)
1795 {
1796     struct dpif_packet *packets[NETDEV_MAX_RX_BATCH];
1797     int error, cnt;
1798
1799     error = netdev_rxq_recv(rxq, packets, &cnt);
1800     if (!error) {
1801         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
1802
1803         *recirc_depth_get() = 0;
1804         dp_netdev_input(dp, flow_cache, packets, cnt, &md);
1805     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1806         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1807
1808         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1809                     netdev_get_name(port->netdev), ovs_strerror(error));
1810     }
1811 }
1812
1813 static void
1814 dpif_netdev_run(struct dpif *dpif)
1815 {
1816     struct dp_netdev_port *port;
1817     struct dp_netdev *dp = get_dp_netdev(dpif);
1818
1819     ovs_mutex_lock(&dp->emc_mutex);
1820     CMAP_FOR_EACH (port, node, &dp->ports) {
1821         if (!netdev_is_pmd(port->netdev)) {
1822             int i;
1823
1824             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1825                 dp_netdev_process_rxq_port(dp, &dp->flow_cache, port,
1826                                            port->rxq[i]);
1827             }
1828         }
1829     }
1830     ovs_mutex_unlock(&dp->emc_mutex);
1831 }
1832
1833 static void
1834 dpif_netdev_wait(struct dpif *dpif)
1835 {
1836     struct dp_netdev_port *port;
1837     struct dp_netdev *dp = get_dp_netdev(dpif);
1838
1839     ovs_mutex_lock(&dp_netdev_mutex);
1840     CMAP_FOR_EACH (port, node, &dp->ports) {
1841         if (!netdev_is_pmd(port->netdev)) {
1842             int i;
1843
1844             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1845                 netdev_rxq_wait(port->rxq[i]);
1846             }
1847         }
1848     }
1849     ovs_mutex_unlock(&dp_netdev_mutex);
1850 }
1851
1852 struct rxq_poll {
1853     struct dp_netdev_port *port;
1854     struct netdev_rxq *rx;
1855 };
1856
1857 static int
1858 pmd_load_queues(struct pmd_thread *f,
1859                 struct rxq_poll **ppoll_list, int poll_cnt)
1860 {
1861     struct dp_netdev *dp = f->dp;
1862     struct rxq_poll *poll_list = *ppoll_list;
1863     struct dp_netdev_port *port;
1864     int id = f->id;
1865     int index;
1866     int i;
1867
1868     /* Simple scheduler for netdev rx polling. */
1869     for (i = 0; i < poll_cnt; i++) {
1870          port_unref(poll_list[i].port);
1871     }
1872
1873     poll_cnt = 0;
1874     index = 0;
1875
1876     CMAP_FOR_EACH (port, node, &f->dp->ports) {
1877         /* Calls port_try_ref() to prevent the main thread
1878          * from deleting the port. */
1879         if (port_try_ref(port)) {
1880             if (netdev_is_pmd(port->netdev)) {
1881                 int i;
1882
1883                 for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1884                     if ((index % dp->n_pmd_threads) == id) {
1885                         poll_list = xrealloc(poll_list,
1886                                         sizeof *poll_list * (poll_cnt + 1));
1887
1888                         port_ref(port);
1889                         poll_list[poll_cnt].port = port;
1890                         poll_list[poll_cnt].rx = port->rxq[i];
1891                         poll_cnt++;
1892                     }
1893                     index++;
1894                 }
1895             }
1896             /* Unrefs the port_try_ref(). */
1897             port_unref(port);
1898         }
1899     }
1900
1901     *ppoll_list = poll_list;
1902     return poll_cnt;
1903 }
1904
1905 static void *
1906 pmd_thread_main(void *f_)
1907 {
1908     struct pmd_thread *f = f_;
1909     struct dp_netdev *dp = f->dp;
1910     unsigned int lc = 0;
1911     struct rxq_poll *poll_list;
1912     unsigned int port_seq = PMD_INITIAL_SEQ;
1913     int poll_cnt;
1914     int i;
1915
1916     poll_cnt = 0;
1917     poll_list = NULL;
1918
1919     pmd_thread_setaffinity_cpu(f->id);
1920 reload:
1921     emc_cache_init(&f->flow_cache);
1922     poll_cnt = pmd_load_queues(f, &poll_list, poll_cnt);
1923
1924     for (;;) {
1925         int i;
1926
1927         for (i = 0; i < poll_cnt; i++) {
1928             dp_netdev_process_rxq_port(dp, &f->flow_cache, poll_list[i].port,
1929                                        poll_list[i].rx);
1930         }
1931
1932         if (lc++ > 1024) {
1933             unsigned int seq;
1934
1935             lc = 0;
1936
1937             ovsrcu_quiesce();
1938
1939             atomic_read_relaxed(&f->change_seq, &seq);
1940             if (seq != port_seq) {
1941                 port_seq = seq;
1942                 break;
1943             }
1944         }
1945     }
1946
1947     emc_cache_uninit(&f->flow_cache);
1948
1949     if (!latch_is_set(&f->dp->exit_latch)){
1950         goto reload;
1951     }
1952
1953     for (i = 0; i < poll_cnt; i++) {
1954          port_unref(poll_list[i].port);
1955     }
1956
1957     free(poll_list);
1958     return NULL;
1959 }
1960
1961 static void
1962 dp_netdev_disable_upcall(struct dp_netdev *dp)
1963     OVS_ACQUIRES(dp->upcall_rwlock)
1964 {
1965     fat_rwlock_wrlock(&dp->upcall_rwlock);
1966 }
1967
1968 static void
1969 dpif_netdev_disable_upcall(struct dpif *dpif)
1970     OVS_NO_THREAD_SAFETY_ANALYSIS
1971 {
1972     struct dp_netdev *dp = get_dp_netdev(dpif);
1973     dp_netdev_disable_upcall(dp);
1974 }
1975
1976 static void
1977 dp_netdev_enable_upcall(struct dp_netdev *dp)
1978     OVS_RELEASES(dp->upcall_rwlock)
1979 {
1980     fat_rwlock_unlock(&dp->upcall_rwlock);
1981 }
1982
1983 static void
1984 dpif_netdev_enable_upcall(struct dpif *dpif)
1985     OVS_NO_THREAD_SAFETY_ANALYSIS
1986 {
1987     struct dp_netdev *dp = get_dp_netdev(dpif);
1988     dp_netdev_enable_upcall(dp);
1989 }
1990
1991 static void
1992 dp_netdev_set_pmd_threads(struct dp_netdev *dp, int n)
1993 {
1994     int i;
1995
1996     if (n == dp->n_pmd_threads) {
1997         return;
1998     }
1999
2000     /* Stop existing threads. */
2001     latch_set(&dp->exit_latch);
2002     dp_netdev_reload_pmd_threads(dp);
2003     for (i = 0; i < dp->n_pmd_threads; i++) {
2004         struct pmd_thread *f = &dp->pmd_threads[i];
2005
2006         xpthread_join(f->thread, NULL);
2007     }
2008     latch_poll(&dp->exit_latch);
2009     free(dp->pmd_threads);
2010
2011     /* Start new threads. */
2012     dp->pmd_threads = xmalloc(n * sizeof *dp->pmd_threads);
2013     dp->n_pmd_threads = n;
2014
2015     for (i = 0; i < n; i++) {
2016         struct pmd_thread *f = &dp->pmd_threads[i];
2017
2018         f->dp = dp;
2019         f->id = i;
2020         atomic_init(&f->change_seq, PMD_INITIAL_SEQ);
2021
2022         /* Each thread will distribute all devices rx-queues among
2023          * themselves. */
2024         f->thread = ovs_thread_create("pmd", pmd_thread_main, f);
2025     }
2026 }
2027
2028 \f
2029 static void *
2030 dp_netdev_flow_stats_new_cb(void)
2031 {
2032     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2033     ovs_mutex_init(&bucket->mutex);
2034     return bucket;
2035 }
2036
2037 static void
2038 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
2039                     int cnt, int size,
2040                     uint16_t tcp_flags)
2041 {
2042     long long int now = time_msec();
2043     struct dp_netdev_flow_stats *bucket;
2044
2045     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
2046                                         dp_netdev_flow_stats_new_cb);
2047
2048     ovs_mutex_lock(&bucket->mutex);
2049     bucket->used = MAX(now, bucket->used);
2050     bucket->packet_count += cnt;
2051     bucket->byte_count += size;
2052     bucket->tcp_flags |= tcp_flags;
2053     ovs_mutex_unlock(&bucket->mutex);
2054 }
2055
2056 static void *
2057 dp_netdev_stats_new_cb(void)
2058 {
2059     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2060     ovs_mutex_init(&bucket->mutex);
2061     return bucket;
2062 }
2063
2064 static void
2065 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type, int cnt)
2066 {
2067     struct dp_netdev_stats *bucket;
2068
2069     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
2070     ovs_mutex_lock(&bucket->mutex);
2071     bucket->n[type] += cnt;
2072     ovs_mutex_unlock(&bucket->mutex);
2073 }
2074
2075 static int
2076 dp_netdev_upcall(struct dp_netdev *dp, struct dpif_packet *packet_,
2077                  struct flow *flow, struct flow_wildcards *wc,
2078                  enum dpif_upcall_type type, const struct nlattr *userdata,
2079                  struct ofpbuf *actions, struct ofpbuf *put_actions)
2080 {
2081     struct ofpbuf *packet = &packet_->ofpbuf;
2082
2083     if (type == DPIF_UC_MISS) {
2084         dp_netdev_count_packet(dp, DP_STAT_MISS, 1);
2085     }
2086
2087     if (OVS_UNLIKELY(!dp->upcall_cb)) {
2088         return ENODEV;
2089     }
2090
2091     if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
2092         struct ds ds = DS_EMPTY_INITIALIZER;
2093         struct ofpbuf key;
2094         char *packet_str;
2095
2096         ofpbuf_init(&key, 0);
2097         odp_flow_key_from_flow(&key, flow, &wc->masks, flow->in_port.odp_port,
2098                                true);
2099
2100         packet_str = ofp_packet_to_string(ofpbuf_data(packet),
2101                                           ofpbuf_size(packet));
2102
2103         odp_flow_key_format(ofpbuf_data(&key), ofpbuf_size(&key), &ds);
2104
2105         VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
2106                  dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
2107
2108         ofpbuf_uninit(&key);
2109         free(packet_str);
2110         ds_destroy(&ds);
2111     }
2112
2113     return dp->upcall_cb(packet, flow, type, userdata, actions, wc,
2114                          put_actions, dp->upcall_aux);
2115 }
2116
2117 static inline uint32_t
2118 dpif_netdev_packet_get_dp_hash(struct dpif_packet *packet,
2119                                const struct miniflow *mf)
2120 {
2121     uint32_t hash;
2122
2123     hash = dpif_packet_get_dp_hash(packet);
2124     if (OVS_UNLIKELY(!hash)) {
2125         hash = miniflow_hash_5tuple(mf, 0);
2126         dpif_packet_set_dp_hash(packet, hash);
2127     }
2128     return hash;
2129 }
2130
2131 struct packet_batch {
2132     unsigned int packet_count;
2133     unsigned int byte_count;
2134     uint16_t tcp_flags;
2135
2136     struct dp_netdev_flow *flow;
2137
2138     struct dpif_packet *packets[NETDEV_MAX_RX_BATCH];
2139     struct pkt_metadata md;
2140 };
2141
2142 static inline void
2143 packet_batch_update(struct packet_batch *batch, struct dpif_packet *packet,
2144                     const struct miniflow *mf)
2145 {
2146     batch->tcp_flags |= miniflow_get_tcp_flags(mf);
2147     batch->packets[batch->packet_count++] = packet;
2148     batch->byte_count += ofpbuf_size(&packet->ofpbuf);
2149 }
2150
2151 static inline void
2152 packet_batch_init(struct packet_batch *batch, struct dp_netdev_flow *flow,
2153                   struct pkt_metadata *md)
2154 {
2155     batch->flow = flow;
2156     batch->md = *md;
2157
2158     batch->packet_count = 0;
2159     batch->byte_count = 0;
2160     batch->tcp_flags = 0;
2161 }
2162
2163 static inline void
2164 packet_batch_execute(struct packet_batch *batch, struct dp_netdev *dp,
2165                      struct emc_cache *flow_cache)
2166 {
2167     struct dp_netdev_actions *actions;
2168     struct dp_netdev_flow *flow = batch->flow;
2169
2170     dp_netdev_flow_used(batch->flow, batch->packet_count, batch->byte_count,
2171                         batch->tcp_flags);
2172
2173     actions = dp_netdev_flow_get_actions(flow);
2174
2175     dp_netdev_execute_actions(dp, batch->packets, batch->packet_count, true,
2176                               &batch->md, flow_cache,
2177                               actions->actions, actions->size);
2178
2179     dp_netdev_count_packet(dp, DP_STAT_HIT, batch->packet_count);
2180 }
2181
2182 static inline bool
2183 dp_netdev_queue_batches(struct dpif_packet *pkt, struct pkt_metadata *md,
2184                         struct dp_netdev_flow *flow, const struct miniflow *mf,
2185                         struct packet_batch *batches, size_t *n_batches,
2186                         size_t max_batches)
2187 {
2188     struct packet_batch *batch = NULL;
2189     int j;
2190
2191     if (OVS_UNLIKELY(!flow)) {
2192         return false;
2193     }
2194     /* XXX: This O(n^2) algortihm makes sense if we're operating under the
2195      * assumption that the number of distinct flows (and therefore the
2196      * number of distinct batches) is quite small.  If this turns out not
2197      * to be the case, it may make sense to pre sort based on the
2198      * netdev_flow pointer.  That done we can get the appropriate batching
2199      * in O(n * log(n)) instead. */
2200     for (j = *n_batches - 1; j >= 0; j--) {
2201         if (batches[j].flow == flow) {
2202             batch = &batches[j];
2203             packet_batch_update(batch, pkt, mf);
2204             return true;
2205         }
2206     }
2207     if (OVS_UNLIKELY(*n_batches >= max_batches)) {
2208         return false;
2209     }
2210
2211     batch = &batches[(*n_batches)++];
2212     packet_batch_init(batch, flow, md);
2213     packet_batch_update(batch, pkt, mf);
2214     return true;
2215 }
2216
2217 static inline void
2218 dpif_packet_swap(struct dpif_packet **a, struct dpif_packet **b)
2219 {
2220     struct dpif_packet *tmp = *a;
2221     *a = *b;
2222     *b = tmp;
2223 }
2224
2225 /* Try to process all ('cnt') the 'packets' using only the exact match cache
2226  * 'flow_cache'. If a flow is not found for a packet 'packets[i]', or if there
2227  * is no matching batch for a packet's flow, the miniflow is copied into 'keys'
2228  * and the packet pointer is moved at the beginning of the 'packets' array.
2229  *
2230  * The function returns the number of packets that needs to be processed in the
2231  * 'packets' array (they have been moved to the beginning of the vector).
2232  */
2233 static inline size_t
2234 emc_processing(struct dp_netdev *dp, struct emc_cache *flow_cache,
2235                struct dpif_packet **packets, size_t cnt,
2236                struct pkt_metadata *md, struct netdev_flow_key *keys)
2237 {
2238     struct netdev_flow_key key;
2239     struct packet_batch batches[4];
2240     size_t n_batches, i;
2241     size_t notfound_cnt = 0;
2242
2243     n_batches = 0;
2244     miniflow_initialize(&key.flow, key.buf);
2245     for (i = 0; i < cnt; i++) {
2246         struct dp_netdev_flow *flow;
2247         uint32_t hash;
2248
2249         if (OVS_UNLIKELY(ofpbuf_size(&packets[i]->ofpbuf) < ETH_HEADER_LEN)) {
2250             dpif_packet_delete(packets[i]);
2251             continue;
2252         }
2253
2254         miniflow_extract(&packets[i]->ofpbuf, md, &key.flow);
2255
2256         hash = dpif_netdev_packet_get_dp_hash(packets[i], &key.flow);
2257
2258         flow = emc_lookup(flow_cache, &key.flow, hash);
2259         if (OVS_UNLIKELY(!dp_netdev_queue_batches(packets[i], md,
2260                                                   flow,  &key.flow,
2261                                                   batches, &n_batches,
2262                                                   ARRAY_SIZE(batches)))) {
2263             if (i != notfound_cnt) {
2264                 dpif_packet_swap(&packets[i], &packets[notfound_cnt]);
2265             }
2266
2267             keys[notfound_cnt++] = key;
2268         }
2269     }
2270
2271     for (i = 0; i < n_batches; i++) {
2272         packet_batch_execute(&batches[i], dp, flow_cache);
2273     }
2274
2275     return notfound_cnt;
2276 }
2277
2278 static inline void
2279 fast_path_processing(struct dp_netdev *dp, struct emc_cache *flow_cache,
2280                      struct dpif_packet **packets, size_t cnt,
2281                      struct pkt_metadata *md, struct netdev_flow_key *keys)
2282 {
2283 #if !defined(__CHECKER__) && !defined(_WIN32)
2284     const size_t PKT_ARRAY_SIZE = cnt;
2285 #else
2286     /* Sparse or MSVC doesn't like variable length array. */
2287     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2288 #endif
2289     struct packet_batch batches[PKT_ARRAY_SIZE];
2290     const struct miniflow *mfs[PKT_ARRAY_SIZE]; /* NULL at bad packets. */
2291     struct cls_rule *rules[PKT_ARRAY_SIZE];
2292     size_t n_batches, i;
2293     bool any_miss;
2294
2295     for (i = 0; i < cnt; i++) {
2296         mfs[i] = &keys[i].flow;
2297     }
2298     any_miss = !classifier_lookup_miniflow_batch(&dp->cls, mfs, rules, cnt);
2299     if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
2300         uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
2301         struct ofpbuf actions, put_actions;
2302         struct match match;
2303
2304         ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
2305         ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
2306
2307         for (i = 0; i < cnt; i++) {
2308             const struct dp_netdev_flow *netdev_flow;
2309             struct ofpbuf *add_actions;
2310             int error;
2311
2312             if (OVS_LIKELY(rules[i] || !mfs[i])) {
2313                 continue;
2314             }
2315
2316             /* It's possible that an earlier slow path execution installed
2317              * the rule this flow needs.  In this case, it's a lot cheaper
2318              * to catch it here than execute a miss. */
2319             netdev_flow = dp_netdev_lookup_flow(dp, mfs[i]);
2320             if (netdev_flow) {
2321                 rules[i] = CONST_CAST(struct cls_rule *, &netdev_flow->cr);
2322                 continue;
2323             }
2324
2325             miniflow_expand(mfs[i], &match.flow);
2326
2327             ofpbuf_clear(&actions);
2328             ofpbuf_clear(&put_actions);
2329
2330             error = dp_netdev_upcall(dp, packets[i], &match.flow, &match.wc,
2331                                       DPIF_UC_MISS, NULL, &actions,
2332                                       &put_actions);
2333             if (OVS_UNLIKELY(error && error != ENOSPC)) {
2334                 continue;
2335             }
2336
2337             /* We can't allow the packet batching in the next loop to execute
2338              * the actions.  Otherwise, if there are any slow path actions,
2339              * we'll send the packet up twice. */
2340             dp_netdev_execute_actions(dp, &packets[i], 1, false, md,
2341                                       flow_cache, ofpbuf_data(&actions),
2342                                       ofpbuf_size(&actions));
2343
2344             add_actions = ofpbuf_size(&put_actions)
2345                 ? &put_actions
2346                 : &actions;
2347
2348             ovs_mutex_lock(&dp->flow_mutex);
2349             /* XXX: There's a brief race where this flow could have already
2350              * been installed since we last did the flow lookup.  This could be
2351              * solved by moving the mutex lock outside the loop, but that's an
2352              * awful long time to be locking everyone out of making flow
2353              * installs.  If we move to a per-core classifier, it would be
2354              * reasonable. */
2355             if (OVS_LIKELY(error != ENOSPC)
2356                 && !dp_netdev_lookup_flow(dp, mfs[i])) {
2357                 dp_netdev_flow_add(dp, &match, ofpbuf_data(add_actions),
2358                                    ofpbuf_size(add_actions));
2359             }
2360             ovs_mutex_unlock(&dp->flow_mutex);
2361         }
2362
2363         ofpbuf_uninit(&actions);
2364         ofpbuf_uninit(&put_actions);
2365         fat_rwlock_unlock(&dp->upcall_rwlock);
2366     }
2367
2368     n_batches = 0;
2369     for (i = 0; i < cnt; i++) {
2370         struct dpif_packet *packet = packets[i];
2371         struct dp_netdev_flow *flow;
2372
2373         if (OVS_UNLIKELY(!rules[i] || !mfs[i])) {
2374             continue;
2375         }
2376
2377         flow = dp_netdev_flow_cast(rules[i]);
2378         emc_insert(flow_cache, mfs[i], dpif_packet_get_dp_hash(packet), flow);
2379         dp_netdev_queue_batches(packet, md, flow, mfs[i], batches, &n_batches,
2380                                 ARRAY_SIZE(batches));
2381     }
2382
2383     for (i = 0; i < n_batches; i++) {
2384         packet_batch_execute(&batches[i], dp, flow_cache);
2385     }
2386 }
2387
2388 static void
2389 dp_netdev_input(struct dp_netdev *dp, struct emc_cache *flow_cache,
2390                 struct dpif_packet **packets, int cnt, struct pkt_metadata *md)
2391 {
2392 #if !defined(__CHECKER__) && !defined(_WIN32)
2393     const size_t PKT_ARRAY_SIZE = cnt;
2394 #else
2395     /* Sparse or MSVC doesn't like variable length array. */
2396     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2397 #endif
2398     struct netdev_flow_key keys[PKT_ARRAY_SIZE];
2399     size_t newcnt;
2400
2401     newcnt = emc_processing(dp, flow_cache, packets, cnt, md, keys);
2402     if (OVS_UNLIKELY(newcnt)) {
2403         fast_path_processing(dp, flow_cache, packets, newcnt, md, keys);
2404     }
2405 }
2406
2407 struct dp_netdev_execute_aux {
2408     struct dp_netdev *dp;
2409     struct emc_cache *flow_cache;
2410 };
2411
2412 static void
2413 dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
2414                                void *aux)
2415 {
2416     struct dp_netdev *dp = get_dp_netdev(dpif);
2417     dp->upcall_aux = aux;
2418     dp->upcall_cb = cb;
2419 }
2420
2421 static void
2422 dp_execute_cb(void *aux_, struct dpif_packet **packets, int cnt,
2423               struct pkt_metadata *md,
2424               const struct nlattr *a, bool may_steal)
2425     OVS_NO_THREAD_SAFETY_ANALYSIS
2426 {
2427     struct dp_netdev_execute_aux *aux = aux_;
2428     uint32_t *depth = recirc_depth_get();
2429     struct dp_netdev *dp = aux->dp;
2430     int type = nl_attr_type(a);
2431     struct dp_netdev_port *p;
2432     int i;
2433
2434     switch ((enum ovs_action_attr)type) {
2435     case OVS_ACTION_ATTR_OUTPUT:
2436         p = dp_netdev_lookup_port(dp, u32_to_odp(nl_attr_get_u32(a)));
2437         if (OVS_LIKELY(p)) {
2438             netdev_send(p->netdev, NETDEV_QID_NONE, packets, cnt, may_steal);
2439         } else if (may_steal) {
2440             for (i = 0; i < cnt; i++) {
2441                 dpif_packet_delete(packets[i]);
2442             }
2443         }
2444         break;
2445
2446     case OVS_ACTION_ATTR_USERSPACE:
2447         if (!fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
2448             const struct nlattr *userdata;
2449             struct ofpbuf actions;
2450             struct flow flow;
2451
2452             userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2453             ofpbuf_init(&actions, 0);
2454
2455             for (i = 0; i < cnt; i++) {
2456                 int error;
2457
2458                 ofpbuf_clear(&actions);
2459
2460                 flow_extract(&packets[i]->ofpbuf, md, &flow);
2461                 error = dp_netdev_upcall(dp, packets[i], &flow, NULL,
2462                                          DPIF_UC_ACTION, userdata, &actions,
2463                                          NULL);
2464                 if (!error || error == ENOSPC) {
2465                     dp_netdev_execute_actions(dp, &packets[i], 1, false, md,
2466                                               aux->flow_cache,
2467                                               ofpbuf_data(&actions),
2468                                               ofpbuf_size(&actions));
2469                 }
2470
2471                 if (may_steal) {
2472                     dpif_packet_delete(packets[i]);
2473                 }
2474             }
2475             ofpbuf_uninit(&actions);
2476             fat_rwlock_unlock(&dp->upcall_rwlock);
2477         }
2478
2479         break;
2480
2481     case OVS_ACTION_ATTR_HASH: {
2482         const struct ovs_action_hash *hash_act;
2483         uint32_t hash;
2484
2485         hash_act = nl_attr_get(a);
2486
2487         for (i = 0; i < cnt; i++) {
2488
2489             if (hash_act->hash_alg == OVS_HASH_ALG_L4) {
2490                 /* Hash need not be symmetric, nor does it need to include
2491                  * L2 fields. */
2492                 hash = hash_2words(dpif_packet_get_dp_hash(packets[i]),
2493                                    hash_act->hash_basis);
2494             } else {
2495                 VLOG_WARN("Unknown hash algorithm specified "
2496                           "for the hash action.");
2497                 hash = 2;
2498             }
2499
2500             if (!hash) {
2501                 hash = 1; /* 0 is not valid */
2502             }
2503
2504             if (i == 0) {
2505                 md->dp_hash = hash;
2506             }
2507             dpif_packet_set_dp_hash(packets[i], hash);
2508         }
2509         break;
2510     }
2511
2512     case OVS_ACTION_ATTR_RECIRC:
2513         if (*depth < MAX_RECIRC_DEPTH) {
2514
2515             (*depth)++;
2516             for (i = 0; i < cnt; i++) {
2517                 struct dpif_packet *recirc_pkt;
2518                 struct pkt_metadata recirc_md = *md;
2519
2520                 recirc_pkt = (may_steal) ? packets[i]
2521                                     : dpif_packet_clone(packets[i]);
2522
2523                 recirc_md.recirc_id = nl_attr_get_u32(a);
2524
2525                 /* Hash is private to each packet */
2526                 recirc_md.dp_hash = dpif_packet_get_dp_hash(packets[i]);
2527
2528                 dp_netdev_input(dp, aux->flow_cache, &recirc_pkt, 1,
2529                                 &recirc_md);
2530             }
2531             (*depth)--;
2532
2533             break;
2534         } else {
2535             VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2536             if (may_steal) {
2537                 for (i = 0; i < cnt; i++) {
2538                     dpif_packet_delete(packets[i]);
2539                 }
2540             }
2541         }
2542         break;
2543
2544     case OVS_ACTION_ATTR_PUSH_VLAN:
2545     case OVS_ACTION_ATTR_POP_VLAN:
2546     case OVS_ACTION_ATTR_PUSH_MPLS:
2547     case OVS_ACTION_ATTR_POP_MPLS:
2548     case OVS_ACTION_ATTR_SET:
2549     case OVS_ACTION_ATTR_SET_MASKED:
2550     case OVS_ACTION_ATTR_SAMPLE:
2551     case OVS_ACTION_ATTR_UNSPEC:
2552     case __OVS_ACTION_ATTR_MAX:
2553         OVS_NOT_REACHED();
2554     }
2555 }
2556
2557 static void
2558 dp_netdev_execute_actions(struct dp_netdev *dp,
2559                           struct dpif_packet **packets, int cnt,
2560                           bool may_steal, struct pkt_metadata *md,
2561                           struct emc_cache *flow_cache,
2562                           const struct nlattr *actions, size_t actions_len)
2563 {
2564     struct dp_netdev_execute_aux aux = {dp, flow_cache};
2565
2566     odp_execute_actions(&aux, packets, cnt, may_steal, md, actions,
2567                         actions_len, dp_execute_cb);
2568 }
2569
2570 const struct dpif_class dpif_netdev_class = {
2571     "netdev",
2572     dpif_netdev_enumerate,
2573     dpif_netdev_port_open_type,
2574     dpif_netdev_open,
2575     dpif_netdev_close,
2576     dpif_netdev_destroy,
2577     dpif_netdev_run,
2578     dpif_netdev_wait,
2579     dpif_netdev_get_stats,
2580     dpif_netdev_port_add,
2581     dpif_netdev_port_del,
2582     dpif_netdev_port_query_by_number,
2583     dpif_netdev_port_query_by_name,
2584     NULL,                       /* port_get_pid */
2585     dpif_netdev_port_dump_start,
2586     dpif_netdev_port_dump_next,
2587     dpif_netdev_port_dump_done,
2588     dpif_netdev_port_poll,
2589     dpif_netdev_port_poll_wait,
2590     dpif_netdev_flow_flush,
2591     dpif_netdev_flow_dump_create,
2592     dpif_netdev_flow_dump_destroy,
2593     dpif_netdev_flow_dump_thread_create,
2594     dpif_netdev_flow_dump_thread_destroy,
2595     dpif_netdev_flow_dump_next,
2596     dpif_netdev_operate,
2597     NULL,                       /* recv_set */
2598     NULL,                       /* handlers_set */
2599     dpif_netdev_queue_to_priority,
2600     NULL,                       /* recv */
2601     NULL,                       /* recv_wait */
2602     NULL,                       /* recv_purge */
2603     dpif_netdev_register_upcall_cb,
2604     dpif_netdev_enable_upcall,
2605     dpif_netdev_disable_upcall,
2606 };
2607
2608 static void
2609 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2610                               const char *argv[], void *aux OVS_UNUSED)
2611 {
2612     struct dp_netdev_port *old_port;
2613     struct dp_netdev_port *new_port;
2614     struct dp_netdev *dp;
2615     odp_port_t port_no;
2616
2617     ovs_mutex_lock(&dp_netdev_mutex);
2618     dp = shash_find_data(&dp_netdevs, argv[1]);
2619     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2620         ovs_mutex_unlock(&dp_netdev_mutex);
2621         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2622         return;
2623     }
2624     ovs_refcount_ref(&dp->ref_cnt);
2625     ovs_mutex_unlock(&dp_netdev_mutex);
2626
2627     ovs_mutex_lock(&dp->port_mutex);
2628     if (get_port_by_name(dp, argv[2], &old_port)) {
2629         unixctl_command_reply_error(conn, "unknown port");
2630         goto exit;
2631     }
2632
2633     port_no = u32_to_odp(atoi(argv[3]));
2634     if (!port_no || port_no == ODPP_NONE) {
2635         unixctl_command_reply_error(conn, "bad port number");
2636         goto exit;
2637     }
2638     if (dp_netdev_lookup_port(dp, port_no)) {
2639         unixctl_command_reply_error(conn, "port number already in use");
2640         goto exit;
2641     }
2642
2643     /* Remove old port. */
2644     cmap_remove(&dp->ports, &old_port->node, hash_port_no(old_port->port_no));
2645     ovsrcu_postpone(free, old_port);
2646
2647     /* Insert new port (cmap semantics mean we cannot re-insert 'old_port'). */
2648     new_port = xmemdup(old_port, sizeof *old_port);
2649     new_port->port_no = port_no;
2650     cmap_insert(&dp->ports, &new_port->node, hash_port_no(port_no));
2651
2652     seq_change(dp->port_seq);
2653     unixctl_command_reply(conn, NULL);
2654
2655 exit:
2656     ovs_mutex_unlock(&dp->port_mutex);
2657     dp_netdev_unref(dp);
2658 }
2659
2660 static void
2661 dpif_dummy_delete_port(struct unixctl_conn *conn, int argc OVS_UNUSED,
2662                        const char *argv[], void *aux OVS_UNUSED)
2663 {
2664     struct dp_netdev_port *port;
2665     struct dp_netdev *dp;
2666
2667     ovs_mutex_lock(&dp_netdev_mutex);
2668     dp = shash_find_data(&dp_netdevs, argv[1]);
2669     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2670         ovs_mutex_unlock(&dp_netdev_mutex);
2671         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2672         return;
2673     }
2674     ovs_refcount_ref(&dp->ref_cnt);
2675     ovs_mutex_unlock(&dp_netdev_mutex);
2676
2677     ovs_mutex_lock(&dp->port_mutex);
2678     if (get_port_by_name(dp, argv[2], &port)) {
2679         unixctl_command_reply_error(conn, "unknown port");
2680     } else if (port->port_no == ODPP_LOCAL) {
2681         unixctl_command_reply_error(conn, "can't delete local port");
2682     } else {
2683         do_del_port(dp, port);
2684         unixctl_command_reply(conn, NULL);
2685     }
2686     ovs_mutex_unlock(&dp->port_mutex);
2687
2688     dp_netdev_unref(dp);
2689 }
2690
2691 static void
2692 dpif_dummy_register__(const char *type)
2693 {
2694     struct dpif_class *class;
2695
2696     class = xmalloc(sizeof *class);
2697     *class = dpif_netdev_class;
2698     class->type = xstrdup(type);
2699     dp_register_provider(class);
2700 }
2701
2702 void
2703 dpif_dummy_register(bool override)
2704 {
2705     if (override) {
2706         struct sset types;
2707         const char *type;
2708
2709         sset_init(&types);
2710         dp_enumerate_types(&types);
2711         SSET_FOR_EACH (type, &types) {
2712             if (!dp_unregister_provider(type)) {
2713                 dpif_dummy_register__(type);
2714             }
2715         }
2716         sset_destroy(&types);
2717     }
2718
2719     dpif_dummy_register__("dummy");
2720
2721     unixctl_command_register("dpif-dummy/change-port-number",
2722                              "dp port new-number",
2723                              3, 3, dpif_dummy_change_port_number, NULL);
2724     unixctl_command_register("dpif-dummy/delete-port", "dp port",
2725                              2, 2, dpif_dummy_delete_port, NULL);
2726 }