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