85d05bb714ce61df9078aa8654f71a183c02dab7
[openvswitch] / lib / dpif.c
1 /*
2  * Copyright (c) 2008, 2009 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 #include "dpif.h"
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/rtnetlink.h>
27 #include <linux/ethtool.h>
28 #include <linux/sockios.h>
29 #include <netinet/in.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <sys/stat.h>
34 #include <sys/sysmacros.h>
35 #include <unistd.h>
36
37 #include "coverage.h"
38 #include "dynamic-string.h"
39 #include "flow.h"
40 #include "netlink.h"
41 #include "odp-util.h"
42 #include "ofp-print.h"
43 #include "ofpbuf.h"
44 #include "packets.h"
45 #include "poll-loop.h"
46 #include "util.h"
47 #include "valgrind.h"
48
49 #include "vlog.h"
50 #define THIS_MODULE VLM_dpif
51
52 /* A datapath interface. */
53 struct dpif {
54     char *name;
55     unsigned int minor;
56     int fd;
57 };
58
59 /* Rate limit for individual messages going to or from the datapath, output at
60  * DBG level.  This is very high because, if these are enabled, it is because
61  * we really need to see them. */
62 static struct vlog_rate_limit dpmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
63
64 /* Not really much point in logging many dpif errors. */
65 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
66
67 static int get_minor_from_name(const char *name, unsigned int *minor);
68 static int name_to_minor(const char *name, unsigned int *minor);
69 static int lookup_minor(const char *name, unsigned int *minor);
70 static int open_by_minor(unsigned int minor, struct dpif **dpifp);
71 static int make_openvswitch_device(unsigned int minor, char **fnp);
72 static void check_rw_odp_flow(struct odp_flow *);
73
74 int
75 dpif_open(const char *name, struct dpif **dpifp)
76 {
77     struct dpif *dpif;
78     unsigned int minor;
79     int listen_mask;
80     int error;
81
82     *dpifp = NULL;
83
84     error = name_to_minor(name, &minor);
85     if (error) {
86         return error;
87     }
88
89     error = open_by_minor(minor, &dpif);
90     if (error) {
91         return error;
92     }
93
94     /* We can open the device, but that doesn't mean that it's been created.
95      * If it hasn't been, then any command other than ODP_DP_CREATE will
96      * return ENODEV.  Try something innocuous. */
97     listen_mask = 0;            /* Make Valgrind happy. */
98     if (ioctl(dpif->fd, ODP_GET_LISTEN_MASK, &listen_mask)) {
99         error = errno;
100         if (error != ENODEV) {
101             VLOG_WARN("%s: probe returned unexpected error: %s",
102                       dpif_name(dpif), strerror(error));
103         }
104         dpif_close(dpif);
105         return error;
106     }
107     *dpifp = dpif;
108     return 0;
109 }
110
111 void
112 dpif_close(struct dpif *dpif)
113 {
114     if (dpif) {
115         free(dpif->name);
116         close(dpif->fd);
117         free(dpif);
118     }
119 }
120
121 static int
122 do_ioctl(const struct dpif *dpif, int cmd, const char *cmd_name,
123          const void *arg)
124 {
125     int error = ioctl(dpif->fd, cmd, arg) ? errno : 0;
126     if (cmd_name) {
127         if (error) {
128             VLOG_WARN_RL(&error_rl, "%s: ioctl(%s) failed (%s)",
129                          dpif_name(dpif), cmd_name, strerror(error));
130         } else {
131             VLOG_DBG_RL(&dpmsg_rl, "%s: ioctl(%s): success",
132                         dpif_name(dpif), cmd_name);
133         }
134     }
135     return error;
136 }
137
138 int
139 dpif_create(const char *name, struct dpif **dpifp)
140 {
141     unsigned int minor;
142     int error;
143
144     *dpifp = NULL;
145     if (!get_minor_from_name(name, &minor)) {
146         /* Minor was specified in 'name', go ahead and create it. */
147         struct dpif *dpif;
148
149         error = open_by_minor(minor, &dpif);
150         if (error) {
151             return error;
152         }
153
154         error = ioctl(dpif->fd, ODP_DP_CREATE, name) < 0 ? errno : 0;
155         if (!error) {
156             *dpifp = dpif;
157         } else {
158             dpif_close(dpif);
159         }
160         return error;
161     } else {
162         for (minor = 0; minor < ODP_MAX; minor++) {
163             struct dpif *dpif;
164
165             error = open_by_minor(minor, &dpif);
166             if (error) {
167                 return error;
168             }
169
170             error = ioctl(dpif->fd, ODP_DP_CREATE, name) < 0 ? errno : 0;
171             if (!error) {
172                 *dpifp = dpif;
173                 return 0;
174             }
175             dpif_close(dpif);
176             if (error != EBUSY) {
177                 return error;
178             }
179         }
180         return ENOBUFS;
181     }
182 }
183
184 const char *
185 dpif_name(const struct dpif *dpif)
186 {
187     return dpif->name;
188 }
189
190 int
191 dpif_delete(struct dpif *dpif)
192 {
193     COVERAGE_INC(dpif_destroy);
194     return do_ioctl(dpif, ODP_DP_DESTROY, "ODP_DP_DESTROY", NULL);
195 }
196
197 int
198 dpif_get_dp_stats(const struct dpif *dpif, struct odp_stats *stats)
199 {
200     memset(stats, 0, sizeof *stats);
201     return do_ioctl(dpif, ODP_DP_STATS, "ODP_DP_STATS", stats);
202 }
203
204 int
205 dpif_get_drop_frags(const struct dpif *dpif, bool *drop_frags)
206 {
207     int tmp;
208     int error = do_ioctl(dpif, ODP_GET_DROP_FRAGS, "ODP_GET_DROP_FRAGS", &tmp);
209     *drop_frags = error ? tmp & 1 : false;
210     return error;
211 }
212
213 int
214 dpif_set_drop_frags(struct dpif *dpif, bool drop_frags)
215 {
216     int tmp = drop_frags;
217     return do_ioctl(dpif, ODP_SET_DROP_FRAGS, "ODP_SET_DROP_FRAGS", &tmp);
218 }
219
220 int
221 dpif_recv_purge(struct dpif *dpif)
222 {
223     struct odp_stats stats;
224     unsigned int i;
225     int error;
226
227     COVERAGE_INC(dpif_purge);
228
229     error = dpif_get_dp_stats(dpif, &stats);
230     if (error) {
231         return error;
232     }
233
234     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue; i++) {
235         struct ofpbuf *buf;
236         error = dpif_recv(dpif, &buf);
237         if (error) {
238             return error == EAGAIN ? 0 : error;
239         }
240         ofpbuf_delete(buf);
241     }
242     return 0;
243 }
244
245 int
246 dpif_port_add(struct dpif *dpif, const char *devname, uint16_t flags,
247               uint16_t *port_nop)
248 {
249     struct odp_port port;
250     uint16_t port_no;
251     int error;
252
253     COVERAGE_INC(dpif_port_add);
254
255     memset(&port, 0, sizeof port);
256     strncpy(port.devname, devname, sizeof port.devname);
257     port.flags = flags;
258
259     error = do_ioctl(dpif, ODP_PORT_ADD, NULL, &port);
260     if (!error) {
261         port_no = port.port;
262         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
263                     dpif_name(dpif), devname, port_no);
264     } else {
265         port_no = UINT16_MAX;
266         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
267                      dpif_name(dpif), devname, strerror(errno));
268     }
269     if (port_nop) {
270         *port_nop = port_no;
271     }
272     return error;
273 }
274
275 int
276 dpif_port_del(struct dpif *dpif, uint16_t port_no)
277 {
278     int tmp = port_no;
279     COVERAGE_INC(dpif_port_del);
280     return do_ioctl(dpif, ODP_PORT_DEL, "ODP_PORT_DEL", &tmp);
281 }
282
283 int
284 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
285                           struct odp_port *port)
286 {
287     memset(port, 0, sizeof *port);
288     port->port = port_no;
289     if (!ioctl(dpif->fd, ODP_PORT_QUERY, port)) {
290         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
291                     dpif_name(dpif), port_no, port->devname);
292         return 0;
293     } else {
294         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
295                      dpif_name(dpif), port_no, strerror(errno));
296         return errno;
297     }
298 }
299
300 int
301 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
302                         struct odp_port *port)
303 {
304     memset(port, 0, sizeof *port);
305     strncpy(port->devname, devname, sizeof port->devname);
306     if (!ioctl(dpif->fd, ODP_PORT_QUERY, port)) {
307         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
308                     dpif_name(dpif), devname, port->port);
309         return 0;
310     } else {
311         /* Log level is DBG here because all the current callers are interested
312          * in whether 'dpif' actually has a port 'devname', so that it's not an
313          * issue worth logging if it doesn't. */
314         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
315                     dpif_name(dpif), devname, strerror(errno));
316         return errno;
317     }
318 }
319
320 int
321 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
322                    char *name, size_t name_size)
323 {
324     struct odp_port port;
325     int error;
326
327     assert(name_size > 0);
328
329     error = dpif_port_query_by_number(dpif, port_no, &port);
330     if (!error) {
331         ovs_strlcpy(name, port.devname, name_size);
332     } else {
333         *name = '\0';
334     }
335     return error;
336 }
337
338 int
339 dpif_port_list(const struct dpif *dpif,
340                struct odp_port **portsp, size_t *n_portsp)
341 {
342     struct odp_port *ports;
343     size_t n_ports;
344     int error;
345
346     for (;;) {
347         struct odp_stats stats;
348         struct odp_portvec pv;
349
350         error = dpif_get_dp_stats(dpif, &stats);
351         if (error) {
352             goto exit;
353         }
354
355         ports = xcalloc(stats.n_ports, sizeof *ports);
356         pv.ports = ports;
357         pv.n_ports = stats.n_ports;
358         error = do_ioctl(dpif, ODP_PORT_LIST, "ODP_PORT_LIST", &pv);
359         if (error) {
360             /* Hard error. */
361             free(ports);
362             goto exit;
363         } else if (pv.n_ports <= stats.n_ports) {
364             /* Success. */
365             error = 0;
366             n_ports = pv.n_ports;
367             goto exit;
368         } else {
369             /* Soft error: port count increased behind our back.  Try again. */
370             free(ports);
371         }
372     }
373
374 exit:
375     if (error) {
376         *portsp = NULL;
377         *n_portsp = 0;
378     } else {
379         *portsp = ports;
380         *n_portsp = n_ports;
381     }
382     return error;
383 }
384
385 int
386 dpif_port_group_set(struct dpif *dpif, uint16_t group,
387                     const uint16_t ports[], size_t n_ports)
388 {
389     struct odp_port_group pg;
390
391     COVERAGE_INC(dpif_port_group_set);
392     assert(n_ports <= UINT16_MAX);
393     pg.group = group;
394     pg.ports = (uint16_t *) ports;
395     pg.n_ports = n_ports;
396     return do_ioctl(dpif, ODP_PORT_GROUP_SET, "ODP_PORT_GROUP_SET", &pg);
397 }
398
399 int
400 dpif_port_group_get(const struct dpif *dpif, uint16_t group,
401                     uint16_t **ports, size_t *n_ports)
402 {
403     int error;
404
405     *ports = NULL;
406     *n_ports = 0;
407     for (;;) {
408         struct odp_port_group pg;
409         pg.group = group;
410         pg.ports = *ports;
411         pg.n_ports = *n_ports;
412
413         error = do_ioctl(dpif, ODP_PORT_GROUP_GET, "ODP_PORT_GROUP_GET", &pg);
414         if (error) {
415             /* Hard error. */
416             free(*ports);
417             *ports = NULL;
418             *n_ports = 0;
419             break;
420         } else if (pg.n_ports <= *n_ports) {
421             /* Success. */
422             *n_ports = pg.n_ports;
423             break;
424         } else {
425             /* Soft error: there were more ports than we expected in the
426              * group.  Try again. */
427             free(*ports);
428             *ports = xcalloc(pg.n_ports, sizeof **ports);
429             *n_ports = pg.n_ports;
430         }
431     }
432     return error;
433 }
434
435 int
436 dpif_flow_flush(struct dpif *dpif)
437 {
438     COVERAGE_INC(dpif_flow_flush);
439     return do_ioctl(dpif, ODP_FLOW_FLUSH, "ODP_FLOW_FLUSH", NULL);
440 }
441
442 static enum vlog_level
443 flow_message_log_level(int error)
444 {
445     return error ? VLL_WARN : VLL_DBG;
446 }
447
448 static bool
449 should_log_flow_message(int error)
450 {
451     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
452                              error ? &error_rl : &dpmsg_rl);
453 }
454
455 static void
456 log_flow_message(const struct dpif *dpif, int error,
457                  const char *operation,
458                  const flow_t *flow, const struct odp_flow_stats *stats,
459                  const union odp_action *actions, size_t n_actions)
460 {
461     struct ds ds = DS_EMPTY_INITIALIZER;
462     ds_put_format(&ds, "%s: ", dpif_name(dpif));
463     if (error) {
464         ds_put_cstr(&ds, "failed to ");
465     }
466     ds_put_format(&ds, "%s ", operation);
467     if (error) {
468         ds_put_format(&ds, "(%s) ", strerror(error));
469     }
470     flow_format(&ds, flow);
471     if (stats) {
472         ds_put_cstr(&ds, ", ");
473         format_odp_flow_stats(&ds, stats);
474     }
475     if (actions || n_actions) {
476         ds_put_cstr(&ds, ", actions:");
477         format_odp_actions(&ds, actions, n_actions);
478     }
479     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
480     ds_destroy(&ds);
481 }
482
483 static int
484 do_flow_ioctl(const struct dpif *dpif, int cmd, struct odp_flow *flow,
485               const char *operation, bool show_stats)
486 {
487     int error = do_ioctl(dpif, cmd, NULL, flow);
488     if (error && show_stats) {
489         flow->n_actions = 0;
490     }
491     if (should_log_flow_message(error)) {
492         log_flow_message(dpif, error, operation, &flow->key,
493                          show_stats && !error ? &flow->stats : NULL,
494                          flow->actions, flow->n_actions);
495     }
496     return error;
497 }
498
499 int
500 dpif_flow_put(struct dpif *dpif, struct odp_flow_put *put)
501 {
502     int error = do_ioctl(dpif, ODP_FLOW_PUT, NULL, put);
503     COVERAGE_INC(dpif_flow_put);
504     if (should_log_flow_message(error)) {
505         struct ds operation = DS_EMPTY_INITIALIZER;
506         ds_put_cstr(&operation, "put");
507         if (put->flags & ODPPF_CREATE) {
508             ds_put_cstr(&operation, "[create]");
509         }
510         if (put->flags & ODPPF_MODIFY) {
511             ds_put_cstr(&operation, "[modify]");
512         }
513         if (put->flags & ODPPF_ZERO_STATS) {
514             ds_put_cstr(&operation, "[zero]");
515         }
516 #define ODPPF_ALL (ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS)
517         if (put->flags & ~ODPPF_ALL) {
518             ds_put_format(&operation, "[%x]", put->flags & ~ODPPF_ALL);
519         }
520         log_flow_message(dpif, error, ds_cstr(&operation), &put->flow.key,
521                          !error ? &put->flow.stats : NULL,
522                          put->flow.actions, put->flow.n_actions);
523         ds_destroy(&operation);
524     }
525     return error;
526 }
527
528 int
529 dpif_flow_del(struct dpif *dpif, struct odp_flow *flow)
530 {
531     COVERAGE_INC(dpif_flow_del);
532     check_rw_odp_flow(flow);
533     memset(&flow->stats, 0, sizeof flow->stats);
534     return do_flow_ioctl(dpif, ODP_FLOW_DEL, flow, "delete flow", true);
535 }
536
537 int
538 dpif_flow_get(const struct dpif *dpif, struct odp_flow *flow)
539 {
540     struct odp_flowvec fv;
541     int error;
542
543     COVERAGE_INC(dpif_flow_get);
544
545     check_rw_odp_flow(flow);
546     fv.flows = flow;
547     fv.n_flows = 1;
548     error = do_ioctl(dpif, ODP_FLOW_GET, "ODP_FLOW_GET", &fv);
549     if (!error) {
550         error = flow->stats.error;
551         if (error) {
552             VLOG_WARN_RL(&error_rl, "%s: ioctl(ODP_FLOW_GET) failed (%s)",
553                          dpif_name(dpif), strerror(error));
554         }
555     }
556     return error;
557 }
558
559 int
560 dpif_flow_get_multiple(const struct dpif *dpif,
561                        struct odp_flow flows[], size_t n)
562 {
563     struct odp_flowvec fv;
564     size_t i;
565
566     COVERAGE_ADD(dpif_flow_query_multiple, n);
567     fv.flows = flows;
568     fv.n_flows = n;
569     for (i = 0; i < n; i++) {
570         check_rw_odp_flow(&flows[i]);
571     }
572     return do_ioctl(dpif, ODP_FLOW_GET, "ODP_FLOW_GET",
573                     &fv);
574 }
575
576 int
577 dpif_flow_list(const struct dpif *dpif, struct odp_flow flows[], size_t n,
578                size_t *n_out)
579 {
580     struct odp_flowvec fv;
581     uint32_t i;
582     int error;
583
584     COVERAGE_INC(dpif_flow_query_list);
585     fv.flows = flows;
586     fv.n_flows = n;
587     if (RUNNING_ON_VALGRIND) {
588         memset(flows, 0, n * sizeof *flows);
589     } else {
590         for (i = 0; i < n; i++) {
591             flows[i].actions = NULL;
592             flows[i].n_actions = 0;
593         }
594     }
595     error = do_ioctl(dpif, ODP_FLOW_LIST, NULL, &fv);
596     if (error) {
597         *n_out = 0;
598         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
599                      dpif_name(dpif), strerror(error));
600     } else {
601         COVERAGE_ADD(dpif_flow_query_list_n, fv.n_flows);
602         *n_out = fv.n_flows;
603         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows",
604                     dpif_name(dpif), *n_out);
605     }
606     return error;
607 }
608
609 int
610 dpif_flow_list_all(const struct dpif *dpif,
611                    struct odp_flow **flowsp, size_t *np)
612 {
613     struct odp_stats stats;
614     struct odp_flow *flows;
615     size_t n_flows;
616     int error;
617
618     *flowsp = NULL;
619     *np = 0;
620
621     error = dpif_get_dp_stats(dpif, &stats);
622     if (error) {
623         return error;
624     }
625
626     flows = xmalloc(sizeof *flows * stats.n_flows);
627     error = dpif_flow_list(dpif, flows, stats.n_flows, &n_flows);
628     if (error) {
629         free(flows);
630         return error;
631     }
632
633     if (stats.n_flows != n_flows) {
634         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
635                      "flows but flow listing reported %zu",
636                      dpif_name(dpif), stats.n_flows, n_flows);
637     }
638     *flowsp = flows;
639     *np = n_flows;
640     return 0;
641 }
642
643 int
644 dpif_execute(struct dpif *dpif, uint16_t in_port,
645              const union odp_action actions[], size_t n_actions,
646              const struct ofpbuf *buf)
647 {
648     int error;
649
650     COVERAGE_INC(dpif_execute);
651     if (n_actions > 0) {
652         struct odp_execute execute;
653         memset(&execute, 0, sizeof execute);
654         execute.in_port = in_port;
655         execute.actions = (union odp_action *) actions;
656         execute.n_actions = n_actions;
657         execute.data = buf->data;
658         execute.length = buf->size;
659         error = do_ioctl(dpif, ODP_EXECUTE, NULL, &execute);
660     } else {
661         error = 0;
662     }
663
664     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
665         struct ds ds = DS_EMPTY_INITIALIZER;
666         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
667         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
668         format_odp_actions(&ds, actions, n_actions);
669         if (error) {
670             ds_put_format(&ds, " failed (%s)", strerror(error));
671         }
672         ds_put_format(&ds, " on packet %s", packet);
673         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
674         ds_destroy(&ds);
675         free(packet);
676     }
677     return error;
678 }
679
680 int
681 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
682 {
683     int error = do_ioctl(dpif, ODP_GET_LISTEN_MASK, "ODP_GET_LISTEN_MASK",
684                          listen_mask);
685     if (error) {
686         *listen_mask = 0;
687     }
688     return error;
689 }
690
691 int
692 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
693 {
694     return do_ioctl(dpif, ODP_SET_LISTEN_MASK, "ODP_SET_LISTEN_MASK",
695                     &listen_mask);
696 }
697
698 int
699 dpif_recv(struct dpif *dpif, struct ofpbuf **bufp)
700 {
701     struct ofpbuf *buf;
702     int retval;
703     int error;
704
705     buf = ofpbuf_new(65536);
706     retval = read(dpif->fd, ofpbuf_tail(buf), ofpbuf_tailroom(buf));
707     if (retval < 0) {
708         error = errno;
709         if (error != EAGAIN) {
710             VLOG_WARN_RL(&error_rl, "%s: read failed: %s",
711                          dpif_name(dpif), strerror(error));
712         }
713     } else if (retval >= sizeof(struct odp_msg)) {
714         struct odp_msg *msg = buf->data;
715         if (msg->length <= retval) {
716             buf->size += retval;
717             if (VLOG_IS_DBG_ENABLED()) {
718                 void *payload = msg + 1;
719                 size_t length = buf->size - sizeof *msg;
720                 char *s = ofp_packet_to_string(payload, length, length);
721                 VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
722                             "%zu on port %"PRIu16": %s", dpif_name(dpif),
723                             (msg->type == _ODPL_MISS_NR ? "miss"
724                              : msg->type == _ODPL_ACTION_NR ? "action"
725                              : "<unknown>"),
726                             msg->length - sizeof(struct odp_msg),
727                             msg->port, s);
728                 free(s);
729             }
730             *bufp = buf;
731             COVERAGE_INC(dpif_recv);
732             return 0;
733         } else {
734             VLOG_WARN_RL(&error_rl, "%s: discarding message truncated "
735                          "from %zu bytes to %d",
736                          dpif_name(dpif), msg->length, retval);
737             error = ERANGE;
738         }
739     } else if (!retval) {
740         VLOG_WARN_RL(&error_rl, "%s: unexpected end of file", dpif_name(dpif));
741         error = EPROTO;
742     } else {
743         VLOG_WARN_RL(&error_rl,
744                      "%s: discarding too-short message (%d bytes)",
745                      dpif_name(dpif), retval);
746         error = ERANGE;
747     }
748
749     *bufp = NULL;
750     ofpbuf_delete(buf);
751     return error;
752 }
753
754 void
755 dpif_recv_wait(struct dpif *dpif)
756 {
757     poll_fd_wait(dpif->fd, POLLIN);
758 }
759
760 void
761 dpif_get_netflow_ids(const struct dpif *dpif,
762                      uint8_t *engine_type, uint8_t *engine_id)
763 {
764     *engine_type = *engine_id = dpif->minor;
765 }
766 \f
767 struct dpifmon {
768     struct dpif *dpif;
769     struct nl_sock *sock;
770     int local_ifindex;
771 };
772
773 int
774 dpifmon_create(const char *datapath_name, struct dpifmon **monp)
775 {
776     struct dpifmon *mon;
777     char local_name[IFNAMSIZ];
778     int error;
779
780     mon = *monp = xmalloc(sizeof *mon);
781
782     error = dpif_open(datapath_name, &mon->dpif);
783     if (error) {
784         goto error;
785     }
786     error = dpif_port_get_name(mon->dpif, ODPP_LOCAL,
787                                local_name, sizeof local_name);
788     if (error) {
789         goto error_close_dpif;
790     }
791
792     mon->local_ifindex = if_nametoindex(local_name);
793     if (!mon->local_ifindex) {
794         error = errno;
795         VLOG_WARN("could not get ifindex of %s device: %s",
796                   local_name, strerror(errno));
797         goto error_close_dpif;
798     }
799
800     error = nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &mon->sock);
801     if (error) {
802         VLOG_WARN("could not create rtnetlink socket: %s", strerror(error));
803         goto error_close_dpif;
804     }
805
806     return 0;
807
808 error_close_dpif:
809     dpif_close(mon->dpif);
810 error:
811     free(mon);
812     *monp = NULL;
813     return error;
814 }
815
816 void
817 dpifmon_destroy(struct dpifmon *mon)
818 {
819     if (mon) {
820         dpif_close(mon->dpif);
821         nl_sock_destroy(mon->sock);
822     }
823 }
824
825 int
826 dpifmon_poll(struct dpifmon *mon, char **devnamep)
827 {
828     static struct vlog_rate_limit slow_rl = VLOG_RATE_LIMIT_INIT(1, 5);
829     static const struct nl_policy rtnlgrp_link_policy[] = {
830         [IFLA_IFNAME] = { .type = NL_A_STRING },
831         [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
832     };
833     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
834     struct ofpbuf *buf;
835     int error;
836
837     *devnamep = NULL;
838 again:
839     error = nl_sock_recv(mon->sock, &buf, false);
840     switch (error) {
841     case 0:
842         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
843                              rtnlgrp_link_policy,
844                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
845             VLOG_WARN_RL(&slow_rl, "received bad rtnl message");
846             error = ENOBUFS;
847         } else {
848             const char *devname = nl_attr_get_string(attrs[IFLA_IFNAME]);
849             bool for_us;
850
851             if (attrs[IFLA_MASTER]) {
852                 uint32_t master_ifindex = nl_attr_get_u32(attrs[IFLA_MASTER]);
853                 for_us = master_ifindex == mon->local_ifindex;
854             } else {
855                 /* It's for us if that device is one of our ports. */
856                 struct odp_port port;
857                 for_us = !dpif_port_query_by_name(mon->dpif, devname, &port);
858             }
859
860             if (!for_us) {
861                 /* Not for us, try again. */
862                 ofpbuf_delete(buf);
863                 COVERAGE_INC(dpifmon_poll_false_wakeup);
864                 goto again;
865             }
866             COVERAGE_INC(dpifmon_poll_changed);
867             *devnamep = xstrdup(devname);
868         }
869         ofpbuf_delete(buf);
870         break;
871
872     case EAGAIN:
873         /* Nothing to do. */
874         break;
875
876     case ENOBUFS:
877         VLOG_WARN_RL(&slow_rl, "dpifmon socket overflowed");
878         break;
879
880     default:
881         VLOG_WARN_RL(&slow_rl, "error on dpifmon socket: %s", strerror(error));
882         break;
883     }
884     return error;
885 }
886
887 void
888 dpifmon_run(struct dpifmon *mon UNUSED)
889 {
890     /* Nothing to do in this implementation. */
891 }
892
893 void
894 dpifmon_wait(struct dpifmon *mon)
895 {
896     nl_sock_wait(mon->sock, POLLIN);
897 }
898 \f
899 static int get_openvswitch_major(void);
900 static int get_major(const char *target, int default_major);
901
902 static int
903 lookup_minor(const char *name, unsigned int *minor)
904 {
905     struct ethtool_drvinfo drvinfo;
906     struct ifreq ifr;
907     int error;
908     int sock;
909
910     *minor = -1;
911     sock = socket(AF_INET, SOCK_DGRAM, 0);
912     if (sock < 0) {
913         VLOG_WARN("socket(AF_INET) failed: %s", strerror(errno));
914         error = errno;
915         goto error;
916     }
917
918     memset(&ifr, 0, sizeof ifr);
919     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
920     ifr.ifr_data = (caddr_t) &drvinfo;
921
922     memset(&drvinfo, 0, sizeof drvinfo);
923     drvinfo.cmd = ETHTOOL_GDRVINFO;
924     if (ioctl(sock, SIOCETHTOOL, &ifr)) {
925         VLOG_WARN("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
926         error = errno;
927         goto error_close_sock;
928     }
929
930     if (strcmp(drvinfo.driver, "openvswitch")) {
931         VLOG_WARN("%s is not an openvswitch device", name);
932         error = EOPNOTSUPP;
933         goto error_close_sock;
934     }
935
936     if (!isdigit(drvinfo.bus_info[0])) {
937         VLOG_WARN("%s ethtool info does not contain an openvswitch minor",
938                   name);
939         error = EPROTOTYPE;
940         goto error_close_sock;
941     }
942
943     *minor = atoi(drvinfo.bus_info);
944     close(sock);
945     return 0;
946
947 error_close_sock:
948     close(sock);
949 error:
950     return error;
951 }
952
953 static int
954 make_openvswitch_device(unsigned int minor, char **fnp)
955 {
956     dev_t dev = makedev(get_openvswitch_major(), minor);
957     const char dirname[] = "/dev/net";
958     struct stat s;
959     char fn[128];
960
961     *fnp = NULL;
962     sprintf(fn, "%s/dp%d", dirname, minor);
963     if (!stat(fn, &s)) {
964         if (!S_ISCHR(s.st_mode)) {
965             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
966                          fn);
967         } else if (s.st_rdev != dev) {
968             VLOG_WARN_RL(&error_rl,
969                          "%s is device %u:%u instead of %u:%u, fixing",
970                          fn, major(s.st_rdev), minor(s.st_rdev),
971                          major(dev), minor(dev));
972         } else {
973             goto success;
974         }
975         if (unlink(fn)) {
976             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
977                          fn, strerror(errno));
978             return errno;
979         }
980     } else if (errno == ENOENT) {
981         if (stat(dirname, &s)) {
982             if (errno == ENOENT) {
983                 if (mkdir(dirname, 0755)) {
984                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
985                                  dirname, strerror(errno));
986                     return errno;
987                 }
988             } else {
989                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
990                              dirname, strerror(errno));
991                 return errno;
992             }
993         }
994     } else {
995         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
996         return errno;
997     }
998
999     /* The device needs to be created. */
1000     if (mknod(fn, S_IFCHR | 0700, dev)) {
1001         VLOG_WARN_RL(&error_rl,
1002                      "%s: creating character device %u:%u failed (%s)",
1003                      fn, major(dev), minor(dev), strerror(errno));
1004         return errno;
1005     }
1006
1007 success:
1008     *fnp = xstrdup(fn);
1009     return 0;
1010 }
1011
1012
1013 static int
1014 get_openvswitch_major(void)
1015 {
1016     static unsigned int openvswitch_major;
1017     if (!openvswitch_major) {
1018         enum { DEFAULT_MAJOR = 248 };
1019         openvswitch_major = get_major("openvswitch", DEFAULT_MAJOR);
1020     }
1021     return openvswitch_major;
1022 }
1023
1024 static int
1025 get_major(const char *target, int default_major)
1026 {
1027     const char fn[] = "/proc/devices";
1028     char line[128];
1029     FILE *file;
1030     int ln;
1031
1032     file = fopen(fn, "r");
1033     if (!file) {
1034         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
1035         goto error;
1036     }
1037
1038     for (ln = 1; fgets(line, sizeof line, file); ln++) {
1039         char name[64];
1040         int major;
1041
1042         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
1043             /* Nothing to do. */
1044         } else if (!strncmp(line, "Block", 5)) {
1045             /* We only want character devices, so skip the rest of the file. */
1046             break;
1047         } else if (sscanf(line, "%d %63s", &major, name)) {
1048             if (!strcmp(name, target)) {
1049                 fclose(file);
1050                 return major;
1051             }
1052         } else {
1053             static bool warned;
1054             if (!warned) {
1055                 VLOG_WARN("%s:%d: syntax error", fn, ln);
1056             }
1057             warned = true;
1058         }
1059     }
1060
1061     VLOG_ERR("%s: %s major not found (is the module loaded?), using "
1062              "default major %d", fn, target, default_major);
1063 error:
1064     VLOG_INFO("using default major %d for %s", default_major, target);
1065     return default_major;
1066 }
1067
1068 static int
1069 name_to_minor(const char *name, unsigned int *minor)
1070 {
1071     if (!get_minor_from_name(name, minor)) {
1072         return 0;
1073     }
1074     return lookup_minor(name, minor);
1075 }
1076
1077 static int
1078 get_minor_from_name(const char *name, unsigned int *minor)
1079 {
1080     if (!strncmp(name, "dp", 2) && isdigit(name[2])) {
1081         *minor = atoi(name + 2);
1082         return 0;
1083     } else {
1084         return EINVAL;
1085     }
1086 }
1087
1088 static int
1089 open_by_minor(unsigned int minor, struct dpif **dpifp)
1090 {
1091     struct dpif *dpif;
1092     int error;
1093     char *fn;
1094     int fd;
1095
1096     *dpifp = NULL;
1097     error = make_openvswitch_device(minor, &fn);
1098     if (error) {
1099         return error;
1100     }
1101
1102     fd = open(fn, O_RDONLY | O_NONBLOCK);
1103     if (fd < 0) {
1104         error = errno;
1105         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
1106         free(fn);
1107         return error;
1108     }
1109     free(fn);
1110
1111     dpif = xmalloc(sizeof *dpif);
1112     dpif->name = xasprintf("dp%u", dpif->minor);
1113     dpif->minor = minor;
1114     dpif->fd = fd;
1115     *dpifp = dpif;
1116     return 0;
1117 }
1118 \f
1119 /* There is a tendency to construct odp_flow objects on the stack and to
1120  * forget to properly initialize their "actions" and "n_actions" members.
1121  * When this happens, we get memory corruption because the kernel
1122  * writes through the random pointer that is in the "actions" member.
1123  *
1124  * This function attempts to combat the problem by:
1125  *
1126  *      - Forcing a segfault if "actions" points to an invalid region (instead
1127  *        of just getting back EFAULT, which can be easily missed in the log).
1128  *
1129  *      - Storing a distinctive value that is likely to cause an
1130  *        easy-to-identify error later if it is dereferenced, etc.
1131  *
1132  *      - Triggering a warning on uninitialized memory from Valgrind if
1133  *        "actions" or "n_actions" was not initialized.
1134  */
1135 static void
1136 check_rw_odp_flow(struct odp_flow *flow)
1137 {
1138     if (flow->n_actions) {
1139         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
1140     }
1141 }