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