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