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