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