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