a1db620b3f5828ae8a7904cc13e05e64c0a737bc
[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, struct pkt_metadata *,
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                             struct pkt_metadata *);
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     struct pkt_metadata *md = &execute->md;
1857
1858     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
1859         ofpbuf_size(execute->packet) > UINT16_MAX) {
1860         return EINVAL;
1861     }
1862
1863     packet.ofpbuf = *execute->packet;
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, md, 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
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         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
2041
2042         *recirc_depth_get() = 0;
2043         dp_netdev_input(pmd, packets, cnt, &md);
2044     } else if (error != EAGAIN && error != EOPNOTSUPP) {
2045         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2046
2047         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
2048                     netdev_get_name(port->netdev), ovs_strerror(error));
2049     }
2050 }
2051
2052 static void
2053 dpif_netdev_run(struct dpif *dpif)
2054 {
2055     struct dp_netdev_port *port;
2056     struct dp_netdev *dp = get_dp_netdev(dpif);
2057     struct dp_netdev_pmd_thread *non_pmd = dp_netdev_get_nonpmd(dp);
2058
2059     ovs_mutex_lock(&dp->non_pmd_mutex);
2060     CMAP_FOR_EACH (port, node, &dp->ports) {
2061         if (!netdev_is_pmd(port->netdev)) {
2062             int i;
2063
2064             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2065                 dp_netdev_process_rxq_port(non_pmd, port, port->rxq[i]);
2066             }
2067         }
2068     }
2069     ovs_mutex_unlock(&dp->non_pmd_mutex);
2070 }
2071
2072 static void
2073 dpif_netdev_wait(struct dpif *dpif)
2074 {
2075     struct dp_netdev_port *port;
2076     struct dp_netdev *dp = get_dp_netdev(dpif);
2077
2078     ovs_mutex_lock(&dp_netdev_mutex);
2079     CMAP_FOR_EACH (port, node, &dp->ports) {
2080         if (!netdev_is_pmd(port->netdev)) {
2081             int i;
2082
2083             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2084                 netdev_rxq_wait(port->rxq[i]);
2085             }
2086         }
2087     }
2088     ovs_mutex_unlock(&dp_netdev_mutex);
2089 }
2090
2091 struct rxq_poll {
2092     struct dp_netdev_port *port;
2093     struct netdev_rxq *rx;
2094 };
2095
2096 static int
2097 pmd_load_queues(struct dp_netdev_pmd_thread *pmd,
2098                 struct rxq_poll **ppoll_list, int poll_cnt)
2099 {
2100     struct rxq_poll *poll_list = *ppoll_list;
2101     struct dp_netdev_port *port;
2102     int n_pmds_on_numa, index, i;
2103
2104     /* Simple scheduler for netdev rx polling. */
2105     for (i = 0; i < poll_cnt; i++) {
2106         port_unref(poll_list[i].port);
2107     }
2108
2109     poll_cnt = 0;
2110     n_pmds_on_numa = get_n_pmd_threads_on_numa(pmd->dp, pmd->numa_id);
2111     index = 0;
2112
2113     CMAP_FOR_EACH (port, node, &pmd->dp->ports) {
2114         /* Calls port_try_ref() to prevent the main thread
2115          * from deleting the port. */
2116         if (port_try_ref(port)) {
2117             if (netdev_is_pmd(port->netdev)
2118                 && netdev_get_numa_id(port->netdev) == pmd->numa_id) {
2119                 int i;
2120
2121                 for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
2122                     if ((index % n_pmds_on_numa) == pmd->index) {
2123                         poll_list = xrealloc(poll_list,
2124                                         sizeof *poll_list * (poll_cnt + 1));
2125
2126                         port_ref(port);
2127                         poll_list[poll_cnt].port = port;
2128                         poll_list[poll_cnt].rx = port->rxq[i];
2129                         poll_cnt++;
2130                     }
2131                     index++;
2132                 }
2133             }
2134             /* Unrefs the port_try_ref(). */
2135             port_unref(port);
2136         }
2137     }
2138
2139     *ppoll_list = poll_list;
2140     return poll_cnt;
2141 }
2142
2143 static void *
2144 pmd_thread_main(void *f_)
2145 {
2146     struct dp_netdev_pmd_thread *pmd = f_;
2147     unsigned int lc = 0;
2148     struct rxq_poll *poll_list;
2149     unsigned int port_seq = PMD_INITIAL_SEQ;
2150     int poll_cnt;
2151     int i;
2152
2153     poll_cnt = 0;
2154     poll_list = NULL;
2155
2156     /* Stores the pmd thread's 'pmd' to 'per_pmd_key'. */
2157     ovsthread_setspecific(pmd->dp->per_pmd_key, pmd);
2158     pmd_thread_setaffinity_cpu(pmd->core_id);
2159 reload:
2160     emc_cache_init(&pmd->flow_cache);
2161     poll_cnt = pmd_load_queues(pmd, &poll_list, poll_cnt);
2162
2163     for (;;) {
2164         int i;
2165
2166         for (i = 0; i < poll_cnt; i++) {
2167             dp_netdev_process_rxq_port(pmd, poll_list[i].port, poll_list[i].rx);
2168         }
2169
2170         if (lc++ > 1024) {
2171             unsigned int seq;
2172
2173             lc = 0;
2174
2175             ovsrcu_quiesce();
2176
2177             atomic_read_relaxed(&pmd->change_seq, &seq);
2178             if (seq != port_seq) {
2179                 port_seq = seq;
2180                 break;
2181             }
2182         }
2183     }
2184
2185     emc_cache_uninit(&pmd->flow_cache);
2186
2187     if (!latch_is_set(&pmd->exit_latch)){
2188         goto reload;
2189     }
2190
2191     for (i = 0; i < poll_cnt; i++) {
2192          port_unref(poll_list[i].port);
2193     }
2194
2195     free(poll_list);
2196     return NULL;
2197 }
2198
2199 static void
2200 dp_netdev_disable_upcall(struct dp_netdev *dp)
2201     OVS_ACQUIRES(dp->upcall_rwlock)
2202 {
2203     fat_rwlock_wrlock(&dp->upcall_rwlock);
2204 }
2205
2206 static void
2207 dpif_netdev_disable_upcall(struct dpif *dpif)
2208     OVS_NO_THREAD_SAFETY_ANALYSIS
2209 {
2210     struct dp_netdev *dp = get_dp_netdev(dpif);
2211     dp_netdev_disable_upcall(dp);
2212 }
2213
2214 static void
2215 dp_netdev_enable_upcall(struct dp_netdev *dp)
2216     OVS_RELEASES(dp->upcall_rwlock)
2217 {
2218     fat_rwlock_unlock(&dp->upcall_rwlock);
2219 }
2220
2221 static void
2222 dpif_netdev_enable_upcall(struct dpif *dpif)
2223     OVS_NO_THREAD_SAFETY_ANALYSIS
2224 {
2225     struct dp_netdev *dp = get_dp_netdev(dpif);
2226     dp_netdev_enable_upcall(dp);
2227 }
2228
2229 /* Returns the pointer to the dp_netdev_pmd_thread for non-pmd threads. */
2230 static struct dp_netdev_pmd_thread *
2231 dp_netdev_get_nonpmd(struct dp_netdev *dp)
2232 {
2233     struct dp_netdev_pmd_thread *pmd;
2234     const struct cmap_node *pnode;
2235
2236     pnode = cmap_find(&dp->poll_threads, hash_int(NON_PMD_CORE_ID, 0));
2237     ovs_assert(pnode);
2238     pmd = CONTAINER_OF(pnode, struct dp_netdev_pmd_thread, node);
2239
2240     return pmd;
2241 }
2242
2243 /* Sets the 'struct dp_netdev_pmd_thread' for non-pmd threads. */
2244 static void
2245 dp_netdev_set_nonpmd(struct dp_netdev *dp)
2246 {
2247     struct dp_netdev_pmd_thread *non_pmd;
2248
2249     non_pmd = xzalloc(sizeof *non_pmd);
2250     dp_netdev_configure_pmd(non_pmd, dp, 0, NON_PMD_CORE_ID,
2251                             OVS_NUMA_UNSPEC);
2252 }
2253
2254 /* Configures the 'pmd' based on the input argument. */
2255 static void
2256 dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd, struct dp_netdev *dp,
2257                         int index, int core_id, int numa_id)
2258 {
2259     pmd->dp = dp;
2260     pmd->index = index;
2261     pmd->core_id = core_id;
2262     pmd->numa_id = numa_id;
2263     latch_init(&pmd->exit_latch);
2264     atomic_init(&pmd->change_seq, PMD_INITIAL_SEQ);
2265     /* init the 'flow_cache' since there is no
2266      * actual thread created for NON_PMD_CORE_ID. */
2267     if (core_id == NON_PMD_CORE_ID) {
2268         emc_cache_init(&pmd->flow_cache);
2269     }
2270     cmap_insert(&dp->poll_threads, CONST_CAST(struct cmap_node *, &pmd->node),
2271                 hash_int(core_id, 0));
2272 }
2273
2274 /* Stops the pmd thread, removes it from the 'dp->poll_threads'
2275  * and destroys the struct. */
2276 static void
2277 dp_netdev_del_pmd(struct dp_netdev_pmd_thread *pmd)
2278 {
2279     /* Uninit the 'flow_cache' since there is
2280      * no actual thread uninit it. */
2281     if (pmd->core_id == NON_PMD_CORE_ID) {
2282         emc_cache_uninit(&pmd->flow_cache);
2283     } else {
2284         latch_set(&pmd->exit_latch);
2285         dp_netdev_reload_pmd__(pmd);
2286         ovs_numa_unpin_core(pmd->core_id);
2287         xpthread_join(pmd->thread, NULL);
2288     }
2289     cmap_remove(&pmd->dp->poll_threads, &pmd->node, hash_int(pmd->core_id, 0));
2290     latch_destroy(&pmd->exit_latch);
2291     free(pmd);
2292 }
2293
2294 /* Destroys all pmd threads. */
2295 static void
2296 dp_netdev_destroy_all_pmds(struct dp_netdev *dp)
2297 {
2298     struct dp_netdev_pmd_thread *pmd;
2299
2300     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2301         dp_netdev_del_pmd(pmd);
2302     }
2303 }
2304
2305 /* Deletes all pmd threads on numa node 'numa_id'. */
2306 static void
2307 dp_netdev_del_pmds_on_numa(struct dp_netdev *dp, int numa_id)
2308 {
2309     struct dp_netdev_pmd_thread *pmd;
2310
2311     CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2312         if (pmd->numa_id == numa_id) {
2313             dp_netdev_del_pmd(pmd);
2314         }
2315     }
2316 }
2317
2318 /* Checks the numa node id of 'netdev' and starts pmd threads for
2319  * the numa node. */
2320 static void
2321 dp_netdev_set_pmds_on_numa(struct dp_netdev *dp, int numa_id)
2322 {
2323     int n_pmds;
2324
2325     if (!ovs_numa_numa_id_is_valid(numa_id)) {
2326         VLOG_ERR("Cannot create pmd threads due to numa id (%d)"
2327                  "invalid", numa_id);
2328         return ;
2329     }
2330
2331     n_pmds = get_n_pmd_threads_on_numa(dp, numa_id);
2332
2333     /* If there are already pmd threads created for the numa node
2334      * in which 'netdev' is on, do nothing.  Else, creates the
2335      * pmd threads for the numa node. */
2336     if (!n_pmds) {
2337         int can_have, n_unpinned, i;
2338
2339         n_unpinned = ovs_numa_get_n_unpinned_cores_on_numa(numa_id);
2340         if (!n_unpinned) {
2341             VLOG_ERR("Cannot create pmd threads due to out of unpinned "
2342                      "cores on numa node");
2343             return;
2344         }
2345
2346         /* If cpu mask is specified, uses all unpinned cores, otherwise
2347          * tries creating NR_PMD_THREADS pmd threads. */
2348         can_have = dp->pmd_cmask ? n_unpinned : MIN(n_unpinned, NR_PMD_THREADS);
2349         for (i = 0; i < can_have; i++) {
2350             struct dp_netdev_pmd_thread *pmd = xzalloc(sizeof *pmd);
2351             int core_id = ovs_numa_get_unpinned_core_on_numa(numa_id);
2352
2353             dp_netdev_configure_pmd(pmd, dp, i, core_id, numa_id);
2354             /* Each thread will distribute all devices rx-queues among
2355              * themselves. */
2356             pmd->thread = ovs_thread_create("pmd", pmd_thread_main, pmd);
2357         }
2358         VLOG_INFO("Created %d pmd threads on numa node %d", can_have, numa_id);
2359     }
2360 }
2361
2362 \f
2363 static void *
2364 dp_netdev_flow_stats_new_cb(void)
2365 {
2366     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2367     ovs_mutex_init(&bucket->mutex);
2368     return bucket;
2369 }
2370
2371 /* Called after pmd threads config change.  Restarts pmd threads with
2372  * new configuration. */
2373 static void
2374 dp_netdev_reset_pmd_threads(struct dp_netdev *dp)
2375 {
2376     struct dp_netdev_port *port;
2377
2378     CMAP_FOR_EACH (port, node, &dp->ports) {
2379         if (netdev_is_pmd(port->netdev)) {
2380             int numa_id = netdev_get_numa_id(port->netdev);
2381
2382             dp_netdev_set_pmds_on_numa(dp, numa_id);
2383         }
2384     }
2385 }
2386
2387 static void
2388 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
2389                     int cnt, int size,
2390                     uint16_t tcp_flags)
2391 {
2392     long long int now = time_msec();
2393     struct dp_netdev_flow_stats *bucket;
2394
2395     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
2396                                         dp_netdev_flow_stats_new_cb);
2397
2398     ovs_mutex_lock(&bucket->mutex);
2399     bucket->used = MAX(now, bucket->used);
2400     bucket->packet_count += cnt;
2401     bucket->byte_count += size;
2402     bucket->tcp_flags |= tcp_flags;
2403     ovs_mutex_unlock(&bucket->mutex);
2404 }
2405
2406 static void *
2407 dp_netdev_stats_new_cb(void)
2408 {
2409     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
2410     ovs_mutex_init(&bucket->mutex);
2411     return bucket;
2412 }
2413
2414 static void
2415 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type, int cnt)
2416 {
2417     struct dp_netdev_stats *bucket;
2418
2419     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
2420     ovs_mutex_lock(&bucket->mutex);
2421     bucket->n[type] += cnt;
2422     ovs_mutex_unlock(&bucket->mutex);
2423 }
2424
2425 static int
2426 dp_netdev_upcall(struct dp_netdev *dp, struct dpif_packet *packet_,
2427                  struct flow *flow, struct flow_wildcards *wc,
2428                  enum dpif_upcall_type type, const struct nlattr *userdata,
2429                  struct ofpbuf *actions, struct ofpbuf *put_actions)
2430 {
2431     struct ofpbuf *packet = &packet_->ofpbuf;
2432
2433     if (type == DPIF_UC_MISS) {
2434         dp_netdev_count_packet(dp, DP_STAT_MISS, 1);
2435     }
2436
2437     if (OVS_UNLIKELY(!dp->upcall_cb)) {
2438         return ENODEV;
2439     }
2440
2441     if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
2442         struct ds ds = DS_EMPTY_INITIALIZER;
2443         struct ofpbuf key;
2444         char *packet_str;
2445
2446         ofpbuf_init(&key, 0);
2447         odp_flow_key_from_flow(&key, flow, &wc->masks, flow->in_port.odp_port,
2448                                true);
2449
2450         packet_str = ofp_packet_to_string(ofpbuf_data(packet),
2451                                           ofpbuf_size(packet));
2452
2453         odp_flow_key_format(ofpbuf_data(&key), ofpbuf_size(&key), &ds);
2454
2455         VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
2456                  dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
2457
2458         ofpbuf_uninit(&key);
2459         free(packet_str);
2460         ds_destroy(&ds);
2461     }
2462
2463     return dp->upcall_cb(packet, flow, type, userdata, actions, wc,
2464                          put_actions, dp->upcall_aux);
2465 }
2466
2467 static inline uint32_t
2468 dpif_netdev_packet_get_dp_hash(struct dpif_packet *packet,
2469                                const struct miniflow *mf)
2470 {
2471     uint32_t hash;
2472
2473     hash = dpif_packet_get_dp_hash(packet);
2474     if (OVS_UNLIKELY(!hash)) {
2475         hash = miniflow_hash_5tuple(mf, 0);
2476         dpif_packet_set_dp_hash(packet, hash);
2477     }
2478     return hash;
2479 }
2480
2481 struct packet_batch {
2482     unsigned int packet_count;
2483     unsigned int byte_count;
2484     uint16_t tcp_flags;
2485
2486     struct dp_netdev_flow *flow;
2487
2488     struct dpif_packet *packets[NETDEV_MAX_RX_BATCH];
2489     struct pkt_metadata md;
2490 };
2491
2492 static inline void
2493 packet_batch_update(struct packet_batch *batch, struct dpif_packet *packet,
2494                     const struct miniflow *mf)
2495 {
2496     batch->tcp_flags |= miniflow_get_tcp_flags(mf);
2497     batch->packets[batch->packet_count++] = packet;
2498     batch->byte_count += ofpbuf_size(&packet->ofpbuf);
2499 }
2500
2501 static inline void
2502 packet_batch_init(struct packet_batch *batch, struct dp_netdev_flow *flow,
2503                   struct pkt_metadata *md)
2504 {
2505     batch->flow = flow;
2506     batch->md = *md;
2507
2508     batch->packet_count = 0;
2509     batch->byte_count = 0;
2510     batch->tcp_flags = 0;
2511 }
2512
2513 static inline void
2514 packet_batch_execute(struct packet_batch *batch,
2515                      struct dp_netdev_pmd_thread *pmd)
2516 {
2517     struct dp_netdev_actions *actions;
2518     struct dp_netdev_flow *flow = batch->flow;
2519
2520     dp_netdev_flow_used(batch->flow, batch->packet_count, batch->byte_count,
2521                         batch->tcp_flags);
2522
2523     actions = dp_netdev_flow_get_actions(flow);
2524
2525     dp_netdev_execute_actions(pmd, batch->packets, batch->packet_count, true,
2526                               &batch->md, actions->actions, actions->size);
2527
2528     dp_netdev_count_packet(pmd->dp, DP_STAT_HIT, batch->packet_count);
2529 }
2530
2531 static inline bool
2532 dp_netdev_queue_batches(struct dpif_packet *pkt, struct pkt_metadata *md,
2533                         struct dp_netdev_flow *flow, const struct miniflow *mf,
2534                         struct packet_batch *batches, size_t *n_batches,
2535                         size_t max_batches)
2536 {
2537     struct packet_batch *batch = NULL;
2538     int j;
2539
2540     if (OVS_UNLIKELY(!flow)) {
2541         return false;
2542     }
2543     /* XXX: This O(n^2) algortihm makes sense if we're operating under the
2544      * assumption that the number of distinct flows (and therefore the
2545      * number of distinct batches) is quite small.  If this turns out not
2546      * to be the case, it may make sense to pre sort based on the
2547      * netdev_flow pointer.  That done we can get the appropriate batching
2548      * in O(n * log(n)) instead. */
2549     for (j = *n_batches - 1; j >= 0; j--) {
2550         if (batches[j].flow == flow) {
2551             batch = &batches[j];
2552             packet_batch_update(batch, pkt, mf);
2553             return true;
2554         }
2555     }
2556     if (OVS_UNLIKELY(*n_batches >= max_batches)) {
2557         return false;
2558     }
2559
2560     batch = &batches[(*n_batches)++];
2561     packet_batch_init(batch, flow, md);
2562     packet_batch_update(batch, pkt, mf);
2563     return true;
2564 }
2565
2566 static inline void
2567 dpif_packet_swap(struct dpif_packet **a, struct dpif_packet **b)
2568 {
2569     struct dpif_packet *tmp = *a;
2570     *a = *b;
2571     *b = tmp;
2572 }
2573
2574 /* Try to process all ('cnt') the 'packets' using only the exact match cache
2575  * 'flow_cache'. If a flow is not found for a packet 'packets[i]', or if there
2576  * is no matching batch for a packet's flow, the miniflow is copied into 'keys'
2577  * and the packet pointer is moved at the beginning of the 'packets' array.
2578  *
2579  * The function returns the number of packets that needs to be processed in the
2580  * 'packets' array (they have been moved to the beginning of the vector).
2581  */
2582 static inline size_t
2583 emc_processing(struct dp_netdev_pmd_thread *pmd, struct dpif_packet **packets,
2584                size_t cnt, struct pkt_metadata *md,
2585                struct netdev_flow_key *keys)
2586 {
2587     struct netdev_flow_key key;
2588     struct packet_batch batches[4];
2589     struct emc_cache *flow_cache = &pmd->flow_cache;
2590     size_t n_batches, i;
2591     size_t notfound_cnt = 0;
2592
2593     n_batches = 0;
2594     miniflow_initialize(&key.flow, key.buf);
2595     for (i = 0; i < cnt; i++) {
2596         struct dp_netdev_flow *flow;
2597         uint32_t hash;
2598
2599         if (OVS_UNLIKELY(ofpbuf_size(&packets[i]->ofpbuf) < ETH_HEADER_LEN)) {
2600             dpif_packet_delete(packets[i]);
2601             continue;
2602         }
2603
2604         miniflow_extract(&packets[i]->ofpbuf, md, &key.flow);
2605
2606         hash = dpif_netdev_packet_get_dp_hash(packets[i], &key.flow);
2607
2608         flow = emc_lookup(flow_cache, &key.flow, hash);
2609         if (OVS_UNLIKELY(!dp_netdev_queue_batches(packets[i], md,
2610                                                   flow,  &key.flow,
2611                                                   batches, &n_batches,
2612                                                   ARRAY_SIZE(batches)))) {
2613             if (i != notfound_cnt) {
2614                 dpif_packet_swap(&packets[i], &packets[notfound_cnt]);
2615             }
2616
2617             keys[notfound_cnt++] = key;
2618         }
2619     }
2620
2621     for (i = 0; i < n_batches; i++) {
2622         packet_batch_execute(&batches[i], pmd);
2623     }
2624
2625     return notfound_cnt;
2626 }
2627
2628 static inline void
2629 fast_path_processing(struct dp_netdev_pmd_thread *pmd,
2630                      struct dpif_packet **packets, size_t cnt,
2631                      struct pkt_metadata *md, struct netdev_flow_key *keys)
2632 {
2633 #if !defined(__CHECKER__) && !defined(_WIN32)
2634     const size_t PKT_ARRAY_SIZE = cnt;
2635 #else
2636     /* Sparse or MSVC doesn't like variable length array. */
2637     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2638 #endif
2639     struct packet_batch batches[PKT_ARRAY_SIZE];
2640     const struct miniflow *mfs[PKT_ARRAY_SIZE]; /* May NOT be NULL. */
2641     struct cls_rule *rules[PKT_ARRAY_SIZE];
2642     struct dp_netdev *dp = pmd->dp;
2643     struct emc_cache *flow_cache = &pmd->flow_cache;
2644     size_t n_batches, i;
2645     bool any_miss;
2646
2647     for (i = 0; i < cnt; i++) {
2648         mfs[i] = &keys[i].flow; /* No bad packets! */
2649     }
2650     any_miss = !classifier_lookup_miniflow_batch(&dp->cls, mfs, rules, cnt);
2651     if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
2652         uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
2653         struct ofpbuf actions, put_actions;
2654         struct match match;
2655
2656         ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
2657         ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
2658
2659         for (i = 0; i < cnt; i++) {
2660             const struct dp_netdev_flow *netdev_flow;
2661             struct ofpbuf *add_actions;
2662             int error;
2663
2664             if (OVS_LIKELY(rules[i] || !mfs[i])) {
2665                 continue;
2666             }
2667
2668             /* It's possible that an earlier slow path execution installed
2669              * the rule this flow needs.  In this case, it's a lot cheaper
2670              * to catch it here than execute a miss. */
2671             netdev_flow = dp_netdev_lookup_flow(dp, mfs[i]);
2672             if (netdev_flow) {
2673                 rules[i] = CONST_CAST(struct cls_rule *, &netdev_flow->cr);
2674                 continue;
2675             }
2676
2677             miniflow_expand(mfs[i], &match.flow);
2678
2679             ofpbuf_clear(&actions);
2680             ofpbuf_clear(&put_actions);
2681
2682             error = dp_netdev_upcall(dp, packets[i], &match.flow, &match.wc,
2683                                       DPIF_UC_MISS, NULL, &actions,
2684                                       &put_actions);
2685             if (OVS_UNLIKELY(error && error != ENOSPC)) {
2686                 continue;
2687             }
2688
2689             /* We can't allow the packet batching in the next loop to execute
2690              * the actions.  Otherwise, if there are any slow path actions,
2691              * we'll send the packet up twice. */
2692             dp_netdev_execute_actions(pmd, &packets[i], 1, true, md,
2693                                       ofpbuf_data(&actions),
2694                                       ofpbuf_size(&actions));
2695
2696             add_actions = ofpbuf_size(&put_actions)
2697                 ? &put_actions
2698                 : &actions;
2699
2700             ovs_mutex_lock(&dp->flow_mutex);
2701             /* XXX: There's a brief race where this flow could have already
2702              * been installed since we last did the flow lookup.  This could be
2703              * solved by moving the mutex lock outside the loop, but that's an
2704              * awful long time to be locking everyone out of making flow
2705              * installs.  If we move to a per-core classifier, it would be
2706              * reasonable. */
2707             if (OVS_LIKELY(error != ENOSPC)
2708                 && !dp_netdev_lookup_flow(dp, mfs[i])) {
2709                 dp_netdev_flow_add(dp, &match, ofpbuf_data(add_actions),
2710                                    ofpbuf_size(add_actions));
2711             }
2712             ovs_mutex_unlock(&dp->flow_mutex);
2713         }
2714
2715         ofpbuf_uninit(&actions);
2716         ofpbuf_uninit(&put_actions);
2717         fat_rwlock_unlock(&dp->upcall_rwlock);
2718     } else if (OVS_UNLIKELY(any_miss)) {
2719         int dropped_cnt = 0;
2720
2721         for (i = 0; i < cnt; i++) {
2722             if (OVS_UNLIKELY(!rules[i] && mfs[i])) {
2723                 dpif_packet_delete(packets[i]);
2724                 dropped_cnt++;
2725             }
2726         }
2727
2728         dp_netdev_count_packet(dp, DP_STAT_LOST, dropped_cnt);
2729     }
2730
2731     n_batches = 0;
2732     for (i = 0; i < cnt; i++) {
2733         struct dpif_packet *packet = packets[i];
2734         struct dp_netdev_flow *flow;
2735
2736         if (OVS_UNLIKELY(!rules[i] || !mfs[i])) {
2737             continue;
2738         }
2739
2740         flow = dp_netdev_flow_cast(rules[i]);
2741         emc_insert(flow_cache, mfs[i], dpif_packet_get_dp_hash(packet),
2742                    flow);
2743         dp_netdev_queue_batches(packet, md, flow, mfs[i], batches, &n_batches,
2744                                 ARRAY_SIZE(batches));
2745     }
2746
2747     for (i = 0; i < n_batches; i++) {
2748         packet_batch_execute(&batches[i], pmd);
2749     }
2750 }
2751
2752 static void
2753 dp_netdev_input(struct dp_netdev_pmd_thread *pmd,
2754                 struct dpif_packet **packets, int cnt, struct pkt_metadata *md)
2755 {
2756 #if !defined(__CHECKER__) && !defined(_WIN32)
2757     const size_t PKT_ARRAY_SIZE = cnt;
2758 #else
2759     /* Sparse or MSVC doesn't like variable length array. */
2760     enum { PKT_ARRAY_SIZE = NETDEV_MAX_RX_BATCH };
2761 #endif
2762     struct netdev_flow_key keys[PKT_ARRAY_SIZE];
2763     size_t newcnt;
2764
2765     newcnt = emc_processing(pmd, packets, cnt, md, keys);
2766     if (OVS_UNLIKELY(newcnt)) {
2767         fast_path_processing(pmd, packets, newcnt, md, keys);
2768     }
2769 }
2770
2771 struct dp_netdev_execute_aux {
2772     struct dp_netdev_pmd_thread *pmd;
2773 };
2774
2775 static void
2776 dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
2777                                void *aux)
2778 {
2779     struct dp_netdev *dp = get_dp_netdev(dpif);
2780     dp->upcall_aux = aux;
2781     dp->upcall_cb = cb;
2782 }
2783
2784 static void
2785 dp_netdev_drop_packets(struct dpif_packet ** packets, int cnt, bool may_steal)
2786 {
2787     int i;
2788
2789     if (may_steal) {
2790         for (i = 0; i < cnt; i++) {
2791             dpif_packet_delete(packets[i]);
2792         }
2793     }
2794 }
2795
2796 static void
2797 dp_execute_cb(void *aux_, struct dpif_packet **packets, int cnt,
2798               struct pkt_metadata *md,
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, 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                                               md, 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             if (i == 0) {
2876                 md->dp_hash = hash;
2877             }
2878             dpif_packet_set_dp_hash(packets[i], hash);
2879         }
2880         return;
2881     }
2882
2883     case OVS_ACTION_ATTR_RECIRC:
2884         if (*depth < MAX_RECIRC_DEPTH) {
2885
2886             (*depth)++;
2887             for (i = 0; i < cnt; i++) {
2888                 struct dpif_packet *recirc_pkt;
2889                 struct pkt_metadata recirc_md = *md;
2890
2891                 recirc_pkt = (may_steal) ? packets[i]
2892                                     : dpif_packet_clone(packets[i]);
2893
2894                 recirc_md.recirc_id = nl_attr_get_u32(a);
2895
2896                 /* Hash is private to each packet */
2897                 recirc_md.dp_hash = dpif_packet_get_dp_hash(packets[i]);
2898
2899                 dp_netdev_input(pmd, &recirc_pkt, 1,
2900                                 &recirc_md);
2901             }
2902             (*depth)--;
2903
2904             return;
2905         }
2906
2907         VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2908         break;
2909
2910     case OVS_ACTION_ATTR_PUSH_VLAN:
2911     case OVS_ACTION_ATTR_POP_VLAN:
2912     case OVS_ACTION_ATTR_PUSH_MPLS:
2913     case OVS_ACTION_ATTR_POP_MPLS:
2914     case OVS_ACTION_ATTR_SET:
2915     case OVS_ACTION_ATTR_SET_MASKED:
2916     case OVS_ACTION_ATTR_SAMPLE:
2917     case OVS_ACTION_ATTR_UNSPEC:
2918     case __OVS_ACTION_ATTR_MAX:
2919         OVS_NOT_REACHED();
2920     }
2921
2922     dp_netdev_drop_packets(packets, cnt, may_steal);
2923 }
2924
2925 static void
2926 dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
2927                           struct dpif_packet **packets, int cnt,
2928                           bool may_steal, struct pkt_metadata *md,
2929                           const struct nlattr *actions, size_t actions_len)
2930 {
2931     struct dp_netdev_execute_aux aux = {pmd};
2932
2933     odp_execute_actions(&aux, packets, cnt, may_steal, md, actions,
2934                         actions_len, dp_execute_cb);
2935 }
2936
2937 const struct dpif_class dpif_netdev_class = {
2938     "netdev",
2939     dpif_netdev_enumerate,
2940     dpif_netdev_port_open_type,
2941     dpif_netdev_open,
2942     dpif_netdev_close,
2943     dpif_netdev_destroy,
2944     dpif_netdev_run,
2945     dpif_netdev_wait,
2946     dpif_netdev_get_stats,
2947     dpif_netdev_port_add,
2948     dpif_netdev_port_del,
2949     dpif_netdev_port_query_by_number,
2950     dpif_netdev_port_query_by_name,
2951     NULL,                       /* port_get_pid */
2952     dpif_netdev_port_dump_start,
2953     dpif_netdev_port_dump_next,
2954     dpif_netdev_port_dump_done,
2955     dpif_netdev_port_poll,
2956     dpif_netdev_port_poll_wait,
2957     dpif_netdev_flow_flush,
2958     dpif_netdev_flow_dump_create,
2959     dpif_netdev_flow_dump_destroy,
2960     dpif_netdev_flow_dump_thread_create,
2961     dpif_netdev_flow_dump_thread_destroy,
2962     dpif_netdev_flow_dump_next,
2963     dpif_netdev_operate,
2964     NULL,                       /* recv_set */
2965     NULL,                       /* handlers_set */
2966     dpif_netdev_pmd_set,
2967     dpif_netdev_queue_to_priority,
2968     NULL,                       /* recv */
2969     NULL,                       /* recv_wait */
2970     NULL,                       /* recv_purge */
2971     dpif_netdev_register_upcall_cb,
2972     dpif_netdev_enable_upcall,
2973     dpif_netdev_disable_upcall,
2974 };
2975
2976 static void
2977 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2978                               const char *argv[], void *aux OVS_UNUSED)
2979 {
2980     struct dp_netdev_port *old_port;
2981     struct dp_netdev_port *new_port;
2982     struct dp_netdev *dp;
2983     odp_port_t port_no;
2984
2985     ovs_mutex_lock(&dp_netdev_mutex);
2986     dp = shash_find_data(&dp_netdevs, argv[1]);
2987     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2988         ovs_mutex_unlock(&dp_netdev_mutex);
2989         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2990         return;
2991     }
2992     ovs_refcount_ref(&dp->ref_cnt);
2993     ovs_mutex_unlock(&dp_netdev_mutex);
2994
2995     ovs_mutex_lock(&dp->port_mutex);
2996     if (get_port_by_name(dp, argv[2], &old_port)) {
2997         unixctl_command_reply_error(conn, "unknown port");
2998         goto exit;
2999     }
3000
3001     port_no = u32_to_odp(atoi(argv[3]));
3002     if (!port_no || port_no == ODPP_NONE) {
3003         unixctl_command_reply_error(conn, "bad port number");
3004         goto exit;
3005     }
3006     if (dp_netdev_lookup_port(dp, port_no)) {
3007         unixctl_command_reply_error(conn, "port number already in use");
3008         goto exit;
3009     }
3010
3011     /* Remove old port. */
3012     cmap_remove(&dp->ports, &old_port->node, hash_port_no(old_port->port_no));
3013     ovsrcu_postpone(free, old_port);
3014
3015     /* Insert new port (cmap semantics mean we cannot re-insert 'old_port'). */
3016     new_port = xmemdup(old_port, sizeof *old_port);
3017     new_port->port_no = port_no;
3018     cmap_insert(&dp->ports, &new_port->node, hash_port_no(port_no));
3019
3020     seq_change(dp->port_seq);
3021     unixctl_command_reply(conn, NULL);
3022
3023 exit:
3024     ovs_mutex_unlock(&dp->port_mutex);
3025     dp_netdev_unref(dp);
3026 }
3027
3028 static void
3029 dpif_dummy_delete_port(struct unixctl_conn *conn, int argc OVS_UNUSED,
3030                        const char *argv[], void *aux OVS_UNUSED)
3031 {
3032     struct dp_netdev_port *port;
3033     struct dp_netdev *dp;
3034
3035     ovs_mutex_lock(&dp_netdev_mutex);
3036     dp = shash_find_data(&dp_netdevs, argv[1]);
3037     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
3038         ovs_mutex_unlock(&dp_netdev_mutex);
3039         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
3040         return;
3041     }
3042     ovs_refcount_ref(&dp->ref_cnt);
3043     ovs_mutex_unlock(&dp_netdev_mutex);
3044
3045     ovs_mutex_lock(&dp->port_mutex);
3046     if (get_port_by_name(dp, argv[2], &port)) {
3047         unixctl_command_reply_error(conn, "unknown port");
3048     } else if (port->port_no == ODPP_LOCAL) {
3049         unixctl_command_reply_error(conn, "can't delete local port");
3050     } else {
3051         do_del_port(dp, port);
3052         unixctl_command_reply(conn, NULL);
3053     }
3054     ovs_mutex_unlock(&dp->port_mutex);
3055
3056     dp_netdev_unref(dp);
3057 }
3058
3059 static void
3060 dpif_dummy_register__(const char *type)
3061 {
3062     struct dpif_class *class;
3063
3064     class = xmalloc(sizeof *class);
3065     *class = dpif_netdev_class;
3066     class->type = xstrdup(type);
3067     dp_register_provider(class);
3068 }
3069
3070 void
3071 dpif_dummy_register(bool override)
3072 {
3073     if (override) {
3074         struct sset types;
3075         const char *type;
3076
3077         sset_init(&types);
3078         dp_enumerate_types(&types);
3079         SSET_FOR_EACH (type, &types) {
3080             if (!dp_unregister_provider(type)) {
3081                 dpif_dummy_register__(type);
3082             }
3083         }
3084         sset_destroy(&types);
3085     }
3086
3087     dpif_dummy_register__("dummy");
3088
3089     unixctl_command_register("dpif-dummy/change-port-number",
3090                              "dp port new-number",
3091                              3, 3, dpif_dummy_change_port_number, NULL);
3092     unixctl_command_register("dpif-dummy/delete-port", "dp port",
3093                              2, 2, dpif_dummy_delete_port, NULL);
3094 }