dpif: Rename odp_msg related functions for more consistency.
[sliver-openvswitch.git] / 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 port_no,
247               uint16_t flags)
248 {
249     struct odp_port port;
250
251     COVERAGE_INC(dpif_port_add);
252     memset(&port, 0, sizeof port);
253     strncpy(port.devname, devname, sizeof port.devname);
254     port.port = port_no;
255     port.flags = flags;
256     if (!ioctl(dpif->fd, ODP_PORT_ADD, &port)) {
257         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
258                     dpif_name(dpif), devname, port_no);
259         return 0;
260     } else {
261         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port %"PRIu16": %s",
262                      dpif_name(dpif), devname, port_no, strerror(errno));
263         return errno;
264     }
265 }
266
267 int
268 dpif_port_del(struct dpif *dpif, uint16_t port_no)
269 {
270     int tmp = port_no;
271     COVERAGE_INC(dpif_port_del);
272     return do_ioctl(dpif, ODP_PORT_DEL, "ODP_PORT_DEL", &tmp);
273 }
274
275 int
276 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
277                           struct odp_port *port)
278 {
279     memset(port, 0, sizeof *port);
280     port->port = port_no;
281     if (!ioctl(dpif->fd, ODP_PORT_QUERY, port)) {
282         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
283                     dpif_name(dpif), port_no, port->devname);
284         return 0;
285     } else {
286         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
287                      dpif_name(dpif), port_no, strerror(errno));
288         return errno;
289     }
290 }
291
292 int
293 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
294                         struct odp_port *port)
295 {
296     memset(port, 0, sizeof *port);
297     strncpy(port->devname, devname, sizeof port->devname);
298     if (!ioctl(dpif->fd, ODP_PORT_QUERY, port)) {
299         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
300                     dpif_name(dpif), devname, port->port);
301         return 0;
302     } else {
303         /* Log level is DBG here because all the current callers are interested
304          * in whether 'dpif' actually has a port 'devname', so that it's not an
305          * issue worth logging if it doesn't. */
306         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
307                     dpif_name(dpif), devname, strerror(errno));
308         return errno;
309     }
310 }
311
312 int
313 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
314                    char *name, size_t name_size)
315 {
316     struct odp_port port;
317     int error;
318
319     assert(name_size > 0);
320
321     error = dpif_port_query_by_number(dpif, port_no, &port);
322     if (!error) {
323         ovs_strlcpy(name, port.devname, name_size);
324     } else {
325         *name = '\0';
326     }
327     return error;
328 }
329
330 int
331 dpif_port_list(const struct dpif *dpif,
332                struct odp_port **ports, size_t *n_ports)
333 {
334     struct odp_portvec pv;
335     struct odp_stats stats;
336     int error;
337
338     do {
339         error = dpif_get_dp_stats(dpif, &stats);
340         if (error) {
341             goto error;
342         }
343
344         *ports = xcalloc(1, stats.n_ports * sizeof **ports);
345         pv.ports = *ports;
346         pv.n_ports = stats.n_ports;
347         error = do_ioctl(dpif, ODP_PORT_LIST, "ODP_PORT_LIST", &pv);
348         if (error) {
349             free(*ports);
350             goto error;
351         }
352     } while (pv.n_ports != stats.n_ports);
353     *n_ports = pv.n_ports;
354     return 0;
355
356 error:
357     *ports = NULL;
358     *n_ports = 0;
359     return error;
360 }
361
362 int
363 dpif_port_group_set(struct dpif *dpif, uint16_t group,
364                     const uint16_t ports[], size_t n_ports)
365 {
366     struct odp_port_group pg;
367
368     COVERAGE_INC(dpif_port_group_set);
369     assert(n_ports <= UINT16_MAX);
370     pg.group = group;
371     pg.ports = (uint16_t *) ports;
372     pg.n_ports = n_ports;
373     return do_ioctl(dpif, ODP_PORT_GROUP_SET, "ODP_PORT_GROUP_SET", &pg);
374 }
375
376 int
377 dpif_port_group_get(const struct dpif *dpif, uint16_t group,
378                     uint16_t **ports, size_t *n_ports)
379 {
380     int error;
381
382     *ports = NULL;
383     *n_ports = 0;
384     for (;;) {
385         struct odp_port_group pg;
386         pg.group = group;
387         pg.ports = *ports;
388         pg.n_ports = *n_ports;
389
390         error = do_ioctl(dpif, ODP_PORT_GROUP_GET, "ODP_PORT_GROUP_GET", &pg);
391         if (error) {
392             /* Hard error. */
393             free(*ports);
394             *ports = NULL;
395             *n_ports = 0;
396             break;
397         } else if (pg.n_ports <= *n_ports) {
398             /* Success. */
399             *n_ports = pg.n_ports;
400             break;
401         } else {
402             /* Soft error: there were more ports than we expected in the
403              * group.  Try again. */
404             free(*ports);
405             *ports = xcalloc(pg.n_ports, sizeof **ports);
406             *n_ports = pg.n_ports;
407         }
408     }
409     return error;
410 }
411
412 int
413 dpif_flow_flush(struct dpif *dpif)
414 {
415     COVERAGE_INC(dpif_flow_flush);
416     return do_ioctl(dpif, ODP_FLOW_FLUSH, "ODP_FLOW_FLUSH", NULL);
417 }
418
419 static enum vlog_level
420 flow_message_log_level(int error)
421 {
422     return error ? VLL_WARN : VLL_DBG;
423 }
424
425 static bool
426 should_log_flow_message(int error)
427 {
428     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
429                              error ? &error_rl : &dpmsg_rl);
430 }
431
432 static void
433 log_flow_message(const struct dpif *dpif, int error,
434                  const char *operation,
435                  const flow_t *flow, const struct odp_flow_stats *stats,
436                  const union odp_action *actions, size_t n_actions)
437 {
438     struct ds ds = DS_EMPTY_INITIALIZER;
439     ds_put_format(&ds, "%s: ", dpif_name(dpif));
440     if (error) {
441         ds_put_cstr(&ds, "failed to ");
442     }
443     ds_put_format(&ds, "%s ", operation);
444     if (error) {
445         ds_put_format(&ds, "(%s) ", strerror(error));
446     }
447     flow_format(&ds, flow);
448     if (stats) {
449         ds_put_cstr(&ds, ", ");
450         format_odp_flow_stats(&ds, stats);
451     }
452     if (actions || n_actions) {
453         ds_put_cstr(&ds, ", actions:");
454         format_odp_actions(&ds, actions, n_actions);
455     }
456     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
457     ds_destroy(&ds);
458 }
459
460 static int
461 do_flow_ioctl(const struct dpif *dpif, int cmd, struct odp_flow *flow,
462               const char *operation, bool show_stats)
463 {
464     int error = do_ioctl(dpif, cmd, NULL, flow);
465     if (error && show_stats) {
466         flow->n_actions = 0;
467     }
468     if (should_log_flow_message(error)) {
469         log_flow_message(dpif, error, operation, &flow->key,
470                          show_stats && !error ? &flow->stats : NULL,
471                          flow->actions, flow->n_actions);
472     }
473     return error;
474 }
475
476 int
477 dpif_flow_put(struct dpif *dpif, struct odp_flow_put *put)
478 {
479     int error = do_ioctl(dpif, ODP_FLOW_PUT, NULL, put);
480     COVERAGE_INC(dpif_flow_put);
481     if (should_log_flow_message(error)) {
482         struct ds operation = DS_EMPTY_INITIALIZER;
483         ds_put_cstr(&operation, "put");
484         if (put->flags & ODPPF_CREATE) {
485             ds_put_cstr(&operation, "[create]");
486         }
487         if (put->flags & ODPPF_MODIFY) {
488             ds_put_cstr(&operation, "[modify]");
489         }
490         if (put->flags & ODPPF_ZERO_STATS) {
491             ds_put_cstr(&operation, "[zero]");
492         }
493 #define ODPPF_ALL (ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS)
494         if (put->flags & ~ODPPF_ALL) {
495             ds_put_format(&operation, "[%x]", put->flags & ~ODPPF_ALL);
496         }
497         log_flow_message(dpif, error, ds_cstr(&operation), &put->flow.key,
498                          !error ? &put->flow.stats : NULL,
499                          put->flow.actions, put->flow.n_actions);
500         ds_destroy(&operation);
501     }
502     return error;
503 }
504
505 int
506 dpif_flow_del(struct dpif *dpif, struct odp_flow *flow)
507 {
508     COVERAGE_INC(dpif_flow_del);
509     check_rw_odp_flow(flow);
510     memset(&flow->stats, 0, sizeof flow->stats);
511     return do_flow_ioctl(dpif, ODP_FLOW_DEL, flow, "delete flow", true);
512 }
513
514 int
515 dpif_flow_get(const struct dpif *dpif, struct odp_flow *flow)
516 {
517     COVERAGE_INC(dpif_flow_query);
518     check_rw_odp_flow(flow);
519     memset(&flow->stats, 0, sizeof flow->stats);
520     return do_flow_ioctl(dpif, ODP_FLOW_GET, flow, "get flow", true);
521 }
522
523 int
524 dpif_flow_get_multiple(const struct dpif *dpif,
525                        struct odp_flow flows[], size_t n)
526 {
527     struct odp_flowvec fv;
528     size_t i;
529
530     COVERAGE_ADD(dpif_flow_query_multiple, n);
531     fv.flows = flows;
532     fv.n_flows = n;
533     for (i = 0; i < n; i++) {
534         check_rw_odp_flow(&flows[i]);
535     }
536     return do_ioctl(dpif, ODP_FLOW_GET_MULTIPLE, "ODP_FLOW_GET_MULTIPLE",
537                     &fv);
538 }
539
540 int
541 dpif_flow_list(const struct dpif *dpif, struct odp_flow flows[], size_t n,
542                size_t *n_out)
543 {
544     struct odp_flowvec fv;
545     uint32_t i;
546     int error;
547
548     COVERAGE_INC(dpif_flow_query_list);
549     fv.flows = flows;
550     fv.n_flows = n;
551     if (RUNNING_ON_VALGRIND) {
552         memset(flows, 0, n * sizeof *flows);
553     } else {
554         for (i = 0; i < n; i++) {
555             flows[i].actions = NULL;
556             flows[i].n_actions = 0;
557         }
558     }
559     error = do_ioctl(dpif, ODP_FLOW_LIST, NULL, &fv);
560     if (error) {
561         *n_out = 0;
562         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
563                      dpif_name(dpif), strerror(error));
564     } else {
565         COVERAGE_ADD(dpif_flow_query_list_n, fv.n_flows);
566         *n_out = fv.n_flows;
567         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows",
568                     dpif_name(dpif), *n_out);
569     }
570     return error;
571 }
572
573 int
574 dpif_flow_list_all(const struct dpif *dpif,
575                    struct odp_flow **flowsp, size_t *np)
576 {
577     struct odp_stats stats;
578     struct odp_flow *flows;
579     size_t n_flows;
580     int error;
581
582     *flowsp = NULL;
583     *np = 0;
584
585     error = dpif_get_dp_stats(dpif, &stats);
586     if (error) {
587         return error;
588     }
589
590     flows = xmalloc(sizeof *flows * stats.n_flows);
591     error = dpif_flow_list(dpif, flows, stats.n_flows, &n_flows);
592     if (error) {
593         free(flows);
594         return error;
595     }
596
597     if (stats.n_flows != n_flows) {
598         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
599                      "flows but flow listing reported %zu",
600                      dpif_name(dpif), stats.n_flows, n_flows);
601     }
602     *flowsp = flows;
603     *np = n_flows;
604     return 0;
605 }
606
607 int
608 dpif_execute(struct dpif *dpif, uint16_t in_port,
609              const union odp_action actions[], size_t n_actions,
610              const struct ofpbuf *buf)
611 {
612     int error;
613
614     COVERAGE_INC(dpif_execute);
615     if (n_actions > 0) {
616         struct odp_execute execute;
617         memset(&execute, 0, sizeof execute);
618         execute.in_port = in_port;
619         execute.actions = (union odp_action *) actions;
620         execute.n_actions = n_actions;
621         execute.data = buf->data;
622         execute.length = buf->size;
623         error = do_ioctl(dpif, ODP_EXECUTE, NULL, &execute);
624     } else {
625         error = 0;
626     }
627
628     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
629         struct ds ds = DS_EMPTY_INITIALIZER;
630         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
631         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
632         format_odp_actions(&ds, actions, n_actions);
633         if (error) {
634             ds_put_format(&ds, " failed (%s)", strerror(error));
635         }
636         ds_put_format(&ds, " on packet %s", packet);
637         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
638         ds_destroy(&ds);
639         free(packet);
640     }
641     return error;
642 }
643
644 int
645 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
646 {
647     int error = do_ioctl(dpif, ODP_GET_LISTEN_MASK, "ODP_GET_LISTEN_MASK",
648                          listen_mask);
649     if (error) {
650         *listen_mask = 0;
651     }
652     return error;
653 }
654
655 int
656 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
657 {
658     return do_ioctl(dpif, ODP_SET_LISTEN_MASK, "ODP_SET_LISTEN_MASK",
659                     &listen_mask);
660 }
661
662 int
663 dpif_recv(struct dpif *dpif, struct ofpbuf **bufp)
664 {
665     struct ofpbuf *buf;
666     int retval;
667     int error;
668
669     buf = ofpbuf_new(65536);
670     retval = read(dpif->fd, ofpbuf_tail(buf), ofpbuf_tailroom(buf));
671     if (retval < 0) {
672         error = errno;
673         if (error != EAGAIN) {
674             VLOG_WARN_RL(&error_rl, "%s: read failed: %s",
675                          dpif_name(dpif), strerror(error));
676         }
677     } else if (retval >= sizeof(struct odp_msg)) {
678         struct odp_msg *msg = buf->data;
679         if (msg->length <= retval) {
680             buf->size += retval;
681             if (VLOG_IS_DBG_ENABLED()) {
682                 void *payload = msg + 1;
683                 size_t length = buf->size - sizeof *msg;
684                 char *s = ofp_packet_to_string(payload, length, length);
685                 VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
686                             "%zu on port %"PRIu16": %s", dpif_name(dpif),
687                             (msg->type == _ODPL_MISS_NR ? "miss"
688                              : msg->type == _ODPL_ACTION_NR ? "action"
689                              : "<unknown>"),
690                             msg->length - sizeof(struct odp_msg),
691                             msg->port, s);
692                 free(s);
693             }
694             *bufp = buf;
695             COVERAGE_INC(dpif_recv);
696             return 0;
697         } else {
698             VLOG_WARN_RL(&error_rl, "%s: discarding message truncated "
699                          "from %zu bytes to %d",
700                          dpif_name(dpif), msg->length, retval);
701             error = ERANGE;
702         }
703     } else if (!retval) {
704         VLOG_WARN_RL(&error_rl, "%s: unexpected end of file", dpif_name(dpif));
705         error = EPROTO;
706     } else {
707         VLOG_WARN_RL(&error_rl,
708                      "%s: discarding too-short message (%d bytes)",
709                      dpif_name(dpif), retval);
710         error = ERANGE;
711     }
712
713     *bufp = NULL;
714     ofpbuf_delete(buf);
715     return error;
716 }
717
718 void
719 dpif_recv_wait(struct dpif *dpif)
720 {
721     poll_fd_wait(dpif->fd, POLLIN);
722 }
723
724 void
725 dpif_get_netflow_ids(const struct dpif *dpif,
726                      uint8_t *engine_type, uint8_t *engine_id)
727 {
728     *engine_type = *engine_id = dpif->minor;
729 }
730 \f
731 struct dpifmon {
732     struct dpif *dpif;
733     struct nl_sock *sock;
734     int local_ifindex;
735 };
736
737 int
738 dpifmon_create(const char *datapath_name, struct dpifmon **monp)
739 {
740     struct dpifmon *mon;
741     char local_name[IFNAMSIZ];
742     int error;
743
744     mon = *monp = xmalloc(sizeof *mon);
745
746     error = dpif_open(datapath_name, &mon->dpif);
747     if (error) {
748         goto error;
749     }
750     error = dpif_port_get_name(mon->dpif, ODPP_LOCAL,
751                                local_name, sizeof local_name);
752     if (error) {
753         goto error_close_dpif;
754     }
755
756     mon->local_ifindex = if_nametoindex(local_name);
757     if (!mon->local_ifindex) {
758         error = errno;
759         VLOG_WARN("could not get ifindex of %s device: %s",
760                   local_name, strerror(errno));
761         goto error_close_dpif;
762     }
763
764     error = nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &mon->sock);
765     if (error) {
766         VLOG_WARN("could not create rtnetlink socket: %s", strerror(error));
767         goto error_close_dpif;
768     }
769
770     return 0;
771
772 error_close_dpif:
773     dpif_close(mon->dpif);
774 error:
775     free(mon);
776     *monp = NULL;
777     return error;
778 }
779
780 void
781 dpifmon_destroy(struct dpifmon *mon)
782 {
783     if (mon) {
784         dpif_close(mon->dpif);
785         nl_sock_destroy(mon->sock);
786     }
787 }
788
789 int
790 dpifmon_poll(struct dpifmon *mon, char **devnamep)
791 {
792     static struct vlog_rate_limit slow_rl = VLOG_RATE_LIMIT_INIT(1, 5);
793     static const struct nl_policy rtnlgrp_link_policy[] = {
794         [IFLA_IFNAME] = { .type = NL_A_STRING },
795         [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
796     };
797     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
798     struct ofpbuf *buf;
799     int error;
800
801     *devnamep = NULL;
802 again:
803     error = nl_sock_recv(mon->sock, &buf, false);
804     switch (error) {
805     case 0:
806         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
807                              rtnlgrp_link_policy,
808                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
809             VLOG_WARN_RL(&slow_rl, "received bad rtnl message");
810             error = ENOBUFS;
811         } else {
812             const char *devname = nl_attr_get_string(attrs[IFLA_IFNAME]);
813             bool for_us;
814
815             if (attrs[IFLA_MASTER]) {
816                 uint32_t master_ifindex = nl_attr_get_u32(attrs[IFLA_MASTER]);
817                 for_us = master_ifindex == mon->local_ifindex;
818             } else {
819                 /* It's for us if that device is one of our ports. */
820                 struct odp_port port;
821                 for_us = !dpif_port_query_by_name(mon->dpif, devname, &port);
822             }
823
824             if (!for_us) {
825                 /* Not for us, try again. */
826                 ofpbuf_delete(buf);
827                 COVERAGE_INC(dpifmon_poll_false_wakeup);
828                 goto again;
829             }
830             COVERAGE_INC(dpifmon_poll_changed);
831             *devnamep = xstrdup(devname);
832         }
833         ofpbuf_delete(buf);
834         break;
835
836     case EAGAIN:
837         /* Nothing to do. */
838         break;
839
840     case ENOBUFS:
841         VLOG_WARN_RL(&slow_rl, "dpifmon socket overflowed");
842         break;
843
844     default:
845         VLOG_WARN_RL(&slow_rl, "error on dpifmon socket: %s", strerror(error));
846         break;
847     }
848     return error;
849 }
850
851 void
852 dpifmon_run(struct dpifmon *mon UNUSED)
853 {
854     /* Nothing to do in this implementation. */
855 }
856
857 void
858 dpifmon_wait(struct dpifmon *mon)
859 {
860     nl_sock_wait(mon->sock, POLLIN);
861 }
862 \f
863 static int get_openvswitch_major(void);
864 static int get_major(const char *target, int default_major);
865
866 static int
867 lookup_minor(const char *name, unsigned int *minor)
868 {
869     struct ethtool_drvinfo drvinfo;
870     struct ifreq ifr;
871     int error;
872     int sock;
873
874     *minor = -1;
875     sock = socket(AF_INET, SOCK_DGRAM, 0);
876     if (sock < 0) {
877         VLOG_WARN("socket(AF_INET) failed: %s", strerror(errno));
878         error = errno;
879         goto error;
880     }
881
882     memset(&ifr, 0, sizeof ifr);
883     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
884     ifr.ifr_data = (caddr_t) &drvinfo;
885
886     memset(&drvinfo, 0, sizeof drvinfo);
887     drvinfo.cmd = ETHTOOL_GDRVINFO;
888     if (ioctl(sock, SIOCETHTOOL, &ifr)) {
889         VLOG_WARN("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
890         error = errno;
891         goto error_close_sock;
892     }
893
894     if (strcmp(drvinfo.driver, "openvswitch")) {
895         VLOG_WARN("%s is not an openvswitch device", name);
896         error = EOPNOTSUPP;
897         goto error_close_sock;
898     }
899
900     if (!isdigit(drvinfo.bus_info[0])) {
901         VLOG_WARN("%s ethtool info does not contain an openvswitch minor",
902                   name);
903         error = EPROTOTYPE;
904         goto error_close_sock;
905     }
906
907     *minor = atoi(drvinfo.bus_info);
908     close(sock);
909     return 0;
910
911 error_close_sock:
912     close(sock);
913 error:
914     return error;
915 }
916
917 static int
918 make_openvswitch_device(unsigned int minor, char **fnp)
919 {
920     dev_t dev = makedev(get_openvswitch_major(), minor);
921     const char dirname[] = "/dev/net";
922     struct stat s;
923     char fn[128];
924
925     *fnp = NULL;
926     sprintf(fn, "%s/dp%d", dirname, minor);
927     if (!stat(fn, &s)) {
928         if (!S_ISCHR(s.st_mode)) {
929             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
930                          fn);
931         } else if (s.st_rdev != dev) {
932             VLOG_WARN_RL(&error_rl,
933                          "%s is device %u:%u instead of %u:%u, fixing",
934                          fn, major(s.st_rdev), minor(s.st_rdev),
935                          major(dev), minor(dev));
936         } else {
937             goto success;
938         }
939         if (unlink(fn)) {
940             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
941                          fn, strerror(errno));
942             return errno;
943         }
944     } else if (errno == ENOENT) {
945         if (stat(dirname, &s)) {
946             if (errno == ENOENT) {
947                 if (mkdir(dirname, 0755)) {
948                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
949                                  dirname, strerror(errno));
950                     return errno;
951                 }
952             } else {
953                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
954                              dirname, strerror(errno));
955                 return errno;
956             }
957         }
958     } else {
959         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
960         return errno;
961     }
962
963     /* The device needs to be created. */
964     if (mknod(fn, S_IFCHR | 0700, dev)) {
965         VLOG_WARN_RL(&error_rl,
966                      "%s: creating character device %u:%u failed (%s)",
967                      fn, major(dev), minor(dev), strerror(errno));
968         return errno;
969     }
970
971 success:
972     *fnp = xstrdup(fn);
973     return 0;
974 }
975
976
977 static int
978 get_openvswitch_major(void)
979 {
980     static unsigned int openvswitch_major;
981     if (!openvswitch_major) {
982         enum { DEFAULT_MAJOR = 248 };
983         openvswitch_major = get_major("openvswitch", DEFAULT_MAJOR);
984     }
985     return openvswitch_major;
986 }
987
988 static int
989 get_major(const char *target, int default_major)
990 {
991     const char fn[] = "/proc/devices";
992     char line[128];
993     FILE *file;
994     int ln;
995
996     file = fopen(fn, "r");
997     if (!file) {
998         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
999         goto error;
1000     }
1001
1002     for (ln = 1; fgets(line, sizeof line, file); ln++) {
1003         char name[64];
1004         int major;
1005
1006         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
1007             /* Nothing to do. */
1008         } else if (!strncmp(line, "Block", 5)) {
1009             /* We only want character devices, so skip the rest of the file. */
1010             break;
1011         } else if (sscanf(line, "%d %63s", &major, name)) {
1012             if (!strcmp(name, target)) {
1013                 fclose(file);
1014                 return major;
1015             }
1016         } else {
1017             static bool warned;
1018             if (!warned) {
1019                 VLOG_WARN("%s:%d: syntax error", fn, ln);
1020             }
1021             warned = true;
1022         }
1023     }
1024
1025     VLOG_ERR("%s: %s major not found (is the module loaded?), using "
1026              "default major %d", fn, target, default_major);
1027 error:
1028     VLOG_INFO("using default major %d for %s", default_major, target);
1029     return default_major;
1030 }
1031
1032 static int
1033 name_to_minor(const char *name, unsigned int *minor)
1034 {
1035     if (!get_minor_from_name(name, minor)) {
1036         return 0;
1037     }
1038     return lookup_minor(name, minor);
1039 }
1040
1041 static int
1042 get_minor_from_name(const char *name, unsigned int *minor)
1043 {
1044     if (!strncmp(name, "dp", 2) && isdigit(name[2])) {
1045         *minor = atoi(name + 2);
1046         return 0;
1047     } else {
1048         return EINVAL;
1049     }
1050 }
1051
1052 static int
1053 open_by_minor(unsigned int minor, struct dpif **dpifp)
1054 {
1055     struct dpif *dpif;
1056     int error;
1057     char *fn;
1058     int fd;
1059
1060     *dpifp = NULL;
1061     error = make_openvswitch_device(minor, &fn);
1062     if (error) {
1063         return error;
1064     }
1065
1066     fd = open(fn, O_RDONLY | O_NONBLOCK);
1067     if (fd < 0) {
1068         error = errno;
1069         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
1070         free(fn);
1071         return error;
1072     }
1073     free(fn);
1074
1075     dpif = xmalloc(sizeof *dpif);
1076     dpif->name = xasprintf("dp%u", dpif->minor);
1077     dpif->minor = minor;
1078     dpif->fd = fd;
1079     *dpifp = dpif;
1080     return 0;
1081 }
1082 \f
1083 /* There is a tendency to construct odp_flow objects on the stack and to
1084  * forget to properly initialize their "actions" and "n_actions" members.
1085  * When this happens, we get memory corruption because the kernel
1086  * writes through the random pointer that is in the "actions" member.
1087  *
1088  * This function attempts to combat the problem by:
1089  *
1090  *      - Forcing a segfault if "actions" points to an invalid region (instead
1091  *        of just getting back EFAULT, which can be easily missed in the log).
1092  *
1093  *      - Storing a distinctive value that is likely to cause an
1094  *        easy-to-identify error later if it is dereferenced, etc.
1095  *
1096  *      - Triggering a warning on uninitialized memory from Valgrind if
1097  *        "actions" or "n_actions" was not initialized.
1098  */
1099 static void
1100 check_rw_odp_flow(struct odp_flow *flow)
1101 {
1102     if (flow->n_actions) {
1103         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
1104     }
1105 }