bridge: Add test that ports that disappear get added back to the datapath.
[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.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 "flow.h"
42 #include "hmap.h"
43 #include "latch.h"
44 #include "list.h"
45 #include "meta-flow.h"
46 #include "netdev.h"
47 #include "netdev-dpdk.h"
48 #include "netdev-vport.h"
49 #include "netlink.h"
50 #include "odp-execute.h"
51 #include "odp-util.h"
52 #include "ofp-print.h"
53 #include "ofpbuf.h"
54 #include "ovs-rcu.h"
55 #include "packets.h"
56 #include "poll-loop.h"
57 #include "random.h"
58 #include "seq.h"
59 #include "shash.h"
60 #include "sset.h"
61 #include "timeval.h"
62 #include "unixctl.h"
63 #include "util.h"
64 #include "vlog.h"
65
66 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
67
68 /* By default, choose a priority in the middle. */
69 #define NETDEV_RULE_PRIORITY 0x8000
70
71 #define NR_THREADS 1
72 /* Use per thread recirc_depth to prevent recirculation loop. */
73 #define MAX_RECIRC_DEPTH 5
74 DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
75
76 /* Configuration parameters. */
77 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
78
79 /* Queues. */
80 enum { MAX_QUEUE_LEN = 128 };   /* Maximum number of packets per queue. */
81 enum { QUEUE_MASK = MAX_QUEUE_LEN - 1 };
82 BUILD_ASSERT_DECL(IS_POW2(MAX_QUEUE_LEN));
83
84 /* Protects against changes to 'dp_netdevs'. */
85 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
86
87 /* Contains all 'struct dp_netdev's. */
88 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
89     = SHASH_INITIALIZER(&dp_netdevs);
90
91 struct dp_netdev_upcall {
92     struct dpif_upcall upcall;  /* Queued upcall information. */
93     struct ofpbuf buf;          /* ofpbuf instance for upcall.packet. */
94 };
95
96 /* A queue passing packets from a struct dp_netdev to its clients (handlers).
97  *
98  *
99  * Thread-safety
100  * =============
101  *
102  * Any access at all requires the owning 'dp_netdev''s queue_rwlock and
103  * its own mutex. */
104 struct dp_netdev_queue {
105     struct ovs_mutex mutex;
106     struct seq *seq;      /* Incremented whenever a packet is queued. */
107     struct dp_netdev_upcall upcalls[MAX_QUEUE_LEN] OVS_GUARDED;
108     unsigned int head OVS_GUARDED;
109     unsigned int tail OVS_GUARDED;
110 };
111
112 /* Datapath based on the network device interface from netdev.h.
113  *
114  *
115  * Thread-safety
116  * =============
117  *
118  * Some members, marked 'const', are immutable.  Accessing other members
119  * requires synchronization, as noted in more detail below.
120  *
121  * Acquisition order is, from outermost to innermost:
122  *
123  *    dp_netdev_mutex (global)
124  *    port_mutex
125  *    flow_mutex
126  *    cls.rwlock
127  *    queue_rwlock
128  */
129 struct dp_netdev {
130     const struct dpif_class *const class;
131     const char *const name;
132     struct ovs_refcount ref_cnt;
133     atomic_flag destroyed;
134
135     /* Flows.
136      *
137      * Readers of 'cls' and 'flow_table' must take a 'cls->rwlock' read lock.
138      *
139      * Writers of 'cls' and 'flow_table' must take the 'flow_mutex' and then
140      * the 'cls->rwlock' write lock.  (The outer 'flow_mutex' allows writers to
141      * atomically perform multiple operations on 'cls' and 'flow_table'.)
142      */
143     struct ovs_mutex flow_mutex;
144     struct classifier cls;      /* Classifier.  Protected by cls.rwlock. */
145     struct hmap flow_table OVS_GUARDED; /* Flow table. */
146
147     /* Queues.
148      *
149      * 'queue_rwlock' protects the modification of 'handler_queues' and
150      * 'n_handlers'.  The queue elements are protected by its
151      * 'handler_queues''s mutex. */
152     struct fat_rwlock queue_rwlock;
153     struct dp_netdev_queue *handler_queues;
154     uint32_t n_handlers;
155
156     /* Statistics.
157      *
158      * ovsthread_stats is internally synchronized. */
159     struct ovsthread_stats stats; /* Contains 'struct dp_netdev_stats *'. */
160
161     /* Ports.
162      *
163      * Protected by RCU.  Take the mutex to add or remove ports. */
164     struct ovs_mutex port_mutex;
165     struct cmap ports;
166     struct seq *port_seq;       /* Incremented whenever a port changes. */
167
168     /* Forwarding threads. */
169     struct latch exit_latch;
170     struct pmd_thread *pmd_threads;
171     size_t n_pmd_threads;
172     int pmd_count;
173 };
174
175 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
176                                                     odp_port_t);
177
178 enum dp_stat_type {
179     DP_STAT_HIT,                /* Packets that matched in the flow table. */
180     DP_STAT_MISS,               /* Packets that did not match. */
181     DP_STAT_LOST,               /* Packets not passed up to the client. */
182     DP_N_STATS
183 };
184
185 /* Contained by struct dp_netdev's 'stats' member.  */
186 struct dp_netdev_stats {
187     struct ovs_mutex mutex;          /* Protects 'n'. */
188
189     /* Indexed by DP_STAT_*, protected by 'mutex'. */
190     unsigned long long int n[DP_N_STATS] OVS_GUARDED;
191 };
192
193
194 /* A port in a netdev-based datapath. */
195 struct dp_netdev_port {
196     struct cmap_node node;      /* Node in dp_netdev's 'ports'. */
197     odp_port_t port_no;
198     struct netdev *netdev;
199     struct netdev_saved_flags *sf;
200     struct netdev_rxq **rxq;
201     struct ovs_refcount ref_cnt;
202     char *type;                 /* Port type as requested by user. */
203 };
204
205 /* A flow in dp_netdev's 'flow_table'.
206  *
207  *
208  * Thread-safety
209  * =============
210  *
211  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
212  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
213  *
214  * Motivation
215  * ----------
216  *
217  * The thread safety rules described here for "struct dp_netdev_flow" are
218  * motivated by two goals:
219  *
220  *    - Prevent threads that read members of "struct dp_netdev_flow" from
221  *      reading bad data due to changes by some thread concurrently modifying
222  *      those members.
223  *
224  *    - Prevent two threads making changes to members of a given "struct
225  *      dp_netdev_flow" from interfering with each other.
226  *
227  *
228  * Rules
229  * -----
230  *
231  * A flow 'flow' may be accessed without a risk of being freed by code that
232  * holds a read-lock or write-lock on 'cls->rwlock' or that owns a reference to
233  * 'flow->ref_cnt' (or both).  Code that needs to hold onto a flow for a while
234  * should take 'cls->rwlock', find the flow it needs, increment 'flow->ref_cnt'
235  * with dpif_netdev_flow_ref(), and drop 'cls->rwlock'.
236  *
237  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
238  * flow from being deleted from 'cls' (that's 'cls->rwlock') and it doesn't
239  * protect members of 'flow' from modification.
240  *
241  * Some members, marked 'const', are immutable.  Accessing other members
242  * requires synchronization, as noted in more detail below.
243  */
244 struct dp_netdev_flow {
245     /* Packet classification. */
246     const struct cls_rule cr;   /* In owning dp_netdev's 'cls'. */
247
248     /* Hash table index by unmasked flow. */
249     const struct hmap_node node; /* In owning dp_netdev's 'flow_table'. */
250     const struct flow flow;      /* The flow that created this entry. */
251
252     /* Statistics.
253      *
254      * Reading or writing these members requires 'mutex'. */
255     struct ovsthread_stats stats; /* Contains "struct dp_netdev_flow_stats". */
256
257     /* Actions. */
258     OVSRCU_TYPE(struct dp_netdev_actions *) actions;
259 };
260
261 static void dp_netdev_flow_free(struct dp_netdev_flow *);
262
263 /* Contained by struct dp_netdev_flow's 'stats' member.  */
264 struct dp_netdev_flow_stats {
265     struct ovs_mutex mutex;         /* Guards all the other members. */
266
267     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
268     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
269     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
270     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
271 };
272
273 /* A set of datapath actions within a "struct dp_netdev_flow".
274  *
275  *
276  * Thread-safety
277  * =============
278  *
279  * A struct dp_netdev_actions 'actions' is protected with RCU. */
280 struct dp_netdev_actions {
281     /* These members are immutable: they do not change during the struct's
282      * lifetime.  */
283     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
284     unsigned int size;          /* Size of 'actions', in bytes. */
285 };
286
287 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
288                                                    size_t);
289 struct dp_netdev_actions *dp_netdev_flow_get_actions(
290     const struct dp_netdev_flow *);
291 static void dp_netdev_actions_free(struct dp_netdev_actions *);
292
293 /* PMD: Poll modes drivers.  PMD accesses devices via polling to eliminate
294  * the performance overhead of interrupt processing.  Therefore netdev can
295  * not implement rx-wait for these devices.  dpif-netdev needs to poll
296  * these device to check for recv buffer.  pmd-thread does polling for
297  * devices assigned to itself thread.
298  *
299  * DPDK used PMD for accessing NIC.
300  *
301  * A thread that receives packets from PMD ports, looks them up in the flow
302  * table, and executes the actions it finds.
303  **/
304 struct pmd_thread {
305     struct dp_netdev *dp;
306     pthread_t thread;
307     int id;
308     atomic_uint change_seq;
309 };
310
311 /* Interface to netdev-based datapath. */
312 struct dpif_netdev {
313     struct dpif dpif;
314     struct dp_netdev *dp;
315     uint64_t last_port_seq;
316 };
317
318 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
319                               struct dp_netdev_port **portp);
320 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
321                             struct dp_netdev_port **portp);
322 static void dp_netdev_free(struct dp_netdev *)
323     OVS_REQUIRES(dp_netdev_mutex);
324 static void dp_netdev_flow_flush(struct dp_netdev *);
325 static int do_add_port(struct dp_netdev *dp, const char *devname,
326                        const char *type, odp_port_t port_no)
327     OVS_REQUIRES(dp->port_mutex);
328 static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
329     OVS_REQUIRES(dp->port_mutex);
330 static void dp_netdev_destroy_all_queues(struct dp_netdev *dp)
331     OVS_REQ_WRLOCK(dp->queue_rwlock);
332 static int dpif_netdev_open(const struct dpif_class *, const char *name,
333                             bool create, struct dpif **);
334 static int dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *,
335                                       int queue_no, int type,
336                                       const struct miniflow *,
337                                       const struct nlattr *userdata);
338 static void dp_netdev_execute_actions(struct dp_netdev *dp,
339                                       const struct miniflow *,
340                                       struct ofpbuf *, bool may_steal,
341                                       struct pkt_metadata *,
342                                       const struct nlattr *actions,
343                                       size_t actions_len);
344 static void dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
345                                  struct pkt_metadata *);
346
347 static void dp_netdev_set_pmd_threads(struct dp_netdev *, int n);
348
349 static struct dpif_netdev *
350 dpif_netdev_cast(const struct dpif *dpif)
351 {
352     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
353     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
354 }
355
356 static struct dp_netdev *
357 get_dp_netdev(const struct dpif *dpif)
358 {
359     return dpif_netdev_cast(dpif)->dp;
360 }
361
362 static int
363 dpif_netdev_enumerate(struct sset *all_dps)
364 {
365     struct shash_node *node;
366
367     ovs_mutex_lock(&dp_netdev_mutex);
368     SHASH_FOR_EACH(node, &dp_netdevs) {
369         sset_add(all_dps, node->name);
370     }
371     ovs_mutex_unlock(&dp_netdev_mutex);
372
373     return 0;
374 }
375
376 static bool
377 dpif_netdev_class_is_dummy(const struct dpif_class *class)
378 {
379     return class != &dpif_netdev_class;
380 }
381
382 static const char *
383 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
384 {
385     return strcmp(type, "internal") ? type
386                   : dpif_netdev_class_is_dummy(class) ? "dummy"
387                   : "tap";
388 }
389
390 static struct dpif *
391 create_dpif_netdev(struct dp_netdev *dp)
392 {
393     uint16_t netflow_id = hash_string(dp->name, 0);
394     struct dpif_netdev *dpif;
395
396     ovs_refcount_ref(&dp->ref_cnt);
397
398     dpif = xmalloc(sizeof *dpif);
399     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
400     dpif->dp = dp;
401     dpif->last_port_seq = seq_read(dp->port_seq);
402
403     return &dpif->dpif;
404 }
405
406 /* Choose an unused, non-zero port number and return it on success.
407  * Return ODPP_NONE on failure. */
408 static odp_port_t
409 choose_port(struct dp_netdev *dp, const char *name)
410     OVS_REQUIRES(dp->port_mutex)
411 {
412     uint32_t port_no;
413
414     if (dp->class != &dpif_netdev_class) {
415         const char *p;
416         int start_no = 0;
417
418         /* If the port name begins with "br", start the number search at
419          * 100 to make writing tests easier. */
420         if (!strncmp(name, "br", 2)) {
421             start_no = 100;
422         }
423
424         /* If the port name contains a number, try to assign that port number.
425          * This can make writing unit tests easier because port numbers are
426          * predictable. */
427         for (p = name; *p != '\0'; p++) {
428             if (isdigit((unsigned char) *p)) {
429                 port_no = start_no + strtol(p, NULL, 10);
430                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
431                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
432                     return u32_to_odp(port_no);
433                 }
434                 break;
435             }
436         }
437     }
438
439     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
440         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
441             return u32_to_odp(port_no);
442         }
443     }
444
445     return ODPP_NONE;
446 }
447
448 static int
449 create_dp_netdev(const char *name, const struct dpif_class *class,
450                  struct dp_netdev **dpp)
451     OVS_REQUIRES(dp_netdev_mutex)
452 {
453     struct dp_netdev *dp;
454     int error;
455
456     dp = xzalloc(sizeof *dp);
457     shash_add(&dp_netdevs, name, dp);
458
459     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
460     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
461     ovs_refcount_init(&dp->ref_cnt);
462     atomic_flag_clear(&dp->destroyed);
463
464     ovs_mutex_init(&dp->flow_mutex);
465     classifier_init(&dp->cls, NULL);
466     hmap_init(&dp->flow_table);
467
468     fat_rwlock_init(&dp->queue_rwlock);
469
470     ovsthread_stats_init(&dp->stats);
471
472     ovs_mutex_init(&dp->port_mutex);
473     cmap_init(&dp->ports);
474     dp->port_seq = seq_create();
475     latch_init(&dp->exit_latch);
476
477     ovs_mutex_lock(&dp->port_mutex);
478     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
479     ovs_mutex_unlock(&dp->port_mutex);
480     if (error) {
481         dp_netdev_free(dp);
482         return error;
483     }
484
485     *dpp = dp;
486     return 0;
487 }
488
489 static int
490 dpif_netdev_open(const struct dpif_class *class, const char *name,
491                  bool create, struct dpif **dpifp)
492 {
493     struct dp_netdev *dp;
494     int error;
495
496     ovs_mutex_lock(&dp_netdev_mutex);
497     dp = shash_find_data(&dp_netdevs, name);
498     if (!dp) {
499         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
500     } else {
501         error = (dp->class != class ? EINVAL
502                  : create ? EEXIST
503                  : 0);
504     }
505     if (!error) {
506         *dpifp = create_dpif_netdev(dp);
507     }
508     ovs_mutex_unlock(&dp_netdev_mutex);
509
510     return error;
511 }
512
513 static void
514 dp_netdev_purge_queues(struct dp_netdev *dp)
515     OVS_REQ_WRLOCK(dp->queue_rwlock)
516 {
517     int i;
518
519     for (i = 0; i < dp->n_handlers; i++) {
520         struct dp_netdev_queue *q = &dp->handler_queues[i];
521
522         ovs_mutex_lock(&q->mutex);
523         while (q->tail != q->head) {
524             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
525             ofpbuf_uninit(&u->upcall.packet);
526             ofpbuf_uninit(&u->buf);
527         }
528         ovs_mutex_unlock(&q->mutex);
529     }
530 }
531
532 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
533  * through the 'dp_netdevs' shash while freeing 'dp'. */
534 static void
535 dp_netdev_free(struct dp_netdev *dp)
536     OVS_REQUIRES(dp_netdev_mutex)
537 {
538     struct dp_netdev_port *port;
539     struct dp_netdev_stats *bucket;
540     struct cmap_cursor cursor;
541     int i;
542
543     shash_find_and_delete(&dp_netdevs, dp->name);
544
545     dp_netdev_set_pmd_threads(dp, 0);
546     free(dp->pmd_threads);
547
548     dp_netdev_flow_flush(dp);
549     ovs_mutex_lock(&dp->port_mutex);
550     CMAP_FOR_EACH (port, node, &cursor, &dp->ports) {
551         do_del_port(dp, port);
552     }
553     ovs_mutex_unlock(&dp->port_mutex);
554
555     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
556         ovs_mutex_destroy(&bucket->mutex);
557         free_cacheline(bucket);
558     }
559     ovsthread_stats_destroy(&dp->stats);
560
561     fat_rwlock_wrlock(&dp->queue_rwlock);
562     dp_netdev_destroy_all_queues(dp);
563     fat_rwlock_unlock(&dp->queue_rwlock);
564
565     fat_rwlock_destroy(&dp->queue_rwlock);
566
567     classifier_destroy(&dp->cls);
568     hmap_destroy(&dp->flow_table);
569     ovs_mutex_destroy(&dp->flow_mutex);
570     seq_destroy(dp->port_seq);
571     cmap_destroy(&dp->ports);
572     latch_destroy(&dp->exit_latch);
573     free(CONST_CAST(char *, dp->name));
574     free(dp);
575 }
576
577 static void
578 dp_netdev_unref(struct dp_netdev *dp)
579 {
580     if (dp) {
581         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
582          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
583         ovs_mutex_lock(&dp_netdev_mutex);
584         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
585             dp_netdev_free(dp);
586         }
587         ovs_mutex_unlock(&dp_netdev_mutex);
588     }
589 }
590
591 static void
592 dpif_netdev_close(struct dpif *dpif)
593 {
594     struct dp_netdev *dp = get_dp_netdev(dpif);
595
596     dp_netdev_unref(dp);
597     free(dpif);
598 }
599
600 static int
601 dpif_netdev_destroy(struct dpif *dpif)
602 {
603     struct dp_netdev *dp = get_dp_netdev(dpif);
604
605     if (!atomic_flag_test_and_set(&dp->destroyed)) {
606         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
607             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
608             OVS_NOT_REACHED();
609         }
610     }
611
612     return 0;
613 }
614
615 static int
616 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
617 {
618     struct dp_netdev *dp = get_dp_netdev(dpif);
619     struct dp_netdev_stats *bucket;
620     size_t i;
621
622     fat_rwlock_rdlock(&dp->cls.rwlock);
623     stats->n_flows = hmap_count(&dp->flow_table);
624     fat_rwlock_unlock(&dp->cls.rwlock);
625
626     stats->n_hit = stats->n_missed = stats->n_lost = 0;
627     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
628         ovs_mutex_lock(&bucket->mutex);
629         stats->n_hit += bucket->n[DP_STAT_HIT];
630         stats->n_missed += bucket->n[DP_STAT_MISS];
631         stats->n_lost += bucket->n[DP_STAT_LOST];
632         ovs_mutex_unlock(&bucket->mutex);
633     }
634     stats->n_masks = UINT32_MAX;
635     stats->n_mask_hit = UINT64_MAX;
636
637     return 0;
638 }
639
640 static void
641 dp_netdev_reload_pmd_threads(struct dp_netdev *dp)
642 {
643     int i;
644
645     for (i = 0; i < dp->n_pmd_threads; i++) {
646         struct pmd_thread *f = &dp->pmd_threads[i];
647         int id;
648
649         atomic_add(&f->change_seq, 1, &id);
650    }
651 }
652
653 static uint32_t
654 hash_port_no(odp_port_t port_no)
655 {
656     return hash_int(odp_to_u32(port_no), 0);
657 }
658
659 static int
660 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
661             odp_port_t port_no)
662     OVS_REQUIRES(dp->port_mutex)
663 {
664     struct netdev_saved_flags *sf;
665     struct dp_netdev_port *port;
666     struct netdev *netdev;
667     enum netdev_flags flags;
668     const char *open_type;
669     int error;
670     int i;
671
672     /* XXX reject devices already in some dp_netdev. */
673
674     /* Open and validate network device. */
675     open_type = dpif_netdev_port_open_type(dp->class, type);
676     error = netdev_open(devname, open_type, &netdev);
677     if (error) {
678         return error;
679     }
680     /* XXX reject non-Ethernet devices */
681
682     netdev_get_flags(netdev, &flags);
683     if (flags & NETDEV_LOOPBACK) {
684         VLOG_ERR("%s: cannot add a loopback device", devname);
685         netdev_close(netdev);
686         return EINVAL;
687     }
688
689     port = xzalloc(sizeof *port);
690     port->port_no = port_no;
691     port->netdev = netdev;
692     port->rxq = xmalloc(sizeof *port->rxq * netdev_n_rxq(netdev));
693     port->type = xstrdup(type);
694     for (i = 0; i < netdev_n_rxq(netdev); i++) {
695         error = netdev_rxq_open(netdev, &port->rxq[i], i);
696         if (error
697             && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
698             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
699                      devname, ovs_strerror(errno));
700             netdev_close(netdev);
701             return error;
702         }
703     }
704
705     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
706     if (error) {
707         for (i = 0; i < netdev_n_rxq(netdev); i++) {
708             netdev_rxq_close(port->rxq[i]);
709         }
710         netdev_close(netdev);
711         free(port->rxq);
712         free(port);
713         return error;
714     }
715     port->sf = sf;
716
717     if (netdev_is_pmd(netdev)) {
718         dp->pmd_count++;
719         dp_netdev_set_pmd_threads(dp, NR_THREADS);
720         dp_netdev_reload_pmd_threads(dp);
721     }
722     ovs_refcount_init(&port->ref_cnt);
723
724     cmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
725     seq_change(dp->port_seq);
726
727     return 0;
728 }
729
730 static int
731 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
732                      odp_port_t *port_nop)
733 {
734     struct dp_netdev *dp = get_dp_netdev(dpif);
735     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
736     const char *dpif_port;
737     odp_port_t port_no;
738     int error;
739
740     ovs_mutex_lock(&dp->port_mutex);
741     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
742     if (*port_nop != ODPP_NONE) {
743         port_no = *port_nop;
744         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
745     } else {
746         port_no = choose_port(dp, dpif_port);
747         error = port_no == ODPP_NONE ? EFBIG : 0;
748     }
749     if (!error) {
750         *port_nop = port_no;
751         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
752     }
753     ovs_mutex_unlock(&dp->port_mutex);
754
755     return error;
756 }
757
758 static int
759 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
760 {
761     struct dp_netdev *dp = get_dp_netdev(dpif);
762     int error;
763
764     ovs_mutex_lock(&dp->port_mutex);
765     if (port_no == ODPP_LOCAL) {
766         error = EINVAL;
767     } else {
768         struct dp_netdev_port *port;
769
770         error = get_port_by_number(dp, port_no, &port);
771         if (!error) {
772             do_del_port(dp, port);
773         }
774     }
775     ovs_mutex_unlock(&dp->port_mutex);
776
777     return error;
778 }
779
780 static bool
781 is_valid_port_number(odp_port_t port_no)
782 {
783     return port_no != ODPP_NONE;
784 }
785
786 static struct dp_netdev_port *
787 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
788 {
789     struct dp_netdev_port *port;
790
791     CMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
792         if (port->port_no == port_no) {
793             return port;
794         }
795     }
796     return NULL;
797 }
798
799 static int
800 get_port_by_number(struct dp_netdev *dp,
801                    odp_port_t port_no, struct dp_netdev_port **portp)
802 {
803     if (!is_valid_port_number(port_no)) {
804         *portp = NULL;
805         return EINVAL;
806     } else {
807         *portp = dp_netdev_lookup_port(dp, port_no);
808         return *portp ? 0 : ENOENT;
809     }
810 }
811
812 static void
813 port_ref(struct dp_netdev_port *port)
814 {
815     if (port) {
816         ovs_refcount_ref(&port->ref_cnt);
817     }
818 }
819
820 static void
821 port_destroy__(struct dp_netdev_port *port)
822 {
823     int n_rxq;
824     int i;
825
826     netdev_close(port->netdev);
827     netdev_restore_flags(port->sf);
828
829     n_rxq = netdev_n_rxq(port->netdev);
830     for (i = 0; i < n_rxq; i++) {
831         netdev_rxq_close(port->rxq[i]);
832     }
833     free(port->rxq);
834     free(port->type);
835     free(port);
836 }
837
838 static void
839 port_unref(struct dp_netdev_port *port)
840 {
841     if (port && ovs_refcount_unref(&port->ref_cnt) == 1) {
842         ovsrcu_postpone(port_destroy__, port);
843     }
844 }
845
846 static int
847 get_port_by_name(struct dp_netdev *dp,
848                  const char *devname, struct dp_netdev_port **portp)
849     OVS_REQUIRES(dp->port_mutex)
850 {
851     struct dp_netdev_port *port;
852     struct cmap_cursor cursor;
853
854     CMAP_FOR_EACH (port, node, &cursor, &dp->ports) {
855         if (!strcmp(netdev_get_name(port->netdev), devname)) {
856             *portp = port;
857             return 0;
858         }
859     }
860     return ENOENT;
861 }
862
863 static void
864 do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
865     OVS_REQUIRES(dp->port_mutex)
866 {
867     cmap_remove(&dp->ports, &port->node, hash_odp_port(port->port_no));
868     seq_change(dp->port_seq);
869     if (netdev_is_pmd(port->netdev)) {
870         dp_netdev_reload_pmd_threads(dp);
871     }
872
873     port_unref(port);
874 }
875
876 static void
877 answer_port_query(const struct dp_netdev_port *port,
878                   struct dpif_port *dpif_port)
879 {
880     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
881     dpif_port->type = xstrdup(port->type);
882     dpif_port->port_no = port->port_no;
883 }
884
885 static int
886 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
887                                  struct dpif_port *dpif_port)
888 {
889     struct dp_netdev *dp = get_dp_netdev(dpif);
890     struct dp_netdev_port *port;
891     int error;
892
893     error = get_port_by_number(dp, port_no, &port);
894     if (!error && dpif_port) {
895         answer_port_query(port, dpif_port);
896     }
897
898     return error;
899 }
900
901 static int
902 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
903                                struct dpif_port *dpif_port)
904 {
905     struct dp_netdev *dp = get_dp_netdev(dpif);
906     struct dp_netdev_port *port;
907     int error;
908
909     ovs_mutex_lock(&dp->port_mutex);
910     error = get_port_by_name(dp, devname, &port);
911     if (!error && dpif_port) {
912         answer_port_query(port, dpif_port);
913     }
914     ovs_mutex_unlock(&dp->port_mutex);
915
916     return error;
917 }
918
919 static void
920 dp_netdev_flow_free(struct dp_netdev_flow *flow)
921 {
922     struct dp_netdev_flow_stats *bucket;
923     size_t i;
924
925     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &flow->stats) {
926         ovs_mutex_destroy(&bucket->mutex);
927         free_cacheline(bucket);
928     }
929     ovsthread_stats_destroy(&flow->stats);
930
931     cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
932     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
933     free(flow);
934 }
935
936 static void
937 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
938     OVS_REQ_WRLOCK(dp->cls.rwlock)
939     OVS_REQUIRES(dp->flow_mutex)
940 {
941     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
942     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
943
944     classifier_remove(&dp->cls, cr);
945     hmap_remove(&dp->flow_table, node);
946     ovsrcu_postpone(dp_netdev_flow_free, flow);
947 }
948
949 static void
950 dp_netdev_flow_flush(struct dp_netdev *dp)
951 {
952     struct dp_netdev_flow *netdev_flow, *next;
953
954     ovs_mutex_lock(&dp->flow_mutex);
955     fat_rwlock_wrlock(&dp->cls.rwlock);
956     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
957         dp_netdev_remove_flow(dp, netdev_flow);
958     }
959     fat_rwlock_unlock(&dp->cls.rwlock);
960     ovs_mutex_unlock(&dp->flow_mutex);
961 }
962
963 static int
964 dpif_netdev_flow_flush(struct dpif *dpif)
965 {
966     struct dp_netdev *dp = get_dp_netdev(dpif);
967
968     dp_netdev_flow_flush(dp);
969     return 0;
970 }
971
972 struct dp_netdev_port_state {
973     struct cmap_position position;
974     char *name;
975 };
976
977 static int
978 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
979 {
980     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
981     return 0;
982 }
983
984 static int
985 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
986                            struct dpif_port *dpif_port)
987 {
988     struct dp_netdev_port_state *state = state_;
989     struct dp_netdev *dp = get_dp_netdev(dpif);
990     struct cmap_node *node;
991     int retval;
992
993     node = cmap_next_position(&dp->ports, &state->position);
994     if (node) {
995         struct dp_netdev_port *port;
996
997         port = CONTAINER_OF(node, struct dp_netdev_port, node);
998
999         free(state->name);
1000         state->name = xstrdup(netdev_get_name(port->netdev));
1001         dpif_port->name = state->name;
1002         dpif_port->type = port->type;
1003         dpif_port->port_no = port->port_no;
1004
1005         retval = 0;
1006     } else {
1007         retval = EOF;
1008     }
1009
1010     return retval;
1011 }
1012
1013 static int
1014 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1015 {
1016     struct dp_netdev_port_state *state = state_;
1017     free(state->name);
1018     free(state);
1019     return 0;
1020 }
1021
1022 static int
1023 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1024 {
1025     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1026     uint64_t new_port_seq;
1027     int error;
1028
1029     new_port_seq = seq_read(dpif->dp->port_seq);
1030     if (dpif->last_port_seq != new_port_seq) {
1031         dpif->last_port_seq = new_port_seq;
1032         error = ENOBUFS;
1033     } else {
1034         error = EAGAIN;
1035     }
1036
1037     return error;
1038 }
1039
1040 static void
1041 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1042 {
1043     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1044
1045     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1046 }
1047
1048 static struct dp_netdev_flow *
1049 dp_netdev_flow_cast(const struct cls_rule *cr)
1050 {
1051     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1052 }
1053
1054 static struct dp_netdev_flow *
1055 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct miniflow *key)
1056     OVS_EXCLUDED(dp->cls.rwlock)
1057 {
1058     struct dp_netdev_flow *netdev_flow;
1059     struct cls_rule *rule;
1060
1061     fat_rwlock_rdlock(&dp->cls.rwlock);
1062     rule = classifier_lookup_miniflow_first(&dp->cls, key);
1063     netdev_flow = dp_netdev_flow_cast(rule);
1064     fat_rwlock_unlock(&dp->cls.rwlock);
1065
1066     return netdev_flow;
1067 }
1068
1069 static struct dp_netdev_flow *
1070 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1071     OVS_REQ_RDLOCK(dp->cls.rwlock)
1072 {
1073     struct dp_netdev_flow *netdev_flow;
1074
1075     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1076                              &dp->flow_table) {
1077         if (flow_equal(&netdev_flow->flow, flow)) {
1078             return netdev_flow;
1079         }
1080     }
1081
1082     return NULL;
1083 }
1084
1085 static void
1086 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1087                     struct dpif_flow_stats *stats)
1088 {
1089     struct dp_netdev_flow_stats *bucket;
1090     size_t i;
1091
1092     memset(stats, 0, sizeof *stats);
1093     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1094         ovs_mutex_lock(&bucket->mutex);
1095         stats->n_packets += bucket->packet_count;
1096         stats->n_bytes += bucket->byte_count;
1097         stats->used = MAX(stats->used, bucket->used);
1098         stats->tcp_flags |= bucket->tcp_flags;
1099         ovs_mutex_unlock(&bucket->mutex);
1100     }
1101 }
1102
1103 static int
1104 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1105                               const struct nlattr *mask_key,
1106                               uint32_t mask_key_len, const struct flow *flow,
1107                               struct flow *mask)
1108 {
1109     if (mask_key_len) {
1110         enum odp_key_fitness fitness;
1111
1112         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1113         if (fitness) {
1114             /* This should not happen: it indicates that
1115              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1116              * disagree on the acceptable form of a mask.  Log the problem
1117              * as an error, with enough details to enable debugging. */
1118             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1119
1120             if (!VLOG_DROP_ERR(&rl)) {
1121                 struct ds s;
1122
1123                 ds_init(&s);
1124                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1125                                 true);
1126                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1127                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1128                 ds_destroy(&s);
1129             }
1130
1131             return EINVAL;
1132         }
1133     } else {
1134         enum mf_field_id id;
1135         /* No mask key, unwildcard everything except fields whose
1136          * prerequisities are not met. */
1137         memset(mask, 0x0, sizeof *mask);
1138
1139         for (id = 0; id < MFF_N_IDS; ++id) {
1140             /* Skip registers and metadata. */
1141             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1142                 && id != MFF_METADATA) {
1143                 const struct mf_field *mf = mf_from_id(id);
1144                 if (mf_are_prereqs_ok(mf, flow)) {
1145                     mf_mask_field(mf, mask);
1146                 }
1147             }
1148         }
1149     }
1150
1151     /* Force unwildcard the in_port.
1152      *
1153      * We need to do this even in the case where we unwildcard "everything"
1154      * above because "everything" only includes the 16-bit OpenFlow port number
1155      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1156      * port number mask->in_port.odp_port. */
1157     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1158
1159     return 0;
1160 }
1161
1162 static int
1163 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1164                               struct flow *flow)
1165 {
1166     odp_port_t in_port;
1167
1168     if (odp_flow_key_to_flow(key, key_len, flow)) {
1169         /* This should not happen: it indicates that odp_flow_key_from_flow()
1170          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1171          * flow.  Log the problem as an error, with enough details to enable
1172          * debugging. */
1173         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1174
1175         if (!VLOG_DROP_ERR(&rl)) {
1176             struct ds s;
1177
1178             ds_init(&s);
1179             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1180             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1181             ds_destroy(&s);
1182         }
1183
1184         return EINVAL;
1185     }
1186
1187     in_port = flow->in_port.odp_port;
1188     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1189         return EINVAL;
1190     }
1191
1192     return 0;
1193 }
1194
1195 static int
1196 dpif_netdev_flow_get(const struct dpif *dpif,
1197                      const struct nlattr *nl_key, size_t nl_key_len,
1198                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1199 {
1200     struct dp_netdev *dp = get_dp_netdev(dpif);
1201     struct dp_netdev_flow *netdev_flow;
1202     struct flow key;
1203     int error;
1204
1205     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1206     if (error) {
1207         return error;
1208     }
1209
1210     fat_rwlock_rdlock(&dp->cls.rwlock);
1211     netdev_flow = dp_netdev_find_flow(dp, &key);
1212     fat_rwlock_unlock(&dp->cls.rwlock);
1213
1214     if (netdev_flow) {
1215         if (stats) {
1216             get_dpif_flow_stats(netdev_flow, stats);
1217         }
1218
1219         if (actionsp) {
1220             struct dp_netdev_actions *actions;
1221
1222             actions = dp_netdev_flow_get_actions(netdev_flow);
1223             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1224         }
1225      } else {
1226         error = ENOENT;
1227     }
1228
1229     return error;
1230 }
1231
1232 static int
1233 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1234                    const struct flow_wildcards *wc,
1235                    const struct nlattr *actions,
1236                    size_t actions_len)
1237     OVS_REQUIRES(dp->flow_mutex)
1238 {
1239     struct dp_netdev_flow *netdev_flow;
1240     struct match match;
1241
1242     netdev_flow = xzalloc(sizeof *netdev_flow);
1243     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1244
1245     ovsthread_stats_init(&netdev_flow->stats);
1246
1247     ovsrcu_set(&netdev_flow->actions,
1248                dp_netdev_actions_create(actions, actions_len));
1249
1250     match_init(&match, flow, wc);
1251     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1252                   &match, NETDEV_RULE_PRIORITY);
1253     fat_rwlock_wrlock(&dp->cls.rwlock);
1254     classifier_insert(&dp->cls,
1255                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1256     hmap_insert(&dp->flow_table,
1257                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1258                 flow_hash(flow, 0));
1259     fat_rwlock_unlock(&dp->cls.rwlock);
1260
1261     return 0;
1262 }
1263
1264 static void
1265 clear_stats(struct dp_netdev_flow *netdev_flow)
1266 {
1267     struct dp_netdev_flow_stats *bucket;
1268     size_t i;
1269
1270     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1271         ovs_mutex_lock(&bucket->mutex);
1272         bucket->used = 0;
1273         bucket->packet_count = 0;
1274         bucket->byte_count = 0;
1275         bucket->tcp_flags = 0;
1276         ovs_mutex_unlock(&bucket->mutex);
1277     }
1278 }
1279
1280 static int
1281 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1282 {
1283     struct dp_netdev *dp = get_dp_netdev(dpif);
1284     struct dp_netdev_flow *netdev_flow;
1285     struct flow flow;
1286     struct miniflow miniflow;
1287     struct flow_wildcards wc;
1288     int error;
1289
1290     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1291     if (error) {
1292         return error;
1293     }
1294     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1295                                           put->mask, put->mask_len,
1296                                           &flow, &wc.masks);
1297     if (error) {
1298         return error;
1299     }
1300     miniflow_init(&miniflow, &flow);
1301
1302     ovs_mutex_lock(&dp->flow_mutex);
1303     netdev_flow = dp_netdev_lookup_flow(dp, &miniflow);
1304     if (!netdev_flow) {
1305         if (put->flags & DPIF_FP_CREATE) {
1306             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1307                 if (put->stats) {
1308                     memset(put->stats, 0, sizeof *put->stats);
1309                 }
1310                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1311                                            put->actions_len);
1312             } else {
1313                 error = EFBIG;
1314             }
1315         } else {
1316             error = ENOENT;
1317         }
1318     } else {
1319         if (put->flags & DPIF_FP_MODIFY
1320             && flow_equal(&flow, &netdev_flow->flow)) {
1321             struct dp_netdev_actions *new_actions;
1322             struct dp_netdev_actions *old_actions;
1323
1324             new_actions = dp_netdev_actions_create(put->actions,
1325                                                    put->actions_len);
1326
1327             old_actions = dp_netdev_flow_get_actions(netdev_flow);
1328             ovsrcu_set(&netdev_flow->actions, new_actions);
1329
1330             if (put->stats) {
1331                 get_dpif_flow_stats(netdev_flow, put->stats);
1332             }
1333             if (put->flags & DPIF_FP_ZERO_STATS) {
1334                 clear_stats(netdev_flow);
1335             }
1336
1337             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
1338         } else if (put->flags & DPIF_FP_CREATE) {
1339             error = EEXIST;
1340         } else {
1341             /* Overlapping flow. */
1342             error = EINVAL;
1343         }
1344     }
1345     ovs_mutex_unlock(&dp->flow_mutex);
1346
1347     return error;
1348 }
1349
1350 static int
1351 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1352 {
1353     struct dp_netdev *dp = get_dp_netdev(dpif);
1354     struct dp_netdev_flow *netdev_flow;
1355     struct flow key;
1356     int error;
1357
1358     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1359     if (error) {
1360         return error;
1361     }
1362
1363     ovs_mutex_lock(&dp->flow_mutex);
1364     fat_rwlock_wrlock(&dp->cls.rwlock);
1365     netdev_flow = dp_netdev_find_flow(dp, &key);
1366     if (netdev_flow) {
1367         if (del->stats) {
1368             get_dpif_flow_stats(netdev_flow, del->stats);
1369         }
1370         dp_netdev_remove_flow(dp, netdev_flow);
1371     } else {
1372         error = ENOENT;
1373     }
1374     fat_rwlock_unlock(&dp->cls.rwlock);
1375     ovs_mutex_unlock(&dp->flow_mutex);
1376
1377     return error;
1378 }
1379
1380 struct dpif_netdev_flow_dump {
1381     struct dpif_flow_dump up;
1382     uint32_t bucket;
1383     uint32_t offset;
1384     int status;
1385     struct ovs_mutex mutex;
1386 };
1387
1388 static struct dpif_netdev_flow_dump *
1389 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
1390 {
1391     return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
1392 }
1393
1394 static struct dpif_flow_dump *
1395 dpif_netdev_flow_dump_create(const struct dpif *dpif_)
1396 {
1397     struct dpif_netdev_flow_dump *dump;
1398
1399     dump = xmalloc(sizeof *dump);
1400     dpif_flow_dump_init(&dump->up, dpif_);
1401     dump->bucket = 0;
1402     dump->offset = 0;
1403     dump->status = 0;
1404     ovs_mutex_init(&dump->mutex);
1405
1406     return &dump->up;
1407 }
1408
1409 static int
1410 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
1411 {
1412     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1413
1414     ovs_mutex_destroy(&dump->mutex);
1415     free(dump);
1416     return 0;
1417 }
1418
1419 struct dpif_netdev_flow_dump_thread {
1420     struct dpif_flow_dump_thread up;
1421     struct dpif_netdev_flow_dump *dump;
1422     struct odputil_keybuf keybuf;
1423     struct odputil_keybuf maskbuf;
1424 };
1425
1426 static struct dpif_netdev_flow_dump_thread *
1427 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1428 {
1429     return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
1430 }
1431
1432 static struct dpif_flow_dump_thread *
1433 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1434 {
1435     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1436     struct dpif_netdev_flow_dump_thread *thread;
1437
1438     thread = xmalloc(sizeof *thread);
1439     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1440     thread->dump = dump;
1441     return &thread->up;
1442 }
1443
1444 static void
1445 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1446 {
1447     struct dpif_netdev_flow_dump_thread *thread
1448         = dpif_netdev_flow_dump_thread_cast(thread_);
1449
1450     free(thread);
1451 }
1452
1453 /* XXX the caller must use 'actions' without quiescing */
1454 static int
1455 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1456                            struct dpif_flow *f, int max_flows OVS_UNUSED)
1457 {
1458     struct dpif_netdev_flow_dump_thread *thread
1459         = dpif_netdev_flow_dump_thread_cast(thread_);
1460     struct dpif_netdev_flow_dump *dump = thread->dump;
1461     struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
1462     struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
1463     struct dp_netdev_flow *netdev_flow;
1464     struct flow_wildcards wc;
1465     struct dp_netdev_actions *dp_actions;
1466     struct ofpbuf buf;
1467     int error;
1468
1469     ovs_mutex_lock(&dump->mutex);
1470     error = dump->status;
1471     if (!error) {
1472         struct hmap_node *node;
1473
1474         fat_rwlock_rdlock(&dp->cls.rwlock);
1475         node = hmap_at_position(&dp->flow_table, &dump->bucket, &dump->offset);
1476         if (node) {
1477             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1478         }
1479         fat_rwlock_unlock(&dp->cls.rwlock);
1480         if (!node) {
1481             dump->status = error = EOF;
1482         }
1483     }
1484     ovs_mutex_unlock(&dump->mutex);
1485     if (error) {
1486         return 0;
1487     }
1488
1489     minimask_expand(&netdev_flow->cr.match.mask, &wc);
1490
1491     /* Key. */
1492     ofpbuf_use_stack(&buf, &thread->keybuf, sizeof thread->keybuf);
1493     odp_flow_key_from_flow(&buf, &netdev_flow->flow, &wc.masks,
1494                            netdev_flow->flow.in_port.odp_port, true);
1495     f->key = ofpbuf_data(&buf);
1496     f->key_len = ofpbuf_size(&buf);
1497
1498     /* Mask. */
1499     ofpbuf_use_stack(&buf, &thread->maskbuf, sizeof thread->maskbuf);
1500     odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1501                            odp_to_u32(wc.masks.in_port.odp_port),
1502                            SIZE_MAX, true);
1503     f->mask = ofpbuf_data(&buf);
1504     f->mask_len = ofpbuf_size(&buf);
1505
1506     /* Actions. */
1507     dp_actions = dp_netdev_flow_get_actions(netdev_flow);
1508     f->actions = dp_actions->actions;
1509     f->actions_len = dp_actions->size;
1510
1511     /* Stats. */
1512     get_dpif_flow_stats(netdev_flow, &f->stats);
1513
1514     return 1;
1515 }
1516
1517 static int
1518 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1519 {
1520     struct dp_netdev *dp = get_dp_netdev(dpif);
1521     struct pkt_metadata *md = &execute->md;
1522     struct {
1523         struct miniflow flow;
1524         uint32_t buf[FLOW_U32S];
1525     } key;
1526
1527     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
1528         ofpbuf_size(execute->packet) > UINT16_MAX) {
1529         return EINVAL;
1530     }
1531
1532     /* Extract flow key. */
1533     miniflow_initialize(&key.flow, key.buf);
1534     miniflow_extract(execute->packet, md, &key.flow);
1535
1536     dp_netdev_execute_actions(dp, &key.flow, execute->packet, false, md,
1537                               execute->actions, execute->actions_len);
1538
1539     return 0;
1540 }
1541
1542 static void
1543 dp_netdev_destroy_all_queues(struct dp_netdev *dp)
1544     OVS_REQ_WRLOCK(dp->queue_rwlock)
1545 {
1546     size_t i;
1547
1548     dp_netdev_purge_queues(dp);
1549
1550     for (i = 0; i < dp->n_handlers; i++) {
1551         struct dp_netdev_queue *q = &dp->handler_queues[i];
1552
1553         ovs_mutex_destroy(&q->mutex);
1554         seq_destroy(q->seq);
1555     }
1556     free(dp->handler_queues);
1557     dp->handler_queues = NULL;
1558     dp->n_handlers = 0;
1559 }
1560
1561 static void
1562 dp_netdev_refresh_queues(struct dp_netdev *dp, uint32_t n_handlers)
1563     OVS_REQ_WRLOCK(dp->queue_rwlock)
1564 {
1565     if (dp->n_handlers != n_handlers) {
1566         size_t i;
1567
1568         dp_netdev_destroy_all_queues(dp);
1569
1570         dp->n_handlers = n_handlers;
1571         dp->handler_queues = xzalloc(n_handlers * sizeof *dp->handler_queues);
1572
1573         for (i = 0; i < n_handlers; i++) {
1574             struct dp_netdev_queue *q = &dp->handler_queues[i];
1575
1576             ovs_mutex_init(&q->mutex);
1577             q->seq = seq_create();
1578         }
1579     }
1580 }
1581
1582 static int
1583 dpif_netdev_recv_set(struct dpif *dpif, bool enable)
1584 {
1585     struct dp_netdev *dp = get_dp_netdev(dpif);
1586
1587     if ((dp->handler_queues != NULL) == enable) {
1588         return 0;
1589     }
1590
1591     fat_rwlock_wrlock(&dp->queue_rwlock);
1592     if (!enable) {
1593         dp_netdev_destroy_all_queues(dp);
1594     } else {
1595         dp_netdev_refresh_queues(dp, 1);
1596     }
1597     fat_rwlock_unlock(&dp->queue_rwlock);
1598
1599     return 0;
1600 }
1601
1602 static int
1603 dpif_netdev_handlers_set(struct dpif *dpif, uint32_t n_handlers)
1604 {
1605     struct dp_netdev *dp = get_dp_netdev(dpif);
1606
1607     fat_rwlock_wrlock(&dp->queue_rwlock);
1608     if (dp->handler_queues) {
1609         dp_netdev_refresh_queues(dp, n_handlers);
1610     }
1611     fat_rwlock_unlock(&dp->queue_rwlock);
1612
1613     return 0;
1614 }
1615
1616 static int
1617 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1618                               uint32_t queue_id, uint32_t *priority)
1619 {
1620     *priority = queue_id;
1621     return 0;
1622 }
1623
1624 static bool
1625 dp_netdev_recv_check(const struct dp_netdev *dp, const uint32_t handler_id)
1626     OVS_REQ_RDLOCK(dp->queue_rwlock)
1627 {
1628     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1629
1630     if (!dp->handler_queues) {
1631         VLOG_WARN_RL(&rl, "receiving upcall disabled");
1632         return false;
1633     }
1634
1635     if (handler_id >= dp->n_handlers) {
1636         VLOG_WARN_RL(&rl, "handler index out of bound");
1637         return false;
1638     }
1639
1640     return true;
1641 }
1642
1643 static int
1644 dpif_netdev_recv(struct dpif *dpif, uint32_t handler_id,
1645                  struct dpif_upcall *upcall, struct ofpbuf *buf)
1646 {
1647     struct dp_netdev *dp = get_dp_netdev(dpif);
1648     struct dp_netdev_queue *q;
1649     int error = 0;
1650
1651     fat_rwlock_rdlock(&dp->queue_rwlock);
1652
1653     if (!dp_netdev_recv_check(dp, handler_id)) {
1654         error = EAGAIN;
1655         goto out;
1656     }
1657
1658     q = &dp->handler_queues[handler_id];
1659     ovs_mutex_lock(&q->mutex);
1660     if (q->head != q->tail) {
1661         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1662
1663         *upcall = u->upcall;
1664
1665         ofpbuf_uninit(buf);
1666         *buf = u->buf;
1667     } else {
1668         error = EAGAIN;
1669     }
1670     ovs_mutex_unlock(&q->mutex);
1671
1672 out:
1673     fat_rwlock_unlock(&dp->queue_rwlock);
1674
1675     return error;
1676 }
1677
1678 static void
1679 dpif_netdev_recv_wait(struct dpif *dpif, uint32_t handler_id)
1680 {
1681     struct dp_netdev *dp = get_dp_netdev(dpif);
1682     struct dp_netdev_queue *q;
1683     uint64_t seq;
1684
1685     fat_rwlock_rdlock(&dp->queue_rwlock);
1686
1687     if (!dp_netdev_recv_check(dp, handler_id)) {
1688         goto out;
1689     }
1690
1691     q = &dp->handler_queues[handler_id];
1692     ovs_mutex_lock(&q->mutex);
1693     seq = seq_read(q->seq);
1694     if (q->head != q->tail) {
1695         poll_immediate_wake();
1696     } else {
1697         seq_wait(q->seq, seq);
1698     }
1699
1700     ovs_mutex_unlock(&q->mutex);
1701
1702 out:
1703     fat_rwlock_unlock(&dp->queue_rwlock);
1704 }
1705
1706 static void
1707 dpif_netdev_recv_purge(struct dpif *dpif)
1708 {
1709     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1710
1711     fat_rwlock_wrlock(&dpif_netdev->dp->queue_rwlock);
1712     dp_netdev_purge_queues(dpif_netdev->dp);
1713     fat_rwlock_unlock(&dpif_netdev->dp->queue_rwlock);
1714 }
1715 \f
1716 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1717  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1718  * 'ofpacts'. */
1719 struct dp_netdev_actions *
1720 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1721 {
1722     struct dp_netdev_actions *netdev_actions;
1723
1724     netdev_actions = xmalloc(sizeof *netdev_actions);
1725     netdev_actions->actions = xmemdup(actions, size);
1726     netdev_actions->size = size;
1727
1728     return netdev_actions;
1729 }
1730
1731 struct dp_netdev_actions *
1732 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
1733 {
1734     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
1735 }
1736
1737 static void
1738 dp_netdev_actions_free(struct dp_netdev_actions *actions)
1739 {
1740     free(actions->actions);
1741     free(actions);
1742 }
1743 \f
1744
1745 static void
1746 dp_netdev_process_rxq_port(struct dp_netdev *dp,
1747                           struct dp_netdev_port *port,
1748                           struct netdev_rxq *rxq)
1749 {
1750     struct ofpbuf *packet[NETDEV_MAX_RX_BATCH];
1751     int error, c;
1752
1753     error = netdev_rxq_recv(rxq, packet, &c);
1754     if (!error) {
1755         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
1756         int i;
1757
1758         for (i = 0; i < c; i++) {
1759             dp_netdev_port_input(dp, packet[i], &md);
1760         }
1761     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1762         static struct vlog_rate_limit rl
1763             = VLOG_RATE_LIMIT_INIT(1, 5);
1764
1765         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1766                     netdev_get_name(port->netdev),
1767                     ovs_strerror(error));
1768     }
1769 }
1770
1771 static void
1772 dpif_netdev_run(struct dpif *dpif)
1773 {
1774     struct dp_netdev_port *port;
1775     struct dp_netdev *dp = get_dp_netdev(dpif);
1776     struct cmap_cursor cursor;
1777
1778     CMAP_FOR_EACH (port, node, &cursor, &dp->ports) {
1779         if (!netdev_is_pmd(port->netdev)) {
1780             int i;
1781
1782             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1783                 dp_netdev_process_rxq_port(dp, port, port->rxq[i]);
1784             }
1785         }
1786     }
1787 }
1788
1789 static void
1790 dpif_netdev_wait(struct dpif *dpif)
1791 {
1792     struct dp_netdev_port *port;
1793     struct dp_netdev *dp = get_dp_netdev(dpif);
1794     struct cmap_cursor cursor;
1795
1796     ovs_mutex_lock(&dp_netdev_mutex);
1797     CMAP_FOR_EACH (port, node, &cursor, &dp->ports) {
1798         if (!netdev_is_pmd(port->netdev)) {
1799             int i;
1800
1801             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1802                 netdev_rxq_wait(port->rxq[i]);
1803             }
1804         }
1805     }
1806     ovs_mutex_unlock(&dp_netdev_mutex);
1807 }
1808
1809 struct rxq_poll {
1810     struct dp_netdev_port *port;
1811     struct netdev_rxq *rx;
1812 };
1813
1814 static int
1815 pmd_load_queues(struct pmd_thread *f,
1816                 struct rxq_poll **ppoll_list, int poll_cnt)
1817 {
1818     struct dp_netdev *dp = f->dp;
1819     struct rxq_poll *poll_list = *ppoll_list;
1820     struct dp_netdev_port *port;
1821     struct cmap_cursor cursor;
1822     int id = f->id;
1823     int index;
1824     int i;
1825
1826     /* Simple scheduler for netdev rx polling. */
1827     for (i = 0; i < poll_cnt; i++) {
1828          port_unref(poll_list[i].port);
1829     }
1830
1831     poll_cnt = 0;
1832     index = 0;
1833
1834     CMAP_FOR_EACH (port, node, &cursor, &f->dp->ports) {
1835         if (netdev_is_pmd(port->netdev)) {
1836             int i;
1837
1838             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1839                 if ((index % dp->n_pmd_threads) == id) {
1840                     poll_list = xrealloc(poll_list, sizeof *poll_list * (poll_cnt + 1));
1841
1842                     port_ref(port);
1843                     poll_list[poll_cnt].port = port;
1844                     poll_list[poll_cnt].rx = port->rxq[i];
1845                     poll_cnt++;
1846                 }
1847                 index++;
1848             }
1849         }
1850     }
1851
1852     *ppoll_list = poll_list;
1853     return poll_cnt;
1854 }
1855
1856 static void *
1857 pmd_thread_main(void *f_)
1858 {
1859     struct pmd_thread *f = f_;
1860     struct dp_netdev *dp = f->dp;
1861     unsigned int lc = 0;
1862     struct rxq_poll *poll_list;
1863     unsigned int port_seq;
1864     int poll_cnt;
1865     int i;
1866
1867     poll_cnt = 0;
1868     poll_list = NULL;
1869
1870     pmd_thread_setaffinity_cpu(f->id);
1871 reload:
1872     poll_cnt = pmd_load_queues(f, &poll_list, poll_cnt);
1873     atomic_read(&f->change_seq, &port_seq);
1874
1875     for (;;) {
1876         unsigned int c_port_seq;
1877         int i;
1878
1879         for (i = 0; i < poll_cnt; i++) {
1880             dp_netdev_process_rxq_port(dp,  poll_list[i].port, poll_list[i].rx);
1881         }
1882
1883         if (lc++ > 1024) {
1884             ovsrcu_quiesce();
1885
1886             /* TODO: need completely userspace based signaling method.
1887              * to keep this thread entirely in userspace.
1888              * For now using atomic counter. */
1889             lc = 0;
1890             atomic_read_explicit(&f->change_seq, &c_port_seq, memory_order_consume);
1891             if (c_port_seq != port_seq) {
1892                 break;
1893             }
1894         }
1895     }
1896
1897     if (!latch_is_set(&f->dp->exit_latch)){
1898         goto reload;
1899     }
1900
1901     for (i = 0; i < poll_cnt; i++) {
1902          port_unref(poll_list[i].port);
1903     }
1904
1905     free(poll_list);
1906     return NULL;
1907 }
1908
1909 static void
1910 dp_netdev_set_pmd_threads(struct dp_netdev *dp, int n)
1911 {
1912     int i;
1913
1914     if (n == dp->n_pmd_threads) {
1915         return;
1916     }
1917
1918     /* Stop existing threads. */
1919     latch_set(&dp->exit_latch);
1920     dp_netdev_reload_pmd_threads(dp);
1921     for (i = 0; i < dp->n_pmd_threads; i++) {
1922         struct pmd_thread *f = &dp->pmd_threads[i];
1923
1924         xpthread_join(f->thread, NULL);
1925     }
1926     latch_poll(&dp->exit_latch);
1927     free(dp->pmd_threads);
1928
1929     /* Start new threads. */
1930     dp->pmd_threads = xmalloc(n * sizeof *dp->pmd_threads);
1931     dp->n_pmd_threads = n;
1932
1933     for (i = 0; i < n; i++) {
1934         struct pmd_thread *f = &dp->pmd_threads[i];
1935
1936         f->dp = dp;
1937         f->id = i;
1938         atomic_store(&f->change_seq, 1);
1939
1940         /* Each thread will distribute all devices rx-queues among
1941          * themselves. */
1942         f->thread = ovs_thread_create("pmd", pmd_thread_main, f);
1943     }
1944 }
1945
1946 \f
1947 static void *
1948 dp_netdev_flow_stats_new_cb(void)
1949 {
1950     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1951     ovs_mutex_init(&bucket->mutex);
1952     return bucket;
1953 }
1954
1955 static void
1956 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1957                     const struct ofpbuf *packet,
1958                     const struct miniflow *key)
1959 {
1960     uint16_t tcp_flags = miniflow_get_tcp_flags(key);
1961     long long int now = time_msec();
1962     struct dp_netdev_flow_stats *bucket;
1963
1964     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
1965                                         dp_netdev_flow_stats_new_cb);
1966
1967     ovs_mutex_lock(&bucket->mutex);
1968     bucket->used = MAX(now, bucket->used);
1969     bucket->packet_count++;
1970     bucket->byte_count += ofpbuf_size(packet);
1971     bucket->tcp_flags |= tcp_flags;
1972     ovs_mutex_unlock(&bucket->mutex);
1973 }
1974
1975 static void *
1976 dp_netdev_stats_new_cb(void)
1977 {
1978     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1979     ovs_mutex_init(&bucket->mutex);
1980     return bucket;
1981 }
1982
1983 static void
1984 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type)
1985 {
1986     struct dp_netdev_stats *bucket;
1987
1988     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
1989     ovs_mutex_lock(&bucket->mutex);
1990     bucket->n[type]++;
1991     ovs_mutex_unlock(&bucket->mutex);
1992 }
1993
1994 static void
1995 dp_netdev_input(struct dp_netdev *dp, struct ofpbuf *packet,
1996                 struct pkt_metadata *md)
1997 {
1998     struct dp_netdev_flow *netdev_flow;
1999     struct {
2000         struct miniflow flow;
2001         uint32_t buf[FLOW_U32S];
2002     } key;
2003
2004     if (ofpbuf_size(packet) < ETH_HEADER_LEN) {
2005         ofpbuf_delete(packet);
2006         return;
2007     }
2008     miniflow_initialize(&key.flow, key.buf);
2009     miniflow_extract(packet, md, &key.flow);
2010
2011     netdev_flow = dp_netdev_lookup_flow(dp, &key.flow);
2012     if (netdev_flow) {
2013         struct dp_netdev_actions *actions;
2014
2015         dp_netdev_flow_used(netdev_flow, packet, &key.flow);
2016
2017         actions = dp_netdev_flow_get_actions(netdev_flow);
2018         dp_netdev_execute_actions(dp, &key.flow, packet, true, md,
2019                                   actions->actions, actions->size);
2020         dp_netdev_count_packet(dp, DP_STAT_HIT);
2021     } else if (dp->handler_queues) {
2022         dp_netdev_count_packet(dp, DP_STAT_MISS);
2023         dp_netdev_output_userspace(dp, packet,
2024                                    miniflow_hash_5tuple(&key.flow, 0)
2025                                    % dp->n_handlers,
2026                                    DPIF_UC_MISS, &key.flow, NULL);
2027         ofpbuf_delete(packet);
2028     }
2029 }
2030
2031 static void
2032 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
2033                      struct pkt_metadata *md)
2034 {
2035     uint32_t *recirc_depth = recirc_depth_get();
2036
2037     *recirc_depth = 0;
2038     dp_netdev_input(dp, packet, md);
2039 }
2040
2041 static int
2042 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
2043                            int queue_no, int type, const struct miniflow *key,
2044                            const struct nlattr *userdata)
2045 {
2046     struct dp_netdev_queue *q;
2047     int error;
2048
2049     fat_rwlock_rdlock(&dp->queue_rwlock);
2050     q = &dp->handler_queues[queue_no];
2051     ovs_mutex_lock(&q->mutex);
2052     if (q->head - q->tail < MAX_QUEUE_LEN) {
2053         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
2054         struct dpif_upcall *upcall = &u->upcall;
2055         struct ofpbuf *buf = &u->buf;
2056         size_t buf_size;
2057         struct flow flow;
2058
2059         upcall->type = type;
2060
2061         /* Allocate buffer big enough for everything. */
2062         buf_size = ODPUTIL_FLOW_KEY_BYTES;
2063         if (userdata) {
2064             buf_size += NLA_ALIGN(userdata->nla_len);
2065         }
2066         buf_size += ofpbuf_size(packet);
2067         ofpbuf_init(buf, buf_size);
2068
2069         /* Put ODP flow. */
2070         miniflow_expand(key, &flow);
2071         odp_flow_key_from_flow(buf, &flow, NULL, flow.in_port.odp_port, true);
2072         upcall->key = ofpbuf_data(buf);
2073         upcall->key_len = ofpbuf_size(buf);
2074
2075         /* Put userdata. */
2076         if (userdata) {
2077             upcall->userdata = ofpbuf_put(buf, userdata,
2078                                           NLA_ALIGN(userdata->nla_len));
2079         }
2080
2081         ofpbuf_set_data(&upcall->packet,
2082                         ofpbuf_put(buf, ofpbuf_data(packet), ofpbuf_size(packet)));
2083         ofpbuf_set_size(&upcall->packet, ofpbuf_size(packet));
2084
2085         seq_change(q->seq);
2086
2087         error = 0;
2088     } else {
2089         dp_netdev_count_packet(dp, DP_STAT_LOST);
2090         error = ENOBUFS;
2091     }
2092     ovs_mutex_unlock(&q->mutex);
2093     fat_rwlock_unlock(&dp->queue_rwlock);
2094
2095     return error;
2096 }
2097
2098 struct dp_netdev_execute_aux {
2099     struct dp_netdev *dp;
2100     const struct miniflow *key;
2101 };
2102
2103 static void
2104 dp_execute_cb(void *aux_, struct ofpbuf *packet,
2105               struct pkt_metadata *md,
2106               const struct nlattr *a, bool may_steal)
2107     OVS_NO_THREAD_SAFETY_ANALYSIS
2108 {
2109     struct dp_netdev_execute_aux *aux = aux_;
2110     int type = nl_attr_type(a);
2111     struct dp_netdev_port *p;
2112     uint32_t *depth = recirc_depth_get();
2113
2114     switch ((enum ovs_action_attr)type) {
2115     case OVS_ACTION_ATTR_OUTPUT:
2116         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
2117         if (p) {
2118             netdev_send(p->netdev, packet, may_steal);
2119         }
2120         break;
2121
2122     case OVS_ACTION_ATTR_USERSPACE: {
2123         const struct nlattr *userdata;
2124
2125         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2126
2127         dp_netdev_output_userspace(aux->dp, packet,
2128                                    miniflow_hash_5tuple(aux->key, 0)
2129                                        % aux->dp->n_handlers,
2130                                    DPIF_UC_ACTION, aux->key,
2131                                    userdata);
2132
2133         if (may_steal) {
2134             ofpbuf_delete(packet);
2135         }
2136         break;
2137     }
2138
2139     case OVS_ACTION_ATTR_HASH: {
2140         const struct ovs_action_hash *hash_act;
2141         uint32_t hash;
2142
2143         hash_act = nl_attr_get(a);
2144         if (hash_act->hash_alg == OVS_HASH_ALG_L4) {
2145             /* Hash need not be symmetric, nor does it need to include
2146              * L2 fields. */
2147             hash = miniflow_hash_5tuple(aux->key, hash_act->hash_basis);
2148             if (!hash) {
2149                 hash = 1; /* 0 is not valid */
2150             }
2151
2152         } else {
2153             VLOG_WARN("Unknown hash algorithm specified for the hash action.");
2154             hash = 2;
2155         }
2156
2157         md->dp_hash = hash;
2158         break;
2159     }
2160
2161     case OVS_ACTION_ATTR_RECIRC:
2162         if (*depth < MAX_RECIRC_DEPTH) {
2163             struct pkt_metadata recirc_md = *md;
2164             struct ofpbuf *recirc_packet;
2165
2166             recirc_packet = may_steal ? packet : ofpbuf_clone(packet);
2167             recirc_md.recirc_id = nl_attr_get_u32(a);
2168
2169             (*depth)++;
2170             dp_netdev_input(aux->dp, recirc_packet, &recirc_md);
2171             (*depth)--;
2172
2173             break;
2174         } else {
2175             VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2176         }
2177         break;
2178
2179     case OVS_ACTION_ATTR_PUSH_VLAN:
2180     case OVS_ACTION_ATTR_POP_VLAN:
2181     case OVS_ACTION_ATTR_PUSH_MPLS:
2182     case OVS_ACTION_ATTR_POP_MPLS:
2183     case OVS_ACTION_ATTR_SET:
2184     case OVS_ACTION_ATTR_SAMPLE:
2185     case OVS_ACTION_ATTR_UNSPEC:
2186     case __OVS_ACTION_ATTR_MAX:
2187         OVS_NOT_REACHED();
2188     }
2189 }
2190
2191 static void
2192 dp_netdev_execute_actions(struct dp_netdev *dp, const struct miniflow *key,
2193                           struct ofpbuf *packet, bool may_steal,
2194                           struct pkt_metadata *md,
2195                           const struct nlattr *actions, size_t actions_len)
2196 {
2197     struct dp_netdev_execute_aux aux = {dp, key};
2198
2199     odp_execute_actions(&aux, packet, may_steal, md,
2200                         actions, actions_len, dp_execute_cb);
2201 }
2202
2203 const struct dpif_class dpif_netdev_class = {
2204     "netdev",
2205     dpif_netdev_enumerate,
2206     dpif_netdev_port_open_type,
2207     dpif_netdev_open,
2208     dpif_netdev_close,
2209     dpif_netdev_destroy,
2210     dpif_netdev_run,
2211     dpif_netdev_wait,
2212     dpif_netdev_get_stats,
2213     dpif_netdev_port_add,
2214     dpif_netdev_port_del,
2215     dpif_netdev_port_query_by_number,
2216     dpif_netdev_port_query_by_name,
2217     NULL,                       /* port_get_pid */
2218     dpif_netdev_port_dump_start,
2219     dpif_netdev_port_dump_next,
2220     dpif_netdev_port_dump_done,
2221     dpif_netdev_port_poll,
2222     dpif_netdev_port_poll_wait,
2223     dpif_netdev_flow_get,
2224     dpif_netdev_flow_put,
2225     dpif_netdev_flow_del,
2226     dpif_netdev_flow_flush,
2227     dpif_netdev_flow_dump_create,
2228     dpif_netdev_flow_dump_destroy,
2229     dpif_netdev_flow_dump_thread_create,
2230     dpif_netdev_flow_dump_thread_destroy,
2231     dpif_netdev_flow_dump_next,
2232     dpif_netdev_execute,
2233     NULL,                       /* operate */
2234     dpif_netdev_recv_set,
2235     dpif_netdev_handlers_set,
2236     dpif_netdev_queue_to_priority,
2237     dpif_netdev_recv,
2238     dpif_netdev_recv_wait,
2239     dpif_netdev_recv_purge,
2240 };
2241
2242 static void
2243 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2244                               const char *argv[], void *aux OVS_UNUSED)
2245 {
2246     struct dp_netdev_port *old_port;
2247     struct dp_netdev_port *new_port;
2248     struct dp_netdev *dp;
2249     odp_port_t port_no;
2250
2251     ovs_mutex_lock(&dp_netdev_mutex);
2252     dp = shash_find_data(&dp_netdevs, argv[1]);
2253     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2254         ovs_mutex_unlock(&dp_netdev_mutex);
2255         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2256         return;
2257     }
2258     ovs_refcount_ref(&dp->ref_cnt);
2259     ovs_mutex_unlock(&dp_netdev_mutex);
2260
2261     ovs_mutex_lock(&dp->port_mutex);
2262     if (get_port_by_name(dp, argv[2], &old_port)) {
2263         unixctl_command_reply_error(conn, "unknown port");
2264         goto exit;
2265     }
2266
2267     port_no = u32_to_odp(atoi(argv[3]));
2268     if (!port_no || port_no == ODPP_NONE) {
2269         unixctl_command_reply_error(conn, "bad port number");
2270         goto exit;
2271     }
2272     if (dp_netdev_lookup_port(dp, port_no)) {
2273         unixctl_command_reply_error(conn, "port number already in use");
2274         goto exit;
2275     }
2276
2277     /* Remove old port. */
2278     cmap_remove(&dp->ports, &old_port->node, hash_port_no(old_port->port_no));
2279     ovsrcu_postpone(free, old_port);
2280
2281     /* Insert new port (cmap semantics mean we cannot re-insert 'old_port'). */
2282     new_port = xmemdup(old_port, sizeof *old_port);
2283     new_port->port_no = port_no;
2284     cmap_insert(&dp->ports, &new_port->node, hash_port_no(port_no));
2285
2286     seq_change(dp->port_seq);
2287     unixctl_command_reply(conn, NULL);
2288
2289 exit:
2290     ovs_mutex_unlock(&dp->port_mutex);
2291     dp_netdev_unref(dp);
2292 }
2293
2294 static void
2295 dpif_dummy_delete_port(struct unixctl_conn *conn, int argc OVS_UNUSED,
2296                        const char *argv[], void *aux OVS_UNUSED)
2297 {
2298     struct dp_netdev_port *port;
2299     struct dp_netdev *dp;
2300
2301     ovs_mutex_lock(&dp_netdev_mutex);
2302     dp = shash_find_data(&dp_netdevs, argv[1]);
2303     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2304         ovs_mutex_unlock(&dp_netdev_mutex);
2305         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2306         return;
2307     }
2308     ovs_refcount_ref(&dp->ref_cnt);
2309     ovs_mutex_unlock(&dp_netdev_mutex);
2310
2311     ovs_mutex_lock(&dp->port_mutex);
2312     if (get_port_by_name(dp, argv[2], &port)) {
2313         unixctl_command_reply_error(conn, "unknown port");
2314     } else if (port->port_no == ODPP_LOCAL) {
2315         unixctl_command_reply_error(conn, "can't delete local port");
2316     } else {
2317         do_del_port(dp, port);
2318         unixctl_command_reply(conn, NULL);
2319     }
2320     ovs_mutex_unlock(&dp->port_mutex);
2321
2322     dp_netdev_unref(dp);
2323 }
2324
2325 static void
2326 dpif_dummy_register__(const char *type)
2327 {
2328     struct dpif_class *class;
2329
2330     class = xmalloc(sizeof *class);
2331     *class = dpif_netdev_class;
2332     class->type = xstrdup(type);
2333     dp_register_provider(class);
2334 }
2335
2336 void
2337 dpif_dummy_register(bool override)
2338 {
2339     if (override) {
2340         struct sset types;
2341         const char *type;
2342
2343         sset_init(&types);
2344         dp_enumerate_types(&types);
2345         SSET_FOR_EACH (type, &types) {
2346             if (!dp_unregister_provider(type)) {
2347                 dpif_dummy_register__(type);
2348             }
2349         }
2350         sset_destroy(&types);
2351     }
2352
2353     dpif_dummy_register__("dummy");
2354
2355     unixctl_command_register("dpif-dummy/change-port-number",
2356                              "DP PORT NEW-NUMBER",
2357                              3, 3, dpif_dummy_change_port_number, NULL);
2358     unixctl_command_register("dpif-dummy/delete-port", "DP PORT",
2359                              2, 2, dpif_dummy_delete_port, NULL);
2360 }