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