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