tunnel: Do not set padding bits in tunnel mask.
[sliver-openvswitch.git] / lib / dpif-netdev.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "dpif.h"
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <netinet/in.h>
25 #include <sys/socket.h>
26 #include <net/if.h>
27 #include <stdint.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/ioctl.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33
34 #include "classifier.h"
35 #include "csum.h"
36 #include "dpif.h"
37 #include "dpif-provider.h"
38 #include "dummy.h"
39 #include "dynamic-string.h"
40 #include "flow.h"
41 #include "hmap.h"
42 #include "latch.h"
43 #include "list.h"
44 #include "meta-flow.h"
45 #include "netdev.h"
46 #include "netdev-vport.h"
47 #include "netlink.h"
48 #include "odp-execute.h"
49 #include "odp-util.h"
50 #include "ofp-print.h"
51 #include "ofpbuf.h"
52 #include "packets.h"
53 #include "poll-loop.h"
54 #include "random.h"
55 #include "seq.h"
56 #include "shash.h"
57 #include "sset.h"
58 #include "timeval.h"
59 #include "unixctl.h"
60 #include "util.h"
61 #include "vlog.h"
62
63 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
64
65 /* By default, choose a priority in the middle. */
66 #define NETDEV_RULE_PRIORITY 0x8000
67
68 /* Configuration parameters. */
69 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
70
71 /* Enough headroom to add a vlan tag, plus an extra 2 bytes to allow IP
72  * headers to be aligned on a 4-byte boundary.  */
73 enum { DP_NETDEV_HEADROOM = 2 + VLAN_HEADER_LEN };
74
75 /* Queues. */
76 enum { N_QUEUES = 2 };          /* Number of queues for dpif_recv(). */
77 enum { MAX_QUEUE_LEN = 128 };   /* Maximum number of packets per queue. */
78 enum { QUEUE_MASK = MAX_QUEUE_LEN - 1 };
79 BUILD_ASSERT_DECL(IS_POW2(MAX_QUEUE_LEN));
80
81 /* Protects against changes to 'dp_netdevs'. */
82 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
83
84 /* Contains all 'struct dp_netdev's. */
85 static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
86     = SHASH_INITIALIZER(&dp_netdevs);
87
88 struct dp_netdev_upcall {
89     struct dpif_upcall upcall;  /* Queued upcall information. */
90     struct ofpbuf buf;          /* ofpbuf instance for upcall.packet. */
91 };
92
93 /* A queue passing packets from a struct dp_netdev to its clients.
94  *
95  *
96  * Thread-safety
97  * =============
98  *
99  * Any access at all requires the owning 'dp_netdev''s queue_mutex. */
100 struct dp_netdev_queue {
101     struct dp_netdev_upcall upcalls[MAX_QUEUE_LEN] OVS_GUARDED;
102     unsigned int head OVS_GUARDED;
103     unsigned int tail OVS_GUARDED;
104 };
105
106 /* Datapath based on the network device interface from netdev.h.
107  *
108  *
109  * Thread-safety
110  * =============
111  *
112  * Some members, marked 'const', are immutable.  Accessing other members
113  * requires synchronization, as noted in more detail below.
114  *
115  * Acquisition order is, from outermost to innermost:
116  *
117  *    dp_netdev_mutex (global)
118  *    port_rwlock
119  *    flow_mutex
120  *    cls.rwlock
121  *    queue_mutex
122  */
123 struct dp_netdev {
124     const struct dpif_class *const class;
125     const char *const name;
126     struct ovs_refcount ref_cnt;
127     atomic_flag destroyed;
128
129     /* Flows.
130      *
131      * Readers of 'cls' and 'flow_table' must take a 'cls->rwlock' read lock.
132      *
133      * Writers of 'cls' and 'flow_table' must take the 'flow_mutex' and then
134      * the 'cls->rwlock' write lock.  (The outer 'flow_mutex' allows writers to
135      * atomically perform multiple operations on 'cls' and 'flow_table'.)
136      */
137     struct ovs_mutex flow_mutex;
138     struct classifier cls;      /* Classifier.  Protected by cls.rwlock. */
139     struct hmap flow_table OVS_GUARDED; /* Flow table. */
140
141     /* Queues.
142      *
143      * Everything in 'queues' is protected by 'queue_mutex'. */
144     struct ovs_mutex queue_mutex;
145     struct dp_netdev_queue queues[N_QUEUES];
146     struct seq *queue_seq;      /* Incremented whenever a packet is queued. */
147
148     /* Statistics.
149      *
150      * ovsthread_counter is internally synchronized. */
151     struct ovsthread_counter *n_hit;    /* Number of flow table matches. */
152     struct ovsthread_counter *n_missed; /* Number of flow table misses. */
153     struct ovsthread_counter *n_lost;   /* Number of misses not passed up. */
154
155     /* Ports.
156      *
157      * Any lookup into 'ports' or any access to the dp_netdev_ports found
158      * through 'ports' requires taking 'port_rwlock'. */
159     struct ovs_rwlock port_rwlock;
160     struct hmap ports OVS_GUARDED;
161     struct seq *port_seq;       /* Incremented whenever a port changes. */
162
163     /* Forwarding threads. */
164     struct latch exit_latch;
165     struct dp_forwarder *forwarders;
166     size_t n_forwarders;
167 };
168
169 static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
170                                                     odp_port_t)
171     OVS_REQ_RDLOCK(dp->port_rwlock);
172
173 /* A port in a netdev-based datapath. */
174 struct dp_netdev_port {
175     struct hmap_node node;      /* Node in dp_netdev's 'ports'. */
176     odp_port_t port_no;
177     struct netdev *netdev;
178     struct netdev_saved_flags *sf;
179     struct netdev_rx *rx;
180     char *type;                 /* Port type as requested by user. */
181 };
182
183 /* A flow in dp_netdev's 'flow_table'.
184  *
185  *
186  * Thread-safety
187  * =============
188  *
189  * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
190  * its dp_netdev's classifier.  The text below calls this classifier 'cls'.
191  *
192  * Motivation
193  * ----------
194  *
195  * The thread safety rules described here for "struct dp_netdev_flow" are
196  * motivated by two goals:
197  *
198  *    - Prevent threads that read members of "struct dp_netdev_flow" from
199  *      reading bad data due to changes by some thread concurrently modifying
200  *      those members.
201  *
202  *    - Prevent two threads making changes to members of a given "struct
203  *      dp_netdev_flow" from interfering with each other.
204  *
205  *
206  * Rules
207  * -----
208  *
209  * A flow 'flow' may be accessed without a risk of being freed by code that
210  * holds a read-lock or write-lock on 'cls->rwlock' or that owns a reference to
211  * 'flow->ref_cnt' (or both).  Code that needs to hold onto a flow for a while
212  * should take 'cls->rwlock', find the flow it needs, increment 'flow->ref_cnt'
213  * with dpif_netdev_flow_ref(), and drop 'cls->rwlock'.
214  *
215  * 'flow->ref_cnt' protects 'flow' from being freed.  It doesn't protect the
216  * flow from being deleted from 'cls' (that's 'cls->rwlock') and it doesn't
217  * protect members of 'flow' from modification (that's 'flow->mutex').
218  *
219  * 'flow->mutex' protects the members of 'flow' from modification.  It doesn't
220  * protect the flow from being deleted from 'cls' (that's 'cls->rwlock') and it
221  * doesn't prevent the flow from being freed (that's 'flow->ref_cnt').
222  *
223  * Some members, marked 'const', are immutable.  Accessing other members
224  * requires synchronization, as noted in more detail below.
225  */
226 struct dp_netdev_flow {
227     /* Packet classification. */
228     const struct cls_rule cr;   /* In owning dp_netdev's 'cls'. */
229
230     /* Hash table index by unmasked flow. */
231     const struct hmap_node node; /* In owning dp_netdev's 'flow_table'. */
232     const struct flow flow;      /* The flow that created this entry. */
233
234     /* Number of references.
235      * The classifier owns one reference.
236      * Any thread trying to keep a rule from being freed should hold its own
237      * reference. */
238     struct ovs_refcount ref_cnt;
239
240     /* Protects members marked OVS_GUARDED.
241      *
242      * Acquire after datapath's flow_mutex. */
243     struct ovs_mutex mutex OVS_ACQ_AFTER(dp_netdev_mutex);
244
245     /* Statistics.
246      *
247      * Reading or writing these members requires 'mutex'. */
248     long long int used OVS_GUARDED; /* Last used time, in monotonic msecs. */
249     long long int packet_count OVS_GUARDED; /* Number of packets matched. */
250     long long int byte_count OVS_GUARDED;   /* Number of bytes matched. */
251     uint16_t tcp_flags OVS_GUARDED; /* Bitwise-OR of seen tcp_flags values. */
252
253     /* Actions.
254      *
255      * Reading 'actions' requires 'mutex'.
256      * Writing 'actions' requires 'mutex' and (to allow for transactions) the
257      * datapath's flow_mutex. */
258     struct dp_netdev_actions *actions OVS_GUARDED;
259 };
260
261 static struct dp_netdev_flow *dp_netdev_flow_ref(
262     const struct dp_netdev_flow *);
263 static void dp_netdev_flow_unref(struct dp_netdev_flow *);
264
265 /* A set of datapath actions within a "struct dp_netdev_flow".
266  *
267  *
268  * Thread-safety
269  * =============
270  *
271  * A struct dp_netdev_actions 'actions' may be accessed without a risk of being
272  * freed by code that holds a read-lock or write-lock on 'flow->mutex' (where
273  * 'flow' is the dp_netdev_flow for which 'flow->actions == actions') or that
274  * owns a reference to 'actions->ref_cnt' (or both). */
275 struct dp_netdev_actions {
276     struct ovs_refcount ref_cnt;
277
278     /* These members are immutable: they do not change during the struct's
279      * lifetime.  */
280     struct nlattr *actions;     /* Sequence of OVS_ACTION_ATTR_* attributes. */
281     unsigned int size;          /* Size of 'actions', in bytes. */
282 };
283
284 struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
285                                                    size_t);
286 struct dp_netdev_actions *dp_netdev_actions_ref(
287     const struct dp_netdev_actions *);
288 void dp_netdev_actions_unref(struct dp_netdev_actions *);
289
290 /* A thread that receives packets from some ports, looks them up in the flow
291  * table, and executes the actions it finds. */
292 struct dp_forwarder {
293     struct dp_netdev *dp;
294     pthread_t thread;
295     char *name;
296     uint32_t min_hash, max_hash;
297 };
298
299 /* Interface to netdev-based datapath. */
300 struct dpif_netdev {
301     struct dpif dpif;
302     struct dp_netdev *dp;
303     uint64_t last_port_seq;
304 };
305
306 static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
307                               struct dp_netdev_port **portp)
308     OVS_REQ_RDLOCK(dp->port_rwlock);
309 static int get_port_by_name(struct dp_netdev *dp, const char *devname,
310                             struct dp_netdev_port **portp)
311     OVS_REQ_RDLOCK(dp->port_rwlock);
312 static void dp_netdev_free(struct dp_netdev *)
313     OVS_REQUIRES(dp_netdev_mutex);
314 static void dp_netdev_flow_flush(struct dp_netdev *);
315 static int do_add_port(struct dp_netdev *dp, const char *devname,
316                        const char *type, odp_port_t port_no)
317     OVS_REQ_WRLOCK(dp->port_rwlock);
318 static int do_del_port(struct dp_netdev *dp, odp_port_t port_no)
319     OVS_REQ_WRLOCK(dp->port_rwlock);
320 static int dpif_netdev_open(const struct dpif_class *, const char *name,
321                             bool create, struct dpif **);
322 static int dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *,
323                                     int queue_no, const struct flow *,
324                                     const struct nlattr *userdata)
325     OVS_EXCLUDED(dp->queue_mutex);
326 static void dp_netdev_execute_actions(struct dp_netdev *dp,
327                                       const struct flow *, struct ofpbuf *,
328                                       struct pkt_metadata *,
329                                       const struct nlattr *actions,
330                                       size_t actions_len)
331     OVS_REQ_RDLOCK(dp->port_rwlock);
332 static void dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
333                                  struct pkt_metadata *)
334     OVS_REQ_RDLOCK(dp->port_rwlock);
335 static void dp_netdev_set_threads(struct dp_netdev *, int n);
336
337 static struct dpif_netdev *
338 dpif_netdev_cast(const struct dpif *dpif)
339 {
340     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
341     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
342 }
343
344 static struct dp_netdev *
345 get_dp_netdev(const struct dpif *dpif)
346 {
347     return dpif_netdev_cast(dpif)->dp;
348 }
349
350 static int
351 dpif_netdev_enumerate(struct sset *all_dps)
352 {
353     struct shash_node *node;
354
355     ovs_mutex_lock(&dp_netdev_mutex);
356     SHASH_FOR_EACH(node, &dp_netdevs) {
357         sset_add(all_dps, node->name);
358     }
359     ovs_mutex_unlock(&dp_netdev_mutex);
360
361     return 0;
362 }
363
364 static bool
365 dpif_netdev_class_is_dummy(const struct dpif_class *class)
366 {
367     return class != &dpif_netdev_class;
368 }
369
370 static const char *
371 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
372 {
373     return strcmp(type, "internal") ? type
374                   : dpif_netdev_class_is_dummy(class) ? "dummy"
375                   : "tap";
376 }
377
378 static struct dpif *
379 create_dpif_netdev(struct dp_netdev *dp)
380 {
381     uint16_t netflow_id = hash_string(dp->name, 0);
382     struct dpif_netdev *dpif;
383
384     ovs_refcount_ref(&dp->ref_cnt);
385
386     dpif = xmalloc(sizeof *dpif);
387     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
388     dpif->dp = dp;
389     dpif->last_port_seq = seq_read(dp->port_seq);
390
391     return &dpif->dpif;
392 }
393
394 /* Choose an unused, non-zero port number and return it on success.
395  * Return ODPP_NONE on failure. */
396 static odp_port_t
397 choose_port(struct dp_netdev *dp, const char *name)
398     OVS_REQ_RDLOCK(dp->port_rwlock)
399 {
400     uint32_t port_no;
401
402     if (dp->class != &dpif_netdev_class) {
403         const char *p;
404         int start_no = 0;
405
406         /* If the port name begins with "br", start the number search at
407          * 100 to make writing tests easier. */
408         if (!strncmp(name, "br", 2)) {
409             start_no = 100;
410         }
411
412         /* If the port name contains a number, try to assign that port number.
413          * This can make writing unit tests easier because port numbers are
414          * predictable. */
415         for (p = name; *p != '\0'; p++) {
416             if (isdigit((unsigned char) *p)) {
417                 port_no = start_no + strtol(p, NULL, 10);
418                 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
419                     && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
420                     return u32_to_odp(port_no);
421                 }
422                 break;
423             }
424         }
425     }
426
427     for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
428         if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
429             return u32_to_odp(port_no);
430         }
431     }
432
433     return ODPP_NONE;
434 }
435
436 static int
437 create_dp_netdev(const char *name, const struct dpif_class *class,
438                  struct dp_netdev **dpp)
439     OVS_REQUIRES(dp_netdev_mutex)
440 {
441     struct dp_netdev *dp;
442     int error;
443     int i;
444
445     dp = xzalloc(sizeof *dp);
446     shash_add(&dp_netdevs, name, dp);
447
448     *CONST_CAST(const struct dpif_class **, &dp->class) = class;
449     *CONST_CAST(const char **, &dp->name) = xstrdup(name);
450     ovs_refcount_init(&dp->ref_cnt);
451     atomic_flag_init(&dp->destroyed);
452
453     ovs_mutex_init(&dp->flow_mutex);
454     classifier_init(&dp->cls, NULL);
455     hmap_init(&dp->flow_table);
456
457     ovs_mutex_init(&dp->queue_mutex);
458     ovs_mutex_lock(&dp->queue_mutex);
459     for (i = 0; i < N_QUEUES; i++) {
460         dp->queues[i].head = dp->queues[i].tail = 0;
461     }
462     ovs_mutex_unlock(&dp->queue_mutex);
463     dp->queue_seq = seq_create();
464
465     dp->n_hit = ovsthread_counter_create();
466     dp->n_missed = ovsthread_counter_create();
467     dp->n_lost = ovsthread_counter_create();
468
469     ovs_rwlock_init(&dp->port_rwlock);
470     hmap_init(&dp->ports);
471     dp->port_seq = seq_create();
472     latch_init(&dp->exit_latch);
473
474     ovs_rwlock_wrlock(&dp->port_rwlock);
475     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
476     ovs_rwlock_unlock(&dp->port_rwlock);
477     if (error) {
478         dp_netdev_free(dp);
479         return error;
480     }
481     dp_netdev_set_threads(dp, 2);
482
483     *dpp = dp;
484     return 0;
485 }
486
487 static int
488 dpif_netdev_open(const struct dpif_class *class, const char *name,
489                  bool create, struct dpif **dpifp)
490 {
491     struct dp_netdev *dp;
492     int error;
493
494     ovs_mutex_lock(&dp_netdev_mutex);
495     dp = shash_find_data(&dp_netdevs, name);
496     if (!dp) {
497         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
498     } else {
499         error = (dp->class != class ? EINVAL
500                  : create ? EEXIST
501                  : 0);
502     }
503     if (!error) {
504         *dpifp = create_dpif_netdev(dp);
505     }
506     ovs_mutex_unlock(&dp_netdev_mutex);
507
508     return error;
509 }
510
511 static void
512 dp_netdev_purge_queues(struct dp_netdev *dp)
513 {
514     int i;
515
516     ovs_mutex_lock(&dp->queue_mutex);
517     for (i = 0; i < N_QUEUES; i++) {
518         struct dp_netdev_queue *q = &dp->queues[i];
519
520         while (q->tail != q->head) {
521             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
522             ofpbuf_uninit(&u->upcall.packet);
523             ofpbuf_uninit(&u->buf);
524         }
525     }
526     ovs_mutex_unlock(&dp->queue_mutex);
527 }
528
529 /* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
530  * through the 'dp_netdevs' shash while freeing 'dp'. */
531 static void
532 dp_netdev_free(struct dp_netdev *dp)
533     OVS_REQUIRES(dp_netdev_mutex)
534 {
535     struct dp_netdev_port *port, *next;
536
537     shash_find_and_delete(&dp_netdevs, dp->name);
538
539     dp_netdev_set_threads(dp, 0);
540     free(dp->forwarders);
541
542     dp_netdev_flow_flush(dp);
543     ovs_rwlock_wrlock(&dp->port_rwlock);
544     HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
545         do_del_port(dp, port->port_no);
546     }
547     ovs_rwlock_unlock(&dp->port_rwlock);
548     ovsthread_counter_destroy(dp->n_hit);
549     ovsthread_counter_destroy(dp->n_missed);
550     ovsthread_counter_destroy(dp->n_lost);
551
552     dp_netdev_purge_queues(dp);
553     seq_destroy(dp->queue_seq);
554     ovs_mutex_destroy(&dp->queue_mutex);
555
556     classifier_destroy(&dp->cls);
557     hmap_destroy(&dp->flow_table);
558     ovs_mutex_destroy(&dp->flow_mutex);
559     seq_destroy(dp->port_seq);
560     hmap_destroy(&dp->ports);
561     atomic_flag_destroy(&dp->destroyed);
562     ovs_refcount_destroy(&dp->ref_cnt);
563     latch_destroy(&dp->exit_latch);
564     free(CONST_CAST(char *, dp->name));
565     free(dp);
566 }
567
568 static void
569 dp_netdev_unref(struct dp_netdev *dp)
570 {
571     if (dp) {
572         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
573          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
574         ovs_mutex_lock(&dp_netdev_mutex);
575         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
576             dp_netdev_free(dp);
577         }
578         ovs_mutex_unlock(&dp_netdev_mutex);
579     }
580 }
581
582 static void
583 dpif_netdev_close(struct dpif *dpif)
584 {
585     struct dp_netdev *dp = get_dp_netdev(dpif);
586
587     dp_netdev_unref(dp);
588     free(dpif);
589 }
590
591 static int
592 dpif_netdev_destroy(struct dpif *dpif)
593 {
594     struct dp_netdev *dp = get_dp_netdev(dpif);
595
596     if (!atomic_flag_test_and_set(&dp->destroyed)) {
597         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
598             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
599             OVS_NOT_REACHED();
600         }
601     }
602
603     return 0;
604 }
605
606 static int
607 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
608 {
609     struct dp_netdev *dp = get_dp_netdev(dpif);
610
611     fat_rwlock_rdlock(&dp->cls.rwlock);
612     stats->n_flows = hmap_count(&dp->flow_table);
613     fat_rwlock_unlock(&dp->cls.rwlock);
614
615     stats->n_hit = ovsthread_counter_read(dp->n_hit);
616     stats->n_missed = ovsthread_counter_read(dp->n_missed);
617     stats->n_lost = ovsthread_counter_read(dp->n_lost);
618     stats->n_masks = UINT32_MAX;
619     stats->n_mask_hit = UINT64_MAX;
620
621     return 0;
622 }
623
624 static int
625 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
626             odp_port_t port_no)
627     OVS_REQ_WRLOCK(dp->port_rwlock)
628 {
629     struct netdev_saved_flags *sf;
630     struct dp_netdev_port *port;
631     struct netdev *netdev;
632     struct netdev_rx *rx;
633     enum netdev_flags flags;
634     const char *open_type;
635     int error;
636
637     /* XXX reject devices already in some dp_netdev. */
638
639     /* Open and validate network device. */
640     open_type = dpif_netdev_port_open_type(dp->class, type);
641     error = netdev_open(devname, open_type, &netdev);
642     if (error) {
643         return error;
644     }
645     /* XXX reject non-Ethernet devices */
646
647     netdev_get_flags(netdev, &flags);
648     if (flags & NETDEV_LOOPBACK) {
649         VLOG_ERR("%s: cannot add a loopback device", devname);
650         netdev_close(netdev);
651         return EINVAL;
652     }
653
654     error = netdev_rx_open(netdev, &rx);
655     if (error
656         && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
657         VLOG_ERR("%s: cannot receive packets on this network device (%s)",
658                  devname, ovs_strerror(errno));
659         netdev_close(netdev);
660         return error;
661     }
662
663     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
664     if (error) {
665         netdev_rx_close(rx);
666         netdev_close(netdev);
667         return error;
668     }
669
670     port = xmalloc(sizeof *port);
671     port->port_no = port_no;
672     port->netdev = netdev;
673     port->sf = sf;
674     port->rx = rx;
675     port->type = xstrdup(type);
676
677     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
678     seq_change(dp->port_seq);
679
680     return 0;
681 }
682
683 static int
684 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
685                      odp_port_t *port_nop)
686 {
687     struct dp_netdev *dp = get_dp_netdev(dpif);
688     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
689     const char *dpif_port;
690     odp_port_t port_no;
691     int error;
692
693     ovs_rwlock_wrlock(&dp->port_rwlock);
694     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
695     if (*port_nop != ODPP_NONE) {
696         port_no = *port_nop;
697         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
698     } else {
699         port_no = choose_port(dp, dpif_port);
700         error = port_no == ODPP_NONE ? EFBIG : 0;
701     }
702     if (!error) {
703         *port_nop = port_no;
704         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
705     }
706     ovs_rwlock_unlock(&dp->port_rwlock);
707
708     return error;
709 }
710
711 static int
712 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
713 {
714     struct dp_netdev *dp = get_dp_netdev(dpif);
715     int error;
716
717     ovs_rwlock_wrlock(&dp->port_rwlock);
718     error = port_no == ODPP_LOCAL ? EINVAL : do_del_port(dp, port_no);
719     ovs_rwlock_unlock(&dp->port_rwlock);
720
721     return error;
722 }
723
724 static bool
725 is_valid_port_number(odp_port_t port_no)
726 {
727     return port_no != ODPP_NONE;
728 }
729
730 static struct dp_netdev_port *
731 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
732     OVS_REQ_RDLOCK(dp->port_rwlock)
733 {
734     struct dp_netdev_port *port;
735
736     HMAP_FOR_EACH_IN_BUCKET (port, node, hash_int(odp_to_u32(port_no), 0),
737                              &dp->ports) {
738         if (port->port_no == port_no) {
739             return port;
740         }
741     }
742     return NULL;
743 }
744
745 static int
746 get_port_by_number(struct dp_netdev *dp,
747                    odp_port_t port_no, struct dp_netdev_port **portp)
748     OVS_REQ_RDLOCK(dp->port_rwlock)
749 {
750     if (!is_valid_port_number(port_no)) {
751         *portp = NULL;
752         return EINVAL;
753     } else {
754         *portp = dp_netdev_lookup_port(dp, port_no);
755         return *portp ? 0 : ENOENT;
756     }
757 }
758
759 static int
760 get_port_by_name(struct dp_netdev *dp,
761                  const char *devname, struct dp_netdev_port **portp)
762     OVS_REQ_RDLOCK(dp->port_rwlock)
763 {
764     struct dp_netdev_port *port;
765
766     HMAP_FOR_EACH (port, node, &dp->ports) {
767         if (!strcmp(netdev_get_name(port->netdev), devname)) {
768             *portp = port;
769             return 0;
770         }
771     }
772     return ENOENT;
773 }
774
775 static int
776 do_del_port(struct dp_netdev *dp, odp_port_t port_no)
777     OVS_REQ_WRLOCK(dp->port_rwlock)
778 {
779     struct dp_netdev_port *port;
780     int error;
781
782     error = get_port_by_number(dp, port_no, &port);
783     if (error) {
784         return error;
785     }
786
787     hmap_remove(&dp->ports, &port->node);
788     seq_change(dp->port_seq);
789
790     netdev_close(port->netdev);
791     netdev_restore_flags(port->sf);
792     netdev_rx_close(port->rx);
793     free(port->type);
794     free(port);
795
796     return 0;
797 }
798
799 static void
800 answer_port_query(const struct dp_netdev_port *port,
801                   struct dpif_port *dpif_port)
802 {
803     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
804     dpif_port->type = xstrdup(port->type);
805     dpif_port->port_no = port->port_no;
806 }
807
808 static int
809 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
810                                  struct dpif_port *dpif_port)
811 {
812     struct dp_netdev *dp = get_dp_netdev(dpif);
813     struct dp_netdev_port *port;
814     int error;
815
816     ovs_rwlock_rdlock(&dp->port_rwlock);
817     error = get_port_by_number(dp, port_no, &port);
818     if (!error && dpif_port) {
819         answer_port_query(port, dpif_port);
820     }
821     ovs_rwlock_unlock(&dp->port_rwlock);
822
823     return error;
824 }
825
826 static int
827 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
828                                struct dpif_port *dpif_port)
829 {
830     struct dp_netdev *dp = get_dp_netdev(dpif);
831     struct dp_netdev_port *port;
832     int error;
833
834     ovs_rwlock_rdlock(&dp->port_rwlock);
835     error = get_port_by_name(dp, devname, &port);
836     if (!error && dpif_port) {
837         answer_port_query(port, dpif_port);
838     }
839     ovs_rwlock_unlock(&dp->port_rwlock);
840
841     return error;
842 }
843
844 static void
845 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
846     OVS_REQ_WRLOCK(dp->cls.rwlock)
847     OVS_REQUIRES(dp->flow_mutex)
848 {
849     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
850     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
851
852     classifier_remove(&dp->cls, cr);
853     hmap_remove(&dp->flow_table, node);
854     dp_netdev_flow_unref(flow);
855 }
856
857 static struct dp_netdev_flow *
858 dp_netdev_flow_ref(const struct dp_netdev_flow *flow_)
859 {
860     struct dp_netdev_flow *flow = CONST_CAST(struct dp_netdev_flow *, flow_);
861     if (flow) {
862         ovs_refcount_ref(&flow->ref_cnt);
863     }
864     return flow;
865 }
866
867 static void
868 dp_netdev_flow_unref(struct dp_netdev_flow *flow)
869 {
870     if (flow && ovs_refcount_unref(&flow->ref_cnt) == 1) {
871         cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
872         ovs_mutex_lock(&flow->mutex);
873         dp_netdev_actions_unref(flow->actions);
874         ovs_refcount_destroy(&flow->ref_cnt);
875         ovs_mutex_unlock(&flow->mutex);
876         ovs_mutex_destroy(&flow->mutex);
877         free(flow);
878     }
879 }
880
881 static void
882 dp_netdev_flow_flush(struct dp_netdev *dp)
883 {
884     struct dp_netdev_flow *netdev_flow, *next;
885
886     ovs_mutex_lock(&dp->flow_mutex);
887     fat_rwlock_wrlock(&dp->cls.rwlock);
888     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
889         dp_netdev_remove_flow(dp, netdev_flow);
890     }
891     fat_rwlock_unlock(&dp->cls.rwlock);
892     ovs_mutex_unlock(&dp->flow_mutex);
893 }
894
895 static int
896 dpif_netdev_flow_flush(struct dpif *dpif)
897 {
898     struct dp_netdev *dp = get_dp_netdev(dpif);
899
900     dp_netdev_flow_flush(dp);
901     return 0;
902 }
903
904 struct dp_netdev_port_state {
905     uint32_t bucket;
906     uint32_t offset;
907     char *name;
908 };
909
910 static int
911 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
912 {
913     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
914     return 0;
915 }
916
917 static int
918 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
919                            struct dpif_port *dpif_port)
920 {
921     struct dp_netdev_port_state *state = state_;
922     struct dp_netdev *dp = get_dp_netdev(dpif);
923     struct hmap_node *node;
924     int retval;
925
926     ovs_rwlock_rdlock(&dp->port_rwlock);
927     node = hmap_at_position(&dp->ports, &state->bucket, &state->offset);
928     if (node) {
929         struct dp_netdev_port *port;
930
931         port = CONTAINER_OF(node, struct dp_netdev_port, node);
932
933         free(state->name);
934         state->name = xstrdup(netdev_get_name(port->netdev));
935         dpif_port->name = state->name;
936         dpif_port->type = port->type;
937         dpif_port->port_no = port->port_no;
938
939         retval = 0;
940     } else {
941         retval = EOF;
942     }
943     ovs_rwlock_unlock(&dp->port_rwlock);
944
945     return retval;
946 }
947
948 static int
949 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
950 {
951     struct dp_netdev_port_state *state = state_;
952     free(state->name);
953     free(state);
954     return 0;
955 }
956
957 static int
958 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
959 {
960     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
961     uint64_t new_port_seq;
962     int error;
963
964     new_port_seq = seq_read(dpif->dp->port_seq);
965     if (dpif->last_port_seq != new_port_seq) {
966         dpif->last_port_seq = new_port_seq;
967         error = ENOBUFS;
968     } else {
969         error = EAGAIN;
970     }
971
972     return error;
973 }
974
975 static void
976 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
977 {
978     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
979
980     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
981 }
982
983 static struct dp_netdev_flow *
984 dp_netdev_flow_cast(const struct cls_rule *cr)
985 {
986     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
987 }
988
989 static struct dp_netdev_flow *
990 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct flow *flow)
991     OVS_EXCLUDED(dp->cls.rwlock)
992 {
993     struct dp_netdev_flow *netdev_flow;
994
995     fat_rwlock_rdlock(&dp->cls.rwlock);
996     netdev_flow = dp_netdev_flow_cast(classifier_lookup(&dp->cls, flow, NULL));
997     dp_netdev_flow_ref(netdev_flow);
998     fat_rwlock_unlock(&dp->cls.rwlock);
999
1000     return netdev_flow;
1001 }
1002
1003 static struct dp_netdev_flow *
1004 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1005     OVS_REQ_RDLOCK(dp->cls.rwlock)
1006 {
1007     struct dp_netdev_flow *netdev_flow;
1008
1009     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1010                              &dp->flow_table) {
1011         if (flow_equal(&netdev_flow->flow, flow)) {
1012             return dp_netdev_flow_ref(netdev_flow);
1013         }
1014     }
1015
1016     return NULL;
1017 }
1018
1019 static void
1020 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1021                     struct dpif_flow_stats *stats)
1022     OVS_REQ_RDLOCK(netdev_flow->mutex)
1023 {
1024     stats->n_packets = netdev_flow->packet_count;
1025     stats->n_bytes = netdev_flow->byte_count;
1026     stats->used = netdev_flow->used;
1027     stats->tcp_flags = netdev_flow->tcp_flags;
1028 }
1029
1030 static int
1031 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1032                               const struct nlattr *mask_key,
1033                               uint32_t mask_key_len, const struct flow *flow,
1034                               struct flow *mask)
1035 {
1036     if (mask_key_len) {
1037         enum odp_key_fitness fitness;
1038
1039         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1040         if (fitness) {
1041             /* This should not happen: it indicates that
1042              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1043              * disagree on the acceptable form of a mask.  Log the problem
1044              * as an error, with enough details to enable debugging. */
1045             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1046
1047             if (!VLOG_DROP_ERR(&rl)) {
1048                 struct ds s;
1049
1050                 ds_init(&s);
1051                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1052                                 true);
1053                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1054                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1055                 ds_destroy(&s);
1056             }
1057
1058             return EINVAL;
1059         }
1060         /* Force unwildcard the in_port. */
1061         mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1062     } else {
1063         enum mf_field_id id;
1064         /* No mask key, unwildcard everything except fields whose
1065          * prerequisities are not met. */
1066         memset(mask, 0x0, sizeof *mask);
1067
1068         for (id = 0; id < MFF_N_IDS; ++id) {
1069             /* Skip registers and metadata. */
1070             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1071                 && id != MFF_METADATA) {
1072                 const struct mf_field *mf = mf_from_id(id);
1073                 if (mf_are_prereqs_ok(mf, flow)) {
1074                     mf_mask_field(mf, mask);
1075                 }
1076             }
1077         }
1078     }
1079
1080     return 0;
1081 }
1082
1083 static int
1084 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1085                               struct flow *flow)
1086 {
1087     odp_port_t in_port;
1088
1089     if (odp_flow_key_to_flow(key, key_len, flow)) {
1090         /* This should not happen: it indicates that odp_flow_key_from_flow()
1091          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1092          * flow.  Log the problem as an error, with enough details to enable
1093          * debugging. */
1094         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1095
1096         if (!VLOG_DROP_ERR(&rl)) {
1097             struct ds s;
1098
1099             ds_init(&s);
1100             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1101             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1102             ds_destroy(&s);
1103         }
1104
1105         return EINVAL;
1106     }
1107
1108     in_port = flow->in_port.odp_port;
1109     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1110         return EINVAL;
1111     }
1112
1113     return 0;
1114 }
1115
1116 static int
1117 dpif_netdev_flow_get(const struct dpif *dpif,
1118                      const struct nlattr *nl_key, size_t nl_key_len,
1119                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1120 {
1121     struct dp_netdev *dp = get_dp_netdev(dpif);
1122     struct dp_netdev_flow *netdev_flow;
1123     struct flow key;
1124     int error;
1125
1126     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1127     if (error) {
1128         return error;
1129     }
1130
1131     fat_rwlock_rdlock(&dp->cls.rwlock);
1132     netdev_flow = dp_netdev_find_flow(dp, &key);
1133     fat_rwlock_unlock(&dp->cls.rwlock);
1134
1135     if (netdev_flow) {
1136         struct dp_netdev_actions *actions = NULL;
1137
1138         ovs_mutex_lock(&netdev_flow->mutex);
1139         if (stats) {
1140             get_dpif_flow_stats(netdev_flow, stats);
1141         }
1142         if (actionsp) {
1143             actions = dp_netdev_actions_ref(netdev_flow->actions);
1144         }
1145         ovs_mutex_unlock(&netdev_flow->mutex);
1146
1147         dp_netdev_flow_unref(netdev_flow);
1148
1149         if (actionsp) {
1150             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1151             dp_netdev_actions_unref(actions);
1152         }
1153     } else {
1154         error = ENOENT;
1155     }
1156
1157     return error;
1158 }
1159
1160 static int
1161 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1162                    const struct flow_wildcards *wc,
1163                    const struct nlattr *actions,
1164                    size_t actions_len)
1165     OVS_REQUIRES(dp->flow_mutex)
1166 {
1167     struct dp_netdev_flow *netdev_flow;
1168     struct match match;
1169
1170     netdev_flow = xzalloc(sizeof *netdev_flow);
1171     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1172     ovs_refcount_init(&netdev_flow->ref_cnt);
1173
1174     ovs_mutex_init(&netdev_flow->mutex);
1175     ovs_mutex_lock(&netdev_flow->mutex);
1176
1177     netdev_flow->actions = dp_netdev_actions_create(actions, actions_len);
1178
1179     match_init(&match, flow, wc);
1180     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1181                   &match, NETDEV_RULE_PRIORITY);
1182     fat_rwlock_wrlock(&dp->cls.rwlock);
1183     classifier_insert(&dp->cls,
1184                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1185     hmap_insert(&dp->flow_table,
1186                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1187                 flow_hash(flow, 0));
1188     fat_rwlock_unlock(&dp->cls.rwlock);
1189
1190     ovs_mutex_unlock(&netdev_flow->mutex);
1191
1192     return 0;
1193 }
1194
1195 static void
1196 clear_stats(struct dp_netdev_flow *netdev_flow)
1197     OVS_REQUIRES(netdev_flow->mutex)
1198 {
1199     netdev_flow->used = 0;
1200     netdev_flow->packet_count = 0;
1201     netdev_flow->byte_count = 0;
1202     netdev_flow->tcp_flags = 0;
1203 }
1204
1205 static int
1206 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1207 {
1208     struct dp_netdev *dp = get_dp_netdev(dpif);
1209     struct dp_netdev_flow *netdev_flow;
1210     struct flow flow;
1211     struct flow_wildcards wc;
1212     int error;
1213
1214     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1215     if (error) {
1216         return error;
1217     }
1218     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1219                                           put->mask, put->mask_len,
1220                                           &flow, &wc.masks);
1221     if (error) {
1222         return error;
1223     }
1224
1225     ovs_mutex_lock(&dp->flow_mutex);
1226     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1227     if (!netdev_flow) {
1228         if (put->flags & DPIF_FP_CREATE) {
1229             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1230                 if (put->stats) {
1231                     memset(put->stats, 0, sizeof *put->stats);
1232                 }
1233                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1234                                            put->actions_len);
1235             } else {
1236                 error = EFBIG;
1237             }
1238         } else {
1239             error = ENOENT;
1240         }
1241     } else {
1242         if (put->flags & DPIF_FP_MODIFY
1243             && flow_equal(&flow, &netdev_flow->flow)) {
1244             struct dp_netdev_actions *new_actions;
1245             struct dp_netdev_actions *old_actions;
1246
1247             new_actions = dp_netdev_actions_create(put->actions,
1248                                                    put->actions_len);
1249
1250             ovs_mutex_lock(&netdev_flow->mutex);
1251             old_actions = netdev_flow->actions;
1252             netdev_flow->actions = new_actions;
1253             if (put->stats) {
1254                 get_dpif_flow_stats(netdev_flow, put->stats);
1255             }
1256             if (put->flags & DPIF_FP_ZERO_STATS) {
1257                 clear_stats(netdev_flow);
1258             }
1259             ovs_mutex_unlock(&netdev_flow->mutex);
1260
1261             dp_netdev_actions_unref(old_actions);
1262         } else if (put->flags & DPIF_FP_CREATE) {
1263             error = EEXIST;
1264         } else {
1265             /* Overlapping flow. */
1266             error = EINVAL;
1267         }
1268         dp_netdev_flow_unref(netdev_flow);
1269     }
1270     ovs_mutex_unlock(&dp->flow_mutex);
1271
1272     return error;
1273 }
1274
1275 static int
1276 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1277 {
1278     struct dp_netdev *dp = get_dp_netdev(dpif);
1279     struct dp_netdev_flow *netdev_flow;
1280     struct flow key;
1281     int error;
1282
1283     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1284     if (error) {
1285         return error;
1286     }
1287
1288     ovs_mutex_lock(&dp->flow_mutex);
1289     fat_rwlock_wrlock(&dp->cls.rwlock);
1290     netdev_flow = dp_netdev_find_flow(dp, &key);
1291     if (netdev_flow) {
1292         if (del->stats) {
1293             ovs_mutex_lock(&netdev_flow->mutex);
1294             get_dpif_flow_stats(netdev_flow, del->stats);
1295             ovs_mutex_unlock(&netdev_flow->mutex);
1296         }
1297         dp_netdev_remove_flow(dp, netdev_flow);
1298         dp_netdev_flow_unref(netdev_flow);
1299     } else {
1300         error = ENOENT;
1301     }
1302     fat_rwlock_unlock(&dp->cls.rwlock);
1303     ovs_mutex_unlock(&dp->flow_mutex);
1304
1305     return error;
1306 }
1307
1308 struct dp_netdev_flow_state {
1309     struct dp_netdev_actions *actions;
1310     struct odputil_keybuf keybuf;
1311     struct odputil_keybuf maskbuf;
1312     struct dpif_flow_stats stats;
1313 };
1314
1315 struct dp_netdev_flow_iter {
1316     uint32_t bucket;
1317     uint32_t offset;
1318     int status;
1319     struct ovs_mutex mutex;
1320 };
1321
1322 static void
1323 dpif_netdev_flow_dump_state_init(void **statep)
1324 {
1325     struct dp_netdev_flow_state *state;
1326
1327     *statep = state = xmalloc(sizeof *state);
1328     state->actions = NULL;
1329 }
1330
1331 static void
1332 dpif_netdev_flow_dump_state_uninit(void *state_)
1333 {
1334     struct dp_netdev_flow_state *state = state_;
1335
1336     dp_netdev_actions_unref(state->actions);
1337     free(state);
1338 }
1339
1340 static int
1341 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **iterp)
1342 {
1343     struct dp_netdev_flow_iter *iter;
1344
1345     *iterp = iter = xmalloc(sizeof *iter);
1346     iter->bucket = 0;
1347     iter->offset = 0;
1348     iter->status = 0;
1349     ovs_mutex_init(&iter->mutex);
1350     return 0;
1351 }
1352
1353 static int
1354 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *iter_, void *state_,
1355                            const struct nlattr **key, size_t *key_len,
1356                            const struct nlattr **mask, size_t *mask_len,
1357                            const struct nlattr **actions, size_t *actions_len,
1358                            const struct dpif_flow_stats **stats)
1359 {
1360     struct dp_netdev_flow_iter *iter = iter_;
1361     struct dp_netdev_flow_state *state = state_;
1362     struct dp_netdev *dp = get_dp_netdev(dpif);
1363     struct dp_netdev_flow *netdev_flow;
1364     int error;
1365
1366     ovs_mutex_lock(&iter->mutex);
1367     error = iter->status;
1368     if (!error) {
1369         struct hmap_node *node;
1370
1371         fat_rwlock_rdlock(&dp->cls.rwlock);
1372         node = hmap_at_position(&dp->flow_table, &iter->bucket, &iter->offset);
1373         if (node) {
1374             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1375             dp_netdev_flow_ref(netdev_flow);
1376         }
1377         fat_rwlock_unlock(&dp->cls.rwlock);
1378         if (!node) {
1379             iter->status = error = EOF;
1380         }
1381     }
1382     ovs_mutex_unlock(&iter->mutex);
1383     if (error) {
1384         return error;
1385     }
1386
1387     if (key) {
1388         struct ofpbuf buf;
1389
1390         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1391         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1392                                netdev_flow->flow.in_port.odp_port);
1393
1394         *key = buf.data;
1395         *key_len = buf.size;
1396     }
1397
1398     if (key && mask) {
1399         struct ofpbuf buf;
1400         struct flow_wildcards wc;
1401
1402         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1403         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1404         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1405                                odp_to_u32(wc.masks.in_port.odp_port),
1406                                SIZE_MAX);
1407
1408         *mask = buf.data;
1409         *mask_len = buf.size;
1410     }
1411
1412     if (actions || stats) {
1413         dp_netdev_actions_unref(state->actions);
1414         state->actions = NULL;
1415
1416         ovs_mutex_lock(&netdev_flow->mutex);
1417         if (actions) {
1418             state->actions = dp_netdev_actions_ref(netdev_flow->actions);
1419             *actions = state->actions->actions;
1420             *actions_len = state->actions->size;
1421         }
1422         if (stats) {
1423             get_dpif_flow_stats(netdev_flow, &state->stats);
1424             *stats = &state->stats;
1425         }
1426         ovs_mutex_unlock(&netdev_flow->mutex);
1427     }
1428
1429     dp_netdev_flow_unref(netdev_flow);
1430
1431     return 0;
1432 }
1433
1434 static int
1435 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *iter_)
1436 {
1437     struct dp_netdev_flow_iter *iter = iter_;
1438
1439     ovs_mutex_destroy(&iter->mutex);
1440     free(iter);
1441     return 0;
1442 }
1443
1444 static int
1445 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1446 {
1447     struct dp_netdev *dp = get_dp_netdev(dpif);
1448     struct pkt_metadata *md = &execute->md;
1449     struct flow key;
1450
1451     if (execute->packet->size < ETH_HEADER_LEN ||
1452         execute->packet->size > UINT16_MAX) {
1453         return EINVAL;
1454     }
1455
1456     /* Extract flow key. */
1457     flow_extract(execute->packet, md, &key);
1458
1459     ovs_rwlock_rdlock(&dp->port_rwlock);
1460     dp_netdev_execute_actions(dp, &key, execute->packet, md, execute->actions,
1461                               execute->actions_len);
1462     ovs_rwlock_unlock(&dp->port_rwlock);
1463
1464     return 0;
1465 }
1466
1467 static int
1468 dpif_netdev_recv_set(struct dpif *dpif OVS_UNUSED, bool enable OVS_UNUSED)
1469 {
1470     return 0;
1471 }
1472
1473 static int
1474 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1475                               uint32_t queue_id, uint32_t *priority)
1476 {
1477     *priority = queue_id;
1478     return 0;
1479 }
1480
1481 static struct dp_netdev_queue *
1482 find_nonempty_queue(struct dp_netdev *dp)
1483     OVS_REQUIRES(dp->queue_mutex)
1484 {
1485     int i;
1486
1487     for (i = 0; i < N_QUEUES; i++) {
1488         struct dp_netdev_queue *q = &dp->queues[i];
1489         if (q->head != q->tail) {
1490             return q;
1491         }
1492     }
1493     return NULL;
1494 }
1495
1496 static int
1497 dpif_netdev_recv(struct dpif *dpif, struct dpif_upcall *upcall,
1498                  struct ofpbuf *buf)
1499 {
1500     struct dp_netdev *dp = get_dp_netdev(dpif);
1501     struct dp_netdev_queue *q;
1502     int error;
1503
1504     ovs_mutex_lock(&dp->queue_mutex);
1505     q = find_nonempty_queue(dp);
1506     if (q) {
1507         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1508
1509         *upcall = u->upcall;
1510
1511         ofpbuf_uninit(buf);
1512         *buf = u->buf;
1513
1514         error = 0;
1515     } else {
1516         error = EAGAIN;
1517     }
1518     ovs_mutex_unlock(&dp->queue_mutex);
1519
1520     return error;
1521 }
1522
1523 static void
1524 dpif_netdev_recv_wait(struct dpif *dpif)
1525 {
1526     struct dp_netdev *dp = get_dp_netdev(dpif);
1527     uint64_t seq;
1528
1529     ovs_mutex_lock(&dp->queue_mutex);
1530     seq = seq_read(dp->queue_seq);
1531     if (find_nonempty_queue(dp)) {
1532         poll_immediate_wake();
1533     } else {
1534         seq_wait(dp->queue_seq, seq);
1535     }
1536     ovs_mutex_unlock(&dp->queue_mutex);
1537 }
1538
1539 static void
1540 dpif_netdev_recv_purge(struct dpif *dpif)
1541 {
1542     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1543
1544     dp_netdev_purge_queues(dpif_netdev->dp);
1545 }
1546 \f
1547 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1548  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1549  * 'ofpacts'. */
1550 struct dp_netdev_actions *
1551 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1552 {
1553     struct dp_netdev_actions *netdev_actions;
1554
1555     netdev_actions = xmalloc(sizeof *netdev_actions);
1556     ovs_refcount_init(&netdev_actions->ref_cnt);
1557     netdev_actions->actions = xmemdup(actions, size);
1558     netdev_actions->size = size;
1559
1560     return netdev_actions;
1561 }
1562
1563 /* Increments 'actions''s refcount. */
1564 struct dp_netdev_actions *
1565 dp_netdev_actions_ref(const struct dp_netdev_actions *actions_)
1566 {
1567     struct dp_netdev_actions *actions;
1568
1569     actions = CONST_CAST(struct dp_netdev_actions *, actions_);
1570     if (actions) {
1571         ovs_refcount_ref(&actions->ref_cnt);
1572     }
1573     return actions;
1574 }
1575
1576 /* Decrements 'actions''s refcount and frees 'actions' if the refcount reaches
1577  * 0. */
1578 void
1579 dp_netdev_actions_unref(struct dp_netdev_actions *actions)
1580 {
1581     if (actions && ovs_refcount_unref(&actions->ref_cnt) == 1) {
1582         ovs_refcount_destroy(&actions->ref_cnt);
1583         free(actions->actions);
1584         free(actions);
1585     }
1586 }
1587 \f
1588 static void *
1589 dp_forwarder_main(void *f_)
1590 {
1591     struct dp_forwarder *f = f_;
1592     struct dp_netdev *dp = f->dp;
1593     struct ofpbuf packet;
1594
1595     f->name = xasprintf("forwarder_%u", ovsthread_id_self());
1596     set_subprogram_name("%s", f->name);
1597
1598     ofpbuf_init(&packet, 0);
1599     while (!latch_is_set(&dp->exit_latch)) {
1600         bool received_anything;
1601         int i;
1602
1603         ovs_rwlock_rdlock(&dp->port_rwlock);
1604         for (i = 0; i < 50; i++) {
1605             struct dp_netdev_port *port;
1606
1607             received_anything = false;
1608             HMAP_FOR_EACH (port, node, &f->dp->ports) {
1609                 if (port->rx
1610                     && port->node.hash >= f->min_hash
1611                     && port->node.hash <= f->max_hash) {
1612                     int buf_size;
1613                     int error;
1614                     int mtu;
1615
1616                     if (netdev_get_mtu(port->netdev, &mtu)) {
1617                         mtu = ETH_PAYLOAD_MAX;
1618                     }
1619                     buf_size = DP_NETDEV_HEADROOM + VLAN_ETH_HEADER_LEN + mtu;
1620
1621                     ofpbuf_clear(&packet);
1622                     ofpbuf_reserve_with_tailroom(&packet, DP_NETDEV_HEADROOM,
1623                                                  buf_size);
1624
1625                     error = netdev_rx_recv(port->rx, &packet);
1626                     if (!error) {
1627                         struct pkt_metadata md
1628                             = PKT_METADATA_INITIALIZER(port->port_no);
1629
1630                         dp_netdev_port_input(dp, &packet, &md);
1631                         received_anything = true;
1632                     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1633                         static struct vlog_rate_limit rl
1634                             = VLOG_RATE_LIMIT_INIT(1, 5);
1635
1636                         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1637                                     netdev_get_name(port->netdev),
1638                                     ovs_strerror(error));
1639                     }
1640                 }
1641             }
1642
1643             if (!received_anything) {
1644                 break;
1645             }
1646         }
1647
1648         if (received_anything) {
1649             poll_immediate_wake();
1650         } else {
1651             struct dp_netdev_port *port;
1652
1653             HMAP_FOR_EACH (port, node, &f->dp->ports)
1654                 if (port->rx
1655                     && port->node.hash >= f->min_hash
1656                     && port->node.hash <= f->max_hash) {
1657                     netdev_rx_wait(port->rx);
1658                 }
1659             seq_wait(dp->port_seq, seq_read(dp->port_seq));
1660             latch_wait(&dp->exit_latch);
1661         }
1662         ovs_rwlock_unlock(&dp->port_rwlock);
1663
1664         poll_block();
1665     }
1666     ofpbuf_uninit(&packet);
1667
1668     free(f->name);
1669
1670     return NULL;
1671 }
1672
1673 static void
1674 dp_netdev_set_threads(struct dp_netdev *dp, int n)
1675 {
1676     int i;
1677
1678     if (n == dp->n_forwarders) {
1679         return;
1680     }
1681
1682     /* Stop existing threads. */
1683     latch_set(&dp->exit_latch);
1684     for (i = 0; i < dp->n_forwarders; i++) {
1685         struct dp_forwarder *f = &dp->forwarders[i];
1686
1687         xpthread_join(f->thread, NULL);
1688     }
1689     latch_poll(&dp->exit_latch);
1690     free(dp->forwarders);
1691
1692     /* Start new threads. */
1693     dp->forwarders = xmalloc(n * sizeof *dp->forwarders);
1694     dp->n_forwarders = n;
1695     for (i = 0; i < n; i++) {
1696         struct dp_forwarder *f = &dp->forwarders[i];
1697
1698         f->dp = dp;
1699         f->min_hash = UINT32_MAX / n * i;
1700         f->max_hash = UINT32_MAX / n * (i + 1) - 1;
1701         if (i == n - 1) {
1702             f->max_hash = UINT32_MAX;
1703         }
1704         xpthread_create(&f->thread, NULL, dp_forwarder_main, f);
1705     }
1706 }
1707 \f
1708 static void
1709 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1710                     const struct ofpbuf *packet)
1711     OVS_REQUIRES(netdev_flow->mutex)
1712 {
1713     netdev_flow->used = time_msec();
1714     netdev_flow->packet_count++;
1715     netdev_flow->byte_count += packet->size;
1716     netdev_flow->tcp_flags |= packet_get_tcp_flags(packet, &netdev_flow->flow);
1717 }
1718
1719 static void
1720 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
1721                      struct pkt_metadata *md)
1722     OVS_REQ_RDLOCK(dp->port_rwlock)
1723 {
1724     struct dp_netdev_flow *netdev_flow;
1725     struct flow key;
1726
1727     if (packet->size < ETH_HEADER_LEN) {
1728         return;
1729     }
1730     flow_extract(packet, md, &key);
1731     netdev_flow = dp_netdev_lookup_flow(dp, &key);
1732     if (netdev_flow) {
1733         struct dp_netdev_actions *actions;
1734
1735         ovs_mutex_lock(&netdev_flow->mutex);
1736         dp_netdev_flow_used(netdev_flow, packet);
1737         actions = dp_netdev_actions_ref(netdev_flow->actions);
1738         ovs_mutex_unlock(&netdev_flow->mutex);
1739
1740         dp_netdev_execute_actions(dp, &key, packet, md,
1741                                   actions->actions, actions->size);
1742         dp_netdev_actions_unref(actions);
1743         dp_netdev_flow_unref(netdev_flow);
1744         ovsthread_counter_inc(dp->n_hit, 1);
1745     } else {
1746         ovsthread_counter_inc(dp->n_missed, 1);
1747         dp_netdev_output_userspace(dp, packet, DPIF_UC_MISS, &key, NULL);
1748     }
1749 }
1750
1751 static int
1752 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
1753                            int queue_no, const struct flow *flow,
1754                            const struct nlattr *userdata)
1755     OVS_EXCLUDED(dp->queue_mutex)
1756 {
1757     struct dp_netdev_queue *q = &dp->queues[queue_no];
1758     int error;
1759
1760     ovs_mutex_lock(&dp->queue_mutex);
1761     if (q->head - q->tail < MAX_QUEUE_LEN) {
1762         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
1763         struct dpif_upcall *upcall = &u->upcall;
1764         struct ofpbuf *buf = &u->buf;
1765         size_t buf_size;
1766
1767         upcall->type = queue_no;
1768
1769         /* Allocate buffer big enough for everything. */
1770         buf_size = ODPUTIL_FLOW_KEY_BYTES;
1771         if (userdata) {
1772             buf_size += NLA_ALIGN(userdata->nla_len);
1773         }
1774         ofpbuf_init(buf, buf_size);
1775
1776         /* Put ODP flow. */
1777         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
1778         upcall->key = buf->data;
1779         upcall->key_len = buf->size;
1780
1781         /* Put userdata. */
1782         if (userdata) {
1783             upcall->userdata = ofpbuf_put(buf, userdata,
1784                                           NLA_ALIGN(userdata->nla_len));
1785         }
1786
1787         /* Steal packet data. */
1788         ovs_assert(packet->source == OFPBUF_MALLOC);
1789         upcall->packet = *packet;
1790         ofpbuf_use(packet, NULL, 0);
1791
1792         seq_change(dp->queue_seq);
1793
1794         error = 0;
1795     } else {
1796         ovsthread_counter_inc(dp->n_lost, 1);
1797         error = ENOBUFS;
1798     }
1799     ovs_mutex_unlock(&dp->queue_mutex);
1800
1801     return error;
1802 }
1803
1804 struct dp_netdev_execute_aux {
1805     struct dp_netdev *dp;
1806     const struct flow *key;
1807 };
1808
1809 static void
1810 dp_execute_cb(void *aux_, struct ofpbuf *packet,
1811               const struct pkt_metadata *md OVS_UNUSED,
1812               const struct nlattr *a, bool may_steal)
1813     OVS_NO_THREAD_SAFETY_ANALYSIS
1814 {
1815     struct dp_netdev_execute_aux *aux = aux_;
1816     int type = nl_attr_type(a);
1817     struct dp_netdev_port *p;
1818
1819     switch ((enum ovs_action_attr)type) {
1820     case OVS_ACTION_ATTR_OUTPUT:
1821         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
1822         if (p) {
1823             netdev_send(p->netdev, packet);
1824         }
1825         break;
1826
1827     case OVS_ACTION_ATTR_USERSPACE: {
1828         const struct nlattr *userdata;
1829
1830         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
1831
1832         /* Make a copy if we are not allowed to steal the packet's data. */
1833         if (!may_steal) {
1834             packet = ofpbuf_clone_with_headroom(packet, DP_NETDEV_HEADROOM);
1835         }
1836         dp_netdev_output_userspace(aux->dp, packet, DPIF_UC_ACTION, aux->key,
1837                                    userdata);
1838         if (!may_steal) {
1839             ofpbuf_uninit(packet);
1840         }
1841         break;
1842     }
1843     case OVS_ACTION_ATTR_PUSH_VLAN:
1844     case OVS_ACTION_ATTR_POP_VLAN:
1845     case OVS_ACTION_ATTR_PUSH_MPLS:
1846     case OVS_ACTION_ATTR_POP_MPLS:
1847     case OVS_ACTION_ATTR_SET:
1848     case OVS_ACTION_ATTR_SAMPLE:
1849     case OVS_ACTION_ATTR_UNSPEC:
1850     case __OVS_ACTION_ATTR_MAX:
1851         OVS_NOT_REACHED();
1852     }
1853 }
1854
1855 static void
1856 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
1857                           struct ofpbuf *packet, struct pkt_metadata *md,
1858                           const struct nlattr *actions, size_t actions_len)
1859     OVS_REQ_RDLOCK(dp->port_rwlock)
1860 {
1861     struct dp_netdev_execute_aux aux = {dp, key};
1862
1863     odp_execute_actions(&aux, packet, md, actions, actions_len, dp_execute_cb);
1864 }
1865
1866 const struct dpif_class dpif_netdev_class = {
1867     "netdev",
1868     dpif_netdev_enumerate,
1869     dpif_netdev_port_open_type,
1870     dpif_netdev_open,
1871     dpif_netdev_close,
1872     dpif_netdev_destroy,
1873     NULL,                       /* run */
1874     NULL,                       /* wait */
1875     dpif_netdev_get_stats,
1876     dpif_netdev_port_add,
1877     dpif_netdev_port_del,
1878     dpif_netdev_port_query_by_number,
1879     dpif_netdev_port_query_by_name,
1880     NULL,                       /* port_get_pid */
1881     dpif_netdev_port_dump_start,
1882     dpif_netdev_port_dump_next,
1883     dpif_netdev_port_dump_done,
1884     dpif_netdev_port_poll,
1885     dpif_netdev_port_poll_wait,
1886     dpif_netdev_flow_get,
1887     dpif_netdev_flow_put,
1888     dpif_netdev_flow_del,
1889     dpif_netdev_flow_flush,
1890     dpif_netdev_flow_dump_state_init,
1891     dpif_netdev_flow_dump_start,
1892     dpif_netdev_flow_dump_next,
1893     NULL,
1894     dpif_netdev_flow_dump_done,
1895     dpif_netdev_flow_dump_state_uninit,
1896     dpif_netdev_execute,
1897     NULL,                       /* operate */
1898     dpif_netdev_recv_set,
1899     dpif_netdev_queue_to_priority,
1900     dpif_netdev_recv,
1901     dpif_netdev_recv_wait,
1902     dpif_netdev_recv_purge,
1903 };
1904
1905 static void
1906 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
1907                               const char *argv[], void *aux OVS_UNUSED)
1908 {
1909     struct dp_netdev_port *port;
1910     struct dp_netdev *dp;
1911     odp_port_t port_no;
1912
1913     ovs_mutex_lock(&dp_netdev_mutex);
1914     dp = shash_find_data(&dp_netdevs, argv[1]);
1915     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
1916         ovs_mutex_unlock(&dp_netdev_mutex);
1917         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
1918         return;
1919     }
1920     ovs_refcount_ref(&dp->ref_cnt);
1921     ovs_mutex_unlock(&dp_netdev_mutex);
1922
1923     ovs_rwlock_wrlock(&dp->port_rwlock);
1924     if (get_port_by_name(dp, argv[2], &port)) {
1925         unixctl_command_reply_error(conn, "unknown port");
1926         goto exit;
1927     }
1928
1929     port_no = u32_to_odp(atoi(argv[3]));
1930     if (!port_no || port_no == ODPP_NONE) {
1931         unixctl_command_reply_error(conn, "bad port number");
1932         goto exit;
1933     }
1934     if (dp_netdev_lookup_port(dp, port_no)) {
1935         unixctl_command_reply_error(conn, "port number already in use");
1936         goto exit;
1937     }
1938     hmap_remove(&dp->ports, &port->node);
1939     port->port_no = port_no;
1940     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
1941     seq_change(dp->port_seq);
1942     unixctl_command_reply(conn, NULL);
1943
1944 exit:
1945     ovs_rwlock_unlock(&dp->port_rwlock);
1946     dp_netdev_unref(dp);
1947 }
1948
1949 static void
1950 dpif_dummy_register__(const char *type)
1951 {
1952     struct dpif_class *class;
1953
1954     class = xmalloc(sizeof *class);
1955     *class = dpif_netdev_class;
1956     class->type = xstrdup(type);
1957     dp_register_provider(class);
1958 }
1959
1960 void
1961 dpif_dummy_register(bool override)
1962 {
1963     if (override) {
1964         struct sset types;
1965         const char *type;
1966
1967         sset_init(&types);
1968         dp_enumerate_types(&types);
1969         SSET_FOR_EACH (type, &types) {
1970             if (!dp_unregister_provider(type)) {
1971                 dpif_dummy_register__(type);
1972             }
1973         }
1974         sset_destroy(&types);
1975     }
1976
1977     dpif_dummy_register__("dummy");
1978
1979     unixctl_command_register("dpif-dummy/change-port-number",
1980                              "DP PORT NEW-NUMBER",
1981                              3, 3, dpif_dummy_change_port_number, NULL);
1982 }