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