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