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