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