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