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