Introduce general-purpose ways to wait for dpif and netdev changes.
[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 /* Polls for changes in the set of ports in 'dpif'.  If the set of ports in
387  * 'dpif' has changed, this function does one of the following:
388  *
389  * - Stores the name of the device that was added to or deleted from 'dpif' in
390  *   '*devnamep' and returns 0.  The caller is responsible for freeing
391  *   '*devnamep' (with free()) when it no longer needs it.
392  *
393  * - Returns ENOBUFS and sets '*devnamep' to NULL.
394  *
395  * This function may also return 'false positives', where it returns 0 and
396  * '*devnamep' names a device that was not actually added or deleted or it
397  * returns ENOBUFS without any change.
398  *
399  * Returns EAGAIN if the set of ports in 'dpif' has not changed.  May also
400  * return other positive errno values to indicate that something has gone
401  * wrong. */
402 int
403 dpif_port_poll(const struct dpif *dpif, char **devnamep)
404 {
405     int error = dpif->class->port_poll(dpif, devnamep);
406     if (error) {
407         *devnamep = NULL;
408     }
409     return error;
410 }
411
412 /* Arranges for the poll loop to wake up when port_poll(dpif) will return a
413  * value other than EAGAIN. */
414 void
415 dpif_port_poll_wait(const struct dpif *dpif)
416 {
417     dpif->class->port_poll_wait(dpif);
418 }
419
420 /* Retrieves a list of the port numbers in port group 'group' in 'dpif'.
421  *
422  * On success, returns 0 and points '*ports' to a newly allocated array of
423  * integers, each of which is a 'dpif' port number for a port in
424  * 'group'.  Stores the number of elements in the array in '*n_ports'.  The
425  * caller is responsible for freeing '*ports' by calling free().
426  *
427  * On failure, returns a positive errno value and sets '*ports' to NULL and
428  * '*n_ports' to 0. */
429 int
430 dpif_port_group_get(const struct dpif *dpif, uint16_t group,
431                     uint16_t **ports, size_t *n_ports)
432 {
433     int error;
434
435     *ports = NULL;
436     *n_ports = 0;
437     for (;;) {
438         int retval = dpif->class->port_group_get(dpif, group,
439                                                  *ports, *n_ports);
440         if (retval < 0) {
441             /* Hard error. */
442             error = -retval;
443             free(*ports);
444             *ports = NULL;
445             *n_ports = 0;
446             break;
447         } else if (retval <= *n_ports) {
448             /* Success. */
449             error = 0;
450             *n_ports = retval;
451             break;
452         } else {
453             /* Soft error: there were more ports than we expected in the
454              * group.  Try again. */
455             free(*ports);
456             *ports = xcalloc(retval, sizeof **ports);
457             *n_ports = retval;
458         }
459     }
460     log_operation(dpif, "port_group_get", error);
461     return error;
462 }
463
464 /* Updates port group 'group' in 'dpif', making it contain the 'n_ports' ports
465  * whose 'dpif' port numbers are given in 'n_ports'.  Returns 0 if
466  * successful, otherwise a positive errno value.
467  *
468  * Behavior is undefined if the values in ports[] are not unique. */
469 int
470 dpif_port_group_set(struct dpif *dpif, uint16_t group,
471                     const uint16_t ports[], size_t n_ports)
472 {
473     int error;
474
475     COVERAGE_INC(dpif_port_group_set);
476
477     error = dpif->class->port_group_set(dpif, group, ports, n_ports);
478     log_operation(dpif, "port_group_set", error);
479     return error;
480 }
481
482 /* Deletes all flows from 'dpif'.  Returns 0 if successful, otherwise a
483  * positive errno value.  */
484 int
485 dpif_flow_flush(struct dpif *dpif)
486 {
487     int error;
488
489     COVERAGE_INC(dpif_flow_flush);
490
491     error = dpif->class->flow_flush(dpif);
492     log_operation(dpif, "flow_flush", error);
493     return error;
494 }
495
496 /* Queries 'dpif' for a flow entry matching 'flow->key'.
497  *
498  * If a flow matching 'flow->key' exists in 'dpif', stores statistics for the
499  * flow into 'flow->stats'.  If 'flow->n_actions' is zero, then 'flow->actions'
500  * is ignored.  If 'flow->n_actions' is nonzero, then 'flow->actions' should
501  * point to an array of the specified number of actions.  At most that many of
502  * the flow's actions will be copied into that array.  'flow->n_actions' will
503  * be updated to the number of actions actually present in the flow, which may
504  * be greater than the number stored if the flow has more actions than space
505  * available in the array.
506  *
507  * If no flow matching 'flow->key' exists in 'dpif', returns ENOENT.  On other
508  * failure, returns a positive errno value. */
509 int
510 dpif_flow_get(const struct dpif *dpif, struct odp_flow *flow)
511 {
512     int error;
513
514     COVERAGE_INC(dpif_flow_get);
515
516     check_rw_odp_flow(flow);
517     error = dpif->class->flow_get(dpif, flow, 1);
518     if (!error) {
519         error = flow->stats.error;
520     }
521     if (should_log_flow_message(error)) {
522         log_flow_operation(dpif, "flow_get", error, flow);
523     }
524     return error;
525 }
526
527 /* For each flow 'flow' in the 'n' flows in 'flows':
528  *
529  * - If a flow matching 'flow->key' exists in 'dpif':
530  *
531  *     Stores 0 into 'flow->stats.error' and stores statistics for the flow
532  *     into 'flow->stats'.
533  *
534  *     If 'flow->n_actions' is zero, then 'flow->actions' is ignored.  If
535  *     'flow->n_actions' is nonzero, then 'flow->actions' should point to an
536  *     array of the specified number of actions.  At most that many of the
537  *     flow's actions will be copied into that array.  'flow->n_actions' will
538  *     be updated to the number of actions actually present in the flow, which
539  *     may be greater than the number stored if the flow has more actions than
540  *     space available in the array.
541  *
542  * - Flow-specific errors are indicated by a positive errno value in
543  *   'flow->stats.error'.  In particular, ENOENT indicates that no flow
544  *   matching 'flow->key' exists in 'dpif'.  When an error value is stored, the
545  *   contents of 'flow->key' are preserved but other members of 'flow' should
546  *   be treated as indeterminate.
547  *
548  * Returns 0 if all 'n' flows in 'flows' were updated (whether they were
549  * individually successful or not is indicated by 'flow->stats.error',
550  * however).  Returns a positive errno value if an error that prevented this
551  * update occurred, in which the caller must not depend on any elements in
552  * 'flows' being updated or not updated.
553  */
554 int
555 dpif_flow_get_multiple(const struct dpif *dpif,
556                        struct odp_flow flows[], size_t n)
557 {
558     int error;
559     size_t i;
560
561     COVERAGE_ADD(dpif_flow_get, n);
562
563     for (i = 0; i < n; i++) {
564         check_rw_odp_flow(&flows[i]);
565     }
566
567     error = dpif->class->flow_get(dpif, flows, n);
568     log_operation(dpif, "flow_get_multiple", error);
569     return error;
570 }
571
572 /* Adds or modifies a flow in 'dpif' as specified in 'put':
573  *
574  * - If the flow specified in 'put->flow' does not exist in 'dpif', then
575  *   behavior depends on whether ODPPF_CREATE is specified in 'put->flags': if
576  *   it is, the flow will be added, otherwise the operation will fail with
577  *   ENOENT.
578  *
579  * - Otherwise, the flow specified in 'put->flow' does exist in 'dpif'.
580  *   Behavior in this case depends on whether ODPPF_MODIFY is specified in
581  *   'put->flags': if it is, the flow's actions will be updated, otherwise the
582  *   operation will fail with EEXIST.  If the flow's actions are updated, then
583  *   its statistics will be zeroed if ODPPF_ZERO_STATS is set in 'put->flags',
584  *   left as-is otherwise.
585  *
586  * Returns 0 if successful, otherwise a positive errno value.
587  */
588 int
589 dpif_flow_put(struct dpif *dpif, struct odp_flow_put *put)
590 {
591     int error;
592
593     COVERAGE_INC(dpif_flow_put);
594
595     error = dpif->class->flow_put(dpif, put);
596     if (should_log_flow_message(error)) {
597         log_flow_put(dpif, error, put);
598     }
599     return error;
600 }
601
602 /* Deletes a flow matching 'flow->key' from 'dpif' or returns ENOENT if 'dpif'
603  * does not contain such a flow.
604  *
605  * If successful, updates 'flow->stats', 'flow->n_actions', and 'flow->actions'
606  * as described for dpif_flow_get(). */
607 int
608 dpif_flow_del(struct dpif *dpif, struct odp_flow *flow)
609 {
610     int error;
611
612     COVERAGE_INC(dpif_flow_del);
613
614     check_rw_odp_flow(flow);
615     memset(&flow->stats, 0, sizeof flow->stats);
616
617     error = dpif->class->flow_del(dpif, flow);
618     if (should_log_flow_message(error)) {
619         log_flow_operation(dpif, "delete flow", error, flow);
620     }
621     return error;
622 }
623
624 /* Stores up to 'n' flows in 'dpif' into 'flows', including their statistics
625  * but not including any information about their actions.  If successful,
626  * returns 0 and sets '*n_out' to the number of flows actually present in
627  * 'dpif', which might be greater than the number stored (if 'dpif' has more
628  * than 'n' flows).  On failure, returns a negative errno value and sets
629  * '*n_out' to 0. */
630 int
631 dpif_flow_list(const struct dpif *dpif, struct odp_flow flows[], size_t n,
632                size_t *n_out)
633 {
634     uint32_t i;
635     int retval;
636
637     COVERAGE_INC(dpif_flow_query_list);
638     if (RUNNING_ON_VALGRIND) {
639         memset(flows, 0, n * sizeof *flows);
640     } else {
641         for (i = 0; i < n; i++) {
642             flows[i].actions = NULL;
643             flows[i].n_actions = 0;
644         }
645     }
646     retval = dpif->class->flow_list(dpif, flows, n);
647     if (retval < 0) {
648         *n_out = 0;
649         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
650                      dpif_name(dpif), strerror(-retval));
651         return -retval;
652     } else {
653         COVERAGE_ADD(dpif_flow_query_list_n, retval);
654         *n_out = MIN(n, retval);
655         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows (of %d)",
656                     dpif_name(dpif), *n_out, retval);
657         return 0;
658     }
659 }
660
661 /* Retrieves all of the flows in 'dpif'.
662  *
663  * If successful, returns 0 and stores in '*flowsp' a pointer to a newly
664  * allocated array of flows, including their statistics but not including any
665  * information about their actions, and sets '*np' to the number of flows in
666  * '*flowsp'.  The caller is responsible for freeing '*flowsp' by calling
667  * free().
668  *
669  * On failure, returns a positive errno value and sets '*flowsp' to NULL and
670  * '*np' to 0. */
671 int
672 dpif_flow_list_all(const struct dpif *dpif,
673                    struct odp_flow **flowsp, size_t *np)
674 {
675     struct odp_stats stats;
676     struct odp_flow *flows;
677     size_t n_flows;
678     int error;
679
680     *flowsp = NULL;
681     *np = 0;
682
683     error = dpif_get_dp_stats(dpif, &stats);
684     if (error) {
685         return error;
686     }
687
688     flows = xmalloc(sizeof *flows * stats.n_flows);
689     error = dpif_flow_list(dpif, flows, stats.n_flows, &n_flows);
690     if (error) {
691         free(flows);
692         return error;
693     }
694
695     if (stats.n_flows != n_flows) {
696         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
697                      "flows but flow listing reported %zu",
698                      dpif_name(dpif), stats.n_flows, n_flows);
699     }
700     *flowsp = flows;
701     *np = n_flows;
702     return 0;
703 }
704
705 /* Causes 'dpif' to perform the 'n_actions' actions in 'actions' on the
706  * Ethernet frame specified in 'packet'.
707  *
708  * Pretends that the frame was originally received on the port numbered
709  * 'in_port'.  This affects only ODPAT_OUTPUT_GROUP actions, which will not
710  * send a packet out their input port.  Specify the number of an unused port
711  * (e.g. UINT16_MAX is currently always unused) to avoid this behavior.
712  *
713  * Returns 0 if successful, otherwise a positive errno value. */
714 int
715 dpif_execute(struct dpif *dpif, uint16_t in_port,
716              const union odp_action actions[], size_t n_actions,
717              const struct ofpbuf *buf)
718 {
719     int error;
720
721     COVERAGE_INC(dpif_execute);
722     if (n_actions > 0) {
723         error = dpif->class->execute(dpif, in_port, actions, n_actions, buf);
724     } else {
725         error = 0;
726     }
727
728     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
729         struct ds ds = DS_EMPTY_INITIALIZER;
730         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
731         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
732         format_odp_actions(&ds, actions, n_actions);
733         if (error) {
734             ds_put_format(&ds, " failed (%s)", strerror(error));
735         }
736         ds_put_format(&ds, " on packet %s", packet);
737         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
738         ds_destroy(&ds);
739         free(packet);
740     }
741     return error;
742 }
743
744 /* Retrieves 'dpif''s "listen mask" into '*listen_mask'.  Each ODPL_* bit set
745  * in '*listen_mask' indicates that dpif_recv() will receive messages of that
746  * type.  Returns 0 if successful, otherwise a positive errno value. */
747 int
748 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
749 {
750     int error = dpif->class->recv_get_mask(dpif, listen_mask);
751     if (error) {
752         *listen_mask = 0;
753     }
754     log_operation(dpif, "recv_get_mask", error);
755     return error;
756 }
757
758 /* Sets 'dpif''s "listen mask" to 'listen_mask'.  Each ODPL_* bit set in
759  * '*listen_mask' requests that dpif_recv() receive messages of that type.
760  * Returns 0 if successful, otherwise a positive errno value. */
761 int
762 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
763 {
764     int error = dpif->class->recv_set_mask(dpif, listen_mask);
765     log_operation(dpif, "recv_set_mask", error);
766     return error;
767 }
768
769 /* Attempts to receive a message from 'dpif'.  If successful, stores the
770  * message into '*packetp'.  The message, if one is received, will begin with
771  * 'struct odp_msg' as a header.  Only messages of the types selected with
772  * dpif_set_listen_mask() will ordinarily be received (but if a message type is
773  * enabled and then later disabled, some stragglers might pop up).
774  *
775  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
776  * if no message is immediately available. */
777 int
778 dpif_recv(struct dpif *dpif, struct ofpbuf **packetp)
779 {
780     int error = dpif->class->recv(dpif, packetp);
781     if (!error) {
782         if (VLOG_IS_DBG_ENABLED()) {
783             struct ofpbuf *buf = *packetp;
784             struct odp_msg *msg = buf->data;
785             void *payload = msg + 1;
786             size_t payload_len = buf->size - sizeof *msg;
787             char *s = ofp_packet_to_string(payload, payload_len, payload_len);
788             VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
789                         "%zu on port %"PRIu16": %s", dpif_name(dpif),
790                         (msg->type == _ODPL_MISS_NR ? "miss"
791                          : msg->type == _ODPL_ACTION_NR ? "action"
792                          : "<unknown>"),
793                         payload_len, msg->port, s);
794             free(s);
795         }
796     } else {
797         *packetp = NULL;
798     }
799     return error;
800 }
801
802 /* Discards all messages that would otherwise be received by dpif_recv() on
803  * 'dpif'.  Returns 0 if successful, otherwise a positive errno value. */
804 int
805 dpif_recv_purge(struct dpif *dpif)
806 {
807     struct odp_stats stats;
808     unsigned int i;
809     int error;
810
811     COVERAGE_INC(dpif_purge);
812
813     error = dpif_get_dp_stats(dpif, &stats);
814     if (error) {
815         return error;
816     }
817
818     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue; i++) {
819         struct ofpbuf *buf;
820         error = dpif_recv(dpif, &buf);
821         if (error) {
822             return error == EAGAIN ? 0 : error;
823         }
824         ofpbuf_delete(buf);
825     }
826     return 0;
827 }
828
829 /* Arranges for the poll loop to wake up when 'dpif' has a message queued to be
830  * received with dpif_recv(). */
831 void
832 dpif_recv_wait(struct dpif *dpif)
833 {
834     dpif->class->recv_wait(dpif);
835 }
836
837 /* Obtains the NetFlow engine type and engine ID for 'dpif' into '*engine_type'
838  * and '*engine_id', respectively. */
839 void
840 dpif_get_netflow_ids(const struct dpif *dpif,
841                      uint8_t *engine_type, uint8_t *engine_id)
842 {
843     *engine_type = dpif->netflow_engine_type;
844     *engine_id = dpif->netflow_engine_id;
845 }
846 \f
847 void
848 dpif_init(struct dpif *dpif, const struct dpif_class *class, const char *name,
849           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
850 {
851     dpif->class = class;
852     dpif->name = xstrdup(name);
853     dpif->netflow_engine_type = netflow_engine_type;
854     dpif->netflow_engine_id = netflow_engine_id;
855 }
856 \f
857 static void
858 log_operation(const struct dpif *dpif, const char *operation, int error)
859 {
860     if (!error) {
861         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", dpif_name(dpif), operation);
862     } else {
863         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
864                      dpif_name(dpif), operation, strerror(error));
865     }
866 }
867
868 static enum vlog_level
869 flow_message_log_level(int error)
870 {
871     return error ? VLL_WARN : VLL_DBG;
872 }
873
874 static bool
875 should_log_flow_message(int error)
876 {
877     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
878                              error ? &error_rl : &dpmsg_rl);
879 }
880
881 static void
882 log_flow_message(const struct dpif *dpif, int error, const char *operation,
883                  const flow_t *flow, const struct odp_flow_stats *stats,
884                  const union odp_action *actions, size_t n_actions)
885 {
886     struct ds ds = DS_EMPTY_INITIALIZER;
887     ds_put_format(&ds, "%s: ", dpif_name(dpif));
888     if (error) {
889         ds_put_cstr(&ds, "failed to ");
890     }
891     ds_put_format(&ds, "%s ", operation);
892     if (error) {
893         ds_put_format(&ds, "(%s) ", strerror(error));
894     }
895     flow_format(&ds, flow);
896     if (stats) {
897         ds_put_cstr(&ds, ", ");
898         format_odp_flow_stats(&ds, stats);
899     }
900     if (actions || n_actions) {
901         ds_put_cstr(&ds, ", actions:");
902         format_odp_actions(&ds, actions, n_actions);
903     }
904     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
905     ds_destroy(&ds);
906 }
907
908 static void
909 log_flow_operation(const struct dpif *dpif, const char *operation, int error,
910                    struct odp_flow *flow)
911 {
912     if (error) {
913         flow->n_actions = 0;
914     }
915     log_flow_message(dpif, error, operation, &flow->key,
916                      !error ? &flow->stats : NULL,
917                      flow->actions, flow->n_actions);
918 }
919
920 static void
921 log_flow_put(struct dpif *dpif, int error, const struct odp_flow_put *put)
922 {
923     enum { ODPPF_ALL = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS };
924     struct ds s;
925
926     ds_init(&s);
927     ds_put_cstr(&s, "put");
928     if (put->flags & ODPPF_CREATE) {
929         ds_put_cstr(&s, "[create]");
930     }
931     if (put->flags & ODPPF_MODIFY) {
932         ds_put_cstr(&s, "[modify]");
933     }
934     if (put->flags & ODPPF_ZERO_STATS) {
935         ds_put_cstr(&s, "[zero]");
936     }
937     if (put->flags & ~ODPPF_ALL) {
938         ds_put_format(&s, "[%x]", put->flags & ~ODPPF_ALL);
939     }
940     log_flow_message(dpif, error, ds_cstr(&s), &put->flow.key,
941                      !error ? &put->flow.stats : NULL,
942                      put->flow.actions, put->flow.n_actions);
943     ds_destroy(&s);
944 }
945
946 /* There is a tendency to construct odp_flow objects on the stack and to
947  * forget to properly initialize their "actions" and "n_actions" members.
948  * When this happens, we get memory corruption because the kernel
949  * writes through the random pointer that is in the "actions" member.
950  *
951  * This function attempts to combat the problem by:
952  *
953  *      - Forcing a segfault if "actions" points to an invalid region (instead
954  *        of just getting back EFAULT, which can be easily missed in the log).
955  *
956  *      - Storing a distinctive value that is likely to cause an
957  *        easy-to-identify error later if it is dereferenced, etc.
958  *
959  *      - Triggering a warning on uninitialized memory from Valgrind if
960  *        "actions" or "n_actions" was not initialized.
961  */
962 static void
963 check_rw_odp_flow(struct odp_flow *flow)
964 {
965     if (flow->n_actions) {
966         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
967     }
968 }