dpif: New function dpif_get_netflow_ids().
[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
684 void
685 dpif_get_netflow_ids(const struct dpif *dpif,
686                      uint8_t *engine_type, uint8_t *engine_id)
687 {
688     *engine_type = *engine_id = dpif->minor;
689 }
690 \f
691 struct dpifmon {
692     struct dpif dpif;
693     struct nl_sock *sock;
694     int local_ifindex;
695 };
696
697 int
698 dpifmon_create(const char *datapath_name, struct dpifmon **monp)
699 {
700     struct dpifmon *mon;
701     char local_name[IFNAMSIZ];
702     int error;
703
704     mon = *monp = xmalloc(sizeof *mon);
705
706     error = dpif_open(datapath_name, &mon->dpif);
707     if (error) {
708         goto error;
709     }
710     error = dpif_port_get_name(&mon->dpif, ODPP_LOCAL,
711                                local_name, sizeof local_name);
712     if (error) {
713         goto error_close_dpif;
714     }
715
716     mon->local_ifindex = if_nametoindex(local_name);
717     if (!mon->local_ifindex) {
718         error = errno;
719         VLOG_WARN("could not get ifindex of %s device: %s",
720                   local_name, strerror(errno));
721         goto error_close_dpif;
722     }
723
724     error = nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &mon->sock);
725     if (error) {
726         VLOG_WARN("could not create rtnetlink socket: %s", strerror(error));
727         goto error_close_dpif;
728     }
729
730     return 0;
731
732 error_close_dpif:
733     dpif_close(&mon->dpif);
734 error:
735     free(mon);
736     *monp = NULL;
737     return error;
738 }
739
740 void
741 dpifmon_destroy(struct dpifmon *mon)
742 {
743     if (mon) {
744         dpif_close(&mon->dpif);
745         nl_sock_destroy(mon->sock);
746     }
747 }
748
749 int
750 dpifmon_poll(struct dpifmon *mon, char **devnamep)
751 {
752     static struct vlog_rate_limit slow_rl = VLOG_RATE_LIMIT_INIT(1, 5);
753     static const struct nl_policy rtnlgrp_link_policy[] = {
754         [IFLA_IFNAME] = { .type = NL_A_STRING },
755         [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
756     };
757     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
758     struct ofpbuf *buf;
759     int error;
760
761     *devnamep = NULL;
762 again:
763     error = nl_sock_recv(mon->sock, &buf, false);
764     switch (error) {
765     case 0:
766         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
767                              rtnlgrp_link_policy,
768                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
769             VLOG_WARN_RL(&slow_rl, "received bad rtnl message");
770             error = ENOBUFS;
771         } else {
772             const char *devname = nl_attr_get_string(attrs[IFLA_IFNAME]);
773             bool for_us;
774
775             if (attrs[IFLA_MASTER]) {
776                 uint32_t master_ifindex = nl_attr_get_u32(attrs[IFLA_MASTER]);
777                 for_us = master_ifindex == mon->local_ifindex;
778             } else {
779                 /* It's for us if that device is one of our ports.  This is
780                  * open-coded instead of using dpif_port_query_by_name() to
781                  * avoid logging a warning on failure. */
782                 struct odp_port port;
783                 memset(&port, 0, sizeof port);
784                 strncpy(port.devname, devname, sizeof port.devname);
785                 for_us = !ioctl(mon->dpif.fd, ODP_PORT_QUERY, &port);
786             }
787
788             if (!for_us) {
789                 /* Not for us, try again. */
790                 ofpbuf_delete(buf);
791                 COVERAGE_INC(dpifmon_poll_false_wakeup);
792                 goto again;
793             }
794             COVERAGE_INC(dpifmon_poll_changed);
795             *devnamep = xstrdup(devname);
796         }
797         ofpbuf_delete(buf);
798         break;
799
800     case EAGAIN:
801         /* Nothing to do. */
802         break;
803
804     case ENOBUFS:
805         VLOG_WARN_RL(&slow_rl, "dpifmon socket overflowed");
806         break;
807
808     default:
809         VLOG_WARN_RL(&slow_rl, "error on dpifmon socket: %s", strerror(error));
810         break;
811     }
812     return error;
813 }
814
815 void
816 dpifmon_run(struct dpifmon *mon UNUSED)
817 {
818     /* Nothing to do in this implementation. */
819 }
820
821 void
822 dpifmon_wait(struct dpifmon *mon)
823 {
824     nl_sock_wait(mon->sock, POLLIN);
825 }
826 \f
827 static int get_openvswitch_major(void);
828 static int get_major(const char *target, int default_major);
829
830 static int
831 lookup_minor(const char *name, unsigned int *minor)
832 {
833     struct ethtool_drvinfo drvinfo;
834     struct ifreq ifr;
835     int error;
836     int sock;
837
838     *minor = -1;
839     sock = socket(AF_INET, SOCK_DGRAM, 0);
840     if (sock < 0) {
841         VLOG_WARN("socket(AF_INET) failed: %s", strerror(errno));
842         error = errno;
843         goto error;
844     }
845
846     memset(&ifr, 0, sizeof ifr);
847     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
848     ifr.ifr_data = (caddr_t) &drvinfo;
849
850     memset(&drvinfo, 0, sizeof drvinfo);
851     drvinfo.cmd = ETHTOOL_GDRVINFO;
852     if (ioctl(sock, SIOCETHTOOL, &ifr)) {
853         VLOG_WARN("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
854         error = errno;
855         goto error_close_sock;
856     }
857
858     if (strcmp(drvinfo.driver, "openvswitch")) {
859         VLOG_WARN("%s is not an openvswitch device", name);
860         error = EOPNOTSUPP;
861         goto error_close_sock;
862     }
863
864     if (!isdigit(drvinfo.bus_info[0])) {
865         VLOG_WARN("%s ethtool info does not contain an openvswitch minor",
866                   name);
867         error = EPROTOTYPE;
868         goto error_close_sock;
869     }
870
871     *minor = atoi(drvinfo.bus_info);
872     close(sock);
873     return 0;
874
875 error_close_sock:
876     close(sock);
877 error:
878     return error;
879 }
880
881 static int
882 make_openvswitch_device(unsigned int minor, char **fnp)
883 {
884     dev_t dev = makedev(get_openvswitch_major(), minor);
885     const char dirname[] = "/dev/net";
886     struct stat s;
887     char fn[128];
888
889     *fnp = NULL;
890     sprintf(fn, "%s/dp%d", dirname, minor);
891     if (!stat(fn, &s)) {
892         if (!S_ISCHR(s.st_mode)) {
893             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
894                          fn);
895         } else if (s.st_rdev != dev) {
896             VLOG_WARN_RL(&error_rl,
897                          "%s is device %u:%u instead of %u:%u, fixing",
898                          fn, major(s.st_rdev), minor(s.st_rdev),
899                          major(dev), minor(dev));
900         } else {
901             goto success;
902         }
903         if (unlink(fn)) {
904             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
905                          fn, strerror(errno));
906             return errno;
907         }
908     } else if (errno == ENOENT) {
909         if (stat(dirname, &s)) {
910             if (errno == ENOENT) {
911                 if (mkdir(dirname, 0755)) {
912                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
913                                  dirname, strerror(errno));
914                     return errno;
915                 }
916             } else {
917                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
918                              dirname, strerror(errno));
919                 return errno;
920             }
921         }
922     } else {
923         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
924         return errno;
925     }
926
927     /* The device needs to be created. */
928     if (mknod(fn, S_IFCHR | 0700, dev)) {
929         VLOG_WARN_RL(&error_rl,
930                      "%s: creating character device %u:%u failed (%s)",
931                      fn, major(dev), minor(dev), strerror(errno));
932         return errno;
933     }
934
935 success:
936     *fnp = xstrdup(fn);
937     return 0;
938 }
939
940
941 static int
942 get_openvswitch_major(void)
943 {
944     static unsigned int openvswitch_major;
945     if (!openvswitch_major) {
946         enum { DEFAULT_MAJOR = 248 };
947         openvswitch_major = get_major("openvswitch", DEFAULT_MAJOR);
948     }
949     return openvswitch_major;
950 }
951
952 static int
953 get_major(const char *target, int default_major)
954 {
955     const char fn[] = "/proc/devices";
956     char line[128];
957     FILE *file;
958     int ln;
959
960     file = fopen(fn, "r");
961     if (!file) {
962         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
963         goto error;
964     }
965
966     for (ln = 1; fgets(line, sizeof line, file); ln++) {
967         char name[64];
968         int major;
969
970         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
971             /* Nothing to do. */
972         } else if (!strncmp(line, "Block", 5)) {
973             /* We only want character devices, so skip the rest of the file. */
974             break;
975         } else if (sscanf(line, "%d %63s", &major, name)) {
976             if (!strcmp(name, target)) {
977                 fclose(file);
978                 return major;
979             }
980         } else {
981             static bool warned;
982             if (!warned) {
983                 VLOG_WARN("%s:%d: syntax error", fn, ln);
984             }
985             warned = true;
986         }
987     }
988
989     VLOG_ERR("%s: %s major not found (is the module loaded?), using "
990              "default major %d", fn, target, default_major);
991 error:
992     VLOG_INFO("using default major %d for %s", default_major, target);
993     return default_major;
994 }
995
996 static int
997 name_to_minor(const char *name, unsigned int *minor)
998 {
999     if (!get_minor_from_name(name, minor)) {
1000         return 0;
1001     }
1002     return lookup_minor(name, minor);
1003 }
1004
1005 static int
1006 get_minor_from_name(const char *name, unsigned int *minor)
1007 {
1008     if (!strncmp(name, "dp", 2) && isdigit(name[2])) {
1009         *minor = atoi(name + 2);
1010         return 0;
1011     } else if (!strncmp(name, "nl:", 3) && isdigit(name[3])) {
1012         /* This is for compatibility only and will be dropped. */
1013         *minor = atoi(name + 3);
1014         return 0;
1015     } else {
1016         return EINVAL;
1017     }
1018 }
1019
1020 static int
1021 open_by_minor(unsigned int minor, struct dpif *dpif)
1022 {
1023     int error;
1024     char *fn;
1025     int fd;
1026
1027     dpif->minor = -1;
1028     dpif->fd = -1;
1029     error = make_openvswitch_device(minor, &fn);
1030     if (error) {
1031         return error;
1032     }
1033
1034     fd = open(fn, O_RDONLY | O_NONBLOCK);
1035     if (fd < 0) {
1036         error = errno;
1037         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
1038         free(fn);
1039         return error;
1040     }
1041
1042     free(fn);
1043     dpif->minor = minor;
1044     dpif->fd = fd;
1045     return 0;
1046 }
1047 \f
1048 /* There is a tendency to construct odp_flow objects on the stack and to
1049  * forget to properly initialize their "actions" and "n_actions" members.
1050  * When this happens, we get memory corruption because the kernel
1051  * writes through the random pointer that is in the "actions" member.
1052  *
1053  * This function attempts to combat the problem by:
1054  *
1055  *      - Forcing a segfault if "actions" points to an invalid region (instead
1056  *        of just getting back EFAULT, which can be easily missed in the log).
1057  *
1058  *      - Storing a distinctive value that is likely to cause an
1059  *        easy-to-identify error later if it is dereferenced, etc.
1060  *
1061  *      - Triggering a warning on uninitialized memory from Valgrind if
1062  *        "actions" or "n_actions" was not initialized.
1063  */
1064 static void
1065 check_rw_odp_flow(struct odp_flow *flow)
1066 {
1067     if (flow->n_actions) {
1068         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
1069     }
1070 }