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