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