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