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