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