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