dpif-netdev: Remove redundant hash action handling.
[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 "cmap.h"
35 #include "csum.h"
36 #include "dpif.h"
37 #include "dpif-provider.h"
38 #include "dummy.h"
39 #include "dynamic-string.h"
40 #include "fat-rwlock.h"
41 #include "flow.h"
42 #include "cmap.h"
43 #include "latch.h"
44 #include "list.h"
45 #include "match.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 "pvector.h"
61 #include "random.h"
62 #include "seq.h"
63 #include "shash.h"
64 #include "sset.h"
65 #include "timeval.h"
66 #include "tnl-arp-cache.h"
67 #include "unixctl.h"
68 #include "util.h"
69 #include "vlog.h"
70
71 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
72
73 #define FLOW_DUMP_MAX_BATCH 50
74 /* Use per thread recirc_depth to prevent recirculation loop. */
75 #define MAX_RECIRC_DEPTH 5
76 DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
77
78 /* Configuration parameters. */
79 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
80
81 /* Protects against changes to 'dp_netdevs'. */
82 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
83
84 /* Contains all 'struct dp_netdev's. */
85 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
86     = SHASH_INITIALIZER(&dp_netdevs);
87
88 static struct vlog_rate_limit upcall_rl = VLOG_RATE_LIMIT_INIT(600, 600);
89
90 /* Stores a miniflow with inline values */
91
92 struct netdev_flow_key {
93     uint32_t hash;       /* Hash function differs for different users. */
94     uint32_t len;        /* Length of the following miniflow (incl. map). */
95     struct miniflow mf;
96     uint32_t buf[FLOW_MAX_PACKET_U32S - MINI_N_INLINE];
97 };
98
99 /* Exact match cache for frequently used flows
100  *
101  * The cache uses a 32-bit hash of the packet (which can be the RSS hash) to
102  * search its entries for a miniflow that matches exactly the miniflow of the
103  * packet. It stores the 'dpcls_rule' (rule) that matches the miniflow.
104  *
105  * A cache entry holds a reference to its 'dp_netdev_flow'.
106  *
107  * A miniflow with a given hash can be in one of EM_FLOW_HASH_SEGS different
108  * entries. The 32-bit hash is split into EM_FLOW_HASH_SEGS values (each of
109  * them is EM_FLOW_HASH_SHIFT bits wide and the remainder is thrown away). Each
110  * value is the index of a cache entry where the miniflow could be.
111  *
112  *
113  * Thread-safety
114  * =============
115  *
116  * Each pmd_thread has its own private exact match cache.
117  * If dp_netdev_input is not called from a pmd thread, a mutex is used.
118  */
119
120 #define EM_FLOW_HASH_SHIFT 10
121 #define EM_FLOW_HASH_ENTRIES (1u << EM_FLOW_HASH_SHIFT)
122 #define EM_FLOW_HASH_MASK (EM_FLOW_HASH_ENTRIES - 1)
123 #define EM_FLOW_HASH_SEGS 2
124
125 struct emc_entry {
126     struct dp_netdev_flow *flow;
127     struct netdev_flow_key key;   /* key.hash used for emc hash value. */
128 };
129
130 struct emc_cache {
131     struct emc_entry entries[EM_FLOW_HASH_ENTRIES];
132     int sweep_idx;                /* For emc_cache_slow_sweep(). */
133 };
134
135 /* Iterate in the exact match cache through every entry that might contain a
136  * miniflow with hash 'HASH'. */
137 #define EMC_FOR_EACH_POS_WITH_HASH(EMC, CURRENT_ENTRY, HASH)                 \
138     for (uint32_t i__ = 0, srch_hash__ = (HASH);                             \
139          (CURRENT_ENTRY) = &(EMC)->entries[srch_hash__ & EM_FLOW_HASH_MASK], \
140          i__ < EM_FLOW_HASH_SEGS;                                            \
141          i__++, srch_hash__ >>= EM_FLOW_HASH_SHIFT)
142 \f
143 /* Simple non-wildcarding single-priority classifier. */
144
145 struct dpcls {
146     struct cmap subtables_map;
147     struct pvector subtables;
148 };
149
150 /* A rule to be inserted to the classifier. */
151 struct dpcls_rule {
152     struct cmap_node cmap_node;   /* Within struct dpcls_subtable 'rules'. */
153     struct netdev_flow_key *mask; /* Subtable's mask. */
154     struct netdev_flow_key flow;  /* Matching key. */
155     /* 'flow' must be the last field, additional space is allocated here. */
156 };
157
158 static void dpcls_init(struct dpcls *);
159 static void dpcls_destroy(struct dpcls *);
160 static void dpcls_insert(struct dpcls *, struct dpcls_rule *,
161                          const struct netdev_flow_key *mask);
162 static void dpcls_remove(struct dpcls *, struct dpcls_rule *);
163 static bool dpcls_lookup(const struct dpcls *cls,
164                          const struct netdev_flow_key keys[],
165                          struct dpcls_rule **rules, size_t cnt);
166 \f
167 /* Datapath based on the network device interface from netdev.h.
168  *
169  *
170  * Thread-safety
171  * =============
172  *
173  * Some members, marked 'const', are immutable.  Accessing other members
174  * requires synchronization, as noted in more detail below.
175  *
176  * Acquisition order is, from outermost to innermost:
177  *
178  *    dp_netdev_mutex (global)
179  *    port_mutex
180  *    flow_mutex
181  */
182 struct dp_netdev {
183     const struct dpif_class *const class;
184     const char *const name;
185     struct dpif *dpif;
186     struct ovs_refcount ref_cnt;
187     atomic_flag destroyed;
188
189     /* Flows.
190      *
191      * Writers of 'flow_table' must take the 'flow_mutex'.  Corresponding
192      * changes to 'cls' must be made while still holding the 'flow_mutex'.
193      */
194     struct ovs_mutex flow_mutex;
195     struct dpcls cls;
196     struct cmap flow_table OVS_GUARDED; /* Flow table. */
197
198     /* Statistics.
199      *
200      * ovsthread_stats is internally synchronized. */
201     struct ovsthread_stats stats; /* Contains 'struct dp_netdev_stats *'. */
202
203     /* Ports.
204      *
205      * Protected by RCU.  Take the mutex to add or remove ports. */
206     struct ovs_mutex port_mutex;
207     struct cmap ports;
208     struct seq *port_seq;       /* Incremented whenever a port changes. */
209
210     /* Protects access to ofproto-dpif-upcall interface during revalidator
211      * thread synchronization. */
212     struct fat_rwlock upcall_rwlock;
213     upcall_callback *upcall_cb;  /* Callback function for executing upcalls. */
214     void *upcall_aux;
215
216     /* Stores all 'struct dp_netdev_pmd_thread's. */
217     struct cmap poll_threads;
218
219     /* Protects the access of the 'struct dp_netdev_pmd_thread'
220      * instance for non-pmd thread. */
221     struct ovs_mutex non_pmd_mutex;
222
223     /* Each pmd thread will store its pointer to
224      * 'struct dp_netdev_pmd_thread' in 'per_pmd_key'. */
225     ovsthread_key_t per_pmd_key;
226
227     /* Number of rx queues for each dpdk interface and the cpu mask
228      * for pin of pmd threads. */
229     size_t n_dpdk_rxqs;
230     char *pmd_cmask;
231     uint64_t last_tnl_conf_seq;
232 };
233
234 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
235                                                     odp_port_t);
236
237 enum dp_stat_type {
238     DP_STAT_HIT,                /* Packets that matched in the flow table. */
239     DP_STAT_MISS,               /* Packets that did not match. */
240     DP_STAT_LOST,               /* Packets not passed up to the client. */
241     DP_N_STATS
242 };
243
244 /* Contained by struct dp_netdev's 'stats' member.  */
245 struct dp_netdev_stats {
246     struct ovs_mutex mutex;          /* Protects 'n'. */
247
248     /* Indexed by DP_STAT_*, protected by 'mutex'. */
249     unsigned long long int n[DP_N_STATS] OVS_GUARDED;
250 };
251
252
253 /* A port in a netdev-based datapath. */
254 struct dp_netdev_port {
255     struct cmap_node node;      /* Node in dp_netdev's 'ports'. */
256     odp_port_t port_no;
257     struct netdev *netdev;
258     struct netdev_saved_flags *sf;
259     struct netdev_rxq **rxq;
260     struct ovs_refcount ref_cnt;
261     char *type;                 /* Port type as requested by user. */
262 };
263
264 \f
265 /* A flow in dp_netdev's 'flow_table'.
266  *
267  *
268  * Thread-safety
269  * =============
270  *
271  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
272  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
273  *
274  * Motivation
275  * ----------
276  *
277  * The thread safety rules described here for "struct dp_netdev_flow" are
278  * motivated by two goals:
279  *
280  *    - Prevent threads that read members of "struct dp_netdev_flow" from
281  *      reading bad data due to changes by some thread concurrently modifying
282  *      those members.
283  *
284  *    - Prevent two threads making changes to members of a given "struct
285  *      dp_netdev_flow" from interfering with each other.
286  *
287  *
288  * Rules
289  * -----
290  *
291  * A flow 'flow' may be accessed without a risk of being freed during an RCU
292  * grace period.  Code that needs to hold onto a flow for a while
293  * should try incrementing 'flow->ref_cnt' with dp_netdev_flow_ref().
294  *
295  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
296  * flow from being deleted from 'cls' and it doesn't protect members of 'flow'
297  * from modification.
298  *
299  * Some members, marked 'const', are immutable.  Accessing other members
300  * requires synchronization, as noted in more detail below.
301  */
302 struct dp_netdev_flow {
303     bool dead;
304
305     /* Hash table index by unmasked flow. */
306     const struct cmap_node node; /* In owning dp_netdev's 'flow_table'. */
307     const struct flow flow;      /* Unmasked flow that created this entry. */
308
309     /* Number of references.
310      * The classifier owns one reference.
311      * Any thread trying to keep a rule from being freed should hold its own
312      * reference. */
313     struct ovs_refcount ref_cnt;
314
315     /* Statistics.
316      *
317      * Reading or writing these members requires 'mutex'. */
318     struct ovsthread_stats stats; /* Contains "struct dp_netdev_flow_stats". */
319
320     /* Actions. */
321     OVSRCU_TYPE(struct dp_netdev_actions *) actions;
322
323     /* Packet classification. */
324     struct dpcls_rule cr;        /* In owning dp_netdev's 'cls'. */
325     /* 'cr' must be the last member. */
326 };
327
328 static void dp_netdev_flow_unref(struct dp_netdev_flow *);
329 static bool dp_netdev_flow_ref(struct dp_netdev_flow *);
330
331 /* Contained by struct dp_netdev_flow's 'stats' member.  */
332 struct dp_netdev_flow_stats {
333     struct ovs_mutex mutex;         /* Guards all the other members. */
334
335     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
336     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
337     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
338     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
339 };
340
341 /* A set of datapath actions within a "struct dp_netdev_flow".
342  *
343  *
344  * Thread-safety
345  * =============
346  *
347  * A struct dp_netdev_actions 'actions' is protected with RCU. */
348 struct dp_netdev_actions {
349     /* These members are immutable: they do not change during the struct's
350      * lifetime.  */
351     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
352     unsigned int size;          /* Size of 'actions', in bytes. */
353 };
354
355 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
356                                                    size_t);
357 struct dp_netdev_actions *dp_netdev_flow_get_actions(
358     const struct dp_netdev_flow *);
359 static void dp_netdev_actions_free(struct dp_netdev_actions *);
360
361 /* PMD: Poll modes drivers.  PMD accesses devices via polling to eliminate
362  * the performance overhead of interrupt processing.  Therefore netdev can
363  * not implement rx-wait for these devices.  dpif-netdev needs to poll
364  * these device to check for recv buffer.  pmd-thread does polling for
365  * devices assigned to itself thread.
366  *
367  * DPDK used PMD for accessing NIC.
368  *
369  * Note, instance with cpu core id NON_PMD_CORE_ID will be reserved for
370  * I/O of all non-pmd threads.  There will be no actual thread created
371  * for the instance.
372  **/
373 struct dp_netdev_pmd_thread {
374     struct dp_netdev *dp;
375     struct cmap_node node;          /* In 'dp->poll_threads'. */
376
377     pthread_cond_t cond;            /* For synchronizing pmd thread reload. */
378     struct ovs_mutex cond_mutex;    /* Mutex for condition variable. */
379
380     /* Per thread exact-match cache.  Note, the instance for cpu core
381      * NON_PMD_CORE_ID can be accessed by multiple threads, and thusly
382      * need to be protected (e.g. by 'dp_netdev_mutex').  All other
383      * instances will only be accessed by its own pmd thread. */
384     struct emc_cache flow_cache;
385     struct latch exit_latch;        /* For terminating the pmd thread. */
386     atomic_uint change_seq;         /* For reloading pmd ports. */
387     pthread_t thread;
388     int index;                      /* Idx of this pmd thread among pmd*/
389                                     /* threads on same numa node. */
390     int core_id;                    /* CPU core id of this pmd thread. */
391     int numa_id;                    /* numa node id of this pmd thread. */
392 };
393
394 #define PMD_INITIAL_SEQ 1
395
396 /* Interface to netdev-based datapath. */
397 struct dpif_netdev {
398     struct dpif dpif;
399     struct dp_netdev *dp;
400     uint64_t last_port_seq;
401 };
402
403 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
404                               struct dp_netdev_port **portp);
405 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
406                             struct dp_netdev_port **portp);
407 static void dp_netdev_free(struct dp_netdev *)
408     OVS_REQUIRES(dp_netdev_mutex);
409 static void dp_netdev_flow_flush(struct dp_netdev *);
410 static int do_add_port(struct dp_netdev *dp, const char *devname,
411                        const char *type, odp_port_t port_no)
412     OVS_REQUIRES(dp->port_mutex);
413 static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
414     OVS_REQUIRES(dp->port_mutex);
415 static int dpif_netdev_open(const struct dpif_class *, const char *name,
416                             bool create, struct dpif **);
417 static void dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
418                                       struct dpif_packet **, int c,
419                                       bool may_steal,
420                                       const struct nlattr *actions,
421                                       size_t actions_len);
422 static void dp_netdev_input(struct dp_netdev_pmd_thread *,
423                             struct dpif_packet **, int cnt);
424
425 static void dp_netdev_disable_upcall(struct dp_netdev *);
426 void dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd);
427 static void dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd,
428                                     struct dp_netdev *dp, int index,
429                                     int core_id, int numa_id);
430 static void dp_netdev_set_nonpmd(struct dp_netdev *dp);
431 static struct dp_netdev_pmd_thread *dp_netdev_get_nonpmd(struct dp_netdev *dp);
432 static void dp_netdev_destroy_all_pmds(struct dp_netdev *dp);
433 static void dp_netdev_del_pmds_on_numa(struct dp_netdev *dp, int numa_id);
434 static void dp_netdev_set_pmds_on_numa(struct dp_netdev *dp, int numa_id);
435 static void dp_netdev_reset_pmd_threads(struct dp_netdev *dp);
436
437 static inline bool emc_entry_alive(struct emc_entry *ce);
438 static void emc_clear_entry(struct emc_entry *ce);
439
440 static void
441 emc_cache_init(struct emc_cache *flow_cache)
442 {
443     int i;
444
445     BUILD_ASSERT(offsetof(struct miniflow, inline_values) == sizeof(uint64_t));
446
447     flow_cache->sweep_idx = 0;
448     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
449         flow_cache->entries[i].flow = NULL;
450         flow_cache->entries[i].key.hash = 0;
451         flow_cache->entries[i].key.len
452             = offsetof(struct miniflow, inline_values);
453         miniflow_initialize(&flow_cache->entries[i].key.mf,
454                             flow_cache->entries[i].key.buf);
455     }
456 }
457
458 static void
459 emc_cache_uninit(struct emc_cache *flow_cache)
460 {
461     int i;
462
463     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
464         emc_clear_entry(&flow_cache->entries[i]);
465     }
466 }
467
468 /* Check and clear dead flow references slowly (one entry at each
469  * invocation).  */
470 static void
471 emc_cache_slow_sweep(struct emc_cache *flow_cache)
472 {
473     struct emc_entry *entry = &flow_cache->entries[flow_cache->sweep_idx];
474
475     if (!emc_entry_alive(entry)) {
476         emc_clear_entry(entry);
477     }
478     flow_cache->sweep_idx = (flow_cache->sweep_idx + 1) & EM_FLOW_HASH_MASK;
479 }
480
481 static struct dpif_netdev *
482 dpif_netdev_cast(const struct dpif *dpif)
483 {
484     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
485     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
486 }
487
488 static struct dp_netdev *
489 get_dp_netdev(const struct dpif *dpif)
490 {
491     return dpif_netdev_cast(dpif)->dp;
492 }
493
494 static int
495 dpif_netdev_enumerate(struct sset *all_dps,
496                       const struct dpif_class *dpif_class)
497 {
498     struct shash_node *node;
499
500     ovs_mutex_lock(&dp_netdev_mutex);
501     SHASH_FOR_EACH(node, &dp_netdevs) {
502         struct dp_netdev *dp = node->data;
503         if (dpif_class != dp->class) {
504             /* 'dp_netdevs' contains both "netdev" and "dummy" dpifs.
505              * If the class doesn't match, skip this dpif. */
506              continue;
507         }
508         sset_add(all_dps, node->name);
509     }
510     ovs_mutex_unlock(&dp_netdev_mutex);
511
512     return 0;
513 }
514
515 static bool
516 dpif_netdev_class_is_dummy(const struct dpif_class *class)
517 {
518     return class != &dpif_netdev_class;
519 }
520
521 static const char *
522 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
523 {
524     return strcmp(type, "internal") ? type
525                   : dpif_netdev_class_is_dummy(class) ? "dummy"
526                   : "tap";
527 }
528
529 static struct dpif *
530 create_dpif_netdev(struct dp_netdev *dp)
531 {
532     uint16_t netflow_id = hash_string(dp->name, 0);
533     struct dpif_netdev *dpif;
534
535     ovs_refcount_ref(&dp->ref_cnt);
536
537     dpif = xmalloc(sizeof *dpif);
538     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
539     dpif->dp = dp;
540     dpif->last_port_seq = seq_read(dp->port_seq);
541
542     return &dpif->dpif;
543 }
544
545 /* Choose an unused, non-zero port number and return it on success.
546  * Return ODPP_NONE on failure. */
547 static odp_port_t
548 choose_port(struct dp_netdev *dp, const char *name)
549     OVS_REQUIRES(dp->port_mutex)
550 {
551     uint32_t port_no;
552
553     if (dp->class != &dpif_netdev_class) {
554         const char *p;
555         int start_no = 0;
556
557         /* If the port name begins with "br", start the number search at
558          * 100 to make writing tests easier. */
559         if (!strncmp(name, "br", 2)) {
560             start_no = 100;
561         }
562
563         /* If the port name contains a number, try to assign that port number.
564          * This can make writing unit tests easier because port numbers are
565          * predictable. */
566         for (p = name; *p != '\0'; p++) {
567             if (isdigit((unsigned char) *p)) {
568                 port_no = start_no + strtol(p, NULL, 10);
569                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
570                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
571                     return u32_to_odp(port_no);
572                 }
573                 break;
574             }
575         }
576     }
577
578     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
579         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
580             return u32_to_odp(port_no);
581         }
582     }
583
584     return ODPP_NONE;
585 }
586
587 static int
588 create_dp_netdev(const char *name, const struct dpif_class *class,
589                  struct dp_netdev **dpp)
590     OVS_REQUIRES(dp_netdev_mutex)
591 {
592     struct dp_netdev *dp;
593     int error;
594
595     dp = xzalloc(sizeof *dp);
596     shash_add(&dp_netdevs, name, dp);
597
598     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
599     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
600     ovs_refcount_init(&dp->ref_cnt);
601     atomic_flag_clear(&dp->destroyed);
602
603     ovs_mutex_init(&dp->flow_mutex);
604     dpcls_init(&dp->cls);
605     cmap_init(&dp->flow_table);
606
607     ovsthread_stats_init(&dp->stats);
608
609     ovs_mutex_init(&dp->port_mutex);
610     cmap_init(&dp->ports);
611     dp->port_seq = seq_create();
612     fat_rwlock_init(&dp->upcall_rwlock);
613
614     /* Disable upcalls by default. */
615     dp_netdev_disable_upcall(dp);
616     dp->upcall_aux = NULL;
617     dp->upcall_cb = NULL;
618
619     cmap_init(&dp->poll_threads);
620     ovs_mutex_init_recursive(&dp->non_pmd_mutex);
621     ovsthread_key_create(&dp->per_pmd_key, NULL);
622
623     /* Reserves the core NON_PMD_CORE_ID for all non-pmd threads. */
624     ovs_numa_try_pin_core_specific(NON_PMD_CORE_ID);
625     dp_netdev_set_nonpmd(dp);
626     dp->n_dpdk_rxqs = NR_QUEUE;
627
628     ovs_mutex_lock(&dp->port_mutex);
629     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
630     ovs_mutex_unlock(&dp->port_mutex);
631     if (error) {
632         dp_netdev_free(dp);
633         return error;
634     }
635
636     dp->last_tnl_conf_seq = seq_read(tnl_conf_seq);
637     *dpp = dp;
638     return 0;
639 }
640
641 static int
642 dpif_netdev_open(const struct dpif_class *class, const char *name,
643                  bool create, struct dpif **dpifp)
644 {
645     struct dp_netdev *dp;
646     int error;
647
648     ovs_mutex_lock(&dp_netdev_mutex);
649     dp = shash_find_data(&dp_netdevs, name);
650     if (!dp) {
651         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
652     } else {
653         error = (dp->class != class ? EINVAL
654                  : create ? EEXIST
655                  : 0);
656     }
657     if (!error) {
658         *dpifp = create_dpif_netdev(dp);
659         dp->dpif = *dpifp;
660     }
661     ovs_mutex_unlock(&dp_netdev_mutex);
662
663     return error;
664 }
665
666 static void
667 dp_netdev_destroy_upcall_lock(struct dp_netdev *dp)
668     OVS_NO_THREAD_SAFETY_ANALYSIS
669 {
670     /* Check that upcalls are disabled, i.e. that the rwlock is taken */
671     ovs_assert(fat_rwlock_tryrdlock(&dp->upcall_rwlock));
672
673     /* Before freeing a lock we should release it */
674     fat_rwlock_unlock(&dp->upcall_rwlock);
675     fat_rwlock_destroy(&dp->upcall_rwlock);
676 }
677
678 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
679  * through the 'dp_netdevs' shash while freeing 'dp'. */
680 static void
681 dp_netdev_free(struct dp_netdev *dp)
682     OVS_REQUIRES(dp_netdev_mutex)
683 {
684     struct dp_netdev_port *port;
685     struct dp_netdev_stats *bucket;
686     int i;
687
688     shash_find_and_delete(&dp_netdevs, dp->name);
689
690     dp_netdev_destroy_all_pmds(dp);
691     cmap_destroy(&dp->poll_threads);
692     ovs_mutex_destroy(&dp->non_pmd_mutex);
693     ovsthread_key_delete(dp->per_pmd_key);
694
695     dp_netdev_flow_flush(dp);
696     ovs_mutex_lock(&dp->port_mutex);
697     CMAP_FOR_EACH (port, node, &dp->ports) {
698         do_del_port(dp, port);
699     }
700     ovs_mutex_unlock(&dp->port_mutex);
701
702     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
703         ovs_mutex_destroy(&bucket->mutex);
704         free_cacheline(bucket);
705     }
706     ovsthread_stats_destroy(&dp->stats);
707
708     dpcls_destroy(&dp->cls);
709     cmap_destroy(&dp->flow_table);
710     ovs_mutex_destroy(&dp->flow_mutex);
711     seq_destroy(dp->port_seq);
712     cmap_destroy(&dp->ports);
713
714     /* Upcalls must be disabled at this point */
715     dp_netdev_destroy_upcall_lock(dp);
716
717     free(dp->pmd_cmask);
718     free(CONST_CAST(char *, dp->name));
719     free(dp);
720 }
721
722 static void
723 dp_netdev_unref(struct dp_netdev *dp)
724 {
725     if (dp) {
726         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
727          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
728         ovs_mutex_lock(&dp_netdev_mutex);
729         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
730             dp_netdev_free(dp);
731         }
732         ovs_mutex_unlock(&dp_netdev_mutex);
733     }
734 }
735
736 static void
737 dpif_netdev_close(struct dpif *dpif)
738 {
739     struct dp_netdev *dp = get_dp_netdev(dpif);
740
741     dp_netdev_unref(dp);
742     free(dpif);
743 }
744
745 static int
746 dpif_netdev_destroy(struct dpif *dpif)
747 {
748     struct dp_netdev *dp = get_dp_netdev(dpif);
749
750     if (!atomic_flag_test_and_set(&dp->destroyed)) {
751         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
752             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
753             OVS_NOT_REACHED();
754         }
755     }
756
757     return 0;
758 }
759
760 static int
761 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
762 {
763     struct dp_netdev *dp = get_dp_netdev(dpif);
764     struct dp_netdev_stats *bucket;
765     size_t i;
766
767     stats->n_flows = cmap_count(&dp->flow_table);
768
769     stats->n_hit = stats->n_missed = stats->n_lost = 0;
770     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
771         ovs_mutex_lock(&bucket->mutex);
772         stats->n_hit += bucket->n[DP_STAT_HIT];
773         stats->n_missed += bucket->n[DP_STAT_MISS];
774         stats->n_lost += bucket->n[DP_STAT_LOST];
775         ovs_mutex_unlock(&bucket->mutex);
776     }
777     stats->n_masks = UINT32_MAX;
778     stats->n_mask_hit = UINT64_MAX;
779
780     return 0;
781 }
782
783 static void
784 dp_netdev_reload_pmd__(struct dp_netdev_pmd_thread *pmd)
785 {
786     int old_seq;
787
788     if (pmd->core_id == NON_PMD_CORE_ID) {
789         return;
790     }
791
792     ovs_mutex_lock(&pmd->cond_mutex);
793     atomic_add_relaxed(&pmd->change_seq, 1, &old_seq);
794     ovs_mutex_cond_wait(&pmd->cond, &pmd->cond_mutex);
795     ovs_mutex_unlock(&pmd->cond_mutex);
796 }
797
798 /* Causes all pmd threads to reload its tx/rx devices.
799  * Must be called after adding/removing ports. */
800 static void
801 dp_netdev_reload_pmds(struct dp_netdev *dp)
802 {
803     struct dp_netdev_pmd_thread *pmd;
804
805     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
806         dp_netdev_reload_pmd__(pmd);
807     }
808 }
809
810 static uint32_t
811 hash_port_no(odp_port_t port_no)
812 {
813     return hash_int(odp_to_u32(port_no), 0);
814 }
815
816 static int
817 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
818             odp_port_t port_no)
819     OVS_REQUIRES(dp->port_mutex)
820 {
821     struct netdev_saved_flags *sf;
822     struct dp_netdev_port *port;
823     struct netdev *netdev;
824     enum netdev_flags flags;
825     const char *open_type;
826     int error;
827     int i;
828
829     /* XXX reject devices already in some dp_netdev. */
830
831     /* Open and validate network device. */
832     open_type = dpif_netdev_port_open_type(dp->class, type);
833     error = netdev_open(devname, open_type, &netdev);
834     if (error) {
835         return error;
836     }
837     /* XXX reject non-Ethernet devices */
838
839     netdev_get_flags(netdev, &flags);
840     if (flags & NETDEV_LOOPBACK) {
841         VLOG_ERR("%s: cannot add a loopback device", devname);
842         netdev_close(netdev);
843         return EINVAL;
844     }
845
846     if (netdev_is_pmd(netdev)) {
847         int n_cores = ovs_numa_get_n_cores();
848
849         if (n_cores == OVS_CORE_UNSPEC) {
850             VLOG_ERR("%s, cannot get cpu core info", devname);
851             return ENOENT;
852         }
853         /* There can only be ovs_numa_get_n_cores() pmd threads,
854          * so creates a txq for each. */
855         error = netdev_set_multiq(netdev, n_cores, dp->n_dpdk_rxqs);
856         if (error && (error != EOPNOTSUPP)) {
857             VLOG_ERR("%s, cannot set multiq", devname);
858             return errno;
859         }
860     }
861     port = xzalloc(sizeof *port);
862     port->port_no = port_no;
863     port->netdev = netdev;
864     port->rxq = xmalloc(sizeof *port->rxq * netdev_n_rxq(netdev));
865     port->type = xstrdup(type);
866     for (i = 0; i < netdev_n_rxq(netdev); i++) {
867         error = netdev_rxq_open(netdev, &port->rxq[i], i);
868         if (error
869             && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
870             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
871                      devname, ovs_strerror(errno));
872             netdev_close(netdev);
873             free(port->type);
874             free(port->rxq);
875             free(port);
876             return error;
877         }
878     }
879
880     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
881     if (error) {
882         for (i = 0; i < netdev_n_rxq(netdev); i++) {
883             netdev_rxq_close(port->rxq[i]);
884         }
885         netdev_close(netdev);
886         free(port->type);
887         free(port->rxq);
888         free(port);
889         return error;
890     }
891     port->sf = sf;
892
893     ovs_refcount_init(&port->ref_cnt);
894     cmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
895
896     if (netdev_is_pmd(netdev)) {
897         dp_netdev_set_pmds_on_numa(dp, netdev_get_numa_id(netdev));
898         dp_netdev_reload_pmds(dp);
899     }
900     seq_change(dp->port_seq);
901
902     return 0;
903 }
904
905 static int
906 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
907                      odp_port_t *port_nop)
908 {
909     struct dp_netdev *dp = get_dp_netdev(dpif);
910     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
911     const char *dpif_port;
912     odp_port_t port_no;
913     int error;
914
915     ovs_mutex_lock(&dp->port_mutex);
916     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
917     if (*port_nop != ODPP_NONE) {
918         port_no = *port_nop;
919         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
920     } else {
921         port_no = choose_port(dp, dpif_port);
922         error = port_no == ODPP_NONE ? EFBIG : 0;
923     }
924     if (!error) {
925         *port_nop = port_no;
926         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
927     }
928     ovs_mutex_unlock(&dp->port_mutex);
929
930     return error;
931 }
932
933 static int
934 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
935 {
936     struct dp_netdev *dp = get_dp_netdev(dpif);
937     int error;
938
939     ovs_mutex_lock(&dp->port_mutex);
940     if (port_no == ODPP_LOCAL) {
941         error = EINVAL;
942     } else {
943         struct dp_netdev_port *port;
944
945         error = get_port_by_number(dp, port_no, &port);
946         if (!error) {
947             do_del_port(dp, port);
948         }
949     }
950     ovs_mutex_unlock(&dp->port_mutex);
951
952     return error;
953 }
954
955 static bool
956 is_valid_port_number(odp_port_t port_no)
957 {
958     return port_no != ODPP_NONE;
959 }
960
961 static struct dp_netdev_port *
962 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
963 {
964     struct dp_netdev_port *port;
965
966     CMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
967         if (port->port_no == port_no) {
968             return port;
969         }
970     }
971     return NULL;
972 }
973
974 static int
975 get_port_by_number(struct dp_netdev *dp,
976                    odp_port_t port_no, struct dp_netdev_port **portp)
977 {
978     if (!is_valid_port_number(port_no)) {
979         *portp = NULL;
980         return EINVAL;
981     } else {
982         *portp = dp_netdev_lookup_port(dp, port_no);
983         return *portp ? 0 : ENOENT;
984     }
985 }
986
987 static void
988 port_ref(struct dp_netdev_port *port)
989 {
990     if (port) {
991         ovs_refcount_ref(&port->ref_cnt);
992     }
993 }
994
995 static bool
996 port_try_ref(struct dp_netdev_port *port)
997 {
998     if (port) {
999         return ovs_refcount_try_ref_rcu(&port->ref_cnt);
1000     }
1001
1002     return false;
1003 }
1004
1005 static void
1006 port_unref(struct dp_netdev_port *port)
1007 {
1008     if (port && ovs_refcount_unref_relaxed(&port->ref_cnt) == 1) {
1009         int n_rxq = netdev_n_rxq(port->netdev);
1010         int i;
1011
1012         netdev_close(port->netdev);
1013         netdev_restore_flags(port->sf);
1014
1015         for (i = 0; i < n_rxq; i++) {
1016             netdev_rxq_close(port->rxq[i]);
1017         }
1018         free(port->rxq);
1019         free(port->type);
1020         free(port);
1021     }
1022 }
1023
1024 static int
1025 get_port_by_name(struct dp_netdev *dp,
1026                  const char *devname, struct dp_netdev_port **portp)
1027     OVS_REQUIRES(dp->port_mutex)
1028 {
1029     struct dp_netdev_port *port;
1030
1031     CMAP_FOR_EACH (port, node, &dp->ports) {
1032         if (!strcmp(netdev_get_name(port->netdev), devname)) {
1033             *portp = port;
1034             return 0;
1035         }
1036     }
1037     return ENOENT;
1038 }
1039
1040 static int
1041 get_n_pmd_threads_on_numa(struct dp_netdev *dp, int numa_id)
1042 {
1043     struct dp_netdev_pmd_thread *pmd;
1044     int n_pmds = 0;
1045
1046     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1047         if (pmd->numa_id == numa_id) {
1048             n_pmds++;
1049         }
1050     }
1051
1052     return n_pmds;
1053 }
1054
1055 /* Returns 'true' if there is a port with pmd netdev and the netdev
1056  * is on numa node 'numa_id'. */
1057 static bool
1058 has_pmd_port_for_numa(struct dp_netdev *dp, int numa_id)
1059 {
1060     struct dp_netdev_port *port;
1061
1062     CMAP_FOR_EACH (port, node, &dp->ports) {
1063         if (netdev_is_pmd(port->netdev)
1064             && netdev_get_numa_id(port->netdev) == numa_id) {
1065             return true;
1066         }
1067     }
1068
1069     return false;
1070 }
1071
1072
1073 static void
1074 do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
1075     OVS_REQUIRES(dp->port_mutex)
1076 {
1077     cmap_remove(&dp->ports, &port->node, hash_odp_port(port->port_no));
1078     seq_change(dp->port_seq);
1079     if (netdev_is_pmd(port->netdev)) {
1080         int numa_id = netdev_get_numa_id(port->netdev);
1081
1082         /* If there is no netdev on the numa node, deletes the pmd threads
1083          * for that numa.  Else, just reloads the queues.  */
1084         if (!has_pmd_port_for_numa(dp, numa_id)) {
1085             dp_netdev_del_pmds_on_numa(dp, numa_id);
1086         }
1087         dp_netdev_reload_pmds(dp);
1088     }
1089
1090     port_unref(port);
1091 }
1092
1093 static void
1094 answer_port_query(const struct dp_netdev_port *port,
1095                   struct dpif_port *dpif_port)
1096 {
1097     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
1098     dpif_port->type = xstrdup(port->type);
1099     dpif_port->port_no = port->port_no;
1100 }
1101
1102 static int
1103 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
1104                                  struct dpif_port *dpif_port)
1105 {
1106     struct dp_netdev *dp = get_dp_netdev(dpif);
1107     struct dp_netdev_port *port;
1108     int error;
1109
1110     error = get_port_by_number(dp, port_no, &port);
1111     if (!error && dpif_port) {
1112         answer_port_query(port, dpif_port);
1113     }
1114
1115     return error;
1116 }
1117
1118 static int
1119 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
1120                                struct dpif_port *dpif_port)
1121 {
1122     struct dp_netdev *dp = get_dp_netdev(dpif);
1123     struct dp_netdev_port *port;
1124     int error;
1125
1126     ovs_mutex_lock(&dp->port_mutex);
1127     error = get_port_by_name(dp, devname, &port);
1128     if (!error && dpif_port) {
1129         answer_port_query(port, dpif_port);
1130     }
1131     ovs_mutex_unlock(&dp->port_mutex);
1132
1133     return error;
1134 }
1135
1136 static void
1137 dp_netdev_flow_free(struct dp_netdev_flow *flow)
1138 {
1139     struct dp_netdev_flow_stats *bucket;
1140     size_t i;
1141
1142     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &flow->stats) {
1143         ovs_mutex_destroy(&bucket->mutex);
1144         free_cacheline(bucket);
1145     }
1146     ovsthread_stats_destroy(&flow->stats);
1147
1148     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
1149     free(flow);
1150 }
1151
1152 static void dp_netdev_flow_unref(struct dp_netdev_flow *flow)
1153 {
1154     if (ovs_refcount_unref_relaxed(&flow->ref_cnt) == 1) {
1155         ovsrcu_postpone(dp_netdev_flow_free, flow);
1156     }
1157 }
1158
1159 static void
1160 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
1161     OVS_REQUIRES(dp->flow_mutex)
1162 {
1163     struct cmap_node *node = CONST_CAST(struct cmap_node *, &flow->node);
1164
1165     dpcls_remove(&dp->cls, &flow->cr);
1166     cmap_remove(&dp->flow_table, node, flow_hash(&flow->flow, 0));
1167     flow->dead = true;
1168
1169     dp_netdev_flow_unref(flow);
1170 }
1171
1172 static void
1173 dp_netdev_flow_flush(struct dp_netdev *dp)
1174 {
1175     struct dp_netdev_flow *netdev_flow;
1176
1177     ovs_mutex_lock(&dp->flow_mutex);
1178     CMAP_FOR_EACH (netdev_flow, node, &dp->flow_table) {
1179         dp_netdev_remove_flow(dp, netdev_flow);
1180     }
1181     ovs_mutex_unlock(&dp->flow_mutex);
1182 }
1183
1184 static int
1185 dpif_netdev_flow_flush(struct dpif *dpif)
1186 {
1187     struct dp_netdev *dp = get_dp_netdev(dpif);
1188
1189     dp_netdev_flow_flush(dp);
1190     return 0;
1191 }
1192
1193 struct dp_netdev_port_state {
1194     struct cmap_position position;
1195     char *name;
1196 };
1197
1198 static int
1199 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
1200 {
1201     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
1202     return 0;
1203 }
1204
1205 static int
1206 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
1207                            struct dpif_port *dpif_port)
1208 {
1209     struct dp_netdev_port_state *state = state_;
1210     struct dp_netdev *dp = get_dp_netdev(dpif);
1211     struct cmap_node *node;
1212     int retval;
1213
1214     node = cmap_next_position(&dp->ports, &state->position);
1215     if (node) {
1216         struct dp_netdev_port *port;
1217
1218         port = CONTAINER_OF(node, struct dp_netdev_port, node);
1219
1220         free(state->name);
1221         state->name = xstrdup(netdev_get_name(port->netdev));
1222         dpif_port->name = state->name;
1223         dpif_port->type = port->type;
1224         dpif_port->port_no = port->port_no;
1225
1226         retval = 0;
1227     } else {
1228         retval = EOF;
1229     }
1230
1231     return retval;
1232 }
1233
1234 static int
1235 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1236 {
1237     struct dp_netdev_port_state *state = state_;
1238     free(state->name);
1239     free(state);
1240     return 0;
1241 }
1242
1243 static int
1244 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1245 {
1246     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1247     uint64_t new_port_seq;
1248     int error;
1249
1250     new_port_seq = seq_read(dpif->dp->port_seq);
1251     if (dpif->last_port_seq != new_port_seq) {
1252         dpif->last_port_seq = new_port_seq;
1253         error = ENOBUFS;
1254     } else {
1255         error = EAGAIN;
1256     }
1257
1258     return error;
1259 }
1260
1261 static void
1262 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1263 {
1264     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1265
1266     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1267 }
1268
1269 static struct dp_netdev_flow *
1270 dp_netdev_flow_cast(const struct dpcls_rule *cr)
1271 {
1272     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1273 }
1274
1275 static bool dp_netdev_flow_ref(struct dp_netdev_flow *flow)
1276 {
1277     return ovs_refcount_try_ref_rcu(&flow->ref_cnt);
1278 }
1279
1280 /* netdev_flow_key utilities.
1281  *
1282  * netdev_flow_key is basically a miniflow.  We use these functions
1283  * (netdev_flow_key_clone, netdev_flow_key_equal, ...) instead of the miniflow
1284  * functions (miniflow_clone_inline, miniflow_equal, ...), because:
1285  *
1286  * - Since we are dealing exclusively with miniflows created by
1287  *   miniflow_extract(), if the map is different the miniflow is different.
1288  *   Therefore we can be faster by comparing the map and the miniflow in a
1289  *   single memcmp().
1290  * _ netdev_flow_key's miniflow has always inline values.
1291  * - These functions can be inlined by the compiler.
1292  *
1293  * The following assertions make sure that what we're doing with miniflow is
1294  * safe
1295  */
1296 BUILD_ASSERT_DECL(offsetof(struct miniflow, inline_values)
1297                   == sizeof(uint64_t));
1298
1299 /* Given the number of bits set in the miniflow map, returns the size of the
1300  * 'netdev_flow_key.mf' */
1301 static inline uint32_t
1302 netdev_flow_key_size(uint32_t flow_u32s)
1303 {
1304     return offsetof(struct miniflow, inline_values) +
1305         MINIFLOW_VALUES_SIZE(flow_u32s);
1306 }
1307
1308 static inline bool
1309 netdev_flow_key_equal(const struct netdev_flow_key *a,
1310                       const struct netdev_flow_key *b)
1311 {
1312     /* 'b->len' may be not set yet. */
1313     return a->hash == b->hash && !memcmp(&a->mf, &b->mf, a->len);
1314 }
1315
1316 /* Used to compare 'netdev_flow_key' in the exact match cache to a miniflow.
1317  * The maps are compared bitwise, so both 'key->mf' 'mf' must have been
1318  * generated by miniflow_extract. */
1319 static inline bool
1320 netdev_flow_key_equal_mf(const struct netdev_flow_key *key,
1321                          const struct miniflow *mf)
1322 {
1323     return !memcmp(&key->mf, mf, key->len);
1324 }
1325
1326 static inline void
1327 netdev_flow_key_clone(struct netdev_flow_key *dst,
1328                       const struct netdev_flow_key *src)
1329 {
1330     memcpy(dst, src,
1331            offsetof(struct netdev_flow_key, mf) + src->len);
1332 }
1333
1334 /* Slow. */
1335 static void
1336 netdev_flow_key_from_flow(struct netdev_flow_key *dst,
1337                           const struct flow *src)
1338 {
1339     struct ofpbuf packet;
1340     uint64_t buf_stub[512 / 8];
1341     struct pkt_metadata md = pkt_metadata_from_flow(src);
1342
1343     miniflow_initialize(&dst->mf, dst->buf);
1344
1345     ofpbuf_use_stub(&packet, buf_stub, sizeof buf_stub);
1346     flow_compose(&packet, src);
1347     miniflow_extract(&packet, &md, &dst->mf);
1348     ofpbuf_uninit(&packet);
1349
1350     dst->len = netdev_flow_key_size(count_1bits(dst->mf.map));
1351     dst->hash = 0; /* Not computed yet. */
1352 }
1353
1354 /* Initialize a netdev_flow_key 'mask' from 'match'. */
1355 static inline void
1356 netdev_flow_mask_init(struct netdev_flow_key *mask,
1357                       const struct match *match)
1358 {
1359     const uint32_t *mask_u32 = (const uint32_t *) &match->wc.masks;
1360     uint32_t *dst = mask->mf.inline_values;
1361     uint64_t map, mask_map = 0;
1362     uint32_t hash = 0;
1363     int n;
1364
1365     /* Only check masks that make sense for the flow. */
1366     map = flow_wc_map(&match->flow);
1367
1368     while (map) {
1369         uint64_t rm1bit = rightmost_1bit(map);
1370         int i = raw_ctz(map);
1371
1372         if (mask_u32[i]) {
1373             mask_map |= rm1bit;
1374             *dst++ = mask_u32[i];
1375             hash = hash_add(hash, mask_u32[i]);
1376         }
1377         map -= rm1bit;
1378     }
1379
1380     mask->mf.values_inline = true;
1381     mask->mf.map = mask_map;
1382
1383     hash = hash_add(hash, mask_map);
1384     hash = hash_add(hash, mask_map >> 32);
1385
1386     n = dst - mask->mf.inline_values;
1387
1388     mask->hash = hash_finish(hash, n * 4);
1389     mask->len = netdev_flow_key_size(n);
1390 }
1391
1392 /* Initializes 'dst' as a copy of 'src' masked with 'mask'. */
1393 static inline void
1394 netdev_flow_key_init_masked(struct netdev_flow_key *dst,
1395                             const struct flow *flow,
1396                             const struct netdev_flow_key *mask)
1397 {
1398     uint32_t *dst_u32 = dst->mf.inline_values;
1399     const uint32_t *mask_u32 = mask->mf.inline_values;
1400     uint32_t hash = 0;
1401     uint32_t value;
1402
1403     dst->len = mask->len;
1404     dst->mf.values_inline = true;
1405     dst->mf.map = mask->mf.map;
1406
1407     FLOW_FOR_EACH_IN_MAP(value, flow, mask->mf.map) {
1408         *dst_u32 = value & *mask_u32++;
1409         hash = hash_add(hash, *dst_u32++);
1410     }
1411     dst->hash = hash_finish(hash, (dst_u32 - dst->mf.inline_values) * 4);
1412 }
1413
1414 /* Iterate through all netdev_flow_key u32 values specified by 'MAP' */
1415 #define NETDEV_FLOW_KEY_FOR_EACH_IN_MAP(VALUE, KEY, MAP)           \
1416     for (struct mf_for_each_in_map_aux aux__                       \
1417              = { (KEY)->mf.inline_values, (KEY)->mf.map, MAP };    \
1418          mf_get_next_in_map(&aux__, &(VALUE));                     \
1419         )
1420
1421 /* Returns a hash value for the bits of 'key' where there are 1-bits in
1422  * 'mask'. */
1423 static inline uint32_t
1424 netdev_flow_key_hash_in_mask(const struct netdev_flow_key *key,
1425                              const struct netdev_flow_key *mask)
1426 {
1427     const uint32_t *p = mask->mf.inline_values;
1428     uint32_t hash = 0;
1429     uint32_t key_u32;
1430
1431     NETDEV_FLOW_KEY_FOR_EACH_IN_MAP(key_u32, key, mask->mf.map) {
1432         hash = hash_add(hash, key_u32 & *p++);
1433     }
1434
1435     return hash_finish(hash, (p - mask->mf.inline_values) * 4);
1436 }
1437
1438 static inline bool
1439 emc_entry_alive(struct emc_entry *ce)
1440 {
1441     return ce->flow && !ce->flow->dead;
1442 }
1443
1444 static void
1445 emc_clear_entry(struct emc_entry *ce)
1446 {
1447     if (ce->flow) {
1448         dp_netdev_flow_unref(ce->flow);
1449         ce->flow = NULL;
1450     }
1451 }
1452
1453 static inline void
1454 emc_change_entry(struct emc_entry *ce, struct dp_netdev_flow *flow,
1455                  const struct netdev_flow_key *key)
1456 {
1457     if (ce->flow != flow) {
1458         if (ce->flow) {
1459             dp_netdev_flow_unref(ce->flow);
1460         }
1461
1462         if (dp_netdev_flow_ref(flow)) {
1463             ce->flow = flow;
1464         } else {
1465             ce->flow = NULL;
1466         }
1467     }
1468     if (key) {
1469         netdev_flow_key_clone(&ce->key, key);
1470     }
1471 }
1472
1473 static inline void
1474 emc_insert(struct emc_cache *cache, const struct netdev_flow_key *key,
1475            struct dp_netdev_flow *flow)
1476 {
1477     struct emc_entry *to_be_replaced = NULL;
1478     struct emc_entry *current_entry;
1479
1480     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
1481         if (netdev_flow_key_equal(&current_entry->key, key)) {
1482             /* We found the entry with the 'mf' miniflow */
1483             emc_change_entry(current_entry, flow, NULL);
1484             return;
1485         }
1486
1487         /* Replacement policy: put the flow in an empty (not alive) entry, or
1488          * in the first entry where it can be */
1489         if (!to_be_replaced
1490             || (emc_entry_alive(to_be_replaced)
1491                 && !emc_entry_alive(current_entry))
1492             || current_entry->key.hash < to_be_replaced->key.hash) {
1493             to_be_replaced = current_entry;
1494         }
1495     }
1496     /* We didn't find the miniflow in the cache.
1497      * The 'to_be_replaced' entry is where the new flow will be stored */
1498
1499     emc_change_entry(to_be_replaced, flow, key);
1500 }
1501
1502 static inline struct dp_netdev_flow *
1503 emc_lookup(struct emc_cache *cache, const struct netdev_flow_key *key)
1504 {
1505     struct emc_entry *current_entry;
1506
1507     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
1508         if (current_entry->key.hash == key->hash
1509             && emc_entry_alive(current_entry)
1510             && netdev_flow_key_equal_mf(&current_entry->key, &key->mf)) {
1511
1512             /* We found the entry with the 'key->mf' miniflow */
1513             return current_entry->flow;
1514         }
1515     }
1516
1517     return NULL;
1518 }
1519
1520 static struct dp_netdev_flow *
1521 dp_netdev_lookup_flow(const struct dp_netdev *dp,
1522                       const struct netdev_flow_key *key)
1523 {
1524     struct dp_netdev_flow *netdev_flow;
1525     struct dpcls_rule *rule;
1526
1527     dpcls_lookup(&dp->cls, key, &rule, 1);
1528     netdev_flow = dp_netdev_flow_cast(rule);
1529
1530     return netdev_flow;
1531 }
1532
1533 static struct dp_netdev_flow *
1534 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1535 {
1536     struct dp_netdev_flow *netdev_flow;
1537
1538     CMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1539                              &dp->flow_table) {
1540         if (flow_equal(&netdev_flow->flow, flow)) {
1541             return netdev_flow;
1542         }
1543     }
1544
1545     return NULL;
1546 }
1547
1548 static void
1549 get_dpif_flow_stats(const struct dp_netdev_flow *netdev_flow,
1550                     struct dpif_flow_stats *stats)
1551 {
1552     struct dp_netdev_flow_stats *bucket;
1553     size_t i;
1554
1555     memset(stats, 0, sizeof *stats);
1556     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1557         ovs_mutex_lock(&bucket->mutex);
1558         stats->n_packets += bucket->packet_count;
1559         stats->n_bytes += bucket->byte_count;
1560         stats->used = MAX(stats->used, bucket->used);
1561         stats->tcp_flags |= bucket->tcp_flags;
1562         ovs_mutex_unlock(&bucket->mutex);
1563     }
1564 }
1565
1566 static void
1567 dp_netdev_flow_to_dpif_flow(const struct dp_netdev_flow *netdev_flow,
1568                             struct ofpbuf *buffer, struct dpif_flow *flow)
1569 {
1570     struct flow_wildcards wc;
1571     struct dp_netdev_actions *actions;
1572
1573     miniflow_expand(&netdev_flow->cr.mask->mf, &wc.masks);
1574     odp_flow_key_from_mask(buffer, &wc.masks, &netdev_flow->flow,
1575                            odp_to_u32(wc.masks.in_port.odp_port),
1576                            SIZE_MAX, true);
1577     flow->mask = ofpbuf_data(buffer);
1578     flow->mask_len = ofpbuf_size(buffer);
1579
1580     actions = dp_netdev_flow_get_actions(netdev_flow);
1581     flow->actions = actions->actions;
1582     flow->actions_len = actions->size;
1583
1584     get_dpif_flow_stats(netdev_flow, &flow->stats);
1585 }
1586
1587 static int
1588 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1589                               const struct nlattr *mask_key,
1590                               uint32_t mask_key_len, const struct flow *flow,
1591                               struct flow *mask)
1592 {
1593     if (mask_key_len) {
1594         enum odp_key_fitness fitness;
1595
1596         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1597         if (fitness) {
1598             /* This should not happen: it indicates that
1599              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1600              * disagree on the acceptable form of a mask.  Log the problem
1601              * as an error, with enough details to enable debugging. */
1602             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1603
1604             if (!VLOG_DROP_ERR(&rl)) {
1605                 struct ds s;
1606
1607                 ds_init(&s);
1608                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1609                                 true);
1610                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1611                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1612                 ds_destroy(&s);
1613             }
1614
1615             return EINVAL;
1616         }
1617     } else {
1618         enum mf_field_id id;
1619         /* No mask key, unwildcard everything except fields whose
1620          * prerequisities are not met. */
1621         memset(mask, 0x0, sizeof *mask);
1622
1623         for (id = 0; id < MFF_N_IDS; ++id) {
1624             /* Skip registers and metadata. */
1625             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1626                 && id != MFF_METADATA) {
1627                 const struct mf_field *mf = mf_from_id(id);
1628                 if (mf_are_prereqs_ok(mf, flow)) {
1629                     mf_mask_field(mf, mask);
1630                 }
1631             }
1632         }
1633     }
1634
1635     /* Force unwildcard the in_port.
1636      *
1637      * We need to do this even in the case where we unwildcard "everything"
1638      * above because "everything" only includes the 16-bit OpenFlow port number
1639      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1640      * port number mask->in_port.odp_port. */
1641     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1642
1643     return 0;
1644 }
1645
1646 static int
1647 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1648                               struct flow *flow)
1649 {
1650     odp_port_t in_port;
1651
1652     if (odp_flow_key_to_flow(key, key_len, flow)) {
1653         /* This should not happen: it indicates that odp_flow_key_from_flow()
1654          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1655          * flow.  Log the problem as an error, with enough details to enable
1656          * debugging. */
1657         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1658
1659         if (!VLOG_DROP_ERR(&rl)) {
1660             struct ds s;
1661
1662             ds_init(&s);
1663             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1664             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1665             ds_destroy(&s);
1666         }
1667
1668         return EINVAL;
1669     }
1670
1671     in_port = flow->in_port.odp_port;
1672     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1673         return EINVAL;
1674     }
1675
1676     return 0;
1677 }
1678
1679 static int
1680 dpif_netdev_flow_get(const struct dpif *dpif, const struct dpif_flow_get *get)
1681 {
1682     struct dp_netdev *dp = get_dp_netdev(dpif);
1683     struct dp_netdev_flow *netdev_flow;
1684     struct flow key;
1685     int error;
1686
1687     error = dpif_netdev_flow_from_nlattrs(get->key, get->key_len, &key);
1688     if (error) {
1689         return error;
1690     }
1691
1692     netdev_flow = dp_netdev_find_flow(dp, &key);
1693
1694     if (netdev_flow) {
1695         dp_netdev_flow_to_dpif_flow(netdev_flow, get->buffer, get->flow);
1696      } else {
1697         error = ENOENT;
1698     }
1699
1700     return error;
1701 }
1702
1703 static struct dp_netdev_flow *
1704 dp_netdev_flow_add(struct dp_netdev *dp, struct match *match,
1705                    const struct nlattr *actions, size_t actions_len)
1706     OVS_REQUIRES(dp->flow_mutex)
1707 {
1708     struct dp_netdev_flow *flow;
1709     struct netdev_flow_key mask;
1710
1711     netdev_flow_mask_init(&mask, match);
1712     /* Make sure wc does not have metadata. */
1713     ovs_assert(!(mask.mf.map & (MINIFLOW_MAP(metadata) | MINIFLOW_MAP(regs))));
1714
1715     /* Do not allocate extra space. */
1716     flow = xmalloc(sizeof *flow - sizeof flow->cr.flow.mf + mask.len);
1717     flow->dead = false;
1718     *CONST_CAST(struct flow *, &flow->flow) = match->flow;
1719     ovs_refcount_init(&flow->ref_cnt);
1720     ovsthread_stats_init(&flow->stats);
1721     ovsrcu_set(&flow->actions, dp_netdev_actions_create(actions, actions_len));
1722
1723     cmap_insert(&dp->flow_table,
1724                 CONST_CAST(struct cmap_node *, &flow->node),
1725                 flow_hash(&flow->flow, 0));
1726     netdev_flow_key_init_masked(&flow->cr.flow, &match->flow, &mask);
1727     dpcls_insert(&dp->cls, &flow->cr, &mask);
1728
1729     if (OVS_UNLIKELY(VLOG_IS_DBG_ENABLED())) {
1730         struct match match;
1731         struct ds ds = DS_EMPTY_INITIALIZER;
1732
1733         match.flow = flow->flow;
1734         miniflow_expand(&flow->cr.mask->mf, &match.wc.masks);
1735
1736         ds_put_cstr(&ds, "flow_add: ");
1737         match_format(&match, &ds, OFP_DEFAULT_PRIORITY);
1738         ds_put_cstr(&ds, ", actions:");
1739         format_odp_actions(&ds, actions, actions_len);
1740
1741         VLOG_DBG_RL(&upcall_rl, "%s", ds_cstr(&ds));
1742
1743         ds_destroy(&ds);
1744     }
1745
1746     return flow;
1747 }
1748
1749 static void
1750 clear_stats(struct dp_netdev_flow *netdev_flow)
1751 {
1752     struct dp_netdev_flow_stats *bucket;
1753     size_t i;
1754
1755     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1756         ovs_mutex_lock(&bucket->mutex);
1757         bucket->used = 0;
1758         bucket->packet_count = 0;
1759         bucket->byte_count = 0;
1760         bucket->tcp_flags = 0;
1761         ovs_mutex_unlock(&bucket->mutex);
1762     }
1763 }
1764
1765 static int
1766 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1767 {
1768     struct dp_netdev *dp = get_dp_netdev(dpif);
1769     struct dp_netdev_flow *netdev_flow;
1770     struct netdev_flow_key key;
1771     struct match match;
1772     int error;
1773
1774     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &match.flow);
1775     if (error) {
1776         return error;
1777     }
1778     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1779                                           put->mask, put->mask_len,
1780                                           &match.flow, &match.wc.masks);
1781     if (error) {
1782         return error;
1783     }
1784
1785     /* Must produce a netdev_flow_key for lookup.
1786      * This interface is no longer performance critical, since it is not used
1787      * for upcall processing any more. */
1788     netdev_flow_key_from_flow(&key, &match.flow);
1789
1790     ovs_mutex_lock(&dp->flow_mutex);
1791     netdev_flow = dp_netdev_lookup_flow(dp, &key);
1792     if (!netdev_flow) {
1793         if (put->flags & DPIF_FP_CREATE) {
1794             if (cmap_count(&dp->flow_table) < MAX_FLOWS) {
1795                 if (put->stats) {
1796                     memset(put->stats, 0, sizeof *put->stats);
1797                 }
1798                 dp_netdev_flow_add(dp, &match, put->actions, put->actions_len);
1799                 error = 0;
1800             } else {
1801                 error = EFBIG;
1802             }
1803         } else {
1804             error = ENOENT;
1805         }
1806     } else {
1807         if (put->flags & DPIF_FP_MODIFY
1808             && flow_equal(&match.flow, &netdev_flow->flow)) {
1809             struct dp_netdev_actions *new_actions;
1810             struct dp_netdev_actions *old_actions;
1811
1812             new_actions = dp_netdev_actions_create(put->actions,
1813                                                    put->actions_len);
1814
1815             old_actions = dp_netdev_flow_get_actions(netdev_flow);
1816             ovsrcu_set(&netdev_flow->actions, new_actions);
1817
1818             if (put->stats) {
1819                 get_dpif_flow_stats(netdev_flow, put->stats);
1820             }
1821             if (put->flags & DPIF_FP_ZERO_STATS) {
1822                 clear_stats(netdev_flow);
1823             }
1824
1825             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
1826         } else if (put->flags & DPIF_FP_CREATE) {
1827             error = EEXIST;
1828         } else {
1829             /* Overlapping flow. */
1830             error = EINVAL;
1831         }
1832     }
1833     ovs_mutex_unlock(&dp->flow_mutex);
1834
1835     return error;
1836 }
1837
1838 static int
1839 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1840 {
1841     struct dp_netdev *dp = get_dp_netdev(dpif);
1842     struct dp_netdev_flow *netdev_flow;
1843     struct flow key;
1844     int error;
1845
1846     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1847     if (error) {
1848         return error;
1849     }
1850
1851     ovs_mutex_lock(&dp->flow_mutex);
1852     netdev_flow = dp_netdev_find_flow(dp, &key);
1853     if (netdev_flow) {
1854         if (del->stats) {
1855             get_dpif_flow_stats(netdev_flow, del->stats);
1856         }
1857         dp_netdev_remove_flow(dp, netdev_flow);
1858     } else {
1859         error = ENOENT;
1860     }
1861     ovs_mutex_unlock(&dp->flow_mutex);
1862
1863     return error;
1864 }
1865
1866 struct dpif_netdev_flow_dump {
1867     struct dpif_flow_dump up;
1868     struct cmap_position pos;
1869     int status;
1870     struct ovs_mutex mutex;
1871 };
1872
1873 static struct dpif_netdev_flow_dump *
1874 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
1875 {
1876     return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
1877 }
1878
1879 static struct dpif_flow_dump *
1880 dpif_netdev_flow_dump_create(const struct dpif *dpif_)
1881 {
1882     struct dpif_netdev_flow_dump *dump;
1883
1884     dump = xmalloc(sizeof *dump);
1885     dpif_flow_dump_init(&dump->up, dpif_);
1886     memset(&dump->pos, 0, sizeof dump->pos);
1887     dump->status = 0;
1888     ovs_mutex_init(&dump->mutex);
1889
1890     return &dump->up;
1891 }
1892
1893 static int
1894 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
1895 {
1896     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1897
1898     ovs_mutex_destroy(&dump->mutex);
1899     free(dump);
1900     return 0;
1901 }
1902
1903 struct dpif_netdev_flow_dump_thread {
1904     struct dpif_flow_dump_thread up;
1905     struct dpif_netdev_flow_dump *dump;
1906     struct odputil_keybuf keybuf[FLOW_DUMP_MAX_BATCH];
1907     struct odputil_keybuf maskbuf[FLOW_DUMP_MAX_BATCH];
1908 };
1909
1910 static struct dpif_netdev_flow_dump_thread *
1911 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1912 {
1913     return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
1914 }
1915
1916 static struct dpif_flow_dump_thread *
1917 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1918 {
1919     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1920     struct dpif_netdev_flow_dump_thread *thread;
1921
1922     thread = xmalloc(sizeof *thread);
1923     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1924     thread->dump = dump;
1925     return &thread->up;
1926 }
1927
1928 static void
1929 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1930 {
1931     struct dpif_netdev_flow_dump_thread *thread
1932         = dpif_netdev_flow_dump_thread_cast(thread_);
1933
1934     free(thread);
1935 }
1936
1937 static int
1938 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1939                            struct dpif_flow *flows, int max_flows)
1940 {
1941     struct dpif_netdev_flow_dump_thread *thread
1942         = dpif_netdev_flow_dump_thread_cast(thread_);
1943     struct dpif_netdev_flow_dump *dump = thread->dump;
1944     struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
1945     struct dp_netdev_flow *netdev_flows[FLOW_DUMP_MAX_BATCH];
1946     struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
1947     int n_flows = 0;
1948     int i;
1949
1950     ovs_mutex_lock(&dump->mutex);
1951     if (!dump->status) {
1952         for (n_flows = 0; n_flows < MIN(max_flows, FLOW_DUMP_MAX_BATCH);
1953              n_flows++) {
1954             struct cmap_node *node;
1955
1956             node = cmap_next_position(&dp->flow_table, &dump->pos);
1957             if (!node) {
1958                 dump->status = EOF;
1959                 break;
1960             }
1961             netdev_flows[n_flows] = CONTAINER_OF(node, struct dp_netdev_flow,
1962                                                  node);
1963         }
1964     }
1965     ovs_mutex_unlock(&dump->mutex);
1966
1967     for (i = 0; i < n_flows; i++) {
1968         struct odputil_keybuf *maskbuf = &thread->maskbuf[i];
1969         struct odputil_keybuf *keybuf = &thread->keybuf[i];
1970         struct dp_netdev_flow *netdev_flow = netdev_flows[i];
1971         struct dpif_flow *f = &flows[i];
1972         struct dp_netdev_actions *dp_actions;
1973         struct flow_wildcards wc;
1974         struct ofpbuf buf;
1975
1976         miniflow_expand(&netdev_flow->cr.mask->mf, &wc.masks);
1977
1978         /* Key. */
1979         ofpbuf_use_stack(&buf, keybuf, sizeof *keybuf);
1980         odp_flow_key_from_flow(&buf, &netdev_flow->flow, &wc.masks,
1981                                netdev_flow->flow.in_port.odp_port, true);
1982         f->key = ofpbuf_data(&buf);
1983         f->key_len = ofpbuf_size(&buf);
1984
1985         /* Mask. */
1986         ofpbuf_use_stack(&buf, maskbuf, sizeof *maskbuf);
1987         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1988                                odp_to_u32(wc.masks.in_port.odp_port),
1989                                SIZE_MAX, true);
1990         f->mask = ofpbuf_data(&buf);
1991         f->mask_len = ofpbuf_size(&buf);
1992
1993         /* Actions. */
1994         dp_actions = dp_netdev_flow_get_actions(netdev_flow);
1995         f->actions = dp_actions->actions;
1996         f->actions_len = dp_actions->size;
1997
1998         /* Stats. */
1999         get_dpif_flow_stats(netdev_flow, &f->stats);
2000     }
2001
2002     return n_flows;
2003 }
2004
2005 static int
2006 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
2007     OVS_NO_THREAD_SAFETY_ANALYSIS
2008 {
2009     struct dp_netdev *dp = get_dp_netdev(dpif);
2010     struct dp_netdev_pmd_thread *pmd;
2011     struct dpif_packet packet, *pp;
2012
2013     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
2014         ofpbuf_size(execute->packet) > UINT16_MAX) {
2015         return EINVAL;
2016     }
2017
2018     packet.ofpbuf = *execute->packet;
2019     packet.md = execute->md;
2020     pp = &packet;
2021
2022     /* Tries finding the 'pmd'.  If NULL is returned, that means
2023      * the current thread is a non-pmd thread and should use
2024      * dp_netdev_get_nonpmd(). */
2025     pmd = ovsthread_getspecific(dp->per_pmd_key);
2026     if (!pmd) {
2027         pmd = dp_netdev_get_nonpmd(dp);
2028     }
2029
2030     /* If the current thread is non-pmd thread, acquires
2031      * the 'non_pmd_mutex'. */
2032     if (pmd->core_id == NON_PMD_CORE_ID) {
2033         ovs_mutex_lock(&dp->non_pmd_mutex);
2034     }
2035     dp_netdev_execute_actions(pmd, &pp, 1, false, execute->actions,
2036                               execute->actions_len);
2037     if (pmd->core_id == NON_PMD_CORE_ID) {
2038         ovs_mutex_unlock(&dp->non_pmd_mutex);
2039     }
2040
2041     /* Even though may_steal is set to false, some actions could modify or
2042      * reallocate the ofpbuf memory. We need to pass those changes to the
2043      * caller */
2044     *execute->packet = packet.ofpbuf;
2045     execute->md = packet.md;
2046     return 0;
2047 }
2048
2049 static void
2050 dpif_netdev_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
2051 {
2052     size_t i;
2053
2054     for (i = 0; i < n_ops; i++) {
2055         struct dpif_op *op = ops[i];
2056
2057         switch (op->type) {
2058         case DPIF_OP_FLOW_PUT:
2059             op->error = dpif_netdev_flow_put(dpif, &op->u.flow_put);
2060             break;
2061
2062         case DPIF_OP_FLOW_DEL:
2063             op->error = dpif_netdev_flow_del(dpif, &op->u.flow_del);
2064             break;
2065
2066         case DPIF_OP_EXECUTE:
2067             op->error = dpif_netdev_execute(dpif, &op->u.execute);
2068             break;
2069
2070         case DPIF_OP_FLOW_GET:
2071             op->error = dpif_netdev_flow_get(dpif, &op->u.flow_get);
2072             break;
2073         }
2074     }
2075 }
2076
2077 /* Returns true if the configuration for rx queues or cpu mask
2078  * is changed. */
2079 static bool
2080 pmd_config_changed(const struct dp_netdev *dp, size_t rxqs, const char *cmask)
2081 {
2082     if (dp->n_dpdk_rxqs != rxqs) {
2083         return true;
2084     } else {
2085         if (dp->pmd_cmask != NULL && cmask != NULL) {
2086             return strcmp(dp->pmd_cmask, cmask);
2087         } else {
2088             return (dp->pmd_cmask != NULL || cmask != NULL);
2089         }
2090     }
2091 }
2092
2093 /* Resets pmd threads if the configuration for 'rxq's or cpu mask changes. */
2094 static int
2095 dpif_netdev_pmd_set(struct dpif *dpif, unsigned int n_rxqs, const char *cmask)
2096 {
2097     struct dp_netdev *dp = get_dp_netdev(dpif);
2098
2099     if (pmd_config_changed(dp, n_rxqs, cmask)) {
2100         struct dp_netdev_port *port;
2101
2102         dp_netdev_destroy_all_pmds(dp);
2103
2104         CMAP_FOR_EACH (port, node, &dp->ports) {
2105             if (netdev_is_pmd(port->netdev)) {
2106                 int i, err;
2107
2108                 /* Closes the existing 'rxq's. */
2109                 for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2110                     netdev_rxq_close(port->rxq[i]);
2111                     port->rxq[i] = NULL;
2112                 }
2113
2114                 /* Sets the new rx queue config.  */
2115                 err = netdev_set_multiq(port->netdev, ovs_numa_get_n_cores(),
2116                                         n_rxqs);
2117                 if (err && (err != EOPNOTSUPP)) {
2118                     VLOG_ERR("Failed to set dpdk interface %s rx_queue to:"
2119                              " %u", netdev_get_name(port->netdev),
2120                              n_rxqs);
2121                     return err;
2122                 }
2123
2124                 /* If the set_multiq() above succeeds, reopens the 'rxq's. */
2125                 port->rxq = xrealloc(port->rxq, sizeof *port->rxq
2126                                      * netdev_n_rxq(port->netdev));
2127                 for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2128                     netdev_rxq_open(port->netdev, &port->rxq[i], i);
2129                 }
2130             }
2131         }
2132         dp->n_dpdk_rxqs = n_rxqs;
2133
2134         /* Reconfigures the cpu mask. */
2135         ovs_numa_set_cpu_mask(cmask);
2136         free(dp->pmd_cmask);
2137         dp->pmd_cmask = cmask ? xstrdup(cmask) : NULL;
2138
2139         /* Restores the non-pmd. */
2140         dp_netdev_set_nonpmd(dp);
2141         /* Restores all pmd threads. */
2142         dp_netdev_reset_pmd_threads(dp);
2143     }
2144
2145     return 0;
2146 }
2147
2148 static int
2149 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
2150                               uint32_t queue_id, uint32_t *priority)
2151 {
2152     *priority = queue_id;
2153     return 0;
2154 }
2155
2156 \f
2157 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
2158  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
2159  * 'ofpacts'. */
2160 struct dp_netdev_actions *
2161 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
2162 {
2163     struct dp_netdev_actions *netdev_actions;
2164
2165     netdev_actions = xmalloc(sizeof *netdev_actions);
2166     netdev_actions->actions = xmemdup(actions, size);
2167     netdev_actions->size = size;
2168
2169     return netdev_actions;
2170 }
2171
2172 struct dp_netdev_actions *
2173 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
2174 {
2175     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
2176 }
2177
2178 static void
2179 dp_netdev_actions_free(struct dp_netdev_actions *actions)
2180 {
2181     free(actions->actions);
2182     free(actions);
2183 }
2184 \f
2185
2186 static void
2187 dp_netdev_process_rxq_port(struct dp_netdev_pmd_thread *pmd,
2188                            struct dp_netdev_port *port,
2189                            struct netdev_rxq *rxq)
2190 {
2191     struct dpif_packet *packets[NETDEV_MAX_RX_BATCH];
2192     int error, cnt;
2193
2194     error = netdev_rxq_recv(rxq, packets, &cnt);
2195     if (!error) {
2196         int i;
2197
2198         *recirc_depth_get() = 0;
2199
2200         /* XXX: initialize md in netdev implementation. */
2201         for (i = 0; i < cnt; i++) {
2202             packets[i]->md = PKT_METADATA_INITIALIZER(port->port_no);
2203         }
2204         dp_netdev_input(pmd, packets, cnt);
2205     } else if (error != EAGAIN && error != EOPNOTSUPP) {
2206         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2207
2208         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
2209                     netdev_get_name(port->netdev), ovs_strerror(error));
2210     }
2211 }
2212
2213 /* Return true if needs to revalidate datapath flows. */
2214 static bool
2215 dpif_netdev_run(struct dpif *dpif)
2216 {
2217     struct dp_netdev_port *port;
2218     struct dp_netdev *dp = get_dp_netdev(dpif);
2219     struct dp_netdev_pmd_thread *non_pmd = dp_netdev_get_nonpmd(dp);
2220     uint64_t new_tnl_seq;
2221
2222     ovs_mutex_lock(&dp->non_pmd_mutex);
2223     CMAP_FOR_EACH (port, node, &dp->ports) {
2224         if (!netdev_is_pmd(port->netdev)) {
2225             int i;
2226
2227             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2228                 dp_netdev_process_rxq_port(non_pmd, port, port->rxq[i]);
2229             }
2230         }
2231     }
2232     ovs_mutex_unlock(&dp->non_pmd_mutex);
2233     tnl_arp_cache_run();
2234     new_tnl_seq = seq_read(tnl_conf_seq);
2235
2236     if (dp->last_tnl_conf_seq != new_tnl_seq) {
2237         dp->last_tnl_conf_seq = new_tnl_seq;
2238         return true;
2239     }
2240     return false;
2241 }
2242
2243 static void
2244 dpif_netdev_wait(struct dpif *dpif)
2245 {
2246     struct dp_netdev_port *port;
2247     struct dp_netdev *dp = get_dp_netdev(dpif);
2248
2249     ovs_mutex_lock(&dp_netdev_mutex);
2250     CMAP_FOR_EACH (port, node, &dp->ports) {
2251         if (!netdev_is_pmd(port->netdev)) {
2252             int i;
2253
2254             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2255                 netdev_rxq_wait(port->rxq[i]);
2256             }
2257         }
2258     }
2259     ovs_mutex_unlock(&dp_netdev_mutex);
2260     seq_wait(tnl_conf_seq, dp->last_tnl_conf_seq);
2261 }
2262
2263 struct rxq_poll {
2264     struct dp_netdev_port *port;
2265     struct netdev_rxq *rx;
2266 };
2267
2268 static int
2269 pmd_load_queues(struct dp_netdev_pmd_thread *pmd,
2270                 struct rxq_poll **ppoll_list, int poll_cnt)
2271 {
2272     struct rxq_poll *poll_list = *ppoll_list;
2273     struct dp_netdev_port *port;
2274     int n_pmds_on_numa, index, i;
2275
2276     /* Simple scheduler for netdev rx polling. */
2277     for (i = 0; i < poll_cnt; i++) {
2278         port_unref(poll_list[i].port);
2279     }
2280
2281     poll_cnt = 0;
2282     n_pmds_on_numa = get_n_pmd_threads_on_numa(pmd->dp, pmd->numa_id);
2283     index = 0;
2284
2285     CMAP_FOR_EACH (port, node, &pmd->dp->ports) {
2286         /* Calls port_try_ref() to prevent the main thread
2287          * from deleting the port. */
2288         if (port_try_ref(port)) {
2289             if (netdev_is_pmd(port->netdev)
2290                 && netdev_get_numa_id(port->netdev) == pmd->numa_id) {
2291                 int i;
2292
2293                 for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2294                     if ((index % n_pmds_on_numa) == pmd->index) {
2295                         poll_list = xrealloc(poll_list,
2296                                         sizeof *poll_list * (poll_cnt + 1));
2297
2298                         port_ref(port);
2299                         poll_list[poll_cnt].port = port;
2300                         poll_list[poll_cnt].rx = port->rxq[i];
2301                         poll_cnt++;
2302                     }
2303                     index++;
2304                 }
2305             }
2306             /* Unrefs the port_try_ref(). */
2307             port_unref(port);
2308         }
2309     }
2310
2311     *ppoll_list = poll_list;
2312     return poll_cnt;
2313 }
2314
2315 static void *
2316 pmd_thread_main(void *f_)
2317 {
2318     struct dp_netdev_pmd_thread *pmd = f_;
2319     unsigned int lc = 0;
2320     struct rxq_poll *poll_list;
2321     unsigned int port_seq = PMD_INITIAL_SEQ;
2322     int poll_cnt;
2323     int i;
2324
2325     poll_cnt = 0;
2326     poll_list = NULL;
2327
2328     /* Stores the pmd thread's 'pmd' to 'per_pmd_key'. */
2329     ovsthread_setspecific(pmd->dp->per_pmd_key, pmd);
2330     pmd_thread_setaffinity_cpu(pmd->core_id);
2331 reload:
2332     emc_cache_init(&pmd->flow_cache);
2333     poll_cnt = pmd_load_queues(pmd, &poll_list, poll_cnt);
2334
2335     /* Signal here to make sure the pmd finishes
2336      * reloading the updated configuration. */
2337     dp_netdev_pmd_reload_done(pmd);
2338
2339     for (;;) {
2340         int i;
2341
2342         for (i = 0; i < poll_cnt; i++) {
2343             dp_netdev_process_rxq_port(pmd, poll_list[i].port, poll_list[i].rx);
2344         }
2345
2346         if (lc++ > 1024) {
2347             unsigned int seq;
2348
2349             lc = 0;
2350
2351             emc_cache_slow_sweep(&pmd->flow_cache);
2352             ovsrcu_quiesce();
2353
2354             atomic_read_relaxed(&pmd->change_seq, &seq);
2355             if (seq != port_seq) {
2356                 port_seq = seq;
2357                 break;
2358             }
2359         }
2360     }
2361
2362     emc_cache_uninit(&pmd->flow_cache);
2363
2364     if (!latch_is_set(&pmd->exit_latch)){
2365         goto reload;
2366     }
2367
2368     for (i = 0; i < poll_cnt; i++) {
2369          port_unref(poll_list[i].port);
2370     }
2371
2372     dp_netdev_pmd_reload_done(pmd);
2373
2374     free(poll_list);
2375     return NULL;
2376 }
2377
2378 static void
2379 dp_netdev_disable_upcall(struct dp_netdev *dp)
2380     OVS_ACQUIRES(dp->upcall_rwlock)
2381 {
2382     fat_rwlock_wrlock(&dp->upcall_rwlock);
2383 }
2384
2385 static void
2386 dpif_netdev_disable_upcall(struct dpif *dpif)
2387     OVS_NO_THREAD_SAFETY_ANALYSIS
2388 {
2389     struct dp_netdev *dp = get_dp_netdev(dpif);
2390     dp_netdev_disable_upcall(dp);
2391 }
2392
2393 static void
2394 dp_netdev_enable_upcall(struct dp_netdev *dp)
2395     OVS_RELEASES(dp->upcall_rwlock)
2396 {
2397     fat_rwlock_unlock(&dp->upcall_rwlock);
2398 }
2399
2400 static void
2401 dpif_netdev_enable_upcall(struct dpif *dpif)
2402     OVS_NO_THREAD_SAFETY_ANALYSIS
2403 {
2404     struct dp_netdev *dp = get_dp_netdev(dpif);
2405     dp_netdev_enable_upcall(dp);
2406 }
2407
2408 void
2409 dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd)
2410 {
2411     ovs_mutex_lock(&pmd->cond_mutex);
2412     xpthread_cond_signal(&pmd->cond);
2413     ovs_mutex_unlock(&pmd->cond_mutex);
2414 }
2415
2416 /* Returns the pointer to the dp_netdev_pmd_thread for non-pmd threads. */
2417 static struct dp_netdev_pmd_thread *
2418 dp_netdev_get_nonpmd(struct dp_netdev *dp)
2419 {
2420     struct dp_netdev_pmd_thread *pmd;
2421     const struct cmap_node *pnode;
2422
2423     pnode = cmap_find(&dp->poll_threads, hash_int(NON_PMD_CORE_ID, 0));
2424     ovs_assert(pnode);
2425     pmd = CONTAINER_OF(pnode, struct dp_netdev_pmd_thread, node);
2426
2427     return pmd;
2428 }
2429
2430 /* Sets the 'struct dp_netdev_pmd_thread' for non-pmd threads. */
2431 static void
2432 dp_netdev_set_nonpmd(struct dp_netdev *dp)
2433 {
2434     struct dp_netdev_pmd_thread *non_pmd;
2435
2436     non_pmd = xzalloc(sizeof *non_pmd);
2437     dp_netdev_configure_pmd(non_pmd, dp, 0, NON_PMD_CORE_ID,
2438                             OVS_NUMA_UNSPEC);
2439 }
2440
2441 /* Configures the 'pmd' based on the input argument. */
2442 static void
2443 dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd, struct dp_netdev *dp,
2444                         int index, int core_id, int numa_id)
2445 {
2446     pmd->dp = dp;
2447     pmd->index = index;
2448     pmd->core_id = core_id;
2449     pmd->numa_id = numa_id;
2450     latch_init(&pmd->exit_latch);
2451     atomic_init(&pmd->change_seq, PMD_INITIAL_SEQ);
2452     xpthread_cond_init(&pmd->cond, NULL);
2453     ovs_mutex_init(&pmd->cond_mutex);
2454     /* init the 'flow_cache' since there is no
2455      * actual thread created for NON_PMD_CORE_ID. */
2456     if (core_id == NON_PMD_CORE_ID) {
2457         emc_cache_init(&pmd->flow_cache);
2458     }
2459     cmap_insert(&dp->poll_threads, CONST_CAST(struct cmap_node *, &pmd->node),
2460                 hash_int(core_id, 0));
2461 }
2462
2463 /* Stops the pmd thread, removes it from the 'dp->poll_threads'
2464  * and destroys the struct. */
2465 static void
2466 dp_netdev_del_pmd(struct dp_netdev_pmd_thread *pmd)
2467 {
2468     /* Uninit the 'flow_cache' since there is
2469      * no actual thread uninit it. */
2470     if (pmd->core_id == NON_PMD_CORE_ID) {
2471         emc_cache_uninit(&pmd->flow_cache);
2472     } else {
2473         latch_set(&pmd->exit_latch);
2474         dp_netdev_reload_pmd__(pmd);
2475         ovs_numa_unpin_core(pmd->core_id);
2476         xpthread_join(pmd->thread, NULL);
2477     }
2478     cmap_remove(&pmd->dp->poll_threads, &pmd->node, hash_int(pmd->core_id, 0));
2479     latch_destroy(&pmd->exit_latch);
2480     xpthread_cond_destroy(&pmd->cond);
2481     ovs_mutex_destroy(&pmd->cond_mutex);
2482     free(pmd);
2483 }
2484
2485 /* Destroys all pmd threads. */
2486 static void
2487 dp_netdev_destroy_all_pmds(struct dp_netdev *dp)
2488 {
2489     struct dp_netdev_pmd_thread *pmd;
2490
2491     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2492         dp_netdev_del_pmd(pmd);
2493     }
2494 }
2495
2496 /* Deletes all pmd threads on numa node 'numa_id'. */
2497 static void
2498 dp_netdev_del_pmds_on_numa(struct dp_netdev *dp, int numa_id)
2499 {
2500     struct dp_netdev_pmd_thread *pmd;
2501
2502     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2503         if (pmd->numa_id == numa_id) {
2504             dp_netdev_del_pmd(pmd);
2505         }
2506     }
2507 }
2508
2509 /* Checks the numa node id of 'netdev' and starts pmd threads for
2510  * the numa node. */
2511 static void
2512 dp_netdev_set_pmds_on_numa(struct dp_netdev *dp, int numa_id)
2513 {
2514     int n_pmds;
2515
2516     if (!ovs_numa_numa_id_is_valid(numa_id)) {
2517         VLOG_ERR("Cannot create pmd threads due to numa id (%d)"
2518                  "invalid", numa_id);
2519         return ;
2520     }
2521
2522     n_pmds = get_n_pmd_threads_on_numa(dp, numa_id);
2523
2524     /* If there are already pmd threads created for the numa node
2525      * in which 'netdev' is on, do nothing.  Else, creates the
2526      * pmd threads for the numa node. */
2527     if (!n_pmds) {
2528         int can_have, n_unpinned, i;
2529
2530         n_unpinned = ovs_numa_get_n_unpinned_cores_on_numa(numa_id);
2531         if (!n_unpinned) {
2532             VLOG_ERR("Cannot create pmd threads due to out of unpinned "
2533                      "cores on numa node");
2534             return;
2535         }
2536
2537         /* If cpu mask is specified, uses all unpinned cores, otherwise
2538          * tries creating NR_PMD_THREADS pmd threads. */
2539         can_have = dp->pmd_cmask ? n_unpinned : MIN(n_unpinned, NR_PMD_THREADS);
2540         for (i = 0; i < can_have; i++) {
2541             struct dp_netdev_pmd_thread *pmd = xzalloc(sizeof *pmd);
2542             int core_id = ovs_numa_get_unpinned_core_on_numa(numa_id);
2543
2544             dp_netdev_configure_pmd(pmd, dp, i, core_id, numa_id);
2545             /* Each thread will distribute all devices rx-queues among
2546              * themselves. */
2547             pmd->thread = ovs_thread_create("pmd", pmd_thread_main, pmd);
2548         }
2549         VLOG_INFO("Created %d pmd threads on numa node %d", can_have, numa_id);
2550     }
2551 }
2552
2553 \f
2554 static void *
2555 dp_netdev_flow_stats_new_cb(void)
2556 {
2557     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2558     ovs_mutex_init(&bucket->mutex);
2559     return bucket;
2560 }
2561
2562 /* Called after pmd threads config change.  Restarts pmd threads with
2563  * new configuration. */
2564 static void
2565 dp_netdev_reset_pmd_threads(struct dp_netdev *dp)
2566 {
2567     struct dp_netdev_port *port;
2568
2569     CMAP_FOR_EACH (port, node, &dp->ports) {
2570         if (netdev_is_pmd(port->netdev)) {
2571             int numa_id = netdev_get_numa_id(port->netdev);
2572
2573             dp_netdev_set_pmds_on_numa(dp, numa_id);
2574         }
2575     }
2576 }
2577
2578 static char *
2579 dpif_netdev_get_datapath_version(void)
2580 {
2581      return xstrdup("<built-in>");
2582 }
2583
2584 static void
2585 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
2586                     int cnt, int size,
2587                     uint16_t tcp_flags)
2588 {
2589     long long int now = time_msec();
2590     struct dp_netdev_flow_stats *bucket;
2591
2592     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
2593                                         dp_netdev_flow_stats_new_cb);
2594
2595     ovs_mutex_lock(&bucket->mutex);
2596     bucket->used = MAX(now, bucket->used);
2597     bucket->packet_count += cnt;
2598     bucket->byte_count += size;
2599     bucket->tcp_flags |= tcp_flags;
2600     ovs_mutex_unlock(&bucket->mutex);
2601 }
2602
2603 static void *
2604 dp_netdev_stats_new_cb(void)
2605 {
2606     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2607     ovs_mutex_init(&bucket->mutex);
2608     return bucket;
2609 }
2610
2611 static void
2612 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type, int cnt)
2613 {
2614     struct dp_netdev_stats *bucket;
2615
2616     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
2617     ovs_mutex_lock(&bucket->mutex);
2618     bucket->n[type] += cnt;
2619     ovs_mutex_unlock(&bucket->mutex);
2620 }
2621
2622 static int
2623 dp_netdev_upcall(struct dp_netdev *dp, struct dpif_packet *packet_,
2624                  struct flow *flow, struct flow_wildcards *wc,
2625                  enum dpif_upcall_type type, const struct nlattr *userdata,
2626                  struct ofpbuf *actions, struct ofpbuf *put_actions)
2627 {
2628     struct ofpbuf *packet = &packet_->ofpbuf;
2629
2630     if (type == DPIF_UC_MISS) {
2631         dp_netdev_count_packet(dp, DP_STAT_MISS, 1);
2632     }
2633
2634     if (OVS_UNLIKELY(!dp->upcall_cb)) {
2635         return ENODEV;
2636     }
2637
2638     if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
2639         struct ds ds = DS_EMPTY_INITIALIZER;
2640         struct ofpbuf key;
2641         char *packet_str;
2642
2643         ofpbuf_init(&key, 0);
2644         odp_flow_key_from_flow(&key, flow, &wc->masks, flow->in_port.odp_port,
2645                                true);
2646
2647         packet_str = ofp_packet_to_string(ofpbuf_data(packet),
2648                                           ofpbuf_size(packet));
2649
2650         odp_flow_key_format(ofpbuf_data(&key), ofpbuf_size(&key), &ds);
2651
2652         VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
2653                  dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
2654
2655         ofpbuf_uninit(&key);
2656         free(packet_str);
2657         ds_destroy(&ds);
2658     }
2659
2660     return dp->upcall_cb(packet, flow, type, userdata, actions, wc,
2661                          put_actions, dp->upcall_aux);
2662 }
2663
2664 static inline uint32_t
2665 dpif_netdev_packet_get_dp_hash(struct dpif_packet *packet,
2666                                const struct miniflow *mf)
2667 {
2668     uint32_t hash;
2669
2670     hash = dpif_packet_get_dp_hash(packet);
2671     if (OVS_UNLIKELY(!hash)) {
2672         hash = miniflow_hash_5tuple(mf, 0);
2673         dpif_packet_set_dp_hash(packet, hash);
2674     }
2675     return hash;
2676 }
2677
2678 struct packet_batch {
2679     unsigned int packet_count;
2680     unsigned int byte_count;
2681     uint16_t tcp_flags;
2682
2683     struct dp_netdev_flow *flow;
2684
2685     struct dpif_packet *packets[NETDEV_MAX_RX_BATCH];
2686 };
2687
2688 static inline void
2689 packet_batch_update(struct packet_batch *batch, struct dpif_packet *packet,
2690                     const struct miniflow *mf)
2691 {
2692     batch->tcp_flags |= miniflow_get_tcp_flags(mf);
2693     batch->packets[batch->packet_count++] = packet;
2694     batch->byte_count += ofpbuf_size(&packet->ofpbuf);
2695 }
2696
2697 static inline void
2698 packet_batch_init(struct packet_batch *batch, struct dp_netdev_flow *flow)
2699 {
2700     batch->flow = flow;
2701
2702     batch->packet_count = 0;
2703     batch->byte_count = 0;
2704     batch->tcp_flags = 0;
2705 }
2706
2707 static inline void
2708 packet_batch_execute(struct packet_batch *batch,
2709                      struct dp_netdev_pmd_thread *pmd)
2710 {
2711     struct dp_netdev_actions *actions;
2712     struct dp_netdev_flow *flow = batch->flow;
2713
2714     dp_netdev_flow_used(batch->flow, batch->packet_count, batch->byte_count,
2715                         batch->tcp_flags);
2716
2717     actions = dp_netdev_flow_get_actions(flow);
2718
2719     dp_netdev_execute_actions(pmd, batch->packets, batch->packet_count, true,
2720                               actions->actions, actions->size);
2721
2722     dp_netdev_count_packet(pmd->dp, DP_STAT_HIT, batch->packet_count);
2723 }
2724
2725 static inline bool
2726 dp_netdev_queue_batches(struct dpif_packet *pkt,
2727                         struct dp_netdev_flow *flow, const struct miniflow *mf,
2728                         struct packet_batch *batches, size_t *n_batches,
2729                         size_t max_batches)
2730 {
2731     struct packet_batch *batch = NULL;
2732     int j;
2733
2734     if (OVS_UNLIKELY(!flow)) {
2735         return false;
2736     }
2737     /* XXX: This O(n^2) algortihm makes sense if we're operating under the
2738      * assumption that the number of distinct flows (and therefore the
2739      * number of distinct batches) is quite small.  If this turns out not
2740      * to be the case, it may make sense to pre sort based on the
2741      * netdev_flow pointer.  That done we can get the appropriate batching
2742      * in O(n * log(n)) instead. */
2743     for (j = *n_batches - 1; j >= 0; j--) {
2744         if (batches[j].flow == flow) {
2745             batch = &batches[j];
2746             packet_batch_update(batch, pkt, mf);
2747             return true;
2748         }
2749     }
2750     if (OVS_UNLIKELY(*n_batches >= max_batches)) {
2751         return false;
2752     }
2753
2754     batch = &batches[(*n_batches)++];
2755     packet_batch_init(batch, flow);
2756     packet_batch_update(batch, pkt, mf);
2757     return true;
2758 }
2759
2760 static inline void
2761 dpif_packet_swap(struct dpif_packet **a, struct dpif_packet **b)
2762 {
2763     struct dpif_packet *tmp = *a;
2764     *a = *b;
2765     *b = tmp;
2766 }
2767
2768 /* Try to process all ('cnt') the 'packets' using only the exact match cache
2769  * 'flow_cache'. If a flow is not found for a packet 'packets[i]', or if there
2770  * is no matching batch for a packet's flow, the miniflow is copied into 'keys'
2771  * and the packet pointer is moved at the beginning of the 'packets' array.
2772  *
2773  * The function returns the number of packets that needs to be processed in the
2774  * 'packets' array (they have been moved to the beginning of the vector).
2775  */
2776 static inline size_t
2777 emc_processing(struct dp_netdev_pmd_thread *pmd, struct dpif_packet **packets,
2778                size_t cnt, struct netdev_flow_key *keys)
2779 {
2780     struct netdev_flow_key key;
2781     struct packet_batch batches[4];
2782     struct emc_cache *flow_cache = &pmd->flow_cache;
2783     size_t n_batches, i;
2784     size_t notfound_cnt = 0;
2785
2786     n_batches = 0;
2787     miniflow_initialize(&key.mf, key.buf);
2788     for (i = 0; i < cnt; i++) {
2789         struct dp_netdev_flow *flow;
2790
2791         if (OVS_UNLIKELY(ofpbuf_size(&packets[i]->ofpbuf) < ETH_HEADER_LEN)) {
2792             dpif_packet_delete(packets[i]);
2793             continue;
2794         }
2795
2796         miniflow_extract(&packets[i]->ofpbuf, &packets[i]->md, &key.mf);
2797         key.len = 0; /* Not computed yet. */
2798         key.hash = dpif_netdev_packet_get_dp_hash(packets[i], &key.mf);
2799
2800         flow = emc_lookup(flow_cache, &key);
2801         if (OVS_UNLIKELY(!dp_netdev_queue_batches(packets[i], flow, &key.mf,
2802                                                   batches, &n_batches,
2803                                                   ARRAY_SIZE(batches)))) {
2804             if (i != notfound_cnt) {
2805                 dpif_packet_swap(&packets[i], &packets[notfound_cnt]);
2806             }
2807
2808             keys[notfound_cnt++] = key;
2809         }
2810     }
2811
2812     for (i = 0; i < n_batches; i++) {
2813         packet_batch_execute(&batches[i], pmd);
2814     }
2815
2816     return notfound_cnt;
2817 }
2818
2819 static inline void
2820 fast_path_processing(struct dp_netdev_pmd_thread *pmd,
2821                      struct dpif_packet **packets, size_t cnt,
2822                      struct netdev_flow_key *keys)
2823 {
2824 #if !defined(__CHECKER__) && !defined(_WIN32)
2825     const size_t PKT_ARRAY_SIZE = cnt;
2826 #else
2827     /* Sparse or MSVC doesn't like variable length array. */
2828     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2829 #endif
2830     struct packet_batch batches[PKT_ARRAY_SIZE];
2831     struct dpcls_rule *rules[PKT_ARRAY_SIZE];
2832     struct dp_netdev *dp = pmd->dp;
2833     struct emc_cache *flow_cache = &pmd->flow_cache;
2834     size_t n_batches, i;
2835     bool any_miss;
2836
2837     for (i = 0; i < cnt; i++) {
2838         /* Key length is needed in all the cases, hash computed on demand. */
2839         keys[i].len = netdev_flow_key_size(count_1bits(keys[i].mf.map));
2840     }
2841     any_miss = !dpcls_lookup(&dp->cls, keys, rules, cnt);
2842     if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
2843         uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
2844         struct ofpbuf actions, put_actions;
2845
2846         ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
2847         ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
2848
2849         for (i = 0; i < cnt; i++) {
2850             struct dp_netdev_flow *netdev_flow;
2851             struct ofpbuf *add_actions;
2852             struct match match;
2853             int error;
2854
2855             if (OVS_LIKELY(rules[i])) {
2856                 continue;
2857             }
2858
2859             /* It's possible that an earlier slow path execution installed
2860              * a rule covering this flow.  In this case, it's a lot cheaper
2861              * to catch it here than execute a miss. */
2862             netdev_flow = dp_netdev_lookup_flow(dp, &keys[i]);
2863             if (netdev_flow) {
2864                 rules[i] = &netdev_flow->cr;
2865                 continue;
2866             }
2867
2868             miniflow_expand(&keys[i].mf, &match.flow);
2869
2870             ofpbuf_clear(&actions);
2871             ofpbuf_clear(&put_actions);
2872
2873             error = dp_netdev_upcall(dp, packets[i], &match.flow, &match.wc,
2874                                      DPIF_UC_MISS, NULL, &actions,
2875                                      &put_actions);
2876             if (OVS_UNLIKELY(error && error != ENOSPC)) {
2877                 continue;
2878             }
2879
2880             /* We can't allow the packet batching in the next loop to execute
2881              * the actions.  Otherwise, if there are any slow path actions,
2882              * we'll send the packet up twice. */
2883             dp_netdev_execute_actions(pmd, &packets[i], 1, true,
2884                                       ofpbuf_data(&actions),
2885                                       ofpbuf_size(&actions));
2886
2887             add_actions = ofpbuf_size(&put_actions)
2888                 ? &put_actions
2889                 : &actions;
2890
2891             if (OVS_LIKELY(error != ENOSPC)) {
2892                 /* XXX: There's a race window where a flow covering this packet
2893                  * could have already been installed since we last did the flow
2894                  * lookup before upcall.  This could be solved by moving the
2895                  * mutex lock outside the loop, but that's an awful long time
2896                  * to be locking everyone out of making flow installs.  If we
2897                  * move to a per-core classifier, it would be reasonable. */
2898                 ovs_mutex_lock(&dp->flow_mutex);
2899                 netdev_flow = dp_netdev_lookup_flow(dp, &keys[i]);
2900                 if (OVS_LIKELY(!netdev_flow)) {
2901                     netdev_flow = dp_netdev_flow_add(dp, &match,
2902                                                      ofpbuf_data(add_actions),
2903                                                      ofpbuf_size(add_actions));
2904                 }
2905                 ovs_mutex_unlock(&dp->flow_mutex);
2906
2907                 emc_insert(flow_cache, &keys[i], netdev_flow);
2908             }
2909         }
2910
2911         ofpbuf_uninit(&actions);
2912         ofpbuf_uninit(&put_actions);
2913         fat_rwlock_unlock(&dp->upcall_rwlock);
2914     } else if (OVS_UNLIKELY(any_miss)) {
2915         int dropped_cnt = 0;
2916
2917         for (i = 0; i < cnt; i++) {
2918             if (OVS_UNLIKELY(!rules[i])) {
2919                 dpif_packet_delete(packets[i]);
2920                 dropped_cnt++;
2921             }
2922         }
2923
2924         dp_netdev_count_packet(dp, DP_STAT_LOST, dropped_cnt);
2925     }
2926
2927     n_batches = 0;
2928     for (i = 0; i < cnt; i++) {
2929         struct dpif_packet *packet = packets[i];
2930         struct dp_netdev_flow *flow;
2931
2932         if (OVS_UNLIKELY(!rules[i])) {
2933             continue;
2934         }
2935
2936         flow = dp_netdev_flow_cast(rules[i]);
2937
2938         emc_insert(flow_cache, &keys[i], flow);
2939         dp_netdev_queue_batches(packet, flow, &keys[i].mf, batches,
2940                                 &n_batches, ARRAY_SIZE(batches));
2941     }
2942
2943     for (i = 0; i < n_batches; i++) {
2944         packet_batch_execute(&batches[i], pmd);
2945     }
2946 }
2947
2948 static void
2949 dp_netdev_input(struct dp_netdev_pmd_thread *pmd,
2950                 struct dpif_packet **packets, int cnt)
2951 {
2952 #if !defined(__CHECKER__) && !defined(_WIN32)
2953     const size_t PKT_ARRAY_SIZE = cnt;
2954 #else
2955     /* Sparse or MSVC doesn't like variable length array. */
2956     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2957 #endif
2958     struct netdev_flow_key keys[PKT_ARRAY_SIZE];
2959     size_t newcnt;
2960
2961     newcnt = emc_processing(pmd, packets, cnt, keys);
2962     if (OVS_UNLIKELY(newcnt)) {
2963         fast_path_processing(pmd, packets, newcnt, keys);
2964     }
2965 }
2966
2967 struct dp_netdev_execute_aux {
2968     struct dp_netdev_pmd_thread *pmd;
2969 };
2970
2971 static void
2972 dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
2973                                void *aux)
2974 {
2975     struct dp_netdev *dp = get_dp_netdev(dpif);
2976     dp->upcall_aux = aux;
2977     dp->upcall_cb = cb;
2978 }
2979
2980 static void
2981 dp_netdev_drop_packets(struct dpif_packet ** packets, int cnt, bool may_steal)
2982 {
2983     if (may_steal) {
2984         int i;
2985
2986         for (i = 0; i < cnt; i++) {
2987             dpif_packet_delete(packets[i]);
2988         }
2989     }
2990 }
2991
2992 static int
2993 push_tnl_action(const struct dp_netdev *dp,
2994                    const struct nlattr *attr,
2995                    struct dpif_packet **packets, int cnt)
2996 {
2997     struct dp_netdev_port *tun_port;
2998     const struct ovs_action_push_tnl *data;
2999
3000     data = nl_attr_get(attr);
3001
3002     tun_port = dp_netdev_lookup_port(dp, u32_to_odp(data->tnl_port));
3003     if (!tun_port) {
3004         return -EINVAL;
3005     }
3006     netdev_push_header(tun_port->netdev, packets, cnt, data);
3007
3008     return 0;
3009 }
3010
3011 static void
3012 dp_netdev_clone_pkt_batch(struct dpif_packet **tnl_pkt,
3013                           struct dpif_packet **packets, int cnt)
3014 {
3015     int i;
3016
3017     for (i = 0; i < cnt; i++) {
3018         tnl_pkt[i] = dpif_packet_clone(packets[i]);
3019     }
3020 }
3021
3022 static void
3023 dp_execute_cb(void *aux_, struct dpif_packet **packets, int cnt,
3024               const struct nlattr *a, bool may_steal)
3025     OVS_NO_THREAD_SAFETY_ANALYSIS
3026 {
3027     struct dp_netdev_execute_aux *aux = aux_;
3028     uint32_t *depth = recirc_depth_get();
3029     struct dp_netdev_pmd_thread *pmd= aux->pmd;
3030     struct dp_netdev *dp= pmd->dp;
3031     int type = nl_attr_type(a);
3032     struct dp_netdev_port *p;
3033     int i;
3034
3035     switch ((enum ovs_action_attr)type) {
3036     case OVS_ACTION_ATTR_OUTPUT:
3037         p = dp_netdev_lookup_port(dp, u32_to_odp(nl_attr_get_u32(a)));
3038         if (OVS_LIKELY(p)) {
3039             netdev_send(p->netdev, pmd->core_id, packets, cnt, may_steal);
3040             return;
3041         }
3042         break;
3043
3044     case OVS_ACTION_ATTR_TUNNEL_PUSH:
3045         if (*depth < MAX_RECIRC_DEPTH) {
3046             struct dpif_packet *tnl_pkt[NETDEV_MAX_RX_BATCH];
3047             int err;
3048
3049             if (!may_steal) {
3050                 dp_netdev_clone_pkt_batch(tnl_pkt, packets, cnt);
3051                 packets = tnl_pkt;
3052             }
3053
3054             err = push_tnl_action(dp, a, packets, cnt);
3055             if (!err) {
3056                 (*depth)++;
3057                 dp_netdev_input(pmd, packets, cnt);
3058                 (*depth)--;
3059             } else {
3060                 dp_netdev_drop_packets(tnl_pkt, cnt, !may_steal);
3061             }
3062             return;
3063         }
3064         break;
3065
3066     case OVS_ACTION_ATTR_TUNNEL_POP:
3067         if (*depth < MAX_RECIRC_DEPTH) {
3068             odp_port_t portno = u32_to_odp(nl_attr_get_u32(a));
3069
3070             p = dp_netdev_lookup_port(dp, portno);
3071             if (p) {
3072                 struct dpif_packet *tnl_pkt[NETDEV_MAX_RX_BATCH];
3073                 int err;
3074
3075                 if (!may_steal) {
3076                    dp_netdev_clone_pkt_batch(tnl_pkt, packets, cnt);
3077                    packets = tnl_pkt;
3078                 }
3079
3080                 err = netdev_pop_header(p->netdev, packets, cnt);
3081                 if (!err) {
3082
3083                     for (i = 0; i < cnt; i++) {
3084                         packets[i]->md.in_port.odp_port = portno;
3085                     }
3086
3087                     (*depth)++;
3088                     dp_netdev_input(pmd, packets, cnt);
3089                     (*depth)--;
3090                 } else {
3091                     dp_netdev_drop_packets(tnl_pkt, cnt, !may_steal);
3092                 }
3093                 return;
3094             }
3095         }
3096         break;
3097
3098     case OVS_ACTION_ATTR_USERSPACE:
3099         if (!fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
3100             const struct nlattr *userdata;
3101             struct ofpbuf actions;
3102             struct flow flow;
3103
3104             userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
3105             ofpbuf_init(&actions, 0);
3106
3107             for (i = 0; i < cnt; i++) {
3108                 int error;
3109
3110                 ofpbuf_clear(&actions);
3111
3112                 flow_extract(&packets[i]->ofpbuf, &packets[i]->md, &flow);
3113                 error = dp_netdev_upcall(dp, packets[i], &flow, NULL,
3114                                          DPIF_UC_ACTION, userdata, &actions,
3115                                          NULL);
3116                 if (!error || error == ENOSPC) {
3117                     dp_netdev_execute_actions(pmd, &packets[i], 1, may_steal,
3118                                               ofpbuf_data(&actions),
3119                                               ofpbuf_size(&actions));
3120                 } else if (may_steal) {
3121                     dpif_packet_delete(packets[i]);
3122                 }
3123             }
3124             ofpbuf_uninit(&actions);
3125             fat_rwlock_unlock(&dp->upcall_rwlock);
3126
3127             return;
3128         }
3129         break;
3130
3131     case OVS_ACTION_ATTR_RECIRC:
3132         if (*depth < MAX_RECIRC_DEPTH) {
3133
3134             (*depth)++;
3135             for (i = 0; i < cnt; i++) {
3136                 struct dpif_packet *recirc_pkt;
3137
3138                 recirc_pkt = (may_steal) ? packets[i]
3139                                     : dpif_packet_clone(packets[i]);
3140
3141                 recirc_pkt->md.recirc_id = nl_attr_get_u32(a);
3142
3143                 /* Hash is private to each packet */
3144                 recirc_pkt->md.dp_hash = dpif_packet_get_dp_hash(packets[i]);
3145
3146                 dp_netdev_input(pmd, &recirc_pkt, 1);
3147             }
3148             (*depth)--;
3149
3150             return;
3151         }
3152
3153         VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
3154         break;
3155
3156     case OVS_ACTION_ATTR_PUSH_VLAN:
3157     case OVS_ACTION_ATTR_POP_VLAN:
3158     case OVS_ACTION_ATTR_PUSH_MPLS:
3159     case OVS_ACTION_ATTR_POP_MPLS:
3160     case OVS_ACTION_ATTR_SET:
3161     case OVS_ACTION_ATTR_SET_MASKED:
3162     case OVS_ACTION_ATTR_SAMPLE:
3163     case OVS_ACTION_ATTR_HASH:
3164     case OVS_ACTION_ATTR_UNSPEC:
3165     case __OVS_ACTION_ATTR_MAX:
3166         OVS_NOT_REACHED();
3167     }
3168
3169     dp_netdev_drop_packets(packets, cnt, may_steal);
3170 }
3171
3172 static void
3173 dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
3174                           struct dpif_packet **packets, int cnt,
3175                           bool may_steal,
3176                           const struct nlattr *actions, size_t actions_len)
3177 {
3178     struct dp_netdev_execute_aux aux = { pmd };
3179
3180     odp_execute_actions(&aux, packets, cnt, may_steal, actions,
3181                         actions_len, dp_execute_cb);
3182 }
3183
3184 const struct dpif_class dpif_netdev_class = {
3185     "netdev",
3186     dpif_netdev_enumerate,
3187     dpif_netdev_port_open_type,
3188     dpif_netdev_open,
3189     dpif_netdev_close,
3190     dpif_netdev_destroy,
3191     dpif_netdev_run,
3192     dpif_netdev_wait,
3193     dpif_netdev_get_stats,
3194     dpif_netdev_port_add,
3195     dpif_netdev_port_del,
3196     dpif_netdev_port_query_by_number,
3197     dpif_netdev_port_query_by_name,
3198     NULL,                       /* port_get_pid */
3199     dpif_netdev_port_dump_start,
3200     dpif_netdev_port_dump_next,
3201     dpif_netdev_port_dump_done,
3202     dpif_netdev_port_poll,
3203     dpif_netdev_port_poll_wait,
3204     dpif_netdev_flow_flush,
3205     dpif_netdev_flow_dump_create,
3206     dpif_netdev_flow_dump_destroy,
3207     dpif_netdev_flow_dump_thread_create,
3208     dpif_netdev_flow_dump_thread_destroy,
3209     dpif_netdev_flow_dump_next,
3210     dpif_netdev_operate,
3211     NULL,                       /* recv_set */
3212     NULL,                       /* handlers_set */
3213     dpif_netdev_pmd_set,
3214     dpif_netdev_queue_to_priority,
3215     NULL,                       /* recv */
3216     NULL,                       /* recv_wait */
3217     NULL,                       /* recv_purge */
3218     dpif_netdev_register_upcall_cb,
3219     dpif_netdev_enable_upcall,
3220     dpif_netdev_disable_upcall,
3221     dpif_netdev_get_datapath_version,
3222 };
3223
3224 static void
3225 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
3226                               const char *argv[], void *aux OVS_UNUSED)
3227 {
3228     struct dp_netdev_port *old_port;
3229     struct dp_netdev_port *new_port;
3230     struct dp_netdev *dp;
3231     odp_port_t port_no;
3232
3233     ovs_mutex_lock(&dp_netdev_mutex);
3234     dp = shash_find_data(&dp_netdevs, argv[1]);
3235     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
3236         ovs_mutex_unlock(&dp_netdev_mutex);
3237         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
3238         return;
3239     }
3240     ovs_refcount_ref(&dp->ref_cnt);
3241     ovs_mutex_unlock(&dp_netdev_mutex);
3242
3243     ovs_mutex_lock(&dp->port_mutex);
3244     if (get_port_by_name(dp, argv[2], &old_port)) {
3245         unixctl_command_reply_error(conn, "unknown port");
3246         goto exit;
3247     }
3248
3249     port_no = u32_to_odp(atoi(argv[3]));
3250     if (!port_no || port_no == ODPP_NONE) {
3251         unixctl_command_reply_error(conn, "bad port number");
3252         goto exit;
3253     }
3254     if (dp_netdev_lookup_port(dp, port_no)) {
3255         unixctl_command_reply_error(conn, "port number already in use");
3256         goto exit;
3257     }
3258
3259     /* Remove old port. */
3260     cmap_remove(&dp->ports, &old_port->node, hash_port_no(old_port->port_no));
3261     ovsrcu_postpone(free, old_port);
3262
3263     /* Insert new port (cmap semantics mean we cannot re-insert 'old_port'). */
3264     new_port = xmemdup(old_port, sizeof *old_port);
3265     new_port->port_no = port_no;
3266     cmap_insert(&dp->ports, &new_port->node, hash_port_no(port_no));
3267
3268     seq_change(dp->port_seq);
3269     unixctl_command_reply(conn, NULL);
3270
3271 exit:
3272     ovs_mutex_unlock(&dp->port_mutex);
3273     dp_netdev_unref(dp);
3274 }
3275
3276 static void
3277 dpif_dummy_delete_port(struct unixctl_conn *conn, int argc OVS_UNUSED,
3278                        const char *argv[], void *aux OVS_UNUSED)
3279 {
3280     struct dp_netdev_port *port;
3281     struct dp_netdev *dp;
3282
3283     ovs_mutex_lock(&dp_netdev_mutex);
3284     dp = shash_find_data(&dp_netdevs, argv[1]);
3285     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
3286         ovs_mutex_unlock(&dp_netdev_mutex);
3287         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
3288         return;
3289     }
3290     ovs_refcount_ref(&dp->ref_cnt);
3291     ovs_mutex_unlock(&dp_netdev_mutex);
3292
3293     ovs_mutex_lock(&dp->port_mutex);
3294     if (get_port_by_name(dp, argv[2], &port)) {
3295         unixctl_command_reply_error(conn, "unknown port");
3296     } else if (port->port_no == ODPP_LOCAL) {
3297         unixctl_command_reply_error(conn, "can't delete local port");
3298     } else {
3299         do_del_port(dp, port);
3300         unixctl_command_reply(conn, NULL);
3301     }
3302     ovs_mutex_unlock(&dp->port_mutex);
3303
3304     dp_netdev_unref(dp);
3305 }
3306
3307 static void
3308 dpif_dummy_register__(const char *type)
3309 {
3310     struct dpif_class *class;
3311
3312     class = xmalloc(sizeof *class);
3313     *class = dpif_netdev_class;
3314     class->type = xstrdup(type);
3315     dp_register_provider(class);
3316 }
3317
3318 void
3319 dpif_dummy_register(bool override)
3320 {
3321     if (override) {
3322         struct sset types;
3323         const char *type;
3324
3325         sset_init(&types);
3326         dp_enumerate_types(&types);
3327         SSET_FOR_EACH (type, &types) {
3328             if (!dp_unregister_provider(type)) {
3329                 dpif_dummy_register__(type);
3330             }
3331         }
3332         sset_destroy(&types);
3333     }
3334
3335     dpif_dummy_register__("dummy");
3336
3337     unixctl_command_register("dpif-dummy/change-port-number",
3338                              "dp port new-number",
3339                              3, 3, dpif_dummy_change_port_number, NULL);
3340     unixctl_command_register("dpif-dummy/delete-port", "dp port",
3341                              2, 2, dpif_dummy_delete_port, NULL);
3342 }
3343 \f
3344 /* Datapath Classifier. */
3345
3346 /* A set of rules that all have the same fields wildcarded. */
3347 struct dpcls_subtable {
3348     /* The fields are only used by writers. */
3349     struct cmap_node cmap_node OVS_GUARDED; /* Within dpcls 'subtables_map'. */
3350
3351     /* These fields are accessed by readers. */
3352     struct cmap rules;           /* Contains "struct dpcls_rule"s. */
3353     struct netdev_flow_key mask; /* Wildcards for fields (const). */
3354     /* 'mask' must be the last field, additional space is allocated here. */
3355 };
3356
3357 /* Initializes 'cls' as a classifier that initially contains no classification
3358  * rules. */
3359 static void
3360 dpcls_init(struct dpcls *cls)
3361 {
3362     cmap_init(&cls->subtables_map);
3363     pvector_init(&cls->subtables);
3364 }
3365
3366 static void
3367 dpcls_destroy_subtable(struct dpcls *cls, struct dpcls_subtable *subtable)
3368 {
3369     pvector_remove(&cls->subtables, subtable);
3370     cmap_remove(&cls->subtables_map, &subtable->cmap_node,
3371                 subtable->mask.hash);
3372     cmap_destroy(&subtable->rules);
3373     ovsrcu_postpone(free, subtable);
3374 }
3375
3376 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
3377  * caller's responsibility.
3378  * May only be called after all the readers have been terminated. */
3379 static void
3380 dpcls_destroy(struct dpcls *cls)
3381 {
3382     if (cls) {
3383         struct dpcls_subtable *subtable;
3384
3385         CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
3386             dpcls_destroy_subtable(cls, subtable);
3387         }
3388         cmap_destroy(&cls->subtables_map);
3389         pvector_destroy(&cls->subtables);
3390     }
3391 }
3392
3393 static struct dpcls_subtable *
3394 dpcls_create_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
3395 {
3396     struct dpcls_subtable *subtable;
3397
3398     /* Need to add one. */
3399     subtable = xmalloc(sizeof *subtable
3400                        - sizeof subtable->mask.mf + mask->len);
3401     cmap_init(&subtable->rules);
3402     netdev_flow_key_clone(&subtable->mask, mask);
3403     cmap_insert(&cls->subtables_map, &subtable->cmap_node, mask->hash);
3404     pvector_insert(&cls->subtables, subtable, 0);
3405     pvector_publish(&cls->subtables);
3406
3407     return subtable;
3408 }
3409
3410 static inline struct dpcls_subtable *
3411 dpcls_find_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
3412 {
3413     struct dpcls_subtable *subtable;
3414
3415     CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, mask->hash,
3416                              &cls->subtables_map) {
3417         if (netdev_flow_key_equal(&subtable->mask, mask)) {
3418             return subtable;
3419         }
3420     }
3421     return dpcls_create_subtable(cls, mask);
3422 }
3423
3424 /* Insert 'rule' into 'cls'. */
3425 static void
3426 dpcls_insert(struct dpcls *cls, struct dpcls_rule *rule,
3427              const struct netdev_flow_key *mask)
3428 {
3429     struct dpcls_subtable *subtable = dpcls_find_subtable(cls, mask);
3430
3431     rule->mask = &subtable->mask;
3432     cmap_insert(&subtable->rules, &rule->cmap_node, rule->flow.hash);
3433 }
3434
3435 /* Removes 'rule' from 'cls', also destructing the 'rule'. */
3436 static void
3437 dpcls_remove(struct dpcls *cls, struct dpcls_rule *rule)
3438 {
3439     struct dpcls_subtable *subtable;
3440
3441     ovs_assert(rule->mask);
3442
3443     INIT_CONTAINER(subtable, rule->mask, mask);
3444
3445     if (cmap_remove(&subtable->rules, &rule->cmap_node, rule->flow.hash)
3446         == 0) {
3447         dpcls_destroy_subtable(cls, subtable);
3448         pvector_publish(&cls->subtables);
3449     }
3450 }
3451
3452 /* Returns true if 'target' satisifies 'key' in 'mask', that is, if each 1-bit
3453  * in 'mask' the values in 'key' and 'target' are the same.
3454  *
3455  * Note: 'key' and 'mask' have the same mask, and 'key' is already masked. */
3456 static inline bool
3457 dpcls_rule_matches_key(const struct dpcls_rule *rule,
3458                        const struct netdev_flow_key *target)
3459 {
3460     const uint32_t *keyp = rule->flow.mf.inline_values;
3461     const uint32_t *maskp = rule->mask->mf.inline_values;
3462     uint32_t target_u32;
3463
3464     NETDEV_FLOW_KEY_FOR_EACH_IN_MAP(target_u32, target, rule->flow.mf.map) {
3465         if (OVS_UNLIKELY((target_u32 & *maskp++) != *keyp++)) {
3466             return false;
3467         }
3468     }
3469     return true;
3470 }
3471
3472 /* For each miniflow in 'flows' performs a classifier lookup writing the result
3473  * into the corresponding slot in 'rules'.  If a particular entry in 'flows' is
3474  * NULL it is skipped.
3475  *
3476  * This function is optimized for use in the userspace datapath and therefore
3477  * does not implement a lot of features available in the standard
3478  * classifier_lookup() function.  Specifically, it does not implement
3479  * priorities, instead returning any rule which matches the flow.
3480  *
3481  * Returns true if all flows found a corresponding rule. */
3482 static bool
3483 dpcls_lookup(const struct dpcls *cls, const struct netdev_flow_key keys[],
3484              struct dpcls_rule **rules, const size_t cnt)
3485 {
3486     /* The batch size 16 was experimentally found faster than 8 or 32. */
3487     typedef uint16_t map_type;
3488 #define MAP_BITS (sizeof(map_type) * CHAR_BIT)
3489
3490 #if !defined(__CHECKER__) && !defined(_WIN32)
3491     const int N_MAPS = DIV_ROUND_UP(cnt, MAP_BITS);
3492 #else
3493     enum { N_MAPS = DIV_ROUND_UP(NETDEV_MAX_RX_BATCH, MAP_BITS) };
3494 #endif
3495     map_type maps[N_MAPS];
3496     struct dpcls_subtable *subtable;
3497
3498     memset(maps, 0xff, sizeof maps);
3499     if (cnt % MAP_BITS) {
3500         maps[N_MAPS - 1] >>= MAP_BITS - cnt % MAP_BITS; /* Clear extra bits. */
3501     }
3502     memset(rules, 0, cnt * sizeof *rules);
3503
3504     PVECTOR_FOR_EACH (subtable, &cls->subtables) {
3505         const struct netdev_flow_key *mkeys = keys;
3506         struct dpcls_rule **mrules = rules;
3507         map_type remains = 0;
3508         int m;
3509
3510         BUILD_ASSERT_DECL(sizeof remains == sizeof *maps);
3511
3512         for (m = 0; m < N_MAPS; m++, mkeys += MAP_BITS, mrules += MAP_BITS) {
3513             uint32_t hashes[MAP_BITS];
3514             const struct cmap_node *nodes[MAP_BITS];
3515             unsigned long map = maps[m];
3516             int i;
3517
3518             if (!map) {
3519                 continue; /* Skip empty maps. */
3520             }
3521
3522             /* Compute hashes for the remaining keys. */
3523             ULONG_FOR_EACH_1(i, map) {
3524                 hashes[i] = netdev_flow_key_hash_in_mask(&mkeys[i],
3525                                                          &subtable->mask);
3526             }
3527             /* Lookup. */
3528             map = cmap_find_batch(&subtable->rules, map, hashes, nodes);
3529             /* Check results. */
3530             ULONG_FOR_EACH_1(i, map) {
3531                 struct dpcls_rule *rule;
3532
3533                 CMAP_NODE_FOR_EACH (rule, cmap_node, nodes[i]) {
3534                     if (OVS_LIKELY(dpcls_rule_matches_key(rule, &mkeys[i]))) {
3535                         mrules[i] = rule;
3536                         goto next;
3537                     }
3538                 }
3539                 ULONG_SET0(map, i);   /* Did not match. */
3540             next:
3541                 ;                     /* Keep Sparse happy. */
3542             }
3543             maps[m] &= ~map;          /* Clear the found rules. */
3544             remains |= maps[m];
3545         }
3546         if (!remains) {
3547             return true;              /* All found. */
3548         }
3549     }
3550     return false;                     /* Some misses. */
3551 }