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         enum odp_key_fitness fitness;
1045
1046         fitness = odp_flow_key_to_mask(mask_key, mask_key_len, mask, flow);
1047         if (fitness) {
1048             /* This should not happen: it indicates that
1049              * odp_flow_key_from_mask() and odp_flow_key_to_mask()
1050              * disagree on the acceptable form of a mask.  Log the problem
1051              * as an error, with enough details to enable debugging. */
1052             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1053
1054             if (!VLOG_DROP_ERR(&rl)) {
1055                 struct ds s;
1056
1057                 ds_init(&s);
1058                 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
1059                                 true);
1060                 VLOG_ERR("internal error parsing flow mask %s (%s)",
1061                          ds_cstr(&s), odp_key_fitness_to_string(fitness));
1062                 ds_destroy(&s);
1063             }
1064
1065             return EINVAL;
1066         }
1067         /* Force unwildcard the in_port. */
1068         mask->in_port.odp_port = u32_to_odp(UINT32_MAX);
1069     } else {
1070         enum mf_field_id id;
1071         /* No mask key, unwildcard everything except fields whose
1072          * prerequisities are not met. */
1073         memset(mask, 0x0, sizeof *mask);
1074
1075         for (id = 0; id < MFF_N_IDS; ++id) {
1076             /* Skip registers and metadata. */
1077             if (!(id >= MFF_REG0 && id < MFF_REG0 + FLOW_N_REGS)
1078                 && id != MFF_METADATA) {
1079                 const struct mf_field *mf = mf_from_id(id);
1080                 if (mf_are_prereqs_ok(mf, flow)) {
1081                     mf_mask_field(mf, mask);
1082                 }
1083             }
1084         }
1085     }
1086
1087     return 0;
1088 }
1089
1090 static int
1091 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
1092                               struct flow *flow)
1093 {
1094     odp_port_t in_port;
1095
1096     if (odp_flow_key_to_flow(key, key_len, flow)) {
1097         /* This should not happen: it indicates that odp_flow_key_from_flow()
1098          * and odp_flow_key_to_flow() disagree on the acceptable form of a
1099          * flow.  Log the problem as an error, with enough details to enable
1100          * debugging. */
1101         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1102
1103         if (!VLOG_DROP_ERR(&rl)) {
1104             struct ds s;
1105
1106             ds_init(&s);
1107             odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
1108             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
1109             ds_destroy(&s);
1110         }
1111
1112         return EINVAL;
1113     }
1114
1115     in_port = flow->in_port.odp_port;
1116     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
1117         return EINVAL;
1118     }
1119
1120     return 0;
1121 }
1122
1123 static int
1124 dpif_netdev_flow_get(const struct dpif *dpif,
1125                      const struct nlattr *nl_key, size_t nl_key_len,
1126                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
1127 {
1128     struct dp_netdev *dp = get_dp_netdev(dpif);
1129     struct dp_netdev_flow *netdev_flow;
1130     struct flow key;
1131     int error;
1132
1133     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
1134     if (error) {
1135         return error;
1136     }
1137
1138     fat_rwlock_rdlock(&dp->cls.rwlock);
1139     netdev_flow = dp_netdev_find_flow(dp, &key);
1140     fat_rwlock_unlock(&dp->cls.rwlock);
1141
1142     if (netdev_flow) {
1143         struct dp_netdev_actions *actions = NULL;
1144
1145         ovs_mutex_lock(&netdev_flow->mutex);
1146         if (stats) {
1147             get_dpif_flow_stats(netdev_flow, stats);
1148         }
1149         if (actionsp) {
1150             actions = dp_netdev_actions_ref(netdev_flow->actions);
1151         }
1152         ovs_mutex_unlock(&netdev_flow->mutex);
1153
1154         dp_netdev_flow_unref(netdev_flow);
1155
1156         if (actionsp) {
1157             *actionsp = ofpbuf_clone_data(actions->actions, actions->size);
1158             dp_netdev_actions_unref(actions);
1159         }
1160     } else {
1161         error = ENOENT;
1162     }
1163
1164     return error;
1165 }
1166
1167 static int
1168 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *flow,
1169                    const struct flow_wildcards *wc,
1170                    const struct nlattr *actions,
1171                    size_t actions_len)
1172     OVS_REQUIRES(dp->flow_mutex)
1173 {
1174     struct dp_netdev_flow *netdev_flow;
1175     struct match match;
1176
1177     netdev_flow = xzalloc(sizeof *netdev_flow);
1178     *CONST_CAST(struct flow *, &netdev_flow->flow) = *flow;
1179     ovs_refcount_init(&netdev_flow->ref_cnt);
1180
1181     ovs_mutex_init(&netdev_flow->mutex);
1182     ovs_mutex_lock(&netdev_flow->mutex);
1183
1184     netdev_flow->actions = dp_netdev_actions_create(actions, actions_len);
1185
1186     match_init(&match, flow, wc);
1187     cls_rule_init(CONST_CAST(struct cls_rule *, &netdev_flow->cr),
1188                   &match, NETDEV_RULE_PRIORITY);
1189     fat_rwlock_wrlock(&dp->cls.rwlock);
1190     classifier_insert(&dp->cls,
1191                       CONST_CAST(struct cls_rule *, &netdev_flow->cr));
1192     hmap_insert(&dp->flow_table,
1193                 CONST_CAST(struct hmap_node *, &netdev_flow->node),
1194                 flow_hash(flow, 0));
1195     fat_rwlock_unlock(&dp->cls.rwlock);
1196
1197     ovs_mutex_unlock(&netdev_flow->mutex);
1198
1199     return 0;
1200 }
1201
1202 static void
1203 clear_stats(struct dp_netdev_flow *netdev_flow)
1204     OVS_REQUIRES(netdev_flow->mutex)
1205 {
1206     netdev_flow->used = 0;
1207     netdev_flow->packet_count = 0;
1208     netdev_flow->byte_count = 0;
1209     netdev_flow->tcp_flags = 0;
1210 }
1211
1212 static int
1213 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
1214 {
1215     struct dp_netdev *dp = get_dp_netdev(dpif);
1216     struct dp_netdev_flow *netdev_flow;
1217     struct flow flow;
1218     struct flow_wildcards wc;
1219     int error;
1220
1221     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &flow);
1222     if (error) {
1223         return error;
1224     }
1225     error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
1226                                           put->mask, put->mask_len,
1227                                           &flow, &wc.masks);
1228     if (error) {
1229         return error;
1230     }
1231
1232     ovs_mutex_lock(&dp->flow_mutex);
1233     netdev_flow = dp_netdev_lookup_flow(dp, &flow);
1234     if (!netdev_flow) {
1235         if (put->flags & DPIF_FP_CREATE) {
1236             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
1237                 if (put->stats) {
1238                     memset(put->stats, 0, sizeof *put->stats);
1239                 }
1240                 error = dp_netdev_flow_add(dp, &flow, &wc, put->actions,
1241                                            put->actions_len);
1242             } else {
1243                 error = EFBIG;
1244             }
1245         } else {
1246             error = ENOENT;
1247         }
1248     } else {
1249         if (put->flags & DPIF_FP_MODIFY
1250             && flow_equal(&flow, &netdev_flow->flow)) {
1251             struct dp_netdev_actions *new_actions;
1252             struct dp_netdev_actions *old_actions;
1253
1254             new_actions = dp_netdev_actions_create(put->actions,
1255                                                    put->actions_len);
1256
1257             ovs_mutex_lock(&netdev_flow->mutex);
1258             old_actions = netdev_flow->actions;
1259             netdev_flow->actions = new_actions;
1260             if (put->stats) {
1261                 get_dpif_flow_stats(netdev_flow, put->stats);
1262             }
1263             if (put->flags & DPIF_FP_ZERO_STATS) {
1264                 clear_stats(netdev_flow);
1265             }
1266             ovs_mutex_unlock(&netdev_flow->mutex);
1267
1268             dp_netdev_actions_unref(old_actions);
1269         } else if (put->flags & DPIF_FP_CREATE) {
1270             error = EEXIST;
1271         } else {
1272             /* Overlapping flow. */
1273             error = EINVAL;
1274         }
1275         dp_netdev_flow_unref(netdev_flow);
1276     }
1277     ovs_mutex_unlock(&dp->flow_mutex);
1278
1279     return error;
1280 }
1281
1282 static int
1283 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
1284 {
1285     struct dp_netdev *dp = get_dp_netdev(dpif);
1286     struct dp_netdev_flow *netdev_flow;
1287     struct flow key;
1288     int error;
1289
1290     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
1291     if (error) {
1292         return error;
1293     }
1294
1295     ovs_mutex_lock(&dp->flow_mutex);
1296     fat_rwlock_wrlock(&dp->cls.rwlock);
1297     netdev_flow = dp_netdev_find_flow(dp, &key);
1298     if (netdev_flow) {
1299         if (del->stats) {
1300             ovs_mutex_lock(&netdev_flow->mutex);
1301             get_dpif_flow_stats(netdev_flow, del->stats);
1302             ovs_mutex_unlock(&netdev_flow->mutex);
1303         }
1304         dp_netdev_remove_flow(dp, netdev_flow);
1305     } else {
1306         error = ENOENT;
1307     }
1308     fat_rwlock_unlock(&dp->cls.rwlock);
1309     ovs_mutex_unlock(&dp->flow_mutex);
1310
1311     return error;
1312 }
1313
1314 struct dp_netdev_flow_state {
1315     uint32_t bucket;
1316     uint32_t offset;
1317     struct dp_netdev_actions *actions;
1318     struct odputil_keybuf keybuf;
1319     struct odputil_keybuf maskbuf;
1320     struct dpif_flow_stats stats;
1321 };
1322
1323 static int
1324 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
1325 {
1326     struct dp_netdev_flow_state *state;
1327
1328     *statep = state = xmalloc(sizeof *state);
1329     state->bucket = 0;
1330     state->offset = 0;
1331     state->actions = NULL;
1332     return 0;
1333 }
1334
1335 static int
1336 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *state_,
1337                            const struct nlattr **key, size_t *key_len,
1338                            const struct nlattr **mask, size_t *mask_len,
1339                            const struct nlattr **actions, size_t *actions_len,
1340                            const struct dpif_flow_stats **stats)
1341 {
1342     struct dp_netdev_flow_state *state = state_;
1343     struct dp_netdev *dp = get_dp_netdev(dpif);
1344     struct dp_netdev_flow *netdev_flow;
1345     struct hmap_node *node;
1346
1347     fat_rwlock_rdlock(&dp->cls.rwlock);
1348     node = hmap_at_position(&dp->flow_table, &state->bucket, &state->offset);
1349     if (node) {
1350         netdev_flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
1351         dp_netdev_flow_ref(netdev_flow);
1352     }
1353     fat_rwlock_unlock(&dp->cls.rwlock);
1354     if (!node) {
1355         return EOF;
1356     }
1357
1358     if (key) {
1359         struct ofpbuf buf;
1360
1361         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
1362         odp_flow_key_from_flow(&buf, &netdev_flow->flow,
1363                                netdev_flow->flow.in_port.odp_port);
1364
1365         *key = buf.data;
1366         *key_len = buf.size;
1367     }
1368
1369     if (key && mask) {
1370         struct ofpbuf buf;
1371         struct flow_wildcards wc;
1372
1373         ofpbuf_use_stack(&buf, &state->maskbuf, sizeof state->maskbuf);
1374         minimask_expand(&netdev_flow->cr.match.mask, &wc);
1375         odp_flow_key_from_mask(&buf, &wc.masks, &netdev_flow->flow,
1376                                odp_to_u32(wc.masks.in_port.odp_port),
1377                                SIZE_MAX);
1378
1379         *mask = buf.data;
1380         *mask_len = buf.size;
1381     }
1382
1383     if (actions || stats) {
1384         dp_netdev_actions_unref(state->actions);
1385         state->actions = NULL;
1386
1387         ovs_mutex_lock(&netdev_flow->mutex);
1388         if (actions) {
1389             state->actions = dp_netdev_actions_ref(netdev_flow->actions);
1390             *actions = state->actions->actions;
1391             *actions_len = state->actions->size;
1392         }
1393         if (stats) {
1394             get_dpif_flow_stats(netdev_flow, &state->stats);
1395             *stats = &state->stats;
1396         }
1397         ovs_mutex_unlock(&netdev_flow->mutex);
1398     }
1399
1400     dp_netdev_flow_unref(netdev_flow);
1401
1402     return 0;
1403 }
1404
1405 static int
1406 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1407 {
1408     struct dp_netdev_flow_state *state = state_;
1409
1410     dp_netdev_actions_unref(state->actions);
1411     free(state);
1412     return 0;
1413 }
1414
1415 static int
1416 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
1417 {
1418     struct dp_netdev *dp = get_dp_netdev(dpif);
1419     struct pkt_metadata *md = &execute->md;
1420     struct flow key;
1421
1422     if (execute->packet->size < ETH_HEADER_LEN ||
1423         execute->packet->size > UINT16_MAX) {
1424         return EINVAL;
1425     }
1426
1427     /* Extract flow key. */
1428     flow_extract(execute->packet, md->skb_priority, md->pkt_mark, &md->tunnel,
1429                  (union flow_in_port *)&md->in_port, &key);
1430
1431     ovs_rwlock_rdlock(&dp->port_rwlock);
1432     dp_netdev_execute_actions(dp, &key, execute->packet, md, execute->actions,
1433                               execute->actions_len);
1434     ovs_rwlock_unlock(&dp->port_rwlock);
1435
1436     return 0;
1437 }
1438
1439 static int
1440 dpif_netdev_recv_set(struct dpif *dpif OVS_UNUSED, bool enable OVS_UNUSED)
1441 {
1442     return 0;
1443 }
1444
1445 static int
1446 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1447                               uint32_t queue_id, uint32_t *priority)
1448 {
1449     *priority = queue_id;
1450     return 0;
1451 }
1452
1453 static struct dp_netdev_queue *
1454 find_nonempty_queue(struct dp_netdev *dp)
1455     OVS_REQUIRES(dp->queue_mutex)
1456 {
1457     int i;
1458
1459     for (i = 0; i < N_QUEUES; i++) {
1460         struct dp_netdev_queue *q = &dp->queues[i];
1461         if (q->head != q->tail) {
1462             return q;
1463         }
1464     }
1465     return NULL;
1466 }
1467
1468 static int
1469 dpif_netdev_recv(struct dpif *dpif, struct dpif_upcall *upcall,
1470                  struct ofpbuf *buf)
1471 {
1472     struct dp_netdev *dp = get_dp_netdev(dpif);
1473     struct dp_netdev_queue *q;
1474     int error;
1475
1476     ovs_mutex_lock(&dp->queue_mutex);
1477     q = find_nonempty_queue(dp);
1478     if (q) {
1479         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1480
1481         *upcall = u->upcall;
1482
1483         ofpbuf_uninit(buf);
1484         *buf = u->buf;
1485
1486         error = 0;
1487     } else {
1488         error = EAGAIN;
1489     }
1490     ovs_mutex_unlock(&dp->queue_mutex);
1491
1492     return error;
1493 }
1494
1495 static void
1496 dpif_netdev_recv_wait(struct dpif *dpif)
1497 {
1498     struct dp_netdev *dp = get_dp_netdev(dpif);
1499     uint64_t seq;
1500
1501     ovs_mutex_lock(&dp->queue_mutex);
1502     seq = seq_read(dp->queue_seq);
1503     if (find_nonempty_queue(dp)) {
1504         poll_immediate_wake();
1505     } else {
1506         seq_wait(dp->queue_seq, seq);
1507     }
1508     ovs_mutex_unlock(&dp->queue_mutex);
1509 }
1510
1511 static void
1512 dpif_netdev_recv_purge(struct dpif *dpif)
1513 {
1514     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1515
1516     dp_netdev_purge_queues(dpif_netdev->dp);
1517 }
1518 \f
1519 /* Creates and returns a new 'struct dp_netdev_actions', with a reference count
1520  * of 1, whose actions are a copy of from the 'ofpacts_len' bytes of
1521  * 'ofpacts'. */
1522 struct dp_netdev_actions *
1523 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
1524 {
1525     struct dp_netdev_actions *netdev_actions;
1526
1527     netdev_actions = xmalloc(sizeof *netdev_actions);
1528     ovs_refcount_init(&netdev_actions->ref_cnt);
1529     netdev_actions->actions = xmemdup(actions, size);
1530     netdev_actions->size = size;
1531
1532     return netdev_actions;
1533 }
1534
1535 /* Increments 'actions''s refcount. */
1536 struct dp_netdev_actions *
1537 dp_netdev_actions_ref(const struct dp_netdev_actions *actions_)
1538 {
1539     struct dp_netdev_actions *actions;
1540
1541     actions = CONST_CAST(struct dp_netdev_actions *, actions_);
1542     if (actions) {
1543         ovs_refcount_ref(&actions->ref_cnt);
1544     }
1545     return actions;
1546 }
1547
1548 /* Decrements 'actions''s refcount and frees 'actions' if the refcount reaches
1549  * 0. */
1550 void
1551 dp_netdev_actions_unref(struct dp_netdev_actions *actions)
1552 {
1553     if (actions && ovs_refcount_unref(&actions->ref_cnt) == 1) {
1554         free(actions->actions);
1555         free(actions);
1556     }
1557 }
1558 \f
1559 static void *
1560 dp_forwarder_main(void *f_)
1561 {
1562     struct dp_forwarder *f = f_;
1563     struct dp_netdev *dp = f->dp;
1564     struct ofpbuf packet;
1565
1566     f->name = xasprintf("forwarder_%u", ovsthread_id_self());
1567     set_subprogram_name("%s", f->name);
1568
1569     ofpbuf_init(&packet, 0);
1570     while (!latch_is_set(&dp->exit_latch)) {
1571         bool received_anything;
1572         int i;
1573
1574         ovs_rwlock_rdlock(&dp->port_rwlock);
1575         for (i = 0; i < 50; i++) {
1576             struct dp_netdev_port *port;
1577
1578             received_anything = false;
1579             HMAP_FOR_EACH (port, node, &f->dp->ports) {
1580                 if (port->rx
1581                     && port->node.hash >= f->min_hash
1582                     && port->node.hash <= f->max_hash) {
1583                     int buf_size;
1584                     int error;
1585                     int mtu;
1586
1587                     if (netdev_get_mtu(port->netdev, &mtu)) {
1588                         mtu = ETH_PAYLOAD_MAX;
1589                     }
1590                     buf_size = DP_NETDEV_HEADROOM + VLAN_ETH_HEADER_LEN + mtu;
1591
1592                     ofpbuf_clear(&packet);
1593                     ofpbuf_reserve_with_tailroom(&packet, DP_NETDEV_HEADROOM,
1594                                                  buf_size);
1595
1596                     error = netdev_rx_recv(port->rx, &packet);
1597                     if (!error) {
1598                         struct pkt_metadata md
1599                             = PKT_METADATA_INITIALIZER(port->port_no);
1600                         dp_netdev_port_input(dp, &packet, &md);
1601
1602                         received_anything = true;
1603                     } else if (error != EAGAIN && error != EOPNOTSUPP) {
1604                         static struct vlog_rate_limit rl
1605                             = VLOG_RATE_LIMIT_INIT(1, 5);
1606
1607                         VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1608                                     netdev_get_name(port->netdev),
1609                                     ovs_strerror(error));
1610                     }
1611                 }
1612             }
1613
1614             if (!received_anything) {
1615                 break;
1616             }
1617         }
1618
1619         if (received_anything) {
1620             poll_immediate_wake();
1621         } else {
1622             struct dp_netdev_port *port;
1623
1624             HMAP_FOR_EACH (port, node, &f->dp->ports)
1625                 if (port->rx
1626                     && port->node.hash >= f->min_hash
1627                     && port->node.hash <= f->max_hash) {
1628                     netdev_rx_wait(port->rx);
1629                 }
1630             seq_wait(dp->port_seq, seq_read(dp->port_seq));
1631             latch_wait(&dp->exit_latch);
1632         }
1633         ovs_rwlock_unlock(&dp->port_rwlock);
1634
1635         poll_block();
1636     }
1637     ofpbuf_uninit(&packet);
1638
1639     free(f->name);
1640
1641     return NULL;
1642 }
1643
1644 static void
1645 dp_netdev_set_threads(struct dp_netdev *dp, int n)
1646 {
1647     int i;
1648
1649     if (n == dp->n_forwarders) {
1650         return;
1651     }
1652
1653     /* Stop existing threads. */
1654     latch_set(&dp->exit_latch);
1655     for (i = 0; i < dp->n_forwarders; i++) {
1656         struct dp_forwarder *f = &dp->forwarders[i];
1657
1658         xpthread_join(f->thread, NULL);
1659     }
1660     latch_poll(&dp->exit_latch);
1661     free(dp->forwarders);
1662
1663     /* Start new threads. */
1664     dp->forwarders = xmalloc(n * sizeof *dp->forwarders);
1665     dp->n_forwarders = n;
1666     for (i = 0; i < n; i++) {
1667         struct dp_forwarder *f = &dp->forwarders[i];
1668
1669         f->dp = dp;
1670         f->min_hash = UINT32_MAX / n * i;
1671         f->max_hash = UINT32_MAX / n * (i + 1) - 1;
1672         if (i == n - 1) {
1673             f->max_hash = UINT32_MAX;
1674         }
1675         xpthread_create(&f->thread, NULL, dp_forwarder_main, f);
1676     }
1677 }
1678 \f
1679 static void
1680 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow,
1681                     const struct ofpbuf *packet)
1682     OVS_REQUIRES(netdev_flow->mutex)
1683 {
1684     netdev_flow->used = time_msec();
1685     netdev_flow->packet_count++;
1686     netdev_flow->byte_count += packet->size;
1687     netdev_flow->tcp_flags |= packet_get_tcp_flags(packet, &netdev_flow->flow);
1688 }
1689
1690 static void
1691 dp_netdev_port_input(struct dp_netdev *dp, struct ofpbuf *packet,
1692                      struct pkt_metadata *md)
1693     OVS_REQ_RDLOCK(dp->port_rwlock)
1694 {
1695     struct dp_netdev_flow *netdev_flow;
1696     struct flow key;
1697
1698     if (packet->size < ETH_HEADER_LEN) {
1699         return;
1700     }
1701     flow_extract(packet, md->skb_priority, md->pkt_mark, &md->tunnel,
1702                  (union flow_in_port *)&md->in_port, &key);
1703     netdev_flow = dp_netdev_lookup_flow(dp, &key);
1704     if (netdev_flow) {
1705         struct dp_netdev_actions *actions;
1706
1707         ovs_mutex_lock(&netdev_flow->mutex);
1708         dp_netdev_flow_used(netdev_flow, packet);
1709         actions = dp_netdev_actions_ref(netdev_flow->actions);
1710         ovs_mutex_unlock(&netdev_flow->mutex);
1711
1712         dp_netdev_execute_actions(dp, &key, packet, md,
1713                                   actions->actions, actions->size);
1714         dp_netdev_actions_unref(actions);
1715         ovsthread_counter_inc(dp->n_hit, 1);
1716     } else {
1717         ovsthread_counter_inc(dp->n_missed, 1);
1718         dp_netdev_output_userspace(dp, packet, DPIF_UC_MISS, &key, NULL);
1719     }
1720 }
1721
1722 static int
1723 dp_netdev_output_userspace(struct dp_netdev *dp, struct ofpbuf *packet,
1724                            int queue_no, const struct flow *flow,
1725                            const struct nlattr *userdata)
1726     OVS_EXCLUDED(dp->queue_mutex)
1727 {
1728     struct dp_netdev_queue *q = &dp->queues[queue_no];
1729     int error;
1730
1731     ovs_mutex_lock(&dp->queue_mutex);
1732     if (q->head - q->tail < MAX_QUEUE_LEN) {
1733         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
1734         struct dpif_upcall *upcall = &u->upcall;
1735         struct ofpbuf *buf = &u->buf;
1736         size_t buf_size;
1737
1738         upcall->type = queue_no;
1739
1740         /* Allocate buffer big enough for everything. */
1741         buf_size = ODPUTIL_FLOW_KEY_BYTES;
1742         if (userdata) {
1743             buf_size += NLA_ALIGN(userdata->nla_len);
1744         }
1745         ofpbuf_init(buf, buf_size);
1746
1747         /* Put ODP flow. */
1748         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
1749         upcall->key = buf->data;
1750         upcall->key_len = buf->size;
1751
1752         /* Put userdata. */
1753         if (userdata) {
1754             upcall->userdata = ofpbuf_put(buf, userdata,
1755                                           NLA_ALIGN(userdata->nla_len));
1756         }
1757
1758         /* Steal packet data. */
1759         ovs_assert(packet->source == OFPBUF_MALLOC);
1760         upcall->packet = *packet;
1761         ofpbuf_use(packet, NULL, 0);
1762
1763         seq_change(dp->queue_seq);
1764
1765         error = 0;
1766     } else {
1767         ovsthread_counter_inc(dp->n_lost, 1);
1768         error = ENOBUFS;
1769     }
1770     ovs_mutex_unlock(&dp->queue_mutex);
1771
1772     return error;
1773 }
1774
1775 struct dp_netdev_execute_aux {
1776     struct dp_netdev *dp;
1777     const struct flow *key;
1778 };
1779
1780 static void
1781 dp_execute_cb(void *aux_, struct ofpbuf *packet,
1782               const struct pkt_metadata *md OVS_UNUSED,
1783               const struct nlattr *a, bool may_steal)
1784     OVS_NO_THREAD_SAFETY_ANALYSIS
1785 {
1786     struct dp_netdev_execute_aux *aux = aux_;
1787     int type = nl_attr_type(a);
1788     struct dp_netdev_port *p;
1789
1790     switch ((enum ovs_action_attr)type) {
1791     case OVS_ACTION_ATTR_OUTPUT:
1792         p = dp_netdev_lookup_port(aux->dp, u32_to_odp(nl_attr_get_u32(a)));
1793         if (p) {
1794             netdev_send(p->netdev, packet);
1795         }
1796         break;
1797
1798     case OVS_ACTION_ATTR_USERSPACE: {
1799         const struct nlattr *userdata;
1800
1801         userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
1802
1803         /* Make a copy if we are not allowed to steal the packet's data. */
1804         if (!may_steal) {
1805             packet = ofpbuf_clone_with_headroom(packet, DP_NETDEV_HEADROOM);
1806         }
1807         dp_netdev_output_userspace(aux->dp, packet, DPIF_UC_ACTION, aux->key,
1808                                    userdata);
1809         if (!may_steal) {
1810             ofpbuf_uninit(packet);
1811         }
1812         break;
1813     }
1814     case OVS_ACTION_ATTR_PUSH_VLAN:
1815     case OVS_ACTION_ATTR_POP_VLAN:
1816     case OVS_ACTION_ATTR_PUSH_MPLS:
1817     case OVS_ACTION_ATTR_POP_MPLS:
1818     case OVS_ACTION_ATTR_SET:
1819     case OVS_ACTION_ATTR_SAMPLE:
1820     case OVS_ACTION_ATTR_UNSPEC:
1821     case __OVS_ACTION_ATTR_MAX:
1822         OVS_NOT_REACHED();
1823     }
1824 }
1825
1826 static void
1827 dp_netdev_execute_actions(struct dp_netdev *dp, const struct flow *key,
1828                           struct ofpbuf *packet, struct pkt_metadata *md,
1829                           const struct nlattr *actions, size_t actions_len)
1830     OVS_REQ_RDLOCK(dp->port_rwlock)
1831 {
1832     struct dp_netdev_execute_aux aux = {dp, key};
1833
1834     odp_execute_actions(&aux, packet, md, actions, actions_len, dp_execute_cb);
1835 }
1836
1837 #define DPIF_NETDEV_CLASS_FUNCTIONS                     \
1838     dpif_netdev_enumerate,                              \
1839     dpif_netdev_port_open_type,                         \
1840     dpif_netdev_open,                                   \
1841     dpif_netdev_close,                                  \
1842     dpif_netdev_destroy,                                \
1843     NULL,                                       \
1844     NULL,                                       \
1845     dpif_netdev_get_stats,                              \
1846     dpif_netdev_port_add,                               \
1847     dpif_netdev_port_del,                               \
1848     dpif_netdev_port_query_by_number,                   \
1849     dpif_netdev_port_query_by_name,                     \
1850     NULL,                       /* port_get_pid */      \
1851     dpif_netdev_port_dump_start,                        \
1852     dpif_netdev_port_dump_next,                         \
1853     dpif_netdev_port_dump_done,                         \
1854     dpif_netdev_port_poll,                              \
1855     dpif_netdev_port_poll_wait,                         \
1856     dpif_netdev_flow_get,                               \
1857     dpif_netdev_flow_put,                               \
1858     dpif_netdev_flow_del,                               \
1859     dpif_netdev_flow_flush,                             \
1860     dpif_netdev_flow_dump_start,                        \
1861     dpif_netdev_flow_dump_next,                         \
1862     dpif_netdev_flow_dump_done,                         \
1863     dpif_netdev_execute,                                \
1864     NULL,                       /* operate */           \
1865     dpif_netdev_recv_set,                               \
1866     dpif_netdev_queue_to_priority,                      \
1867     dpif_netdev_recv,                                   \
1868     dpif_netdev_recv_wait,                              \
1869     dpif_netdev_recv_purge,                             \
1870
1871 const struct dpif_class dpif_netdev_class = {
1872     "netdev",
1873     DPIF_NETDEV_CLASS_FUNCTIONS
1874 };
1875
1876 const struct dpif_class dpif_planetlab_class = {
1877     "planetlab",
1878     DPIF_NETDEV_CLASS_FUNCTIONS
1879 };
1880
1881 static void
1882 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
1883                               const char *argv[], void *aux OVS_UNUSED)
1884 {
1885     struct dp_netdev_port *port;
1886     struct dp_netdev *dp;
1887     odp_port_t port_no;
1888
1889     ovs_mutex_lock(&dp_netdev_mutex);
1890     dp = shash_find_data(&dp_netdevs, argv[1]);
1891     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
1892         ovs_mutex_unlock(&dp_netdev_mutex);
1893         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
1894         return;
1895     }
1896     ovs_refcount_ref(&dp->ref_cnt);
1897     ovs_mutex_unlock(&dp_netdev_mutex);
1898
1899     ovs_rwlock_wrlock(&dp->port_rwlock);
1900     if (get_port_by_name(dp, argv[2], &port)) {
1901         unixctl_command_reply_error(conn, "unknown port");
1902         goto exit;
1903     }
1904
1905     port_no = u32_to_odp(atoi(argv[3]));
1906     if (!port_no || port_no == ODPP_NONE) {
1907         unixctl_command_reply_error(conn, "bad port number");
1908         goto exit;
1909     }
1910     if (dp_netdev_lookup_port(dp, port_no)) {
1911         unixctl_command_reply_error(conn, "port number already in use");
1912         goto exit;
1913     }
1914     hmap_remove(&dp->ports, &port->node);
1915     port->port_no = port_no;
1916     hmap_insert(&dp->ports, &port->node, hash_int(odp_to_u32(port_no), 0));
1917     seq_change(dp->port_seq);
1918     unixctl_command_reply(conn, NULL);
1919
1920 exit:
1921     ovs_rwlock_unlock(&dp->port_rwlock);
1922     dp_netdev_unref(dp);
1923 }
1924
1925 static void
1926 dpif_dummy_register__(const char *type)
1927 {
1928     struct dpif_class *class;
1929
1930     class = xmalloc(sizeof *class);
1931     *class = dpif_netdev_class;
1932     class->type = xstrdup(type);
1933     dp_register_provider(class);
1934 }
1935
1936 void
1937 dpif_dummy_register(bool override)
1938 {
1939     if (override) {
1940         struct sset types;
1941         const char *type;
1942
1943         sset_init(&types);
1944         dp_enumerate_types(&types);
1945         SSET_FOR_EACH (type, &types) {
1946             if (!dp_unregister_provider(type)) {
1947                 dpif_dummy_register__(type);
1948             }
1949         }
1950         sset_destroy(&types);
1951     }
1952
1953     dpif_dummy_register__("dummy");
1954
1955     unixctl_command_register("dpif-dummy/change-port-number",
1956                              "DP PORT NEW-NUMBER",
1957                              3, 3, dpif_dummy_change_port_number, NULL);
1958 }
1959