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