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