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     char *name;
327 };
328
329 /* Interface to netdev-based datapath. */
330 struct dpif_netdev {
331     struct dpif dpif;
332     struct dp_netdev *dp;
333     uint64_t last_port_seq;
334 };
335
336 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
337                               struct dp_netdev_port **portp)
338     OVS_REQ_RDLOCK(dp->port_rwlock);
339 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
340                             struct dp_netdev_port **portp)
341     OVS_REQ_RDLOCK(dp->port_rwlock);
342 static void dp_netdev_free(struct dp_netdev *)
343     OVS_REQUIRES(dp_netdev_mutex);
344 static void dp_netdev_flow_flush(struct dp_netdev *);
345 static int do_add_port(struct dp_netdev *dp, const char *devname,
346                        const char *type, odp_port_t port_no)
347     OVS_REQ_WRLOCK(dp->port_rwlock);
348 static int do_del_port(struct dp_netdev *dp, odp_port_t port_no)
349     OVS_REQ_WRLOCK(dp->port_rwlock);
350 static void dp_netdev_destroy_all_queues(struct dp_netdev *dp)
351     OVS_REQ_WRLOCK(dp->queue_rwlock);
352 static int dpif_netdev_open(const struct dpif_class *, const char *name,
353                             bool create, struct dpif **);
354 static int dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *,
355                                       int queue_no, int type,
356                                       const struct flow *,
357                                       const struct nlattr *userdata);
358 static void dp_netdev_execute_actions(struct dp_netdev *dp,
359                                       const struct flow *, 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 flow *flow)
1075     OVS_EXCLUDED(dp->cls.rwlock)
1076 {
1077     struct dp_netdev_flow *netdev_flow;
1078
1079     fat_rwlock_rdlock(&dp->cls.rwlock);
1080     netdev_flow = dp_netdev_flow_cast(classifier_lookup(&dp->cls, flow, NULL));
1081     fat_rwlock_unlock(&dp->cls.rwlock);
1082
1083     return netdev_flow;
1084 }
1085
1086 static struct dp_netdev_flow *
1087 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1088     OVS_REQ_RDLOCK(dp->cls.rwlock)
1089 {
1090     struct dp_netdev_flow *netdev_flow;
1091
1092     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1093                              &dp->flow_table) {
1094         if (flow_equal(&netdev_flow->flow, flow)) {
1095             return netdev_flow;
1096         }
1097     }
1098
1099     return NULL;
1100 }
1101
1102 static void
1103 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1104                     struct dpif_flow_stats *stats)
1105 {
1106     struct dp_netdev_flow_stats *bucket;
1107     size_t i;
1108
1109     memset(stats, 0, sizeof *stats);
1110     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1111         ovs_mutex_lock(&bucket->mutex);
1112         stats->n_packets += bucket->packet_count;
1113         stats->n_bytes += bucket->byte_count;
1114         stats->used = MAX(stats->used, bucket->used);
1115         stats->tcp_flags |= bucket->tcp_flags;
1116         ovs_mutex_unlock(&bucket->mutex);
1117     }
1118 }
1119
1120 static int
1121 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1122                               const struct nlattr *mask_key,
1123                               uint32_t mask_key_len, const struct flow *flow,
1124                               struct flow *mask)
1125 {
1126     if (mask_key_len) {
1127         enum odp_key_fitness fitness;
1128
1129         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1130         if (fitness) {
1131             /* This should not happen: it indicates that
1132              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1133              * disagree on the acceptable form of a mask.  Log the problem
1134              * as an error, with enough details to enable debugging. */
1135             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1136
1137             if (!VLOG_DROP_ERR(&rl)) {
1138                 struct ds s;
1139
1140                 ds_init(&s);
1141                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1142                                 true);
1143                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1144                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1145                 ds_destroy(&s);
1146             }
1147
1148             return EINVAL;
1149         }
1150     } else {
1151         enum mf_field_id id;
1152         /* No mask key, unwildcard everything except fields whose
1153          * prerequisities are not met. */
1154         memset(mask, 0x0, sizeof *mask);
1155
1156         for (id = 0; id < MFF_N_IDS; ++id) {
1157             /* Skip registers and metadata. */
1158             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1159                 && id != MFF_METADATA) {
1160                 const struct mf_field *mf = mf_from_id(id);
1161                 if (mf_are_prereqs_ok(mf, flow)) {
1162                     mf_mask_field(mf, mask);
1163                 }
1164             }
1165         }
1166     }
1167
1168     /* Force unwildcard the in_port.
1169      *
1170      * We need to do this even in the case where we unwildcard "everything"
1171      * above because "everything" only includes the 16-bit OpenFlow port number
1172      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1173      * port number mask->in_port.odp_port. */
1174     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1175
1176     return 0;
1177 }
1178
1179 static int
1180 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1181                               struct flow *flow)
1182 {
1183     odp_port_t in_port;
1184
1185     if (odp_flow_key_to_flow(key, key_len, flow)) {
1186         /* This should not happen: it indicates that odp_flow_key_from_flow()
1187          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1188          * flow.  Log the problem as an error, with enough details to enable
1189          * debugging. */
1190         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1191
1192         if (!VLOG_DROP_ERR(&rl)) {
1193             struct ds s;
1194
1195             ds_init(&s);
1196             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1197             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1198             ds_destroy(&s);
1199         }
1200
1201         return EINVAL;
1202     }
1203
1204     in_port = flow->in_port.odp_port;
1205     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1206         return EINVAL;
1207     }
1208
1209     return 0;
1210 }
1211
1212 static int
1213 dpif_netdev_flow_get(const struct dpif *dpif,
1214                      const struct nlattr *nl_key, size_t nl_key_len,
1215                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1216 {
1217     struct dp_netdev *dp = get_dp_netdev(dpif);
1218     struct dp_netdev_flow *netdev_flow;
1219     struct flow key;
1220     int error;
1221
1222     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1223     if (error) {
1224         return error;
1225     }
1226
1227     fat_rwlock_rdlock(&dp->cls.rwlock);
1228     netdev_flow = dp_netdev_find_flow(dp, &key);
1229     fat_rwlock_unlock(&dp->cls.rwlock);
1230
1231     if (netdev_flow) {
1232         if (stats) {
1233             get_dpif_flow_stats(netdev_flow, stats);
1234         }
1235
1236         if (actionsp) {
1237             struct dp_netdev_actions *actions;
1238
1239             actions = dp_netdev_flow_get_actions(netdev_flow);
1240             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1241         }
1242      } else {
1243         error = ENOENT;
1244     }
1245
1246     return error;
1247 }
1248
1249 static int
1250 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1251                    const struct flow_wildcards *wc,
1252                    const struct nlattr *actions,
1253                    size_t actions_len)
1254     OVS_REQUIRES(dp->flow_mutex)
1255 {
1256     struct dp_netdev_flow *netdev_flow;
1257     struct match match;
1258
1259     netdev_flow = xzalloc(sizeof *netdev_flow);
1260     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1261
1262     ovs_mutex_init(&netdev_flow->mutex);
1263
1264     ovsthread_stats_init(&netdev_flow->stats);
1265
1266     ovsrcu_set(&netdev_flow->actions,
1267                dp_netdev_actions_create(actions, actions_len));
1268
1269     match_init(&match, flow, wc);
1270     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1271                   &match, NETDEV_RULE_PRIORITY);
1272     fat_rwlock_wrlock(&dp->cls.rwlock);
1273     classifier_insert(&dp->cls,
1274                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1275     hmap_insert(&dp->flow_table,
1276                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1277                 flow_hash(flow, 0));
1278     fat_rwlock_unlock(&dp->cls.rwlock);
1279
1280     return 0;
1281 }
1282
1283 static void
1284 clear_stats(struct dp_netdev_flow *netdev_flow)
1285 {
1286     struct dp_netdev_flow_stats *bucket;
1287     size_t i;
1288
1289     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1290         ovs_mutex_lock(&bucket->mutex);
1291         bucket->used = 0;
1292         bucket->packet_count = 0;
1293         bucket->byte_count = 0;
1294         bucket->tcp_flags = 0;
1295         ovs_mutex_unlock(&bucket->mutex);
1296     }
1297 }
1298
1299 static int
1300 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1301 {
1302     struct dp_netdev *dp = get_dp_netdev(dpif);
1303     struct dp_netdev_flow *netdev_flow;
1304     struct flow flow;
1305     struct flow_wildcards wc;
1306     int error;
1307
1308     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1309     if (error) {
1310         return error;
1311     }
1312     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1313                                           put->mask, put->mask_len,
1314                                           &flow, &wc.masks);
1315     if (error) {
1316         return error;
1317     }
1318
1319     ovs_mutex_lock(&dp->flow_mutex);
1320     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1321     if (!netdev_flow) {
1322         if (put->flags & DPIF_FP_CREATE) {
1323             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1324                 if (put->stats) {
1325                     memset(put->stats, 0, sizeof *put->stats);
1326                 }
1327                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1328                                            put->actions_len);
1329             } else {
1330                 error = EFBIG;
1331             }
1332         } else {
1333             error = ENOENT;
1334         }
1335     } else {
1336         if (put->flags & DPIF_FP_MODIFY
1337             && flow_equal(&flow, &netdev_flow->flow)) {
1338             struct dp_netdev_actions *new_actions;
1339             struct dp_netdev_actions *old_actions;
1340
1341             new_actions = dp_netdev_actions_create(put->actions,
1342                                                    put->actions_len);
1343
1344             old_actions = dp_netdev_flow_get_actions(netdev_flow);
1345             ovsrcu_set(&netdev_flow->actions, new_actions);
1346
1347             if (put->stats) {
1348                 get_dpif_flow_stats(netdev_flow, put->stats);
1349             }
1350             if (put->flags & DPIF_FP_ZERO_STATS) {
1351                 clear_stats(netdev_flow);
1352             }
1353
1354             ovsrcu_postpone(dp_netdev_actions_free, old_actions);
1355         } else if (put->flags & DPIF_FP_CREATE) {
1356             error = EEXIST;
1357         } else {
1358             /* Overlapping flow. */
1359             error = EINVAL;
1360         }
1361     }
1362     ovs_mutex_unlock(&dp->flow_mutex);
1363
1364     return error;
1365 }
1366
1367 static int
1368 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1369 {
1370     struct dp_netdev *dp = get_dp_netdev(dpif);
1371     struct dp_netdev_flow *netdev_flow;
1372     struct flow key;
1373     int error;
1374
1375     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1376     if (error) {
1377         return error;
1378     }
1379
1380     ovs_mutex_lock(&dp->flow_mutex);
1381     fat_rwlock_wrlock(&dp->cls.rwlock);
1382     netdev_flow = dp_netdev_find_flow(dp, &key);
1383     if (netdev_flow) {
1384         if (del->stats) {
1385             get_dpif_flow_stats(netdev_flow, del->stats);
1386         }
1387         dp_netdev_remove_flow(dp, netdev_flow);
1388     } else {
1389         error = ENOENT;
1390     }
1391     fat_rwlock_unlock(&dp->cls.rwlock);
1392     ovs_mutex_unlock(&dp->flow_mutex);
1393
1394     return error;
1395 }
1396
1397 struct dp_netdev_flow_state {
1398     struct dp_netdev_actions *actions;
1399     struct odputil_keybuf keybuf;
1400     struct odputil_keybuf maskbuf;
1401     struct dpif_flow_stats stats;
1402 };
1403
1404 struct dp_netdev_flow_iter {
1405     uint32_t bucket;
1406     uint32_t offset;
1407     int status;
1408     struct ovs_mutex mutex;
1409 };
1410
1411 static void
1412 dpif_netdev_flow_dump_state_init(void **statep)
1413 {
1414     struct dp_netdev_flow_state *state;
1415
1416     *statep = state = xmalloc(sizeof *state);
1417     state->actions = NULL;
1418 }
1419
1420 static void
1421 dpif_netdev_flow_dump_state_uninit(void *state_)
1422 {
1423     struct dp_netdev_flow_state *state = state_;
1424
1425     free(state);
1426 }
1427
1428 static int
1429 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **iterp)
1430 {
1431     struct dp_netdev_flow_iter *iter;
1432
1433     *iterp = iter = xmalloc(sizeof *iter);
1434     iter->bucket = 0;
1435     iter->offset = 0;
1436     iter->status = 0;
1437     ovs_mutex_init(&iter->mutex);
1438     return 0;
1439 }
1440
1441 /* XXX the caller must use 'actions' without quiescing */
1442 static int
1443 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *iter_, void *state_,
1444                            const struct nlattr **key, size_t *key_len,
1445                            const struct nlattr **mask, size_t *mask_len,
1446                            const struct nlattr **actions, size_t *actions_len,
1447                            const struct dpif_flow_stats **stats)
1448 {
1449     struct dp_netdev_flow_iter *iter = iter_;
1450     struct dp_netdev_flow_state *state = state_;
1451     struct dp_netdev *dp = get_dp_netdev(dpif);
1452     struct dp_netdev_flow *netdev_flow;
1453     int error;
1454
1455     ovs_mutex_lock(&iter->mutex);
1456     error = iter->status;
1457     if (!error) {
1458         struct hmap_node *node;
1459
1460         fat_rwlock_rdlock(&dp->cls.rwlock);
1461         node = hmap_at_position(&dp->flow_table, &iter->bucket, &iter->offset);
1462         if (node) {
1463             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1464         }
1465         fat_rwlock_unlock(&dp->cls.rwlock);
1466         if (!node) {
1467             iter->status = error = EOF;
1468         }
1469     }
1470     ovs_mutex_unlock(&iter->mutex);
1471     if (error) {
1472         return error;
1473     }
1474
1475     if (key) {
1476         struct ofpbuf buf;
1477
1478         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1479         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1480                                netdev_flow->flow.in_port.odp_port);
1481
1482         *key = ofpbuf_data(&buf);
1483         *key_len = ofpbuf_size(&buf);
1484     }
1485
1486     if (key && mask) {
1487         struct ofpbuf buf;
1488         struct flow_wildcards wc;
1489
1490         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1491         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1492         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1493                                odp_to_u32(wc.masks.in_port.odp_port),
1494                                SIZE_MAX);
1495
1496         *mask = ofpbuf_data(&buf);
1497         *mask_len = ofpbuf_size(&buf);
1498     }
1499
1500     if (actions || stats) {
1501         state->actions = NULL;
1502
1503         if (actions) {
1504             state->actions = dp_netdev_flow_get_actions(netdev_flow);
1505             *actions = state->actions->actions;
1506             *actions_len = state->actions->size;
1507         }
1508
1509         if (stats) {
1510             get_dpif_flow_stats(netdev_flow, &state->stats);
1511             *stats = &state->stats;
1512         }
1513     }
1514
1515     return 0;
1516 }
1517
1518 static int
1519 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *iter_)
1520 {
1521     struct dp_netdev_flow_iter *iter = iter_;
1522
1523     ovs_mutex_destroy(&iter->mutex);
1524     free(iter);
1525     return 0;
1526 }
1527
1528 static int
1529 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1530 {
1531     struct dp_netdev *dp = get_dp_netdev(dpif);
1532     struct pkt_metadata *md = &execute->md;
1533     struct flow 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     flow_extract(execute->packet, md, &key);
1542
1543     ovs_rwlock_rdlock(&dp->port_rwlock);
1544     dp_netdev_execute_actions(dp, &key, execute->packet, false, md,
1545                               execute->actions, execute->actions_len);
1546     ovs_rwlock_unlock(&dp->port_rwlock);
1547
1548     return 0;
1549 }
1550
1551 static void
1552 dp_netdev_destroy_all_queues(struct dp_netdev *dp)
1553     OVS_REQ_WRLOCK(dp->queue_rwlock)
1554 {
1555     size_t i;
1556
1557     dp_netdev_purge_queues(dp);
1558
1559     for (i = 0; i < dp->n_handlers; i++) {
1560         struct dp_netdev_queue *q = &dp->handler_queues[i];
1561
1562         ovs_mutex_destroy(&q->mutex);
1563         seq_destroy(q->seq);
1564     }
1565     free(dp->handler_queues);
1566     dp->handler_queues = NULL;
1567     dp->n_handlers = 0;
1568 }
1569
1570 static void
1571 dp_netdev_refresh_queues(struct dp_netdev *dp, uint32_t n_handlers)
1572     OVS_REQ_WRLOCK(dp->queue_rwlock)
1573 {
1574     if (dp->n_handlers != n_handlers) {
1575         size_t i;
1576
1577         dp_netdev_destroy_all_queues(dp);
1578
1579         dp->n_handlers = n_handlers;
1580         dp->handler_queues = xzalloc(n_handlers * sizeof *dp->handler_queues);
1581
1582         for (i = 0; i < n_handlers; i++) {
1583             struct dp_netdev_queue *q = &dp->handler_queues[i];
1584
1585             ovs_mutex_init(&q->mutex);
1586             q->seq = seq_create();
1587         }
1588     }
1589 }
1590
1591 static int
1592 dpif_netdev_recv_set(struct dpif *dpif, bool enable)
1593 {
1594     struct dp_netdev *dp = get_dp_netdev(dpif);
1595
1596     if ((dp->handler_queues != NULL) == enable) {
1597         return 0;
1598     }
1599
1600     fat_rwlock_wrlock(&dp->queue_rwlock);
1601     if (!enable) {
1602         dp_netdev_destroy_all_queues(dp);
1603     } else {
1604         dp_netdev_refresh_queues(dp, 1);
1605     }
1606     fat_rwlock_unlock(&dp->queue_rwlock);
1607
1608     return 0;
1609 }
1610
1611 static int
1612 dpif_netdev_handlers_set(struct dpif *dpif, uint32_t n_handlers)
1613 {
1614     struct dp_netdev *dp = get_dp_netdev(dpif);
1615
1616     fat_rwlock_wrlock(&dp->queue_rwlock);
1617     if (dp->handler_queues) {
1618         dp_netdev_refresh_queues(dp, n_handlers);
1619     }
1620     fat_rwlock_unlock(&dp->queue_rwlock);
1621
1622     return 0;
1623 }
1624
1625 static int
1626 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1627                               uint32_t queue_id, uint32_t *priority)
1628 {
1629     *priority = queue_id;
1630     return 0;
1631 }
1632
1633 static bool
1634 dp_netdev_recv_check(const struct dp_netdev *dp, const uint32_t handler_id)
1635     OVS_REQ_RDLOCK(dp->queue_rwlock)
1636 {
1637     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1638
1639     if (!dp->handler_queues) {
1640         VLOG_WARN_RL(&rl, "receiving upcall disabled");
1641         return false;
1642     }
1643
1644     if (handler_id >= dp->n_handlers) {
1645         VLOG_WARN_RL(&rl, "handler index out of bound");
1646         return false;
1647     }
1648
1649     return true;
1650 }
1651
1652 static int
1653 dpif_netdev_recv(struct dpif *dpif, uint32_t handler_id,
1654                  struct dpif_upcall *upcall, struct ofpbuf *buf)
1655 {
1656     struct dp_netdev *dp = get_dp_netdev(dpif);
1657     struct dp_netdev_queue *q;
1658     int error = 0;
1659
1660     fat_rwlock_rdlock(&dp->queue_rwlock);
1661
1662     if (!dp_netdev_recv_check(dp, handler_id)) {
1663         error = EAGAIN;
1664         goto out;
1665     }
1666
1667     q = &dp->handler_queues[handler_id];
1668     ovs_mutex_lock(&q->mutex);
1669     if (q->head != q->tail) {
1670         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1671
1672         *upcall = u->upcall;
1673
1674         ofpbuf_uninit(buf);
1675         *buf = u->buf;
1676     } else {
1677         error = EAGAIN;
1678     }
1679     ovs_mutex_unlock(&q->mutex);
1680
1681 out:
1682     fat_rwlock_unlock(&dp->queue_rwlock);
1683
1684     return error;
1685 }
1686
1687 static void
1688 dpif_netdev_recv_wait(struct dpif *dpif, uint32_t handler_id)
1689 {
1690     struct dp_netdev *dp = get_dp_netdev(dpif);
1691     struct dp_netdev_queue *q;
1692     uint64_t seq;
1693
1694     fat_rwlock_rdlock(&dp->queue_rwlock);
1695
1696     if (!dp_netdev_recv_check(dp, handler_id)) {
1697         goto out;
1698     }
1699
1700     q = &dp->handler_queues[handler_id];
1701     ovs_mutex_lock(&q->mutex);
1702     seq = seq_read(q->seq);
1703     if (q->head != q->tail) {
1704         poll_immediate_wake();
1705     } else {
1706         seq_wait(q->seq, seq);
1707     }
1708
1709     ovs_mutex_unlock(&q->mutex);
1710
1711 out:
1712     fat_rwlock_unlock(&dp->queue_rwlock);
1713 }
1714
1715 static void
1716 dpif_netdev_recv_purge(struct dpif *dpif)
1717 {
1718     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1719
1720     fat_rwlock_wrlock(&dpif_netdev->dp->queue_rwlock);
1721     dp_netdev_purge_queues(dpif_netdev->dp);
1722     fat_rwlock_unlock(&dpif_netdev->dp->queue_rwlock);
1723 }
1724 \f
1725 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1726  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1727  * 'ofpacts'. */
1728 struct dp_netdev_actions *
1729 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1730 {
1731     struct dp_netdev_actions *netdev_actions;
1732
1733     netdev_actions = xmalloc(sizeof *netdev_actions);
1734     netdev_actions->actions = xmemdup(actions, size);
1735     netdev_actions->size = size;
1736
1737     return netdev_actions;
1738 }
1739
1740 struct dp_netdev_actions *
1741 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
1742 {
1743     return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
1744 }
1745
1746 static void
1747 dp_netdev_actions_free(struct dp_netdev_actions *actions)
1748 {
1749     free(actions->actions);
1750     free(actions);
1751 }
1752 \f
1753
1754 static void
1755 dp_netdev_process_rxq_port(struct dp_netdev *dp,
1756                           struct dp_netdev_port *port,
1757                           struct netdev_rxq *rxq)
1758 {
1759     struct ofpbuf *packet[NETDEV_MAX_RX_BATCH];
1760     int error, c;
1761
1762     error = netdev_rxq_recv(rxq, packet, &c);
1763     if (!error) {
1764         struct pkt_metadata md = PKT_METADATA_INITIALIZER(port->port_no);
1765         int i;
1766
1767         for (i = 0; i < c; i++) {
1768             dp_netdev_port_input(dp, packet[i], &md);
1769         }
1770     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1771         static struct vlog_rate_limit rl
1772             = VLOG_RATE_LIMIT_INIT(1, 5);
1773
1774         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1775                     netdev_get_name(port->netdev),
1776                     ovs_strerror(error));
1777     }
1778 }
1779
1780 static void
1781 dpif_netdev_run(struct dpif *dpif)
1782 {
1783     struct dp_netdev_port *port;
1784     struct dp_netdev *dp = get_dp_netdev(dpif);
1785
1786     ovs_rwlock_rdlock(&dp->port_rwlock);
1787
1788     HMAP_FOR_EACH (port, node, &dp->ports) {
1789         if (!netdev_is_pmd(port->netdev)) {
1790             int i;
1791
1792             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1793                 dp_netdev_process_rxq_port(dp, port, port->rxq[i]);
1794             }
1795         }
1796     }
1797
1798     ovs_rwlock_unlock(&dp->port_rwlock);
1799 }
1800
1801 static void
1802 dpif_netdev_wait(struct dpif *dpif)
1803 {
1804     struct dp_netdev_port *port;
1805     struct dp_netdev *dp = get_dp_netdev(dpif);
1806
1807     ovs_rwlock_rdlock(&dp->port_rwlock);
1808
1809     HMAP_FOR_EACH (port, node, &dp->ports) {
1810         if (!netdev_is_pmd(port->netdev)) {
1811             int i;
1812
1813             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1814                 netdev_rxq_wait(port->rxq[i]);
1815             }
1816         }
1817     }
1818     ovs_rwlock_unlock(&dp->port_rwlock);
1819 }
1820
1821 struct rxq_poll {
1822     struct dp_netdev_port *port;
1823     struct netdev_rxq *rx;
1824 };
1825
1826 static int
1827 pmd_load_queues(struct pmd_thread *f,
1828                 struct rxq_poll **ppoll_list, int poll_cnt)
1829 {
1830     struct dp_netdev *dp = f->dp;
1831     struct rxq_poll *poll_list = *ppoll_list;
1832     struct dp_netdev_port *port;
1833     int id = f->id;
1834     int index;
1835     int i;
1836
1837     /* Simple scheduler for netdev rx polling. */
1838     ovs_rwlock_rdlock(&dp->port_rwlock);
1839     for (i = 0; i < poll_cnt; i++) {
1840          port_unref(poll_list[i].port);
1841     }
1842
1843     poll_cnt = 0;
1844     index = 0;
1845
1846     HMAP_FOR_EACH (port, node, &f->dp->ports) {
1847         if (netdev_is_pmd(port->netdev)) {
1848             int i;
1849
1850             for (i = 0; i < netdev_n_rxq(port->netdev); i++) {
1851                 if ((index % dp->n_pmd_threads) == id) {
1852                     poll_list = xrealloc(poll_list, sizeof *poll_list * (poll_cnt + 1));
1853
1854                     port_ref(port);
1855                     poll_list[poll_cnt].port = port;
1856                     poll_list[poll_cnt].rx = port->rxq[i];
1857                     poll_cnt++;
1858                 }
1859                 index++;
1860             }
1861         }
1862     }
1863
1864     ovs_rwlock_unlock(&dp->port_rwlock);
1865     *ppoll_list = poll_list;
1866     return poll_cnt;
1867 }
1868
1869 static void *
1870 pmd_thread_main(void *f_)
1871 {
1872     struct pmd_thread *f = f_;
1873     struct dp_netdev *dp = f->dp;
1874     unsigned int lc = 0;
1875     struct rxq_poll *poll_list;
1876     unsigned int port_seq;
1877     int poll_cnt;
1878     int i;
1879
1880     f->name = xasprintf("pmd_%u", ovsthread_id_self());
1881     set_subprogram_name("%s", f->name);
1882     poll_cnt = 0;
1883     poll_list = NULL;
1884
1885     pmd_thread_setaffinity_cpu(f->id);
1886 reload:
1887     poll_cnt = pmd_load_queues(f, &poll_list, poll_cnt);
1888     atomic_read(&f->change_seq, &port_seq);
1889
1890     for (;;) {
1891         unsigned int c_port_seq;
1892         int i;
1893
1894         for (i = 0; i < poll_cnt; i++) {
1895             dp_netdev_process_rxq_port(dp,  poll_list[i].port, poll_list[i].rx);
1896         }
1897
1898         if (lc++ > 1024) {
1899             ovsrcu_quiesce();
1900
1901             /* TODO: need completely userspace based signaling method.
1902              * to keep this thread entirely in userspace.
1903              * For now using atomic counter. */
1904             lc = 0;
1905             atomic_read_explicit(&f->change_seq, &c_port_seq, memory_order_consume);
1906             if (c_port_seq != port_seq) {
1907                 break;
1908             }
1909         }
1910     }
1911
1912     if (!latch_is_set(&f->dp->exit_latch)){
1913         goto reload;
1914     }
1915
1916     for (i = 0; i < poll_cnt; i++) {
1917          port_unref(poll_list[i].port);
1918     }
1919
1920     free(poll_list);
1921     free(f->name);
1922     return NULL;
1923 }
1924
1925 static void
1926 dp_netdev_set_pmd_threads(struct dp_netdev *dp, int n)
1927 {
1928     int i;
1929
1930     if (n == dp->n_pmd_threads) {
1931         return;
1932     }
1933
1934     /* Stop existing threads. */
1935     latch_set(&dp->exit_latch);
1936     dp_netdev_reload_pmd_threads(dp);
1937     for (i = 0; i < dp->n_pmd_threads; i++) {
1938         struct pmd_thread *f = &dp->pmd_threads[i];
1939
1940         xpthread_join(f->thread, NULL);
1941     }
1942     latch_poll(&dp->exit_latch);
1943     free(dp->pmd_threads);
1944
1945     /* Start new threads. */
1946     dp->pmd_threads = xmalloc(n * sizeof *dp->pmd_threads);
1947     dp->n_pmd_threads = n;
1948
1949     for (i = 0; i < n; i++) {
1950         struct pmd_thread *f = &dp->pmd_threads[i];
1951
1952         f->dp = dp;
1953         f->id = i;
1954         atomic_store(&f->change_seq, 1);
1955
1956         /* Each thread will distribute all devices rx-queues among
1957          * themselves. */
1958         xpthread_create(&f->thread, NULL, pmd_thread_main, f);
1959     }
1960 }
1961
1962 \f
1963 static void *
1964 dp_netdev_flow_stats_new_cb(void)
1965 {
1966     struct dp_netdev_flow_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1967     ovs_mutex_init(&bucket->mutex);
1968     return bucket;
1969 }
1970
1971 static void
1972 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1973                     const struct ofpbuf *packet,
1974                     const struct flow *key)
1975 {
1976     uint16_t tcp_flags = ntohs(key->tcp_flags);
1977     long long int now = time_msec();
1978     struct dp_netdev_flow_stats *bucket;
1979
1980     bucket = ovsthread_stats_bucket_get(&netdev_flow->stats,
1981                                         dp_netdev_flow_stats_new_cb);
1982
1983     ovs_mutex_lock(&bucket->mutex);
1984     bucket->used = MAX(now, bucket->used);
1985     bucket->packet_count++;
1986     bucket->byte_count += ofpbuf_size(packet);
1987     bucket->tcp_flags |= tcp_flags;
1988     ovs_mutex_unlock(&bucket->mutex);
1989 }
1990
1991 static void *
1992 dp_netdev_stats_new_cb(void)
1993 {
1994     struct dp_netdev_stats *bucket = xzalloc_cacheline(sizeof *bucket);
1995     ovs_mutex_init(&bucket->mutex);
1996     return bucket;
1997 }
1998
1999 static void
2000 dp_netdev_count_packet(struct dp_netdev *dp, enum dp_stat_type type)
2001 {
2002     struct dp_netdev_stats *bucket;
2003
2004     bucket = ovsthread_stats_bucket_get(&dp->stats, dp_netdev_stats_new_cb);
2005     ovs_mutex_lock(&bucket->mutex);
2006     bucket->n[type]++;
2007     ovs_mutex_unlock(&bucket->mutex);
2008 }
2009
2010 static void
2011 dp_netdev_input(struct dp_netdev *dp, struct ofpbuf *packet,
2012                 struct pkt_metadata *md)
2013     OVS_REQ_RDLOCK(dp->port_rwlock)
2014 {
2015     struct dp_netdev_flow *netdev_flow;
2016     struct flow key;
2017
2018     if (ofpbuf_size(packet) < ETH_HEADER_LEN) {
2019         ofpbuf_delete(packet);
2020         return;
2021     }
2022     flow_extract(packet, md, &key);
2023     netdev_flow = dp_netdev_lookup_flow(dp, &key);
2024     if (netdev_flow) {
2025         struct dp_netdev_actions *actions;
2026
2027         dp_netdev_flow_used(netdev_flow, packet, &key);
2028
2029         actions = dp_netdev_flow_get_actions(netdev_flow);
2030         dp_netdev_execute_actions(dp, &key, packet, true, md,
2031                                   actions->actions, actions->size);
2032         dp_netdev_count_packet(dp, DP_STAT_HIT);
2033     } else if (dp->handler_queues) {
2034         dp_netdev_count_packet(dp, DP_STAT_MISS);
2035         dp_netdev_output_userspace(dp, packet,
2036                                    flow_hash_5tuple(&key, 0) % dp->n_handlers,
2037                                    DPIF_UC_MISS, &key, NULL);
2038         ofpbuf_delete(packet);
2039     }
2040 }
2041
2042 static void
2043 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
2044                      struct pkt_metadata *md)
2045     OVS_REQ_RDLOCK(dp->port_rwlock)
2046 {
2047     uint32_t *recirc_depth = recirc_depth_get();
2048
2049     *recirc_depth = 0;
2050     dp_netdev_input(dp, packet, md);
2051 }
2052
2053 static int
2054 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
2055                            int queue_no, int type, const struct flow *flow,
2056                            const struct nlattr *userdata)
2057 {
2058     struct dp_netdev_queue *q;
2059     int error;
2060
2061     fat_rwlock_rdlock(&dp->queue_rwlock);
2062     q = &dp->handler_queues[queue_no];
2063     ovs_mutex_lock(&q->mutex);
2064     if (q->head - q->tail < MAX_QUEUE_LEN) {
2065         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
2066         struct dpif_upcall *upcall = &u->upcall;
2067         struct ofpbuf *buf = &u->buf;
2068         size_t buf_size;
2069
2070         upcall->type = type;
2071
2072         /* Allocate buffer big enough for everything. */
2073         buf_size = ODPUTIL_FLOW_KEY_BYTES;
2074         if (userdata) {
2075             buf_size += NLA_ALIGN(userdata->nla_len);
2076         }
2077         buf_size += ofpbuf_size(packet);
2078         ofpbuf_init(buf, buf_size);
2079
2080         /* Put ODP flow. */
2081         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
2082         upcall->key = ofpbuf_data(buf);
2083         upcall->key_len = ofpbuf_size(buf);
2084
2085         /* Put userdata. */
2086         if (userdata) {
2087             upcall->userdata = ofpbuf_put(buf, userdata,
2088                                           NLA_ALIGN(userdata->nla_len));
2089         }
2090
2091         ofpbuf_set_data(&upcall->packet,
2092                         ofpbuf_put(buf, ofpbuf_data(packet), ofpbuf_size(packet)));
2093         ofpbuf_set_size(&upcall->packet, ofpbuf_size(packet));
2094
2095         seq_change(q->seq);
2096
2097         error = 0;
2098     } else {
2099         dp_netdev_count_packet(dp, DP_STAT_LOST);
2100         error = ENOBUFS;
2101     }
2102     ovs_mutex_unlock(&q->mutex);
2103     fat_rwlock_unlock(&dp->queue_rwlock);
2104
2105     return error;
2106 }
2107
2108 struct dp_netdev_execute_aux {
2109     struct dp_netdev *dp;
2110     const struct flow *key;
2111 };
2112
2113 static void
2114 dp_execute_cb(void *aux_, struct ofpbuf *packet,
2115               struct pkt_metadata *md,
2116               const struct nlattr *a, bool may_steal)
2117     OVS_NO_THREAD_SAFETY_ANALYSIS
2118 {
2119     struct dp_netdev_execute_aux *aux = aux_;
2120     int type = nl_attr_type(a);
2121     struct dp_netdev_port *p;
2122     uint32_t *depth = recirc_depth_get();
2123
2124     switch ((enum ovs_action_attr)type) {
2125     case OVS_ACTION_ATTR_OUTPUT:
2126         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
2127         if (p) {
2128             netdev_send(p->netdev, packet, may_steal);
2129         }
2130         break;
2131
2132     case OVS_ACTION_ATTR_USERSPACE: {
2133         const struct nlattr *userdata;
2134
2135         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2136
2137         dp_netdev_output_userspace(aux->dp, packet,
2138                                    flow_hash_5tuple(aux->key, 0)
2139                                        % aux->dp->n_handlers,
2140                                    DPIF_UC_ACTION, aux->key,
2141                                    userdata);
2142
2143         if (may_steal) {
2144             ofpbuf_delete(packet);
2145         }
2146         break;
2147     }
2148
2149     case OVS_ACTION_ATTR_RECIRC:
2150         if (*depth < MAX_RECIRC_DEPTH) {
2151             struct pkt_metadata recirc_md = *md;
2152             struct ofpbuf *recirc_packet;
2153             const struct ovs_action_recirc *act;
2154
2155             recirc_packet = may_steal ? packet : ofpbuf_clone(packet);
2156
2157             act = nl_attr_get(a);
2158             recirc_md.recirc_id = act->recirc_id;
2159             recirc_md.dp_hash = 0;
2160
2161             if (act->hash_alg == OVS_RECIRC_HASH_ALG_L4) {
2162                 recirc_md.dp_hash = flow_hash_symmetric_l4(aux->key,
2163                                                            act->hash_bias);
2164                 if (!recirc_md.dp_hash) {
2165                     recirc_md.dp_hash = 1;  /* 0 is not valid */
2166                 }
2167             }
2168
2169             (*depth)++;
2170             dp_netdev_input(aux->dp, recirc_packet, &recirc_md);
2171             (*depth)--;
2172
2173             break;
2174         } else {
2175             VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2176         }
2177         break;
2178
2179     case OVS_ACTION_ATTR_PUSH_VLAN:
2180     case OVS_ACTION_ATTR_POP_VLAN:
2181     case OVS_ACTION_ATTR_PUSH_MPLS:
2182     case OVS_ACTION_ATTR_POP_MPLS:
2183     case OVS_ACTION_ATTR_SET:
2184     case OVS_ACTION_ATTR_SAMPLE:
2185     case OVS_ACTION_ATTR_UNSPEC:
2186     case __OVS_ACTION_ATTR_MAX:
2187         OVS_NOT_REACHED();
2188     }
2189 }
2190
2191 static void
2192 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
2193                           struct ofpbuf *packet, bool may_steal,
2194                           struct pkt_metadata *md,
2195                           const struct nlattr *actions, size_t actions_len)
2196 {
2197     struct dp_netdev_execute_aux aux = {dp, key};
2198
2199     odp_execute_actions(&aux, packet, may_steal, md,
2200                         actions, actions_len, dp_execute_cb);
2201 }
2202
2203 #define DPIF_NETDEV_CLASS_FUNCTIONS                     \
2204     dpif_netdev_enumerate,                              \
2205     dpif_netdev_port_open_type,                         \
2206     dpif_netdev_open,                                   \
2207     dpif_netdev_close,                                  \
2208     dpif_netdev_destroy,                                \
2209     dpif_netdev_run,                                    \
2210     dpif_netdev_wait,                                   \
2211     dpif_netdev_get_stats,                              \
2212     dpif_netdev_port_add,                               \
2213     dpif_netdev_port_del,                               \
2214     dpif_netdev_port_query_by_number,                   \
2215     dpif_netdev_port_query_by_name,                     \
2216     NULL,                       /* port_get_pid */      \
2217     dpif_netdev_port_dump_start,                        \
2218     dpif_netdev_port_dump_next,                         \
2219     dpif_netdev_port_dump_done,                         \
2220     dpif_netdev_port_poll,                              \
2221     dpif_netdev_port_poll_wait,                         \
2222     dpif_netdev_flow_get,                               \
2223     dpif_netdev_flow_put,                               \
2224     dpif_netdev_flow_del,                               \
2225     dpif_netdev_flow_flush,                             \
2226     dpif_netdev_flow_dump_state_init,   \
2227     dpif_netdev_flow_dump_start,                        \
2228     dpif_netdev_flow_dump_next,                         \
2229     NULL,                                   \
2230     dpif_netdev_flow_dump_done,                         \
2231     dpif_netdev_flow_dump_state_uninit,     \
2232     dpif_netdev_execute,                                \
2233     NULL,                       /* operate */           \
2234     dpif_netdev_recv_set,                               \
2235     dpif_netdev_handlers_set,           \
2236     dpif_netdev_queue_to_priority,                      \
2237     dpif_netdev_recv,                                   \
2238     dpif_netdev_recv_wait,                              \
2239     dpif_netdev_recv_purge,                             \
2240
2241 const struct dpif_class dpif_netdev_class = {
2242     "netdev",
2243     DPIF_NETDEV_CLASS_FUNCTIONS
2244 };
2245
2246 const struct dpif_class dpif_planetlab_class = {
2247     "planetlab",
2248     DPIF_NETDEV_CLASS_FUNCTIONS
2249 };
2250
2251 static void
2252 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2253                               const char *argv[], void *aux OVS_UNUSED)
2254 {
2255     struct dp_netdev_port *port;
2256     struct dp_netdev *dp;
2257     odp_port_t port_no;
2258
2259     ovs_mutex_lock(&dp_netdev_mutex);
2260     dp = shash_find_data(&dp_netdevs, argv[1]);
2261     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2262         ovs_mutex_unlock(&dp_netdev_mutex);
2263         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2264         return;
2265     }
2266     ovs_refcount_ref(&dp->ref_cnt);
2267     ovs_mutex_unlock(&dp_netdev_mutex);
2268
2269     ovs_rwlock_wrlock(&dp->port_rwlock);
2270     if (get_port_by_name(dp, argv[2], &port)) {
2271         unixctl_command_reply_error(conn, "unknown port");
2272         goto exit;
2273     }
2274
2275     port_no = u32_to_odp(atoi(argv[3]));
2276     if (!port_no || port_no == ODPP_NONE) {
2277         unixctl_command_reply_error(conn, "bad port number");
2278         goto exit;
2279     }
2280     if (dp_netdev_lookup_port(dp, port_no)) {
2281         unixctl_command_reply_error(conn, "port number already in use");
2282         goto exit;
2283     }
2284     hmap_remove(&dp->ports, &port->node);
2285     port->port_no = port_no;
2286     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
2287     seq_change(dp->port_seq);
2288     unixctl_command_reply(conn, NULL);
2289
2290 exit:
2291     ovs_rwlock_unlock(&dp->port_rwlock);
2292     dp_netdev_unref(dp);
2293 }
2294
2295 static void
2296 dpif_dummy_register__(const char *type)
2297 {
2298     struct dpif_class *class;
2299
2300     class = xmalloc(sizeof *class);
2301     *class = dpif_netdev_class;
2302     class->type = xstrdup(type);
2303     dp_register_provider(class);
2304 }
2305
2306 void
2307 dpif_dummy_register(bool override)
2308 {
2309     if (override) {
2310         struct sset types;
2311         const char *type;
2312
2313         sset_init(&types);
2314         dp_enumerate_types(&types);
2315         SSET_FOR_EACH (type, &types) {
2316             if (!dp_unregister_provider(type)) {
2317                 dpif_dummy_register__(type);
2318             }
2319         }
2320         sset_destroy(&types);
2321     }
2322
2323     dpif_dummy_register__("dummy");
2324
2325     unixctl_command_register("dpif-dummy/change-port-number",
2326                              "DP PORT NEW-NUMBER",
2327                              3, 3, dpif_dummy_change_port_number, NULL);
2328 }
2329