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