dpif-netdev: init atomic flag dp->destroyed
[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_clear(&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     latch_destroy(&dp->exit_latch);
562     free(CONST_CAST(char *, dp->name));
563     free(dp);
564 }
565
566 static void
567 dp_netdev_unref(struct dp_netdev *dp)
568 {
569     if (dp) {
570         /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
571          * get a new reference to 'dp' through the 'dp_netdevs' shash. */
572         ovs_mutex_lock(&dp_netdev_mutex);
573         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
574             dp_netdev_free(dp);
575         }
576         ovs_mutex_unlock(&dp_netdev_mutex);
577     }
578 }
579
580 static void
581 dpif_netdev_close(struct dpif *dpif)
582 {
583     struct dp_netdev *dp = get_dp_netdev(dpif);
584
585     dp_netdev_unref(dp);
586     free(dpif);
587 }
588
589 static int
590 dpif_netdev_destroy(struct dpif *dpif)
591 {
592     struct dp_netdev *dp = get_dp_netdev(dpif);
593
594     if (!atomic_flag_test_and_set(&dp->destroyed)) {
595         if (ovs_refcount_unref(&dp->ref_cnt) == 1) {
596             /* Can't happen: 'dpif' still owns a reference to 'dp'. */
597             OVS_NOT_REACHED();
598         }
599     }
600
601     return 0;
602 }
603
604 static int
605 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
606 {
607     struct dp_netdev *dp = get_dp_netdev(dpif);
608
609     fat_rwlock_rdlock(&dp->cls.rwlock);
610     stats->n_flows = hmap_count(&dp->flow_table);
611     fat_rwlock_unlock(&dp->cls.rwlock);
612
613     stats->n_hit = ovsthread_counter_read(dp->n_hit);
614     stats->n_missed = ovsthread_counter_read(dp->n_missed);
615     stats->n_lost = ovsthread_counter_read(dp->n_lost);
616     stats->n_masks = UINT32_MAX;
617     stats->n_mask_hit = UINT64_MAX;
618
619     return 0;
620 }
621
622 static int
623 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
624             odp_port_t port_no)
625     OVS_REQ_WRLOCK(dp->port_rwlock)
626 {
627     struct netdev_saved_flags *sf;
628     struct dp_netdev_port *port;
629     struct netdev *netdev;
630     struct netdev_rx *rx;
631     enum netdev_flags flags;
632     const char *open_type;
633     int error;
634
635     /* XXX reject devices already in some dp_netdev. */
636
637     /* Open and validate network device. */
638     open_type = dpif_netdev_port_open_type(dp->class, type);
639     error = netdev_open(devname, open_type, &netdev);
640     if (error) {
641         return error;
642     }
643     /* XXX reject non-Ethernet devices */
644
645     netdev_get_flags(netdev, &flags);
646     if (flags & NETDEV_LOOPBACK) {
647         VLOG_ERR("%s: cannot add a loopback device", devname);
648         netdev_close(netdev);
649         return EINVAL;
650     }
651
652     error = netdev_rx_open(netdev, &rx);
653     if (error
654         && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
655         VLOG_ERR("%s: cannot receive packets on this network device (%s)",
656                  devname, ovs_strerror(errno));
657         netdev_close(netdev);
658         return error;
659     }
660
661     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
662     if (error) {
663         netdev_rx_close(rx);
664         netdev_close(netdev);
665         return error;
666     }
667
668     port = xmalloc(sizeof *port);
669     port->port_no = port_no;
670     port->netdev = netdev;
671     port->sf = sf;
672     port->rx = rx;
673     port->type = xstrdup(type);
674
675     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
676     seq_change(dp->port_seq);
677
678     return 0;
679 }
680
681 static int
682 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
683                      odp_port_t *port_nop)
684 {
685     struct dp_netdev *dp = get_dp_netdev(dpif);
686     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
687     const char *dpif_port;
688     odp_port_t port_no;
689     int error;
690
691     ovs_rwlock_wrlock(&dp->port_rwlock);
692     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
693     if (*port_nop != ODPP_NONE) {
694         port_no = *port_nop;
695         error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
696     } else {
697         port_no = choose_port(dp, dpif_port);
698         error = port_no == ODPP_NONE ? EFBIG : 0;
699     }
700     if (!error) {
701         *port_nop = port_no;
702         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
703     }
704     ovs_rwlock_unlock(&dp->port_rwlock);
705
706     return error;
707 }
708
709 static int
710 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
711 {
712     struct dp_netdev *dp = get_dp_netdev(dpif);
713     int error;
714
715     ovs_rwlock_wrlock(&dp->port_rwlock);
716     error = port_no == ODPP_LOCAL ? EINVAL : do_del_port(dp, port_no);
717     ovs_rwlock_unlock(&dp->port_rwlock);
718
719     return error;
720 }
721
722 static bool
723 is_valid_port_number(odp_port_t port_no)
724 {
725     return port_no != ODPP_NONE;
726 }
727
728 static struct dp_netdev_port *
729 dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
730     OVS_REQ_RDLOCK(dp->port_rwlock)
731 {
732     struct dp_netdev_port *port;
733
734     HMAP_FOR_EACH_IN_BUCKET (port, node, hash_int(odp_to_u32(port_no), 0),
735                              &dp->ports) {
736         if (port->port_no == port_no) {
737             return port;
738         }
739     }
740     return NULL;
741 }
742
743 static int
744 get_port_by_number(struct dp_netdev *dp,
745                    odp_port_t port_no, struct dp_netdev_port **portp)
746     OVS_REQ_RDLOCK(dp->port_rwlock)
747 {
748     if (!is_valid_port_number(port_no)) {
749         *portp = NULL;
750         return EINVAL;
751     } else {
752         *portp = dp_netdev_lookup_port(dp, port_no);
753         return *portp ? 0 : ENOENT;
754     }
755 }
756
757 static int
758 get_port_by_name(struct dp_netdev *dp,
759                  const char *devname, struct dp_netdev_port **portp)
760     OVS_REQ_RDLOCK(dp->port_rwlock)
761 {
762     struct dp_netdev_port *port;
763
764     HMAP_FOR_EACH (port, node, &dp->ports) {
765         if (!strcmp(netdev_get_name(port->netdev), devname)) {
766             *portp = port;
767             return 0;
768         }
769     }
770     return ENOENT;
771 }
772
773 static int
774 do_del_port(struct dp_netdev *dp, odp_port_t port_no)
775     OVS_REQ_WRLOCK(dp->port_rwlock)
776 {
777     struct dp_netdev_port *port;
778     int error;
779
780     error = get_port_by_number(dp, port_no, &port);
781     if (error) {
782         return error;
783     }
784
785     hmap_remove(&dp->ports, &port->node);
786     seq_change(dp->port_seq);
787
788     netdev_close(port->netdev);
789     netdev_restore_flags(port->sf);
790     netdev_rx_close(port->rx);
791     free(port->type);
792     free(port);
793
794     return 0;
795 }
796
797 static void
798 answer_port_query(const struct dp_netdev_port *port,
799                   struct dpif_port *dpif_port)
800 {
801     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
802     dpif_port->type = xstrdup(port->type);
803     dpif_port->port_no = port->port_no;
804 }
805
806 static int
807 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
808                                  struct dpif_port *dpif_port)
809 {
810     struct dp_netdev *dp = get_dp_netdev(dpif);
811     struct dp_netdev_port *port;
812     int error;
813
814     ovs_rwlock_rdlock(&dp->port_rwlock);
815     error = get_port_by_number(dp, port_no, &port);
816     if (!error && dpif_port) {
817         answer_port_query(port, dpif_port);
818     }
819     ovs_rwlock_unlock(&dp->port_rwlock);
820
821     return error;
822 }
823
824 static int
825 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
826                                struct dpif_port *dpif_port)
827 {
828     struct dp_netdev *dp = get_dp_netdev(dpif);
829     struct dp_netdev_port *port;
830     int error;
831
832     ovs_rwlock_rdlock(&dp->port_rwlock);
833     error = get_port_by_name(dp, devname, &port);
834     if (!error && dpif_port) {
835         answer_port_query(port, dpif_port);
836     }
837     ovs_rwlock_unlock(&dp->port_rwlock);
838
839     return error;
840 }
841
842 static void
843 dp_netdev_remove_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
844     OVS_REQ_WRLOCK(dp->cls.rwlock)
845     OVS_REQUIRES(dp->flow_mutex)
846 {
847     struct cls_rule *cr = CONST_CAST(struct cls_rule *, &flow->cr);
848     struct hmap_node *node = CONST_CAST(struct hmap_node *, &flow->node);
849
850     classifier_remove(&dp->cls, cr);
851     hmap_remove(&dp->flow_table, node);
852     dp_netdev_flow_unref(flow);
853 }
854
855 static struct dp_netdev_flow *
856 dp_netdev_flow_ref(const struct dp_netdev_flow *flow_)
857 {
858     struct dp_netdev_flow *flow = CONST_CAST(struct dp_netdev_flow *, flow_);
859     if (flow) {
860         ovs_refcount_ref(&flow->ref_cnt);
861     }
862     return flow;
863 }
864
865 static void
866 dp_netdev_flow_unref(struct dp_netdev_flow *flow)
867 {
868     if (flow && ovs_refcount_unref(&flow->ref_cnt) == 1) {
869         cls_rule_destroy(CONST_CAST(struct cls_rule *, &flow->cr));
870         ovs_mutex_lock(&flow->mutex);
871         dp_netdev_actions_unref(flow->actions);
872         ovs_mutex_unlock(&flow->mutex);
873         ovs_mutex_destroy(&flow->mutex);
874         free(flow);
875     }
876 }
877
878 static void
879 dp_netdev_flow_flush(struct dp_netdev *dp)
880 {
881     struct dp_netdev_flow *netdev_flow, *next;
882
883     ovs_mutex_lock(&dp->flow_mutex);
884     fat_rwlock_wrlock(&dp->cls.rwlock);
885     HMAP_FOR_EACH_SAFE (netdev_flow, next, node, &dp->flow_table) {
886         dp_netdev_remove_flow(dp, netdev_flow);
887     }
888     fat_rwlock_unlock(&dp->cls.rwlock);
889     ovs_mutex_unlock(&dp->flow_mutex);
890 }
891
892 static int
893 dpif_netdev_flow_flush(struct dpif *dpif)
894 {
895     struct dp_netdev *dp = get_dp_netdev(dpif);
896
897     dp_netdev_flow_flush(dp);
898     return 0;
899 }
900
901 struct dp_netdev_port_state {
902     uint32_t bucket;
903     uint32_t offset;
904     char *name;
905 };
906
907 static int
908 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
909 {
910     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
911     return 0;
912 }
913
914 static int
915 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
916                            struct dpif_port *dpif_port)
917 {
918     struct dp_netdev_port_state *state = state_;
919     struct dp_netdev *dp = get_dp_netdev(dpif);
920     struct hmap_node *node;
921     int retval;
922
923     ovs_rwlock_rdlock(&dp->port_rwlock);
924     node = hmap_at_position(&dp->ports, &state->bucket, &state->offset);
925     if (node) {
926         struct dp_netdev_port *port;
927
928         port = CONTAINER_OF(node, struct dp_netdev_port, node);
929
930         free(state->name);
931         state->name = xstrdup(netdev_get_name(port->netdev));
932         dpif_port->name = state->name;
933         dpif_port->type = port->type;
934         dpif_port->port_no = port->port_no;
935
936         retval = 0;
937     } else {
938         retval = EOF;
939     }
940     ovs_rwlock_unlock(&dp->port_rwlock);
941
942     return retval;
943 }
944
945 static int
946 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
947 {
948     struct dp_netdev_port_state *state = state_;
949     free(state->name);
950     free(state);
951     return 0;
952 }
953
954 static int
955 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
956 {
957     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
958     uint64_t new_port_seq;
959     int error;
960
961     new_port_seq = seq_read(dpif->dp->port_seq);
962     if (dpif->last_port_seq != new_port_seq) {
963         dpif->last_port_seq = new_port_seq;
964         error = ENOBUFS;
965     } else {
966         error = EAGAIN;
967     }
968
969     return error;
970 }
971
972 static void
973 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
974 {
975     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
976
977     seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
978 }
979
980 static struct dp_netdev_flow *
981 dp_netdev_flow_cast(const struct cls_rule *cr)
982 {
983     return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
984 }
985
986 static struct dp_netdev_flow *
987 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct flow *flow)
988     OVS_EXCLUDED(dp->cls.rwlock)
989 {
990     struct dp_netdev_flow *netdev_flow;
991
992     fat_rwlock_rdlock(&dp->cls.rwlock);
993     netdev_flow = dp_netdev_flow_cast(classifier_lookup(&dp->cls, flow, NULL));
994     dp_netdev_flow_ref(netdev_flow);
995     fat_rwlock_unlock(&dp->cls.rwlock);
996
997     return netdev_flow;
998 }
999
1000 static struct dp_netdev_flow *
1001 dp_netdev_find_flow(const struct dp_netdev *dp, const struct flow *flow)
1002     OVS_REQ_RDLOCK(dp->cls.rwlock)
1003 {
1004     struct dp_netdev_flow *netdev_flow;
1005
1006     HMAP_FOR_EACH_WITH_HASH (netdev_flow, node, flow_hash(flow, 0),
1007                              &dp->flow_table) {
1008         if (flow_equal(&netdev_flow->flow, flow)) {
1009             return dp_netdev_flow_ref(netdev_flow);
1010         }
1011     }
1012
1013     return NULL;
1014 }
1015
1016 static void
1017 get_dpif_flow_stats(struct dp_netdev_flow *netdev_flow,
1018                     struct dpif_flow_stats *stats)
1019     OVS_REQ_RDLOCK(netdev_flow->mutex)
1020 {
1021     stats->n_packets = netdev_flow->packet_count;
1022     stats->n_bytes = netdev_flow->byte_count;
1023     stats->used = netdev_flow->used;
1024     stats->tcp_flags = netdev_flow->tcp_flags;
1025 }
1026
1027 static int
1028 dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1029                               const struct nlattr *mask_key,
1030                               uint32_t mask_key_len, const struct flow *flow,
1031                               struct flow *mask)
1032 {
1033     if (mask_key_len) {
1034         enum odp_key_fitness fitness;
1035
1036         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1037         if (fitness) {
1038             /* This should not happen: it indicates that
1039              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1040              * disagree on the acceptable form of a mask.  Log the problem
1041              * as an error, with enough details to enable debugging. */
1042             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1043
1044             if (!VLOG_DROP_ERR(&rl)) {
1045                 struct ds s;
1046
1047                 ds_init(&s);
1048                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1049                                 true);
1050                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1051                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1052                 ds_destroy(&s);
1053             }
1054
1055             return EINVAL;
1056         }
1057         /* Force unwildcard the in_port. */
1058         mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1059     } else {
1060         enum mf_field_id id;
1061         /* No mask key, unwildcard everything except fields whose
1062          * prerequisities are not met. */
1063         memset(mask, 0x0, sizeof *mask);
1064
1065         for (id = 0; id < MFF_N_IDS; ++id) {
1066             /* Skip registers and metadata. */
1067             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1068                 && id != MFF_METADATA) {
1069                 const struct mf_field *mf = mf_from_id(id);
1070                 if (mf_are_prereqs_ok(mf, flow)) {
1071                     mf_mask_field(mf, mask);
1072                 }
1073             }
1074         }
1075     }
1076
1077     return 0;
1078 }
1079
1080 static int
1081 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1082                               struct flow *flow)
1083 {
1084     odp_port_t in_port;
1085
1086     if (odp_flow_key_to_flow(key, key_len, flow)) {
1087         /* This should not happen: it indicates that odp_flow_key_from_flow()
1088          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1089          * flow.  Log the problem as an error, with enough details to enable
1090          * debugging. */
1091         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1092
1093         if (!VLOG_DROP_ERR(&rl)) {
1094             struct ds s;
1095
1096             ds_init(&s);
1097             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1098             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1099             ds_destroy(&s);
1100         }
1101
1102         return EINVAL;
1103     }
1104
1105     in_port = flow->in_port.odp_port;
1106     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1107         return EINVAL;
1108     }
1109
1110     return 0;
1111 }
1112
1113 static int
1114 dpif_netdev_flow_get(const struct dpif *dpif,
1115                      const struct nlattr *nl_key, size_t nl_key_len,
1116                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1117 {
1118     struct dp_netdev *dp = get_dp_netdev(dpif);
1119     struct dp_netdev_flow *netdev_flow;
1120     struct flow key;
1121     int error;
1122
1123     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1124     if (error) {
1125         return error;
1126     }
1127
1128     fat_rwlock_rdlock(&dp->cls.rwlock);
1129     netdev_flow = dp_netdev_find_flow(dp, &key);
1130     fat_rwlock_unlock(&dp->cls.rwlock);
1131
1132     if (netdev_flow) {
1133         struct dp_netdev_actions *actions = NULL;
1134
1135         ovs_mutex_lock(&netdev_flow->mutex);
1136         if (stats) {
1137             get_dpif_flow_stats(netdev_flow, stats);
1138         }
1139         if (actionsp) {
1140             actions = dp_netdev_actions_ref(netdev_flow->actions);
1141         }
1142         ovs_mutex_unlock(&netdev_flow->mutex);
1143
1144         dp_netdev_flow_unref(netdev_flow);
1145
1146         if (actionsp) {
1147             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1148             dp_netdev_actions_unref(actions);
1149         }
1150     } else {
1151         error = ENOENT;
1152     }
1153
1154     return error;
1155 }
1156
1157 static int
1158 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1159                    const struct flow_wildcards *wc,
1160                    const struct nlattr *actions,
1161                    size_t actions_len)
1162     OVS_REQUIRES(dp->flow_mutex)
1163 {
1164     struct dp_netdev_flow *netdev_flow;
1165     struct match match;
1166
1167     netdev_flow = xzalloc(sizeof *netdev_flow);
1168     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1169     ovs_refcount_init(&netdev_flow->ref_cnt);
1170
1171     ovs_mutex_init(&netdev_flow->mutex);
1172     ovs_mutex_lock(&netdev_flow->mutex);
1173
1174     netdev_flow->actions = dp_netdev_actions_create(actions, actions_len);
1175
1176     match_init(&match, flow, wc);
1177     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1178                   &match, NETDEV_RULE_PRIORITY);
1179     fat_rwlock_wrlock(&dp->cls.rwlock);
1180     classifier_insert(&dp->cls,
1181                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1182     hmap_insert(&dp->flow_table,
1183                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1184                 flow_hash(flow, 0));
1185     fat_rwlock_unlock(&dp->cls.rwlock);
1186
1187     ovs_mutex_unlock(&netdev_flow->mutex);
1188
1189     return 0;
1190 }
1191
1192 static void
1193 clear_stats(struct dp_netdev_flow *netdev_flow)
1194     OVS_REQUIRES(netdev_flow->mutex)
1195 {
1196     netdev_flow->used = 0;
1197     netdev_flow->packet_count = 0;
1198     netdev_flow->byte_count = 0;
1199     netdev_flow->tcp_flags = 0;
1200 }
1201
1202 static int
1203 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1204 {
1205     struct dp_netdev *dp = get_dp_netdev(dpif);
1206     struct dp_netdev_flow *netdev_flow;
1207     struct flow flow;
1208     struct flow_wildcards wc;
1209     int error;
1210
1211     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1212     if (error) {
1213         return error;
1214     }
1215     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1216                                           put->mask, put->mask_len,
1217                                           &flow, &wc.masks);
1218     if (error) {
1219         return error;
1220     }
1221
1222     ovs_mutex_lock(&dp->flow_mutex);
1223     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1224     if (!netdev_flow) {
1225         if (put->flags & DPIF_FP_CREATE) {
1226             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1227                 if (put->stats) {
1228                     memset(put->stats, 0, sizeof *put->stats);
1229                 }
1230                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1231                                            put->actions_len);
1232             } else {
1233                 error = EFBIG;
1234             }
1235         } else {
1236             error = ENOENT;
1237         }
1238     } else {
1239         if (put->flags & DPIF_FP_MODIFY
1240             && flow_equal(&flow, &netdev_flow->flow)) {
1241             struct dp_netdev_actions *new_actions;
1242             struct dp_netdev_actions *old_actions;
1243
1244             new_actions = dp_netdev_actions_create(put->actions,
1245                                                    put->actions_len);
1246
1247             ovs_mutex_lock(&netdev_flow->mutex);
1248             old_actions = netdev_flow->actions;
1249             netdev_flow->actions = new_actions;
1250             if (put->stats) {
1251                 get_dpif_flow_stats(netdev_flow, put->stats);
1252             }
1253             if (put->flags & DPIF_FP_ZERO_STATS) {
1254                 clear_stats(netdev_flow);
1255             }
1256             ovs_mutex_unlock(&netdev_flow->mutex);
1257
1258             dp_netdev_actions_unref(old_actions);
1259         } else if (put->flags & DPIF_FP_CREATE) {
1260             error = EEXIST;
1261         } else {
1262             /* Overlapping flow. */
1263             error = EINVAL;
1264         }
1265         dp_netdev_flow_unref(netdev_flow);
1266     }
1267     ovs_mutex_unlock(&dp->flow_mutex);
1268
1269     return error;
1270 }
1271
1272 static int
1273 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1274 {
1275     struct dp_netdev *dp = get_dp_netdev(dpif);
1276     struct dp_netdev_flow *netdev_flow;
1277     struct flow key;
1278     int error;
1279
1280     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1281     if (error) {
1282         return error;
1283     }
1284
1285     ovs_mutex_lock(&dp->flow_mutex);
1286     fat_rwlock_wrlock(&dp->cls.rwlock);
1287     netdev_flow = dp_netdev_find_flow(dp, &key);
1288     if (netdev_flow) {
1289         if (del->stats) {
1290             ovs_mutex_lock(&netdev_flow->mutex);
1291             get_dpif_flow_stats(netdev_flow, del->stats);
1292             ovs_mutex_unlock(&netdev_flow->mutex);
1293         }
1294         dp_netdev_remove_flow(dp, netdev_flow);
1295         dp_netdev_flow_unref(netdev_flow);
1296     } else {
1297         error = ENOENT;
1298     }
1299     fat_rwlock_unlock(&dp->cls.rwlock);
1300     ovs_mutex_unlock(&dp->flow_mutex);
1301
1302     return error;
1303 }
1304
1305 struct dp_netdev_flow_state {
1306     struct dp_netdev_actions *actions;
1307     struct odputil_keybuf keybuf;
1308     struct odputil_keybuf maskbuf;
1309     struct dpif_flow_stats stats;
1310 };
1311
1312 struct dp_netdev_flow_iter {
1313     uint32_t bucket;
1314     uint32_t offset;
1315     int status;
1316     struct ovs_mutex mutex;
1317 };
1318
1319 static void
1320 dpif_netdev_flow_dump_state_init(void **statep)
1321 {
1322     struct dp_netdev_flow_state *state;
1323
1324     *statep = state = xmalloc(sizeof *state);
1325     state->actions = NULL;
1326 }
1327
1328 static void
1329 dpif_netdev_flow_dump_state_uninit(void *state_)
1330 {
1331     struct dp_netdev_flow_state *state = state_;
1332
1333     dp_netdev_actions_unref(state->actions);
1334     free(state);
1335 }
1336
1337 static int
1338 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **iterp)
1339 {
1340     struct dp_netdev_flow_iter *iter;
1341
1342     *iterp = iter = xmalloc(sizeof *iter);
1343     iter->bucket = 0;
1344     iter->offset = 0;
1345     iter->status = 0;
1346     ovs_mutex_init(&iter->mutex);
1347     return 0;
1348 }
1349
1350 static int
1351 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *iter_, void *state_,
1352                            const struct nlattr **key, size_t *key_len,
1353                            const struct nlattr **mask, size_t *mask_len,
1354                            const struct nlattr **actions, size_t *actions_len,
1355                            const struct dpif_flow_stats **stats)
1356 {
1357     struct dp_netdev_flow_iter *iter = iter_;
1358     struct dp_netdev_flow_state *state = state_;
1359     struct dp_netdev *dp = get_dp_netdev(dpif);
1360     struct dp_netdev_flow *netdev_flow;
1361     int error;
1362
1363     ovs_mutex_lock(&iter->mutex);
1364     error = iter->status;
1365     if (!error) {
1366         struct hmap_node *node;
1367
1368         fat_rwlock_rdlock(&dp->cls.rwlock);
1369         node = hmap_at_position(&dp->flow_table, &iter->bucket, &iter->offset);
1370         if (node) {
1371             netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1372             dp_netdev_flow_ref(netdev_flow);
1373         }
1374         fat_rwlock_unlock(&dp->cls.rwlock);
1375         if (!node) {
1376             iter->status = error = EOF;
1377         }
1378     }
1379     ovs_mutex_unlock(&iter->mutex);
1380     if (error) {
1381         return error;
1382     }
1383
1384     if (key) {
1385         struct ofpbuf buf;
1386
1387         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1388         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1389                                netdev_flow->flow.in_port.odp_port);
1390
1391         *key = buf.data;
1392         *key_len = buf.size;
1393     }
1394
1395     if (key && mask) {
1396         struct ofpbuf buf;
1397         struct flow_wildcards wc;
1398
1399         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1400         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1401         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1402                                odp_to_u32(wc.masks.in_port.odp_port),
1403                                SIZE_MAX);
1404
1405         *mask = buf.data;
1406         *mask_len = buf.size;
1407     }
1408
1409     if (actions || stats) {
1410         dp_netdev_actions_unref(state->actions);
1411         state->actions = NULL;
1412
1413         ovs_mutex_lock(&netdev_flow->mutex);
1414         if (actions) {
1415             state->actions = dp_netdev_actions_ref(netdev_flow->actions);
1416             *actions = state->actions->actions;
1417             *actions_len = state->actions->size;
1418         }
1419         if (stats) {
1420             get_dpif_flow_stats(netdev_flow, &state->stats);
1421             *stats = &state->stats;
1422         }
1423         ovs_mutex_unlock(&netdev_flow->mutex);
1424     }
1425
1426     dp_netdev_flow_unref(netdev_flow);
1427
1428     return 0;
1429 }
1430
1431 static int
1432 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *iter_)
1433 {
1434     struct dp_netdev_flow_iter *iter = iter_;
1435
1436     ovs_mutex_destroy(&iter->mutex);
1437     free(iter);
1438     return 0;
1439 }
1440
1441 static int
1442 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1443 {
1444     struct dp_netdev *dp = get_dp_netdev(dpif);
1445     struct pkt_metadata *md = &execute->md;
1446     struct flow key;
1447
1448     if (execute->packet->size < ETH_HEADER_LEN ||
1449         execute->packet->size > UINT16_MAX) {
1450         return EINVAL;
1451     }
1452
1453     /* Extract flow key. */
1454     flow_extract(execute->packet, md, &key);
1455
1456     ovs_rwlock_rdlock(&dp->port_rwlock);
1457     dp_netdev_execute_actions(dp, &key, execute->packet, md, execute->actions,
1458                               execute->actions_len);
1459     ovs_rwlock_unlock(&dp->port_rwlock);
1460
1461     return 0;
1462 }
1463
1464 static int
1465 dpif_netdev_recv_set(struct dpif *dpif OVS_UNUSED, bool enable OVS_UNUSED)
1466 {
1467     return 0;
1468 }
1469
1470 static int
1471 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1472                               uint32_t queue_id, uint32_t *priority)
1473 {
1474     *priority = queue_id;
1475     return 0;
1476 }
1477
1478 static struct dp_netdev_queue *
1479 find_nonempty_queue(struct dp_netdev *dp)
1480     OVS_REQUIRES(dp->queue_mutex)
1481 {
1482     int i;
1483
1484     for (i = 0; i < N_QUEUES; i++) {
1485         struct dp_netdev_queue *q = &dp->queues[i];
1486         if (q->head != q->tail) {
1487             return q;
1488         }
1489     }
1490     return NULL;
1491 }
1492
1493 static int
1494 dpif_netdev_recv(struct dpif *dpif, struct dpif_upcall *upcall,
1495                  struct ofpbuf *buf)
1496 {
1497     struct dp_netdev *dp = get_dp_netdev(dpif);
1498     struct dp_netdev_queue *q;
1499     int error;
1500
1501     ovs_mutex_lock(&dp->queue_mutex);
1502     q = find_nonempty_queue(dp);
1503     if (q) {
1504         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1505
1506         *upcall = u->upcall;
1507
1508         ofpbuf_uninit(buf);
1509         *buf = u->buf;
1510
1511         error = 0;
1512     } else {
1513         error = EAGAIN;
1514     }
1515     ovs_mutex_unlock(&dp->queue_mutex);
1516
1517     return error;
1518 }
1519
1520 static void
1521 dpif_netdev_recv_wait(struct dpif *dpif)
1522 {
1523     struct dp_netdev *dp = get_dp_netdev(dpif);
1524     uint64_t seq;
1525
1526     ovs_mutex_lock(&dp->queue_mutex);
1527     seq = seq_read(dp->queue_seq);
1528     if (find_nonempty_queue(dp)) {
1529         poll_immediate_wake();
1530     } else {
1531         seq_wait(dp->queue_seq, seq);
1532     }
1533     ovs_mutex_unlock(&dp->queue_mutex);
1534 }
1535
1536 static void
1537 dpif_netdev_recv_purge(struct dpif *dpif)
1538 {
1539     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1540
1541     dp_netdev_purge_queues(dpif_netdev->dp);
1542 }
1543 \f
1544 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1545  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1546  * 'ofpacts'. */
1547 struct dp_netdev_actions *
1548 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1549 {
1550     struct dp_netdev_actions *netdev_actions;
1551
1552     netdev_actions = xmalloc(sizeof *netdev_actions);
1553     ovs_refcount_init(&netdev_actions->ref_cnt);
1554     netdev_actions->actions = xmemdup(actions, size);
1555     netdev_actions->size = size;
1556
1557     return netdev_actions;
1558 }
1559
1560 /* Increments 'actions''s refcount. */
1561 struct dp_netdev_actions *
1562 dp_netdev_actions_ref(const struct dp_netdev_actions *actions_)
1563 {
1564     struct dp_netdev_actions *actions;
1565
1566     actions = CONST_CAST(struct dp_netdev_actions *, actions_);
1567     if (actions) {
1568         ovs_refcount_ref(&actions->ref_cnt);
1569     }
1570     return actions;
1571 }
1572
1573 /* Decrements 'actions''s refcount and frees 'actions' if the refcount reaches
1574  * 0. */
1575 void
1576 dp_netdev_actions_unref(struct dp_netdev_actions *actions)
1577 {
1578     if (actions && ovs_refcount_unref(&actions->ref_cnt) == 1) {
1579         free(actions->actions);
1580         free(actions);
1581     }
1582 }
1583 \f
1584 static void *
1585 dp_forwarder_main(void *f_)
1586 {
1587     struct dp_forwarder *f = f_;
1588     struct dp_netdev *dp = f->dp;
1589     struct ofpbuf packet;
1590
1591     f->name = xasprintf("forwarder_%u", ovsthread_id_self());
1592     set_subprogram_name("%s", f->name);
1593
1594     ofpbuf_init(&packet, 0);
1595     while (!latch_is_set(&dp->exit_latch)) {
1596         bool received_anything;
1597         int i;
1598
1599         ovs_rwlock_rdlock(&dp->port_rwlock);
1600         for (i = 0; i < 50; i++) {
1601             struct dp_netdev_port *port;
1602
1603             received_anything = false;
1604             HMAP_FOR_EACH (port, node, &f->dp->ports) {
1605                 if (port->rx
1606                     && port->node.hash >= f->min_hash
1607                     && port->node.hash <= f->max_hash) {
1608                     int buf_size;
1609                     int error;
1610                     int mtu;
1611
1612                     if (netdev_get_mtu(port->netdev, &mtu)) {
1613                         mtu = ETH_PAYLOAD_MAX;
1614                     }
1615                     buf_size = DP_NETDEV_HEADROOM + VLAN_ETH_HEADER_LEN + mtu;
1616
1617                     ofpbuf_clear(&packet);
1618                     ofpbuf_reserve_with_tailroom(&packet, DP_NETDEV_HEADROOM,
1619                                                  buf_size);
1620
1621                     error = netdev_rx_recv(port->rx, &packet);
1622                     if (!error) {
1623                         struct pkt_metadata md
1624                             = PKT_METADATA_INITIALIZER(port->port_no);
1625
1626                         dp_netdev_port_input(dp, &packet, &md);
1627                         received_anything = true;
1628                     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1629                         static struct vlog_rate_limit rl
1630                             = VLOG_RATE_LIMIT_INIT(1, 5);
1631
1632                         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1633                                     netdev_get_name(port->netdev),
1634                                     ovs_strerror(error));
1635                     }
1636                 }
1637             }
1638
1639             if (!received_anything) {
1640                 break;
1641             }
1642         }
1643
1644         if (received_anything) {
1645             poll_immediate_wake();
1646         } else {
1647             struct dp_netdev_port *port;
1648
1649             HMAP_FOR_EACH (port, node, &f->dp->ports)
1650                 if (port->rx
1651                     && port->node.hash >= f->min_hash
1652                     && port->node.hash <= f->max_hash) {
1653                     netdev_rx_wait(port->rx);
1654                 }
1655             seq_wait(dp->port_seq, seq_read(dp->port_seq));
1656             latch_wait(&dp->exit_latch);
1657         }
1658         ovs_rwlock_unlock(&dp->port_rwlock);
1659
1660         poll_block();
1661     }
1662     ofpbuf_uninit(&packet);
1663
1664     free(f->name);
1665
1666     return NULL;
1667 }
1668
1669 static void
1670 dp_netdev_set_threads(struct dp_netdev *dp, int n)
1671 {
1672     int i;
1673
1674     if (n == dp->n_forwarders) {
1675         return;
1676     }
1677
1678     /* Stop existing threads. */
1679     latch_set(&dp->exit_latch);
1680     for (i = 0; i < dp->n_forwarders; i++) {
1681         struct dp_forwarder *f = &dp->forwarders[i];
1682
1683         xpthread_join(f->thread, NULL);
1684     }
1685     latch_poll(&dp->exit_latch);
1686     free(dp->forwarders);
1687
1688     /* Start new threads. */
1689     dp->forwarders = xmalloc(n * sizeof *dp->forwarders);
1690     dp->n_forwarders = n;
1691     for (i = 0; i < n; i++) {
1692         struct dp_forwarder *f = &dp->forwarders[i];
1693
1694         f->dp = dp;
1695         f->min_hash = UINT32_MAX / n * i;
1696         f->max_hash = UINT32_MAX / n * (i + 1) - 1;
1697         if (i == n - 1) {
1698             f->max_hash = UINT32_MAX;
1699         }
1700         xpthread_create(&f->thread, NULL, dp_forwarder_main, f);
1701     }
1702 }
1703 \f
1704 static void
1705 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1706                     const struct ofpbuf *packet)
1707     OVS_REQUIRES(netdev_flow->mutex)
1708 {
1709     netdev_flow->used = time_msec();
1710     netdev_flow->packet_count++;
1711     netdev_flow->byte_count += packet->size;
1712     netdev_flow->tcp_flags |= packet_get_tcp_flags(packet, &netdev_flow->flow);
1713 }
1714
1715 static void
1716 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
1717                      struct pkt_metadata *md)
1718     OVS_REQ_RDLOCK(dp->port_rwlock)
1719 {
1720     struct dp_netdev_flow *netdev_flow;
1721     struct flow key;
1722
1723     if (packet->size < ETH_HEADER_LEN) {
1724         return;
1725     }
1726     flow_extract(packet, md, &key);
1727     netdev_flow = dp_netdev_lookup_flow(dp, &key);
1728     if (netdev_flow) {
1729         struct dp_netdev_actions *actions;
1730
1731         ovs_mutex_lock(&netdev_flow->mutex);
1732         dp_netdev_flow_used(netdev_flow, packet);
1733         actions = dp_netdev_actions_ref(netdev_flow->actions);
1734         ovs_mutex_unlock(&netdev_flow->mutex);
1735
1736         dp_netdev_execute_actions(dp, &key, packet, md,
1737                                   actions->actions, actions->size);
1738         dp_netdev_actions_unref(actions);
1739         dp_netdev_flow_unref(netdev_flow);
1740         ovsthread_counter_inc(dp->n_hit, 1);
1741     } else {
1742         ovsthread_counter_inc(dp->n_missed, 1);
1743         dp_netdev_output_userspace(dp, packet, DPIF_UC_MISS, &key, NULL);
1744     }
1745 }
1746
1747 static int
1748 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
1749                            int queue_no, const struct flow *flow,
1750                            const struct nlattr *userdata)
1751     OVS_EXCLUDED(dp->queue_mutex)
1752 {
1753     struct dp_netdev_queue *q = &dp->queues[queue_no];
1754     int error;
1755
1756     ovs_mutex_lock(&dp->queue_mutex);
1757     if (q->head - q->tail < MAX_QUEUE_LEN) {
1758         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
1759         struct dpif_upcall *upcall = &u->upcall;
1760         struct ofpbuf *buf = &u->buf;
1761         size_t buf_size;
1762
1763         upcall->type = queue_no;
1764
1765         /* Allocate buffer big enough for everything. */
1766         buf_size = ODPUTIL_FLOW_KEY_BYTES;
1767         if (userdata) {
1768             buf_size += NLA_ALIGN(userdata->nla_len);
1769         }
1770         ofpbuf_init(buf, buf_size);
1771
1772         /* Put ODP flow. */
1773         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
1774         upcall->key = buf->data;
1775         upcall->key_len = buf->size;
1776
1777         /* Put userdata. */
1778         if (userdata) {
1779             upcall->userdata = ofpbuf_put(buf, userdata,
1780                                           NLA_ALIGN(userdata->nla_len));
1781         }
1782
1783         /* Steal packet data. */
1784         ovs_assert(packet->source == OFPBUF_MALLOC);
1785         upcall->packet = *packet;
1786         ofpbuf_use(packet, NULL, 0);
1787
1788         seq_change(dp->queue_seq);
1789
1790         error = 0;
1791     } else {
1792         ovsthread_counter_inc(dp->n_lost, 1);
1793         error = ENOBUFS;
1794     }
1795     ovs_mutex_unlock(&dp->queue_mutex);
1796
1797     return error;
1798 }
1799
1800 struct dp_netdev_execute_aux {
1801     struct dp_netdev *dp;
1802     const struct flow *key;
1803 };
1804
1805 static void
1806 dp_execute_cb(void *aux_, struct ofpbuf *packet,
1807               const struct pkt_metadata *md OVS_UNUSED,
1808               const struct nlattr *a, bool may_steal)
1809     OVS_NO_THREAD_SAFETY_ANALYSIS
1810 {
1811     struct dp_netdev_execute_aux *aux = aux_;
1812     int type = nl_attr_type(a);
1813     struct dp_netdev_port *p;
1814
1815     switch ((enum ovs_action_attr)type) {
1816     case OVS_ACTION_ATTR_OUTPUT:
1817         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
1818         if (p) {
1819             netdev_send(p->netdev, packet);
1820         }
1821         break;
1822
1823     case OVS_ACTION_ATTR_USERSPACE: {
1824         const struct nlattr *userdata;
1825
1826         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
1827
1828         /* Make a copy if we are not allowed to steal the packet's data. */
1829         if (!may_steal) {
1830             packet = ofpbuf_clone_with_headroom(packet, DP_NETDEV_HEADROOM);
1831         }
1832         dp_netdev_output_userspace(aux->dp, packet, DPIF_UC_ACTION, aux->key,
1833                                    userdata);
1834         if (!may_steal) {
1835             ofpbuf_uninit(packet);
1836         }
1837         break;
1838     }
1839     case OVS_ACTION_ATTR_PUSH_VLAN:
1840     case OVS_ACTION_ATTR_POP_VLAN:
1841     case OVS_ACTION_ATTR_PUSH_MPLS:
1842     case OVS_ACTION_ATTR_POP_MPLS:
1843     case OVS_ACTION_ATTR_SET:
1844     case OVS_ACTION_ATTR_SAMPLE:
1845     case OVS_ACTION_ATTR_UNSPEC:
1846     case __OVS_ACTION_ATTR_MAX:
1847         OVS_NOT_REACHED();
1848     }
1849 }
1850
1851 static void
1852 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
1853                           struct ofpbuf *packet, struct pkt_metadata *md,
1854                           const struct nlattr *actions, size_t actions_len)
1855     OVS_REQ_RDLOCK(dp->port_rwlock)
1856 {
1857     struct dp_netdev_execute_aux aux = {dp, key};
1858
1859     odp_execute_actions(&aux, packet, md, actions, actions_len, dp_execute_cb);
1860 }
1861
1862 const struct dpif_class dpif_netdev_class = {
1863     "netdev",
1864     dpif_netdev_enumerate,
1865     dpif_netdev_port_open_type,
1866     dpif_netdev_open,
1867     dpif_netdev_close,
1868     dpif_netdev_destroy,
1869     NULL,                       /* run */
1870     NULL,                       /* wait */
1871     dpif_netdev_get_stats,
1872     dpif_netdev_port_add,
1873     dpif_netdev_port_del,
1874     dpif_netdev_port_query_by_number,
1875     dpif_netdev_port_query_by_name,
1876     NULL,                       /* port_get_pid */
1877     dpif_netdev_port_dump_start,
1878     dpif_netdev_port_dump_next,
1879     dpif_netdev_port_dump_done,
1880     dpif_netdev_port_poll,
1881     dpif_netdev_port_poll_wait,
1882     dpif_netdev_flow_get,
1883     dpif_netdev_flow_put,
1884     dpif_netdev_flow_del,
1885     dpif_netdev_flow_flush,
1886     dpif_netdev_flow_dump_state_init,
1887     dpif_netdev_flow_dump_start,
1888     dpif_netdev_flow_dump_next,
1889     NULL,
1890     dpif_netdev_flow_dump_done,
1891     dpif_netdev_flow_dump_state_uninit,
1892     dpif_netdev_execute,
1893     NULL,                       /* operate */
1894     dpif_netdev_recv_set,
1895     dpif_netdev_queue_to_priority,
1896     dpif_netdev_recv,
1897     dpif_netdev_recv_wait,
1898     dpif_netdev_recv_purge,
1899 };
1900
1901 static void
1902 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
1903                               const char *argv[], void *aux OVS_UNUSED)
1904 {
1905     struct dp_netdev_port *port;
1906     struct dp_netdev *dp;
1907     odp_port_t port_no;
1908
1909     ovs_mutex_lock(&dp_netdev_mutex);
1910     dp = shash_find_data(&dp_netdevs, argv[1]);
1911     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
1912         ovs_mutex_unlock(&dp_netdev_mutex);
1913         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
1914         return;
1915     }
1916     ovs_refcount_ref(&dp->ref_cnt);
1917     ovs_mutex_unlock(&dp_netdev_mutex);
1918
1919     ovs_rwlock_wrlock(&dp->port_rwlock);
1920     if (get_port_by_name(dp, argv[2], &port)) {
1921         unixctl_command_reply_error(conn, "unknown port");
1922         goto exit;
1923     }
1924
1925     port_no = u32_to_odp(atoi(argv[3]));
1926     if (!port_no || port_no == ODPP_NONE) {
1927         unixctl_command_reply_error(conn, "bad port number");
1928         goto exit;
1929     }
1930     if (dp_netdev_lookup_port(dp, port_no)) {
1931         unixctl_command_reply_error(conn, "port number already in use");
1932         goto exit;
1933     }
1934     hmap_remove(&dp->ports, &port->node);
1935     port->port_no = port_no;
1936     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
1937     seq_change(dp->port_seq);
1938     unixctl_command_reply(conn, NULL);
1939
1940 exit:
1941     ovs_rwlock_unlock(&dp->port_rwlock);
1942     dp_netdev_unref(dp);
1943 }
1944
1945 static void
1946 dpif_dummy_register__(const char *type)
1947 {
1948     struct dpif_class *class;
1949
1950     class = xmalloc(sizeof *class);
1951     *class = dpif_netdev_class;
1952     class->type = xstrdup(type);
1953     dp_register_provider(class);
1954 }
1955
1956 void
1957 dpif_dummy_register(bool override)
1958 {
1959     if (override) {
1960         struct sset types;
1961         const char *type;
1962
1963         sset_init(&types);
1964         dp_enumerate_types(&types);
1965         SSET_FOR_EACH (type, &types) {
1966             if (!dp_unregister_provider(type)) {
1967                 dpif_dummy_register__(type);
1968             }
1969         }
1970         sset_destroy(&types);
1971     }
1972
1973     dpif_dummy_register__("dummy");
1974
1975     unixctl_command_register("dpif-dummy/change-port-number",
1976                              "DP PORT NEW-NUMBER",
1977                              3, 3, dpif_dummy_change_port_number, NULL);
1978 }