lib/flow: Maintain miniflow offline values explicitly.
[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 {
1531         struct miniflow flow;
1532         uint32_t buf[FLOW_U32S];
1533     } key;
1534
1535     if (ofpbuf_size(execute->packet) < ETH_HEADER_LEN ||
1536         ofpbuf_size(execute->packet) > UINT16_MAX) {
1537         return EINVAL;
1538     }
1539
1540     /* Extract flow key. */
1541     miniflow_initialize(&key.flow, key.buf);
1542     miniflow_extract(execute->packet, md, &key.flow);
1543
1544     ovs_rwlock_rdlock(&dp->port_rwlock);
1545     dp_netdev_execute_actions(dp, &key.flow, execute->packet, false, md,
1546                               execute->actions, execute->actions_len);
1547     ovs_rwlock_unlock(&dp->port_rwlock);
1548
1549     return 0;
1550 }
1551
1552 static void
1553 dp_netdev_destroy_all_queues(struct dp_netdev *dp)
1554     OVS_REQ_WRLOCK(dp->queue_rwlock)
1555 {
1556     size_t i;
1557
1558     dp_netdev_purge_queues(dp);
1559
1560     for (i = 0; i < dp->n_handlers; i++) {
1561         struct dp_netdev_queue *q = &dp->handler_queues[i];
1562
1563         ovs_mutex_destroy(&q->mutex);
1564         seq_destroy(q->seq);
1565     }
1566     free(dp->handler_queues);
1567     dp->handler_queues = NULL;
1568     dp->n_handlers = 0;
1569 }
1570
1571 static void
1572 dp_netdev_refresh_queues(struct dp_netdev *dp, uint32_t n_handlers)
1573     OVS_REQ_WRLOCK(dp->queue_rwlock)
1574 {
1575     if (dp->n_handlers != n_handlers) {
1576         size_t i;
1577
1578         dp_netdev_destroy_all_queues(dp);
1579
1580         dp->n_handlers = n_handlers;
1581         dp->handler_queues = xzalloc(n_handlers * sizeof *dp->handler_queues);
1582
1583         for (i = 0; i < n_handlers; i++) {
1584             struct dp_netdev_queue *q = &dp->handler_queues[i];
1585
1586             ovs_mutex_init(&q->mutex);
1587             q->seq = seq_create();
1588         }
1589     }
1590 }
1591
1592 static int
1593 dpif_netdev_recv_set(struct dpif *dpif, bool enable)
1594 {
1595     struct dp_netdev *dp = get_dp_netdev(dpif);
1596
1597     if ((dp->handler_queues != NULL) == enable) {
1598         return 0;
1599     }
1600
1601     fat_rwlock_wrlock(&dp->queue_rwlock);
1602     if (!enable) {
1603         dp_netdev_destroy_all_queues(dp);
1604     } else {
1605         dp_netdev_refresh_queues(dp, 1);
1606     }
1607     fat_rwlock_unlock(&dp->queue_rwlock);
1608
1609     return 0;
1610 }
1611
1612 static int
1613 dpif_netdev_handlers_set(struct dpif *dpif, uint32_t n_handlers)
1614 {
1615     struct dp_netdev *dp = get_dp_netdev(dpif);
1616
1617     fat_rwlock_wrlock(&dp->queue_rwlock);
1618     if (dp->handler_queues) {
1619         dp_netdev_refresh_queues(dp, n_handlers);
1620     }
1621     fat_rwlock_unlock(&dp->queue_rwlock);
1622
1623     return 0;
1624 }
1625
1626 static int
1627 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1628                               uint32_t queue_id, uint32_t *priority)
1629 {
1630     *priority = queue_id;
1631     return 0;
1632 }
1633
1634 static bool
1635 dp_netdev_recv_check(const struct dp_netdev *dp, const uint32_t handler_id)
1636     OVS_REQ_RDLOCK(dp->queue_rwlock)
1637 {
1638     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1639
1640     if (!dp->handler_queues) {
1641         VLOG_WARN_RL(&rl, "receiving upcall disabled");
1642         return false;
1643     }
1644
1645     if (handler_id >= dp->n_handlers) {
1646         VLOG_WARN_RL(&rl, "handler index out of bound");
1647         return false;
1648     }
1649
1650     return true;
1651 }
1652
1653 static int
1654 dpif_netdev_recv(struct dpif *dpif, uint32_t handler_id,
1655                  struct dpif_upcall *upcall, struct ofpbuf *buf)
1656 {
1657     struct dp_netdev *dp = get_dp_netdev(dpif);
1658     struct dp_netdev_queue *q;
1659     int error = 0;
1660
1661     fat_rwlock_rdlock(&dp->queue_rwlock);
1662
1663     if (!dp_netdev_recv_check(dp, handler_id)) {
1664         error = EAGAIN;
1665         goto out;
1666     }
1667
1668     q = &dp->handler_queues[handler_id];
1669     ovs_mutex_lock(&q->mutex);
1670     if (q->head != q->tail) {
1671         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1672
1673         *upcall = u->upcall;
1674
1675         ofpbuf_uninit(buf);
1676         *buf = u->buf;
1677     } else {
1678         error = EAGAIN;
1679     }
1680     ovs_mutex_unlock(&q->mutex);
1681
1682 out:
1683     fat_rwlock_unlock(&dp->queue_rwlock);
1684
1685     return error;
1686 }
1687
1688 static void
1689 dpif_netdev_recv_wait(struct dpif *dpif, uint32_t handler_id)
1690 {
1691     struct dp_netdev *dp = get_dp_netdev(dpif);
1692     struct dp_netdev_queue *q;
1693     uint64_t seq;
1694
1695     fat_rwlock_rdlock(&dp->queue_rwlock);
1696
1697     if (!dp_netdev_recv_check(dp, handler_id)) {
1698         goto out;
1699     }
1700
1701     q = &dp->handler_queues[handler_id];
1702     ovs_mutex_lock(&q->mutex);
1703     seq = seq_read(q->seq);
1704     if (q->head != q->tail) {
1705         poll_immediate_wake();
1706     } else {
1707         seq_wait(q->seq, seq);
1708     }
1709
1710     ovs_mutex_unlock(&q->mutex);
1711
1712 out:
1713     fat_rwlock_unlock(&dp->queue_rwlock);
1714 }
1715
1716 static void
1717 dpif_netdev_recv_purge(struct dpif *dpif)
1718 {
1719     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1720
1721     fat_rwlock_wrlock(&dpif_netdev->dp->queue_rwlock);
1722     dp_netdev_purge_queues(dpif_netdev->dp);
1723     fat_rwlock_unlock(&dpif_netdev->dp->queue_rwlock);
1724 }
1725 \f
1726 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1727  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1728  * 'ofpacts'. */
1729 struct dp_netdev_actions *
1730 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1731 {
1732     struct dp_netdev_actions *netdev_actions;
1733
1734     netdev_actions = xmalloc(sizeof *netdev_actions);
1735     netdev_actions->actions = xmemdup(actions, size);
1736     netdev_actions->size = size;
1737
1738     return netdev_actions;
1739 }
1740
1741 struct dp_netdev_actions *
1742 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
1743 {
1744     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
1745 }
1746
1747 static void
1748 dp_netdev_actions_free(struct dp_netdev_actions *actions)
1749 {
1750     free(actions->actions);
1751     free(actions);
1752 }
1753 \f
1754
1755 static void
1756 dp_netdev_process_rxq_port(struct dp_netdev *dp,
1757                           struct dp_netdev_port *port,
1758                           struct netdev_rxq *rxq)
1759 {
1760     struct ofpbuf *packet[NETDEV_MAX_RX_BATCH];
1761     int error, c;
1762
1763     error = netdev_rxq_recv(rxq, packet, &c);
1764     if (!error) {
1765         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
1766         int i;
1767
1768         for (i = 0; i < c; i++) {
1769             dp_netdev_port_input(dp, packet[i], &md);
1770         }
1771     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1772         static struct vlog_rate_limit rl
1773             = VLOG_RATE_LIMIT_INIT(1, 5);
1774
1775         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1776                     netdev_get_name(port->netdev),
1777                     ovs_strerror(error));
1778     }
1779 }
1780
1781 static void
1782 dpif_netdev_run(struct dpif *dpif)
1783 {
1784     struct dp_netdev_port *port;
1785     struct dp_netdev *dp = get_dp_netdev(dpif);
1786
1787     ovs_rwlock_rdlock(&dp->port_rwlock);
1788
1789     HMAP_FOR_EACH (port, node, &dp->ports) {
1790         if (!netdev_is_pmd(port->netdev)) {
1791             int i;
1792
1793             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1794                 dp_netdev_process_rxq_port(dp, port, port->rxq[i]);
1795             }
1796         }
1797     }
1798
1799     ovs_rwlock_unlock(&dp->port_rwlock);
1800 }
1801
1802 static void
1803 dpif_netdev_wait(struct dpif *dpif)
1804 {
1805     struct dp_netdev_port *port;
1806     struct dp_netdev *dp = get_dp_netdev(dpif);
1807
1808     ovs_rwlock_rdlock(&dp->port_rwlock);
1809
1810     HMAP_FOR_EACH (port, node, &dp->ports) {
1811         if (!netdev_is_pmd(port->netdev)) {
1812             int i;
1813
1814             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1815                 netdev_rxq_wait(port->rxq[i]);
1816             }
1817         }
1818     }
1819     ovs_rwlock_unlock(&dp->port_rwlock);
1820 }
1821
1822 struct rxq_poll {
1823     struct dp_netdev_port *port;
1824     struct netdev_rxq *rx;
1825 };
1826
1827 static int
1828 pmd_load_queues(struct pmd_thread *f,
1829                 struct rxq_poll **ppoll_list, int poll_cnt)
1830 {
1831     struct dp_netdev *dp = f->dp;
1832     struct rxq_poll *poll_list = *ppoll_list;
1833     struct dp_netdev_port *port;
1834     int id = f->id;
1835     int index;
1836     int i;
1837
1838     /* Simple scheduler for netdev rx polling. */
1839     ovs_rwlock_rdlock(&dp->port_rwlock);
1840     for (i = 0; i < poll_cnt; i++) {
1841          port_unref(poll_list[i].port);
1842     }
1843
1844     poll_cnt = 0;
1845     index = 0;
1846
1847     HMAP_FOR_EACH (port, node, &f->dp->ports) {
1848         if (netdev_is_pmd(port->netdev)) {
1849             int i;
1850
1851             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1852                 if ((index % dp->n_pmd_threads) == id) {
1853                     poll_list = xrealloc(poll_list, sizeof *poll_list * (poll_cnt + 1));
1854
1855                     port_ref(port);
1856                     poll_list[poll_cnt].port = port;
1857                     poll_list[poll_cnt].rx = port->rxq[i];
1858                     poll_cnt++;
1859                 }
1860                 index++;
1861             }
1862         }
1863     }
1864
1865     ovs_rwlock_unlock(&dp->port_rwlock);
1866     *ppoll_list = poll_list;
1867     return poll_cnt;
1868 }
1869
1870 static void *
1871 pmd_thread_main(void *f_)
1872 {
1873     struct pmd_thread *f = f_;
1874     struct dp_netdev *dp = f->dp;
1875     unsigned int lc = 0;
1876     struct rxq_poll *poll_list;
1877     unsigned int port_seq;
1878     int poll_cnt;
1879     int i;
1880
1881     poll_cnt = 0;
1882     poll_list = NULL;
1883
1884     pmd_thread_setaffinity_cpu(f->id);
1885 reload:
1886     poll_cnt = pmd_load_queues(f, &poll_list, poll_cnt);
1887     atomic_read(&f->change_seq, &port_seq);
1888
1889     for (;;) {
1890         unsigned int c_port_seq;
1891         int i;
1892
1893         for (i = 0; i < poll_cnt; i++) {
1894             dp_netdev_process_rxq_port(dp,  poll_list[i].port, poll_list[i].rx);
1895         }
1896
1897         if (lc++ > 1024) {
1898             ovsrcu_quiesce();
1899
1900             /* TODO: need completely userspace based signaling method.
1901              * to keep this thread entirely in userspace.
1902              * For now using atomic counter. */
1903             lc = 0;
1904             atomic_read_explicit(&f->change_seq, &c_port_seq, memory_order_consume);
1905             if (c_port_seq != port_seq) {
1906                 break;
1907             }
1908         }
1909     }
1910
1911     if (!latch_is_set(&f->dp->exit_latch)){
1912         goto reload;
1913     }
1914
1915     for (i = 0; i < poll_cnt; i++) {
1916          port_unref(poll_list[i].port);
1917     }
1918
1919     free(poll_list);
1920     return NULL;
1921 }
1922
1923 static void
1924 dp_netdev_set_pmd_threads(struct dp_netdev *dp, int n)
1925 {
1926     int i;
1927
1928     if (n == dp->n_pmd_threads) {
1929         return;
1930     }
1931
1932     /* Stop existing threads. */
1933     latch_set(&dp->exit_latch);
1934     dp_netdev_reload_pmd_threads(dp);
1935     for (i = 0; i < dp->n_pmd_threads; i++) {
1936         struct pmd_thread *f = &dp->pmd_threads[i];
1937
1938         xpthread_join(f->thread, NULL);
1939     }
1940     latch_poll(&dp->exit_latch);
1941     free(dp->pmd_threads);
1942
1943     /* Start new threads. */
1944     dp->pmd_threads = xmalloc(n * sizeof *dp->pmd_threads);
1945     dp->n_pmd_threads = n;
1946
1947     for (i = 0; i < n; i++) {
1948         struct pmd_thread *f = &dp->pmd_threads[i];
1949
1950         f->dp = dp;
1951         f->id = i;
1952         atomic_store(&f->change_seq, 1);
1953
1954         /* Each thread will distribute all devices rx-queues among
1955          * themselves. */
1956         f->thread = ovs_thread_create("pmd", pmd_thread_main, f);
1957     }
1958 }
1959
1960 \f
1961 static void *
1962 dp_netdev_flow_stats_new_cb(void)
1963 {
1964     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1965     ovs_mutex_init(&bucket->mutex);
1966     return bucket;
1967 }
1968
1969 static void
1970 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1971                     const struct ofpbuf *packet,
1972                     const struct miniflow *key)
1973 {
1974     uint16_t tcp_flags = miniflow_get_tcp_flags(key);
1975     long long int now = time_msec();
1976     struct dp_netdev_flow_stats *bucket;
1977
1978     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
1979                                         dp_netdev_flow_stats_new_cb);
1980
1981     ovs_mutex_lock(&bucket->mutex);
1982     bucket->used = MAX(now, bucket->used);
1983     bucket->packet_count++;
1984     bucket->byte_count += ofpbuf_size(packet);
1985     bucket->tcp_flags |= tcp_flags;
1986     ovs_mutex_unlock(&bucket->mutex);
1987 }
1988
1989 static void *
1990 dp_netdev_stats_new_cb(void)
1991 {
1992     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1993     ovs_mutex_init(&bucket->mutex);
1994     return bucket;
1995 }
1996
1997 static void
1998 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type)
1999 {
2000     struct dp_netdev_stats *bucket;
2001
2002     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
2003     ovs_mutex_lock(&bucket->mutex);
2004     bucket->n[type]++;
2005     ovs_mutex_unlock(&bucket->mutex);
2006 }
2007
2008 static void
2009 dp_netdev_input(struct dp_netdev *dp, struct ofpbuf *packet,
2010                 struct pkt_metadata *md)
2011     OVS_REQ_RDLOCK(dp->port_rwlock)
2012 {
2013     struct dp_netdev_flow *netdev_flow;
2014     struct {
2015         struct miniflow flow;
2016         uint32_t buf[FLOW_U32S];
2017     } key;
2018
2019     if (ofpbuf_size(packet) < ETH_HEADER_LEN) {
2020         ofpbuf_delete(packet);
2021         return;
2022     }
2023     miniflow_initialize(&key.flow, key.buf);
2024     miniflow_extract(packet, md, &key.flow);
2025
2026     netdev_flow = dp_netdev_lookup_flow(dp, &key.flow);
2027     if (netdev_flow) {
2028         struct dp_netdev_actions *actions;
2029
2030         dp_netdev_flow_used(netdev_flow, packet, &key.flow);
2031
2032         actions = dp_netdev_flow_get_actions(netdev_flow);
2033         dp_netdev_execute_actions(dp, &key.flow, packet, true, md,
2034                                   actions->actions, actions->size);
2035         dp_netdev_count_packet(dp, DP_STAT_HIT);
2036     } else if (dp->handler_queues) {
2037         dp_netdev_count_packet(dp, DP_STAT_MISS);
2038         dp_netdev_output_userspace(dp, packet,
2039                                    miniflow_hash_5tuple(&key.flow, 0)
2040                                    % dp->n_handlers,
2041                                    DPIF_UC_MISS, &key.flow, NULL);
2042         ofpbuf_delete(packet);
2043     }
2044 }
2045
2046 static void
2047 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
2048                      struct pkt_metadata *md)
2049     OVS_REQ_RDLOCK(dp->port_rwlock)
2050 {
2051     uint32_t *recirc_depth = recirc_depth_get();
2052
2053     *recirc_depth = 0;
2054     dp_netdev_input(dp, packet, md);
2055 }
2056
2057 static int
2058 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
2059                            int queue_no, int type, const struct miniflow *key,
2060                            const struct nlattr *userdata)
2061 {
2062     struct dp_netdev_queue *q;
2063     int error;
2064
2065     fat_rwlock_rdlock(&dp->queue_rwlock);
2066     q = &dp->handler_queues[queue_no];
2067     ovs_mutex_lock(&q->mutex);
2068     if (q->head - q->tail < MAX_QUEUE_LEN) {
2069         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
2070         struct dpif_upcall *upcall = &u->upcall;
2071         struct ofpbuf *buf = &u->buf;
2072         size_t buf_size;
2073         struct flow flow;
2074
2075         upcall->type = type;
2076
2077         /* Allocate buffer big enough for everything. */
2078         buf_size = ODPUTIL_FLOW_KEY_BYTES;
2079         if (userdata) {
2080             buf_size += NLA_ALIGN(userdata->nla_len);
2081         }
2082         buf_size += ofpbuf_size(packet);
2083         ofpbuf_init(buf, buf_size);
2084
2085         /* Put ODP flow. */
2086         miniflow_expand(key, &flow);
2087         odp_flow_key_from_flow(buf, &flow, NULL, flow.in_port.odp_port);
2088         upcall->key = ofpbuf_data(buf);
2089         upcall->key_len = ofpbuf_size(buf);
2090
2091         /* Put userdata. */
2092         if (userdata) {
2093             upcall->userdata = ofpbuf_put(buf, userdata,
2094                                           NLA_ALIGN(userdata->nla_len));
2095         }
2096
2097         ofpbuf_set_data(&upcall->packet,
2098                         ofpbuf_put(buf, ofpbuf_data(packet), ofpbuf_size(packet)));
2099         ofpbuf_set_size(&upcall->packet, ofpbuf_size(packet));
2100
2101         seq_change(q->seq);
2102
2103         error = 0;
2104     } else {
2105         dp_netdev_count_packet(dp, DP_STAT_LOST);
2106         error = ENOBUFS;
2107     }
2108     ovs_mutex_unlock(&q->mutex);
2109     fat_rwlock_unlock(&dp->queue_rwlock);
2110
2111     return error;
2112 }
2113
2114 struct dp_netdev_execute_aux {
2115     struct dp_netdev *dp;
2116     const struct miniflow *key;
2117 };
2118
2119 static void
2120 dp_execute_cb(void *aux_, struct ofpbuf *packet,
2121               struct pkt_metadata *md,
2122               const struct nlattr *a, bool may_steal)
2123     OVS_NO_THREAD_SAFETY_ANALYSIS
2124 {
2125     struct dp_netdev_execute_aux *aux = aux_;
2126     int type = nl_attr_type(a);
2127     struct dp_netdev_port *p;
2128     uint32_t *depth = recirc_depth_get();
2129
2130     switch ((enum ovs_action_attr)type) {
2131     case OVS_ACTION_ATTR_OUTPUT:
2132         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
2133         if (p) {
2134             netdev_send(p->netdev, packet, may_steal);
2135         }
2136         break;
2137
2138     case OVS_ACTION_ATTR_USERSPACE: {
2139         const struct nlattr *userdata;
2140
2141         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2142
2143         dp_netdev_output_userspace(aux->dp, packet,
2144                                    miniflow_hash_5tuple(aux->key, 0)
2145                                        % aux->dp->n_handlers,
2146                                    DPIF_UC_ACTION, aux->key,
2147                                    userdata);
2148
2149         if (may_steal) {
2150             ofpbuf_delete(packet);
2151         }
2152         break;
2153     }
2154
2155     case OVS_ACTION_ATTR_HASH: {
2156         const struct ovs_action_hash *hash_act;
2157         uint32_t hash;
2158
2159         hash_act = nl_attr_get(a);
2160         if (hash_act->hash_alg == OVS_HASH_ALG_L4) {
2161             /* Hash need not be symmetric, nor does it need to include
2162              * L2 fields. */
2163             hash = miniflow_hash_5tuple(aux->key, hash_act->hash_basis);
2164             if (!hash) {
2165                 hash = 1; /* 0 is not valid */
2166             }
2167
2168         } else {
2169             VLOG_WARN("Unknown hash algorithm specified for the hash action.");
2170             hash = 2;
2171         }
2172
2173         md->dp_hash = hash;
2174         break;
2175     }
2176
2177     case OVS_ACTION_ATTR_RECIRC:
2178         if (*depth < MAX_RECIRC_DEPTH) {
2179             struct pkt_metadata recirc_md = *md;
2180             struct ofpbuf *recirc_packet;
2181
2182             recirc_packet = may_steal ? packet : ofpbuf_clone(packet);
2183             recirc_md.recirc_id = nl_attr_get_u32(a);
2184
2185             (*depth)++;
2186             dp_netdev_input(aux->dp, recirc_packet, &recirc_md);
2187             (*depth)--;
2188
2189             break;
2190         } else {
2191             VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2192         }
2193         break;
2194
2195     case OVS_ACTION_ATTR_PUSH_VLAN:
2196     case OVS_ACTION_ATTR_POP_VLAN:
2197     case OVS_ACTION_ATTR_PUSH_MPLS:
2198     case OVS_ACTION_ATTR_POP_MPLS:
2199     case OVS_ACTION_ATTR_SET:
2200     case OVS_ACTION_ATTR_SAMPLE:
2201     case OVS_ACTION_ATTR_UNSPEC:
2202     case __OVS_ACTION_ATTR_MAX:
2203         OVS_NOT_REACHED();
2204     }
2205 }
2206
2207 static void
2208 dp_netdev_execute_actions(struct dp_netdev *dp, const struct miniflow *key,
2209                           struct ofpbuf *packet, bool may_steal,
2210                           struct pkt_metadata *md,
2211                           const struct nlattr *actions, size_t actions_len)
2212 {
2213     struct dp_netdev_execute_aux aux = {dp, key};
2214
2215     odp_execute_actions(&aux, packet, may_steal, md,
2216                         actions, actions_len, dp_execute_cb);
2217 }
2218
2219 const struct dpif_class dpif_netdev_class = {
2220     "netdev",
2221     dpif_netdev_enumerate,
2222     dpif_netdev_port_open_type,
2223     dpif_netdev_open,
2224     dpif_netdev_close,
2225     dpif_netdev_destroy,
2226     dpif_netdev_run,
2227     dpif_netdev_wait,
2228     dpif_netdev_get_stats,
2229     dpif_netdev_port_add,
2230     dpif_netdev_port_del,
2231     dpif_netdev_port_query_by_number,
2232     dpif_netdev_port_query_by_name,
2233     NULL,                       /* port_get_pid */
2234     dpif_netdev_port_dump_start,
2235     dpif_netdev_port_dump_next,
2236     dpif_netdev_port_dump_done,
2237     dpif_netdev_port_poll,
2238     dpif_netdev_port_poll_wait,
2239     dpif_netdev_flow_get,
2240     dpif_netdev_flow_put,
2241     dpif_netdev_flow_del,
2242     dpif_netdev_flow_flush,
2243     dpif_netdev_flow_dump_state_init,
2244     dpif_netdev_flow_dump_start,
2245     dpif_netdev_flow_dump_next,
2246     NULL,
2247     dpif_netdev_flow_dump_done,
2248     dpif_netdev_flow_dump_state_uninit,
2249     dpif_netdev_execute,
2250     NULL,                       /* operate */
2251     dpif_netdev_recv_set,
2252     dpif_netdev_handlers_set,
2253     dpif_netdev_queue_to_priority,
2254     dpif_netdev_recv,
2255     dpif_netdev_recv_wait,
2256     dpif_netdev_recv_purge,
2257 };
2258
2259 static void
2260 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2261                               const char *argv[], void *aux OVS_UNUSED)
2262 {
2263     struct dp_netdev_port *port;
2264     struct dp_netdev *dp;
2265     odp_port_t port_no;
2266
2267     ovs_mutex_lock(&dp_netdev_mutex);
2268     dp = shash_find_data(&dp_netdevs, argv[1]);
2269     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2270         ovs_mutex_unlock(&dp_netdev_mutex);
2271         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2272         return;
2273     }
2274     ovs_refcount_ref(&dp->ref_cnt);
2275     ovs_mutex_unlock(&dp_netdev_mutex);
2276
2277     ovs_rwlock_wrlock(&dp->port_rwlock);
2278     if (get_port_by_name(dp, argv[2], &port)) {
2279         unixctl_command_reply_error(conn, "unknown port");
2280         goto exit;
2281     }
2282
2283     port_no = u32_to_odp(atoi(argv[3]));
2284     if (!port_no || port_no == ODPP_NONE) {
2285         unixctl_command_reply_error(conn, "bad port number");
2286         goto exit;
2287     }
2288     if (dp_netdev_lookup_port(dp, port_no)) {
2289         unixctl_command_reply_error(conn, "port number already in use");
2290         goto exit;
2291     }
2292     hmap_remove(&dp->ports, &port->node);
2293     port->port_no = port_no;
2294     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
2295     seq_change(dp->port_seq);
2296     unixctl_command_reply(conn, NULL);
2297
2298 exit:
2299     ovs_rwlock_unlock(&dp->port_rwlock);
2300     dp_netdev_unref(dp);
2301 }
2302
2303 static void
2304 dpif_dummy_register__(const char *type)
2305 {
2306     struct dpif_class *class;
2307
2308     class = xmalloc(sizeof *class);
2309     *class = dpif_netdev_class;
2310     class->type = xstrdup(type);
2311     dp_register_provider(class);
2312 }
2313
2314 void
2315 dpif_dummy_register(bool override)
2316 {
2317     if (override) {
2318         struct sset types;
2319         const char *type;
2320
2321         sset_init(&types);
2322         dp_enumerate_types(&types);
2323         SSET_FOR_EACH (type, &types) {
2324             if (!dp_unregister_provider(type)) {
2325                 dpif_dummy_register__(type);
2326             }
2327         }
2328         sset_destroy(&types);
2329     }
2330
2331     dpif_dummy_register__("dummy");
2332
2333     unixctl_command_register("dpif-dummy/change-port-number",
2334                              "DP PORT NEW-NUMBER",
2335                              3, 3, dpif_dummy_change_port_number, NULL);
2336 }