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