datapath: Change userspace vport interface to use Netlink attributes.
[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_flow_flush(struct dpif *dpif_)
370 {
371     return do_ioctl(dpif_, ODP_FLOW_FLUSH, NULL);
372 }
373
374 struct dpif_linux_port_state {
375     struct ofpbuf *buf;
376     uint32_t next;
377 };
378
379 static int
380 dpif_linux_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
381 {
382     *statep = xzalloc(sizeof(struct dpif_linux_port_state));
383     return 0;
384 }
385
386 static int
387 dpif_linux_port_dump_next(const struct dpif *dpif, void *state_,
388                           struct dpif_port *dpif_port)
389 {
390     struct dpif_linux_port_state *state = state_;
391     struct dpif_linux_vport request, reply;
392     struct ofpbuf *buf;
393     int error;
394
395     ofpbuf_delete(state->buf);
396     state->buf = NULL;
397
398     dpif_linux_vport_init(&request);
399     request.cmd = ODP_VPORT_DUMP;
400     request.dp_idx = dpif_linux_cast(dpif)->minor;
401     request.port_no = state->next;
402     error = dpif_linux_vport_transact(&request, &reply, &buf);
403     if (error) {
404         return error == ENODEV ? EOF : error;
405     } else {
406         dpif_port->name = (char *) reply.name;
407         dpif_port->type = (char *) netdev_vport_get_netdev_type(&reply);
408         dpif_port->port_no = reply.port_no;
409         state->buf = buf;
410         state->next = reply.port_no + 1;
411         return 0;
412     }
413 }
414
415 static int
416 dpif_linux_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
417 {
418     struct dpif_linux_port_state *state = state_;
419     ofpbuf_delete(state->buf);
420     free(state);
421     return 0;
422 }
423
424 static int
425 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
426 {
427     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
428
429     if (dpif->change_error) {
430         dpif->change_error = false;
431         shash_clear(&dpif->changed_ports);
432         return ENOBUFS;
433     } else if (!shash_is_empty(&dpif->changed_ports)) {
434         struct shash_node *node = shash_first(&dpif->changed_ports);
435         *devnamep = shash_steal(&dpif->changed_ports, node);
436         return 0;
437     } else {
438         return EAGAIN;
439     }
440 }
441
442 static void
443 dpif_linux_port_poll_wait(const struct dpif *dpif_)
444 {
445     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
446     if (!shash_is_empty(&dpif->changed_ports) || dpif->change_error) {
447         poll_immediate_wake();
448     } else {
449         rtnetlink_link_notifier_wait();
450     }
451 }
452
453 static int
454 dpif_linux_flow_get(const struct dpif *dpif_, struct odp_flow flows[], int n)
455 {
456     struct odp_flowvec fv;
457     fv.flows = flows;
458     fv.n_flows = n;
459     return do_ioctl(dpif_, ODP_FLOW_GET, &fv);
460 }
461
462 static int
463 dpif_linux_flow_put(struct dpif *dpif_, struct odp_flow_put *put)
464 {
465     return do_ioctl(dpif_, ODP_FLOW_PUT, put);
466 }
467
468 static int
469 dpif_linux_flow_del(struct dpif *dpif_, struct odp_flow *flow)
470 {
471     return do_ioctl(dpif_, ODP_FLOW_DEL, flow);
472 }
473
474 static int
475 dpif_linux_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
476 {
477     *statep = xzalloc(sizeof(struct odp_flow_dump));
478     return 0;
479 }
480
481 static int
482 dpif_linux_flow_dump_next(const struct dpif *dpif, void *state,
483                           struct odp_flow *flow)
484 {
485     struct odp_flow_dump *dump = state;
486     int error;
487
488     dump->flow = flow;
489     error = do_ioctl(dpif, ODP_FLOW_DUMP, dump);
490     return error ? error : flow->flags & ODPFF_EOF ? EOF : 0;
491 }
492
493 static int
494 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state)
495 {
496     free(state);
497     return 0;
498 }
499
500 static int
501 dpif_linux_execute(struct dpif *dpif_,
502                    const struct nlattr *actions, size_t actions_len,
503                    const struct ofpbuf *buf)
504 {
505     struct odp_execute execute;
506     memset(&execute, 0, sizeof execute);
507     execute.actions = (struct nlattr *) actions;
508     execute.actions_len = actions_len;
509     execute.data = buf->data;
510     execute.length = buf->size;
511     return do_ioctl(dpif_, ODP_EXECUTE, &execute);
512 }
513
514 static int
515 dpif_linux_recv_get_mask(const struct dpif *dpif_, int *listen_mask)
516 {
517     return do_ioctl(dpif_, ODP_GET_LISTEN_MASK, listen_mask);
518 }
519
520 static int
521 dpif_linux_recv_set_mask(struct dpif *dpif_, int listen_mask)
522 {
523     return do_ioctl(dpif_, ODP_SET_LISTEN_MASK, &listen_mask);
524 }
525
526 static int
527 dpif_linux_get_sflow_probability(const struct dpif *dpif_,
528                                  uint32_t *probability)
529 {
530     return do_ioctl(dpif_, ODP_GET_SFLOW_PROBABILITY, probability);
531 }
532
533 static int
534 dpif_linux_set_sflow_probability(struct dpif *dpif_, uint32_t probability)
535 {
536     return do_ioctl(dpif_, ODP_SET_SFLOW_PROBABILITY, &probability);
537 }
538
539 static int
540 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
541                              uint32_t queue_id, uint32_t *priority)
542 {
543     if (queue_id < 0xf000) {
544         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
545         return 0;
546     } else {
547         return EINVAL;
548     }
549 }
550
551 static int
552 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall)
553 {
554     static const struct nl_policy odp_packet_policy[] = {
555         /* Always present. */
556         [ODP_PACKET_ATTR_TYPE] = { .type = NL_A_U32 },
557         [ODP_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
558                                      .min_len = ETH_HEADER_LEN },
559         [ODP_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
560
561         /* _ODPL_ACTION_NR only. */
562         [ODP_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
563
564         /* _ODPL_SFLOW_NR only. */
565         [ODP_PACKET_ATTR_SAMPLE_POOL] = { .type = NL_A_U32, .optional = true },
566         [ODP_PACKET_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
567     };
568
569     struct odp_packet *odp_packet = buf->data;
570     struct nlattr *a[ARRAY_SIZE(odp_packet_policy)];
571
572     if (!nl_policy_parse(buf, sizeof *odp_packet, odp_packet_policy,
573                          a, ARRAY_SIZE(odp_packet_policy))) {
574         return EINVAL;
575     }
576
577     memset(upcall, 0, sizeof *upcall);
578     upcall->type = nl_attr_get_u32(a[ODP_PACKET_ATTR_TYPE]);
579     upcall->packet = buf;
580     upcall->packet->data = (void *) nl_attr_get(a[ODP_PACKET_ATTR_PACKET]);
581     upcall->packet->size = nl_attr_get_size(a[ODP_PACKET_ATTR_PACKET]);
582     upcall->key = (void *) nl_attr_get(a[ODP_PACKET_ATTR_KEY]);
583     upcall->key_len = nl_attr_get_size(a[ODP_PACKET_ATTR_KEY]);
584     upcall->userdata = (a[ODP_PACKET_ATTR_USERDATA]
585                         ? nl_attr_get_u64(a[ODP_PACKET_ATTR_USERDATA])
586                         : 0);
587     upcall->sample_pool = (a[ODP_PACKET_ATTR_SAMPLE_POOL]
588                         ? nl_attr_get_u32(a[ODP_PACKET_ATTR_SAMPLE_POOL])
589                            : 0);
590     if (a[ODP_PACKET_ATTR_ACTIONS]) {
591         upcall->actions = (void *) nl_attr_get(a[ODP_PACKET_ATTR_ACTIONS]);
592         upcall->actions_len = nl_attr_get_size(a[ODP_PACKET_ATTR_ACTIONS]);
593     }
594
595     return 0;
596 }
597
598 static int
599 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
600 {
601     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
602     struct ofpbuf *buf;
603     int retval;
604     int error;
605
606     buf = ofpbuf_new(65536);
607     retval = read(dpif->fd, ofpbuf_tail(buf), ofpbuf_tailroom(buf));
608     if (retval < 0) {
609         error = errno;
610         if (error != EAGAIN) {
611             VLOG_WARN_RL(&error_rl, "%s: read failed: %s",
612                          dpif_name(dpif_), strerror(error));
613         }
614     } else if (retval >= sizeof(struct odp_packet)) {
615         struct odp_packet *odp_packet = buf->data;
616         buf->size += retval;
617
618         if (odp_packet->len <= retval) {
619             error = parse_odp_packet(buf, upcall);
620         } else {
621             VLOG_WARN_RL(&error_rl, "%s: discarding message truncated "
622                          "from %"PRIu32" bytes to %d",
623                          dpif_name(dpif_), odp_packet->len, retval);
624             error = ERANGE;
625         }
626     } else if (!retval) {
627         VLOG_WARN_RL(&error_rl, "%s: unexpected end of file", dpif_name(dpif_));
628         error = EPROTO;
629     } else {
630         VLOG_WARN_RL(&error_rl, "%s: discarding too-short message (%d bytes)",
631                      dpif_name(dpif_), retval);
632         error = ERANGE;
633     }
634
635     if (error) {
636         ofpbuf_delete(buf);
637     }
638     return error;
639 }
640
641 static void
642 dpif_linux_recv_wait(struct dpif *dpif_)
643 {
644     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
645     poll_fd_wait(dpif->fd, POLLIN);
646 }
647
648 const struct dpif_class dpif_linux_class = {
649     "system",
650     NULL,
651     NULL,
652     dpif_linux_enumerate,
653     dpif_linux_open,
654     dpif_linux_close,
655     dpif_linux_get_all_names,
656     dpif_linux_destroy,
657     dpif_linux_get_stats,
658     dpif_linux_get_drop_frags,
659     dpif_linux_set_drop_frags,
660     dpif_linux_port_add,
661     dpif_linux_port_del,
662     dpif_linux_port_query_by_number,
663     dpif_linux_port_query_by_name,
664     dpif_linux_port_dump_start,
665     dpif_linux_port_dump_next,
666     dpif_linux_port_dump_done,
667     dpif_linux_port_poll,
668     dpif_linux_port_poll_wait,
669     dpif_linux_flow_get,
670     dpif_linux_flow_put,
671     dpif_linux_flow_del,
672     dpif_linux_flow_flush,
673     dpif_linux_flow_dump_start,
674     dpif_linux_flow_dump_next,
675     dpif_linux_flow_dump_done,
676     dpif_linux_execute,
677     dpif_linux_recv_get_mask,
678     dpif_linux_recv_set_mask,
679     dpif_linux_get_sflow_probability,
680     dpif_linux_set_sflow_probability,
681     dpif_linux_queue_to_priority,
682     dpif_linux_recv,
683     dpif_linux_recv_wait,
684 };
685 \f
686 static int get_openvswitch_major(void);
687 static int get_major(const char *target);
688
689 static int
690 do_ioctl(const struct dpif *dpif_, int cmd, const void *arg)
691 {
692     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
693     return ioctl(dpif->fd, cmd, arg) ? errno : 0;
694 }
695
696 bool
697 dpif_linux_is_internal_device(const char *name)
698 {
699     struct dpif_linux_vport reply;
700     struct ofpbuf *buf;
701     int error;
702
703     error = dpif_linux_vport_get(name, &reply, &buf);
704     if (!error) {
705         ofpbuf_delete(buf);
706     } else if (error != ENODEV) {
707         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
708                      name, strerror(error));
709     }
710
711     return reply.type == ODP_VPORT_TYPE_INTERNAL;
712 }
713
714 static int
715 make_openvswitch_device(int minor, char **fnp)
716 {
717     const char dirname[] = "/dev/net";
718     int major;
719     dev_t dev;
720     struct stat s;
721     char fn[128];
722
723     *fnp = NULL;
724
725     major = get_openvswitch_major();
726     if (major < 0) {
727         return -major;
728     }
729     dev = makedev(major, minor);
730
731     sprintf(fn, "%s/dp%d", dirname, minor);
732     if (!stat(fn, &s)) {
733         if (!S_ISCHR(s.st_mode)) {
734             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
735                          fn);
736         } else if (s.st_rdev != dev) {
737             VLOG_WARN_RL(&error_rl,
738                          "%s is device %u:%u but should be %u:%u, fixing",
739                          fn, major(s.st_rdev), minor(s.st_rdev),
740                          major(dev), minor(dev));
741         } else {
742             goto success;
743         }
744         if (unlink(fn)) {
745             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
746                          fn, strerror(errno));
747             return errno;
748         }
749     } else if (errno == ENOENT) {
750         if (stat(dirname, &s)) {
751             if (errno == ENOENT) {
752                 if (mkdir(dirname, 0755)) {
753                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
754                                  dirname, strerror(errno));
755                     return errno;
756                 }
757             } else {
758                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
759                              dirname, strerror(errno));
760                 return errno;
761             }
762         }
763     } else {
764         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
765         return errno;
766     }
767
768     /* The device needs to be created. */
769     if (mknod(fn, S_IFCHR | 0700, dev)) {
770         VLOG_WARN_RL(&error_rl,
771                      "%s: creating character device %u:%u failed (%s)",
772                      fn, major(dev), minor(dev), strerror(errno));
773         return errno;
774     }
775
776 success:
777     *fnp = xstrdup(fn);
778     return 0;
779 }
780
781 /* Return the major device number of the Open vSwitch device.  If it
782  * cannot be determined, a negative errno is returned. */
783 static int
784 get_openvswitch_major(void)
785 {
786     static int openvswitch_major = -1;
787     if (openvswitch_major < 0) {
788         openvswitch_major = get_major("openvswitch");
789     }
790     return openvswitch_major;
791 }
792
793 static int
794 get_major(const char *target)
795 {
796     const char fn[] = "/proc/devices";
797     char line[128];
798     FILE *file;
799     int ln;
800
801     file = fopen(fn, "r");
802     if (!file) {
803         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
804         return -errno;
805     }
806
807     for (ln = 1; fgets(line, sizeof line, file); ln++) {
808         char name[64];
809         int major;
810
811         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
812             /* Nothing to do. */
813         } else if (!strncmp(line, "Block", 5)) {
814             /* We only want character devices, so skip the rest of the file. */
815             break;
816         } else if (sscanf(line, "%d %63s", &major, name)) {
817             if (!strcmp(name, target)) {
818                 fclose(file);
819                 return major;
820             }
821         } else {
822             VLOG_WARN_ONCE("%s:%d: syntax error", fn, ln);
823         }
824     }
825
826     fclose(file);
827
828     VLOG_ERR("%s: %s major not found (is the module loaded?)", fn, target);
829     return -ENODEV;
830 }
831
832 static int
833 create_minor(const char *name, int minor)
834 {
835     int error;
836     int fd;
837
838     error = open_minor(minor, &fd);
839     if (error) {
840         return error;
841     }
842
843     error = ioctl(fd, ODP_DP_CREATE, name) ? errno : 0;
844     close(fd);
845     return error;
846 }
847
848 static int
849 open_minor(int minor, int *fdp)
850 {
851     int error;
852     char *fn;
853
854     error = make_openvswitch_device(minor, &fn);
855     if (error) {
856         return error;
857     }
858
859     *fdp = open(fn, O_RDONLY | O_NONBLOCK);
860     if (*fdp < 0) {
861         error = errno;
862         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
863         free(fn);
864         return error;
865     }
866     free(fn);
867     return 0;
868 }
869
870 static void
871 dpif_linux_port_changed(const struct rtnetlink_link_change *change,
872                         void *dpif_)
873 {
874     struct dpif_linux *dpif = dpif_;
875
876     if (change) {
877         if (change->master_ifindex == dpif->local_ifindex
878             && (change->nlmsg_type == RTM_NEWLINK
879                 || change->nlmsg_type == RTM_DELLINK))
880         {
881             /* Our datapath changed, either adding a new port or deleting an
882              * existing one. */
883             shash_add_once(&dpif->changed_ports, change->ifname, NULL);
884         }
885     } else {
886         dpif->change_error = true;
887     }
888 }
889 \f
890 /* Parses the contents of 'buf', which contains a "struct odp_vport" followed
891  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
892  * positive errno value.
893  *
894  * 'vport' will contain pointers into 'buf', so the caller should not free
895  * 'buf' while 'vport' is still in use. */
896 static int
897 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
898                              const struct ofpbuf *buf)
899 {
900     static const struct nl_policy odp_vport_policy[] = {
901         [ODP_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
902         [ODP_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
903         [ODP_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
904         [ODP_VPORT_ATTR_STATS] = { .type = NL_A_UNSPEC,
905                                    .min_len = sizeof(struct rtnl_link_stats64),
906                                    .max_len = sizeof(struct rtnl_link_stats64),
907                                    .optional = true },
908         [ODP_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
909                                      .min_len = ETH_ADDR_LEN,
910                                      .max_len = ETH_ADDR_LEN,
911                                      .optional = true },
912         [ODP_VPORT_ATTR_MTU] = { .type = NL_A_U32, .optional = true },
913         [ODP_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
914         [ODP_VPORT_ATTR_IFINDEX] = { .type = NL_A_U32, .optional = true },
915         [ODP_VPORT_ATTR_IFLINK] = { .type = NL_A_U32, .optional = true },
916     };
917
918     struct odp_vport *odp_vport;
919     struct nlattr *a[ARRAY_SIZE(odp_vport_policy)];
920
921     dpif_linux_vport_init(vport);
922
923     if (!nl_policy_parse(buf, sizeof *odp_vport, odp_vport_policy,
924                          a, ARRAY_SIZE(odp_vport_policy))) {
925         return EINVAL;
926     }
927     odp_vport = buf->data;
928
929     vport->dp_idx = odp_vport->dp_idx;
930     vport->port_no = nl_attr_get_u32(a[ODP_VPORT_ATTR_PORT_NO]);
931     vport->type = nl_attr_get_u32(a[ODP_VPORT_ATTR_TYPE]);
932     vport->name = nl_attr_get_string(a[ODP_VPORT_ATTR_NAME]);
933     if (a[ODP_VPORT_ATTR_STATS]) {
934         vport->stats = nl_attr_get(a[ODP_VPORT_ATTR_STATS]);
935     }
936     if (a[ODP_VPORT_ATTR_ADDRESS]) {
937         vport->address = nl_attr_get(a[ODP_VPORT_ATTR_ADDRESS]);
938     }
939     if (a[ODP_VPORT_ATTR_MTU]) {
940         vport->mtu = nl_attr_get_u32(a[ODP_VPORT_ATTR_MTU]);
941     }
942     if (a[ODP_VPORT_ATTR_OPTIONS]) {
943         vport->options = nl_attr_get(a[ODP_VPORT_ATTR_OPTIONS]);
944         vport->options_len = nl_attr_get_size(a[ODP_VPORT_ATTR_OPTIONS]);
945     }
946     if (a[ODP_VPORT_ATTR_IFINDEX]) {
947         vport->ifindex = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFINDEX]);
948     }
949     if (a[ODP_VPORT_ATTR_IFLINK]) {
950         vport->iflink = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFLINK]);
951     }
952     return 0;
953 }
954
955 /* Appends to 'buf' (which must initially be empty) a "struct odp_vport"
956  * followed by Netlink attributes corresponding to 'vport'. */
957 static void
958 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
959                            struct ofpbuf *buf)
960 {
961     struct odp_vport *odp_vport;
962
963     ofpbuf_reserve(buf, sizeof odp_vport);
964
965     if (vport->port_no != UINT32_MAX) {
966         nl_msg_put_u32(buf, ODP_VPORT_ATTR_PORT_NO, vport->port_no);
967     }
968
969     if (vport->type != ODP_VPORT_TYPE_UNSPEC) {
970         nl_msg_put_u32(buf, ODP_VPORT_ATTR_TYPE, vport->type);
971     }
972
973     if (vport->name) {
974         nl_msg_put_string(buf, ODP_VPORT_ATTR_NAME, vport->name);
975     }
976
977     if (vport->stats) {
978         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_STATS,
979                           vport->stats, sizeof *vport->stats);
980     }
981
982     if (vport->address) {
983         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_ADDRESS,
984                           vport->address, ETH_ADDR_LEN);
985     }
986
987     if (vport->mtu) {
988         nl_msg_put_u32(buf, ODP_VPORT_ATTR_MTU, vport->mtu);
989     }
990
991     if (vport->options) {
992         nl_msg_put_nested(buf, ODP_VPORT_ATTR_OPTIONS,
993                           vport->options, vport->options_len);
994     }
995
996     if (vport->ifindex) {
997         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFINDEX, vport->ifindex);
998     }
999
1000     if (vport->iflink) {
1001         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFLINK, vport->iflink);
1002     }
1003
1004     odp_vport = ofpbuf_push_uninit(buf, sizeof *odp_vport);
1005     odp_vport->dp_idx = vport->dp_idx;
1006     odp_vport->len = buf->size;
1007     odp_vport->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1008 }
1009
1010 /* Clears 'vport' to "empty" values. */
1011 void
1012 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1013 {
1014     memset(vport, 0, sizeof *vport);
1015     vport->dp_idx = UINT32_MAX;
1016     vport->port_no = UINT32_MAX;
1017 }
1018
1019 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1020  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1021  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1022  * result of the command is expected to be an odp_vport also, which is decoded
1023  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1024  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1025 int
1026 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1027                           struct dpif_linux_vport *reply,
1028                           struct ofpbuf **bufp)
1029 {
1030     static int dp0_fd = -1;
1031     struct ofpbuf *buf = NULL;
1032     int error;
1033
1034     assert((reply != NULL) == (bufp != NULL));
1035     if (dp0_fd < 0) {
1036         int fd;
1037
1038         error = open_minor(0, &fd);
1039         if (error) {
1040             goto error;
1041         }
1042         dp0_fd = fd;
1043     }
1044
1045     buf = ofpbuf_new(1024);
1046     dpif_linux_vport_to_ofpbuf(request, buf);
1047
1048     error = ioctl(dp0_fd, request->cmd, buf->data) ? errno : 0;
1049     if (error) {
1050         goto error;
1051     }
1052
1053     if (bufp) {
1054         buf->size = ((struct odp_vport *) buf->data)->len;
1055         error = dpif_linux_vport_from_ofpbuf(reply, buf);
1056         if (error) {
1057             goto error;
1058         }
1059         *bufp = buf;
1060     } else {
1061         ofpbuf_delete(buf);
1062     }
1063     return 0;
1064
1065 error:
1066     ofpbuf_delete(buf);
1067     if (bufp) {
1068         memset(reply, 0, sizeof *reply);
1069         *bufp = NULL;
1070     }
1071     return error;
1072 }
1073
1074 /* Obtains information about the kernel vport named 'name' and stores it into
1075  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1076  * longer needed ('reply' will contain pointers into '*bufp').  */
1077 int
1078 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1079                      struct ofpbuf **bufp)
1080 {
1081     struct dpif_linux_vport request;
1082
1083     dpif_linux_vport_init(&request);
1084     request.cmd = ODP_VPORT_GET;
1085     request.name = name;
1086
1087     return dpif_linux_vport_transact(&request, reply, bufp);
1088 }
1089