8c33736b0b20f96685c789aa3de3111dbe31fd68
[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-provider.h"
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "flow.h"
30 #include "netlink.h"
31 #include "odp-util.h"
32 #include "ofp-print.h"
33 #include "ofpbuf.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "util.h"
37 #include "valgrind.h"
38
39 #include "vlog.h"
40 #define THIS_MODULE VLM_dpif
41
42 static struct dpif_class *dpif_classes[] = {
43     &dpif_linux_class,
44 };
45 enum { N_DPIF_CLASSES = ARRAY_SIZE(dpif_classes) };
46
47 /* Rate limit for individual messages going to or from the datapath, output at
48  * DBG level.  This is very high because, if these are enabled, it is because
49  * we really need to see them. */
50 static struct vlog_rate_limit dpmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
51
52 /* Not really much point in logging many dpif errors. */
53 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
54
55 static void log_operation(const struct dpif *, const char *operation,
56                           int error);
57 static void log_flow_operation(const struct dpif *, const char *operation,
58                                int error, struct odp_flow *flow);
59 static void log_flow_put(struct dpif *, int error,
60                          const struct odp_flow_put *);
61 static bool should_log_flow_message(int error);
62 static void check_rw_odp_flow(struct odp_flow *);
63
64 /* Performs periodic work needed by all the various kinds of dpifs.
65  *
66  * If your program opens any dpifs, it must call this function within its main
67  * poll loop. */
68 void
69 dp_run(void)
70 {
71     int i;
72     for (i = 0; i < N_DPIF_CLASSES; i++) {
73         const struct dpif_class *class = dpif_classes[i];
74         if (class->run) {
75             class->run();
76         }
77     }
78 }
79
80 /* Arranges for poll_block() to wake up when dp_run() needs to be called.
81  *
82  * If your program opens any dpifs, it must call this function within its main
83  * poll loop. */
84 void
85 dp_wait(void)
86 {
87     int i;
88     for (i = 0; i < N_DPIF_CLASSES; i++) {
89         const struct dpif_class *class = dpif_classes[i];
90         if (class->wait) {
91             class->wait();
92         }
93     }
94 }
95
96 static int
97 do_open(const char *name_, bool create, struct dpif **dpifp)
98 {
99     char *name = xstrdup(name_);
100     char *prefix, *suffix, *colon;
101     struct dpif *dpif = NULL;
102     int error;
103     int i;
104
105     colon = strchr(name, ':');
106     if (colon) {
107         *colon = '\0';
108         prefix = name;
109         suffix = colon + 1;
110     } else {
111         prefix = "";
112         suffix = name;
113     }
114
115     for (i = 0; i < N_DPIF_CLASSES; i++) {
116         const struct dpif_class *class = dpif_classes[i];
117         if (!strcmp(prefix, class->prefix)) {
118             error = class->open(name_, suffix, create, &dpif);
119             goto exit;
120         }
121     }
122     error = EAFNOSUPPORT;
123
124 exit:
125     *dpifp = error ? NULL : dpif;
126     return error;
127 }
128
129 /* Tries to open an existing datapath named 'name'.  Will fail if no datapath
130  * named 'name' exists.  Returns 0 if successful, otherwise a positive errno
131  * value.  On success stores a pointer to the datapath in '*dpifp', otherwise a
132  * null pointer. */
133 int
134 dpif_open(const char *name, struct dpif **dpifp)
135 {
136     return do_open(name, false, dpifp);
137 }
138
139 /* Tries to create and open a new datapath with the given 'name'.  Will fail if
140  * a datapath named 'name' already exists.  Returns 0 if successful, otherwise
141  * a positive errno value.  On success stores a pointer to the datapath in
142  * '*dpifp', otherwise a null pointer.*/
143 int
144 dpif_create(const char *name, struct dpif **dpifp)
145 {
146     return do_open(name, true, dpifp);
147 }
148
149 /* Closes and frees the connection to 'dpif'.  Does not destroy the datapath
150  * itself; call dpif_delete() first, instead, if that is desirable. */
151 void
152 dpif_close(struct dpif *dpif)
153 {
154     if (dpif) {
155         char *name = dpif->name;
156         dpif->class->close(dpif);
157         free(name);
158     }
159 }
160
161 /* Returns the name of datapath 'dpif' (for use in log messages). */
162 const char *
163 dpif_name(const struct dpif *dpif)
164 {
165     return dpif->name;
166 }
167
168 /* Destroys the datapath that 'dpif' is connected to, first removing all of its
169  * ports.  After calling this function, it does not make sense to pass 'dpif'
170  * to any functions other than dpif_name() or dpif_close(). */
171 int
172 dpif_delete(struct dpif *dpif)
173 {
174     int error;
175
176     COVERAGE_INC(dpif_destroy);
177
178     error = dpif->class->delete(dpif);
179     log_operation(dpif, "delete", error);
180     return error;
181 }
182
183 /* Retrieves statistics for 'dpif' into 'stats'.  Returns 0 if successful,
184  * otherwise a positive errno value. */
185 int
186 dpif_get_dp_stats(const struct dpif *dpif, struct odp_stats *stats)
187 {
188     int error = dpif->class->get_stats(dpif, stats);
189     if (error) {
190         memset(stats, 0, sizeof *stats);
191     }
192     log_operation(dpif, "get_stats", error);
193     return error;
194 }
195
196 /* Retrieves the current IP fragment handling policy for 'dpif' into
197  * '*drop_frags': true indicates that fragments are dropped, false indicates
198  * that fragments are treated in the same way as other IP packets (except that
199  * the L4 header cannot be read).  Returns 0 if successful, otherwise a
200  * positive errno value. */
201 int
202 dpif_get_drop_frags(const struct dpif *dpif, bool *drop_frags)
203 {
204     int error = dpif->class->get_drop_frags(dpif, drop_frags);
205     if (error) {
206         *drop_frags = false;
207     }
208     log_operation(dpif, "get_drop_frags", error);
209     return error;
210 }
211
212 /* Changes 'dpif''s treatment of IP fragments to 'drop_frags', whose meaning is
213  * the same as for the get_drop_frags member function.  Returns 0 if
214  * successful, otherwise a positive errno value. */
215 int
216 dpif_set_drop_frags(struct dpif *dpif, bool drop_frags)
217 {
218     int error = dpif->class->set_drop_frags(dpif, drop_frags);
219     log_operation(dpif, "set_drop_frags", error);
220     return error;
221 }
222
223 /* Attempts to add 'devname' as a port on 'dpif', given the combination of
224  * ODP_PORT_* flags in 'flags'.  If successful, returns 0 and sets '*port_nop'
225  * to the new port's port number (if 'port_nop' is non-null).  On failure,
226  * returns a positive errno value and sets '*port_nop' to UINT16_MAX (if
227  * 'port_nop' is non-null). */
228 int
229 dpif_port_add(struct dpif *dpif, const char *devname, uint16_t flags,
230               uint16_t *port_nop)
231 {
232     uint16_t port_no;
233     int error;
234
235     COVERAGE_INC(dpif_port_add);
236
237     error = dpif->class->port_add(dpif, devname, flags, &port_no);
238     if (!error) {
239         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
240                     dpif_name(dpif), devname, port_no);
241     } else {
242         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
243                      dpif_name(dpif), devname, strerror(error));
244         port_no = UINT16_MAX;
245     }
246     if (port_nop) {
247         *port_nop = port_no;
248     }
249     return error;
250 }
251
252 /* Attempts to remove 'dpif''s port number 'port_no'.  Returns 0 if successful,
253  * otherwise a positive errno value. */
254 int
255 dpif_port_del(struct dpif *dpif, uint16_t port_no)
256 {
257     int error;
258
259     COVERAGE_INC(dpif_port_del);
260
261     error = dpif->class->port_del(dpif, port_no);
262     log_operation(dpif, "port_del", error);
263     return error;
264 }
265
266 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and
267  * initializes '*port' appropriately; on failure, returns a positive errno
268  * value. */
269 int
270 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
271                           struct odp_port *port)
272 {
273     int error = dpif->class->port_query_by_number(dpif, port_no, port);
274     if (!error) {
275         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
276                     dpif_name(dpif), port_no, port->devname);
277     } else {
278         memset(port, 0, sizeof *port);
279         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
280                      dpif_name(dpif), port_no, strerror(error));
281     }
282     return error;
283 }
284
285 /* Looks up port named 'devname' in 'dpif'.  On success, returns 0 and
286  * initializes '*port' appropriately; on failure, returns a positive errno
287  * value. */
288 int
289 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
290                         struct odp_port *port)
291 {
292     int error = dpif->class->port_query_by_name(dpif, devname, port);
293     if (!error) {
294         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
295                     dpif_name(dpif), devname, port->port);
296     } else {
297         memset(port, 0, sizeof *port);
298
299         /* Log level is DBG here because all the current callers are interested
300          * in whether 'dpif' actually has a port 'devname', so that it's not an
301          * issue worth logging if it doesn't. */
302         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
303                     dpif_name(dpif), devname, strerror(error));
304     }
305     return error;
306 }
307
308 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and copies
309  * the port's name into the 'name_size' bytes in 'name', ensuring that the
310  * result is null-terminated.  On failure, returns a positive errno value and
311  * makes 'name' the empty string. */
312 int
313 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
314                    char *name, size_t name_size)
315 {
316     struct odp_port port;
317     int error;
318
319     assert(name_size > 0);
320
321     error = dpif_port_query_by_number(dpif, port_no, &port);
322     if (!error) {
323         ovs_strlcpy(name, port.devname, name_size);
324     } else {
325         *name = '\0';
326     }
327     return error;
328 }
329
330 /* Obtains a list of all the ports in 'dpif'.
331  *
332  * If successful, returns 0 and sets '*portsp' to point to an array of
333  * appropriately initialized port structures and '*n_portsp' to the number of
334  * ports in the array.  The caller is responsible for freeing '*portp' by
335  * calling free().
336  *
337  * On failure, returns a positive errno value and sets '*portsp' to NULL and
338  * '*n_portsp' to 0. */
339 int
340 dpif_port_list(const struct dpif *dpif,
341                struct odp_port **portsp, size_t *n_portsp)
342 {
343     struct odp_port *ports;
344     size_t n_ports;
345     int error;
346
347     for (;;) {
348         struct odp_stats stats;
349         int retval;
350
351         error = dpif_get_dp_stats(dpif, &stats);
352         if (error) {
353             goto exit;
354         }
355
356         ports = xcalloc(stats.n_ports, sizeof *ports);
357         retval = dpif->class->port_list(dpif, ports, stats.n_ports);
358         if (retval < 0) {
359             /* Hard error. */
360             error = -retval;
361             free(ports);
362             goto exit;
363         } else if (retval <= stats.n_ports) {
364             /* Success. */
365             error = 0;
366             n_ports = retval;
367             goto exit;
368         } else {
369             /* Soft error: port count increased behind our back.  Try again. */
370             free(ports);
371         }
372     }
373
374 exit:
375     if (error) {
376         *portsp = NULL;
377         *n_portsp = 0;
378     } else {
379         *portsp = ports;
380         *n_portsp = n_ports;
381     }
382     log_operation(dpif, "port_list", error);
383     return error;
384 }
385
386 /* Retrieves a list of the port numbers in port group 'group' in 'dpif'.
387  *
388  * On success, returns 0 and points '*ports' to a newly allocated array of
389  * integers, each of which is a 'dpif' port number for a port in
390  * 'group'.  Stores the number of elements in the array in '*n_ports'.  The
391  * caller is responsible for freeing '*ports' by calling free().
392  *
393  * On failure, returns a positive errno value and sets '*ports' to NULL and
394  * '*n_ports' to 0. */
395 int
396 dpif_port_group_get(const struct dpif *dpif, uint16_t group,
397                     uint16_t **ports, size_t *n_ports)
398 {
399     int error;
400
401     *ports = NULL;
402     *n_ports = 0;
403     for (;;) {
404         int retval = dpif->class->port_group_get(dpif, group,
405                                                  *ports, *n_ports);
406         if (retval < 0) {
407             /* Hard error. */
408             error = -retval;
409             free(*ports);
410             *ports = NULL;
411             *n_ports = 0;
412             break;
413         } else if (retval <= *n_ports) {
414             /* Success. */
415             error = 0;
416             *n_ports = retval;
417             break;
418         } else {
419             /* Soft error: there were more ports than we expected in the
420              * group.  Try again. */
421             free(*ports);
422             *ports = xcalloc(retval, sizeof **ports);
423             *n_ports = retval;
424         }
425     }
426     log_operation(dpif, "port_group_get", error);
427     return error;
428 }
429
430 /* Updates port group 'group' in 'dpif', making it contain the 'n_ports' ports
431  * whose 'dpif' port numbers are given in 'n_ports'.  Returns 0 if
432  * successful, otherwise a positive errno value.
433  *
434  * Behavior is undefined if the values in ports[] are not unique. */
435 int
436 dpif_port_group_set(struct dpif *dpif, uint16_t group,
437                     const uint16_t ports[], size_t n_ports)
438 {
439     int error;
440
441     COVERAGE_INC(dpif_port_group_set);
442
443     error = dpif->class->port_group_set(dpif, group, ports, n_ports);
444     log_operation(dpif, "port_group_set", error);
445     return error;
446 }
447
448 /* Deletes all flows from 'dpif'.  Returns 0 if successful, otherwise a
449  * positive errno value.  */
450 int
451 dpif_flow_flush(struct dpif *dpif)
452 {
453     int error;
454
455     COVERAGE_INC(dpif_flow_flush);
456
457     error = dpif->class->flow_flush(dpif);
458     log_operation(dpif, "flow_flush", error);
459     return error;
460 }
461
462 /* Queries 'dpif' for a flow entry matching 'flow->key'.
463  *
464  * If a flow matching 'flow->key' exists in 'dpif', stores statistics for the
465  * flow into 'flow->stats'.  If 'flow->n_actions' is zero, then 'flow->actions'
466  * is ignored.  If 'flow->n_actions' is nonzero, then 'flow->actions' should
467  * point to an array of the specified number of actions.  At most that many of
468  * the flow's actions will be copied into that array.  'flow->n_actions' will
469  * be updated to the number of actions actually present in the flow, which may
470  * be greater than the number stored if the flow has more actions than space
471  * available in the array.
472  *
473  * If no flow matching 'flow->key' exists in 'dpif', returns ENOENT.  On other
474  * failure, returns a positive errno value. */
475 int
476 dpif_flow_get(const struct dpif *dpif, struct odp_flow *flow)
477 {
478     int error;
479
480     COVERAGE_INC(dpif_flow_get);
481
482     check_rw_odp_flow(flow);
483     error = dpif->class->flow_get(dpif, flow, 1);
484     if (!error) {
485         error = flow->stats.error;
486     }
487     if (should_log_flow_message(error)) {
488         log_flow_operation(dpif, "flow_get", error, flow);
489     }
490     return error;
491 }
492
493 /* For each flow 'flow' in the 'n' flows in 'flows':
494  *
495  * - If a flow matching 'flow->key' exists in 'dpif':
496  *
497  *     Stores 0 into 'flow->stats.error' and stores statistics for the flow
498  *     into 'flow->stats'.
499  *
500  *     If 'flow->n_actions' is zero, then 'flow->actions' is ignored.  If
501  *     'flow->n_actions' is nonzero, then 'flow->actions' should point to an
502  *     array of the specified number of actions.  At most that many of the
503  *     flow's actions will be copied into that array.  'flow->n_actions' will
504  *     be updated to the number of actions actually present in the flow, which
505  *     may be greater than the number stored if the flow has more actions than
506  *     space available in the array.
507  *
508  * - Flow-specific errors are indicated by a positive errno value in
509  *   'flow->stats.error'.  In particular, ENOENT indicates that no flow
510  *   matching 'flow->key' exists in 'dpif'.  When an error value is stored, the
511  *   contents of 'flow->key' are preserved but other members of 'flow' should
512  *   be treated as indeterminate.
513  *
514  * Returns 0 if all 'n' flows in 'flows' were updated (whether they were
515  * individually successful or not is indicated by 'flow->stats.error',
516  * however).  Returns a positive errno value if an error that prevented this
517  * update occurred, in which the caller must not depend on any elements in
518  * 'flows' being updated or not updated.
519  */
520 int
521 dpif_flow_get_multiple(const struct dpif *dpif,
522                        struct odp_flow flows[], size_t n)
523 {
524     int error;
525     size_t i;
526
527     COVERAGE_ADD(dpif_flow_get, n);
528
529     for (i = 0; i < n; i++) {
530         check_rw_odp_flow(&flows[i]);
531     }
532
533     error = dpif->class->flow_get(dpif, flows, n);
534     log_operation(dpif, "flow_get_multiple", error);
535     return error;
536 }
537
538 /* Adds or modifies a flow in 'dpif' as specified in 'put':
539  *
540  * - If the flow specified in 'put->flow' does not exist in 'dpif', then
541  *   behavior depends on whether ODPPF_CREATE is specified in 'put->flags': if
542  *   it is, the flow will be added, otherwise the operation will fail with
543  *   ENOENT.
544  *
545  * - Otherwise, the flow specified in 'put->flow' does exist in 'dpif'.
546  *   Behavior in this case depends on whether ODPPF_MODIFY is specified in
547  *   'put->flags': if it is, the flow's actions will be updated, otherwise the
548  *   operation will fail with EEXIST.  If the flow's actions are updated, then
549  *   its statistics will be zeroed if ODPPF_ZERO_STATS is set in 'put->flags',
550  *   left as-is otherwise.
551  *
552  * Returns 0 if successful, otherwise a positive errno value.
553  */
554 int
555 dpif_flow_put(struct dpif *dpif, struct odp_flow_put *put)
556 {
557     int error;
558
559     COVERAGE_INC(dpif_flow_put);
560
561     error = dpif->class->flow_put(dpif, put);
562     if (should_log_flow_message(error)) {
563         log_flow_put(dpif, error, put);
564     }
565     return error;
566 }
567
568 /* Deletes a flow matching 'flow->key' from 'dpif' or returns ENOENT if 'dpif'
569  * does not contain such a flow.
570  *
571  * If successful, updates 'flow->stats', 'flow->n_actions', and 'flow->actions'
572  * as described for dpif_flow_get(). */
573 int
574 dpif_flow_del(struct dpif *dpif, struct odp_flow *flow)
575 {
576     int error;
577
578     COVERAGE_INC(dpif_flow_del);
579
580     check_rw_odp_flow(flow);
581     memset(&flow->stats, 0, sizeof flow->stats);
582
583     error = dpif->class->flow_del(dpif, flow);
584     if (should_log_flow_message(error)) {
585         log_flow_operation(dpif, "delete flow", error, flow);
586     }
587     return error;
588 }
589
590 /* Stores up to 'n' flows in 'dpif' into 'flows', including their statistics
591  * but not including any information about their actions.  If successful,
592  * returns 0 and sets '*n_out' to the number of flows actually present in
593  * 'dpif', which might be greater than the number stored (if 'dpif' has more
594  * than 'n' flows).  On failure, returns a negative errno value and sets
595  * '*n_out' to 0. */
596 int
597 dpif_flow_list(const struct dpif *dpif, struct odp_flow flows[], size_t n,
598                size_t *n_out)
599 {
600     uint32_t i;
601     int retval;
602
603     COVERAGE_INC(dpif_flow_query_list);
604     if (RUNNING_ON_VALGRIND) {
605         memset(flows, 0, n * sizeof *flows);
606     } else {
607         for (i = 0; i < n; i++) {
608             flows[i].actions = NULL;
609             flows[i].n_actions = 0;
610         }
611     }
612     retval = dpif->class->flow_list(dpif, flows, n);
613     if (retval < 0) {
614         *n_out = 0;
615         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
616                      dpif_name(dpif), strerror(-retval));
617         return -retval;
618     } else {
619         COVERAGE_ADD(dpif_flow_query_list_n, retval);
620         *n_out = MIN(n, retval);
621         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows (of %d)",
622                     dpif_name(dpif), *n_out, retval);
623         return 0;
624     }
625 }
626
627 /* Retrieves all of the flows in 'dpif'.
628  *
629  * If successful, returns 0 and stores in '*flowsp' a pointer to a newly
630  * allocated array of flows, including their statistics but not including any
631  * information about their actions, and sets '*np' to the number of flows in
632  * '*flowsp'.  The caller is responsible for freeing '*flowsp' by calling
633  * free().
634  *
635  * On failure, returns a positive errno value and sets '*flowsp' to NULL and
636  * '*np' to 0. */
637 int
638 dpif_flow_list_all(const struct dpif *dpif,
639                    struct odp_flow **flowsp, size_t *np)
640 {
641     struct odp_stats stats;
642     struct odp_flow *flows;
643     size_t n_flows;
644     int error;
645
646     *flowsp = NULL;
647     *np = 0;
648
649     error = dpif_get_dp_stats(dpif, &stats);
650     if (error) {
651         return error;
652     }
653
654     flows = xmalloc(sizeof *flows * stats.n_flows);
655     error = dpif_flow_list(dpif, flows, stats.n_flows, &n_flows);
656     if (error) {
657         free(flows);
658         return error;
659     }
660
661     if (stats.n_flows != n_flows) {
662         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
663                      "flows but flow listing reported %zu",
664                      dpif_name(dpif), stats.n_flows, n_flows);
665     }
666     *flowsp = flows;
667     *np = n_flows;
668     return 0;
669 }
670
671 /* Causes 'dpif' to perform the 'n_actions' actions in 'actions' on the
672  * Ethernet frame specified in 'packet'.
673  *
674  * Pretends that the frame was originally received on the port numbered
675  * 'in_port'.  This affects only ODPAT_OUTPUT_GROUP actions, which will not
676  * send a packet out their input port.  Specify the number of an unused port
677  * (e.g. UINT16_MAX is currently always unused) to avoid this behavior.
678  *
679  * Returns 0 if successful, otherwise a positive errno value. */
680 int
681 dpif_execute(struct dpif *dpif, uint16_t in_port,
682              const union odp_action actions[], size_t n_actions,
683              const struct ofpbuf *buf)
684 {
685     int error;
686
687     COVERAGE_INC(dpif_execute);
688     if (n_actions > 0) {
689         error = dpif->class->execute(dpif, in_port, actions, n_actions, buf);
690     } else {
691         error = 0;
692     }
693
694     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
695         struct ds ds = DS_EMPTY_INITIALIZER;
696         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
697         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
698         format_odp_actions(&ds, actions, n_actions);
699         if (error) {
700             ds_put_format(&ds, " failed (%s)", strerror(error));
701         }
702         ds_put_format(&ds, " on packet %s", packet);
703         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
704         ds_destroy(&ds);
705         free(packet);
706     }
707     return error;
708 }
709
710 /* Retrieves 'dpif''s "listen mask" into '*listen_mask'.  Each ODPL_* bit set
711  * in '*listen_mask' indicates that dpif_recv() will receive messages of that
712  * type.  Returns 0 if successful, otherwise a positive errno value. */
713 int
714 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
715 {
716     int error = dpif->class->recv_get_mask(dpif, listen_mask);
717     if (error) {
718         *listen_mask = 0;
719     }
720     log_operation(dpif, "recv_get_mask", error);
721     return error;
722 }
723
724 /* Sets 'dpif''s "listen mask" to 'listen_mask'.  Each ODPL_* bit set in
725  * '*listen_mask' requests that dpif_recv() receive messages of that type.
726  * Returns 0 if successful, otherwise a positive errno value. */
727 int
728 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
729 {
730     int error = dpif->class->recv_set_mask(dpif, listen_mask);
731     log_operation(dpif, "recv_set_mask", error);
732     return error;
733 }
734
735 /* Attempts to receive a message from 'dpif'.  If successful, stores the
736  * message into '*packetp'.  The message, if one is received, will begin with
737  * 'struct odp_msg' as a header.  Only messages of the types selected with
738  * dpif_set_listen_mask() will ordinarily be received (but if a message type is
739  * enabled and then later disabled, some stragglers might pop up).
740  *
741  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
742  * if no message is immediately available. */
743 int
744 dpif_recv(struct dpif *dpif, struct ofpbuf **packetp)
745 {
746     int error = dpif->class->recv(dpif, packetp);
747     if (!error) {
748         if (VLOG_IS_DBG_ENABLED()) {
749             struct ofpbuf *buf = *packetp;
750             struct odp_msg *msg = buf->data;
751             void *payload = msg + 1;
752             size_t payload_len = buf->size - sizeof *msg;
753             char *s = ofp_packet_to_string(payload, payload_len, payload_len);
754             VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
755                         "%zu on port %"PRIu16": %s", dpif_name(dpif),
756                         (msg->type == _ODPL_MISS_NR ? "miss"
757                          : msg->type == _ODPL_ACTION_NR ? "action"
758                          : "<unknown>"),
759                         payload_len, msg->port, s);
760             free(s);
761         }
762     } else {
763         *packetp = NULL;
764     }
765     return error;
766 }
767
768 /* Discards all messages that would otherwise be received by dpif_recv() on
769  * 'dpif'.  Returns 0 if successful, otherwise a positive errno value. */
770 int
771 dpif_recv_purge(struct dpif *dpif)
772 {
773     struct odp_stats stats;
774     unsigned int i;
775     int error;
776
777     COVERAGE_INC(dpif_purge);
778
779     error = dpif_get_dp_stats(dpif, &stats);
780     if (error) {
781         return error;
782     }
783
784     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue; i++) {
785         struct ofpbuf *buf;
786         error = dpif_recv(dpif, &buf);
787         if (error) {
788             return error == EAGAIN ? 0 : error;
789         }
790         ofpbuf_delete(buf);
791     }
792     return 0;
793 }
794
795 /* Arranges for the poll loop to wake up when 'dpif' has a message queued to be
796  * received with dpif_recv(). */
797 void
798 dpif_recv_wait(struct dpif *dpif)
799 {
800     dpif->class->recv_wait(dpif);
801 }
802
803 /* Obtains the NetFlow engine type and engine ID for 'dpif' into '*engine_type'
804  * and '*engine_id', respectively. */
805 void
806 dpif_get_netflow_ids(const struct dpif *dpif,
807                      uint8_t *engine_type, uint8_t *engine_id)
808 {
809     *engine_type = dpif->netflow_engine_type;
810     *engine_id = dpif->netflow_engine_id;
811 }
812 \f
813 void
814 dpif_init(struct dpif *dpif, const struct dpif_class *class, const char *name,
815           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
816 {
817     dpif->class = class;
818     dpif->name = xstrdup(name);
819     dpif->netflow_engine_type = netflow_engine_type;
820     dpif->netflow_engine_id = netflow_engine_id;
821 }
822 \f
823 static void
824 log_operation(const struct dpif *dpif, const char *operation, int error)
825 {
826     if (!error) {
827         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", dpif_name(dpif), operation);
828     } else {
829         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
830                      dpif_name(dpif), operation, strerror(error));
831     }
832 }
833
834 static enum vlog_level
835 flow_message_log_level(int error)
836 {
837     return error ? VLL_WARN : VLL_DBG;
838 }
839
840 static bool
841 should_log_flow_message(int error)
842 {
843     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
844                              error ? &error_rl : &dpmsg_rl);
845 }
846
847 static void
848 log_flow_message(const struct dpif *dpif, int error, const char *operation,
849                  const flow_t *flow, const struct odp_flow_stats *stats,
850                  const union odp_action *actions, size_t n_actions)
851 {
852     struct ds ds = DS_EMPTY_INITIALIZER;
853     ds_put_format(&ds, "%s: ", dpif_name(dpif));
854     if (error) {
855         ds_put_cstr(&ds, "failed to ");
856     }
857     ds_put_format(&ds, "%s ", operation);
858     if (error) {
859         ds_put_format(&ds, "(%s) ", strerror(error));
860     }
861     flow_format(&ds, flow);
862     if (stats) {
863         ds_put_cstr(&ds, ", ");
864         format_odp_flow_stats(&ds, stats);
865     }
866     if (actions || n_actions) {
867         ds_put_cstr(&ds, ", actions:");
868         format_odp_actions(&ds, actions, n_actions);
869     }
870     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
871     ds_destroy(&ds);
872 }
873
874 static void
875 log_flow_operation(const struct dpif *dpif, const char *operation, int error,
876                    struct odp_flow *flow)
877 {
878     if (error) {
879         flow->n_actions = 0;
880     }
881     log_flow_message(dpif, error, operation, &flow->key,
882                      !error ? &flow->stats : NULL,
883                      flow->actions, flow->n_actions);
884 }
885
886 static void
887 log_flow_put(struct dpif *dpif, int error, const struct odp_flow_put *put)
888 {
889     enum { ODPPF_ALL = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS };
890     struct ds s;
891
892     ds_init(&s);
893     ds_put_cstr(&s, "put");
894     if (put->flags & ODPPF_CREATE) {
895         ds_put_cstr(&s, "[create]");
896     }
897     if (put->flags & ODPPF_MODIFY) {
898         ds_put_cstr(&s, "[modify]");
899     }
900     if (put->flags & ODPPF_ZERO_STATS) {
901         ds_put_cstr(&s, "[zero]");
902     }
903     if (put->flags & ~ODPPF_ALL) {
904         ds_put_format(&s, "[%x]", put->flags & ~ODPPF_ALL);
905     }
906     log_flow_message(dpif, error, ds_cstr(&s), &put->flow.key,
907                      !error ? &put->flow.stats : NULL,
908                      put->flow.actions, put->flow.n_actions);
909     ds_destroy(&s);
910 }
911
912 /* There is a tendency to construct odp_flow objects on the stack and to
913  * forget to properly initialize their "actions" and "n_actions" members.
914  * When this happens, we get memory corruption because the kernel
915  * writes through the random pointer that is in the "actions" member.
916  *
917  * This function attempts to combat the problem by:
918  *
919  *      - Forcing a segfault if "actions" points to an invalid region (instead
920  *        of just getting back EFAULT, which can be easily missed in the log).
921  *
922  *      - Storing a distinctive value that is likely to cause an
923  *        easy-to-identify error later if it is dereferenced, etc.
924  *
925  *      - Triggering a warning on uninitialized memory from Valgrind if
926  *        "actions" or "n_actions" was not initialized.
927  */
928 static void
929 check_rw_odp_flow(struct odp_flow *flow)
930 {
931     if (flow->n_actions) {
932         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
933     }
934 }
935 \f
936 #include <net/if.h>
937 #include <linux/rtnetlink.h>
938 #include <linux/ethtool.h>
939 #include <linux/sockios.h>
940 #include <netinet/in.h>
941 #include <sys/ioctl.h>
942 #include <sys/stat.h>
943 #include <sys/sysmacros.h>
944 #include <unistd.h>
945
946 struct dpifmon {
947     struct dpif *dpif;
948     struct nl_sock *sock;
949     int local_ifindex;
950 };
951
952 int
953 dpifmon_create(const char *datapath_name, struct dpifmon **monp)
954 {
955     struct dpifmon *mon;
956     char local_name[IFNAMSIZ];
957     int error;
958
959     mon = *monp = xmalloc(sizeof *mon);
960
961     error = dpif_open(datapath_name, &mon->dpif);
962     if (error) {
963         goto error;
964     }
965     error = dpif_port_get_name(mon->dpif, ODPP_LOCAL,
966                                local_name, sizeof local_name);
967     if (error) {
968         goto error_close_dpif;
969     }
970
971     mon->local_ifindex = if_nametoindex(local_name);
972     if (!mon->local_ifindex) {
973         error = errno;
974         VLOG_WARN("could not get ifindex of %s device: %s",
975                   local_name, strerror(errno));
976         goto error_close_dpif;
977     }
978
979     error = nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &mon->sock);
980     if (error) {
981         VLOG_WARN("could not create rtnetlink socket: %s", strerror(error));
982         goto error_close_dpif;
983     }
984
985     return 0;
986
987 error_close_dpif:
988     dpif_close(mon->dpif);
989 error:
990     free(mon);
991     *monp = NULL;
992     return error;
993 }
994
995 void
996 dpifmon_destroy(struct dpifmon *mon)
997 {
998     if (mon) {
999         dpif_close(mon->dpif);
1000         nl_sock_destroy(mon->sock);
1001     }
1002 }
1003
1004 int
1005 dpifmon_poll(struct dpifmon *mon, char **devnamep)
1006 {
1007     static struct vlog_rate_limit slow_rl = VLOG_RATE_LIMIT_INIT(1, 5);
1008     static const struct nl_policy rtnlgrp_link_policy[] = {
1009         [IFLA_IFNAME] = { .type = NL_A_STRING },
1010         [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
1011     };
1012     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1013     struct ofpbuf *buf;
1014     int error;
1015
1016     *devnamep = NULL;
1017 again:
1018     error = nl_sock_recv(mon->sock, &buf, false);
1019     switch (error) {
1020     case 0:
1021         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1022                              rtnlgrp_link_policy,
1023                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1024             VLOG_WARN_RL(&slow_rl, "received bad rtnl message");
1025             error = ENOBUFS;
1026         } else {
1027             const char *devname = nl_attr_get_string(attrs[IFLA_IFNAME]);
1028             bool for_us;
1029
1030             if (attrs[IFLA_MASTER]) {
1031                 uint32_t master_ifindex = nl_attr_get_u32(attrs[IFLA_MASTER]);
1032                 for_us = master_ifindex == mon->local_ifindex;
1033             } else {
1034                 /* It's for us if that device is one of our ports. */
1035                 struct odp_port port;
1036                 for_us = !dpif_port_query_by_name(mon->dpif, devname, &port);
1037             }
1038
1039             if (!for_us) {
1040                 /* Not for us, try again. */
1041                 ofpbuf_delete(buf);
1042                 COVERAGE_INC(dpifmon_poll_false_wakeup);
1043                 goto again;
1044             }
1045             COVERAGE_INC(dpifmon_poll_changed);
1046             *devnamep = xstrdup(devname);
1047         }
1048         ofpbuf_delete(buf);
1049         break;
1050
1051     case EAGAIN:
1052         /* Nothing to do. */
1053         break;
1054
1055     case ENOBUFS:
1056         VLOG_WARN_RL(&slow_rl, "dpifmon socket overflowed");
1057         break;
1058
1059     default:
1060         VLOG_WARN_RL(&slow_rl, "error on dpifmon socket: %s", strerror(error));
1061         break;
1062     }
1063     return error;
1064 }
1065
1066 void
1067 dpifmon_run(struct dpifmon *mon UNUSED)
1068 {
1069     /* Nothing to do in this implementation. */
1070 }
1071
1072 void
1073 dpifmon_wait(struct dpifmon *mon)
1074 {
1075     nl_sock_wait(mon->sock, POLLIN);
1076 }