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