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