dpif-netdev: Delete packet if not able to do upcall
[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 "flow.h"
42 #include "hmap.h"
43 #include "latch.h"
44 #include "list.h"
45 #include "meta-flow.h"
46 #include "netdev.h"
47 #include "netdev-dpdk.h"
48 #include "netdev-vport.h"
49 #include "netlink.h"
50 #include "odp-execute.h"
51 #include "odp-util.h"
52 #include "ofp-print.h"
53 #include "ofpbuf.h"
54 #include "ovs-rcu.h"
55 #include "packet-dpif.h"
56 #include "packets.h"
57 #include "poll-loop.h"
58 #include "random.h"
59 #include "seq.h"
60 #include "shash.h"
61 #include "sset.h"
62 #include "timeval.h"
63 #include "unixctl.h"
64 #include "util.h"
65 #include "vlog.h"
66
67 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
68
69 /* By default, choose a priority in the middle. */
70 #define NETDEV_RULE_PRIORITY 0x8000
71
72 #define NR_THREADS 1
73 /* Use per thread recirc_depth to prevent recirculation loop. */
74 #define MAX_RECIRC_DEPTH 5
75 DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
76
77 /* Configuration parameters. */
78 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
79
80 /* Queues. */
81 enum { MAX_QUEUE_LEN = 128 };   /* Maximum number of packets per queue. */
82 enum { QUEUE_MASK = MAX_QUEUE_LEN - 1 };
83 BUILD_ASSERT_DECL(IS_POW2(MAX_QUEUE_LEN));
84
85 /* Protects against changes to 'dp_netdevs'. */
86 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
87
88 /* Contains all 'struct dp_netdev's. */
89 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
90     = SHASH_INITIALIZER(&dp_netdevs);
91
92 struct dp_netdev_upcall {
93     struct dpif_upcall upcall;  /* Queued upcall information. */
94     struct ofpbuf buf;          /* ofpbuf instance for upcall.packet. */
95 };
96
97 /* A queue passing packets from a struct dp_netdev to its clients (handlers).
98  *
99  *
100  * Thread-safety
101  * =============
102  *
103  * Any access at all requires the owning 'dp_netdev''s queue_rwlock and
104  * its own mutex. */
105 struct dp_netdev_queue {
106     struct ovs_mutex mutex;
107     struct seq *seq;      /* Incremented whenever a packet is queued. */
108     struct dp_netdev_upcall upcalls[MAX_QUEUE_LEN] OVS_GUARDED;
109     unsigned int head OVS_GUARDED;
110     unsigned int tail OVS_GUARDED;
111 };
112
113 /* Datapath based on the network device interface from netdev.h.
114  *
115  *
116  * Thread-safety
117  * =============
118  *
119  * Some members, marked 'const', are immutable.  Accessing other members
120  * requires synchronization, as noted in more detail below.
121  *
122  * Acquisition order is, from outermost to innermost:
123  *
124  *    dp_netdev_mutex (global)
125  *    port_mutex
126  *    flow_mutex
127  *    cls.rwlock
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      * Readers of 'cls' and 'flow_table' must take a 'cls->rwlock' read lock.
139      *
140      * Writers of 'cls' and 'flow_table' must take the 'flow_mutex' and then
141      * the 'cls->rwlock' write lock.  (The outer 'flow_mutex' allows writers to
142      * atomically perform multiple operations on 'cls' and 'flow_table'.)
143      */
144     struct ovs_mutex flow_mutex;
145     struct classifier cls;      /* Classifier.  Protected by cls.rwlock. */
146     struct hmap flow_table OVS_GUARDED; /* Flow table. */
147
148     /* Queues.
149      *
150      * 'queue_rwlock' protects the modification of 'handler_queues' and
151      * 'n_handlers'.  The queue elements are protected by its
152      * 'handler_queues''s mutex. */
153     struct fat_rwlock queue_rwlock;
154     struct dp_netdev_queue *handler_queues;
155     uint32_t n_handlers;
156
157     /* Statistics.
158      *
159      * ovsthread_stats is internally synchronized. */
160     struct ovsthread_stats stats; /* Contains 'struct dp_netdev_stats *'. */
161
162     /* Ports.
163      *
164      * Protected by RCU.  Take the mutex to add or remove ports. */
165     struct ovs_mutex port_mutex;
166     struct cmap ports;
167     struct seq *port_seq;       /* Incremented whenever a port changes. */
168
169     /* Forwarding threads. */
170     struct latch exit_latch;
171     struct pmd_thread *pmd_threads;
172     size_t n_pmd_threads;
173     int pmd_count;
174 };
175
176 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
177                                                     odp_port_t);
178
179 enum dp_stat_type {
180     DP_STAT_HIT,                /* Packets that matched in the flow table. */
181     DP_STAT_MISS,               /* Packets that did not match. */
182     DP_STAT_LOST,               /* Packets not passed up to the client. */
183     DP_N_STATS
184 };
185
186 /* Contained by struct dp_netdev's 'stats' member.  */
187 struct dp_netdev_stats {
188     struct ovs_mutex mutex;          /* Protects 'n'. */
189
190     /* Indexed by DP_STAT_*, protected by 'mutex'. */
191     unsigned long long int n[DP_N_STATS] OVS_GUARDED;
192 };
193
194
195 /* A port in a netdev-based datapath. */
196 struct dp_netdev_port {
197     struct cmap_node node;      /* Node in dp_netdev's 'ports'. */
198     odp_port_t port_no;
199     struct netdev *netdev;
200     struct netdev_saved_flags *sf;
201     struct netdev_rxq **rxq;
202     struct ovs_refcount ref_cnt;
203     char *type;                 /* Port type as requested by user. */
204 };
205
206
207 /* Stores a miniflow */
208
209 /* There are fields in the flow structure that we never use. Therefore we can
210  * save a few words of memory */
211 #define NETDEV_KEY_BUF_SIZE_U32 (FLOW_U32S \
212                                  - FLOW_U32_SIZE(regs) \
213                                  - FLOW_U32_SIZE(metadata) \
214                                 )
215 struct netdev_flow_key {
216     struct miniflow flow;
217     uint32_t buf[NETDEV_KEY_BUF_SIZE_U32];
218 };
219
220 /* A flow in dp_netdev's 'flow_table'.
221  *
222  *
223  * Thread-safety
224  * =============
225  *
226  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
227  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
228  *
229  * Motivation
230  * ----------
231  *
232  * The thread safety rules described here for "struct dp_netdev_flow" are
233  * motivated by two goals:
234  *
235  *    - Prevent threads that read members of "struct dp_netdev_flow" from
236  *      reading bad data due to changes by some thread concurrently modifying
237  *      those members.
238  *
239  *    - Prevent two threads making changes to members of a given "struct
240  *      dp_netdev_flow" from interfering with each other.
241  *
242  *
243  * Rules
244  * -----
245  *
246  * A flow 'flow' may be accessed without a risk of being freed by code that
247  * holds a read-lock or write-lock on 'cls->rwlock' or that owns a reference to
248  * 'flow->ref_cnt' (or both).  Code that needs to hold onto a flow for a while
249  * should take 'cls->rwlock', find the flow it needs, increment 'flow->ref_cnt'
250  * with dpif_netdev_flow_ref(), and drop 'cls->rwlock'.
251  *
252  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
253  * flow from being deleted from 'cls' (that's 'cls->rwlock') and it doesn't
254  * protect members of 'flow' from modification.
255  *
256  * Some members, marked 'const', are immutable.  Accessing other members
257  * requires synchronization, as noted in more detail below.
258  */
259 struct dp_netdev_flow {
260     /* Packet classification. */
261     const struct cls_rule cr;   /* In owning dp_netdev's 'cls'. */
262
263     /* Hash table index by unmasked flow. */
264     const struct hmap_node node; /* In owning dp_netdev's 'flow_table'. */
265     const struct flow flow;      /* The flow that created this entry. */
266
267     /* Statistics.
268      *
269      * Reading or writing these members requires 'mutex'. */
270     struct ovsthread_stats stats; /* Contains "struct dp_netdev_flow_stats". */
271
272     /* Actions. */
273     OVSRCU_TYPE(struct dp_netdev_actions *) actions;
274 };
275
276 static void dp_netdev_flow_free(struct dp_netdev_flow *);
277
278 /* Contained by struct dp_netdev_flow's 'stats' member.  */
279 struct dp_netdev_flow_stats {
280     struct ovs_mutex mutex;         /* Guards all the other members. */
281
282     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
283     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
284     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
285     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
286 };
287
288 /* A set of datapath actions within a "struct dp_netdev_flow".
289  *
290  *
291  * Thread-safety
292  * =============
293  *
294  * A struct dp_netdev_actions 'actions' is protected with RCU. */
295 struct dp_netdev_actions {
296     /* These members are immutable: they do not change during the struct's
297      * lifetime.  */
298     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
299     unsigned int size;          /* Size of 'actions', in bytes. */
300 };
301
302 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
303                                                    size_t);
304 struct dp_netdev_actions *dp_netdev_flow_get_actions(
305     const struct dp_netdev_flow *);
306 static void dp_netdev_actions_free(struct dp_netdev_actions *);
307
308 /* PMD: Poll modes drivers.  PMD accesses devices via polling to eliminate
309  * the performance overhead of interrupt processing.  Therefore netdev can
310  * not implement rx-wait for these devices.  dpif-netdev needs to poll
311  * these device to check for recv buffer.  pmd-thread does polling for
312  * devices assigned to itself thread.
313  *
314  * DPDK used PMD for accessing NIC.
315  *
316  * A thread that receives packets from PMD ports, looks them up in the flow
317  * table, and executes the actions it finds.
318  **/
319 struct pmd_thread {
320     struct dp_netdev *dp;
321     pthread_t thread;
322     int id;
323     atomic_uint change_seq;
324 };
325
326 /* Interface to netdev-based datapath. */
327 struct dpif_netdev {
328     struct dpif dpif;
329     struct dp_netdev *dp;
330     uint64_t last_port_seq;
331 };
332
333 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
334                               struct dp_netdev_port **portp);
335 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
336                             struct dp_netdev_port **portp);
337 static void dp_netdev_free(struct dp_netdev *)
338     OVS_REQUIRES(dp_netdev_mutex);
339 static void dp_netdev_flow_flush(struct dp_netdev *);
340 static int do_add_port(struct dp_netdev *dp, const char *devname,
341                        const char *type, odp_port_t port_no)
342     OVS_REQUIRES(dp->port_mutex);
343 static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
344     OVS_REQUIRES(dp->port_mutex);
345 static void dp_netdev_destroy_all_queues(struct dp_netdev *dp)
346     OVS_REQ_WRLOCK(dp->queue_rwlock);
347 static int dpif_netdev_open(const struct dpif_class *, const char *name,
348                             bool create, struct dpif **);
349 static int dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf **,
350                                       int cnt, int queue_no, int type,
351                                       const struct miniflow *,
352                                       const struct nlattr *userdata);
353 static void dp_netdev_execute_actions(struct dp_netdev *dp,
354                                       struct dpif_packet **, int c,
355                                       bool may_steal, struct pkt_metadata *,
356                                       const struct nlattr *actions,
357                                       size_t actions_len);
358 static void dp_netdev_port_input(struct dp_netdev *dp,
359                                  struct dpif_packet **packets, int cnt,
360                                  odp_port_t port_no);
361
362 static void dp_netdev_set_pmd_threads(struct dp_netdev *, int n);
363
364 static struct dpif_netdev *
365 dpif_netdev_cast(const struct dpif *dpif)
366 {
367     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
368     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
369 }
370
371 static struct dp_netdev *
372 get_dp_netdev(const struct dpif *dpif)
373 {
374     return dpif_netdev_cast(dpif)->dp;
375 }
376
377 static int
378 dpif_netdev_enumerate(struct sset *all_dps,
379                       const struct dpif_class *dpif_class)
380 {
381     struct shash_node *node;
382
383     ovs_mutex_lock(&dp_netdev_mutex);
384     SHASH_FOR_EACH(node, &dp_netdevs) {
385         struct dp_netdev *dp = node->data;
386         if (dpif_class != dp->class) {
387             /* 'dp_netdevs' contains both "netdev" and "dummy" dpifs.
388              * If the class doesn't match, skip this dpif. */
389              continue;
390         }
391         sset_add(all_dps, node->name);
392     }
393     ovs_mutex_unlock(&dp_netdev_mutex);
394
395     return 0;
396 }
397
398 static bool
399 dpif_netdev_class_is_dummy(const struct dpif_class *class)
400 {
401     return class != &dpif_netdev_class;
402 }
403
404 static const char *
405 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
406 {
407     return strcmp(type, "internal") ? type
408                   : dpif_netdev_class_is_dummy(class) ? "dummy"
409                   : "tap";
410 }
411
412 static struct dpif *
413 create_dpif_netdev(struct dp_netdev *dp)
414 {
415     uint16_t netflow_id = hash_string(dp->name, 0);
416     struct dpif_netdev *dpif;
417
418     ovs_refcount_ref(&dp->ref_cnt);
419
420     dpif = xmalloc(sizeof *dpif);
421     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
422     dpif->dp = dp;
423     dpif->last_port_seq = seq_read(dp->port_seq);
424
425     return &dpif->dpif;
426 }
427
428 /* Choose an unused, non-zero port number and return it on success.
429  * Return ODPP_NONE on failure. */
430 static odp_port_t
431 choose_port(struct dp_netdev *dp, const char *name)
432     OVS_REQUIRES(dp->port_mutex)
433 {
434     uint32_t port_no;
435
436     if (dp->class != &dpif_netdev_class) {
437         const char *p;
438         int start_no = 0;
439
440         /* If the port name begins with "br", start the number search at
441          * 100 to make writing tests easier. */
442         if (!strncmp(name, "br", 2)) {
443             start_no = 100;
444         }
445
446         /* If the port name contains a number, try to assign that port number.
447          * This can make writing unit tests easier because port numbers are
448          * predictable. */
449         for (p = name; *p != '\0'; p++) {
450             if (isdigit((unsigned char) *p)) {
451                 port_no = start_no + strtol(p, NULL, 10);
452                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
453                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
454                     return u32_to_odp(port_no);
455                 }
456                 break;
457             }
458         }
459     }
460
461     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
462         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
463             return u32_to_odp(port_no);
464         }
465     }
466
467     return ODPP_NONE;
468 }
469
470 static int
471 create_dp_netdev(const char *name, const struct dpif_class *class,
472                  struct dp_netdev **dpp)
473     OVS_REQUIRES(dp_netdev_mutex)
474 {
475     struct dp_netdev *dp;
476     int error;
477
478     dp = xzalloc(sizeof *dp);
479     shash_add(&dp_netdevs, name, dp);
480
481     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
482     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
483     ovs_refcount_init(&dp->ref_cnt);
484     atomic_flag_clear(&dp->destroyed);
485
486     ovs_mutex_init(&dp->flow_mutex);
487     classifier_init(&dp->cls, NULL);
488     hmap_init(&dp->flow_table);
489
490     fat_rwlock_init(&dp->queue_rwlock);
491
492     ovsthread_stats_init(&dp->stats);
493
494     ovs_mutex_init(&dp->port_mutex);
495     cmap_init(&dp->ports);
496     dp->port_seq = seq_create();
497     latch_init(&dp->exit_latch);
498
499     ovs_mutex_lock(&dp->port_mutex);
500     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
501     ovs_mutex_unlock(&dp->port_mutex);
502     if (error) {
503         dp_netdev_free(dp);
504         return error;
505     }
506
507     *dpp = dp;
508     return 0;
509 }
510
511 static int
512 dpif_netdev_open(const struct dpif_class *class, const char *name,
513                  bool create, struct dpif **dpifp)
514 {
515     struct dp_netdev *dp;
516     int error;
517
518     ovs_mutex_lock(&dp_netdev_mutex);
519     dp = shash_find_data(&dp_netdevs, name);
520     if (!dp) {
521         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
522     } else {
523         error = (dp->class != class ? EINVAL
524                  : create ? EEXIST
525                  : 0);
526     }
527     if (!error) {
528         *dpifp = create_dpif_netdev(dp);
529     }
530     ovs_mutex_unlock(&dp_netdev_mutex);
531
532     return error;
533 }
534
535 static void
536 dp_netdev_purge_queues(struct dp_netdev *dp)
537     OVS_REQ_WRLOCK(dp->queue_rwlock)
538 {
539     int i;
540
541     for (i = 0; i < dp->n_handlers; i++) {
542         struct dp_netdev_queue *q = &dp->handler_queues[i];
543
544         ovs_mutex_lock(&q->mutex);
545         while (q->tail != q->head) {
546             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
547             ofpbuf_uninit(&u->upcall.packet);
548             ofpbuf_uninit(&u->buf);
549         }
550         ovs_mutex_unlock(&q->mutex);
551     }
552 }
553
554 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
555  * through the 'dp_netdevs' shash while freeing 'dp'. */
556 static void
557 dp_netdev_free(struct dp_netdev *dp)
558     OVS_REQUIRES(dp_netdev_mutex)
559 {
560     struct dp_netdev_port *port;
561     struct dp_netdev_stats *bucket;
562     int i;
563
564     shash_find_and_delete(&dp_netdevs, dp->name);
565
566     dp_netdev_set_pmd_threads(dp, 0);
567     free(dp->pmd_threads);
568
569     dp_netdev_flow_flush(dp);
570     ovs_mutex_lock(&dp->port_mutex);
571     CMAP_FOR_EACH (port, node, &dp->ports) {
572         do_del_port(dp, port);
573     }
574     ovs_mutex_unlock(&dp->port_mutex);
575
576     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
577         ovs_mutex_destroy(&bucket->mutex);
578         free_cacheline(bucket);
579     }
580     ovsthread_stats_destroy(&dp->stats);
581
582     fat_rwlock_wrlock(&dp->queue_rwlock);
583     dp_netdev_destroy_all_queues(dp);
584     fat_rwlock_unlock(&dp->queue_rwlock);
585
586     fat_rwlock_destroy(&dp->queue_rwlock);
587
588     classifier_destroy(&dp->cls);
589     hmap_destroy(&dp->flow_table);
590     ovs_mutex_destroy(&dp->flow_mutex);
591     seq_destroy(dp->port_seq);
592     cmap_destroy(&dp->ports);
593     latch_destroy(&dp->exit_latch);
594     free(CONST_CAST(char *, dp->name));
595     free(dp);
596 }
597
598 static void
599 dp_netdev_unref(struct dp_netdev *dp)
600 {
601     if (dp) {
602         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
603          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
604         ovs_mutex_lock(&dp_netdev_mutex);
605         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
606             dp_netdev_free(dp);
607         }
608         ovs_mutex_unlock(&dp_netdev_mutex);
609     }
610 }
611
612 static void
613 dpif_netdev_close(struct dpif *dpif)
614 {
615     struct dp_netdev *dp = get_dp_netdev(dpif);
616
617     dp_netdev_unref(dp);
618     free(dpif);
619 }
620
621 static int
622 dpif_netdev_destroy(struct dpif *dpif)
623 {
624     struct dp_netdev *dp = get_dp_netdev(dpif);
625
626     if (!atomic_flag_test_and_set(&dp->destroyed)) {
627         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
628             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
629             OVS_NOT_REACHED();
630         }
631     }
632
633     return 0;
634 }
635
636 static int
637 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
638 {
639     struct dp_netdev *dp = get_dp_netdev(dpif);
640     struct dp_netdev_stats *bucket;
641     size_t i;
642
643     fat_rwlock_rdlock(&dp->cls.rwlock);
644     stats->n_flows = hmap_count(&dp->flow_table);
645     fat_rwlock_unlock(&dp->cls.rwlock);
646
647     stats->n_hit = stats->n_missed = stats->n_lost = 0;
648     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &dp->stats) {
649         ovs_mutex_lock(&bucket->mutex);
650         stats->n_hit += bucket->n[DP_STAT_HIT];
651         stats->n_missed += bucket->n[DP_STAT_MISS];
652         stats->n_lost += bucket->n[DP_STAT_LOST];
653         ovs_mutex_unlock(&bucket->mutex);
654     }
655     stats->n_masks = UINT32_MAX;
656     stats->n_mask_hit = UINT64_MAX;
657
658     return 0;
659 }
660
661 static void
662 dp_netdev_reload_pmd_threads(struct dp_netdev *dp)
663 {
664     int i;
665
666     for (i = 0; i < dp->n_pmd_threads; i++) {
667         struct pmd_thread *f = &dp->pmd_threads[i];
668         int id;
669
670         atomic_add(&f->change_seq, 1, &id);
671    }
672 }
673
674 static uint32_t
675 hash_port_no(odp_port_t port_no)
676 {
677     return hash_int(odp_to_u32(port_no), 0);
678 }
679
680 static int
681 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
682             odp_port_t port_no)
683     OVS_REQUIRES(dp->port_mutex)
684 {
685     struct netdev_saved_flags *sf;
686     struct dp_netdev_port *port;
687     struct netdev *netdev;
688     enum netdev_flags flags;
689     const char *open_type;
690     int error;
691     int i;
692
693     /* XXX reject devices already in some dp_netdev. */
694
695     /* Open and validate network device. */
696     open_type = dpif_netdev_port_open_type(dp->class, type);
697     error = netdev_open(devname, open_type, &netdev);
698     if (error) {
699         return error;
700     }
701     /* XXX reject non-Ethernet devices */
702
703     netdev_get_flags(netdev, &flags);
704     if (flags & NETDEV_LOOPBACK) {
705         VLOG_ERR("%s: cannot add a loopback device", devname);
706         netdev_close(netdev);
707         return EINVAL;
708     }
709
710     port = xzalloc(sizeof *port);
711     port->port_no = port_no;
712     port->netdev = netdev;
713     port->rxq = xmalloc(sizeof *port->rxq * netdev_n_rxq(netdev));
714     port->type = xstrdup(type);
715     for (i = 0; i < netdev_n_rxq(netdev); i++) {
716         error = netdev_rxq_open(netdev, &port->rxq[i], i);
717         if (error
718             && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
719             VLOG_ERR("%s: cannot receive packets on this network device (%s)",
720                      devname, ovs_strerror(errno));
721             netdev_close(netdev);
722             return error;
723         }
724     }
725
726     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
727     if (error) {
728         for (i = 0; i < netdev_n_rxq(netdev); i++) {
729             netdev_rxq_close(port->rxq[i]);
730         }
731         netdev_close(netdev);
732         free(port->rxq);
733         free(port);
734         return error;
735     }
736     port->sf = sf;
737
738     if (netdev_is_pmd(netdev)) {
739         dp->pmd_count++;
740         dp_netdev_set_pmd_threads(dp, NR_THREADS);
741         dp_netdev_reload_pmd_threads(dp);
742     }
743     ovs_refcount_init(&port->ref_cnt);
744
745     cmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
746     seq_change(dp->port_seq);
747
748     return 0;
749 }
750
751 static int
752 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
753                      odp_port_t *port_nop)
754 {
755     struct dp_netdev *dp = get_dp_netdev(dpif);
756     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
757     const char *dpif_port;
758     odp_port_t port_no;
759     int error;
760
761     ovs_mutex_lock(&dp->port_mutex);
762     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
763     if (*port_nop != ODPP_NONE) {
764         port_no = *port_nop;
765         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
766     } else {
767         port_no = choose_port(dp, dpif_port);
768         error = port_no == ODPP_NONE ? EFBIG : 0;
769     }
770     if (!error) {
771         *port_nop = port_no;
772         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
773     }
774     ovs_mutex_unlock(&dp->port_mutex);
775
776     return error;
777 }
778
779 static int
780 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
781 {
782     struct dp_netdev *dp = get_dp_netdev(dpif);
783     int error;
784
785     ovs_mutex_lock(&dp->port_mutex);
786     if (port_no == ODPP_LOCAL) {
787         error = EINVAL;
788     } else {
789         struct dp_netdev_port *port;
790
791         error = get_port_by_number(dp, port_no, &port);
792         if (!error) {
793             do_del_port(dp, port);
794         }
795     }
796     ovs_mutex_unlock(&dp->port_mutex);
797
798     return error;
799 }
800
801 static bool
802 is_valid_port_number(odp_port_t port_no)
803 {
804     return port_no != ODPP_NONE;
805 }
806
807 static struct dp_netdev_port *
808 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
809 {
810     struct dp_netdev_port *port;
811
812     CMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
813         if (port->port_no == port_no) {
814             return port;
815         }
816     }
817     return NULL;
818 }
819
820 static int
821 get_port_by_number(struct dp_netdev *dp,
822                    odp_port_t port_no, struct dp_netdev_port **portp)
823 {
824     if (!is_valid_port_number(port_no)) {
825         *portp = NULL;
826         return EINVAL;
827     } else {
828         *portp = dp_netdev_lookup_port(dp, port_no);
829         return *portp ? 0 : ENOENT;
830     }
831 }
832
833 static void
834 port_ref(struct dp_netdev_port *port)
835 {
836     if (port) {
837         ovs_refcount_ref(&port->ref_cnt);
838     }
839 }
840
841 static void
842 port_destroy__(struct dp_netdev_port *port)
843 {
844     int n_rxq = netdev_n_rxq(port->netdev);
845     int i;
846
847     netdev_close(port->netdev);
848     netdev_restore_flags(port->sf);
849
850     for (i = 0; i < n_rxq; i++) {
851         netdev_rxq_close(port->rxq[i]);
852     }
853     free(port->rxq);
854     free(port->type);
855     free(port);
856 }
857
858 static void
859 port_unref(struct dp_netdev_port *port)
860 {
861     if (port && ovs_refcount_unref(&port->ref_cnt) == 1) {
862         ovsrcu_postpone(port_destroy__, port);
863     }
864 }
865
866 static int
867 get_port_by_name(struct dp_netdev *dp,
868                  const char *devname, struct dp_netdev_port **portp)
869     OVS_REQUIRES(dp->port_mutex)
870 {
871     struct dp_netdev_port *port;
872
873     CMAP_FOR_EACH (port, node, &dp->ports) {
874         if (!strcmp(netdev_get_name(port->netdev), devname)) {
875             *portp = port;
876             return 0;
877         }
878     }
879     return ENOENT;
880 }
881
882 static void
883 do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
884     OVS_REQUIRES(dp->port_mutex)
885 {
886     cmap_remove(&dp->ports, &port->node, hash_odp_port(port->port_no));
887     seq_change(dp->port_seq);
888     if (netdev_is_pmd(port->netdev)) {
889         dp_netdev_reload_pmd_threads(dp);
890     }
891
892     port_unref(port);
893 }
894
895 static void
896 answer_port_query(const struct dp_netdev_port *port,
897                   struct dpif_port *dpif_port)
898 {
899     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
900     dpif_port->type = xstrdup(port->type);
901     dpif_port->port_no = port->port_no;
902 }
903
904 static int
905 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
906                                  struct dpif_port *dpif_port)
907 {
908     struct dp_netdev *dp = get_dp_netdev(dpif);
909     struct dp_netdev_port *port;
910     int error;
911
912     error = get_port_by_number(dp, port_no, &port);
913     if (!error && dpif_port) {
914         answer_port_query(port, dpif_port);
915     }
916
917     return error;
918 }
919
920 static int
921 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
922                                struct dpif_port *dpif_port)
923 {
924     struct dp_netdev *dp = get_dp_netdev(dpif);
925     struct dp_netdev_port *port;
926     int error;
927
928     ovs_mutex_lock(&dp->port_mutex);
929     error = get_port_by_name(dp, devname, &port);
930     if (!error && dpif_port) {
931         answer_port_query(port, dpif_port);
932     }
933     ovs_mutex_unlock(&dp->port_mutex);
934
935     return error;
936 }
937
938 static void
939 dp_netdev_flow_free(struct dp_netdev_flow *flow)
940 {
941     struct dp_netdev_flow_stats *bucket;
942     size_t i;
943
944     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &flow->stats) {
945         ovs_mutex_destroy(&bucket->mutex);
946         free_cacheline(bucket);
947     }
948     ovsthread_stats_destroy(&flow->stats);
949
950     cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
951     dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
952     free(flow);
953 }
954
955 static void
956 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
957     OVS_REQ_WRLOCK(dp->cls.rwlock)
958     OVS_REQUIRES(dp->flow_mutex)
959 {
960     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
961     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
962
963     classifier_remove(&dp->cls, cr);
964     hmap_remove(&dp->flow_table, node);
965     ovsrcu_postpone(dp_netdev_flow_free, flow);
966 }
967
968 static void
969 dp_netdev_flow_flush(struct dp_netdev *dp)
970 {
971     struct dp_netdev_flow *netdev_flow, *next;
972
973     ovs_mutex_lock(&dp->flow_mutex);
974     fat_rwlock_wrlock(&dp->cls.rwlock);
975     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
976         dp_netdev_remove_flow(dp, netdev_flow);
977     }
978     fat_rwlock_unlock(&dp->cls.rwlock);
979     ovs_mutex_unlock(&dp->flow_mutex);
980 }
981
982 static int
983 dpif_netdev_flow_flush(struct dpif *dpif)
984 {
985     struct dp_netdev *dp = get_dp_netdev(dpif);
986
987     dp_netdev_flow_flush(dp);
988     return 0;
989 }
990
991 struct dp_netdev_port_state {
992     struct cmap_position position;
993     char *name;
994 };
995
996 static int
997 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
998 {
999     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
1000     return 0;
1001 }
1002
1003 static int
1004 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
1005                            struct dpif_port *dpif_port)
1006 {
1007     struct dp_netdev_port_state *state = state_;
1008     struct dp_netdev *dp = get_dp_netdev(dpif);
1009     struct cmap_node *node;
1010     int retval;
1011
1012     node = cmap_next_position(&dp->ports, &state->position);
1013     if (node) {
1014         struct dp_netdev_port *port;
1015
1016         port = CONTAINER_OF(node, struct dp_netdev_port, node);
1017
1018         free(state->name);
1019         state->name = xstrdup(netdev_get_name(port->netdev));
1020         dpif_port->name = state->name;
1021         dpif_port->type = port->type;
1022         dpif_port->port_no = port->port_no;
1023
1024         retval = 0;
1025     } else {
1026         retval = EOF;
1027     }
1028
1029     return retval;
1030 }
1031
1032 static int
1033 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1034 {
1035     struct dp_netdev_port_state *state = state_;
1036     free(state->name);
1037     free(state);
1038     return 0;
1039 }
1040
1041 static int
1042 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
1043 {
1044     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1045     uint64_t new_port_seq;
1046     int error;
1047
1048     new_port_seq = seq_read(dpif->dp->port_seq);
1049     if (dpif->last_port_seq != new_port_seq) {
1050         dpif->last_port_seq = new_port_seq;
1051         error = ENOBUFS;
1052     } else {
1053         error = EAGAIN;
1054     }
1055
1056     return error;
1057 }
1058
1059 static void
1060 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
1061 {
1062     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
1063
1064     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
1065 }
1066
1067 static struct dp_netdev_flow *
1068 dp_netdev_flow_cast(const struct cls_rule *cr)
1069 {
1070     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
1071 }
1072
1073 static struct dp_netdev_flow *
1074 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct miniflow *key)
1075     OVS_EXCLUDED(dp->cls.rwlock)
1076 {
1077     struct dp_netdev_flow *netdev_flow;
1078     struct cls_rule *rule;
1079
1080     fat_rwlock_rdlock(&dp->cls.rwlock);
1081     rule = classifier_lookup_miniflow_first(&dp->cls, key);
1082     netdev_flow = dp_netdev_flow_cast(rule);
1083     fat_rwlock_unlock(&dp->cls.rwlock);
1084
1085     return netdev_flow;
1086 }
1087
1088 static struct dp_netdev_flow *
1089 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1090     OVS_REQ_RDLOCK(dp->cls.rwlock)
1091 {
1092     struct dp_netdev_flow *netdev_flow;
1093
1094     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1095                              &dp->flow_table) {
1096         if (flow_equal(&netdev_flow->flow, flow)) {
1097             return netdev_flow;
1098         }
1099     }
1100
1101     return NULL;
1102 }
1103
1104 static void
1105 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1106                     struct dpif_flow_stats *stats)
1107 {
1108     struct dp_netdev_flow_stats *bucket;
1109     size_t i;
1110
1111     memset(stats, 0, sizeof *stats);
1112     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1113         ovs_mutex_lock(&bucket->mutex);
1114         stats->n_packets += bucket->packet_count;
1115         stats->n_bytes += bucket->byte_count;
1116         stats->used = MAX(stats->used, bucket->used);
1117         stats->tcp_flags |= bucket->tcp_flags;
1118         ovs_mutex_unlock(&bucket->mutex);
1119     }
1120 }
1121
1122 static int
1123 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1124                               const struct nlattr *mask_key,
1125                               uint32_t mask_key_len, const struct flow *flow,
1126                               struct flow *mask)
1127 {
1128     if (mask_key_len) {
1129         enum odp_key_fitness fitness;
1130
1131         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1132         if (fitness) {
1133             /* This should not happen: it indicates that
1134              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1135              * disagree on the acceptable form of a mask.  Log the problem
1136              * as an error, with enough details to enable debugging. */
1137             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1138
1139             if (!VLOG_DROP_ERR(&rl)) {
1140                 struct ds s;
1141
1142                 ds_init(&s);
1143                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1144                                 true);
1145                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1146                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1147                 ds_destroy(&s);
1148             }
1149
1150             return EINVAL;
1151         }
1152     } else {
1153         enum mf_field_id id;
1154         /* No mask key, unwildcard everything except fields whose
1155          * prerequisities are not met. */
1156         memset(mask, 0x0, sizeof *mask);
1157
1158         for (id = 0; id < MFF_N_IDS; ++id) {
1159             /* Skip registers and metadata. */
1160             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1161                 && id != MFF_METADATA) {
1162                 const struct mf_field *mf = mf_from_id(id);
1163                 if (mf_are_prereqs_ok(mf, flow)) {
1164                     mf_mask_field(mf, mask);
1165                 }
1166             }
1167         }
1168     }
1169
1170     /* Force unwildcard the in_port.
1171      *
1172      * We need to do this even in the case where we unwildcard "everything"
1173      * above because "everything" only includes the 16-bit OpenFlow port number
1174      * mask->in_port.ofp_port, which only covers half of the 32-bit datapath
1175      * port number mask->in_port.odp_port. */
1176     mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1177
1178     return 0;
1179 }
1180
1181 static int
1182 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1183                               struct flow *flow)
1184 {
1185     odp_port_t in_port;
1186
1187     if (odp_flow_key_to_flow(key, key_len, flow)) {
1188         /* This should not happen: it indicates that odp_flow_key_from_flow()
1189          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1190          * flow.  Log the problem as an error, with enough details to enable
1191          * debugging. */
1192         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1193
1194         if (!VLOG_DROP_ERR(&rl)) {
1195             struct ds s;
1196
1197             ds_init(&s);
1198             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1199             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1200             ds_destroy(&s);
1201         }
1202
1203         return EINVAL;
1204     }
1205
1206     in_port = flow->in_port.odp_port;
1207     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1208         return EINVAL;
1209     }
1210
1211     return 0;
1212 }
1213
1214 static int
1215 dpif_netdev_flow_get(const struct dpif *dpif,
1216                      const struct nlattr *nl_key, size_t nl_key_len,
1217                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1218 {
1219     struct dp_netdev *dp = get_dp_netdev(dpif);
1220     struct dp_netdev_flow *netdev_flow;
1221     struct flow key;
1222     int error;
1223
1224     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1225     if (error) {
1226         return error;
1227     }
1228
1229     fat_rwlock_rdlock(&dp->cls.rwlock);
1230     netdev_flow = dp_netdev_find_flow(dp, &key);
1231     fat_rwlock_unlock(&dp->cls.rwlock);
1232
1233     if (netdev_flow) {
1234         if (stats) {
1235             get_dpif_flow_stats(netdev_flow, stats);
1236         }
1237
1238         if (actionsp) {
1239             struct dp_netdev_actions *actions;
1240
1241             actions = dp_netdev_flow_get_actions(netdev_flow);
1242             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1243         }
1244      } else {
1245         error = ENOENT;
1246     }
1247
1248     return error;
1249 }
1250
1251 static int
1252 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1253                    const struct flow_wildcards *wc,
1254                    const struct nlattr *actions,
1255                    size_t actions_len)
1256     OVS_REQUIRES(dp->flow_mutex)
1257 {
1258     struct dp_netdev_flow *netdev_flow;
1259     struct match match;
1260
1261     netdev_flow = xzalloc(sizeof *netdev_flow);
1262     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1263
1264     ovsthread_stats_init(&netdev_flow->stats);
1265
1266     ovsrcu_set(&netdev_flow->actions,
1267                dp_netdev_actions_create(actions, actions_len));
1268
1269     match_init(&match, flow, wc);
1270     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1271                   &match, NETDEV_RULE_PRIORITY);
1272     fat_rwlock_wrlock(&dp->cls.rwlock);
1273     classifier_insert(&dp->cls,
1274                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1275     hmap_insert(&dp->flow_table,
1276                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1277                 flow_hash(flow, 0));
1278     fat_rwlock_unlock(&dp->cls.rwlock);
1279
1280     return 0;
1281 }
1282
1283 static void
1284 clear_stats(struct dp_netdev_flow *netdev_flow)
1285 {
1286     struct dp_netdev_flow_stats *bucket;
1287     size_t i;
1288
1289     OVSTHREAD_STATS_FOR_EACH_BUCKET (bucket, i, &netdev_flow->stats) {
1290         ovs_mutex_lock(&bucket->mutex);
1291         bucket->used = 0;
1292         bucket->packet_count = 0;
1293         bucket->byte_count = 0;
1294         bucket->tcp_flags = 0;
1295         ovs_mutex_unlock(&bucket->mutex);
1296     }
1297 }
1298
1299 static int
1300 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1301 {
1302     struct dp_netdev *dp = get_dp_netdev(dpif);
1303     struct dp_netdev_flow *netdev_flow;
1304     struct flow flow;
1305     struct 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 (hmap_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
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     fat_rwlock_wrlock(&dp->cls.rwlock);
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     fat_rwlock_unlock(&dp->cls.rwlock);
1394     ovs_mutex_unlock(&dp->flow_mutex);
1395
1396     return error;
1397 }
1398
1399 struct dpif_netdev_flow_dump {
1400     struct dpif_flow_dump up;
1401     uint32_t bucket;
1402     uint32_t offset;
1403     int status;
1404     struct ovs_mutex mutex;
1405 };
1406
1407 static struct dpif_netdev_flow_dump *
1408 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
1409 {
1410     return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
1411 }
1412
1413 static struct dpif_flow_dump *
1414 dpif_netdev_flow_dump_create(const struct dpif *dpif_)
1415 {
1416     struct dpif_netdev_flow_dump *dump;
1417
1418     dump = xmalloc(sizeof *dump);
1419     dpif_flow_dump_init(&dump->up, dpif_);
1420     dump->bucket = 0;
1421     dump->offset = 0;
1422     dump->status = 0;
1423     ovs_mutex_init(&dump->mutex);
1424
1425     return &dump->up;
1426 }
1427
1428 static int
1429 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
1430 {
1431     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1432
1433     ovs_mutex_destroy(&dump->mutex);
1434     free(dump);
1435     return 0;
1436 }
1437
1438 struct dpif_netdev_flow_dump_thread {
1439     struct dpif_flow_dump_thread up;
1440     struct dpif_netdev_flow_dump *dump;
1441     struct odputil_keybuf keybuf;
1442     struct odputil_keybuf maskbuf;
1443 };
1444
1445 static struct dpif_netdev_flow_dump_thread *
1446 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1447 {
1448     return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
1449 }
1450
1451 static struct dpif_flow_dump_thread *
1452 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1453 {
1454     struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
1455     struct dpif_netdev_flow_dump_thread *thread;
1456
1457     thread = xmalloc(sizeof *thread);
1458     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1459     thread->dump = dump;
1460     return &thread->up;
1461 }
1462
1463 static void
1464 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1465 {
1466     struct dpif_netdev_flow_dump_thread *thread
1467         = dpif_netdev_flow_dump_thread_cast(thread_);
1468
1469     free(thread);
1470 }
1471
1472 /* XXX the caller must use 'actions' without quiescing */
1473 static int
1474 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1475                            struct dpif_flow *f, int max_flows OVS_UNUSED)
1476 {
1477     struct dpif_netdev_flow_dump_thread *thread
1478         = dpif_netdev_flow_dump_thread_cast(thread_);
1479     struct dpif_netdev_flow_dump *dump = thread->dump;
1480     struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
1481     struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
1482     struct dp_netdev_flow *netdev_flow;
1483     struct flow_wildcards wc;
1484     struct dp_netdev_actions *dp_actions;
1485     struct ofpbuf buf;
1486     int error;
1487
1488     ovs_mutex_lock(&dump->mutex);
1489     error = dump->status;
1490     if (!error) {
1491         struct hmap_node *node;
1492
1493         fat_rwlock_rdlock(&dp->cls.rwlock);
1494         node = hmap_at_position(&dp->flow_table, &dump->bucket, &dump->offset);
1495         if (node) {
1496             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1497         }
1498         fat_rwlock_unlock(&dp->cls.rwlock);
1499         if (!node) {
1500             dump->status = error = EOF;
1501         }
1502     }
1503     ovs_mutex_unlock(&dump->mutex);
1504     if (error) {
1505         return 0;
1506     }
1507
1508     minimask_expand(&netdev_flow->cr.match.mask, &wc);
1509
1510     /* Key. */
1511     ofpbuf_use_stack(&buf, &thread->keybuf, sizeof thread->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, &thread->maskbuf, sizeof thread->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     return 1;
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 batch_pkt_execute {
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 batch_pkt_execute *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 batch_pkt_execute *batch, struct dp_netdev_flow *flow,
2027                   struct dpif_packet *packet, struct pkt_metadata *md,
2028                   const struct miniflow *mf)
2029 {
2030     batch->flow = flow;
2031     batch->md = *md;
2032     batch->packets[0] = packet;
2033
2034     batch->packet_count = 0;
2035     batch->byte_count = 0;
2036     batch->tcp_flags = 0;
2037
2038     packet_batch_update(batch, packet, mf);
2039 }
2040
2041 static inline void
2042 packet_batch_execute(struct batch_pkt_execute *batch, struct dp_netdev *dp)
2043 {
2044     struct dp_netdev_actions *actions;
2045     struct dp_netdev_flow *flow = batch->flow;
2046
2047     dp_netdev_flow_used(batch->flow, batch->packet_count, batch->byte_count,
2048                         batch->tcp_flags);
2049
2050     actions = dp_netdev_flow_get_actions(flow);
2051
2052     dp_netdev_execute_actions(dp, batch->packets,
2053                               batch->packet_count, true, &batch->md,
2054                               actions->actions, actions->size);
2055
2056     dp_netdev_count_packet(dp, DP_STAT_HIT, batch->packet_count);
2057 }
2058
2059 static void
2060 dp_netdev_input(struct dp_netdev *dp, struct dpif_packet **packets, int cnt,
2061                 struct pkt_metadata *md)
2062 {
2063     struct batch_pkt_execute batch;
2064
2065     struct netdev_flow_key key;
2066
2067     int i;
2068
2069     batch.flow = NULL;
2070
2071     miniflow_initialize(&key.flow, key.buf);
2072
2073     for (i = 0; i < cnt; i++) {
2074         struct dp_netdev_flow *netdev_flow;
2075         struct ofpbuf *buf = &packets[i]->ofpbuf;
2076
2077         if (ofpbuf_size(buf) < ETH_HEADER_LEN) {
2078             dpif_packet_delete(packets[i]);
2079             continue;
2080         }
2081
2082         miniflow_extract(buf, md, &key.flow);
2083
2084         netdev_flow = dp_netdev_lookup_flow(dp, &key.flow);
2085
2086         if (netdev_flow) {
2087             if (!batch.flow) {
2088                 packet_batch_init(&batch, netdev_flow, packets[i], md,
2089                                   &key.flow);
2090             } else if (batch.flow == netdev_flow) {
2091                 packet_batch_update(&batch, packets[i], &key.flow);
2092             } else {
2093                 packet_batch_execute(&batch, dp);
2094                 packet_batch_init(&batch, netdev_flow, packets[i], md,
2095                                   &key.flow);
2096             }
2097         } else {
2098             /* Packet's flow not in datapath */
2099             dp_netdev_count_packet(dp, DP_STAT_MISS, 1);
2100
2101             if (dp->handler_queues) {
2102                 /* Upcall */
2103                 dp_netdev_output_userspace(dp, &buf, 1,
2104                                            miniflow_hash_5tuple(&key.flow, 0)
2105                                            % dp->n_handlers,
2106                                            DPIF_UC_MISS, &key.flow, NULL);
2107             } else {
2108                 /* No upcall queue.  Freeing the packet */
2109                 dpif_packet_delete(packets[i]);
2110             }
2111         }
2112     }
2113
2114     if (batch.flow) {
2115         packet_batch_execute(&batch, dp);
2116     }
2117 }
2118
2119 static void
2120 dp_netdev_port_input(struct dp_netdev *dp, struct dpif_packet **packets,
2121                      int cnt, odp_port_t port_no)
2122 {
2123     uint32_t *recirc_depth = recirc_depth_get();
2124     struct pkt_metadata md = PKT_METADATA_INITIALIZER(port_no);
2125
2126     *recirc_depth = 0;
2127     dp_netdev_input(dp, packets, cnt, &md);
2128 }
2129
2130 static int
2131 dp_netdev_queue_userspace_packet(struct dp_netdev_queue *q,
2132                                  struct ofpbuf *packet, int type,
2133                                  const struct miniflow *key,
2134                                  const struct nlattr *userdata)
2135 OVS_REQUIRES(q->mutex)
2136 {
2137     if (q->head - q->tail < MAX_QUEUE_LEN) {
2138         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
2139         struct dpif_upcall *upcall = &u->upcall;
2140         struct ofpbuf *buf = &u->buf;
2141         size_t buf_size;
2142         struct flow flow;
2143
2144         upcall->type = type;
2145
2146         /* Allocate buffer big enough for everything. */
2147         buf_size = ODPUTIL_FLOW_KEY_BYTES;
2148         if (userdata) {
2149             buf_size += NLA_ALIGN(userdata->nla_len);
2150         }
2151         ofpbuf_init(buf, buf_size);
2152
2153         /* Put ODP flow. */
2154         miniflow_expand(key, &flow);
2155         odp_flow_key_from_flow(buf, &flow, NULL, flow.in_port.odp_port, true);
2156         upcall->key = ofpbuf_data(buf);
2157         upcall->key_len = ofpbuf_size(buf);
2158
2159         /* Put userdata. */
2160         if (userdata) {
2161             upcall->userdata = ofpbuf_put(buf, userdata,
2162                     NLA_ALIGN(userdata->nla_len));
2163         }
2164
2165         upcall->packet = *packet;
2166
2167         seq_change(q->seq);
2168
2169         return 0;
2170     } else {
2171         ofpbuf_delete(packet);
2172         return ENOBUFS;
2173     }
2174
2175 }
2176
2177 static int
2178 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf **packets,
2179                            int cnt, int queue_no, int type,
2180                            const struct miniflow *key,
2181                            const struct nlattr *userdata)
2182 {
2183     struct dp_netdev_queue *q;
2184     int error;
2185     int i;
2186
2187     fat_rwlock_rdlock(&dp->queue_rwlock);
2188     q = &dp->handler_queues[queue_no];
2189     ovs_mutex_lock(&q->mutex);
2190     for (i = 0; i < cnt; i++) {
2191         struct ofpbuf *packet = packets[i];
2192
2193         error = dp_netdev_queue_userspace_packet(q, packet, type, key,
2194                                                  userdata);
2195         if (error == ENOBUFS) {
2196             dp_netdev_count_packet(dp, DP_STAT_LOST, 1);
2197         }
2198     }
2199     ovs_mutex_unlock(&q->mutex);
2200     fat_rwlock_unlock(&dp->queue_rwlock);
2201
2202     return error;
2203 }
2204
2205 struct dp_netdev_execute_aux {
2206     struct dp_netdev *dp;
2207 };
2208
2209 static void
2210 dp_execute_cb(void *aux_, struct dpif_packet **packets, int cnt,
2211               struct pkt_metadata *md,
2212               const struct nlattr *a, bool may_steal)
2213     OVS_NO_THREAD_SAFETY_ANALYSIS
2214 {
2215     struct dp_netdev_execute_aux *aux = aux_;
2216     int type = nl_attr_type(a);
2217     struct dp_netdev_port *p;
2218     uint32_t *depth = recirc_depth_get();
2219     int i;
2220
2221     switch ((enum ovs_action_attr)type) {
2222     case OVS_ACTION_ATTR_OUTPUT:
2223         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
2224         if (p) {
2225             netdev_send(p->netdev, packets, cnt, may_steal);
2226         }
2227         break;
2228
2229     case OVS_ACTION_ATTR_USERSPACE: {
2230         const struct nlattr *userdata;
2231         struct netdev_flow_key key;
2232
2233         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
2234
2235         miniflow_initialize(&key.flow, key.buf);
2236
2237         for (i = 0; i < cnt; i++) {
2238             struct ofpbuf *packet, *userspace_packet;
2239
2240             packet = &packets[i]->ofpbuf;
2241
2242             miniflow_extract(packet, md, &key.flow);
2243
2244             userspace_packet = may_steal ? packet : ofpbuf_clone(packet);
2245
2246             dp_netdev_output_userspace(aux->dp, &userspace_packet, 1,
2247                                        miniflow_hash_5tuple(&key.flow, 0)
2248                                            % aux->dp->n_handlers,
2249                                        DPIF_UC_ACTION, &key.flow,
2250                                        userdata);
2251         }
2252         break;
2253     }
2254
2255     case OVS_ACTION_ATTR_HASH: {
2256         const struct ovs_action_hash *hash_act;
2257         struct netdev_flow_key key;
2258         uint32_t hash;
2259
2260         hash_act = nl_attr_get(a);
2261
2262         miniflow_initialize(&key.flow, key.buf);
2263
2264         for (i = 0; i < cnt; i++) {
2265
2266             /* TODO: this is slow. Use RSS hash in the future */
2267             miniflow_extract(&packets[i]->ofpbuf, md, &key.flow);
2268
2269             if (hash_act->hash_alg == OVS_HASH_ALG_L4) {
2270                 /* Hash need not be symmetric, nor does it need to include
2271                  * L2 fields. */
2272                 hash = miniflow_hash_5tuple(&key.flow, hash_act->hash_basis);
2273             } else {
2274                 VLOG_WARN("Unknown hash algorithm specified "
2275                           "for the hash action.");
2276                 hash = 2;
2277             }
2278
2279             if (!hash) {
2280                 hash = 1; /* 0 is not valid */
2281             }
2282
2283             if (i == 0) {
2284                 md->dp_hash = hash;
2285             }
2286             packets[i]->dp_hash = hash;
2287         }
2288         break;
2289     }
2290
2291     case OVS_ACTION_ATTR_RECIRC:
2292         if (*depth < MAX_RECIRC_DEPTH) {
2293
2294             (*depth)++;
2295             for (i = 0; i < cnt; i++) {
2296                 struct dpif_packet *recirc_pkt;
2297                 struct pkt_metadata recirc_md = *md;
2298
2299                 recirc_pkt = (may_steal) ? packets[i]
2300                                     : dpif_packet_clone(packets[i]);
2301
2302                 recirc_md.recirc_id = nl_attr_get_u32(a);
2303
2304                 /* Hash is private to each packet */
2305                 recirc_md.dp_hash = packets[i]->dp_hash;
2306
2307                 dp_netdev_input(aux->dp, &recirc_pkt, 1, &recirc_md);
2308             }
2309             (*depth)--;
2310
2311             break;
2312         } else {
2313             VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
2314         }
2315         break;
2316
2317     case OVS_ACTION_ATTR_PUSH_VLAN:
2318     case OVS_ACTION_ATTR_POP_VLAN:
2319     case OVS_ACTION_ATTR_PUSH_MPLS:
2320     case OVS_ACTION_ATTR_POP_MPLS:
2321     case OVS_ACTION_ATTR_SET:
2322     case OVS_ACTION_ATTR_SAMPLE:
2323     case OVS_ACTION_ATTR_UNSPEC:
2324     case __OVS_ACTION_ATTR_MAX:
2325         OVS_NOT_REACHED();
2326     }
2327 }
2328
2329 static void
2330 dp_netdev_execute_actions(struct dp_netdev *dp,
2331                           struct dpif_packet **packets, int cnt,
2332                           bool may_steal, struct pkt_metadata *md,
2333                           const struct nlattr *actions, size_t actions_len)
2334 {
2335     struct dp_netdev_execute_aux aux = {dp};
2336
2337     odp_execute_actions(&aux, packets, cnt, may_steal, md, actions,
2338                         actions_len, dp_execute_cb);
2339 }
2340
2341 const struct dpif_class dpif_netdev_class = {
2342     "netdev",
2343     dpif_netdev_enumerate,
2344     dpif_netdev_port_open_type,
2345     dpif_netdev_open,
2346     dpif_netdev_close,
2347     dpif_netdev_destroy,
2348     dpif_netdev_run,
2349     dpif_netdev_wait,
2350     dpif_netdev_get_stats,
2351     dpif_netdev_port_add,
2352     dpif_netdev_port_del,
2353     dpif_netdev_port_query_by_number,
2354     dpif_netdev_port_query_by_name,
2355     NULL,                       /* port_get_pid */
2356     dpif_netdev_port_dump_start,
2357     dpif_netdev_port_dump_next,
2358     dpif_netdev_port_dump_done,
2359     dpif_netdev_port_poll,
2360     dpif_netdev_port_poll_wait,
2361     dpif_netdev_flow_get,
2362     dpif_netdev_flow_put,
2363     dpif_netdev_flow_del,
2364     dpif_netdev_flow_flush,
2365     dpif_netdev_flow_dump_create,
2366     dpif_netdev_flow_dump_destroy,
2367     dpif_netdev_flow_dump_thread_create,
2368     dpif_netdev_flow_dump_thread_destroy,
2369     dpif_netdev_flow_dump_next,
2370     dpif_netdev_execute,
2371     NULL,                       /* operate */
2372     dpif_netdev_recv_set,
2373     dpif_netdev_handlers_set,
2374     dpif_netdev_queue_to_priority,
2375     dpif_netdev_recv,
2376     dpif_netdev_recv_wait,
2377     dpif_netdev_recv_purge,
2378 };
2379
2380 static void
2381 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
2382                               const char *argv[], void *aux OVS_UNUSED)
2383 {
2384     struct dp_netdev_port *old_port;
2385     struct dp_netdev_port *new_port;
2386     struct dp_netdev *dp;
2387     odp_port_t port_no;
2388
2389     ovs_mutex_lock(&dp_netdev_mutex);
2390     dp = shash_find_data(&dp_netdevs, argv[1]);
2391     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2392         ovs_mutex_unlock(&dp_netdev_mutex);
2393         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2394         return;
2395     }
2396     ovs_refcount_ref(&dp->ref_cnt);
2397     ovs_mutex_unlock(&dp_netdev_mutex);
2398
2399     ovs_mutex_lock(&dp->port_mutex);
2400     if (get_port_by_name(dp, argv[2], &old_port)) {
2401         unixctl_command_reply_error(conn, "unknown port");
2402         goto exit;
2403     }
2404
2405     port_no = u32_to_odp(atoi(argv[3]));
2406     if (!port_no || port_no == ODPP_NONE) {
2407         unixctl_command_reply_error(conn, "bad port number");
2408         goto exit;
2409     }
2410     if (dp_netdev_lookup_port(dp, port_no)) {
2411         unixctl_command_reply_error(conn, "port number already in use");
2412         goto exit;
2413     }
2414
2415     /* Remove old port. */
2416     cmap_remove(&dp->ports, &old_port->node, hash_port_no(old_port->port_no));
2417     ovsrcu_postpone(free, old_port);
2418
2419     /* Insert new port (cmap semantics mean we cannot re-insert 'old_port'). */
2420     new_port = xmemdup(old_port, sizeof *old_port);
2421     new_port->port_no = port_no;
2422     cmap_insert(&dp->ports, &new_port->node, hash_port_no(port_no));
2423
2424     seq_change(dp->port_seq);
2425     unixctl_command_reply(conn, NULL);
2426
2427 exit:
2428     ovs_mutex_unlock(&dp->port_mutex);
2429     dp_netdev_unref(dp);
2430 }
2431
2432 static void
2433 dpif_dummy_delete_port(struct unixctl_conn *conn, int argc OVS_UNUSED,
2434                        const char *argv[], void *aux OVS_UNUSED)
2435 {
2436     struct dp_netdev_port *port;
2437     struct dp_netdev *dp;
2438
2439     ovs_mutex_lock(&dp_netdev_mutex);
2440     dp = shash_find_data(&dp_netdevs, argv[1]);
2441     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
2442         ovs_mutex_unlock(&dp_netdev_mutex);
2443         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
2444         return;
2445     }
2446     ovs_refcount_ref(&dp->ref_cnt);
2447     ovs_mutex_unlock(&dp_netdev_mutex);
2448
2449     ovs_mutex_lock(&dp->port_mutex);
2450     if (get_port_by_name(dp, argv[2], &port)) {
2451         unixctl_command_reply_error(conn, "unknown port");
2452     } else if (port->port_no == ODPP_LOCAL) {
2453         unixctl_command_reply_error(conn, "can't delete local port");
2454     } else {
2455         do_del_port(dp, port);
2456         unixctl_command_reply(conn, NULL);
2457     }
2458     ovs_mutex_unlock(&dp->port_mutex);
2459
2460     dp_netdev_unref(dp);
2461 }
2462
2463 static void
2464 dpif_dummy_register__(const char *type)
2465 {
2466     struct dpif_class *class;
2467
2468     class = xmalloc(sizeof *class);
2469     *class = dpif_netdev_class;
2470     class->type = xstrdup(type);
2471     dp_register_provider(class);
2472 }
2473
2474 void
2475 dpif_dummy_register(bool override)
2476 {
2477     if (override) {
2478         struct sset types;
2479         const char *type;
2480
2481         sset_init(&types);
2482         dp_enumerate_types(&types);
2483         SSET_FOR_EACH (type, &types) {
2484             if (!dp_unregister_provider(type)) {
2485                 dpif_dummy_register__(type);
2486             }
2487         }
2488         sset_destroy(&types);
2489     }
2490
2491     dpif_dummy_register__("dummy");
2492
2493     unixctl_command_register("dpif-dummy/change-port-number",
2494                              "DP PORT NEW-NUMBER",
2495                              3, 3, dpif_dummy_change_port_number, NULL);
2496     unixctl_command_register("dpif-dummy/delete-port", "DP PORT",
2497                              2, 2, dpif_dummy_delete_port, NULL);
2498 }