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