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