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