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