dpif-netdev: use the open_type when creating the local port
[cascardo/ovs.git] / lib / dpif-netdev.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2016 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 <net/if.h>
25 #include <netinet/in.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33
34 #include "bitmap.h"
35 #include "cmap.h"
36 #include "coverage.h"
37 #include "csum.h"
38 #include "dp-packet.h"
39 #include "dpif.h"
40 #include "dpif-provider.h"
41 #include "dummy.h"
42 #include "fat-rwlock.h"
43 #include "flow.h"
44 #include "hmapx.h"
45 #include "latch.h"
46 #include "netdev.h"
47 #include "netdev-dpdk.h"
48 #include "netdev-vport.h"
49 #include "netlink.h"
50 #include "odp-execute.h"
51 #include "odp-util.h"
52 #include "openvswitch/dynamic-string.h"
53 #include "openvswitch/list.h"
54 #include "openvswitch/match.h"
55 #include "openvswitch/ofp-print.h"
56 #include "openvswitch/ofpbuf.h"
57 #include "openvswitch/vlog.h"
58 #include "ovs-numa.h"
59 #include "ovs-rcu.h"
60 #include "packets.h"
61 #include "poll-loop.h"
62 #include "pvector.h"
63 #include "random.h"
64 #include "seq.h"
65 #include "openvswitch/shash.h"
66 #include "sset.h"
67 #include "timeval.h"
68 #include "tnl-neigh-cache.h"
69 #include "tnl-ports.h"
70 #include "unixctl.h"
71 #include "util.h"
72
73 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
74
75 #define FLOW_DUMP_MAX_BATCH 50
76 /* Use per thread recirc_depth to prevent recirculation loop. */
77 #define MAX_RECIRC_DEPTH 5
78 DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
79
80 /* Configuration parameters. */
81 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
82
83 /* Protects against changes to 'dp_netdevs'. */
84 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
85
86 /* Contains all 'struct dp_netdev's. */
87 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
88     = SHASH_INITIALIZER(&dp_netdevs);
89
90 static struct vlog_rate_limit upcall_rl = VLOG_RATE_LIMIT_INIT(600, 600);
91
92 static struct odp_support dp_netdev_support = {
93     .max_mpls_depth = SIZE_MAX,
94     .recirc = true,
95 };
96
97 /* Stores a miniflow with inline values */
98
99 struct netdev_flow_key {
100     uint32_t hash;       /* Hash function differs for different users. */
101     uint32_t len;        /* Length of the following miniflow (incl. map). */
102     struct miniflow mf;
103     uint64_t buf[FLOW_MAX_PACKET_U64S];
104 };
105
106 /* Exact match cache for frequently used flows
107  *
108  * The cache uses a 32-bit hash of the packet (which can be the RSS hash) to
109  * search its entries for a miniflow that matches exactly the miniflow of the
110  * packet. It stores the 'dpcls_rule' (rule) that matches the miniflow.
111  *
112  * A cache entry holds a reference to its 'dp_netdev_flow'.
113  *
114  * A miniflow with a given hash can be in one of EM_FLOW_HASH_SEGS different
115  * entries. The 32-bit hash is split into EM_FLOW_HASH_SEGS values (each of
116  * them is EM_FLOW_HASH_SHIFT bits wide and the remainder is thrown away). Each
117  * value is the index of a cache entry where the miniflow could be.
118  *
119  *
120  * Thread-safety
121  * =============
122  *
123  * Each pmd_thread has its own private exact match cache.
124  * If dp_netdev_input is not called from a pmd thread, a mutex is used.
125  */
126
127 #define EM_FLOW_HASH_SHIFT 13
128 #define EM_FLOW_HASH_ENTRIES (1u << EM_FLOW_HASH_SHIFT)
129 #define EM_FLOW_HASH_MASK (EM_FLOW_HASH_ENTRIES - 1)
130 #define EM_FLOW_HASH_SEGS 2
131
132 struct emc_entry {
133     struct dp_netdev_flow *flow;
134     struct netdev_flow_key key;   /* key.hash used for emc hash value. */
135 };
136
137 struct emc_cache {
138     struct emc_entry entries[EM_FLOW_HASH_ENTRIES];
139     int sweep_idx;                /* For emc_cache_slow_sweep(). */
140 };
141
142 /* Iterate in the exact match cache through every entry that might contain a
143  * miniflow with hash 'HASH'. */
144 #define EMC_FOR_EACH_POS_WITH_HASH(EMC, CURRENT_ENTRY, HASH)                 \
145     for (uint32_t i__ = 0, srch_hash__ = (HASH);                             \
146          (CURRENT_ENTRY) = &(EMC)->entries[srch_hash__ & EM_FLOW_HASH_MASK], \
147          i__ < EM_FLOW_HASH_SEGS;                                            \
148          i__++, srch_hash__ >>= EM_FLOW_HASH_SHIFT)
149 \f
150 /* Simple non-wildcarding single-priority classifier. */
151
152 struct dpcls {
153     struct cmap subtables_map;
154     struct pvector subtables;
155 };
156
157 /* A rule to be inserted to the classifier. */
158 struct dpcls_rule {
159     struct cmap_node cmap_node;   /* Within struct dpcls_subtable 'rules'. */
160     struct netdev_flow_key *mask; /* Subtable's mask. */
161     struct netdev_flow_key flow;  /* Matching key. */
162     /* 'flow' must be the last field, additional space is allocated here. */
163 };
164
165 static void dpcls_init(struct dpcls *);
166 static void dpcls_destroy(struct dpcls *);
167 static void dpcls_insert(struct dpcls *, struct dpcls_rule *,
168                          const struct netdev_flow_key *mask);
169 static void dpcls_remove(struct dpcls *, struct dpcls_rule *);
170 static bool dpcls_lookup(const struct dpcls *cls,
171                          const struct netdev_flow_key keys[],
172                          struct dpcls_rule **rules, size_t cnt);
173 \f
174 /* Datapath based on the network device interface from netdev.h.
175  *
176  *
177  * Thread-safety
178  * =============
179  *
180  * Some members, marked 'const', are immutable.  Accessing other members
181  * requires synchronization, as noted in more detail below.
182  *
183  * Acquisition order is, from outermost to innermost:
184  *
185  *    dp_netdev_mutex (global)
186  *    port_mutex
187  *    non_pmd_mutex
188  */
189 struct dp_netdev {
190     const struct dpif_class *const class;
191     const char *const name;
192     struct dpif *dpif;
193     struct ovs_refcount ref_cnt;
194     atomic_flag destroyed;
195
196     /* Ports.
197      *
198      * Any lookup into 'ports' or any access to the dp_netdev_ports found
199      * through 'ports' requires taking 'port_mutex'. */
200     struct ovs_mutex port_mutex;
201     struct hmap ports;
202     struct seq *port_seq;       /* Incremented whenever a port changes. */
203
204     /* Protects access to ofproto-dpif-upcall interface during revalidator
205      * thread synchronization. */
206     struct fat_rwlock upcall_rwlock;
207     upcall_callback *upcall_cb;  /* Callback function for executing upcalls. */
208     void *upcall_aux;
209
210     /* Callback function for notifying the purging of dp flows (during
211      * reseting pmd deletion). */
212     dp_purge_callback *dp_purge_cb;
213     void *dp_purge_aux;
214
215     /* Stores all 'struct dp_netdev_pmd_thread's. */
216     struct cmap poll_threads;
217
218     /* Protects the access of the 'struct dp_netdev_pmd_thread'
219      * instance for non-pmd thread. */
220     struct ovs_mutex non_pmd_mutex;
221
222     /* Each pmd thread will store its pointer to
223      * 'struct dp_netdev_pmd_thread' in 'per_pmd_key'. */
224     ovsthread_key_t per_pmd_key;
225
226     /* Cpu mask for pin of pmd threads. */
227     char *requested_pmd_cmask;
228     char *pmd_cmask;
229
230     uint64_t last_tnl_conf_seq;
231 };
232
233 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
234                                                     odp_port_t)
235     OVS_REQUIRES(dp->port_mutex);
236
237 enum dp_stat_type {
238     DP_STAT_EXACT_HIT,          /* Packets that had an exact match (emc). */
239     DP_STAT_MASKED_HIT,         /* Packets that matched in the flow table. */
240     DP_STAT_MISS,               /* Packets that did not match. */
241     DP_STAT_LOST,               /* Packets not passed up to the client. */
242     DP_N_STATS
243 };
244
245 enum pmd_cycles_counter_type {
246     PMD_CYCLES_POLLING,         /* Cycles spent polling NICs. */
247     PMD_CYCLES_PROCESSING,      /* Cycles spent processing packets */
248     PMD_N_CYCLES
249 };
250
251 /* A port in a netdev-based datapath. */
252 struct dp_netdev_port {
253     odp_port_t port_no;
254     struct netdev *netdev;
255     struct hmap_node node;      /* Node in dp_netdev's 'ports'. */
256     struct netdev_saved_flags *sf;
257     unsigned n_rxq;             /* Number of elements in 'rxq' */
258     struct netdev_rxq **rxq;
259     char *type;                 /* Port type as requested by user. */
260 };
261
262 /* Contained by struct dp_netdev_flow's 'stats' member.  */
263 struct dp_netdev_flow_stats {
264     atomic_llong used;             /* Last used time, in monotonic msecs. */
265     atomic_ullong packet_count;    /* Number of packets matched. */
266     atomic_ullong byte_count;      /* Number of bytes matched. */
267     atomic_uint16_t tcp_flags;     /* Bitwise-OR of seen tcp_flags values. */
268 };
269
270 /* A flow in 'dp_netdev_pmd_thread's 'flow_table'.
271  *
272  *
273  * Thread-safety
274  * =============
275  *
276  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
277  * its pmd thread's classifier.  The text below calls this classifier 'cls'.
278  *
279  * Motivation
280  * ----------
281  *
282  * The thread safety rules described here for "struct dp_netdev_flow" are
283  * motivated by two goals:
284  *
285  *    - Prevent threads that read members of "struct dp_netdev_flow" from
286  *      reading bad data due to changes by some thread concurrently modifying
287  *      those members.
288  *
289  *    - Prevent two threads making changes to members of a given "struct
290  *      dp_netdev_flow" from interfering with each other.
291  *
292  *
293  * Rules
294  * -----
295  *
296  * A flow 'flow' may be accessed without a risk of being freed during an RCU
297  * grace period.  Code that needs to hold onto a flow for a while
298  * should try incrementing 'flow->ref_cnt' with dp_netdev_flow_ref().
299  *
300  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
301  * flow from being deleted from 'cls' and it doesn't protect members of 'flow'
302  * from modification.
303  *
304  * Some members, marked 'const', are immutable.  Accessing other members
305  * requires synchronization, as noted in more detail below.
306  */
307 struct dp_netdev_flow {
308     const struct flow flow;      /* Unmasked flow that created this entry. */
309     /* Hash table index by unmasked flow. */
310     const struct cmap_node node; /* In owning dp_netdev_pmd_thread's */
311                                  /* 'flow_table'. */
312     const ovs_u128 ufid;         /* Unique flow identifier. */
313     const unsigned pmd_id;       /* The 'core_id' of pmd thread owning this */
314                                  /* flow. */
315
316     /* Number of references.
317      * The classifier owns one reference.
318      * Any thread trying to keep a rule from being freed should hold its own
319      * reference. */
320     struct ovs_refcount ref_cnt;
321
322     bool dead;
323
324     /* Statistics. */
325     struct dp_netdev_flow_stats stats;
326
327     /* Actions. */
328     OVSRCU_TYPE(struct dp_netdev_actions *) actions;
329
330     /* While processing a group of input packets, the datapath uses the next
331      * member to store a pointer to the output batch for the flow.  It is
332      * reset after the batch has been sent out (See dp_netdev_queue_batches(),
333      * packet_batch_per_flow_init() and packet_batch_per_flow_execute()). */
334     struct packet_batch_per_flow *batch;
335
336     /* Packet classification. */
337     struct dpcls_rule cr;        /* In owning dp_netdev's 'cls'. */
338     /* 'cr' must be the last member. */
339 };
340
341 static void dp_netdev_flow_unref(struct dp_netdev_flow *);
342 static bool dp_netdev_flow_ref(struct dp_netdev_flow *);
343 static int dpif_netdev_flow_from_nlattrs(const struct nlattr *, uint32_t,
344                                          struct flow *);
345
346 /* A set of datapath actions within a "struct dp_netdev_flow".
347  *
348  *
349  * Thread-safety
350  * =============
351  *
352  * A struct dp_netdev_actions 'actions' is protected with RCU. */
353 struct dp_netdev_actions {
354     /* These members are immutable: they do not change during the struct's
355      * lifetime.  */
356     unsigned int size;          /* Size of 'actions', in bytes. */
357     struct nlattr actions[];    /* Sequence of OVS_ACTION_ATTR_* attributes. */
358 };
359
360 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
361                                                    size_t);
362 struct dp_netdev_actions *dp_netdev_flow_get_actions(
363     const struct dp_netdev_flow *);
364 static void dp_netdev_actions_free(struct dp_netdev_actions *);
365
366 /* Contained by struct dp_netdev_pmd_thread's 'stats' member.  */
367 struct dp_netdev_pmd_stats {
368     /* Indexed by DP_STAT_*. */
369     atomic_ullong n[DP_N_STATS];
370 };
371
372 /* Contained by struct dp_netdev_pmd_thread's 'cycle' member.  */
373 struct dp_netdev_pmd_cycles {
374     /* Indexed by PMD_CYCLES_*. */
375     atomic_ullong n[PMD_N_CYCLES];
376 };
377
378 /* Contained by struct dp_netdev_pmd_thread's 'poll_list' member. */
379 struct rxq_poll {
380     struct dp_netdev_port *port;
381     struct netdev_rxq *rx;
382     struct ovs_list node;
383 };
384
385 /* Contained by struct dp_netdev_pmd_thread's 'port_cache' or 'tx_ports'. */
386 struct tx_port {
387     odp_port_t port_no;
388     struct netdev *netdev;
389     struct hmap_node node;
390 };
391
392 /* PMD: Poll modes drivers.  PMD accesses devices via polling to eliminate
393  * the performance overhead of interrupt processing.  Therefore netdev can
394  * not implement rx-wait for these devices.  dpif-netdev needs to poll
395  * these device to check for recv buffer.  pmd-thread does polling for
396  * devices assigned to itself.
397  *
398  * DPDK used PMD for accessing NIC.
399  *
400  * Note, instance with cpu core id NON_PMD_CORE_ID will be reserved for
401  * I/O of all non-pmd threads.  There will be no actual thread created
402  * for the instance.
403  *
404  * Each struct has its own flow table and classifier.  Packets received
405  * from managed ports are looked up in the corresponding pmd thread's
406  * flow table, and are executed with the found actions.
407  * */
408 struct dp_netdev_pmd_thread {
409     struct dp_netdev *dp;
410     struct ovs_refcount ref_cnt;    /* Every reference must be refcount'ed. */
411     struct cmap_node node;          /* In 'dp->poll_threads'. */
412
413     pthread_cond_t cond;            /* For synchronizing pmd thread reload. */
414     struct ovs_mutex cond_mutex;    /* Mutex for condition variable. */
415
416     /* Per thread exact-match cache.  Note, the instance for cpu core
417      * NON_PMD_CORE_ID can be accessed by multiple threads, and thusly
418      * need to be protected by 'non_pmd_mutex'.  Every other instance
419      * will only be accessed by its own pmd thread. */
420     struct emc_cache flow_cache;
421
422     /* Classifier and Flow-Table.
423      *
424      * Writers of 'flow_table' must take the 'flow_mutex'.  Corresponding
425      * changes to 'cls' must be made while still holding the 'flow_mutex'.
426      */
427     struct ovs_mutex flow_mutex;
428     struct dpcls cls;
429     struct cmap flow_table OVS_GUARDED; /* Flow table. */
430
431     /* Statistics. */
432     struct dp_netdev_pmd_stats stats;
433
434     /* Cycles counters */
435     struct dp_netdev_pmd_cycles cycles;
436
437     /* Used to count cicles. See 'cycles_counter_end()' */
438     unsigned long long last_cycles;
439
440     struct latch exit_latch;        /* For terminating the pmd thread. */
441     atomic_uint change_seq;         /* For reloading pmd ports. */
442     pthread_t thread;
443     unsigned core_id;               /* CPU core id of this pmd thread. */
444     int numa_id;                    /* numa node id of this pmd thread. */
445
446     /* Queue id used by this pmd thread to send packets on all netdevs.
447      * All tx_qid's are unique and less than 'ovs_numa_get_n_cores() + 1'. */
448     atomic_int tx_qid;
449
450     struct ovs_mutex port_mutex;    /* Mutex for 'poll_list' and 'tx_ports'. */
451     /* List of rx queues to poll. */
452     struct ovs_list poll_list OVS_GUARDED;
453     /* Number of elements in 'poll_list' */
454     int poll_cnt;
455     /* Map of 'tx_port's used for transmission.  Written by the main thread,
456      * read by the pmd thread. */
457     struct hmap tx_ports OVS_GUARDED;
458
459     /* Map of 'tx_port' used in the fast path. This is a thread-local copy of
460      * 'tx_ports'. The instance for cpu core NON_PMD_CORE_ID can be accessed
461      * by multiple threads, and thusly need to be protected by 'non_pmd_mutex'.
462      * Every other instance will only be accessed by its own pmd thread. */
463     struct hmap port_cache;
464
465     /* Only a pmd thread can write on its own 'cycles' and 'stats'.
466      * The main thread keeps 'stats_zero' and 'cycles_zero' as base
467      * values and subtracts them from 'stats' and 'cycles' before
468      * reporting to the user */
469     unsigned long long stats_zero[DP_N_STATS];
470     uint64_t cycles_zero[PMD_N_CYCLES];
471 };
472
473 #define PMD_INITIAL_SEQ 1
474
475 /* Interface to netdev-based datapath. */
476 struct dpif_netdev {
477     struct dpif dpif;
478     struct dp_netdev *dp;
479     uint64_t last_port_seq;
480 };
481
482 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
483                               struct dp_netdev_port **portp)
484     OVS_REQUIRES(dp->port_mutex);
485 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
486                             struct dp_netdev_port **portp)
487     OVS_REQUIRES(dp->port_mutex);
488 static void dp_netdev_free(struct dp_netdev *)
489     OVS_REQUIRES(dp_netdev_mutex);
490 static int do_add_port(struct dp_netdev *dp, const char *devname,
491                        const char *type, odp_port_t port_no)
492     OVS_REQUIRES(dp->port_mutex);
493 static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
494     OVS_REQUIRES(dp->port_mutex);
495 static int dpif_netdev_open(const struct dpif_class *, const char *name,
496                             bool create, struct dpif **);
497 static void dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
498                                       struct dp_packet_batch *,
499                                       bool may_steal,
500                                       const struct nlattr *actions,
501                                       size_t actions_len);
502 static void dp_netdev_input(struct dp_netdev_pmd_thread *,
503                             struct dp_packet_batch *, odp_port_t port_no);
504 static void dp_netdev_recirculate(struct dp_netdev_pmd_thread *,
505                                   struct dp_packet_batch *);
506
507 static void dp_netdev_disable_upcall(struct dp_netdev *);
508 static void dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd);
509 static void dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd,
510                                     struct dp_netdev *dp, unsigned core_id,
511                                     int numa_id);
512 static void dp_netdev_destroy_pmd(struct dp_netdev_pmd_thread *pmd);
513 static void dp_netdev_set_nonpmd(struct dp_netdev *dp)
514     OVS_REQUIRES(dp->port_mutex);
515
516 static struct dp_netdev_pmd_thread *dp_netdev_get_pmd(struct dp_netdev *dp,
517                                                       unsigned core_id);
518 static struct dp_netdev_pmd_thread *
519 dp_netdev_pmd_get_next(struct dp_netdev *dp, struct cmap_position *pos);
520 static void dp_netdev_destroy_all_pmds(struct dp_netdev *dp);
521 static void dp_netdev_del_pmds_on_numa(struct dp_netdev *dp, int numa_id);
522 static void dp_netdev_set_pmds_on_numa(struct dp_netdev *dp, int numa_id)
523     OVS_REQUIRES(dp->port_mutex);
524 static void dp_netdev_pmd_clear_ports(struct dp_netdev_pmd_thread *pmd);
525 static void dp_netdev_del_port_from_all_pmds(struct dp_netdev *dp,
526                                              struct dp_netdev_port *port);
527 static void dp_netdev_add_port_to_pmds(struct dp_netdev *dp,
528                                        struct dp_netdev_port *port);
529 static void dp_netdev_add_port_tx_to_pmd(struct dp_netdev_pmd_thread *pmd,
530                                          struct dp_netdev_port *port);
531 static void dp_netdev_add_rxq_to_pmd(struct dp_netdev_pmd_thread *pmd,
532                                      struct dp_netdev_port *port,
533                                      struct netdev_rxq *rx);
534 static struct dp_netdev_pmd_thread *
535 dp_netdev_less_loaded_pmd_on_numa(struct dp_netdev *dp, int numa_id);
536 static void dp_netdev_reset_pmd_threads(struct dp_netdev *dp)
537     OVS_REQUIRES(dp->port_mutex);
538 static bool dp_netdev_pmd_try_ref(struct dp_netdev_pmd_thread *pmd);
539 static void dp_netdev_pmd_unref(struct dp_netdev_pmd_thread *pmd);
540 static void dp_netdev_pmd_flow_flush(struct dp_netdev_pmd_thread *pmd);
541 static void pmd_load_cached_ports(struct dp_netdev_pmd_thread *pmd)
542     OVS_REQUIRES(pmd->port_mutex);
543
544 static inline bool emc_entry_alive(struct emc_entry *ce);
545 static void emc_clear_entry(struct emc_entry *ce);
546
547 static void
548 emc_cache_init(struct emc_cache *flow_cache)
549 {
550     int i;
551
552     flow_cache->sweep_idx = 0;
553     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
554         flow_cache->entries[i].flow = NULL;
555         flow_cache->entries[i].key.hash = 0;
556         flow_cache->entries[i].key.len = sizeof(struct miniflow);
557         flowmap_init(&flow_cache->entries[i].key.mf.map);
558     }
559 }
560
561 static void
562 emc_cache_uninit(struct emc_cache *flow_cache)
563 {
564     int i;
565
566     for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
567         emc_clear_entry(&flow_cache->entries[i]);
568     }
569 }
570
571 /* Check and clear dead flow references slowly (one entry at each
572  * invocation).  */
573 static void
574 emc_cache_slow_sweep(struct emc_cache *flow_cache)
575 {
576     struct emc_entry *entry = &flow_cache->entries[flow_cache->sweep_idx];
577
578     if (!emc_entry_alive(entry)) {
579         emc_clear_entry(entry);
580     }
581     flow_cache->sweep_idx = (flow_cache->sweep_idx + 1) & EM_FLOW_HASH_MASK;
582 }
583
584 /* Returns true if 'dpif' is a netdev or dummy dpif, false otherwise. */
585 bool
586 dpif_is_netdev(const struct dpif *dpif)
587 {
588     return dpif->dpif_class->open == dpif_netdev_open;
589 }
590
591 static struct dpif_netdev *
592 dpif_netdev_cast(const struct dpif *dpif)
593 {
594     ovs_assert(dpif_is_netdev(dpif));
595     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
596 }
597
598 static struct dp_netdev *
599 get_dp_netdev(const struct dpif *dpif)
600 {
601     return dpif_netdev_cast(dpif)->dp;
602 }
603 \f
604 enum pmd_info_type {
605     PMD_INFO_SHOW_STATS,  /* Show how cpu cycles are spent. */
606     PMD_INFO_CLEAR_STATS, /* Set the cycles count to 0. */
607     PMD_INFO_SHOW_RXQ     /* Show poll-lists of pmd threads. */
608 };
609
610 static void
611 pmd_info_show_stats(struct ds *reply,
612                     struct dp_netdev_pmd_thread *pmd,
613                     unsigned long long stats[DP_N_STATS],
614                     uint64_t cycles[PMD_N_CYCLES])
615 {
616     unsigned long long total_packets = 0;
617     uint64_t total_cycles = 0;
618     int i;
619
620     /* These loops subtracts reference values ('*_zero') from the counters.
621      * Since loads and stores are relaxed, it might be possible for a '*_zero'
622      * value to be more recent than the current value we're reading from the
623      * counter.  This is not a big problem, since these numbers are not
624      * supposed to be too accurate, but we should at least make sure that
625      * the result is not negative. */
626     for (i = 0; i < DP_N_STATS; i++) {
627         if (stats[i] > pmd->stats_zero[i]) {
628             stats[i] -= pmd->stats_zero[i];
629         } else {
630             stats[i] = 0;
631         }
632
633         if (i != DP_STAT_LOST) {
634             /* Lost packets are already included in DP_STAT_MISS */
635             total_packets += stats[i];
636         }
637     }
638
639     for (i = 0; i < PMD_N_CYCLES; i++) {
640         if (cycles[i] > pmd->cycles_zero[i]) {
641            cycles[i] -= pmd->cycles_zero[i];
642         } else {
643             cycles[i] = 0;
644         }
645
646         total_cycles += cycles[i];
647     }
648
649     ds_put_cstr(reply, (pmd->core_id == NON_PMD_CORE_ID)
650                         ? "main thread" : "pmd thread");
651
652     if (pmd->numa_id != OVS_NUMA_UNSPEC) {
653         ds_put_format(reply, " numa_id %d", pmd->numa_id);
654     }
655     if (pmd->core_id != OVS_CORE_UNSPEC && pmd->core_id != NON_PMD_CORE_ID) {
656         ds_put_format(reply, " core_id %u", pmd->core_id);
657     }
658     ds_put_cstr(reply, ":\n");
659
660     ds_put_format(reply,
661                   "\temc hits:%llu\n\tmegaflow hits:%llu\n"
662                   "\tmiss:%llu\n\tlost:%llu\n",
663                   stats[DP_STAT_EXACT_HIT], stats[DP_STAT_MASKED_HIT],
664                   stats[DP_STAT_MISS], stats[DP_STAT_LOST]);
665
666     if (total_cycles == 0) {
667         return;
668     }
669
670     ds_put_format(reply,
671                   "\tpolling cycles:%"PRIu64" (%.02f%%)\n"
672                   "\tprocessing cycles:%"PRIu64" (%.02f%%)\n",
673                   cycles[PMD_CYCLES_POLLING],
674                   cycles[PMD_CYCLES_POLLING] / (double)total_cycles * 100,
675                   cycles[PMD_CYCLES_PROCESSING],
676                   cycles[PMD_CYCLES_PROCESSING] / (double)total_cycles * 100);
677
678     if (total_packets == 0) {
679         return;
680     }
681
682     ds_put_format(reply,
683                   "\tavg cycles per packet: %.02f (%"PRIu64"/%llu)\n",
684                   total_cycles / (double)total_packets,
685                   total_cycles, total_packets);
686
687     ds_put_format(reply,
688                   "\tavg processing cycles per packet: "
689                   "%.02f (%"PRIu64"/%llu)\n",
690                   cycles[PMD_CYCLES_PROCESSING] / (double)total_packets,
691                   cycles[PMD_CYCLES_PROCESSING], total_packets);
692 }
693
694 static void
695 pmd_info_clear_stats(struct ds *reply OVS_UNUSED,
696                     struct dp_netdev_pmd_thread *pmd,
697                     unsigned long long stats[DP_N_STATS],
698                     uint64_t cycles[PMD_N_CYCLES])
699 {
700     int i;
701
702     /* We cannot write 'stats' and 'cycles' (because they're written by other
703      * threads) and we shouldn't change 'stats' (because they're used to count
704      * datapath stats, which must not be cleared here).  Instead, we save the
705      * current values and subtract them from the values to be displayed in the
706      * future */
707     for (i = 0; i < DP_N_STATS; i++) {
708         pmd->stats_zero[i] = stats[i];
709     }
710     for (i = 0; i < PMD_N_CYCLES; i++) {
711         pmd->cycles_zero[i] = cycles[i];
712     }
713 }
714
715 static void
716 pmd_info_show_rxq(struct ds *reply, struct dp_netdev_pmd_thread *pmd)
717 {
718     if (pmd->core_id != NON_PMD_CORE_ID) {
719         struct rxq_poll *poll;
720         const char *prev_name = NULL;
721
722         ds_put_format(reply, "pmd thread numa_id %d core_id %u:\n",
723                       pmd->numa_id, pmd->core_id);
724
725         ovs_mutex_lock(&pmd->port_mutex);
726         LIST_FOR_EACH (poll, node, &pmd->poll_list) {
727             const char *name = netdev_get_name(poll->port->netdev);
728
729             if (!prev_name || strcmp(name, prev_name)) {
730                 if (prev_name) {
731                     ds_put_cstr(reply, "\n");
732                 }
733                 ds_put_format(reply, "\tport: %s\tqueue-id:",
734                               netdev_get_name(poll->port->netdev));
735             }
736             ds_put_format(reply, " %d", netdev_rxq_get_queue_id(poll->rx));
737             prev_name = name;
738         }
739         ovs_mutex_unlock(&pmd->port_mutex);
740         ds_put_cstr(reply, "\n");
741     }
742 }
743
744 static void
745 dpif_netdev_pmd_info(struct unixctl_conn *conn, int argc, const char *argv[],
746                      void *aux)
747 {
748     struct ds reply = DS_EMPTY_INITIALIZER;
749     struct dp_netdev_pmd_thread *pmd;
750     struct dp_netdev *dp = NULL;
751     enum pmd_info_type type = *(enum pmd_info_type *) aux;
752
753     ovs_mutex_lock(&dp_netdev_mutex);
754
755     if (argc == 2) {
756         dp = shash_find_data(&dp_netdevs, argv[1]);
757     } else if (shash_count(&dp_netdevs) == 1) {
758         /* There's only one datapath */
759         dp = shash_first(&dp_netdevs)->data;
760     }
761
762     if (!dp) {
763         ovs_mutex_unlock(&dp_netdev_mutex);
764         unixctl_command_reply_error(conn,
765                                     "please specify an existing datapath");
766         return;
767     }
768
769     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
770         if (type == PMD_INFO_SHOW_RXQ) {
771             pmd_info_show_rxq(&reply, pmd);
772         } else {
773             unsigned long long stats[DP_N_STATS];
774             uint64_t cycles[PMD_N_CYCLES];
775             int i;
776
777             /* Read current stats and cycle counters */
778             for (i = 0; i < ARRAY_SIZE(stats); i++) {
779                 atomic_read_relaxed(&pmd->stats.n[i], &stats[i]);
780             }
781             for (i = 0; i < ARRAY_SIZE(cycles); i++) {
782                 atomic_read_relaxed(&pmd->cycles.n[i], &cycles[i]);
783             }
784
785             if (type == PMD_INFO_CLEAR_STATS) {
786                 pmd_info_clear_stats(&reply, pmd, stats, cycles);
787             } else if (type == PMD_INFO_SHOW_STATS) {
788                 pmd_info_show_stats(&reply, pmd, stats, cycles);
789             }
790         }
791     }
792
793     ovs_mutex_unlock(&dp_netdev_mutex);
794
795     unixctl_command_reply(conn, ds_cstr(&reply));
796     ds_destroy(&reply);
797 }
798 \f
799 static int
800 dpif_netdev_init(void)
801 {
802     static enum pmd_info_type show_aux = PMD_INFO_SHOW_STATS,
803                               clear_aux = PMD_INFO_CLEAR_STATS,
804                               poll_aux = PMD_INFO_SHOW_RXQ;
805
806     unixctl_command_register("dpif-netdev/pmd-stats-show", "[dp]",
807                              0, 1, dpif_netdev_pmd_info,
808                              (void *)&show_aux);
809     unixctl_command_register("dpif-netdev/pmd-stats-clear", "[dp]",
810                              0, 1, dpif_netdev_pmd_info,
811                              (void *)&clear_aux);
812     unixctl_command_register("dpif-netdev/pmd-rxq-show", "[dp]",
813                              0, 1, dpif_netdev_pmd_info,
814                              (void *)&poll_aux);
815     return 0;
816 }
817
818 static int
819 dpif_netdev_enumerate(struct sset *all_dps,
820                       const struct dpif_class *dpif_class)
821 {
822     struct shash_node *node;
823
824     ovs_mutex_lock(&dp_netdev_mutex);
825     SHASH_FOR_EACH(node, &dp_netdevs) {
826         struct dp_netdev *dp = node->data;
827         if (dpif_class != dp->class) {
828             /* 'dp_netdevs' contains both "netdev" and "dummy" dpifs.
829              * If the class doesn't match, skip this dpif. */
830              continue;
831         }
832         sset_add(all_dps, node->name);
833     }
834     ovs_mutex_unlock(&dp_netdev_mutex);
835
836     return 0;
837 }
838
839 static bool
840 dpif_netdev_class_is_dummy(const struct dpif_class *class)
841 {
842     return class != &dpif_netdev_class;
843 }
844
845 static const char *
846 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
847 {
848     return strcmp(type, "internal") ? type
849                   : dpif_netdev_class_is_dummy(class) ? "dummy"
850                   : "tap";
851 }
852
853 static struct dpif *
854 create_dpif_netdev(struct dp_netdev *dp)
855 {
856     uint16_t netflow_id = hash_string(dp->name, 0);
857     struct dpif_netdev *dpif;
858
859     ovs_refcount_ref(&dp->ref_cnt);
860
861     dpif = xmalloc(sizeof *dpif);
862     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
863     dpif->dp = dp;
864     dpif->last_port_seq = seq_read(dp->port_seq);
865
866     return &dpif->dpif;
867 }
868
869 /* Choose an unused, non-zero port number and return it on success.
870  * Return ODPP_NONE on failure. */
871 static odp_port_t
872 choose_port(struct dp_netdev *dp, const char *name)
873     OVS_REQUIRES(dp->port_mutex)
874 {
875     uint32_t port_no;
876
877     if (dp->class != &dpif_netdev_class) {
878         const char *p;
879         int start_no = 0;
880
881         /* If the port name begins with "br", start the number search at
882          * 100 to make writing tests easier. */
883         if (!strncmp(name, "br", 2)) {
884             start_no = 100;
885         }
886
887         /* If the port name contains a number, try to assign that port number.
888          * This can make writing unit tests easier because port numbers are
889          * predictable. */
890         for (p = name; *p != '\0'; p++) {
891             if (isdigit((unsigned char) *p)) {
892                 port_no = start_no + strtol(p, NULL, 10);
893                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
894                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
895                     return u32_to_odp(port_no);
896                 }
897                 break;
898             }
899         }
900     }
901
902     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
903         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
904             return u32_to_odp(port_no);
905         }
906     }
907
908     return ODPP_NONE;
909 }
910
911 static int
912 create_dp_netdev(const char *name, const struct dpif_class *class,
913                  struct dp_netdev **dpp)
914     OVS_REQUIRES(dp_netdev_mutex)
915 {
916     struct dp_netdev *dp;
917     int error;
918
919     dp = xzalloc(sizeof *dp);
920     shash_add(&dp_netdevs, name, dp);
921
922     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
923     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
924     ovs_refcount_init(&dp->ref_cnt);
925     atomic_flag_clear(&dp->destroyed);
926
927     ovs_mutex_init(&dp->port_mutex);
928     hmap_init(&dp->ports);
929     dp->port_seq = seq_create();
930     fat_rwlock_init(&dp->upcall_rwlock);
931
932     /* Disable upcalls by default. */
933     dp_netdev_disable_upcall(dp);
934     dp->upcall_aux = NULL;
935     dp->upcall_cb = NULL;
936
937     cmap_init(&dp->poll_threads);
938     ovs_mutex_init_recursive(&dp->non_pmd_mutex);
939     ovsthread_key_create(&dp->per_pmd_key, NULL);
940
941     ovs_mutex_lock(&dp->port_mutex);
942     dp_netdev_set_nonpmd(dp);
943
944     error = do_add_port(dp, name, dpif_netdev_port_open_type(dp->class,
945                                                              "internal"),
946                         ODPP_LOCAL);
947     ovs_mutex_unlock(&dp->port_mutex);
948     if (error) {
949         dp_netdev_free(dp);
950         return error;
951     }
952
953     dp->last_tnl_conf_seq = seq_read(tnl_conf_seq);
954     *dpp = dp;
955     return 0;
956 }
957
958 static int
959 dpif_netdev_open(const struct dpif_class *class, const char *name,
960                  bool create, struct dpif **dpifp)
961 {
962     struct dp_netdev *dp;
963     int error;
964
965     ovs_mutex_lock(&dp_netdev_mutex);
966     dp = shash_find_data(&dp_netdevs, name);
967     if (!dp) {
968         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
969     } else {
970         error = (dp->class != class ? EINVAL
971                  : create ? EEXIST
972                  : 0);
973     }
974     if (!error) {
975         *dpifp = create_dpif_netdev(dp);
976         dp->dpif = *dpifp;
977     }
978     ovs_mutex_unlock(&dp_netdev_mutex);
979
980     return error;
981 }
982
983 static void
984 dp_netdev_destroy_upcall_lock(struct dp_netdev *dp)
985     OVS_NO_THREAD_SAFETY_ANALYSIS
986 {
987     /* Check that upcalls are disabled, i.e. that the rwlock is taken */
988     ovs_assert(fat_rwlock_tryrdlock(&dp->upcall_rwlock));
989
990     /* Before freeing a lock we should release it */
991     fat_rwlock_unlock(&dp->upcall_rwlock);
992     fat_rwlock_destroy(&dp->upcall_rwlock);
993 }
994
995 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
996  * through the 'dp_netdevs' shash while freeing 'dp'. */
997 static void
998 dp_netdev_free(struct dp_netdev *dp)
999     OVS_REQUIRES(dp_netdev_mutex)
1000 {
1001     struct dp_netdev_port *port, *next;
1002
1003     shash_find_and_delete(&dp_netdevs, dp->name);
1004
1005     dp_netdev_destroy_all_pmds(dp);
1006     ovs_mutex_destroy(&dp->non_pmd_mutex);
1007     ovsthread_key_delete(dp->per_pmd_key);
1008
1009     ovs_mutex_lock(&dp->port_mutex);
1010     HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
1011         do_del_port(dp, port);
1012     }
1013     ovs_mutex_unlock(&dp->port_mutex);
1014     cmap_destroy(&dp->poll_threads);
1015
1016     seq_destroy(dp->port_seq);
1017     hmap_destroy(&dp->ports);
1018     ovs_mutex_destroy(&dp->port_mutex);
1019
1020     /* Upcalls must be disabled at this point */
1021     dp_netdev_destroy_upcall_lock(dp);
1022
1023     free(dp->pmd_cmask);
1024     free(CONST_CAST(char *, dp->name));
1025     free(dp);
1026 }
1027
1028 static void
1029 dp_netdev_unref(struct dp_netdev *dp)
1030 {
1031     if (dp) {
1032         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
1033          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
1034         ovs_mutex_lock(&dp_netdev_mutex);
1035         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
1036             dp_netdev_free(dp);
1037         }
1038         ovs_mutex_unlock(&dp_netdev_mutex);
1039     }
1040 }
1041
1042 static void
1043 dpif_netdev_close(struct dpif *dpif)
1044 {
1045     struct dp_netdev *dp = get_dp_netdev(dpif);
1046
1047     dp_netdev_unref(dp);
1048     free(dpif);
1049 }
1050
1051 static int
1052 dpif_netdev_destroy(struct dpif *dpif)
1053 {
1054     struct dp_netdev *dp = get_dp_netdev(dpif);
1055
1056     if (!atomic_flag_test_and_set(&dp->destroyed)) {
1057         if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
1058             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
1059             OVS_NOT_REACHED();
1060         }
1061     }
1062
1063     return 0;
1064 }
1065
1066 /* Add 'n' to the atomic variable 'var' non-atomically and using relaxed
1067  * load/store semantics.  While the increment is not atomic, the load and
1068  * store operations are, making it impossible to read inconsistent values.
1069  *
1070  * This is used to update thread local stats counters. */
1071 static void
1072 non_atomic_ullong_add(atomic_ullong *var, unsigned long long n)
1073 {
1074     unsigned long long tmp;
1075
1076     atomic_read_relaxed(var, &tmp);
1077     tmp += n;
1078     atomic_store_relaxed(var, tmp);
1079 }
1080
1081 static int
1082 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
1083 {
1084     struct dp_netdev *dp = get_dp_netdev(dpif);
1085     struct dp_netdev_pmd_thread *pmd;
1086
1087     stats->n_flows = stats->n_hit = stats->n_missed = stats->n_lost = 0;
1088     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1089         unsigned long long n;
1090         stats->n_flows += cmap_count(&pmd->flow_table);
1091
1092         atomic_read_relaxed(&pmd->stats.n[DP_STAT_MASKED_HIT], &n);
1093         stats->n_hit += n;
1094         atomic_read_relaxed(&pmd->stats.n[DP_STAT_EXACT_HIT], &n);
1095         stats->n_hit += n;
1096         atomic_read_relaxed(&pmd->stats.n[DP_STAT_MISS], &n);
1097         stats->n_missed += n;
1098         atomic_read_relaxed(&pmd->stats.n[DP_STAT_LOST], &n);
1099         stats->n_lost += n;
1100     }
1101     stats->n_masks = UINT32_MAX;
1102     stats->n_mask_hit = UINT64_MAX;
1103
1104     return 0;
1105 }
1106
1107 static void
1108 dp_netdev_reload_pmd__(struct dp_netdev_pmd_thread *pmd)
1109 {
1110     int old_seq;
1111
1112     if (pmd->core_id == NON_PMD_CORE_ID) {
1113         ovs_mutex_lock(&pmd->dp->non_pmd_mutex);
1114         ovs_mutex_lock(&pmd->port_mutex);
1115         pmd_load_cached_ports(pmd);
1116         ovs_mutex_unlock(&pmd->port_mutex);
1117         ovs_mutex_unlock(&pmd->dp->non_pmd_mutex);
1118         return;
1119     }
1120
1121     ovs_mutex_lock(&pmd->cond_mutex);
1122     atomic_add_relaxed(&pmd->change_seq, 1, &old_seq);
1123     ovs_mutex_cond_wait(&pmd->cond, &pmd->cond_mutex);
1124     ovs_mutex_unlock(&pmd->cond_mutex);
1125 }
1126
1127 static uint32_t
1128 hash_port_no(odp_port_t port_no)
1129 {
1130     return hash_int(odp_to_u32(port_no), 0);
1131 }
1132
1133 static int
1134 port_create(const char *devname, const char *type,
1135             odp_port_t port_no, struct dp_netdev_port **portp)
1136 {
1137     struct netdev_saved_flags *sf;
1138     struct dp_netdev_port *port;
1139     enum netdev_flags flags;
1140     struct netdev *netdev;
1141     int n_open_rxqs = 0;
1142     int i, error;
1143
1144     *portp = NULL;
1145
1146     /* Open and validate network device. */
1147     error = netdev_open(devname, type, &netdev);
1148     if (error) {
1149         return error;
1150     }
1151     /* XXX reject non-Ethernet devices */
1152
1153     netdev_get_flags(netdev, &flags);
1154     if (flags & NETDEV_LOOPBACK) {
1155         VLOG_ERR("%s: cannot add a loopback device", devname);
1156         error = EINVAL;
1157         goto out;
1158     }
1159
1160     if (netdev_is_pmd(netdev)) {
1161         int n_cores = ovs_numa_get_n_cores();
1162
1163         if (n_cores == OVS_CORE_UNSPEC) {
1164             VLOG_ERR("%s, cannot get cpu core info", devname);
1165             error = ENOENT;
1166             goto out;
1167         }
1168         /* There can only be ovs_numa_get_n_cores() pmd threads,
1169          * so creates a txq for each, and one extra for the non
1170          * pmd threads. */
1171         error = netdev_set_tx_multiq(netdev, n_cores + 1);
1172         if (error && (error != EOPNOTSUPP)) {
1173             VLOG_ERR("%s, cannot set multiq", devname);
1174             goto out;
1175         }
1176     }
1177
1178     if (netdev_is_reconf_required(netdev)) {
1179         error = netdev_reconfigure(netdev);
1180         if (error) {
1181             goto out;
1182         }
1183     }
1184
1185     port = xzalloc(sizeof *port);
1186     port->port_no = port_no;
1187     port->netdev = netdev;
1188     port->n_rxq = netdev_n_rxq(netdev);
1189     port->rxq = xcalloc(port->n_rxq, sizeof *port->rxq);
1190     port->type = xstrdup(type);
1191
1192     for (i = 0; i < port->n_rxq; i++) {
1193         error = netdev_rxq_open(netdev, &port->rxq[i], i);
1194         if (error) {
1195             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
1196                      devname, ovs_strerror(errno));
1197             goto out_rxq_close;
1198         }
1199         n_open_rxqs++;
1200     }
1201
1202     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
1203     if (error) {
1204         goto out_rxq_close;
1205     }
1206     port->sf = sf;
1207
1208     *portp = port;
1209
1210     return 0;
1211
1212 out_rxq_close:
1213     for (i = 0; i < n_open_rxqs; i++) {
1214         netdev_rxq_close(port->rxq[i]);
1215     }
1216     free(port->type);
1217     free(port->rxq);
1218     free(port);
1219
1220 out:
1221     netdev_close(netdev);
1222     return error;
1223 }
1224
1225 static int
1226 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
1227             odp_port_t port_no)
1228     OVS_REQUIRES(dp->port_mutex)
1229 {
1230     struct dp_netdev_port *port;
1231     int error;
1232
1233     /* Reject devices already in 'dp'. */
1234     if (!get_port_by_name(dp, devname, &port)) {
1235         return EEXIST;
1236     }
1237
1238     error = port_create(devname, type, port_no, &port);
1239     if (error) {
1240         return error;
1241     }
1242
1243     if (netdev_is_pmd(port->netdev)) {
1244         int numa_id = netdev_get_numa_id(port->netdev);
1245
1246         ovs_assert(ovs_numa_numa_id_is_valid(numa_id));
1247         dp_netdev_set_pmds_on_numa(dp, numa_id);
1248     }
1249
1250     dp_netdev_add_port_to_pmds(dp, port);
1251
1252     hmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
1253     seq_change(dp->port_seq);
1254
1255     return 0;
1256 }
1257
1258 static int
1259 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
1260                      odp_port_t *port_nop)
1261 {
1262     struct dp_netdev *dp = get_dp_netdev(dpif);
1263     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1264     const char *dpif_port;
1265     odp_port_t port_no;
1266     int error;
1267
1268     ovs_mutex_lock(&dp->port_mutex);
1269     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
1270     if (*port_nop != ODPP_NONE) {
1271         port_no = *port_nop;
1272         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
1273     } else {
1274         port_no = choose_port(dp, dpif_port);
1275         error = port_no == ODPP_NONE ? EFBIG : 0;
1276     }
1277     if (!error) {
1278         *port_nop = port_no;
1279         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
1280     }
1281     ovs_mutex_unlock(&dp->port_mutex);
1282
1283     return error;
1284 }
1285
1286 static int
1287 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
1288 {
1289     struct dp_netdev *dp = get_dp_netdev(dpif);
1290     int error;
1291
1292     ovs_mutex_lock(&dp->port_mutex);
1293     if (port_no == ODPP_LOCAL) {
1294         error = EINVAL;
1295     } else {
1296         struct dp_netdev_port *port;
1297
1298         error = get_port_by_number(dp, port_no, &port);
1299         if (!error) {
1300             do_del_port(dp, port);
1301         }
1302     }
1303     ovs_mutex_unlock(&dp->port_mutex);
1304
1305     return error;
1306 }
1307
1308 static bool
1309 is_valid_port_number(odp_port_t port_no)
1310 {
1311     return port_no != ODPP_NONE;
1312 }
1313
1314 static struct dp_netdev_port *
1315 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
1316     OVS_REQUIRES(dp->port_mutex)
1317 {
1318     struct dp_netdev_port *port;
1319
1320     HMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
1321         if (port->port_no == port_no) {
1322             return port;
1323         }
1324     }
1325     return NULL;
1326 }
1327
1328 static int
1329 get_port_by_number(struct dp_netdev *dp,
1330                    odp_port_t port_no, struct dp_netdev_port **portp)
1331     OVS_REQUIRES(dp->port_mutex)
1332 {
1333     if (!is_valid_port_number(port_no)) {
1334         *portp = NULL;
1335         return EINVAL;
1336     } else {
1337         *portp = dp_netdev_lookup_port(dp, port_no);
1338         return *portp ? 0 : ENOENT;
1339     }
1340 }
1341
1342 static void
1343 port_destroy(struct dp_netdev_port *port)
1344 {
1345     if (!port) {
1346         return;
1347     }
1348
1349     netdev_close(port->netdev);
1350     netdev_restore_flags(port->sf);
1351
1352     for (unsigned i = 0; i < port->n_rxq; i++) {
1353         netdev_rxq_close(port->rxq[i]);
1354     }
1355
1356     free(port->rxq);
1357     free(port->type);
1358     free(port);
1359 }
1360
1361 static int
1362 get_port_by_name(struct dp_netdev *dp,
1363                  const char *devname, struct dp_netdev_port **portp)
1364     OVS_REQUIRES(dp->port_mutex)
1365 {
1366     struct dp_netdev_port *port;
1367
1368     HMAP_FOR_EACH (port, node, &dp->ports) {
1369         if (!strcmp(netdev_get_name(port->netdev), devname)) {
1370             *portp = port;
1371             return 0;
1372         }
1373     }
1374     return ENOENT;
1375 }
1376
1377 static int
1378 get_n_pmd_threads(struct dp_netdev *dp)
1379 {
1380     /* There is one non pmd thread in dp->poll_threads */
1381     return cmap_count(&dp->poll_threads) - 1;
1382 }
1383
1384 static int
1385 get_n_pmd_threads_on_numa(struct dp_netdev *dp, int numa_id)
1386 {
1387     struct dp_netdev_pmd_thread *pmd;
1388     int n_pmds = 0;
1389
1390     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1391         if (pmd->numa_id == numa_id) {
1392             n_pmds++;
1393         }
1394     }
1395
1396     return n_pmds;
1397 }
1398
1399 /* Returns 'true' if there is a port with pmd netdev and the netdev
1400  * is on numa node 'numa_id'. */
1401 static bool
1402 has_pmd_port_for_numa(struct dp_netdev *dp, int numa_id)
1403     OVS_REQUIRES(dp->port_mutex)
1404 {
1405     struct dp_netdev_port *port;
1406
1407     HMAP_FOR_EACH (port, node, &dp->ports) {
1408         if (netdev_is_pmd(port->netdev)
1409             && netdev_get_numa_id(port->netdev) == numa_id) {
1410             return true;
1411         }
1412     }
1413
1414     return false;
1415 }
1416
1417
1418 static void
1419 do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
1420     OVS_REQUIRES(dp->port_mutex)
1421 {
1422     hmap_remove(&dp->ports, &port->node);
1423     seq_change(dp->port_seq);
1424
1425     dp_netdev_del_port_from_all_pmds(dp, port);
1426
1427     if (netdev_is_pmd(port->netdev)) {
1428         int numa_id = netdev_get_numa_id(port->netdev);
1429
1430         /* PMD threads can not be on invalid numa node. */
1431         ovs_assert(ovs_numa_numa_id_is_valid(numa_id));
1432         /* If there is no netdev on the numa node, deletes the pmd threads
1433          * for that numa. */
1434         if (!has_pmd_port_for_numa(dp, numa_id)) {
1435             dp_netdev_del_pmds_on_numa(dp, numa_id);
1436         }
1437     }
1438
1439     port_destroy(port);
1440 }
1441
1442 static void
1443 answer_port_query(const struct dp_netdev_port *port,
1444                   struct dpif_port *dpif_port)
1445 {
1446     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
1447     dpif_port->type = xstrdup(port->type);
1448     dpif_port->port_no = port->port_no;
1449 }
1450
1451 static int
1452 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
1453                                  struct dpif_port *dpif_port)
1454 {
1455     struct dp_netdev *dp = get_dp_netdev(dpif);
1456     struct dp_netdev_port *port;
1457     int error;
1458
1459     ovs_mutex_lock(&dp->port_mutex);
1460     error = get_port_by_number(dp, port_no, &port);
1461     if (!error && dpif_port) {
1462         answer_port_query(port, dpif_port);
1463     }
1464     ovs_mutex_unlock(&dp->port_mutex);
1465
1466     return error;
1467 }
1468
1469 static int
1470 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
1471                                struct dpif_port *dpif_port)
1472 {
1473     struct dp_netdev *dp = get_dp_netdev(dpif);
1474     struct dp_netdev_port *port;
1475     int error;
1476
1477     ovs_mutex_lock(&dp->port_mutex);
1478     error = get_port_by_name(dp, devname, &port);
1479     if (!error && dpif_port) {
1480         answer_port_query(port, dpif_port);
1481     }
1482     ovs_mutex_unlock(&dp->port_mutex);
1483
1484     return error;
1485 }
1486
1487 static void
1488 dp_netdev_flow_free(struct dp_netdev_flow *flow)
1489 {
1490     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
1491     free(flow);
1492 }
1493
1494 static void dp_netdev_flow_unref(struct dp_netdev_flow *flow)
1495 {
1496     if (ovs_refcount_unref_relaxed(&flow->ref_cnt) == 1) {
1497         ovsrcu_postpone(dp_netdev_flow_free, flow);
1498     }
1499 }
1500
1501 static uint32_t
1502 dp_netdev_flow_hash(const ovs_u128 *ufid)
1503 {
1504     return ufid->u32[0];
1505 }
1506
1507 static void
1508 dp_netdev_pmd_remove_flow(struct dp_netdev_pmd_thread *pmd,
1509                           struct dp_netdev_flow *flow)
1510     OVS_REQUIRES(pmd->flow_mutex)
1511 {
1512     struct cmap_node *node = CONST_CAST(struct cmap_node *, &flow->node);
1513
1514     dpcls_remove(&pmd->cls, &flow->cr);
1515     cmap_remove(&pmd->flow_table, node, dp_netdev_flow_hash(&flow->ufid));
1516     flow->dead = true;
1517
1518     dp_netdev_flow_unref(flow);
1519 }
1520
1521 static void
1522 dp_netdev_pmd_flow_flush(struct dp_netdev_pmd_thread *pmd)
1523 {
1524     struct dp_netdev_flow *netdev_flow;
1525
1526     ovs_mutex_lock(&pmd->flow_mutex);
1527     CMAP_FOR_EACH (netdev_flow, node, &pmd->flow_table) {
1528         dp_netdev_pmd_remove_flow(pmd, netdev_flow);
1529     }
1530     ovs_mutex_unlock(&pmd->flow_mutex);
1531 }
1532
1533 static int
1534 dpif_netdev_flow_flush(struct dpif *dpif)
1535 {
1536     struct dp_netdev *dp = get_dp_netdev(dpif);
1537     struct dp_netdev_pmd_thread *pmd;
1538
1539     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1540         dp_netdev_pmd_flow_flush(pmd);
1541     }
1542
1543     return 0;
1544 }
1545
1546 struct dp_netdev_port_state {
1547     struct hmap_position position;
1548     char *name;
1549 };
1550
1551 static int
1552 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
1553 {
1554     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
1555     return 0;
1556 }
1557
1558 static int
1559 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
1560                            struct dpif_port *dpif_port)
1561 {
1562     struct dp_netdev_port_state *state = state_;
1563     struct dp_netdev *dp = get_dp_netdev(dpif);
1564     struct hmap_node *node;
1565     int retval;
1566
1567     ovs_mutex_lock(&dp->port_mutex);
1568     node = hmap_at_position(&dp->ports, &state->position);
1569     if (node) {
1570         struct dp_netdev_port *port;
1571
1572         port = CONTAINER_OF(node, struct dp_netdev_port, node);
1573
1574         free(state->name);
1575         state->name = xstrdup(netdev_get_name(port->netdev));
1576         dpif_port->name = state->name;
1577         dpif_port->type = port->type;
1578         dpif_port->port_no = port->port_no;
1579
1580         retval = 0;
1581     } else {
1582         retval = EOF;
1583     }
1584     ovs_mutex_unlock(&dp->port_mutex);
1585
1586     return retval;
1587 }
1588
1589 static int
1590 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1591 {
1592     struct dp_netdev_port_state *state = state_;
1593     free(state->name);
1594     free(state);
1595     return 0;
1596 }
1597
1598 static int
1599 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1600 {
1601     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1602     uint64_t new_port_seq;
1603     int error;
1604
1605     new_port_seq = seq_read(dpif->dp->port_seq);
1606     if (dpif->last_port_seq != new_port_seq) {
1607         dpif->last_port_seq = new_port_seq;
1608         error = ENOBUFS;
1609     } else {
1610         error = EAGAIN;
1611     }
1612
1613     return error;
1614 }
1615
1616 static void
1617 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1618 {
1619     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1620
1621     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1622 }
1623
1624 static struct dp_netdev_flow *
1625 dp_netdev_flow_cast(const struct dpcls_rule *cr)
1626 {
1627     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1628 }
1629
1630 static bool dp_netdev_flow_ref(struct dp_netdev_flow *flow)
1631 {
1632     return ovs_refcount_try_ref_rcu(&flow->ref_cnt);
1633 }
1634
1635 /* netdev_flow_key utilities.
1636  *
1637  * netdev_flow_key is basically a miniflow.  We use these functions
1638  * (netdev_flow_key_clone, netdev_flow_key_equal, ...) instead of the miniflow
1639  * functions (miniflow_clone_inline, miniflow_equal, ...), because:
1640  *
1641  * - Since we are dealing exclusively with miniflows created by
1642  *   miniflow_extract(), if the map is different the miniflow is different.
1643  *   Therefore we can be faster by comparing the map and the miniflow in a
1644  *   single memcmp().
1645  * - These functions can be inlined by the compiler. */
1646
1647 /* Given the number of bits set in miniflow's maps, returns the size of the
1648  * 'netdev_flow_key.mf' */
1649 static inline size_t
1650 netdev_flow_key_size(size_t flow_u64s)
1651 {
1652     return sizeof(struct miniflow) + MINIFLOW_VALUES_SIZE(flow_u64s);
1653 }
1654
1655 static inline bool
1656 netdev_flow_key_equal(const struct netdev_flow_key *a,
1657                       const struct netdev_flow_key *b)
1658 {
1659     /* 'b->len' may be not set yet. */
1660     return a->hash == b->hash && !memcmp(&a->mf, &b->mf, a->len);
1661 }
1662
1663 /* Used to compare 'netdev_flow_key' in the exact match cache to a miniflow.
1664  * The maps are compared bitwise, so both 'key->mf' and 'mf' must have been
1665  * generated by miniflow_extract. */
1666 static inline bool
1667 netdev_flow_key_equal_mf(const struct netdev_flow_key *key,
1668                          const struct miniflow *mf)
1669 {
1670     return !memcmp(&key->mf, mf, key->len);
1671 }
1672
1673 static inline void
1674 netdev_flow_key_clone(struct netdev_flow_key *dst,
1675                       const struct netdev_flow_key *src)
1676 {
1677     memcpy(dst, src,
1678            offsetof(struct netdev_flow_key, mf) + src->len);
1679 }
1680
1681 /* Slow. */
1682 static void
1683 netdev_flow_key_from_flow(struct netdev_flow_key *dst,
1684                           const struct flow *src)
1685 {
1686     struct dp_packet packet;
1687     uint64_t buf_stub[512 / 8];
1688
1689     dp_packet_use_stub(&packet, buf_stub, sizeof buf_stub);
1690     pkt_metadata_from_flow(&packet.md, src);
1691     flow_compose(&packet, src);
1692     miniflow_extract(&packet, &dst->mf);
1693     dp_packet_uninit(&packet);
1694
1695     dst->len = netdev_flow_key_size(miniflow_n_values(&dst->mf));
1696     dst->hash = 0; /* Not computed yet. */
1697 }
1698
1699 /* Initialize a netdev_flow_key 'mask' from 'match'. */
1700 static inline void
1701 netdev_flow_mask_init(struct netdev_flow_key *mask,
1702                       const struct match *match)
1703 {
1704     uint64_t *dst = miniflow_values(&mask->mf);
1705     struct flowmap fmap;
1706     uint32_t hash = 0;
1707     size_t idx;
1708
1709     /* Only check masks that make sense for the flow. */
1710     flow_wc_map(&match->flow, &fmap);
1711     flowmap_init(&mask->mf.map);
1712
1713     FLOWMAP_FOR_EACH_INDEX(idx, fmap) {
1714         uint64_t mask_u64 = flow_u64_value(&match->wc.masks, idx);
1715
1716         if (mask_u64) {
1717             flowmap_set(&mask->mf.map, idx, 1);
1718             *dst++ = mask_u64;
1719             hash = hash_add64(hash, mask_u64);
1720         }
1721     }
1722
1723     map_t map;
1724
1725     FLOWMAP_FOR_EACH_MAP (map, mask->mf.map) {
1726         hash = hash_add64(hash, map);
1727     }
1728
1729     size_t n = dst - miniflow_get_values(&mask->mf);
1730
1731     mask->hash = hash_finish(hash, n * 8);
1732     mask->len = netdev_flow_key_size(n);
1733 }
1734
1735 /* Initializes 'dst' as a copy of 'flow' masked with 'mask'. */
1736 static inline void
1737 netdev_flow_key_init_masked(struct netdev_flow_key *dst,
1738                             const struct flow *flow,
1739                             const struct netdev_flow_key *mask)
1740 {
1741     uint64_t *dst_u64 = miniflow_values(&dst->mf);
1742     const uint64_t *mask_u64 = miniflow_get_values(&mask->mf);
1743     uint32_t hash = 0;
1744     uint64_t value;
1745
1746     dst->len = mask->len;
1747     dst->mf = mask->mf;   /* Copy maps. */
1748
1749     FLOW_FOR_EACH_IN_MAPS(value, flow, mask->mf.map) {
1750         *dst_u64 = value & *mask_u64++;
1751         hash = hash_add64(hash, *dst_u64++);
1752     }
1753     dst->hash = hash_finish(hash,
1754                             (dst_u64 - miniflow_get_values(&dst->mf)) * 8);
1755 }
1756
1757 /* Iterate through netdev_flow_key TNL u64 values specified by 'FLOWMAP'. */
1758 #define NETDEV_FLOW_KEY_FOR_EACH_IN_FLOWMAP(VALUE, KEY, FLOWMAP)   \
1759     MINIFLOW_FOR_EACH_IN_FLOWMAP(VALUE, &(KEY)->mf, FLOWMAP)
1760
1761 /* Returns a hash value for the bits of 'key' where there are 1-bits in
1762  * 'mask'. */
1763 static inline uint32_t
1764 netdev_flow_key_hash_in_mask(const struct netdev_flow_key *key,
1765                              const struct netdev_flow_key *mask)
1766 {
1767     const uint64_t *p = miniflow_get_values(&mask->mf);
1768     uint32_t hash = 0;
1769     uint64_t value;
1770
1771     NETDEV_FLOW_KEY_FOR_EACH_IN_FLOWMAP(value, key, mask->mf.map) {
1772         hash = hash_add64(hash, value & *p++);
1773     }
1774
1775     return hash_finish(hash, (p - miniflow_get_values(&mask->mf)) * 8);
1776 }
1777
1778 static inline bool
1779 emc_entry_alive(struct emc_entry *ce)
1780 {
1781     return ce->flow && !ce->flow->dead;
1782 }
1783
1784 static void
1785 emc_clear_entry(struct emc_entry *ce)
1786 {
1787     if (ce->flow) {
1788         dp_netdev_flow_unref(ce->flow);
1789         ce->flow = NULL;
1790     }
1791 }
1792
1793 static inline void
1794 emc_change_entry(struct emc_entry *ce, struct dp_netdev_flow *flow,
1795                  const struct netdev_flow_key *key)
1796 {
1797     if (ce->flow != flow) {
1798         if (ce->flow) {
1799             dp_netdev_flow_unref(ce->flow);
1800         }
1801
1802         if (dp_netdev_flow_ref(flow)) {
1803             ce->flow = flow;
1804         } else {
1805             ce->flow = NULL;
1806         }
1807     }
1808     if (key) {
1809         netdev_flow_key_clone(&ce->key, key);
1810     }
1811 }
1812
1813 static inline void
1814 emc_insert(struct emc_cache *cache, const struct netdev_flow_key *key,
1815            struct dp_netdev_flow *flow)
1816 {
1817     struct emc_entry *to_be_replaced = NULL;
1818     struct emc_entry *current_entry;
1819
1820     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
1821         if (netdev_flow_key_equal(&current_entry->key, key)) {
1822             /* We found the entry with the 'mf' miniflow */
1823             emc_change_entry(current_entry, flow, NULL);
1824             return;
1825         }
1826
1827         /* Replacement policy: put the flow in an empty (not alive) entry, or
1828          * in the first entry where it can be */
1829         if (!to_be_replaced
1830             || (emc_entry_alive(to_be_replaced)
1831                 && !emc_entry_alive(current_entry))
1832             || current_entry->key.hash < to_be_replaced->key.hash) {
1833             to_be_replaced = current_entry;
1834         }
1835     }
1836     /* We didn't find the miniflow in the cache.
1837      * The 'to_be_replaced' entry is where the new flow will be stored */
1838
1839     emc_change_entry(to_be_replaced, flow, key);
1840 }
1841
1842 static inline struct dp_netdev_flow *
1843 emc_lookup(struct emc_cache *cache, const struct netdev_flow_key *key)
1844 {
1845     struct emc_entry *current_entry;
1846
1847     EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
1848         if (current_entry->key.hash == key->hash
1849             && emc_entry_alive(current_entry)
1850             && netdev_flow_key_equal_mf(&current_entry->key, &key->mf)) {
1851
1852             /* We found the entry with the 'key->mf' miniflow */
1853             return current_entry->flow;
1854         }
1855     }
1856
1857     return NULL;
1858 }
1859
1860 static struct dp_netdev_flow *
1861 dp_netdev_pmd_lookup_flow(const struct dp_netdev_pmd_thread *pmd,
1862                           const struct netdev_flow_key *key)
1863 {
1864     struct dp_netdev_flow *netdev_flow;
1865     struct dpcls_rule *rule;
1866
1867     dpcls_lookup(&pmd->cls, key, &rule, 1);
1868     netdev_flow = dp_netdev_flow_cast(rule);
1869
1870     return netdev_flow;
1871 }
1872
1873 static struct dp_netdev_flow *
1874 dp_netdev_pmd_find_flow(const struct dp_netdev_pmd_thread *pmd,
1875                         const ovs_u128 *ufidp, const struct nlattr *key,
1876                         size_t key_len)
1877 {
1878     struct dp_netdev_flow *netdev_flow;
1879     struct flow flow;
1880     ovs_u128 ufid;
1881
1882     /* If a UFID is not provided, determine one based on the key. */
1883     if (!ufidp && key && key_len
1884         && !dpif_netdev_flow_from_nlattrs(key, key_len, &flow)) {
1885         dpif_flow_hash(pmd->dp->dpif, &flow, sizeof flow, &ufid);
1886         ufidp = &ufid;
1887     }
1888
1889     if (ufidp) {
1890         CMAP_FOR_EACH_WITH_HASH (netdev_flow, node, dp_netdev_flow_hash(ufidp),
1891                                  &pmd->flow_table) {
1892             if (ovs_u128_equals(netdev_flow->ufid, *ufidp)) {
1893                 return netdev_flow;
1894             }
1895         }
1896     }
1897
1898     return NULL;
1899 }
1900
1901 static void
1902 get_dpif_flow_stats(const struct dp_netdev_flow *netdev_flow_,
1903                     struct dpif_flow_stats *stats)
1904 {
1905     struct dp_netdev_flow *netdev_flow;
1906     unsigned long long n;
1907     long long used;
1908     uint16_t flags;
1909
1910     netdev_flow = CONST_CAST(struct dp_netdev_flow *, netdev_flow_);
1911
1912     atomic_read_relaxed(&netdev_flow->stats.packet_count, &n);
1913     stats->n_packets = n;
1914     atomic_read_relaxed(&netdev_flow->stats.byte_count, &n);
1915     stats->n_bytes = n;
1916     atomic_read_relaxed(&netdev_flow->stats.used, &used);
1917     stats->used = used;
1918     atomic_read_relaxed(&netdev_flow->stats.tcp_flags, &flags);
1919     stats->tcp_flags = flags;
1920 }
1921
1922 /* Converts to the dpif_flow format, using 'key_buf' and 'mask_buf' for
1923  * storing the netlink-formatted key/mask. 'key_buf' may be the same as
1924  * 'mask_buf'. Actions will be returned without copying, by relying on RCU to
1925  * protect them. */
1926 static void
1927 dp_netdev_flow_to_dpif_flow(const struct dp_netdev_flow *netdev_flow,
1928                             struct ofpbuf *key_buf, struct ofpbuf *mask_buf,
1929                             struct dpif_flow *flow, bool terse)
1930 {
1931     if (terse) {
1932         memset(flow, 0, sizeof *flow);
1933     } else {
1934         struct flow_wildcards wc;
1935         struct dp_netdev_actions *actions;
1936         size_t offset;
1937         struct odp_flow_key_parms odp_parms = {
1938             .flow = &netdev_flow->flow,
1939             .mask = &wc.masks,
1940             .support = dp_netdev_support,
1941         };
1942
1943         miniflow_expand(&netdev_flow->cr.mask->mf, &wc.masks);
1944
1945         /* Key */
1946         offset = key_buf->size;
1947         flow->key = ofpbuf_tail(key_buf);
1948         odp_flow_key_from_flow(&odp_parms, key_buf);
1949         flow->key_len = key_buf->size - offset;
1950
1951         /* Mask */
1952         offset = mask_buf->size;
1953         flow->mask = ofpbuf_tail(mask_buf);
1954         odp_parms.key_buf = key_buf;
1955         odp_flow_key_from_mask(&odp_parms, mask_buf);
1956         flow->mask_len = mask_buf->size - offset;
1957
1958         /* Actions */
1959         actions = dp_netdev_flow_get_actions(netdev_flow);
1960         flow->actions = actions->actions;
1961         flow->actions_len = actions->size;
1962     }
1963
1964     flow->ufid = netdev_flow->ufid;
1965     flow->ufid_present = true;
1966     flow->pmd_id = netdev_flow->pmd_id;
1967     get_dpif_flow_stats(netdev_flow, &flow->stats);
1968 }
1969
1970 static int
1971 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1972                               const struct nlattr *mask_key,
1973                               uint32_t mask_key_len, const struct flow *flow,
1974                               struct flow_wildcards *wc)
1975 {
1976     enum odp_key_fitness fitness;
1977
1978     fitness = odp_flow_key_to_mask_udpif(mask_key, mask_key_len, key,
1979                                          key_len, wc, flow);
1980     if (fitness) {
1981         /* This should not happen: it indicates that
1982          * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1983          * disagree on the acceptable form of a mask.  Log the problem
1984          * as an error, with enough details to enable debugging. */
1985         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1986
1987         if (!VLOG_DROP_ERR(&rl)) {
1988             struct ds s;
1989
1990             ds_init(&s);
1991             odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1992                             true);
1993             VLOG_ERR("internal error parsing flow mask %s (%s)",
1994                      ds_cstr(&s), odp_key_fitness_to_string(fitness));
1995             ds_destroy(&s);
1996         }
1997
1998         return EINVAL;
1999     }
2000
2001     return 0;
2002 }
2003
2004 static int
2005 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
2006                               struct flow *flow)
2007 {
2008     odp_port_t in_port;
2009
2010     if (odp_flow_key_to_flow_udpif(key, key_len, flow)) {
2011         /* This should not happen: it indicates that odp_flow_key_from_flow()
2012          * and odp_flow_key_to_flow() disagree on the acceptable form of a
2013          * flow.  Log the problem as an error, with enough details to enable
2014          * debugging. */
2015         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2016
2017         if (!VLOG_DROP_ERR(&rl)) {
2018             struct ds s;
2019
2020             ds_init(&s);
2021             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
2022             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
2023             ds_destroy(&s);
2024         }
2025
2026         return EINVAL;
2027     }
2028
2029     in_port = flow->in_port.odp_port;
2030     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
2031         return EINVAL;
2032     }
2033
2034     /* Userspace datapath doesn't support conntrack. */
2035     if (flow->ct_state || flow->ct_zone || flow->ct_mark
2036         || !ovs_u128_is_zero(flow->ct_label)) {
2037         return EINVAL;
2038     }
2039
2040     return 0;
2041 }
2042
2043 static int
2044 dpif_netdev_flow_get(const struct dpif *dpif, const struct dpif_flow_get *get)
2045 {
2046     struct dp_netdev *dp = get_dp_netdev(dpif);
2047     struct dp_netdev_flow *netdev_flow;
2048     struct dp_netdev_pmd_thread *pmd;
2049     struct hmapx to_find = HMAPX_INITIALIZER(&to_find);
2050     struct hmapx_node *node;
2051     int error = EINVAL;
2052
2053     if (get->pmd_id == PMD_ID_NULL) {
2054         CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2055             if (dp_netdev_pmd_try_ref(pmd) && !hmapx_add(&to_find, pmd)) {
2056                 dp_netdev_pmd_unref(pmd);
2057             }
2058         }
2059     } else {
2060         pmd = dp_netdev_get_pmd(dp, get->pmd_id);
2061         if (!pmd) {
2062             goto out;
2063         }
2064         hmapx_add(&to_find, pmd);
2065     }
2066
2067     if (!hmapx_count(&to_find)) {
2068         goto out;
2069     }
2070
2071     HMAPX_FOR_EACH (node, &to_find) {
2072         pmd = (struct dp_netdev_pmd_thread *) node->data;
2073         netdev_flow = dp_netdev_pmd_find_flow(pmd, get->ufid, get->key,
2074                                               get->key_len);
2075         if (netdev_flow) {
2076             dp_netdev_flow_to_dpif_flow(netdev_flow, get->buffer, get->buffer,
2077                                         get->flow, false);
2078             error = 0;
2079             break;
2080         } else {
2081             error = ENOENT;
2082         }
2083     }
2084
2085     HMAPX_FOR_EACH (node, &to_find) {
2086         pmd = (struct dp_netdev_pmd_thread *) node->data;
2087         dp_netdev_pmd_unref(pmd);
2088     }
2089 out:
2090     hmapx_destroy(&to_find);
2091     return error;
2092 }
2093
2094 static struct dp_netdev_flow *
2095 dp_netdev_flow_add(struct dp_netdev_pmd_thread *pmd,
2096                    struct match *match, const ovs_u128 *ufid,
2097                    const struct nlattr *actions, size_t actions_len)
2098     OVS_REQUIRES(pmd->flow_mutex)
2099 {
2100     struct dp_netdev_flow *flow;
2101     struct netdev_flow_key mask;
2102
2103     netdev_flow_mask_init(&mask, match);
2104     /* Make sure wc does not have metadata. */
2105     ovs_assert(!FLOWMAP_HAS_FIELD(&mask.mf.map, metadata)
2106                && !FLOWMAP_HAS_FIELD(&mask.mf.map, regs));
2107
2108     /* Do not allocate extra space. */
2109     flow = xmalloc(sizeof *flow - sizeof flow->cr.flow.mf + mask.len);
2110     memset(&flow->stats, 0, sizeof flow->stats);
2111     flow->dead = false;
2112     flow->batch = NULL;
2113     *CONST_CAST(unsigned *, &flow->pmd_id) = pmd->core_id;
2114     *CONST_CAST(struct flow *, &flow->flow) = match->flow;
2115     *CONST_CAST(ovs_u128 *, &flow->ufid) = *ufid;
2116     ovs_refcount_init(&flow->ref_cnt);
2117     ovsrcu_set(&flow->actions, dp_netdev_actions_create(actions, actions_len));
2118
2119     netdev_flow_key_init_masked(&flow->cr.flow, &match->flow, &mask);
2120     dpcls_insert(&pmd->cls, &flow->cr, &mask);
2121
2122     cmap_insert(&pmd->flow_table, CONST_CAST(struct cmap_node *, &flow->node),
2123                 dp_netdev_flow_hash(&flow->ufid));
2124
2125     if (OVS_UNLIKELY(VLOG_IS_DBG_ENABLED())) {
2126         struct ds ds = DS_EMPTY_INITIALIZER;
2127         struct ofpbuf key_buf, mask_buf;
2128         struct odp_flow_key_parms odp_parms = {
2129             .flow = &match->flow,
2130             .mask = &match->wc.masks,
2131             .support = dp_netdev_support,
2132         };
2133
2134         ofpbuf_init(&key_buf, 0);
2135         ofpbuf_init(&mask_buf, 0);
2136
2137         odp_flow_key_from_flow(&odp_parms, &key_buf);
2138         odp_parms.key_buf = &key_buf;
2139         odp_flow_key_from_mask(&odp_parms, &mask_buf);
2140
2141         ds_put_cstr(&ds, "flow_add: ");
2142         odp_format_ufid(ufid, &ds);
2143         ds_put_cstr(&ds, " ");
2144         odp_flow_format(key_buf.data, key_buf.size,
2145                         mask_buf.data, mask_buf.size,
2146                         NULL, &ds, false);
2147         ds_put_cstr(&ds, ", actions:");
2148         format_odp_actions(&ds, actions, actions_len);
2149
2150         VLOG_DBG_RL(&upcall_rl, "%s", ds_cstr(&ds));
2151
2152         ofpbuf_uninit(&key_buf);
2153         ofpbuf_uninit(&mask_buf);
2154         ds_destroy(&ds);
2155     }
2156
2157     return flow;
2158 }
2159
2160 static int
2161 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
2162 {
2163     struct dp_netdev *dp = get_dp_netdev(dpif);
2164     struct dp_netdev_flow *netdev_flow;
2165     struct netdev_flow_key key;
2166     struct dp_netdev_pmd_thread *pmd;
2167     struct match match;
2168     ovs_u128 ufid;
2169     unsigned pmd_id = put->pmd_id == PMD_ID_NULL
2170                       ? NON_PMD_CORE_ID : put->pmd_id;
2171     int error;
2172
2173     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &match.flow);
2174     if (error) {
2175         return error;
2176     }
2177     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
2178                                           put->mask, put->mask_len,
2179                                           &match.flow, &match.wc);
2180     if (error) {
2181         return error;
2182     }
2183
2184     pmd = dp_netdev_get_pmd(dp, pmd_id);
2185     if (!pmd) {
2186         return EINVAL;
2187     }
2188
2189     /* Must produce a netdev_flow_key for lookup.
2190      * This interface is no longer performance critical, since it is not used
2191      * for upcall processing any more. */
2192     netdev_flow_key_from_flow(&key, &match.flow);
2193
2194     if (put->ufid) {
2195         ufid = *put->ufid;
2196     } else {
2197         dpif_flow_hash(dpif, &match.flow, sizeof match.flow, &ufid);
2198     }
2199
2200     ovs_mutex_lock(&pmd->flow_mutex);
2201     netdev_flow = dp_netdev_pmd_lookup_flow(pmd, &key);
2202     if (!netdev_flow) {
2203         if (put->flags & DPIF_FP_CREATE) {
2204             if (cmap_count(&pmd->flow_table) < MAX_FLOWS) {
2205                 if (put->stats) {
2206                     memset(put->stats, 0, sizeof *put->stats);
2207                 }
2208                 dp_netdev_flow_add(pmd, &match, &ufid, put->actions,
2209                                    put->actions_len);
2210                 error = 0;
2211             } else {
2212                 error = EFBIG;
2213             }
2214         } else {
2215             error = ENOENT;
2216         }
2217     } else {
2218         if (put->flags & DPIF_FP_MODIFY
2219             && flow_equal(&match.flow, &netdev_flow->flow)) {
2220             struct dp_netdev_actions *new_actions;
2221             struct dp_netdev_actions *old_actions;
2222
2223             new_actions = dp_netdev_actions_create(put->actions,
2224                                                    put->actions_len);
2225
2226             old_actions = dp_netdev_flow_get_actions(netdev_flow);
2227             ovsrcu_set(&netdev_flow->actions, new_actions);
2228
2229             if (put->stats) {
2230                 get_dpif_flow_stats(netdev_flow, put->stats);
2231             }
2232             if (put->flags & DPIF_FP_ZERO_STATS) {
2233                 /* XXX: The userspace datapath uses thread local statistics
2234                  * (for flows), which should be updated only by the owning
2235                  * thread.  Since we cannot write on stats memory here,
2236                  * we choose not to support this flag.  Please note:
2237                  * - This feature is currently used only by dpctl commands with
2238                  *   option --clear.
2239                  * - Should the need arise, this operation can be implemented
2240                  *   by keeping a base value (to be update here) for each
2241                  *   counter, and subtracting it before outputting the stats */
2242                 error = EOPNOTSUPP;
2243             }
2244
2245             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
2246         } else if (put->flags & DPIF_FP_CREATE) {
2247             error = EEXIST;
2248         } else {
2249             /* Overlapping flow. */
2250             error = EINVAL;
2251         }
2252     }
2253     ovs_mutex_unlock(&pmd->flow_mutex);
2254     dp_netdev_pmd_unref(pmd);
2255
2256     return error;
2257 }
2258
2259 static int
2260 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
2261 {
2262     struct dp_netdev *dp = get_dp_netdev(dpif);
2263     struct dp_netdev_flow *netdev_flow;
2264     struct dp_netdev_pmd_thread *pmd;
2265     unsigned pmd_id = del->pmd_id == PMD_ID_NULL
2266                       ? NON_PMD_CORE_ID : del->pmd_id;
2267     int error = 0;
2268
2269     pmd = dp_netdev_get_pmd(dp, pmd_id);
2270     if (!pmd) {
2271         return EINVAL;
2272     }
2273
2274     ovs_mutex_lock(&pmd->flow_mutex);
2275     netdev_flow = dp_netdev_pmd_find_flow(pmd, del->ufid, del->key,
2276                                           del->key_len);
2277     if (netdev_flow) {
2278         if (del->stats) {
2279             get_dpif_flow_stats(netdev_flow, del->stats);
2280         }
2281         dp_netdev_pmd_remove_flow(pmd, netdev_flow);
2282     } else {
2283         error = ENOENT;
2284     }
2285     ovs_mutex_unlock(&pmd->flow_mutex);
2286     dp_netdev_pmd_unref(pmd);
2287
2288     return error;
2289 }
2290
2291 struct dpif_netdev_flow_dump {
2292     struct dpif_flow_dump up;
2293     struct cmap_position poll_thread_pos;
2294     struct cmap_position flow_pos;
2295     struct dp_netdev_pmd_thread *cur_pmd;
2296     int status;
2297     struct ovs_mutex mutex;
2298 };
2299
2300 static struct dpif_netdev_flow_dump *
2301 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
2302 {
2303     return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
2304 }
2305
2306 static struct dpif_flow_dump *
2307 dpif_netdev_flow_dump_create(const struct dpif *dpif_, bool terse)
2308 {
2309     struct dpif_netdev_flow_dump *dump;
2310
2311     dump = xzalloc(sizeof *dump);
2312     dpif_flow_dump_init(&dump->up, dpif_);
2313     dump->up.terse = terse;
2314     ovs_mutex_init(&dump->mutex);
2315
2316     return &dump->up;
2317 }
2318
2319 static int
2320 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
2321 {
2322     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
2323
2324     ovs_mutex_destroy(&dump->mutex);
2325     free(dump);
2326     return 0;
2327 }
2328
2329 struct dpif_netdev_flow_dump_thread {
2330     struct dpif_flow_dump_thread up;
2331     struct dpif_netdev_flow_dump *dump;
2332     struct odputil_keybuf keybuf[FLOW_DUMP_MAX_BATCH];
2333     struct odputil_keybuf maskbuf[FLOW_DUMP_MAX_BATCH];
2334 };
2335
2336 static struct dpif_netdev_flow_dump_thread *
2337 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
2338 {
2339     return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
2340 }
2341
2342 static struct dpif_flow_dump_thread *
2343 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
2344 {
2345     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
2346     struct dpif_netdev_flow_dump_thread *thread;
2347
2348     thread = xmalloc(sizeof *thread);
2349     dpif_flow_dump_thread_init(&thread->up, &dump->up);
2350     thread->dump = dump;
2351     return &thread->up;
2352 }
2353
2354 static void
2355 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
2356 {
2357     struct dpif_netdev_flow_dump_thread *thread
2358         = dpif_netdev_flow_dump_thread_cast(thread_);
2359
2360     free(thread);
2361 }
2362
2363 static int
2364 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
2365                            struct dpif_flow *flows, int max_flows)
2366 {
2367     struct dpif_netdev_flow_dump_thread *thread
2368         = dpif_netdev_flow_dump_thread_cast(thread_);
2369     struct dpif_netdev_flow_dump *dump = thread->dump;
2370     struct dp_netdev_flow *netdev_flows[FLOW_DUMP_MAX_BATCH];
2371     int n_flows = 0;
2372     int i;
2373
2374     ovs_mutex_lock(&dump->mutex);
2375     if (!dump->status) {
2376         struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
2377         struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
2378         struct dp_netdev_pmd_thread *pmd = dump->cur_pmd;
2379         int flow_limit = MIN(max_flows, FLOW_DUMP_MAX_BATCH);
2380
2381         /* First call to dump_next(), extracts the first pmd thread.
2382          * If there is no pmd thread, returns immediately. */
2383         if (!pmd) {
2384             pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
2385             if (!pmd) {
2386                 ovs_mutex_unlock(&dump->mutex);
2387                 return n_flows;
2388
2389             }
2390         }
2391
2392         do {
2393             for (n_flows = 0; n_flows < flow_limit; n_flows++) {
2394                 struct cmap_node *node;
2395
2396                 node = cmap_next_position(&pmd->flow_table, &dump->flow_pos);
2397                 if (!node) {
2398                     break;
2399                 }
2400                 netdev_flows[n_flows] = CONTAINER_OF(node,
2401                                                      struct dp_netdev_flow,
2402                                                      node);
2403             }
2404             /* When finishing dumping the current pmd thread, moves to
2405              * the next. */
2406             if (n_flows < flow_limit) {
2407                 memset(&dump->flow_pos, 0, sizeof dump->flow_pos);
2408                 dp_netdev_pmd_unref(pmd);
2409                 pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
2410                 if (!pmd) {
2411                     dump->status = EOF;
2412                     break;
2413                 }
2414             }
2415             /* Keeps the reference to next caller. */
2416             dump->cur_pmd = pmd;
2417
2418             /* If the current dump is empty, do not exit the loop, since the
2419              * remaining pmds could have flows to be dumped.  Just dumps again
2420              * on the new 'pmd'. */
2421         } while (!n_flows);
2422     }
2423     ovs_mutex_unlock(&dump->mutex);
2424
2425     for (i = 0; i < n_flows; i++) {
2426         struct odputil_keybuf *maskbuf = &thread->maskbuf[i];
2427         struct odputil_keybuf *keybuf = &thread->keybuf[i];
2428         struct dp_netdev_flow *netdev_flow = netdev_flows[i];
2429         struct dpif_flow *f = &flows[i];
2430         struct ofpbuf key, mask;
2431
2432         ofpbuf_use_stack(&key, keybuf, sizeof *keybuf);
2433         ofpbuf_use_stack(&mask, maskbuf, sizeof *maskbuf);
2434         dp_netdev_flow_to_dpif_flow(netdev_flow, &key, &mask, f,
2435                                     dump->up.terse);
2436     }
2437
2438     return n_flows;
2439 }
2440
2441 static int
2442 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
2443     OVS_NO_THREAD_SAFETY_ANALYSIS
2444 {
2445     struct dp_netdev *dp = get_dp_netdev(dpif);
2446     struct dp_netdev_pmd_thread *pmd;
2447     struct dp_packet_batch pp;
2448
2449     if (dp_packet_size(execute->packet) < ETH_HEADER_LEN ||
2450         dp_packet_size(execute->packet) > UINT16_MAX) {
2451         return EINVAL;
2452     }
2453
2454     /* Tries finding the 'pmd'.  If NULL is returned, that means
2455      * the current thread is a non-pmd thread and should use
2456      * dp_netdev_get_pmd(dp, NON_PMD_CORE_ID). */
2457     pmd = ovsthread_getspecific(dp->per_pmd_key);
2458     if (!pmd) {
2459         pmd = dp_netdev_get_pmd(dp, NON_PMD_CORE_ID);
2460     }
2461
2462     /* If the current thread is non-pmd thread, acquires
2463      * the 'non_pmd_mutex'. */
2464     if (pmd->core_id == NON_PMD_CORE_ID) {
2465         ovs_mutex_lock(&dp->non_pmd_mutex);
2466     }
2467
2468     /* The action processing expects the RSS hash to be valid, because
2469      * it's always initialized at the beginning of datapath processing.
2470      * In this case, though, 'execute->packet' may not have gone through
2471      * the datapath at all, it may have been generated by the upper layer
2472      * (OpenFlow packet-out, BFD frame, ...). */
2473     if (!dp_packet_rss_valid(execute->packet)) {
2474         dp_packet_set_rss_hash(execute->packet,
2475                                flow_hash_5tuple(execute->flow, 0));
2476     }
2477
2478     packet_batch_init_packet(&pp, execute->packet);
2479     dp_netdev_execute_actions(pmd, &pp, false, execute->actions,
2480                               execute->actions_len);
2481
2482     if (pmd->core_id == NON_PMD_CORE_ID) {
2483         ovs_mutex_unlock(&dp->non_pmd_mutex);
2484         dp_netdev_pmd_unref(pmd);
2485     }
2486
2487     return 0;
2488 }
2489
2490 static void
2491 dpif_netdev_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
2492 {
2493     size_t i;
2494
2495     for (i = 0; i < n_ops; i++) {
2496         struct dpif_op *op = ops[i];
2497
2498         switch (op->type) {
2499         case DPIF_OP_FLOW_PUT:
2500             op->error = dpif_netdev_flow_put(dpif, &op->u.flow_put);
2501             break;
2502
2503         case DPIF_OP_FLOW_DEL:
2504             op->error = dpif_netdev_flow_del(dpif, &op->u.flow_del);
2505             break;
2506
2507         case DPIF_OP_EXECUTE:
2508             op->error = dpif_netdev_execute(dpif, &op->u.execute);
2509             break;
2510
2511         case DPIF_OP_FLOW_GET:
2512             op->error = dpif_netdev_flow_get(dpif, &op->u.flow_get);
2513             break;
2514         }
2515     }
2516 }
2517
2518 /* Changes the number or the affinity of pmd threads.  The changes are actually
2519  * applied in dpif_netdev_run(). */
2520 static int
2521 dpif_netdev_pmd_set(struct dpif *dpif, const char *cmask)
2522 {
2523     struct dp_netdev *dp = get_dp_netdev(dpif);
2524
2525     if (!nullable_string_is_equal(dp->requested_pmd_cmask, cmask)) {
2526         free(dp->requested_pmd_cmask);
2527         dp->requested_pmd_cmask = nullable_xstrdup(cmask);
2528     }
2529
2530     return 0;
2531 }
2532
2533 static int
2534 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
2535                               uint32_t queue_id, uint32_t *priority)
2536 {
2537     *priority = queue_id;
2538     return 0;
2539 }
2540
2541 \f
2542 /* Creates and returns a new 'struct dp_netdev_actions', whose actions are
2543  * a copy of the 'ofpacts_len' bytes of 'ofpacts'. */
2544 struct dp_netdev_actions *
2545 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
2546 {
2547     struct dp_netdev_actions *netdev_actions;
2548
2549     netdev_actions = xmalloc(sizeof *netdev_actions + size);
2550     memcpy(netdev_actions->actions, actions, size);
2551     netdev_actions->size = size;
2552
2553     return netdev_actions;
2554 }
2555
2556 struct dp_netdev_actions *
2557 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
2558 {
2559     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
2560 }
2561
2562 static void
2563 dp_netdev_actions_free(struct dp_netdev_actions *actions)
2564 {
2565     free(actions);
2566 }
2567 \f
2568 static inline unsigned long long
2569 cycles_counter(void)
2570 {
2571 #ifdef DPDK_NETDEV
2572     return rte_get_tsc_cycles();
2573 #else
2574     return 0;
2575 #endif
2576 }
2577
2578 /* Fake mutex to make sure that the calls to cycles_count_* are balanced */
2579 extern struct ovs_mutex cycles_counter_fake_mutex;
2580
2581 /* Start counting cycles.  Must be followed by 'cycles_count_end()' */
2582 static inline void
2583 cycles_count_start(struct dp_netdev_pmd_thread *pmd)
2584     OVS_ACQUIRES(&cycles_counter_fake_mutex)
2585     OVS_NO_THREAD_SAFETY_ANALYSIS
2586 {
2587     pmd->last_cycles = cycles_counter();
2588 }
2589
2590 /* Stop counting cycles and add them to the counter 'type' */
2591 static inline void
2592 cycles_count_end(struct dp_netdev_pmd_thread *pmd,
2593                  enum pmd_cycles_counter_type type)
2594     OVS_RELEASES(&cycles_counter_fake_mutex)
2595     OVS_NO_THREAD_SAFETY_ANALYSIS
2596 {
2597     unsigned long long interval = cycles_counter() - pmd->last_cycles;
2598
2599     non_atomic_ullong_add(&pmd->cycles.n[type], interval);
2600 }
2601
2602 static void
2603 dp_netdev_process_rxq_port(struct dp_netdev_pmd_thread *pmd,
2604                            struct dp_netdev_port *port,
2605                            struct netdev_rxq *rxq)
2606 {
2607     struct dp_packet_batch batch;
2608     int error;
2609
2610     dp_packet_batch_init(&batch);
2611     cycles_count_start(pmd);
2612     error = netdev_rxq_recv(rxq, &batch);
2613     cycles_count_end(pmd, PMD_CYCLES_POLLING);
2614     if (!error) {
2615         *recirc_depth_get() = 0;
2616
2617         cycles_count_start(pmd);
2618         dp_netdev_input(pmd, &batch, port->port_no);
2619         cycles_count_end(pmd, PMD_CYCLES_PROCESSING);
2620     } else if (error != EAGAIN && error != EOPNOTSUPP) {
2621         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2622
2623         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
2624                     netdev_get_name(port->netdev), ovs_strerror(error));
2625     }
2626 }
2627
2628 static int
2629 port_reconfigure(struct dp_netdev_port *port)
2630 {
2631     struct netdev *netdev = port->netdev;
2632     int i, err;
2633
2634     if (!netdev_is_reconf_required(netdev)) {
2635         return 0;
2636     }
2637
2638     /* Closes the existing 'rxq's. */
2639     for (i = 0; i < port->n_rxq; i++) {
2640         netdev_rxq_close(port->rxq[i]);
2641         port->rxq[i] = NULL;
2642     }
2643     port->n_rxq = 0;
2644
2645     /* Allows 'netdev' to apply the pending configuration changes. */
2646     err = netdev_reconfigure(netdev);
2647     if (err && (err != EOPNOTSUPP)) {
2648         VLOG_ERR("Failed to set interface %s new configuration",
2649                  netdev_get_name(netdev));
2650         return err;
2651     }
2652     /* If the netdev_reconfigure() above succeeds, reopens the 'rxq's. */
2653     port->rxq = xrealloc(port->rxq, sizeof *port->rxq * netdev_n_rxq(netdev));
2654     for (i = 0; i < netdev_n_rxq(netdev); i++) {
2655         err = netdev_rxq_open(netdev, &port->rxq[i], i);
2656         if (err) {
2657             return err;
2658         }
2659         port->n_rxq++;
2660     }
2661
2662     return 0;
2663 }
2664
2665 static void
2666 reconfigure_pmd_threads(struct dp_netdev *dp)
2667     OVS_REQUIRES(dp->port_mutex)
2668 {
2669     struct dp_netdev_port *port, *next;
2670
2671     dp_netdev_destroy_all_pmds(dp);
2672
2673     HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
2674         int err;
2675
2676         err = port_reconfigure(port);
2677         if (err) {
2678             hmap_remove(&dp->ports, &port->node);
2679             seq_change(dp->port_seq);
2680             port_destroy(port);
2681         }
2682     }
2683     /* Reconfigures the cpu mask. */
2684     ovs_numa_set_cpu_mask(dp->requested_pmd_cmask);
2685     free(dp->pmd_cmask);
2686     dp->pmd_cmask = nullable_xstrdup(dp->requested_pmd_cmask);
2687
2688     /* Restores the non-pmd. */
2689     dp_netdev_set_nonpmd(dp);
2690     /* Restores all pmd threads. */
2691     dp_netdev_reset_pmd_threads(dp);
2692 }
2693
2694 /* Returns true if one of the netdevs in 'dp' requires a reconfiguration */
2695 static bool
2696 ports_require_restart(const struct dp_netdev *dp)
2697     OVS_REQUIRES(dp->port_mutex)
2698 {
2699     struct dp_netdev_port *port;
2700
2701     HMAP_FOR_EACH (port, node, &dp->ports) {
2702         if (netdev_is_reconf_required(port->netdev)) {
2703             return true;
2704         }
2705     }
2706
2707     return false;
2708 }
2709
2710 /* Return true if needs to revalidate datapath flows. */
2711 static bool
2712 dpif_netdev_run(struct dpif *dpif)
2713 {
2714     struct dp_netdev_port *port;
2715     struct dp_netdev *dp = get_dp_netdev(dpif);
2716     struct dp_netdev_pmd_thread *non_pmd = dp_netdev_get_pmd(dp,
2717                                                              NON_PMD_CORE_ID);
2718     uint64_t new_tnl_seq;
2719
2720     ovs_mutex_lock(&dp->port_mutex);
2721     ovs_mutex_lock(&dp->non_pmd_mutex);
2722     HMAP_FOR_EACH (port, node, &dp->ports) {
2723         if (!netdev_is_pmd(port->netdev)) {
2724             int i;
2725
2726             for (i = 0; i < port->n_rxq; i++) {
2727                 dp_netdev_process_rxq_port(non_pmd, port, port->rxq[i]);
2728             }
2729         }
2730     }
2731     ovs_mutex_unlock(&dp->non_pmd_mutex);
2732
2733     dp_netdev_pmd_unref(non_pmd);
2734
2735     if (!nullable_string_is_equal(dp->pmd_cmask, dp->requested_pmd_cmask)
2736         || ports_require_restart(dp)) {
2737         reconfigure_pmd_threads(dp);
2738     }
2739     ovs_mutex_unlock(&dp->port_mutex);
2740
2741     tnl_neigh_cache_run();
2742     tnl_port_map_run();
2743     new_tnl_seq = seq_read(tnl_conf_seq);
2744
2745     if (dp->last_tnl_conf_seq != new_tnl_seq) {
2746         dp->last_tnl_conf_seq = new_tnl_seq;
2747         return true;
2748     }
2749     return false;
2750 }
2751
2752 static void
2753 dpif_netdev_wait(struct dpif *dpif)
2754 {
2755     struct dp_netdev_port *port;
2756     struct dp_netdev *dp = get_dp_netdev(dpif);
2757
2758     ovs_mutex_lock(&dp_netdev_mutex);
2759     ovs_mutex_lock(&dp->port_mutex);
2760     HMAP_FOR_EACH (port, node, &dp->ports) {
2761         netdev_wait_reconf_required(port->netdev);
2762         if (!netdev_is_pmd(port->netdev)) {
2763             int i;
2764
2765             for (i = 0; i < port->n_rxq; i++) {
2766                 netdev_rxq_wait(port->rxq[i]);
2767             }
2768         }
2769     }
2770     ovs_mutex_unlock(&dp->port_mutex);
2771     ovs_mutex_unlock(&dp_netdev_mutex);
2772     seq_wait(tnl_conf_seq, dp->last_tnl_conf_seq);
2773 }
2774
2775 static void
2776 pmd_free_cached_ports(struct dp_netdev_pmd_thread *pmd)
2777 {
2778     struct tx_port *tx_port_cached;
2779
2780     HMAP_FOR_EACH_POP (tx_port_cached, node, &pmd->port_cache) {
2781         free(tx_port_cached);
2782     }
2783 }
2784
2785 /* Copies ports from 'pmd->tx_ports' (shared with the main thread) to
2786  * 'pmd->port_cache' (thread local) */
2787 static void
2788 pmd_load_cached_ports(struct dp_netdev_pmd_thread *pmd)
2789     OVS_REQUIRES(pmd->port_mutex)
2790 {
2791     struct tx_port *tx_port, *tx_port_cached;
2792
2793     pmd_free_cached_ports(pmd);
2794     hmap_shrink(&pmd->port_cache);
2795
2796     HMAP_FOR_EACH (tx_port, node, &pmd->tx_ports) {
2797         tx_port_cached = xmemdup(tx_port, sizeof *tx_port_cached);
2798         hmap_insert(&pmd->port_cache, &tx_port_cached->node,
2799                     hash_port_no(tx_port_cached->port_no));
2800     }
2801 }
2802
2803 static int
2804 pmd_load_queues_and_ports(struct dp_netdev_pmd_thread *pmd,
2805                           struct rxq_poll **ppoll_list)
2806 {
2807     struct rxq_poll *poll_list = *ppoll_list;
2808     struct rxq_poll *poll;
2809     int i;
2810
2811     ovs_mutex_lock(&pmd->port_mutex);
2812     poll_list = xrealloc(poll_list, pmd->poll_cnt * sizeof *poll_list);
2813
2814     i = 0;
2815     LIST_FOR_EACH (poll, node, &pmd->poll_list) {
2816         poll_list[i++] = *poll;
2817     }
2818
2819     pmd_load_cached_ports(pmd);
2820
2821     ovs_mutex_unlock(&pmd->port_mutex);
2822
2823     *ppoll_list = poll_list;
2824     return i;
2825 }
2826
2827 static void *
2828 pmd_thread_main(void *f_)
2829 {
2830     struct dp_netdev_pmd_thread *pmd = f_;
2831     unsigned int lc = 0;
2832     struct rxq_poll *poll_list;
2833     unsigned int port_seq = PMD_INITIAL_SEQ;
2834     bool exiting;
2835     int poll_cnt;
2836     int i;
2837
2838     poll_list = NULL;
2839
2840     /* Stores the pmd thread's 'pmd' to 'per_pmd_key'. */
2841     ovsthread_setspecific(pmd->dp->per_pmd_key, pmd);
2842     ovs_numa_thread_setaffinity_core(pmd->core_id);
2843     dpdk_set_lcore_id(pmd->core_id);
2844     poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
2845 reload:
2846     emc_cache_init(&pmd->flow_cache);
2847
2848     /* List port/core affinity */
2849     for (i = 0; i < poll_cnt; i++) {
2850        VLOG_DBG("Core %d processing port \'%s\' with queue-id %d\n",
2851                 pmd->core_id, netdev_get_name(poll_list[i].port->netdev),
2852                 netdev_rxq_get_queue_id(poll_list[i].rx));
2853     }
2854
2855     for (;;) {
2856         for (i = 0; i < poll_cnt; i++) {
2857             dp_netdev_process_rxq_port(pmd, poll_list[i].port, poll_list[i].rx);
2858         }
2859
2860         if (lc++ > 1024) {
2861             unsigned int seq;
2862
2863             lc = 0;
2864
2865             coverage_try_clear();
2866             if (!ovsrcu_try_quiesce()) {
2867                 emc_cache_slow_sweep(&pmd->flow_cache);
2868             }
2869
2870             atomic_read_relaxed(&pmd->change_seq, &seq);
2871             if (seq != port_seq) {
2872                 port_seq = seq;
2873                 break;
2874             }
2875         }
2876     }
2877
2878     poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
2879     exiting = latch_is_set(&pmd->exit_latch);
2880     /* Signal here to make sure the pmd finishes
2881      * reloading the updated configuration. */
2882     dp_netdev_pmd_reload_done(pmd);
2883
2884     emc_cache_uninit(&pmd->flow_cache);
2885
2886     if (!exiting) {
2887         goto reload;
2888     }
2889
2890     free(poll_list);
2891     pmd_free_cached_ports(pmd);
2892     return NULL;
2893 }
2894
2895 static void
2896 dp_netdev_disable_upcall(struct dp_netdev *dp)
2897     OVS_ACQUIRES(dp->upcall_rwlock)
2898 {
2899     fat_rwlock_wrlock(&dp->upcall_rwlock);
2900 }
2901
2902 static void
2903 dpif_netdev_disable_upcall(struct dpif *dpif)
2904     OVS_NO_THREAD_SAFETY_ANALYSIS
2905 {
2906     struct dp_netdev *dp = get_dp_netdev(dpif);
2907     dp_netdev_disable_upcall(dp);
2908 }
2909
2910 static void
2911 dp_netdev_enable_upcall(struct dp_netdev *dp)
2912     OVS_RELEASES(dp->upcall_rwlock)
2913 {
2914     fat_rwlock_unlock(&dp->upcall_rwlock);
2915 }
2916
2917 static void
2918 dpif_netdev_enable_upcall(struct dpif *dpif)
2919     OVS_NO_THREAD_SAFETY_ANALYSIS
2920 {
2921     struct dp_netdev *dp = get_dp_netdev(dpif);
2922     dp_netdev_enable_upcall(dp);
2923 }
2924
2925 static void
2926 dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd)
2927 {
2928     ovs_mutex_lock(&pmd->cond_mutex);
2929     xpthread_cond_signal(&pmd->cond);
2930     ovs_mutex_unlock(&pmd->cond_mutex);
2931 }
2932
2933 /* Finds and refs the dp_netdev_pmd_thread on core 'core_id'.  Returns
2934  * the pointer if succeeds, otherwise, NULL.
2935  *
2936  * Caller must unrefs the returned reference.  */
2937 static struct dp_netdev_pmd_thread *
2938 dp_netdev_get_pmd(struct dp_netdev *dp, unsigned core_id)
2939 {
2940     struct dp_netdev_pmd_thread *pmd;
2941     const struct cmap_node *pnode;
2942
2943     pnode = cmap_find(&dp->poll_threads, hash_int(core_id, 0));
2944     if (!pnode) {
2945         return NULL;
2946     }
2947     pmd = CONTAINER_OF(pnode, struct dp_netdev_pmd_thread, node);
2948
2949     return dp_netdev_pmd_try_ref(pmd) ? pmd : NULL;
2950 }
2951
2952 /* Sets the 'struct dp_netdev_pmd_thread' for non-pmd threads. */
2953 static void
2954 dp_netdev_set_nonpmd(struct dp_netdev *dp)
2955     OVS_REQUIRES(dp->port_mutex)
2956 {
2957     struct dp_netdev_pmd_thread *non_pmd;
2958     struct dp_netdev_port *port;
2959
2960     non_pmd = xzalloc(sizeof *non_pmd);
2961     dp_netdev_configure_pmd(non_pmd, dp, NON_PMD_CORE_ID, OVS_NUMA_UNSPEC);
2962
2963     HMAP_FOR_EACH (port, node, &dp->ports) {
2964         dp_netdev_add_port_tx_to_pmd(non_pmd, port);
2965     }
2966
2967     dp_netdev_reload_pmd__(non_pmd);
2968 }
2969
2970 /* Caller must have valid pointer to 'pmd'. */
2971 static bool
2972 dp_netdev_pmd_try_ref(struct dp_netdev_pmd_thread *pmd)
2973 {
2974     return ovs_refcount_try_ref_rcu(&pmd->ref_cnt);
2975 }
2976
2977 static void
2978 dp_netdev_pmd_unref(struct dp_netdev_pmd_thread *pmd)
2979 {
2980     if (pmd && ovs_refcount_unref(&pmd->ref_cnt) == 1) {
2981         ovsrcu_postpone(dp_netdev_destroy_pmd, pmd);
2982     }
2983 }
2984
2985 /* Given cmap position 'pos', tries to ref the next node.  If try_ref()
2986  * fails, keeps checking for next node until reaching the end of cmap.
2987  *
2988  * Caller must unrefs the returned reference. */
2989 static struct dp_netdev_pmd_thread *
2990 dp_netdev_pmd_get_next(struct dp_netdev *dp, struct cmap_position *pos)
2991 {
2992     struct dp_netdev_pmd_thread *next;
2993
2994     do {
2995         struct cmap_node *node;
2996
2997         node = cmap_next_position(&dp->poll_threads, pos);
2998         next = node ? CONTAINER_OF(node, struct dp_netdev_pmd_thread, node)
2999             : NULL;
3000     } while (next && !dp_netdev_pmd_try_ref(next));
3001
3002     return next;
3003 }
3004
3005 /* Configures the 'pmd' based on the input argument. */
3006 static void
3007 dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd, struct dp_netdev *dp,
3008                         unsigned core_id, int numa_id)
3009 {
3010     pmd->dp = dp;
3011     pmd->core_id = core_id;
3012     pmd->numa_id = numa_id;
3013     pmd->poll_cnt = 0;
3014
3015     atomic_init(&pmd->tx_qid,
3016                 (core_id == NON_PMD_CORE_ID)
3017                 ? ovs_numa_get_n_cores()
3018                 : get_n_pmd_threads(dp));
3019
3020     ovs_refcount_init(&pmd->ref_cnt);
3021     latch_init(&pmd->exit_latch);
3022     atomic_init(&pmd->change_seq, PMD_INITIAL_SEQ);
3023     xpthread_cond_init(&pmd->cond, NULL);
3024     ovs_mutex_init(&pmd->cond_mutex);
3025     ovs_mutex_init(&pmd->flow_mutex);
3026     ovs_mutex_init(&pmd->port_mutex);
3027     dpcls_init(&pmd->cls);
3028     cmap_init(&pmd->flow_table);
3029     ovs_list_init(&pmd->poll_list);
3030     hmap_init(&pmd->tx_ports);
3031     hmap_init(&pmd->port_cache);
3032     /* init the 'flow_cache' since there is no
3033      * actual thread created for NON_PMD_CORE_ID. */
3034     if (core_id == NON_PMD_CORE_ID) {
3035         emc_cache_init(&pmd->flow_cache);
3036     }
3037     cmap_insert(&dp->poll_threads, CONST_CAST(struct cmap_node *, &pmd->node),
3038                 hash_int(core_id, 0));
3039 }
3040
3041 static void
3042 dp_netdev_destroy_pmd(struct dp_netdev_pmd_thread *pmd)
3043 {
3044     dp_netdev_pmd_flow_flush(pmd);
3045     dpcls_destroy(&pmd->cls);
3046     hmap_destroy(&pmd->port_cache);
3047     hmap_destroy(&pmd->tx_ports);
3048     cmap_destroy(&pmd->flow_table);
3049     ovs_mutex_destroy(&pmd->flow_mutex);
3050     latch_destroy(&pmd->exit_latch);
3051     xpthread_cond_destroy(&pmd->cond);
3052     ovs_mutex_destroy(&pmd->cond_mutex);
3053     ovs_mutex_destroy(&pmd->port_mutex);
3054     free(pmd);
3055 }
3056
3057 /* Stops the pmd thread, removes it from the 'dp->poll_threads',
3058  * and unrefs the struct. */
3059 static void
3060 dp_netdev_del_pmd(struct dp_netdev *dp, struct dp_netdev_pmd_thread *pmd)
3061 {
3062     /* NON_PMD_CORE_ID doesn't have a thread, so we don't have to synchronize,
3063      * but extra cleanup is necessary */
3064     if (pmd->core_id == NON_PMD_CORE_ID) {
3065         emc_cache_uninit(&pmd->flow_cache);
3066         pmd_free_cached_ports(pmd);
3067     } else {
3068         latch_set(&pmd->exit_latch);
3069         dp_netdev_reload_pmd__(pmd);
3070         ovs_numa_unpin_core(pmd->core_id);
3071         xpthread_join(pmd->thread, NULL);
3072     }
3073
3074     dp_netdev_pmd_clear_ports(pmd);
3075
3076     /* Purges the 'pmd''s flows after stopping the thread, but before
3077      * destroying the flows, so that the flow stats can be collected. */
3078     if (dp->dp_purge_cb) {
3079         dp->dp_purge_cb(dp->dp_purge_aux, pmd->core_id);
3080     }
3081     cmap_remove(&pmd->dp->poll_threads, &pmd->node, hash_int(pmd->core_id, 0));
3082     dp_netdev_pmd_unref(pmd);
3083 }
3084
3085 /* Destroys all pmd threads. */
3086 static void
3087 dp_netdev_destroy_all_pmds(struct dp_netdev *dp)
3088 {
3089     struct dp_netdev_pmd_thread *pmd;
3090     struct dp_netdev_pmd_thread **pmd_list;
3091     size_t k = 0, n_pmds;
3092
3093     n_pmds = cmap_count(&dp->poll_threads);
3094     pmd_list = xcalloc(n_pmds, sizeof *pmd_list);
3095
3096     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3097         /* We cannot call dp_netdev_del_pmd(), since it alters
3098          * 'dp->poll_threads' (while we're iterating it) and it
3099          * might quiesce. */
3100         ovs_assert(k < n_pmds);
3101         pmd_list[k++] = pmd;
3102     }
3103
3104     for (size_t i = 0; i < k; i++) {
3105         dp_netdev_del_pmd(dp, pmd_list[i]);
3106     }
3107     free(pmd_list);
3108 }
3109
3110 /* Deletes all pmd threads on numa node 'numa_id' and
3111  * fixes tx_qids of other threads to keep them sequential. */
3112 static void
3113 dp_netdev_del_pmds_on_numa(struct dp_netdev *dp, int numa_id)
3114 {
3115     struct dp_netdev_pmd_thread *pmd;
3116     int n_pmds_on_numa, n_pmds;
3117     int *free_idx, k = 0;
3118     struct dp_netdev_pmd_thread **pmd_list;
3119
3120     n_pmds_on_numa = get_n_pmd_threads_on_numa(dp, numa_id);
3121     free_idx = xcalloc(n_pmds_on_numa, sizeof *free_idx);
3122     pmd_list = xcalloc(n_pmds_on_numa, sizeof *pmd_list);
3123
3124     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3125         /* We cannot call dp_netdev_del_pmd(), since it alters
3126          * 'dp->poll_threads' (while we're iterating it) and it
3127          * might quiesce. */
3128         if (pmd->numa_id == numa_id) {
3129             atomic_read_relaxed(&pmd->tx_qid, &free_idx[k]);
3130             pmd_list[k] = pmd;
3131             ovs_assert(k < n_pmds_on_numa);
3132             k++;
3133         }
3134     }
3135
3136     for (int i = 0; i < k; i++) {
3137         dp_netdev_del_pmd(dp, pmd_list[i]);
3138     }
3139
3140     n_pmds = get_n_pmd_threads(dp);
3141     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3142         int old_tx_qid;
3143
3144         atomic_read_relaxed(&pmd->tx_qid, &old_tx_qid);
3145
3146         if (old_tx_qid >= n_pmds) {
3147             int new_tx_qid = free_idx[--k];
3148
3149             atomic_store_relaxed(&pmd->tx_qid, new_tx_qid);
3150         }
3151     }
3152
3153     free(pmd_list);
3154     free(free_idx);
3155 }
3156
3157 /* Deletes all rx queues from pmd->poll_list and all the ports from
3158  * pmd->tx_ports. */
3159 static void
3160 dp_netdev_pmd_clear_ports(struct dp_netdev_pmd_thread *pmd)
3161 {
3162     struct rxq_poll *poll;
3163     struct tx_port *port;
3164
3165     ovs_mutex_lock(&pmd->port_mutex);
3166     LIST_FOR_EACH_POP (poll, node, &pmd->poll_list) {
3167         free(poll);
3168     }
3169     pmd->poll_cnt = 0;
3170     HMAP_FOR_EACH_POP (port, node, &pmd->tx_ports) {
3171         free(port);
3172     }
3173     ovs_mutex_unlock(&pmd->port_mutex);
3174 }
3175
3176 static struct tx_port *
3177 tx_port_lookup(const struct hmap *hmap, odp_port_t port_no)
3178 {
3179     struct tx_port *tx;
3180
3181     HMAP_FOR_EACH_IN_BUCKET (tx, node, hash_port_no(port_no), hmap) {
3182         if (tx->port_no == port_no) {
3183             return tx;
3184         }
3185     }
3186
3187     return NULL;
3188 }
3189
3190 /* Deletes all rx queues of 'port' from 'poll_list', and the 'port' from
3191  * 'tx_ports' of 'pmd' thread.  Returns true if 'port' was found in 'pmd'
3192  * (therefore a restart is required). */
3193 static bool
3194 dp_netdev_del_port_from_pmd__(struct dp_netdev_port *port,
3195                               struct dp_netdev_pmd_thread *pmd)
3196 {
3197     struct rxq_poll *poll, *next;
3198     struct tx_port *tx;
3199     bool found = false;
3200
3201     ovs_mutex_lock(&pmd->port_mutex);
3202     LIST_FOR_EACH_SAFE (poll, next, node, &pmd->poll_list) {
3203         if (poll->port == port) {
3204             found = true;
3205             ovs_list_remove(&poll->node);
3206             pmd->poll_cnt--;
3207             free(poll);
3208         }
3209     }
3210
3211     tx = tx_port_lookup(&pmd->tx_ports, port->port_no);
3212     if (tx) {
3213         hmap_remove(&pmd->tx_ports, &tx->node);
3214         free(tx);
3215         found = true;
3216     }
3217     ovs_mutex_unlock(&pmd->port_mutex);
3218
3219     return found;
3220 }
3221
3222 /* Deletes 'port' from the 'poll_list' and from the 'tx_ports' of all the pmd
3223  * threads.  The pmd threads that need to be restarted are inserted in
3224  * 'to_reload'. */
3225 static void
3226 dp_netdev_del_port_from_all_pmds__(struct dp_netdev *dp,
3227                                    struct dp_netdev_port *port,
3228                                    struct hmapx *to_reload)
3229 {
3230     struct dp_netdev_pmd_thread *pmd;
3231
3232     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3233         bool found;
3234
3235         found = dp_netdev_del_port_from_pmd__(port, pmd);
3236
3237         if (found) {
3238             hmapx_add(to_reload, pmd);
3239         }
3240     }
3241 }
3242
3243 /* Deletes 'port' from the 'poll_list' and from the 'tx_ports' of all the pmd
3244  * threads. Reloads the threads if needed. */
3245 static void
3246 dp_netdev_del_port_from_all_pmds(struct dp_netdev *dp,
3247                                  struct dp_netdev_port *port)
3248 {
3249     struct dp_netdev_pmd_thread *pmd;
3250     struct hmapx to_reload = HMAPX_INITIALIZER(&to_reload);
3251     struct hmapx_node *node;
3252
3253     dp_netdev_del_port_from_all_pmds__(dp, port, &to_reload);
3254
3255     HMAPX_FOR_EACH (node, &to_reload) {
3256         pmd = (struct dp_netdev_pmd_thread *) node->data;
3257         dp_netdev_reload_pmd__(pmd);
3258     }
3259
3260     hmapx_destroy(&to_reload);
3261 }
3262
3263
3264 /* Returns PMD thread from this numa node with fewer rx queues to poll.
3265  * Returns NULL if there is no PMD threads on this numa node.
3266  * Can be called safely only by main thread. */
3267 static struct dp_netdev_pmd_thread *
3268 dp_netdev_less_loaded_pmd_on_numa(struct dp_netdev *dp, int numa_id)
3269 {
3270     int min_cnt = -1;
3271     struct dp_netdev_pmd_thread *pmd, *res = NULL;
3272
3273     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3274         if (pmd->numa_id == numa_id
3275             && (min_cnt > pmd->poll_cnt || res == NULL)) {
3276             min_cnt = pmd->poll_cnt;
3277             res = pmd;
3278         }
3279     }
3280
3281     return res;
3282 }
3283
3284 /* Adds rx queue to poll_list of PMD thread. */
3285 static void
3286 dp_netdev_add_rxq_to_pmd(struct dp_netdev_pmd_thread *pmd,
3287                          struct dp_netdev_port *port, struct netdev_rxq *rx)
3288     OVS_REQUIRES(pmd->port_mutex)
3289 {
3290     struct rxq_poll *poll = xmalloc(sizeof *poll);
3291
3292     poll->port = port;
3293     poll->rx = rx;
3294
3295     ovs_list_push_back(&pmd->poll_list, &poll->node);
3296     pmd->poll_cnt++;
3297 }
3298
3299 /* Add 'port' to the tx port cache of 'pmd', which must be reloaded for the
3300  * changes to take effect. */
3301 static void
3302 dp_netdev_add_port_tx_to_pmd(struct dp_netdev_pmd_thread *pmd,
3303                              struct dp_netdev_port *port)
3304 {
3305     struct tx_port *tx = xzalloc(sizeof *tx);
3306
3307     tx->netdev = port->netdev;
3308     tx->port_no = port->port_no;
3309
3310     ovs_mutex_lock(&pmd->port_mutex);
3311     hmap_insert(&pmd->tx_ports, &tx->node, hash_port_no(tx->port_no));
3312     ovs_mutex_unlock(&pmd->port_mutex);
3313 }
3314
3315 /* Distribute all rx queues of 'port' between PMD threads in 'dp'. The pmd
3316  * threads that need to be restarted are inserted in 'to_reload'. */
3317 static void
3318 dp_netdev_add_port_rx_to_pmds(struct dp_netdev *dp,
3319                               struct dp_netdev_port *port,
3320                               struct hmapx *to_reload)
3321 {
3322     int numa_id = netdev_get_numa_id(port->netdev);
3323     int i;
3324
3325     if (!netdev_is_pmd(port->netdev)) {
3326         return;
3327     }
3328
3329     for (i = 0; i < port->n_rxq; i++) {
3330         struct dp_netdev_pmd_thread *pmd;
3331
3332         pmd = dp_netdev_less_loaded_pmd_on_numa(dp, numa_id);
3333         if (!pmd) {
3334             VLOG_WARN("There's no pmd thread on numa node %d", numa_id);
3335             break;
3336         }
3337
3338         ovs_mutex_lock(&pmd->port_mutex);
3339         dp_netdev_add_rxq_to_pmd(pmd, port, port->rxq[i]);
3340         ovs_mutex_unlock(&pmd->port_mutex);
3341
3342         hmapx_add(to_reload, pmd);
3343     }
3344 }
3345
3346 /* Distributes all rx queues of 'port' between all PMD threads in 'dp' and
3347  * inserts 'port' in the PMD threads 'tx_ports'. The pmd threads that need to
3348  * be restarted are inserted in 'to_reload'. */
3349 static void
3350 dp_netdev_add_port_to_pmds__(struct dp_netdev *dp, struct dp_netdev_port *port,
3351                              struct hmapx *to_reload)
3352 {
3353     struct dp_netdev_pmd_thread *pmd;
3354
3355     dp_netdev_add_port_rx_to_pmds(dp, port, to_reload);
3356
3357     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3358         dp_netdev_add_port_tx_to_pmd(pmd, port);
3359         hmapx_add(to_reload, pmd);
3360     }
3361 }
3362
3363 /* Distributes all rx queues of 'port' between all PMD threads in 'dp', inserts
3364  * 'port' in the PMD threads 'tx_ports' and reloads them, if needed. */
3365 static void
3366 dp_netdev_add_port_to_pmds(struct dp_netdev *dp, struct dp_netdev_port *port)
3367 {
3368     struct dp_netdev_pmd_thread *pmd;
3369     struct hmapx to_reload = HMAPX_INITIALIZER(&to_reload);
3370     struct hmapx_node *node;
3371
3372     dp_netdev_add_port_to_pmds__(dp, port, &to_reload);
3373
3374     HMAPX_FOR_EACH (node, &to_reload) {
3375         pmd = (struct dp_netdev_pmd_thread *) node->data;
3376         dp_netdev_reload_pmd__(pmd);
3377     }
3378
3379     hmapx_destroy(&to_reload);
3380 }
3381
3382 /* Starts pmd threads for the numa node 'numa_id', if not already started.
3383  * The function takes care of filling the threads tx port cache. */
3384 static void
3385 dp_netdev_set_pmds_on_numa(struct dp_netdev *dp, int numa_id)
3386     OVS_REQUIRES(dp->port_mutex)
3387 {
3388     int n_pmds;
3389
3390     if (!ovs_numa_numa_id_is_valid(numa_id)) {
3391         VLOG_WARN("Cannot create pmd threads due to numa id (%d) invalid",
3392                   numa_id);
3393         return;
3394     }
3395
3396     n_pmds = get_n_pmd_threads_on_numa(dp, numa_id);
3397
3398     /* If there are already pmd threads created for the numa node
3399      * in which 'netdev' is on, do nothing.  Else, creates the
3400      * pmd threads for the numa node. */
3401     if (!n_pmds) {
3402         int can_have, n_unpinned, i;
3403
3404         n_unpinned = ovs_numa_get_n_unpinned_cores_on_numa(numa_id);
3405         if (!n_unpinned) {
3406             VLOG_WARN("Cannot create pmd threads due to out of unpinned "
3407                       "cores on numa node %d", numa_id);
3408             return;
3409         }
3410
3411         /* If cpu mask is specified, uses all unpinned cores, otherwise
3412          * tries creating NR_PMD_THREADS pmd threads. */
3413         can_have = dp->pmd_cmask ? n_unpinned : MIN(n_unpinned, NR_PMD_THREADS);
3414         for (i = 0; i < can_have; i++) {
3415             unsigned core_id = ovs_numa_get_unpinned_core_on_numa(numa_id);
3416             struct dp_netdev_pmd_thread *pmd = xzalloc(sizeof *pmd);
3417             struct dp_netdev_port *port;
3418
3419             dp_netdev_configure_pmd(pmd, dp, core_id, numa_id);
3420
3421             HMAP_FOR_EACH (port, node, &dp->ports) {
3422                 dp_netdev_add_port_tx_to_pmd(pmd, port);
3423             }
3424
3425             pmd->thread = ovs_thread_create("pmd", pmd_thread_main, pmd);
3426         }
3427         VLOG_INFO("Created %d pmd threads on numa node %d", can_have, numa_id);
3428     }
3429 }
3430
3431 \f
3432 /* Called after pmd threads config change.  Restarts pmd threads with
3433  * new configuration. */
3434 static void
3435 dp_netdev_reset_pmd_threads(struct dp_netdev *dp)
3436     OVS_REQUIRES(dp->port_mutex)
3437 {
3438     struct hmapx to_reload = HMAPX_INITIALIZER(&to_reload);
3439     struct dp_netdev_pmd_thread *pmd;
3440     struct dp_netdev_port *port;
3441     struct hmapx_node *node;
3442
3443     HMAP_FOR_EACH (port, node, &dp->ports) {
3444         if (netdev_is_pmd(port->netdev)) {
3445             int numa_id = netdev_get_numa_id(port->netdev);
3446
3447             dp_netdev_set_pmds_on_numa(dp, numa_id);
3448         }
3449         dp_netdev_add_port_rx_to_pmds(dp, port, &to_reload);
3450     }
3451
3452     HMAPX_FOR_EACH (node, &to_reload) {
3453         pmd = (struct dp_netdev_pmd_thread *) node->data;
3454         dp_netdev_reload_pmd__(pmd);
3455     }
3456
3457     hmapx_destroy(&to_reload);
3458 }
3459
3460 static char *
3461 dpif_netdev_get_datapath_version(void)
3462 {
3463      return xstrdup("<built-in>");
3464 }
3465
3466 static void
3467 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow, int cnt, int size,
3468                     uint16_t tcp_flags, long long now)
3469 {
3470     uint16_t flags;
3471
3472     atomic_store_relaxed(&netdev_flow->stats.used, now);
3473     non_atomic_ullong_add(&netdev_flow->stats.packet_count, cnt);
3474     non_atomic_ullong_add(&netdev_flow->stats.byte_count, size);
3475     atomic_read_relaxed(&netdev_flow->stats.tcp_flags, &flags);
3476     flags |= tcp_flags;
3477     atomic_store_relaxed(&netdev_flow->stats.tcp_flags, flags);
3478 }
3479
3480 static void
3481 dp_netdev_count_packet(struct dp_netdev_pmd_thread *pmd,
3482                        enum dp_stat_type type, int cnt)
3483 {
3484     non_atomic_ullong_add(&pmd->stats.n[type], cnt);
3485 }
3486
3487 static int
3488 dp_netdev_upcall(struct dp_netdev_pmd_thread *pmd, struct dp_packet *packet_,
3489                  struct flow *flow, struct flow_wildcards *wc, ovs_u128 *ufid,
3490                  enum dpif_upcall_type type, const struct nlattr *userdata,
3491                  struct ofpbuf *actions, struct ofpbuf *put_actions)
3492 {
3493     struct dp_netdev *dp = pmd->dp;
3494     struct flow_tnl orig_tunnel;
3495     int err;
3496
3497     if (OVS_UNLIKELY(!dp->upcall_cb)) {
3498         return ENODEV;
3499     }
3500
3501     /* Upcall processing expects the Geneve options to be in the translated
3502      * format but we need to retain the raw format for datapath use. */
3503     orig_tunnel.flags = flow->tunnel.flags;
3504     if (flow->tunnel.flags & FLOW_TNL_F_UDPIF) {
3505         orig_tunnel.metadata.present.len = flow->tunnel.metadata.present.len;
3506         memcpy(orig_tunnel.metadata.opts.gnv, flow->tunnel.metadata.opts.gnv,
3507                flow->tunnel.metadata.present.len);
3508         err = tun_metadata_from_geneve_udpif(&orig_tunnel, &orig_tunnel,
3509                                              &flow->tunnel);
3510         if (err) {
3511             return err;
3512         }
3513     }
3514
3515     if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
3516         struct ds ds = DS_EMPTY_INITIALIZER;
3517         char *packet_str;
3518         struct ofpbuf key;
3519         struct odp_flow_key_parms odp_parms = {
3520             .flow = flow,
3521             .mask = &wc->masks,
3522             .support = dp_netdev_support,
3523         };
3524
3525         ofpbuf_init(&key, 0);
3526         odp_flow_key_from_flow(&odp_parms, &key);
3527         packet_str = ofp_packet_to_string(dp_packet_data(packet_),
3528                                           dp_packet_size(packet_));
3529
3530         odp_flow_key_format(key.data, key.size, &ds);
3531
3532         VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
3533                  dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
3534
3535         ofpbuf_uninit(&key);
3536         free(packet_str);
3537
3538         ds_destroy(&ds);
3539     }
3540
3541     err = dp->upcall_cb(packet_, flow, ufid, pmd->core_id, type, userdata,
3542                         actions, wc, put_actions, dp->upcall_aux);
3543     if (err && err != ENOSPC) {
3544         return err;
3545     }
3546
3547     /* Translate tunnel metadata masks to datapath format. */
3548     if (wc) {
3549         if (wc->masks.tunnel.metadata.present.map) {
3550             struct geneve_opt opts[TLV_TOT_OPT_SIZE /
3551                                    sizeof(struct geneve_opt)];
3552
3553             if (orig_tunnel.flags & FLOW_TNL_F_UDPIF) {
3554                 tun_metadata_to_geneve_udpif_mask(&flow->tunnel,
3555                                                   &wc->masks.tunnel,
3556                                                   orig_tunnel.metadata.opts.gnv,
3557                                                   orig_tunnel.metadata.present.len,
3558                                                   opts);
3559             } else {
3560                 orig_tunnel.metadata.present.len = 0;
3561             }
3562
3563             memset(&wc->masks.tunnel.metadata, 0,
3564                    sizeof wc->masks.tunnel.metadata);
3565             memcpy(&wc->masks.tunnel.metadata.opts.gnv, opts,
3566                    orig_tunnel.metadata.present.len);
3567         }
3568         wc->masks.tunnel.metadata.present.len = 0xff;
3569     }
3570
3571     /* Restore tunnel metadata. We need to use the saved options to ensure
3572      * that any unknown options are not lost. The generated mask will have
3573      * the same structure, matching on types and lengths but wildcarding
3574      * option data we don't care about. */
3575     if (orig_tunnel.flags & FLOW_TNL_F_UDPIF) {
3576         memcpy(&flow->tunnel.metadata.opts.gnv, orig_tunnel.metadata.opts.gnv,
3577                orig_tunnel.metadata.present.len);
3578         flow->tunnel.metadata.present.len = orig_tunnel.metadata.present.len;
3579         flow->tunnel.flags |= FLOW_TNL_F_UDPIF;
3580     }
3581
3582     return err;
3583 }
3584
3585 static inline uint32_t
3586 dpif_netdev_packet_get_rss_hash(struct dp_packet *packet,
3587                                 const struct miniflow *mf)
3588 {
3589     uint32_t hash, recirc_depth;
3590
3591     if (OVS_LIKELY(dp_packet_rss_valid(packet))) {
3592         hash = dp_packet_get_rss_hash(packet);
3593     } else {
3594         hash = miniflow_hash_5tuple(mf, 0);
3595         dp_packet_set_rss_hash(packet, hash);
3596     }
3597
3598     /* The RSS hash must account for the recirculation depth to avoid
3599      * collisions in the exact match cache */
3600     recirc_depth = *recirc_depth_get_unsafe();
3601     if (OVS_UNLIKELY(recirc_depth)) {
3602         hash = hash_finish(hash, recirc_depth);
3603         dp_packet_set_rss_hash(packet, hash);
3604     }
3605     return hash;
3606 }
3607
3608 struct packet_batch_per_flow {
3609     unsigned int byte_count;
3610     uint16_t tcp_flags;
3611     struct dp_netdev_flow *flow;
3612
3613     struct dp_packet_batch array;
3614 };
3615
3616 static inline void
3617 packet_batch_per_flow_update(struct packet_batch_per_flow *batch,
3618                              struct dp_packet *packet,
3619                              const struct miniflow *mf)
3620 {
3621     batch->byte_count += dp_packet_size(packet);
3622     batch->tcp_flags |= miniflow_get_tcp_flags(mf);
3623     batch->array.packets[batch->array.count++] = packet;
3624 }
3625
3626 static inline void
3627 packet_batch_per_flow_init(struct packet_batch_per_flow *batch,
3628                            struct dp_netdev_flow *flow)
3629 {
3630     flow->batch = batch;
3631
3632     batch->flow = flow;
3633     dp_packet_batch_init(&batch->array);
3634     batch->byte_count = 0;
3635     batch->tcp_flags = 0;
3636 }
3637
3638 static inline void
3639 packet_batch_per_flow_execute(struct packet_batch_per_flow *batch,
3640                               struct dp_netdev_pmd_thread *pmd,
3641                               long long now)
3642 {
3643     struct dp_netdev_actions *actions;
3644     struct dp_netdev_flow *flow = batch->flow;
3645
3646     dp_netdev_flow_used(flow, batch->array.count, batch->byte_count,
3647                         batch->tcp_flags, now);
3648
3649     actions = dp_netdev_flow_get_actions(flow);
3650
3651     dp_netdev_execute_actions(pmd, &batch->array, true,
3652                               actions->actions, actions->size);
3653 }
3654
3655 static inline void
3656 dp_netdev_queue_batches(struct dp_packet *pkt,
3657                         struct dp_netdev_flow *flow, const struct miniflow *mf,
3658                         struct packet_batch_per_flow *batches, size_t *n_batches)
3659 {
3660     struct packet_batch_per_flow *batch = flow->batch;
3661
3662     if (OVS_UNLIKELY(!batch)) {
3663         batch = &batches[(*n_batches)++];
3664         packet_batch_per_flow_init(batch, flow);
3665     }
3666
3667     packet_batch_per_flow_update(batch, pkt, mf);
3668 }
3669
3670 /* Try to process all ('cnt') the 'packets' using only the exact match cache
3671  * 'pmd->flow_cache'. If a flow is not found for a packet 'packets[i]', the
3672  * miniflow is copied into 'keys' and the packet pointer is moved at the
3673  * beginning of the 'packets' array.
3674  *
3675  * The function returns the number of packets that needs to be processed in the
3676  * 'packets' array (they have been moved to the beginning of the vector).
3677  *
3678  * If 'md_is_valid' is false, the metadata in 'packets' is not valid and must be
3679  * initialized by this function using 'port_no'.
3680  */
3681 static inline size_t
3682 emc_processing(struct dp_netdev_pmd_thread *pmd, struct dp_packet_batch *packets_,
3683                struct netdev_flow_key *keys,
3684                struct packet_batch_per_flow batches[], size_t *n_batches,
3685                bool md_is_valid, odp_port_t port_no)
3686 {
3687     struct emc_cache *flow_cache = &pmd->flow_cache;
3688     struct netdev_flow_key *key = &keys[0];
3689     size_t i, n_missed = 0, n_dropped = 0;
3690     struct dp_packet **packets = packets_->packets;
3691     int cnt = packets_->count;
3692
3693     for (i = 0; i < cnt; i++) {
3694         struct dp_netdev_flow *flow;
3695         struct dp_packet *packet = packets[i];
3696
3697         if (OVS_UNLIKELY(dp_packet_size(packet) < ETH_HEADER_LEN)) {
3698             dp_packet_delete(packet);
3699             n_dropped++;
3700             continue;
3701         }
3702
3703         if (i != cnt - 1) {
3704             /* Prefetch next packet data and metadata. */
3705             OVS_PREFETCH(dp_packet_data(packets[i+1]));
3706             pkt_metadata_prefetch_init(&packets[i+1]->md);
3707         }
3708
3709         if (!md_is_valid) {
3710             pkt_metadata_init(&packet->md, port_no);
3711         }
3712         miniflow_extract(packet, &key->mf);
3713         key->len = 0; /* Not computed yet. */
3714         key->hash = dpif_netdev_packet_get_rss_hash(packet, &key->mf);
3715
3716         flow = emc_lookup(flow_cache, key);
3717         if (OVS_LIKELY(flow)) {
3718             dp_netdev_queue_batches(packet, flow, &key->mf, batches,
3719                                     n_batches);
3720         } else {
3721             /* Exact match cache missed. Group missed packets together at
3722              * the beginning of the 'packets' array.  */
3723             packets[n_missed] = packet;
3724             /* 'key[n_missed]' contains the key of the current packet and it
3725              * must be returned to the caller. The next key should be extracted
3726              * to 'keys[n_missed + 1]'. */
3727             key = &keys[++n_missed];
3728         }
3729     }
3730
3731     dp_netdev_count_packet(pmd, DP_STAT_EXACT_HIT, cnt - n_dropped - n_missed);
3732
3733     return n_missed;
3734 }
3735
3736 static inline void
3737 handle_packet_upcall(struct dp_netdev_pmd_thread *pmd, struct dp_packet *packet,
3738                      const struct netdev_flow_key *key,
3739                      struct ofpbuf *actions, struct ofpbuf *put_actions,
3740                      int *lost_cnt)
3741 {
3742     struct ofpbuf *add_actions;
3743     struct dp_packet_batch b;
3744     struct match match;
3745     ovs_u128 ufid;
3746     int error;
3747
3748     match.tun_md.valid = false;
3749     miniflow_expand(&key->mf, &match.flow);
3750
3751     ofpbuf_clear(actions);
3752     ofpbuf_clear(put_actions);
3753
3754     dpif_flow_hash(pmd->dp->dpif, &match.flow, sizeof match.flow, &ufid);
3755     error = dp_netdev_upcall(pmd, packet, &match.flow, &match.wc,
3756                              &ufid, DPIF_UC_MISS, NULL, actions,
3757                              put_actions);
3758     if (OVS_UNLIKELY(error && error != ENOSPC)) {
3759         dp_packet_delete(packet);
3760         (*lost_cnt)++;
3761         return;
3762     }
3763
3764     /* The Netlink encoding of datapath flow keys cannot express
3765      * wildcarding the presence of a VLAN tag. Instead, a missing VLAN
3766      * tag is interpreted as exact match on the fact that there is no
3767      * VLAN.  Unless we refactor a lot of code that translates between
3768      * Netlink and struct flow representations, we have to do the same
3769      * here. */
3770     if (!match.wc.masks.vlan_tci) {
3771         match.wc.masks.vlan_tci = htons(0xffff);
3772     }
3773
3774     /* We can't allow the packet batching in the next loop to execute
3775      * the actions.  Otherwise, if there are any slow path actions,
3776      * we'll send the packet up twice. */
3777     packet_batch_init_packet(&b, packet);
3778     dp_netdev_execute_actions(pmd, &b, true,
3779                               actions->data, actions->size);
3780
3781     add_actions = put_actions->size ? put_actions : actions;
3782     if (OVS_LIKELY(error != ENOSPC)) {
3783         struct dp_netdev_flow *netdev_flow;
3784
3785         /* XXX: There's a race window where a flow covering this packet
3786          * could have already been installed since we last did the flow
3787          * lookup before upcall.  This could be solved by moving the
3788          * mutex lock outside the loop, but that's an awful long time
3789          * to be locking everyone out of making flow installs.  If we
3790          * move to a per-core classifier, it would be reasonable. */
3791         ovs_mutex_lock(&pmd->flow_mutex);
3792         netdev_flow = dp_netdev_pmd_lookup_flow(pmd, key);
3793         if (OVS_LIKELY(!netdev_flow)) {
3794             netdev_flow = dp_netdev_flow_add(pmd, &match, &ufid,
3795                                              add_actions->data,
3796                                              add_actions->size);
3797         }
3798         ovs_mutex_unlock(&pmd->flow_mutex);
3799
3800         emc_insert(&pmd->flow_cache, key, netdev_flow);
3801     }
3802 }
3803
3804 static inline void
3805 fast_path_processing(struct dp_netdev_pmd_thread *pmd,
3806                      struct dp_packet_batch *packets_,
3807                      struct netdev_flow_key *keys,
3808                      struct packet_batch_per_flow batches[], size_t *n_batches)
3809 {
3810     int cnt = packets_->count;
3811 #if !defined(__CHECKER__) && !defined(_WIN32)
3812     const size_t PKT_ARRAY_SIZE = cnt;
3813 #else
3814     /* Sparse or MSVC doesn't like variable length array. */
3815     enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
3816 #endif
3817     struct dp_packet **packets = packets_->packets;
3818     struct dpcls_rule *rules[PKT_ARRAY_SIZE];
3819     struct dp_netdev *dp = pmd->dp;
3820     struct emc_cache *flow_cache = &pmd->flow_cache;
3821     int miss_cnt = 0, lost_cnt = 0;
3822     bool any_miss;
3823     size_t i;
3824
3825     for (i = 0; i < cnt; i++) {
3826         /* Key length is needed in all the cases, hash computed on demand. */
3827         keys[i].len = netdev_flow_key_size(miniflow_n_values(&keys[i].mf));
3828     }
3829     any_miss = !dpcls_lookup(&pmd->cls, keys, rules, cnt);
3830     if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
3831         uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
3832         struct ofpbuf actions, put_actions;
3833
3834         ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
3835         ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
3836
3837         for (i = 0; i < cnt; i++) {
3838             struct dp_netdev_flow *netdev_flow;
3839
3840             if (OVS_LIKELY(rules[i])) {
3841                 continue;
3842             }
3843
3844             /* It's possible that an earlier slow path execution installed
3845              * a rule covering this flow.  In this case, it's a lot cheaper
3846              * to catch it here than execute a miss. */
3847             netdev_flow = dp_netdev_pmd_lookup_flow(pmd, &keys[i]);
3848             if (netdev_flow) {
3849                 rules[i] = &netdev_flow->cr;
3850                 continue;
3851             }
3852
3853             miss_cnt++;
3854             handle_packet_upcall(pmd, packets[i], &keys[i], &actions, &put_actions,
3855                           &lost_cnt);
3856         }
3857
3858         ofpbuf_uninit(&actions);
3859         ofpbuf_uninit(&put_actions);
3860         fat_rwlock_unlock(&dp->upcall_rwlock);
3861         dp_netdev_count_packet(pmd, DP_STAT_LOST, lost_cnt);
3862     } else if (OVS_UNLIKELY(any_miss)) {
3863         for (i = 0; i < cnt; i++) {
3864             if (OVS_UNLIKELY(!rules[i])) {
3865                 dp_packet_delete(packets[i]);
3866                 lost_cnt++;
3867                 miss_cnt++;
3868             }
3869         }
3870     }
3871
3872     for (i = 0; i < cnt; i++) {
3873         struct dp_packet *packet = packets[i];
3874         struct dp_netdev_flow *flow;
3875
3876         if (OVS_UNLIKELY(!rules[i])) {
3877             continue;
3878         }
3879
3880         flow = dp_netdev_flow_cast(rules[i]);
3881
3882         emc_insert(flow_cache, &keys[i], flow);
3883         dp_netdev_queue_batches(packet, flow, &keys[i].mf, batches, n_batches);
3884     }
3885
3886     dp_netdev_count_packet(pmd, DP_STAT_MASKED_HIT, cnt - miss_cnt);
3887     dp_netdev_count_packet(pmd, DP_STAT_MISS, miss_cnt);
3888     dp_netdev_count_packet(pmd, DP_STAT_LOST, lost_cnt);
3889 }
3890
3891 /* Packets enter the datapath from a port (or from recirculation) here.
3892  *
3893  * For performance reasons a caller may choose not to initialize the metadata
3894  * in 'packets': in this case 'mdinit' is false and this function needs to
3895  * initialize it using 'port_no'.  If the metadata in 'packets' is already
3896  * valid, 'md_is_valid' must be true and 'port_no' will be ignored. */
3897 static void
3898 dp_netdev_input__(struct dp_netdev_pmd_thread *pmd,
3899                   struct dp_packet_batch *packets,
3900                   bool md_is_valid, odp_port_t port_no)
3901 {
3902     int cnt = packets->count;
3903 #if !defined(__CHECKER__) && !defined(_WIN32)
3904     const size_t PKT_ARRAY_SIZE = cnt;
3905 #else
3906     /* Sparse or MSVC doesn't like variable length array. */
3907     enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
3908 #endif
3909     struct netdev_flow_key keys[PKT_ARRAY_SIZE];
3910     struct packet_batch_per_flow batches[PKT_ARRAY_SIZE];
3911     long long now = time_msec();
3912     size_t newcnt, n_batches, i;
3913
3914     n_batches = 0;
3915     newcnt = emc_processing(pmd, packets, keys, batches, &n_batches,
3916                             md_is_valid, port_no);
3917     if (OVS_UNLIKELY(newcnt)) {
3918         packets->count = newcnt;
3919         fast_path_processing(pmd, packets, keys, batches, &n_batches);
3920     }
3921
3922     for (i = 0; i < n_batches; i++) {
3923         batches[i].flow->batch = NULL;
3924     }
3925
3926     for (i = 0; i < n_batches; i++) {
3927         packet_batch_per_flow_execute(&batches[i], pmd, now);
3928     }
3929 }
3930
3931 static void
3932 dp_netdev_input(struct dp_netdev_pmd_thread *pmd,
3933                 struct dp_packet_batch *packets,
3934                 odp_port_t port_no)
3935 {
3936      dp_netdev_input__(pmd, packets, false, port_no);
3937 }
3938
3939 static void
3940 dp_netdev_recirculate(struct dp_netdev_pmd_thread *pmd,
3941                       struct dp_packet_batch *packets)
3942 {
3943      dp_netdev_input__(pmd, packets, true, 0);
3944 }
3945
3946 struct dp_netdev_execute_aux {
3947     struct dp_netdev_pmd_thread *pmd;
3948 };
3949
3950 static void
3951 dpif_netdev_register_dp_purge_cb(struct dpif *dpif, dp_purge_callback *cb,
3952                                  void *aux)
3953 {
3954     struct dp_netdev *dp = get_dp_netdev(dpif);
3955     dp->dp_purge_aux = aux;
3956     dp->dp_purge_cb = cb;
3957 }
3958
3959 static void
3960 dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
3961                                void *aux)
3962 {
3963     struct dp_netdev *dp = get_dp_netdev(dpif);
3964     dp->upcall_aux = aux;
3965     dp->upcall_cb = cb;
3966 }
3967
3968 static struct tx_port *
3969 pmd_tx_port_cache_lookup(const struct dp_netdev_pmd_thread *pmd,
3970                          odp_port_t port_no)
3971 {
3972     return tx_port_lookup(&pmd->port_cache, port_no);
3973 }
3974
3975 static int
3976 push_tnl_action(const struct dp_netdev_pmd_thread *pmd,
3977                 const struct nlattr *attr,
3978                 struct dp_packet_batch *batch)
3979 {
3980     struct tx_port *tun_port;
3981     const struct ovs_action_push_tnl *data;
3982     int err;
3983
3984     data = nl_attr_get(attr);
3985
3986     tun_port = pmd_tx_port_cache_lookup(pmd, u32_to_odp(data->tnl_port));
3987     if (!tun_port) {
3988         err = -EINVAL;
3989         goto error;
3990     }
3991     err = netdev_push_header(tun_port->netdev, batch, data);
3992     if (!err) {
3993         return 0;
3994     }
3995 error:
3996     dp_packet_delete_batch(batch, true);
3997     return err;
3998 }
3999
4000 static void
4001 dp_execute_userspace_action(struct dp_netdev_pmd_thread *pmd,
4002                             struct dp_packet *packet, bool may_steal,
4003                             struct flow *flow, ovs_u128 *ufid,
4004                             struct ofpbuf *actions,
4005                             const struct nlattr *userdata)
4006 {
4007     struct dp_packet_batch b;
4008     int error;
4009
4010     ofpbuf_clear(actions);
4011
4012     error = dp_netdev_upcall(pmd, packet, flow, NULL, ufid,
4013                              DPIF_UC_ACTION, userdata, actions,
4014                              NULL);
4015     if (!error || error == ENOSPC) {
4016         packet_batch_init_packet(&b, packet);
4017         dp_netdev_execute_actions(pmd, &b, may_steal,
4018                                   actions->data, actions->size);
4019     } else if (may_steal) {
4020         dp_packet_delete(packet);
4021     }
4022 }
4023
4024 static void
4025 dp_execute_cb(void *aux_, struct dp_packet_batch *packets_,
4026               const struct nlattr *a, bool may_steal)
4027 {
4028     struct dp_netdev_execute_aux *aux = aux_;
4029     uint32_t *depth = recirc_depth_get();
4030     struct dp_netdev_pmd_thread *pmd = aux->pmd;
4031     struct dp_netdev *dp = pmd->dp;
4032     int type = nl_attr_type(a);
4033     struct tx_port *p;
4034
4035     switch ((enum ovs_action_attr)type) {
4036     case OVS_ACTION_ATTR_OUTPUT:
4037         p = pmd_tx_port_cache_lookup(pmd, u32_to_odp(nl_attr_get_u32(a)));
4038         if (OVS_LIKELY(p)) {
4039             int tx_qid;
4040
4041             atomic_read_relaxed(&pmd->tx_qid, &tx_qid);
4042
4043             netdev_send(p->netdev, tx_qid, packets_, may_steal);
4044             return;
4045         }
4046         break;
4047
4048     case OVS_ACTION_ATTR_TUNNEL_PUSH:
4049         if (*depth < MAX_RECIRC_DEPTH) {
4050             struct dp_packet_batch tnl_pkt;
4051             struct dp_packet_batch *orig_packets_ = packets_;
4052             int err;
4053
4054             if (!may_steal) {
4055                 dp_packet_batch_clone(&tnl_pkt, packets_);
4056                 packets_ = &tnl_pkt;
4057                 dp_packet_batch_reset_cutlen(orig_packets_);
4058             }
4059
4060             dp_packet_batch_apply_cutlen(packets_);
4061
4062             err = push_tnl_action(pmd, a, packets_);
4063             if (!err) {
4064                 (*depth)++;
4065                 dp_netdev_recirculate(pmd, packets_);
4066                 (*depth)--;
4067             }
4068             return;
4069         }
4070         break;
4071
4072     case OVS_ACTION_ATTR_TUNNEL_POP:
4073         if (*depth < MAX_RECIRC_DEPTH) {
4074             struct dp_packet_batch *orig_packets_ = packets_;
4075             odp_port_t portno = u32_to_odp(nl_attr_get_u32(a));
4076
4077             p = pmd_tx_port_cache_lookup(pmd, portno);
4078             if (p) {
4079                 struct dp_packet_batch tnl_pkt;
4080                 int i;
4081
4082                 if (!may_steal) {
4083                     dp_packet_batch_clone(&tnl_pkt, packets_);
4084                     packets_ = &tnl_pkt;
4085                     dp_packet_batch_reset_cutlen(orig_packets_);
4086                 }
4087
4088                 dp_packet_batch_apply_cutlen(packets_);
4089
4090                 netdev_pop_header(p->netdev, packets_);
4091                 if (!packets_->count) {
4092                     return;
4093                 }
4094
4095                 for (i = 0; i < packets_->count; i++) {
4096                     packets_->packets[i]->md.in_port.odp_port = portno;
4097                 }
4098
4099                 (*depth)++;
4100                 dp_netdev_recirculate(pmd, packets_);
4101                 (*depth)--;
4102                 return;
4103             }
4104         }
4105         break;
4106
4107     case OVS_ACTION_ATTR_USERSPACE:
4108         if (!fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
4109             struct dp_packet_batch *orig_packets_ = packets_;
4110             struct dp_packet **packets = packets_->packets;
4111             const struct nlattr *userdata;
4112             struct dp_packet_batch usr_pkt;
4113             struct ofpbuf actions;
4114             struct flow flow;
4115             ovs_u128 ufid;
4116             bool clone = false;
4117             int i;
4118
4119             userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
4120             ofpbuf_init(&actions, 0);
4121
4122             if (packets_->trunc) {
4123                 if (!may_steal) {
4124                     dp_packet_batch_clone(&usr_pkt, packets_);
4125                     packets_ = &usr_pkt;
4126                     packets = packets_->packets;
4127                     clone = true;
4128                     dp_packet_batch_reset_cutlen(orig_packets_);
4129                 }
4130
4131                 dp_packet_batch_apply_cutlen(packets_);
4132             }
4133
4134             for (i = 0; i < packets_->count; i++) {
4135                 flow_extract(packets[i], &flow);
4136                 dpif_flow_hash(dp->dpif, &flow, sizeof flow, &ufid);
4137                 dp_execute_userspace_action(pmd, packets[i], may_steal, &flow,
4138                                             &ufid, &actions, userdata);
4139             }
4140
4141             if (clone) {
4142                 dp_packet_delete_batch(packets_, true);
4143             }
4144
4145             ofpbuf_uninit(&actions);
4146             fat_rwlock_unlock(&dp->upcall_rwlock);
4147
4148             return;
4149         }
4150         break;
4151
4152     case OVS_ACTION_ATTR_RECIRC:
4153         if (*depth < MAX_RECIRC_DEPTH) {
4154             struct dp_packet_batch recirc_pkts;
4155             int i;
4156
4157             if (!may_steal) {
4158                dp_packet_batch_clone(&recirc_pkts, packets_);
4159                packets_ = &recirc_pkts;
4160             }
4161
4162             for (i = 0; i < packets_->count; i++) {
4163                 packets_->packets[i]->md.recirc_id = nl_attr_get_u32(a);
4164             }
4165
4166             (*depth)++;
4167             dp_netdev_recirculate(pmd, packets_);
4168             (*depth)--;
4169
4170             return;
4171         }
4172
4173         VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
4174         break;
4175
4176     case OVS_ACTION_ATTR_CT:
4177         /* If a flow with this action is slow-pathed, datapath assistance is
4178          * required to implement it. However, we don't support this action
4179          * in the userspace datapath. */
4180         VLOG_WARN("Cannot execute conntrack action in userspace.");
4181         break;
4182
4183     case OVS_ACTION_ATTR_PUSH_VLAN:
4184     case OVS_ACTION_ATTR_POP_VLAN:
4185     case OVS_ACTION_ATTR_PUSH_MPLS:
4186     case OVS_ACTION_ATTR_POP_MPLS:
4187     case OVS_ACTION_ATTR_SET:
4188     case OVS_ACTION_ATTR_SET_MASKED:
4189     case OVS_ACTION_ATTR_SAMPLE:
4190     case OVS_ACTION_ATTR_HASH:
4191     case OVS_ACTION_ATTR_UNSPEC:
4192     case OVS_ACTION_ATTR_TRUNC:
4193     case __OVS_ACTION_ATTR_MAX:
4194         OVS_NOT_REACHED();
4195     }
4196
4197     dp_packet_delete_batch(packets_, may_steal);
4198 }
4199
4200 static void
4201 dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
4202                           struct dp_packet_batch *packets,
4203                           bool may_steal,
4204                           const struct nlattr *actions, size_t actions_len)
4205 {
4206     struct dp_netdev_execute_aux aux = { pmd };
4207
4208     odp_execute_actions(&aux, packets, may_steal, actions,
4209                         actions_len, dp_execute_cb);
4210 }
4211
4212 const struct dpif_class dpif_netdev_class = {
4213     "netdev",
4214     dpif_netdev_init,
4215     dpif_netdev_enumerate,
4216     dpif_netdev_port_open_type,
4217     dpif_netdev_open,
4218     dpif_netdev_close,
4219     dpif_netdev_destroy,
4220     dpif_netdev_run,
4221     dpif_netdev_wait,
4222     dpif_netdev_get_stats,
4223     dpif_netdev_port_add,
4224     dpif_netdev_port_del,
4225     dpif_netdev_port_query_by_number,
4226     dpif_netdev_port_query_by_name,
4227     NULL,                       /* port_get_pid */
4228     dpif_netdev_port_dump_start,
4229     dpif_netdev_port_dump_next,
4230     dpif_netdev_port_dump_done,
4231     dpif_netdev_port_poll,
4232     dpif_netdev_port_poll_wait,
4233     dpif_netdev_flow_flush,
4234     dpif_netdev_flow_dump_create,
4235     dpif_netdev_flow_dump_destroy,
4236     dpif_netdev_flow_dump_thread_create,
4237     dpif_netdev_flow_dump_thread_destroy,
4238     dpif_netdev_flow_dump_next,
4239     dpif_netdev_operate,
4240     NULL,                       /* recv_set */
4241     NULL,                       /* handlers_set */
4242     dpif_netdev_pmd_set,
4243     dpif_netdev_queue_to_priority,
4244     NULL,                       /* recv */
4245     NULL,                       /* recv_wait */
4246     NULL,                       /* recv_purge */
4247     dpif_netdev_register_dp_purge_cb,
4248     dpif_netdev_register_upcall_cb,
4249     dpif_netdev_enable_upcall,
4250     dpif_netdev_disable_upcall,
4251     dpif_netdev_get_datapath_version,
4252     NULL,                       /* ct_dump_start */
4253     NULL,                       /* ct_dump_next */
4254     NULL,                       /* ct_dump_done */
4255     NULL,                       /* ct_flush */
4256 };
4257
4258 static void
4259 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
4260                               const char *argv[], void *aux OVS_UNUSED)
4261 {
4262     struct dp_netdev_port *port;
4263     struct dp_netdev *dp;
4264     odp_port_t port_no;
4265
4266     ovs_mutex_lock(&dp_netdev_mutex);
4267     dp = shash_find_data(&dp_netdevs, argv[1]);
4268     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
4269         ovs_mutex_unlock(&dp_netdev_mutex);
4270         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
4271         return;
4272     }
4273     ovs_refcount_ref(&dp->ref_cnt);
4274     ovs_mutex_unlock(&dp_netdev_mutex);
4275
4276     ovs_mutex_lock(&dp->port_mutex);
4277     if (get_port_by_name(dp, argv[2], &port)) {
4278         unixctl_command_reply_error(conn, "unknown port");
4279         goto exit;
4280     }
4281
4282     port_no = u32_to_odp(atoi(argv[3]));
4283     if (!port_no || port_no == ODPP_NONE) {
4284         unixctl_command_reply_error(conn, "bad port number");
4285         goto exit;
4286     }
4287     if (dp_netdev_lookup_port(dp, port_no)) {
4288         unixctl_command_reply_error(conn, "port number already in use");
4289         goto exit;
4290     }
4291
4292     /* Remove port. */
4293     hmap_remove(&dp->ports, &port->node);
4294     dp_netdev_del_port_from_all_pmds(dp, port);
4295
4296     /* Reinsert with new port number. */
4297     port->port_no = port_no;
4298     hmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
4299     dp_netdev_add_port_to_pmds(dp, port);
4300
4301     seq_change(dp->port_seq);
4302     unixctl_command_reply(conn, NULL);
4303
4304 exit:
4305     ovs_mutex_unlock(&dp->port_mutex);
4306     dp_netdev_unref(dp);
4307 }
4308
4309 static void
4310 dpif_dummy_register__(const char *type)
4311 {
4312     struct dpif_class *class;
4313
4314     class = xmalloc(sizeof *class);
4315     *class = dpif_netdev_class;
4316     class->type = xstrdup(type);
4317     dp_register_provider(class);
4318 }
4319
4320 static void
4321 dpif_dummy_override(const char *type)
4322 {
4323     int error;
4324
4325     /*
4326      * Ignore EAFNOSUPPORT to allow --enable-dummy=system with
4327      * a userland-only build.  It's useful for testsuite.
4328      */
4329     error = dp_unregister_provider(type);
4330     if (error == 0 || error == EAFNOSUPPORT) {
4331         dpif_dummy_register__(type);
4332     }
4333 }
4334
4335 void
4336 dpif_dummy_register(enum dummy_level level)
4337 {
4338     if (level == DUMMY_OVERRIDE_ALL) {
4339         struct sset types;
4340         const char *type;
4341
4342         sset_init(&types);
4343         dp_enumerate_types(&types);
4344         SSET_FOR_EACH (type, &types) {
4345             dpif_dummy_override(type);
4346         }
4347         sset_destroy(&types);
4348     } else if (level == DUMMY_OVERRIDE_SYSTEM) {
4349         dpif_dummy_override("system");
4350     }
4351
4352     dpif_dummy_register__("dummy");
4353
4354     unixctl_command_register("dpif-dummy/change-port-number",
4355                              "dp port new-number",
4356                              3, 3, dpif_dummy_change_port_number, NULL);
4357 }
4358 \f
4359 /* Datapath Classifier. */
4360
4361 /* A set of rules that all have the same fields wildcarded. */
4362 struct dpcls_subtable {
4363     /* The fields are only used by writers. */
4364     struct cmap_node cmap_node OVS_GUARDED; /* Within dpcls 'subtables_map'. */
4365
4366     /* These fields are accessed by readers. */
4367     struct cmap rules;           /* Contains "struct dpcls_rule"s. */
4368     struct netdev_flow_key mask; /* Wildcards for fields (const). */
4369     /* 'mask' must be the last field, additional space is allocated here. */
4370 };
4371
4372 /* Initializes 'cls' as a classifier that initially contains no classification
4373  * rules. */
4374 static void
4375 dpcls_init(struct dpcls *cls)
4376 {
4377     cmap_init(&cls->subtables_map);
4378     pvector_init(&cls->subtables);
4379 }
4380
4381 static void
4382 dpcls_destroy_subtable(struct dpcls *cls, struct dpcls_subtable *subtable)
4383 {
4384     pvector_remove(&cls->subtables, subtable);
4385     cmap_remove(&cls->subtables_map, &subtable->cmap_node,
4386                 subtable->mask.hash);
4387     cmap_destroy(&subtable->rules);
4388     ovsrcu_postpone(free, subtable);
4389 }
4390
4391 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
4392  * caller's responsibility.
4393  * May only be called after all the readers have been terminated. */
4394 static void
4395 dpcls_destroy(struct dpcls *cls)
4396 {
4397     if (cls) {
4398         struct dpcls_subtable *subtable;
4399
4400         CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
4401             ovs_assert(cmap_count(&subtable->rules) == 0);
4402             dpcls_destroy_subtable(cls, subtable);
4403         }
4404         cmap_destroy(&cls->subtables_map);
4405         pvector_destroy(&cls->subtables);
4406     }
4407 }
4408
4409 static struct dpcls_subtable *
4410 dpcls_create_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
4411 {
4412     struct dpcls_subtable *subtable;
4413
4414     /* Need to add one. */
4415     subtable = xmalloc(sizeof *subtable
4416                        - sizeof subtable->mask.mf + mask->len);
4417     cmap_init(&subtable->rules);
4418     netdev_flow_key_clone(&subtable->mask, mask);
4419     cmap_insert(&cls->subtables_map, &subtable->cmap_node, mask->hash);
4420     pvector_insert(&cls->subtables, subtable, 0);
4421     pvector_publish(&cls->subtables);
4422
4423     return subtable;
4424 }
4425
4426 static inline struct dpcls_subtable *
4427 dpcls_find_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
4428 {
4429     struct dpcls_subtable *subtable;
4430
4431     CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, mask->hash,
4432                              &cls->subtables_map) {
4433         if (netdev_flow_key_equal(&subtable->mask, mask)) {
4434             return subtable;
4435         }
4436     }
4437     return dpcls_create_subtable(cls, mask);
4438 }
4439
4440 /* Insert 'rule' into 'cls'. */
4441 static void
4442 dpcls_insert(struct dpcls *cls, struct dpcls_rule *rule,
4443              const struct netdev_flow_key *mask)
4444 {
4445     struct dpcls_subtable *subtable = dpcls_find_subtable(cls, mask);
4446
4447     rule->mask = &subtable->mask;
4448     cmap_insert(&subtable->rules, &rule->cmap_node, rule->flow.hash);
4449 }
4450
4451 /* Removes 'rule' from 'cls', also destructing the 'rule'. */
4452 static void
4453 dpcls_remove(struct dpcls *cls, struct dpcls_rule *rule)
4454 {
4455     struct dpcls_subtable *subtable;
4456
4457     ovs_assert(rule->mask);
4458
4459     INIT_CONTAINER(subtable, rule->mask, mask);
4460
4461     if (cmap_remove(&subtable->rules, &rule->cmap_node, rule->flow.hash)
4462         == 0) {
4463         dpcls_destroy_subtable(cls, subtable);
4464         pvector_publish(&cls->subtables);
4465     }
4466 }
4467
4468 /* Returns true if 'target' satisfies 'key' in 'mask', that is, if each 1-bit
4469  * in 'mask' the values in 'key' and 'target' are the same. */
4470 static inline bool
4471 dpcls_rule_matches_key(const struct dpcls_rule *rule,
4472                        const struct netdev_flow_key *target)
4473 {
4474     const uint64_t *keyp = miniflow_get_values(&rule->flow.mf);
4475     const uint64_t *maskp = miniflow_get_values(&rule->mask->mf);
4476     uint64_t value;
4477
4478     NETDEV_FLOW_KEY_FOR_EACH_IN_FLOWMAP(value, target, rule->flow.mf.map) {
4479         if (OVS_UNLIKELY((value & *maskp++) != *keyp++)) {
4480             return false;
4481         }
4482     }
4483     return true;
4484 }
4485
4486 /* For each miniflow in 'flows' performs a classifier lookup writing the result
4487  * into the corresponding slot in 'rules'.  If a particular entry in 'flows' is
4488  * NULL it is skipped.
4489  *
4490  * This function is optimized for use in the userspace datapath and therefore
4491  * does not implement a lot of features available in the standard
4492  * classifier_lookup() function.  Specifically, it does not implement
4493  * priorities, instead returning any rule which matches the flow.
4494  *
4495  * Returns true if all flows found a corresponding rule. */
4496 static bool
4497 dpcls_lookup(const struct dpcls *cls, const struct netdev_flow_key keys[],
4498              struct dpcls_rule **rules, const size_t cnt)
4499 {
4500     /* The batch size 16 was experimentally found faster than 8 or 32. */
4501     typedef uint16_t map_type;
4502 #define MAP_BITS (sizeof(map_type) * CHAR_BIT)
4503
4504 #if !defined(__CHECKER__) && !defined(_WIN32)
4505     const int N_MAPS = DIV_ROUND_UP(cnt, MAP_BITS);
4506 #else
4507     enum { N_MAPS = DIV_ROUND_UP(NETDEV_MAX_BURST, MAP_BITS) };
4508 #endif
4509     map_type maps[N_MAPS];
4510     struct dpcls_subtable *subtable;
4511
4512     memset(maps, 0xff, sizeof maps);
4513     if (cnt % MAP_BITS) {
4514         maps[N_MAPS - 1] >>= MAP_BITS - cnt % MAP_BITS; /* Clear extra bits. */
4515     }
4516     memset(rules, 0, cnt * sizeof *rules);
4517
4518     PVECTOR_FOR_EACH (subtable, &cls->subtables) {
4519         const struct netdev_flow_key *mkeys = keys;
4520         struct dpcls_rule **mrules = rules;
4521         map_type remains = 0;
4522         int m;
4523
4524         BUILD_ASSERT_DECL(sizeof remains == sizeof *maps);
4525
4526         for (m = 0; m < N_MAPS; m++, mkeys += MAP_BITS, mrules += MAP_BITS) {
4527             uint32_t hashes[MAP_BITS];
4528             const struct cmap_node *nodes[MAP_BITS];
4529             unsigned long map = maps[m];
4530             int i;
4531
4532             if (!map) {
4533                 continue; /* Skip empty maps. */
4534             }
4535
4536             /* Compute hashes for the remaining keys. */
4537             ULLONG_FOR_EACH_1(i, map) {
4538                 hashes[i] = netdev_flow_key_hash_in_mask(&mkeys[i],
4539                                                          &subtable->mask);
4540             }
4541             /* Lookup. */
4542             map = cmap_find_batch(&subtable->rules, map, hashes, nodes);
4543             /* Check results. */
4544             ULLONG_FOR_EACH_1(i, map) {
4545                 struct dpcls_rule *rule;
4546
4547                 CMAP_NODE_FOR_EACH (rule, cmap_node, nodes[i]) {
4548                     if (OVS_LIKELY(dpcls_rule_matches_key(rule, &mkeys[i]))) {
4549                         mrules[i] = rule;
4550                         goto next;
4551                     }
4552                 }
4553                 ULLONG_SET0(map, i);  /* Did not match. */
4554             next:
4555                 ;                     /* Keep Sparse happy. */
4556             }
4557             maps[m] &= ~map;          /* Clear the found rules. */
4558             remains |= maps[m];
4559         }
4560         if (!remains) {
4561             return true;              /* All found. */
4562         }
4563     }
4564     return false;                     /* Some misses. */
4565 }