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