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