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