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