Merge remote-tracking branch 'ovs-dev/master'
[sliver-openvswitch.git] / lib / dpif-netdev.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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 "csum.h"
35 #include "dpif.h"
36 #include "dpif-provider.h"
37 #include "dummy.h"
38 #include "dynamic-string.h"
39 #include "flow.h"
40 #include "hmap.h"
41 #include "list.h"
42 #include "netdev.h"
43 #include "netdev-vport.h"
44 #include "netlink.h"
45 #include "odp-execute.h"
46 #include "odp-util.h"
47 #include "ofp-print.h"
48 #include "ofpbuf.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "shash.h"
53 #include "sset.h"
54 #include "timeval.h"
55 #include "unixctl.h"
56 #include "util.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(dpif_netdev);
60
61 /* Configuration parameters. */
62 enum { MAX_PORTS = 256 };       /* Maximum number of ports. */
63 enum { MAX_FLOWS = 65536 };     /* Maximum number of flows in flow table. */
64
65 /* Enough headroom to add a vlan tag, plus an extra 2 bytes to allow IP
66  * headers to be aligned on a 4-byte boundary.  */
67 enum { DP_NETDEV_HEADROOM = 2 + VLAN_HEADER_LEN };
68
69 /* Queues. */
70 enum { N_QUEUES = 2 };          /* Number of queues for dpif_recv(). */
71 enum { MAX_QUEUE_LEN = 128 };   /* Maximum number of packets per queue. */
72 enum { QUEUE_MASK = MAX_QUEUE_LEN - 1 };
73 BUILD_ASSERT_DECL(IS_POW2(MAX_QUEUE_LEN));
74
75 struct dp_netdev_upcall {
76     struct dpif_upcall upcall;  /* Queued upcall information. */
77     struct ofpbuf buf;          /* ofpbuf instance for upcall.packet. */
78 };
79
80 struct dp_netdev_queue {
81     struct dp_netdev_upcall upcalls[MAX_QUEUE_LEN];
82     unsigned int head, tail;
83 };
84
85 /* Datapath based on the network device interface from netdev.h. */
86 struct dp_netdev {
87     const struct dpif_class *class;
88     char *name;
89     int open_cnt;
90     bool destroyed;
91     int max_mtu;                /* Maximum MTU of any port added so far. */
92
93     struct dp_netdev_queue queues[N_QUEUES];
94     struct hmap flow_table;     /* Flow table. */
95
96     /* Statistics. */
97     long long int n_hit;        /* Number of flow table matches. */
98     long long int n_missed;     /* Number of flow table misses. */
99     long long int n_lost;       /* Number of misses not passed to client. */
100
101     /* Ports. */
102     struct dp_netdev_port *ports[MAX_PORTS];
103     struct list port_list;
104     unsigned int serial;
105 };
106
107 /* A port in a netdev-based datapath. */
108 struct dp_netdev_port {
109     odp_port_t port_no;         /* Index into dp_netdev's 'ports'. */
110     struct list node;           /* Element in dp_netdev's 'port_list'. */
111     struct netdev *netdev;
112     struct netdev_saved_flags *sf;
113     struct netdev_rx *rx;
114     char *type;                 /* Port type as requested by user. */
115 };
116
117 /* A flow in dp_netdev's 'flow_table'. */
118 struct dp_netdev_flow {
119     struct hmap_node node;      /* Element in dp_netdev's 'flow_table'. */
120     struct flow key;
121
122     /* Statistics. */
123     long long int used;         /* Last used time, in monotonic msecs. */
124     long long int packet_count; /* Number of packets matched. */
125     long long int byte_count;   /* Number of bytes matched. */
126     uint8_t tcp_flags;          /* Bitwise-OR of seen tcp_flags values. */
127
128     /* Actions. */
129     struct nlattr *actions;
130     size_t actions_len;
131 };
132
133 /* Interface to netdev-based datapath. */
134 struct dpif_netdev {
135     struct dpif dpif;
136     struct dp_netdev *dp;
137     unsigned int dp_serial;
138 };
139
140 /* All netdev-based datapaths. */
141 static struct shash dp_netdevs = SHASH_INITIALIZER(&dp_netdevs);
142
143 /* Global lock for all data. */
144 static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
145
146 static int get_port_by_number(struct dp_netdev *, odp_port_t port_no,
147                               struct dp_netdev_port **portp);
148 static int get_port_by_name(struct dp_netdev *, const char *devname,
149                             struct dp_netdev_port **portp);
150 static void dp_netdev_free(struct dp_netdev *);
151 static void dp_netdev_flow_flush(struct dp_netdev *);
152 static int do_add_port(struct dp_netdev *, const char *devname,
153                        const char *type, odp_port_t port_no);
154 static int do_del_port(struct dp_netdev *, odp_port_t port_no);
155 static int dpif_netdev_open(const struct dpif_class *, const char *name,
156                             bool create, struct dpif **);
157 static int dp_netdev_output_userspace(struct dp_netdev *, const struct ofpbuf *,
158                                     int queue_no, const struct flow *,
159                                     const struct nlattr *userdata);
160 static void dp_netdev_execute_actions(struct dp_netdev *,
161                                       struct ofpbuf *, struct flow *,
162                                       const struct nlattr *actions,
163                                       size_t actions_len);
164 static void dp_netdev_port_input(struct dp_netdev *dp,
165                                  struct dp_netdev_port *port,
166                                  struct ofpbuf *packet, uint32_t skb_priority,
167                                  uint32_t skb_mark, const struct flow_tnl *tnl);
168
169 static struct dpif_netdev *
170 dpif_netdev_cast(const struct dpif *dpif)
171 {
172     ovs_assert(dpif->dpif_class->open == dpif_netdev_open);
173     return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
174 }
175
176 static struct dp_netdev *
177 get_dp_netdev(const struct dpif *dpif)
178 {
179     return dpif_netdev_cast(dpif)->dp;
180 }
181
182 static int
183 dpif_netdev_enumerate(struct sset *all_dps)
184 {
185     struct shash_node *node;
186
187     ovs_mutex_lock(&dp_netdev_mutex);
188     SHASH_FOR_EACH(node, &dp_netdevs) {
189         sset_add(all_dps, node->name);
190     }
191     ovs_mutex_unlock(&dp_netdev_mutex);
192
193     return 0;
194 }
195
196 static bool
197 dpif_netdev_class_is_dummy(const struct dpif_class *class)
198 {
199     return class != &dpif_netdev_class;
200 }
201
202 static bool
203 dpif_netdev_class_is_planetlab(const struct dpif_class *class)
204 {
205     return class == &dpif_planetlab_class;
206 }
207
208 static const char *
209 dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
210 {
211     return strcmp(type, "internal") ? type
212                   : dpif_netdev_class_is_planetlab(class) ? "pltap"
213                   : dpif_netdev_class_is_dummy(class) ? "dummy"
214                   : "tap";
215 }
216
217 static struct dpif *
218 create_dpif_netdev(struct dp_netdev *dp)
219 {
220     uint16_t netflow_id = hash_string(dp->name, 0);
221     struct dpif_netdev *dpif;
222
223     dp->open_cnt++;
224
225     dpif = xmalloc(sizeof *dpif);
226     dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
227     dpif->dp = dp;
228     dpif->dp_serial = dp->serial;
229
230     return &dpif->dpif;
231 }
232
233 /* Choose an unused, non-zero port number and return it on success.
234  * Return ODPP_NONE on failure. */
235 static odp_port_t
236 choose_port(struct dp_netdev *dp, const char *name)
237 {
238     uint32_t port_no;
239
240     if (dp->class != &dpif_netdev_class && 
241         dp->class != &dpif_planetlab_class) {
242         const char *p;
243         int start_no = 0;
244
245         /* If the port name begins with "br", start the number search at
246          * 100 to make writing tests easier. */
247         if (!strncmp(name, "br", 2)) {
248             start_no = 100;
249         }
250
251         /* If the port name contains a number, try to assign that port number.
252          * This can make writing unit tests easier because port numbers are
253          * predictable. */
254         for (p = name; *p != '\0'; p++) {
255             if (isdigit((unsigned char) *p)) {
256                 port_no = start_no + strtol(p, NULL, 10);
257                 if (port_no > 0 && port_no < MAX_PORTS
258                     && !dp->ports[port_no]) {
259                     return u32_to_odp(port_no);
260                 }
261                 break;
262             }
263         }
264     }
265
266     for (port_no = 1; port_no < MAX_PORTS; port_no++) {
267         if (!dp->ports[port_no]) {
268             return u32_to_odp(port_no);
269         }
270     }
271
272     return ODPP_NONE;
273 }
274
275 static int
276 create_dp_netdev(const char *name, const struct dpif_class *class,
277                  struct dp_netdev **dpp)
278 {
279     struct dp_netdev *dp;
280     int error;
281     int i;
282
283     dp = xzalloc(sizeof *dp);
284     dp->class = class;
285     dp->name = xstrdup(name);
286     dp->open_cnt = 0;
287     dp->max_mtu = ETH_PAYLOAD_MAX;
288     for (i = 0; i < N_QUEUES; i++) {
289         dp->queues[i].head = dp->queues[i].tail = 0;
290     }
291     hmap_init(&dp->flow_table);
292     list_init(&dp->port_list);
293
294     error = do_add_port(dp, name, "internal", ODPP_LOCAL);
295     if (error) {
296         dp_netdev_free(dp);
297         return error;
298     }
299
300     shash_add(&dp_netdevs, name, dp);
301
302     *dpp = dp;
303     return 0;
304 }
305
306 static int
307 dpif_netdev_open(const struct dpif_class *class, const char *name,
308                  bool create, struct dpif **dpifp)
309 {
310     struct dp_netdev *dp;
311     int error;
312
313     ovs_mutex_lock(&dp_netdev_mutex);
314     dp = shash_find_data(&dp_netdevs, name);
315     if (!dp) {
316         error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
317     } else {
318         error = (dp->class != class ? EINVAL
319                  : create ? EEXIST
320                  : 0);
321     }
322     if (!error) {
323         *dpifp = create_dpif_netdev(dp);
324     }
325     ovs_mutex_unlock(&dp_netdev_mutex);
326
327     return error;
328 }
329
330 static void
331 dp_netdev_purge_queues(struct dp_netdev *dp)
332 {
333     int i;
334
335     for (i = 0; i < N_QUEUES; i++) {
336         struct dp_netdev_queue *q = &dp->queues[i];
337
338         while (q->tail != q->head) {
339             struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
340             ofpbuf_uninit(&u->buf);
341         }
342     }
343 }
344
345 static void
346 dp_netdev_free(struct dp_netdev *dp)
347 {
348     struct dp_netdev_port *port, *next;
349
350     dp_netdev_flow_flush(dp);
351     LIST_FOR_EACH_SAFE (port, next, node, &dp->port_list) {
352         do_del_port(dp, port->port_no);
353     }
354     dp_netdev_purge_queues(dp);
355     hmap_destroy(&dp->flow_table);
356     free(dp->name);
357     free(dp);
358 }
359
360 static void
361 dpif_netdev_close(struct dpif *dpif)
362 {
363     struct dp_netdev *dp = get_dp_netdev(dpif);
364
365     ovs_mutex_lock(&dp_netdev_mutex);
366
367     ovs_assert(dp->open_cnt > 0);
368     if (--dp->open_cnt == 0 && dp->destroyed) {
369         shash_find_and_delete(&dp_netdevs, dp->name);
370         dp_netdev_free(dp);
371     }
372     free(dpif);
373
374     ovs_mutex_unlock(&dp_netdev_mutex);
375 }
376
377 static int
378 dpif_netdev_destroy(struct dpif *dpif)
379 {
380     struct dp_netdev *dp = get_dp_netdev(dpif);
381
382     ovs_mutex_lock(&dp_netdev_mutex);
383     dp->destroyed = true;
384     ovs_mutex_unlock(&dp_netdev_mutex);
385
386     return 0;
387 }
388
389 static int
390 dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
391 {
392     struct dp_netdev *dp = get_dp_netdev(dpif);
393
394     ovs_mutex_lock(&dp_netdev_mutex);
395     stats->n_flows = hmap_count(&dp->flow_table);
396     stats->n_hit = dp->n_hit;
397     stats->n_missed = dp->n_missed;
398     stats->n_lost = dp->n_lost;
399     ovs_mutex_unlock(&dp_netdev_mutex);
400
401     return 0;
402 }
403
404 static int
405 do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
406             odp_port_t port_no)
407 {
408     struct netdev_saved_flags *sf;
409     struct dp_netdev_port *port;
410     struct netdev *netdev;
411     struct netdev_rx *rx;
412     const char *open_type;
413     int mtu;
414     int error;
415
416     /* XXX reject devices already in some dp_netdev. */
417
418     /* Open and validate network device. */
419     open_type = dpif_netdev_port_open_type(dp->class, type);
420     error = netdev_open(devname, open_type, &netdev);
421     if (error) {
422         return error;
423     }
424     /* XXX reject loopback devices */
425     /* XXX reject non-Ethernet devices */
426
427     error = netdev_rx_open(netdev, &rx);
428     if (error
429         && !(error == EOPNOTSUPP && dpif_netdev_class_is_dummy(dp->class))) {
430         VLOG_ERR("%s: cannot receive packets on this network device (%s)",
431                  devname, ovs_strerror(errno));
432         netdev_close(netdev);
433         return error;
434     }
435
436     error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
437     if (error) {
438         netdev_rx_close(rx);
439         netdev_close(netdev);
440         return error;
441     }
442
443     port = xmalloc(sizeof *port);
444     port->port_no = port_no;
445     port->netdev = netdev;
446     port->sf = sf;
447     port->rx = rx;
448     port->type = xstrdup(type);
449
450     error = netdev_get_mtu(netdev, &mtu);
451     if (!error && mtu > dp->max_mtu) {
452         dp->max_mtu = mtu;
453     }
454
455     list_push_back(&dp->port_list, &port->node);
456     dp->ports[odp_to_u32(port_no)] = port;
457     dp->serial++;
458
459     return 0;
460 }
461
462 static int
463 dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
464                      odp_port_t *port_nop)
465 {
466     struct dp_netdev *dp = get_dp_netdev(dpif);
467     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
468     const char *dpif_port;
469     odp_port_t port_no;
470     int error;
471
472     ovs_mutex_lock(&dp_netdev_mutex);
473     dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
474     if (*port_nop != ODPP_NONE) {
475         uint32_t port_idx = odp_to_u32(*port_nop);
476         if (port_idx >= MAX_PORTS) {
477             error = EFBIG;
478         } else if (dp->ports[port_idx]) {
479             error = EBUSY;
480         } else {
481             error = 0;
482             port_no = *port_nop;
483         }
484     } else {
485         port_no = choose_port(dp, dpif_port);
486         error = port_no == ODPP_NONE ? EFBIG : 0;
487     }
488     if (!error) {
489         *port_nop = port_no;
490         error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
491     }
492     ovs_mutex_unlock(&dp_netdev_mutex);
493
494     return error;
495 }
496
497 static int
498 dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
499 {
500     struct dp_netdev *dp = get_dp_netdev(dpif);
501     int error;
502
503     ovs_mutex_lock(&dp_netdev_mutex);
504     error = port_no == ODPP_LOCAL ? EINVAL : do_del_port(dp, port_no);
505     ovs_mutex_unlock(&dp_netdev_mutex);
506
507     return error;
508 }
509
510 static bool
511 is_valid_port_number(odp_port_t port_no)
512 {
513     return odp_to_u32(port_no) < MAX_PORTS;
514 }
515
516 static int
517 get_port_by_number(struct dp_netdev *dp,
518                    odp_port_t port_no, struct dp_netdev_port **portp)
519 {
520     if (!is_valid_port_number(port_no)) {
521         *portp = NULL;
522         return EINVAL;
523     } else {
524         *portp = dp->ports[odp_to_u32(port_no)];
525         return *portp ? 0 : ENOENT;
526     }
527 }
528
529 static int
530 get_port_by_name(struct dp_netdev *dp,
531                  const char *devname, struct dp_netdev_port **portp)
532 {
533     struct dp_netdev_port *port;
534
535     LIST_FOR_EACH (port, node, &dp->port_list) {
536         if (!strcmp(netdev_get_name(port->netdev), devname)) {
537             *portp = port;
538             return 0;
539         }
540     }
541     return ENOENT;
542 }
543
544 static int
545 do_del_port(struct dp_netdev *dp, odp_port_t port_no)
546 {
547     struct dp_netdev_port *port;
548     int error;
549
550     error = get_port_by_number(dp, port_no, &port);
551     if (error) {
552         return error;
553     }
554
555     list_remove(&port->node);
556     dp->ports[odp_to_u32(port_no)] = NULL;
557     dp->serial++;
558
559     netdev_close(port->netdev);
560     netdev_restore_flags(port->sf);
561     netdev_rx_close(port->rx);
562     free(port->type);
563     free(port);
564
565     return 0;
566 }
567
568 static void
569 answer_port_query(const struct dp_netdev_port *port,
570                   struct dpif_port *dpif_port)
571 {
572     dpif_port->name = xstrdup(netdev_get_name(port->netdev));
573     dpif_port->type = xstrdup(port->type);
574     dpif_port->port_no = port->port_no;
575 }
576
577 static int
578 dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
579                                  struct dpif_port *dpif_port)
580 {
581     struct dp_netdev *dp = get_dp_netdev(dpif);
582     struct dp_netdev_port *port;
583     int error;
584
585     ovs_mutex_lock(&dp_netdev_mutex);
586     error = get_port_by_number(dp, port_no, &port);
587     if (!error && dpif_port) {
588         answer_port_query(port, dpif_port);
589     }
590     ovs_mutex_unlock(&dp_netdev_mutex);
591
592     return error;
593 }
594
595 static int
596 dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
597                                struct dpif_port *dpif_port)
598 {
599     struct dp_netdev *dp = get_dp_netdev(dpif);
600     struct dp_netdev_port *port;
601     int error;
602
603     ovs_mutex_lock(&dp_netdev_mutex);
604     error = get_port_by_name(dp, devname, &port);
605     if (!error && dpif_port) {
606         answer_port_query(port, dpif_port);
607     }
608     ovs_mutex_unlock(&dp_netdev_mutex);
609
610     return error;
611 }
612
613 static odp_port_t
614 dpif_netdev_get_max_ports(const struct dpif *dpif OVS_UNUSED)
615 {
616     return u32_to_odp(MAX_PORTS);
617 }
618
619 static void
620 dp_netdev_free_flow(struct dp_netdev *dp, struct dp_netdev_flow *flow)
621 {
622     hmap_remove(&dp->flow_table, &flow->node);
623     free(flow->actions);
624     free(flow);
625 }
626
627 static void
628 dp_netdev_flow_flush(struct dp_netdev *dp)
629 {
630     struct dp_netdev_flow *flow, *next;
631
632     HMAP_FOR_EACH_SAFE (flow, next, node, &dp->flow_table) {
633         dp_netdev_free_flow(dp, flow);
634     }
635 }
636
637 static int
638 dpif_netdev_flow_flush(struct dpif *dpif)
639 {
640     struct dp_netdev *dp = get_dp_netdev(dpif);
641
642     ovs_mutex_lock(&dp_netdev_mutex);
643     dp_netdev_flow_flush(dp);
644     ovs_mutex_unlock(&dp_netdev_mutex);
645
646     return 0;
647 }
648
649 struct dp_netdev_port_state {
650     odp_port_t port_no;
651     char *name;
652 };
653
654 static int
655 dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
656 {
657     *statep = xzalloc(sizeof(struct dp_netdev_port_state));
658     return 0;
659 }
660
661 static int
662 dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
663                            struct dpif_port *dpif_port)
664 {
665     struct dp_netdev_port_state *state = state_;
666     struct dp_netdev *dp = get_dp_netdev(dpif);
667     uint32_t port_idx;
668
669     ovs_mutex_lock(&dp_netdev_mutex);
670     for (port_idx = odp_to_u32(state->port_no);
671          port_idx < MAX_PORTS; port_idx++) {
672         struct dp_netdev_port *port = dp->ports[port_idx];
673         if (port) {
674             free(state->name);
675             state->name = xstrdup(netdev_get_name(port->netdev));
676             dpif_port->name = state->name;
677             dpif_port->type = port->type;
678             dpif_port->port_no = port->port_no;
679             state->port_no = u32_to_odp(port_idx + 1);
680             ovs_mutex_unlock(&dp_netdev_mutex);
681
682             return 0;
683         }
684     }
685     ovs_mutex_unlock(&dp_netdev_mutex);
686
687     return EOF;
688 }
689
690 static int
691 dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
692 {
693     struct dp_netdev_port_state *state = state_;
694     free(state->name);
695     free(state);
696     return 0;
697 }
698
699 static int
700 dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
701 {
702     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
703     int error;
704
705     ovs_mutex_lock(&dp_netdev_mutex);
706     if (dpif->dp_serial != dpif->dp->serial) {
707         dpif->dp_serial = dpif->dp->serial;
708         error = ENOBUFS;
709     } else {
710         error = EAGAIN;
711     }
712     ovs_mutex_unlock(&dp_netdev_mutex);
713
714     return error;
715 }
716
717 static void
718 dpif_netdev_port_poll_wait(const struct dpif *dpif_)
719 {
720     struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
721
722     /* XXX In a multithreaded process, there is a race window between this
723      * function and the poll_block() in one thread and a change in
724      * dpif->dp->serial in another thread. */
725
726     ovs_mutex_lock(&dp_netdev_mutex);
727     if (dpif->dp_serial != dpif->dp->serial) {
728         poll_immediate_wake();
729     }
730     ovs_mutex_unlock(&dp_netdev_mutex);
731 }
732
733 static struct dp_netdev_flow *
734 dp_netdev_lookup_flow(const struct dp_netdev *dp, const struct flow *key)
735 {
736     struct dp_netdev_flow *flow;
737
738     HMAP_FOR_EACH_WITH_HASH (flow, node, flow_hash(key, 0), &dp->flow_table) {
739         if (flow_equal(&flow->key, key)) {
740             return flow;
741         }
742     }
743     return NULL;
744 }
745
746 static void
747 get_dpif_flow_stats(struct dp_netdev_flow *flow, struct dpif_flow_stats *stats)
748 {
749     stats->n_packets = flow->packet_count;
750     stats->n_bytes = flow->byte_count;
751     stats->used = flow->used;
752     stats->tcp_flags = flow->tcp_flags;
753 }
754
755 static int
756 dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
757                               struct flow *flow)
758 {
759     odp_port_t in_port;
760
761     if (odp_flow_key_to_flow(key, key_len, flow) != ODP_FIT_PERFECT) {
762         /* This should not happen: it indicates that odp_flow_key_from_flow()
763          * and odp_flow_key_to_flow() disagree on the acceptable form of a
764          * flow.  Log the problem as an error, with enough details to enable
765          * debugging. */
766         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
767
768         if (!VLOG_DROP_ERR(&rl)) {
769             struct ds s;
770
771             ds_init(&s);
772             odp_flow_key_format(key, key_len, &s);
773             VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
774             ds_destroy(&s);
775         }
776
777         return EINVAL;
778     }
779
780     in_port = flow->in_port.odp_port;
781     if (!is_valid_port_number(in_port) && in_port != ODPP_NONE) {
782         return EINVAL;
783     }
784
785     return 0;
786 }
787
788 static int
789 dpif_netdev_flow_get(const struct dpif *dpif,
790                      const struct nlattr *nl_key, size_t nl_key_len,
791                      struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
792 {
793     struct dp_netdev *dp = get_dp_netdev(dpif);
794     struct dp_netdev_flow *flow;
795     struct flow key;
796     int error;
797
798     error = dpif_netdev_flow_from_nlattrs(nl_key, nl_key_len, &key);
799     if (error) {
800         return error;
801     }
802
803     ovs_mutex_lock(&dp_netdev_mutex);
804     flow = dp_netdev_lookup_flow(dp, &key);
805     if (flow) {
806         if (stats) {
807             get_dpif_flow_stats(flow, stats);
808         }
809         if (actionsp) {
810             *actionsp = ofpbuf_clone_data(flow->actions, flow->actions_len);
811         }
812     } else {
813         error = ENOENT;
814     }
815     ovs_mutex_unlock(&dp_netdev_mutex);
816
817     return error;
818 }
819
820 static int
821 set_flow_actions(struct dp_netdev_flow *flow,
822                  const struct nlattr *actions, size_t actions_len)
823 {
824     flow->actions = xrealloc(flow->actions, actions_len);
825     flow->actions_len = actions_len;
826     memcpy(flow->actions, actions, actions_len);
827     return 0;
828 }
829
830 static int
831 dp_netdev_flow_add(struct dp_netdev *dp, const struct flow *key,
832                    const struct nlattr *actions, size_t actions_len)
833 {
834     struct dp_netdev_flow *flow;
835     int error;
836
837     flow = xzalloc(sizeof *flow);
838     flow->key = *key;
839
840     error = set_flow_actions(flow, actions, actions_len);
841     if (error) {
842         free(flow);
843         return error;
844     }
845
846     hmap_insert(&dp->flow_table, &flow->node, flow_hash(&flow->key, 0));
847     return 0;
848 }
849
850 static void
851 clear_stats(struct dp_netdev_flow *flow)
852 {
853     flow->used = 0;
854     flow->packet_count = 0;
855     flow->byte_count = 0;
856     flow->tcp_flags = 0;
857 }
858
859 static int
860 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
861 {
862     struct dp_netdev *dp = get_dp_netdev(dpif);
863     struct dp_netdev_flow *flow;
864     struct flow key;
865     int error;
866
867     error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &key);
868     if (error) {
869         return error;
870     }
871
872     ovs_mutex_lock(&dp_netdev_mutex);
873     flow = dp_netdev_lookup_flow(dp, &key);
874     if (!flow) {
875         if (put->flags & DPIF_FP_CREATE) {
876             if (hmap_count(&dp->flow_table) < MAX_FLOWS) {
877                 if (put->stats) {
878                     memset(put->stats, 0, sizeof *put->stats);
879                 }
880                 error = dp_netdev_flow_add(dp, &key, put->actions,
881                                            put->actions_len);
882             } else {
883                 error = EFBIG;
884             }
885         } else {
886             error = ENOENT;
887         }
888     } else {
889         if (put->flags & DPIF_FP_MODIFY) {
890             error = set_flow_actions(flow, put->actions, put->actions_len);
891             if (!error) {
892                 if (put->stats) {
893                     get_dpif_flow_stats(flow, put->stats);
894                 }
895                 if (put->flags & DPIF_FP_ZERO_STATS) {
896                     clear_stats(flow);
897                 }
898             }
899         } else {
900             error = EEXIST;
901         }
902     }
903     ovs_mutex_unlock(&dp_netdev_mutex);
904
905     return error;
906 }
907
908 static int
909 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
910 {
911     struct dp_netdev *dp = get_dp_netdev(dpif);
912     struct dp_netdev_flow *flow;
913     struct flow key;
914     int error;
915
916     error = dpif_netdev_flow_from_nlattrs(del->key, del->key_len, &key);
917     if (error) {
918         return error;
919     }
920
921     ovs_mutex_lock(&dp_netdev_mutex);
922     flow = dp_netdev_lookup_flow(dp, &key);
923     if (flow) {
924         if (del->stats) {
925             get_dpif_flow_stats(flow, del->stats);
926         }
927         dp_netdev_free_flow(dp, flow);
928     } else {
929         error = ENOENT;
930     }
931     ovs_mutex_unlock(&dp_netdev_mutex);
932
933     return error;
934 }
935
936 struct dp_netdev_flow_state {
937     uint32_t bucket;
938     uint32_t offset;
939     struct nlattr *actions;
940     struct odputil_keybuf keybuf;
941     struct dpif_flow_stats stats;
942 };
943
944 static int
945 dpif_netdev_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
946 {
947     struct dp_netdev_flow_state *state;
948
949     *statep = state = xmalloc(sizeof *state);
950     state->bucket = 0;
951     state->offset = 0;
952     state->actions = NULL;
953     return 0;
954 }
955
956 static int
957 dpif_netdev_flow_dump_next(const struct dpif *dpif, void *state_,
958                            const struct nlattr **key, size_t *key_len,
959                            const struct nlattr **mask, size_t *mask_len,
960                            const struct nlattr **actions, size_t *actions_len,
961                            const struct dpif_flow_stats **stats)
962 {
963     struct dp_netdev_flow_state *state = state_;
964     struct dp_netdev *dp = get_dp_netdev(dpif);
965     struct dp_netdev_flow *flow;
966     struct hmap_node *node;
967
968     ovs_mutex_lock(&dp_netdev_mutex);
969     node = hmap_at_position(&dp->flow_table, &state->bucket, &state->offset);
970     if (!node) {
971         ovs_mutex_unlock(&dp_netdev_mutex);
972         return EOF;
973     }
974
975     flow = CONTAINER_OF(node, struct dp_netdev_flow, node);
976
977     if (key) {
978         struct ofpbuf buf;
979
980         ofpbuf_use_stack(&buf, &state->keybuf, sizeof state->keybuf);
981         odp_flow_key_from_flow(&buf, &flow->key, flow->key.in_port.odp_port);
982
983         *key = buf.data;
984         *key_len = buf.size;
985     }
986
987     if (mask) {
988         *mask = NULL;
989         *mask_len = 0;
990     }
991
992     if (actions) {
993         free(state->actions);
994         state->actions = xmemdup(flow->actions, flow->actions_len);
995
996         *actions = state->actions;
997         *actions_len = flow->actions_len;
998     }
999
1000     if (stats) {
1001         get_dpif_flow_stats(flow, &state->stats);
1002         *stats = &state->stats;
1003     }
1004
1005     ovs_mutex_unlock(&dp_netdev_mutex);
1006     return 0;
1007 }
1008
1009 static int
1010 dpif_netdev_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1011 {
1012     struct dp_netdev_flow_state *state = state_;
1013
1014     free(state->actions);
1015     free(state);
1016     return 0;
1017 }
1018
1019 static int
1020 dpif_netdev_execute(struct dpif *dpif, const struct dpif_execute *execute)
1021 {
1022     struct dp_netdev *dp = get_dp_netdev(dpif);
1023     struct ofpbuf copy;
1024     struct flow key;
1025     int error;
1026
1027     if (execute->packet->size < ETH_HEADER_LEN ||
1028         execute->packet->size > UINT16_MAX) {
1029         return EINVAL;
1030     }
1031
1032     /* Make a deep copy of 'packet', because we might modify its data. */
1033     ofpbuf_init(&copy, DP_NETDEV_HEADROOM + execute->packet->size);
1034     ofpbuf_reserve(&copy, DP_NETDEV_HEADROOM);
1035     ofpbuf_put(&copy, execute->packet->data, execute->packet->size);
1036
1037     flow_extract(&copy, 0, 0, NULL, NULL, &key);
1038     error = dpif_netdev_flow_from_nlattrs(execute->key, execute->key_len,
1039                                           &key);
1040     if (!error) {
1041         ovs_mutex_lock(&dp_netdev_mutex);
1042         dp_netdev_execute_actions(dp, &copy, &key,
1043                                   execute->actions, execute->actions_len);
1044         ovs_mutex_unlock(&dp_netdev_mutex);
1045     }
1046
1047     ofpbuf_uninit(&copy);
1048     return error;
1049 }
1050
1051 static int
1052 dpif_netdev_recv_set(struct dpif *dpif OVS_UNUSED, bool enable OVS_UNUSED)
1053 {
1054     return 0;
1055 }
1056
1057 static int
1058 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1059                               uint32_t queue_id, uint32_t *priority)
1060 {
1061     *priority = queue_id;
1062     return 0;
1063 }
1064
1065 static struct dp_netdev_queue *
1066 find_nonempty_queue(struct dpif *dpif)
1067 {
1068     struct dp_netdev *dp = get_dp_netdev(dpif);
1069     int i;
1070
1071     for (i = 0; i < N_QUEUES; i++) {
1072         struct dp_netdev_queue *q = &dp->queues[i];
1073         if (q->head != q->tail) {
1074             return q;
1075         }
1076     }
1077     return NULL;
1078 }
1079
1080 static int
1081 dpif_netdev_recv(struct dpif *dpif, struct dpif_upcall *upcall,
1082                  struct ofpbuf *buf)
1083 {
1084     struct dp_netdev_queue *q;
1085     int error;
1086
1087     ovs_mutex_lock(&dp_netdev_mutex);
1088     q = find_nonempty_queue(dpif);
1089     if (q) {
1090         struct dp_netdev_upcall *u = &q->upcalls[q->tail++ & QUEUE_MASK];
1091
1092         *upcall = u->upcall;
1093         upcall->packet = buf;
1094
1095         ofpbuf_uninit(buf);
1096         *buf = u->buf;
1097
1098         error = 0;
1099     } else {
1100         error = EAGAIN;
1101     }
1102     ovs_mutex_unlock(&dp_netdev_mutex);
1103
1104     return error;
1105 }
1106
1107 static void
1108 dpif_netdev_recv_wait(struct dpif *dpif)
1109 {
1110     /* XXX In a multithreaded process, there is a race window between this
1111      * function and the poll_block() in one thread and a packet being queued in
1112      * another thread. */
1113
1114     ovs_mutex_lock(&dp_netdev_mutex);
1115     if (find_nonempty_queue(dpif)) {
1116         poll_immediate_wake();
1117     }
1118     ovs_mutex_unlock(&dp_netdev_mutex);
1119 }
1120
1121 static void
1122 dpif_netdev_recv_purge(struct dpif *dpif)
1123 {
1124     struct dpif_netdev *dpif_netdev = dpif_netdev_cast(dpif);
1125     ovs_mutex_lock(&dp_netdev_mutex);
1126     dp_netdev_purge_queues(dpif_netdev->dp);
1127     ovs_mutex_unlock(&dp_netdev_mutex);
1128 }
1129 \f
1130 static void
1131 dp_netdev_flow_used(struct dp_netdev_flow *flow, const struct ofpbuf *packet)
1132 {
1133     flow->used = time_msec();
1134     flow->packet_count++;
1135     flow->byte_count += packet->size;
1136     flow->tcp_flags |= packet_get_tcp_flags(packet, &flow->key);
1137 }
1138
1139 static void
1140 dp_netdev_port_input(struct dp_netdev *dp, struct dp_netdev_port *port,
1141                      struct ofpbuf *packet, uint32_t skb_priority,
1142                      uint32_t skb_mark, const struct flow_tnl *tnl)
1143 {
1144     struct dp_netdev_flow *flow;
1145     struct flow key;
1146     union flow_in_port in_port_;
1147
1148     if (packet->size < ETH_HEADER_LEN) {
1149         return;
1150     }
1151     in_port_.odp_port = port->port_no;
1152     flow_extract(packet, skb_priority, skb_mark, tnl, &in_port_, &key);
1153     flow = dp_netdev_lookup_flow(dp, &key);
1154     if (flow) {
1155         dp_netdev_flow_used(flow, packet);
1156         dp_netdev_execute_actions(dp, packet, &key,
1157                                   flow->actions, flow->actions_len);
1158         dp->n_hit++;
1159     } else {
1160         dp->n_missed++;
1161         dp_netdev_output_userspace(dp, packet, DPIF_UC_MISS, &key, NULL);
1162     }
1163 }
1164
1165 static void
1166 dpif_netdev_run(struct dpif *dpif)
1167 {
1168     struct dp_netdev_port *port;
1169     struct dp_netdev *dp;
1170     struct ofpbuf packet;
1171
1172     ovs_mutex_lock(&dp_netdev_mutex);
1173     dp = get_dp_netdev(dpif);
1174     ofpbuf_init(&packet,
1175                 DP_NETDEV_HEADROOM + VLAN_ETH_HEADER_LEN + dp->max_mtu);
1176
1177     LIST_FOR_EACH (port, node, &dp->port_list) {
1178         int error;
1179
1180         /* Reset packet contents. */
1181         ofpbuf_clear(&packet);
1182         ofpbuf_reserve(&packet, DP_NETDEV_HEADROOM);
1183
1184         error = port->rx ? netdev_rx_recv(port->rx, &packet) : EOPNOTSUPP;
1185         if (!error) {
1186             dp_netdev_port_input(dp, port, &packet, 0, 0, NULL);
1187         } else if (error != EAGAIN && error != EOPNOTSUPP) {
1188             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1189
1190             VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
1191                         netdev_get_name(port->netdev), ovs_strerror(error));
1192         }
1193     }
1194     ofpbuf_uninit(&packet);
1195     ovs_mutex_unlock(&dp_netdev_mutex);
1196 }
1197
1198 static void
1199 dpif_netdev_wait(struct dpif *dpif)
1200 {
1201     struct dp_netdev_port *port;
1202
1203     /* There is a race here, if thread A calls dpif_netdev_wait(dpif) and
1204      * thread B calls dpif_port_add(dpif) or dpif_port_remove(dpif) before
1205      * A makes it to poll_block().
1206      *
1207      * But I think it doesn't matter:
1208      *
1209      *     - In the dpif_port_add() case, A will not wake up when a packet
1210      *       arrives on the new port, but this would also happen if the
1211      *       ordering were reversed.
1212      *
1213      *     - In the dpif_port_remove() case, A might wake up spuriously, but
1214      *       that is harmless. */
1215
1216     ovs_mutex_lock(&dp_netdev_mutex);
1217     LIST_FOR_EACH (port, node, &get_dp_netdev(dpif)->port_list) {
1218         if (port->rx) {
1219             netdev_rx_wait(port->rx);
1220         }
1221     }
1222     ovs_mutex_unlock(&dp_netdev_mutex);
1223 }
1224
1225 static void
1226 dp_netdev_output_port(void *dp_, struct ofpbuf *packet, uint32_t out_port)
1227 {
1228     struct dp_netdev *dp = dp_;
1229     struct dp_netdev_port *p = dp->ports[out_port];
1230     if (p) {
1231         netdev_send(p->netdev, packet);
1232     }
1233 }
1234
1235 static int
1236 dp_netdev_output_userspace(struct dp_netdev *dp, const struct ofpbuf *packet,
1237                            int queue_no, const struct flow *flow,
1238                            const struct nlattr *userdata)
1239 {
1240     struct dp_netdev_queue *q = &dp->queues[queue_no];
1241     if (q->head - q->tail < MAX_QUEUE_LEN) {
1242         struct dp_netdev_upcall *u = &q->upcalls[q->head++ & QUEUE_MASK];
1243         struct dpif_upcall *upcall = &u->upcall;
1244         struct ofpbuf *buf = &u->buf;
1245         size_t buf_size;
1246
1247         upcall->type = queue_no;
1248
1249         /* Allocate buffer big enough for everything. */
1250         buf_size = ODPUTIL_FLOW_KEY_BYTES + 2 + packet->size;
1251         if (userdata) {
1252             buf_size += NLA_ALIGN(userdata->nla_len);
1253         }
1254         ofpbuf_init(buf, buf_size);
1255
1256         /* Put ODP flow. */
1257         odp_flow_key_from_flow(buf, flow, flow->in_port.odp_port);
1258         upcall->key = buf->data;
1259         upcall->key_len = buf->size;
1260
1261         /* Put userdata. */
1262         if (userdata) {
1263             upcall->userdata = ofpbuf_put(buf, userdata,
1264                                           NLA_ALIGN(userdata->nla_len));
1265         }
1266
1267         /* Put packet.
1268          *
1269          * We adjust 'data' and 'size' in 'buf' so that only the packet itself
1270          * is visible in 'upcall->packet'.  The ODP flow and (if present)
1271          * userdata become part of the headroom. */
1272         ofpbuf_put_zeros(buf, 2);
1273         buf->data = ofpbuf_put(buf, packet->data, packet->size);
1274         buf->size = packet->size;
1275         upcall->packet = buf;
1276
1277         return 0;
1278     } else {
1279         dp->n_lost++;
1280         return ENOBUFS;
1281     }
1282 }
1283
1284 static void
1285 dp_netdev_action_userspace(void *dp, struct ofpbuf *packet,
1286                            const struct flow *key,
1287                            const struct nlattr *userdata)
1288 {
1289     dp_netdev_output_userspace(dp, packet, DPIF_UC_ACTION, key, userdata);
1290 }
1291
1292 static void
1293 dp_netdev_execute_actions(struct dp_netdev *dp,
1294                           struct ofpbuf *packet, struct flow *key,
1295                           const struct nlattr *actions,
1296                           size_t actions_len)
1297 {
1298     odp_execute_actions(dp, packet, key, actions, actions_len,
1299                         dp_netdev_output_port, dp_netdev_action_userspace);
1300 }
1301
1302 #define DPIF_NETDEV_CLASS_FUNCTIONS                     \
1303     dpif_netdev_enumerate,                              \
1304     dpif_netdev_port_open_type,                         \
1305     dpif_netdev_open,                                   \
1306     dpif_netdev_close,                                  \
1307     dpif_netdev_destroy,                                \
1308     dpif_netdev_run,                                    \
1309     dpif_netdev_wait,                                   \
1310     dpif_netdev_get_stats,                              \
1311     dpif_netdev_port_add,                               \
1312     dpif_netdev_port_del,                               \
1313     dpif_netdev_port_query_by_number,                   \
1314     dpif_netdev_port_query_by_name,                     \
1315     dpif_netdev_get_max_ports,                          \
1316     NULL,                       /* port_get_pid */      \
1317     dpif_netdev_port_dump_start,                        \
1318     dpif_netdev_port_dump_next,                         \
1319     dpif_netdev_port_dump_done,                         \
1320     dpif_netdev_port_poll,                              \
1321     dpif_netdev_port_poll_wait,                         \
1322     dpif_netdev_flow_get,                               \
1323     dpif_netdev_flow_put,                               \
1324     dpif_netdev_flow_del,                               \
1325     dpif_netdev_flow_flush,                             \
1326     dpif_netdev_flow_dump_start,                        \
1327     dpif_netdev_flow_dump_next,                         \
1328     dpif_netdev_flow_dump_done,                         \
1329     dpif_netdev_execute,                                \
1330     NULL,                       /* operate */           \
1331     dpif_netdev_recv_set,                               \
1332     dpif_netdev_queue_to_priority,                      \
1333     dpif_netdev_recv,                                   \
1334     dpif_netdev_recv_wait,                              \
1335     dpif_netdev_recv_purge,                             \
1336
1337 const struct dpif_class dpif_netdev_class = {
1338     "netdev",
1339     DPIF_NETDEV_CLASS_FUNCTIONS
1340 };
1341
1342 const struct dpif_class dpif_planetlab_class = {
1343     "planetlab",
1344     DPIF_NETDEV_CLASS_FUNCTIONS
1345 };
1346
1347 static void
1348 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
1349                               const char *argv[], void *aux OVS_UNUSED)
1350 {
1351     struct dp_netdev_port *port;
1352     struct dp_netdev *dp;
1353     int port_no;
1354
1355     dp = shash_find_data(&dp_netdevs, argv[1]);
1356     if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
1357         unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
1358         return;
1359     }
1360
1361     if (get_port_by_name(dp, argv[2], &port)) {
1362         unixctl_command_reply_error(conn, "unknown port");
1363         return;
1364     }
1365
1366     port_no = atoi(argv[3]);
1367     if (port_no <= 0 || port_no >= MAX_PORTS) {
1368         unixctl_command_reply_error(conn, "bad port number");
1369         return;
1370     }
1371     if (dp->ports[port_no]) {
1372         unixctl_command_reply_error(conn, "port number already in use");
1373         return;
1374     }
1375     dp->ports[odp_to_u32(port->port_no)] = NULL;
1376     dp->ports[port_no] = port;
1377     port->port_no = u32_to_odp(port_no);
1378     dp->serial++;
1379     unixctl_command_reply(conn, NULL);
1380 }
1381
1382 static void
1383 dpif_dummy_register__(const char *type)
1384 {
1385     struct dpif_class *class;
1386
1387     class = xmalloc(sizeof *class);
1388     *class = dpif_netdev_class;
1389     class->type = xstrdup(type);
1390     dp_register_provider(class);
1391 }
1392
1393 void
1394 dpif_dummy_register(bool override)
1395 {
1396     if (override) {
1397         struct sset types;
1398         const char *type;
1399
1400         sset_init(&types);
1401         dp_enumerate_types(&types);
1402         SSET_FOR_EACH (type, &types) {
1403             if (!dp_unregister_provider(type)) {
1404                 dpif_dummy_register__(type);
1405             }
1406         }
1407         sset_destroy(&types);
1408     }
1409
1410     dpif_dummy_register__("dummy");
1411
1412     unixctl_command_register("dpif-dummy/change-port-number",
1413                              "DP PORT NEW-NUMBER",
1414                              3, 3, dpif_dummy_change_port_number, NULL);
1415 }
1416