6e85d61a059bc0c2f13d15b7a29dc26c2f920ab7
[sliver-openvswitch.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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
19 #include "dpif-linux.h"
20
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
26 #include <net/if.h>
27 #include <linux/types.h>
28 #include <linux/ethtool.h>
29 #include <linux/pkt_sched.h>
30 #include <linux/rtnetlink.h>
31 #include <linux/sockios.h>
32 #include <stdlib.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "dpif-provider.h"
38 #include "netdev.h"
39 #include "netdev-vport.h"
40 #include "netlink.h"
41 #include "ofpbuf.h"
42 #include "openvswitch/tunnel.h"
43 #include "packets.h"
44 #include "poll-loop.h"
45 #include "rtnetlink.h"
46 #include "rtnetlink-link.h"
47 #include "shash.h"
48 #include "svec.h"
49 #include "util.h"
50 #include "vlog.h"
51
52 VLOG_DEFINE_THIS_MODULE(dpif_linux);
53
54 /* Datapath interface for the openvswitch Linux kernel module. */
55 struct dpif_linux {
56     struct dpif dpif;
57     int fd;
58
59     /* Used by dpif_linux_get_all_names(). */
60     char *local_ifname;
61     int minor;
62
63     /* Change notification. */
64     int local_ifindex;          /* Ifindex of local port. */
65     struct shash changed_ports;  /* Ports that have changed. */
66     struct rtnetlink_notifier port_notifier;
67     bool change_error;
68 };
69
70 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
71
72 static int do_ioctl(const struct dpif *, int cmd, const void *arg);
73 static int open_dpif(const struct dpif_linux_vport *local_vport,
74                      struct dpif **);
75 static int get_openvswitch_major(void);
76 static int create_minor(const char *name, int minor);
77 static int open_minor(int minor, int *fdp);
78 static int make_openvswitch_device(int minor, char **fnp);
79 static void dpif_linux_port_changed(const struct rtnetlink_link_change *,
80                                     void *dpif);
81
82 static struct dpif_linux *
83 dpif_linux_cast(const struct dpif *dpif)
84 {
85     dpif_assert_class(dpif, &dpif_linux_class);
86     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
87 }
88
89 static int
90 dpif_linux_enumerate(struct svec *all_dps)
91 {
92     int major;
93     int error;
94     int i;
95
96     /* Check that the Open vSwitch module is loaded. */
97     major = get_openvswitch_major();
98     if (major < 0) {
99         return -major;
100     }
101
102     error = 0;
103     for (i = 0; i < ODP_MAX; i++) {
104         struct dpif *dpif;
105         char devname[16];
106         int retval;
107
108         sprintf(devname, "dp%d", i);
109         retval = dpif_open(devname, "system", &dpif);
110         if (!retval) {
111             svec_add(all_dps, devname);
112             dpif_uninit(dpif, true);
113         } else if (retval != ENODEV && !error) {
114             error = retval;
115         }
116     }
117     return error;
118 }
119
120 static int
121 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
122                 bool create, struct dpif **dpifp)
123 {
124     struct dpif_linux_vport request, reply;
125     struct ofpbuf *buf;
126     int minor;
127     int error;
128
129     minor = !strncmp(name, "dp", 2)
130             && isdigit((unsigned char)name[2]) ? atoi(name + 2) : -1;
131     if (create) {
132         if (minor >= 0) {
133             error = create_minor(name, minor);
134             if (error) {
135                 return error;
136             }
137         } else {
138             /* Scan for unused minor number. */
139             for (minor = 0; ; minor++) {
140                 if (minor >= ODP_MAX) {
141                     /* All datapath numbers in use. */
142                     return ENOBUFS;
143                 }
144
145                 error = create_minor(name, minor);
146                 if (!error) {
147                     break;
148                 } else if (error != EBUSY) {
149                     return error;
150                 }
151             }
152         }
153     }
154
155     dpif_linux_vport_init(&request);
156     request.cmd = ODP_VPORT_GET;
157     request.port_no = ODPP_LOCAL;
158     if (minor >= 0) {
159         request.dp_idx = minor;
160     } else {
161         request.name = name;
162     }
163
164     error = dpif_linux_vport_transact(&request, &reply, &buf);
165     if (error) {
166         return error;
167     } else if (reply.port_no != ODPP_LOCAL) {
168         /* This is an Open vSwitch device but not the local port.  We
169          * intentionally support only using the name of the local port as the
170          * name of a datapath; otherwise, it would be too difficult to
171          * enumerate all the names of a datapath. */
172         error = EOPNOTSUPP;
173     } else {
174         error = open_dpif(&reply, dpifp);
175     }
176
177     ofpbuf_delete(buf);
178     return error;
179 }
180
181 static int
182 open_dpif(const struct dpif_linux_vport *local_vport, struct dpif **dpifp)
183 {
184     int dp_idx = local_vport->dp_idx;
185     struct dpif_linux *dpif;
186     char *name;
187     int error;
188     int fd;
189
190     error = open_minor(dp_idx, &fd);
191     if (error) {
192         goto error;
193     }
194
195     dpif = xmalloc(sizeof *dpif);
196     error = rtnetlink_link_notifier_register(&dpif->port_notifier,
197                                              dpif_linux_port_changed, dpif);
198     if (error) {
199         goto error_free;
200     }
201
202     name = xasprintf("dp%d", dp_idx);
203     dpif_init(&dpif->dpif, &dpif_linux_class, name, dp_idx, dp_idx);
204     free(name);
205
206     dpif->fd = fd;
207     dpif->local_ifname = xstrdup(local_vport->name);
208     dpif->local_ifindex = local_vport->ifindex;
209     dpif->minor = dp_idx;
210     shash_init(&dpif->changed_ports);
211     dpif->change_error = false;
212     *dpifp = &dpif->dpif;
213
214     return 0;
215
216 error_free:
217     free(dpif);
218     close(fd);
219 error:
220     return error;
221 }
222
223 static void
224 dpif_linux_close(struct dpif *dpif_)
225 {
226     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
227     rtnetlink_link_notifier_unregister(&dpif->port_notifier);
228     shash_destroy(&dpif->changed_ports);
229     free(dpif->local_ifname);
230     close(dpif->fd);
231     free(dpif);
232 }
233
234 static int
235 dpif_linux_get_all_names(const struct dpif *dpif_, struct svec *all_names)
236 {
237     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
238
239     svec_add_nocopy(all_names, xasprintf("dp%d", dpif->minor));
240     svec_add(all_names, dpif->local_ifname);
241     return 0;
242 }
243
244 static int
245 dpif_linux_destroy(struct dpif *dpif_)
246 {
247     return do_ioctl(dpif_, ODP_DP_DESTROY, NULL);
248 }
249
250 static int
251 dpif_linux_get_stats(const struct dpif *dpif_, struct odp_stats *stats)
252 {
253     memset(stats, 0, sizeof *stats);
254     return do_ioctl(dpif_, ODP_DP_STATS, stats);
255 }
256
257 static int
258 dpif_linux_get_drop_frags(const struct dpif *dpif_, bool *drop_fragsp)
259 {
260     int drop_frags;
261     int error;
262
263     error = do_ioctl(dpif_, ODP_GET_DROP_FRAGS, &drop_frags);
264     if (!error) {
265         *drop_fragsp = drop_frags & 1;
266     }
267     return error;
268 }
269
270 static int
271 dpif_linux_set_drop_frags(struct dpif *dpif_, bool drop_frags)
272 {
273     int drop_frags_int = drop_frags;
274     return do_ioctl(dpif_, ODP_SET_DROP_FRAGS, &drop_frags_int);
275 }
276
277 static int
278 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
279                     uint16_t *port_nop)
280 {
281     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
282     const char *name = netdev_get_name(netdev);
283     const char *type = netdev_get_type(netdev);
284     struct dpif_linux_vport request, reply;
285     const struct ofpbuf *options;
286     struct ofpbuf *buf;
287     int error;
288
289     dpif_linux_vport_init(&request);
290     request.cmd = ODP_VPORT_NEW;
291     request.dp_idx = dpif->minor;
292     request.type = netdev_vport_get_vport_type(netdev);
293     if (request.type == ODP_VPORT_TYPE_UNSPEC) {
294         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
295                      "unsupported type `%s'",
296                      dpif_name(dpif_), name, type);
297         return EINVAL;
298     }
299     request.name = name;
300
301     options = netdev_vport_get_options(netdev);
302     if (options && options->size) {
303         request.options = options->data;
304         request.options_len = options->size;
305     }
306
307     error = dpif_linux_vport_transact(&request, &reply, &buf);
308     if (!error) {
309         *port_nop = reply.port_no;
310         ofpbuf_delete(buf);
311     }
312
313     return error;
314 }
315
316 static int
317 dpif_linux_port_del(struct dpif *dpif_, uint16_t port_no)
318 {
319     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
320     struct dpif_linux_vport vport;
321
322     dpif_linux_vport_init(&vport);
323     vport.cmd = ODP_VPORT_DEL;
324     vport.dp_idx = dpif->minor;
325     vport.port_no = port_no;
326     return dpif_linux_vport_transact(&vport, NULL, NULL);
327 }
328
329 static int
330 dpif_linux_port_query__(const struct dpif *dpif, uint32_t port_no,
331                         const char *port_name, struct dpif_port *dpif_port)
332 {
333     struct dpif_linux_vport request;
334     struct dpif_linux_vport reply;
335     struct ofpbuf *buf;
336     int error;
337
338     dpif_linux_vport_init(&request);
339     request.cmd = ODP_VPORT_GET;
340     request.dp_idx = dpif_linux_cast(dpif)->minor;
341     request.port_no = port_no;
342     request.name = port_name;
343
344     error = dpif_linux_vport_transact(&request, &reply, &buf);
345     if (!error) {
346         dpif_port->name = xstrdup(reply.name);
347         dpif_port->type = xstrdup(netdev_vport_get_netdev_type(&reply));
348         dpif_port->port_no = reply.port_no;
349         ofpbuf_delete(buf);
350     }
351     return error;
352 }
353
354 static int
355 dpif_linux_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
356                                 struct dpif_port *dpif_port)
357 {
358     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
359 }
360
361 static int
362 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
363                               struct dpif_port *dpif_port)
364 {
365     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
366 }
367
368 static int
369 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
370 {
371     /* If the datapath increases its range of supported ports, then it should
372      * start reporting that. */
373     return 1024;
374 }
375
376 static int
377 dpif_linux_flow_flush(struct dpif *dpif_)
378 {
379     return do_ioctl(dpif_, ODP_FLOW_FLUSH, NULL);
380 }
381
382 struct dpif_linux_port_state {
383     struct ofpbuf *buf;
384     uint32_t next;
385 };
386
387 static int
388 dpif_linux_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
389 {
390     *statep = xzalloc(sizeof(struct dpif_linux_port_state));
391     return 0;
392 }
393
394 static int
395 dpif_linux_port_dump_next(const struct dpif *dpif, void *state_,
396                           struct dpif_port *dpif_port)
397 {
398     struct dpif_linux_port_state *state = state_;
399     struct dpif_linux_vport request, reply;
400     struct ofpbuf *buf;
401     int error;
402
403     ofpbuf_delete(state->buf);
404     state->buf = NULL;
405
406     dpif_linux_vport_init(&request);
407     request.cmd = ODP_VPORT_DUMP;
408     request.dp_idx = dpif_linux_cast(dpif)->minor;
409     request.port_no = state->next;
410     error = dpif_linux_vport_transact(&request, &reply, &buf);
411     if (error) {
412         return error == ENODEV ? EOF : error;
413     } else {
414         dpif_port->name = (char *) reply.name;
415         dpif_port->type = (char *) netdev_vport_get_netdev_type(&reply);
416         dpif_port->port_no = reply.port_no;
417         state->buf = buf;
418         state->next = reply.port_no + 1;
419         return 0;
420     }
421 }
422
423 static int
424 dpif_linux_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
425 {
426     struct dpif_linux_port_state *state = state_;
427     ofpbuf_delete(state->buf);
428     free(state);
429     return 0;
430 }
431
432 static int
433 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
434 {
435     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
436
437     if (dpif->change_error) {
438         dpif->change_error = false;
439         shash_clear(&dpif->changed_ports);
440         return ENOBUFS;
441     } else if (!shash_is_empty(&dpif->changed_ports)) {
442         struct shash_node *node = shash_first(&dpif->changed_ports);
443         *devnamep = shash_steal(&dpif->changed_ports, node);
444         return 0;
445     } else {
446         return EAGAIN;
447     }
448 }
449
450 static void
451 dpif_linux_port_poll_wait(const struct dpif *dpif_)
452 {
453     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
454     if (!shash_is_empty(&dpif->changed_ports) || dpif->change_error) {
455         poll_immediate_wake();
456     } else {
457         rtnetlink_link_notifier_wait();
458     }
459 }
460
461 static int
462 dpif_linux_flow_get(const struct dpif *dpif_, struct odp_flow flows[], int n)
463 {
464     struct odp_flowvec fv;
465     fv.flows = flows;
466     fv.n_flows = n;
467     return do_ioctl(dpif_, ODP_FLOW_GET, &fv);
468 }
469
470 static int
471 dpif_linux_flow_put(struct dpif *dpif_, struct odp_flow_put *put)
472 {
473     return do_ioctl(dpif_, ODP_FLOW_PUT, put);
474 }
475
476 static int
477 dpif_linux_flow_del(struct dpif *dpif_, struct odp_flow *flow)
478 {
479     return do_ioctl(dpif_, ODP_FLOW_DEL, flow);
480 }
481
482 static int
483 dpif_linux_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
484 {
485     *statep = xzalloc(sizeof(struct odp_flow_dump));
486     return 0;
487 }
488
489 static int
490 dpif_linux_flow_dump_next(const struct dpif *dpif, void *state,
491                           struct odp_flow *flow)
492 {
493     struct odp_flow_dump *dump = state;
494     int error;
495
496     dump->flow = flow;
497     error = do_ioctl(dpif, ODP_FLOW_DUMP, dump);
498     return error ? error : flow->flags & ODPFF_EOF ? EOF : 0;
499 }
500
501 static int
502 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state)
503 {
504     free(state);
505     return 0;
506 }
507
508 static int
509 dpif_linux_execute(struct dpif *dpif_,
510                    const struct nlattr *actions, size_t actions_len,
511                    const struct ofpbuf *buf)
512 {
513     struct odp_execute execute;
514     memset(&execute, 0, sizeof execute);
515     execute.actions = (struct nlattr *) actions;
516     execute.actions_len = actions_len;
517     execute.data = buf->data;
518     execute.length = buf->size;
519     return do_ioctl(dpif_, ODP_EXECUTE, &execute);
520 }
521
522 static int
523 dpif_linux_recv_get_mask(const struct dpif *dpif_, int *listen_mask)
524 {
525     return do_ioctl(dpif_, ODP_GET_LISTEN_MASK, listen_mask);
526 }
527
528 static int
529 dpif_linux_recv_set_mask(struct dpif *dpif_, int listen_mask)
530 {
531     return do_ioctl(dpif_, ODP_SET_LISTEN_MASK, &listen_mask);
532 }
533
534 static int
535 dpif_linux_get_sflow_probability(const struct dpif *dpif_,
536                                  uint32_t *probability)
537 {
538     return do_ioctl(dpif_, ODP_GET_SFLOW_PROBABILITY, probability);
539 }
540
541 static int
542 dpif_linux_set_sflow_probability(struct dpif *dpif_, uint32_t probability)
543 {
544     return do_ioctl(dpif_, ODP_SET_SFLOW_PROBABILITY, &probability);
545 }
546
547 static int
548 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
549                              uint32_t queue_id, uint32_t *priority)
550 {
551     if (queue_id < 0xf000) {
552         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
553         return 0;
554     } else {
555         return EINVAL;
556     }
557 }
558
559 static int
560 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall)
561 {
562     static const struct nl_policy odp_packet_policy[] = {
563         /* Always present. */
564         [ODP_PACKET_ATTR_TYPE] = { .type = NL_A_U32 },
565         [ODP_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
566                                      .min_len = ETH_HEADER_LEN },
567         [ODP_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
568
569         /* _ODPL_ACTION_NR only. */
570         [ODP_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
571
572         /* _ODPL_SFLOW_NR only. */
573         [ODP_PACKET_ATTR_SAMPLE_POOL] = { .type = NL_A_U32, .optional = true },
574         [ODP_PACKET_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
575     };
576
577     struct odp_packet *odp_packet = buf->data;
578     struct nlattr *a[ARRAY_SIZE(odp_packet_policy)];
579
580     if (!nl_policy_parse(buf, sizeof *odp_packet, odp_packet_policy,
581                          a, ARRAY_SIZE(odp_packet_policy))) {
582         return EINVAL;
583     }
584
585     memset(upcall, 0, sizeof *upcall);
586     upcall->type = nl_attr_get_u32(a[ODP_PACKET_ATTR_TYPE]);
587     upcall->packet = buf;
588     upcall->packet->data = (void *) nl_attr_get(a[ODP_PACKET_ATTR_PACKET]);
589     upcall->packet->size = nl_attr_get_size(a[ODP_PACKET_ATTR_PACKET]);
590     upcall->key = (void *) nl_attr_get(a[ODP_PACKET_ATTR_KEY]);
591     upcall->key_len = nl_attr_get_size(a[ODP_PACKET_ATTR_KEY]);
592     upcall->userdata = (a[ODP_PACKET_ATTR_USERDATA]
593                         ? nl_attr_get_u64(a[ODP_PACKET_ATTR_USERDATA])
594                         : 0);
595     upcall->sample_pool = (a[ODP_PACKET_ATTR_SAMPLE_POOL]
596                         ? nl_attr_get_u32(a[ODP_PACKET_ATTR_SAMPLE_POOL])
597                            : 0);
598     if (a[ODP_PACKET_ATTR_ACTIONS]) {
599         upcall->actions = (void *) nl_attr_get(a[ODP_PACKET_ATTR_ACTIONS]);
600         upcall->actions_len = nl_attr_get_size(a[ODP_PACKET_ATTR_ACTIONS]);
601     }
602
603     return 0;
604 }
605
606 static int
607 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
608 {
609     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
610     struct ofpbuf *buf;
611     int retval;
612     int error;
613
614     buf = ofpbuf_new(65536);
615     retval = read(dpif->fd, ofpbuf_tail(buf), ofpbuf_tailroom(buf));
616     if (retval < 0) {
617         error = errno;
618         if (error != EAGAIN) {
619             VLOG_WARN_RL(&error_rl, "%s: read failed: %s",
620                          dpif_name(dpif_), strerror(error));
621         }
622     } else if (retval >= sizeof(struct odp_packet)) {
623         struct odp_packet *odp_packet = buf->data;
624         buf->size += retval;
625
626         if (odp_packet->len <= retval) {
627             error = parse_odp_packet(buf, upcall);
628         } else {
629             VLOG_WARN_RL(&error_rl, "%s: discarding message truncated "
630                          "from %"PRIu32" bytes to %d",
631                          dpif_name(dpif_), odp_packet->len, retval);
632             error = ERANGE;
633         }
634     } else if (!retval) {
635         VLOG_WARN_RL(&error_rl, "%s: unexpected end of file", dpif_name(dpif_));
636         error = EPROTO;
637     } else {
638         VLOG_WARN_RL(&error_rl, "%s: discarding too-short message (%d bytes)",
639                      dpif_name(dpif_), retval);
640         error = ERANGE;
641     }
642
643     if (error) {
644         ofpbuf_delete(buf);
645     }
646     return error;
647 }
648
649 static void
650 dpif_linux_recv_wait(struct dpif *dpif_)
651 {
652     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
653     poll_fd_wait(dpif->fd, POLLIN);
654 }
655
656 static void
657 dpif_linux_recv_purge(struct dpif *dpif_)
658 {
659     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
660     int i;
661
662     /* This is somewhat bogus because it assumes that the following macros have
663      * fixed values, but it's going to go away later.  */
664 #define DP_N_QUEUES 3
665 #define DP_MAX_QUEUE_LEN 100
666     for (i = 0; i < DP_N_QUEUES * DP_MAX_QUEUE_LEN; i++) {
667         /* Reading even 1 byte discards a whole datagram and saves time. */
668         char buffer;
669
670         if (read(dpif->fd, &buffer, 1) != 1) {
671             break;
672         }
673     }
674 }
675
676 const struct dpif_class dpif_linux_class = {
677     "system",
678     NULL,
679     NULL,
680     dpif_linux_enumerate,
681     dpif_linux_open,
682     dpif_linux_close,
683     dpif_linux_get_all_names,
684     dpif_linux_destroy,
685     dpif_linux_get_stats,
686     dpif_linux_get_drop_frags,
687     dpif_linux_set_drop_frags,
688     dpif_linux_port_add,
689     dpif_linux_port_del,
690     dpif_linux_port_query_by_number,
691     dpif_linux_port_query_by_name,
692     dpif_linux_get_max_ports,
693     dpif_linux_port_dump_start,
694     dpif_linux_port_dump_next,
695     dpif_linux_port_dump_done,
696     dpif_linux_port_poll,
697     dpif_linux_port_poll_wait,
698     dpif_linux_flow_get,
699     dpif_linux_flow_put,
700     dpif_linux_flow_del,
701     dpif_linux_flow_flush,
702     dpif_linux_flow_dump_start,
703     dpif_linux_flow_dump_next,
704     dpif_linux_flow_dump_done,
705     dpif_linux_execute,
706     dpif_linux_recv_get_mask,
707     dpif_linux_recv_set_mask,
708     dpif_linux_get_sflow_probability,
709     dpif_linux_set_sflow_probability,
710     dpif_linux_queue_to_priority,
711     dpif_linux_recv,
712     dpif_linux_recv_wait,
713     dpif_linux_recv_purge,
714 };
715 \f
716 static int get_openvswitch_major(void);
717 static int get_major(const char *target);
718
719 static int
720 do_ioctl(const struct dpif *dpif_, int cmd, const void *arg)
721 {
722     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
723     return ioctl(dpif->fd, cmd, arg) ? errno : 0;
724 }
725
726 bool
727 dpif_linux_is_internal_device(const char *name)
728 {
729     struct dpif_linux_vport reply;
730     struct ofpbuf *buf;
731     int error;
732
733     error = dpif_linux_vport_get(name, &reply, &buf);
734     if (!error) {
735         ofpbuf_delete(buf);
736     } else if (error != ENODEV) {
737         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
738                      name, strerror(error));
739     }
740
741     return reply.type == ODP_VPORT_TYPE_INTERNAL;
742 }
743
744 static int
745 make_openvswitch_device(int minor, char **fnp)
746 {
747     const char dirname[] = "/dev/net";
748     int major;
749     dev_t dev;
750     struct stat s;
751     char fn[128];
752
753     *fnp = NULL;
754
755     major = get_openvswitch_major();
756     if (major < 0) {
757         return -major;
758     }
759     dev = makedev(major, minor);
760
761     sprintf(fn, "%s/dp%d", dirname, minor);
762     if (!stat(fn, &s)) {
763         if (!S_ISCHR(s.st_mode)) {
764             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
765                          fn);
766         } else if (s.st_rdev != dev) {
767             VLOG_WARN_RL(&error_rl,
768                          "%s is device %u:%u but should be %u:%u, fixing",
769                          fn, major(s.st_rdev), minor(s.st_rdev),
770                          major(dev), minor(dev));
771         } else {
772             goto success;
773         }
774         if (unlink(fn)) {
775             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
776                          fn, strerror(errno));
777             return errno;
778         }
779     } else if (errno == ENOENT) {
780         if (stat(dirname, &s)) {
781             if (errno == ENOENT) {
782                 if (mkdir(dirname, 0755)) {
783                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
784                                  dirname, strerror(errno));
785                     return errno;
786                 }
787             } else {
788                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
789                              dirname, strerror(errno));
790                 return errno;
791             }
792         }
793     } else {
794         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
795         return errno;
796     }
797
798     /* The device needs to be created. */
799     if (mknod(fn, S_IFCHR | 0700, dev)) {
800         VLOG_WARN_RL(&error_rl,
801                      "%s: creating character device %u:%u failed (%s)",
802                      fn, major(dev), minor(dev), strerror(errno));
803         return errno;
804     }
805
806 success:
807     *fnp = xstrdup(fn);
808     return 0;
809 }
810
811 /* Return the major device number of the Open vSwitch device.  If it
812  * cannot be determined, a negative errno is returned. */
813 static int
814 get_openvswitch_major(void)
815 {
816     static int openvswitch_major = -1;
817     if (openvswitch_major < 0) {
818         openvswitch_major = get_major("openvswitch");
819     }
820     return openvswitch_major;
821 }
822
823 static int
824 get_major(const char *target)
825 {
826     const char fn[] = "/proc/devices";
827     char line[128];
828     FILE *file;
829     int ln;
830
831     file = fopen(fn, "r");
832     if (!file) {
833         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
834         return -errno;
835     }
836
837     for (ln = 1; fgets(line, sizeof line, file); ln++) {
838         char name[64];
839         int major;
840
841         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
842             /* Nothing to do. */
843         } else if (!strncmp(line, "Block", 5)) {
844             /* We only want character devices, so skip the rest of the file. */
845             break;
846         } else if (sscanf(line, "%d %63s", &major, name)) {
847             if (!strcmp(name, target)) {
848                 fclose(file);
849                 return major;
850             }
851         } else {
852             VLOG_WARN_ONCE("%s:%d: syntax error", fn, ln);
853         }
854     }
855
856     fclose(file);
857
858     VLOG_ERR("%s: %s major not found (is the module loaded?)", fn, target);
859     return -ENODEV;
860 }
861
862 static int
863 create_minor(const char *name, int minor)
864 {
865     int error;
866     int fd;
867
868     error = open_minor(minor, &fd);
869     if (error) {
870         return error;
871     }
872
873     error = ioctl(fd, ODP_DP_CREATE, name) ? errno : 0;
874     close(fd);
875     return error;
876 }
877
878 static int
879 open_minor(int minor, int *fdp)
880 {
881     int error;
882     char *fn;
883
884     error = make_openvswitch_device(minor, &fn);
885     if (error) {
886         return error;
887     }
888
889     *fdp = open(fn, O_RDONLY | O_NONBLOCK);
890     if (*fdp < 0) {
891         error = errno;
892         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
893         free(fn);
894         return error;
895     }
896     free(fn);
897     return 0;
898 }
899
900 static void
901 dpif_linux_port_changed(const struct rtnetlink_link_change *change,
902                         void *dpif_)
903 {
904     struct dpif_linux *dpif = dpif_;
905
906     if (change) {
907         if (change->master_ifindex == dpif->local_ifindex
908             && (change->nlmsg_type == RTM_NEWLINK
909                 || change->nlmsg_type == RTM_DELLINK))
910         {
911             /* Our datapath changed, either adding a new port or deleting an
912              * existing one. */
913             shash_add_once(&dpif->changed_ports, change->ifname, NULL);
914         }
915     } else {
916         dpif->change_error = true;
917     }
918 }
919 \f
920 /* Parses the contents of 'buf', which contains a "struct odp_vport" followed
921  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
922  * positive errno value.
923  *
924  * 'vport' will contain pointers into 'buf', so the caller should not free
925  * 'buf' while 'vport' is still in use. */
926 static int
927 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
928                              const struct ofpbuf *buf)
929 {
930     static const struct nl_policy odp_vport_policy[] = {
931         [ODP_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
932         [ODP_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
933         [ODP_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
934         [ODP_VPORT_ATTR_STATS] = { .type = NL_A_UNSPEC,
935                                    .min_len = sizeof(struct rtnl_link_stats64),
936                                    .max_len = sizeof(struct rtnl_link_stats64),
937                                    .optional = true },
938         [ODP_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
939                                      .min_len = ETH_ADDR_LEN,
940                                      .max_len = ETH_ADDR_LEN,
941                                      .optional = true },
942         [ODP_VPORT_ATTR_MTU] = { .type = NL_A_U32, .optional = true },
943         [ODP_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
944         [ODP_VPORT_ATTR_IFINDEX] = { .type = NL_A_U32, .optional = true },
945         [ODP_VPORT_ATTR_IFLINK] = { .type = NL_A_U32, .optional = true },
946     };
947
948     struct odp_vport *odp_vport;
949     struct nlattr *a[ARRAY_SIZE(odp_vport_policy)];
950
951     dpif_linux_vport_init(vport);
952
953     if (!nl_policy_parse(buf, sizeof *odp_vport, odp_vport_policy,
954                          a, ARRAY_SIZE(odp_vport_policy))) {
955         return EINVAL;
956     }
957     odp_vport = buf->data;
958
959     vport->dp_idx = odp_vport->dp_idx;
960     vport->port_no = nl_attr_get_u32(a[ODP_VPORT_ATTR_PORT_NO]);
961     vport->type = nl_attr_get_u32(a[ODP_VPORT_ATTR_TYPE]);
962     vport->name = nl_attr_get_string(a[ODP_VPORT_ATTR_NAME]);
963     if (a[ODP_VPORT_ATTR_STATS]) {
964         vport->stats = nl_attr_get(a[ODP_VPORT_ATTR_STATS]);
965     }
966     if (a[ODP_VPORT_ATTR_ADDRESS]) {
967         vport->address = nl_attr_get(a[ODP_VPORT_ATTR_ADDRESS]);
968     }
969     if (a[ODP_VPORT_ATTR_MTU]) {
970         vport->mtu = nl_attr_get_u32(a[ODP_VPORT_ATTR_MTU]);
971     }
972     if (a[ODP_VPORT_ATTR_OPTIONS]) {
973         vport->options = nl_attr_get(a[ODP_VPORT_ATTR_OPTIONS]);
974         vport->options_len = nl_attr_get_size(a[ODP_VPORT_ATTR_OPTIONS]);
975     }
976     if (a[ODP_VPORT_ATTR_IFINDEX]) {
977         vport->ifindex = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFINDEX]);
978     }
979     if (a[ODP_VPORT_ATTR_IFLINK]) {
980         vport->iflink = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFLINK]);
981     }
982     return 0;
983 }
984
985 /* Appends to 'buf' (which must initially be empty) a "struct odp_vport"
986  * followed by Netlink attributes corresponding to 'vport'. */
987 static void
988 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
989                            struct ofpbuf *buf)
990 {
991     struct odp_vport *odp_vport;
992
993     ofpbuf_reserve(buf, sizeof odp_vport);
994
995     if (vport->port_no != UINT32_MAX) {
996         nl_msg_put_u32(buf, ODP_VPORT_ATTR_PORT_NO, vport->port_no);
997     }
998
999     if (vport->type != ODP_VPORT_TYPE_UNSPEC) {
1000         nl_msg_put_u32(buf, ODP_VPORT_ATTR_TYPE, vport->type);
1001     }
1002
1003     if (vport->name) {
1004         nl_msg_put_string(buf, ODP_VPORT_ATTR_NAME, vport->name);
1005     }
1006
1007     if (vport->stats) {
1008         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_STATS,
1009                           vport->stats, sizeof *vport->stats);
1010     }
1011
1012     if (vport->address) {
1013         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_ADDRESS,
1014                           vport->address, ETH_ADDR_LEN);
1015     }
1016
1017     if (vport->mtu) {
1018         nl_msg_put_u32(buf, ODP_VPORT_ATTR_MTU, vport->mtu);
1019     }
1020
1021     if (vport->options) {
1022         nl_msg_put_nested(buf, ODP_VPORT_ATTR_OPTIONS,
1023                           vport->options, vport->options_len);
1024     }
1025
1026     if (vport->ifindex) {
1027         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFINDEX, vport->ifindex);
1028     }
1029
1030     if (vport->iflink) {
1031         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFLINK, vport->iflink);
1032     }
1033
1034     odp_vport = ofpbuf_push_uninit(buf, sizeof *odp_vport);
1035     odp_vport->dp_idx = vport->dp_idx;
1036     odp_vport->len = buf->size;
1037     odp_vport->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1038 }
1039
1040 /* Clears 'vport' to "empty" values. */
1041 void
1042 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1043 {
1044     memset(vport, 0, sizeof *vport);
1045     vport->dp_idx = UINT32_MAX;
1046     vport->port_no = UINT32_MAX;
1047 }
1048
1049 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1050  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1051  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1052  * result of the command is expected to be an odp_vport also, which is decoded
1053  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1054  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1055 int
1056 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1057                           struct dpif_linux_vport *reply,
1058                           struct ofpbuf **bufp)
1059 {
1060     static int dp0_fd = -1;
1061     struct ofpbuf *buf = NULL;
1062     int error;
1063
1064     assert((reply != NULL) == (bufp != NULL));
1065     if (dp0_fd < 0) {
1066         int fd;
1067
1068         error = open_minor(0, &fd);
1069         if (error) {
1070             goto error;
1071         }
1072         dp0_fd = fd;
1073     }
1074
1075     buf = ofpbuf_new(1024);
1076     dpif_linux_vport_to_ofpbuf(request, buf);
1077
1078     error = ioctl(dp0_fd, request->cmd, buf->data) ? errno : 0;
1079     if (error) {
1080         goto error;
1081     }
1082
1083     if (bufp) {
1084         buf->size = ((struct odp_vport *) buf->data)->len;
1085         error = dpif_linux_vport_from_ofpbuf(reply, buf);
1086         if (error) {
1087             goto error;
1088         }
1089         *bufp = buf;
1090     } else {
1091         ofpbuf_delete(buf);
1092     }
1093     return 0;
1094
1095 error:
1096     ofpbuf_delete(buf);
1097     if (bufp) {
1098         memset(reply, 0, sizeof *reply);
1099         *bufp = NULL;
1100     }
1101     return error;
1102 }
1103
1104 /* Obtains information about the kernel vport named 'name' and stores it into
1105  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1106  * longer needed ('reply' will contain pointers into '*bufp').  */
1107 int
1108 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1109                      struct ofpbuf **bufp)
1110 {
1111     struct dpif_linux_vport request;
1112
1113     dpif_linux_vport_init(&request);
1114     request.cmd = ODP_VPORT_GET;
1115     request.name = name;
1116
1117     return dpif_linux_vport_transact(&request, reply, bufp);
1118 }
1119