487b60a3db614b0498912f81066c040ad0787105
[sliver-openvswitch.git] / lib / dpif.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 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_flow_message(const struct dpif *dpif, int error,
80                              const char *operation,
81                              const struct nlattr *key, size_t key_len,
82                              const struct odp_flow_stats *stats,
83                              const struct nlattr *actions, size_t actions_len);
84 static void log_operation(const struct dpif *, const char *operation,
85                           int error);
86 static bool should_log_flow_message(int error);
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 /* Makes a deep copy of 'src' into 'dst'. */
495 void
496 dpif_port_clone(struct dpif_port *dst, const struct dpif_port *src)
497 {
498     dst->name = xstrdup(src->name);
499     dst->type = xstrdup(src->type);
500     dst->port_no = src->port_no;
501 }
502
503 /* Frees memory allocated to members of 'dpif_port'.
504  *
505  * Do not call this function on a dpif_port obtained from
506  * dpif_port_dump_next(): that function retains ownership of the data in the
507  * dpif_port. */
508 void
509 dpif_port_destroy(struct dpif_port *dpif_port)
510 {
511     free(dpif_port->name);
512     free(dpif_port->type);
513 }
514
515 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and
516  * initializes '*port' appropriately; on failure, returns a positive errno
517  * value.
518  *
519  * The caller owns the data in 'port' and must free it with
520  * dpif_port_destroy() when it is no longer needed. */
521 int
522 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
523                           struct dpif_port *port)
524 {
525     int error = dpif->dpif_class->port_query_by_number(dpif, port_no, port);
526     if (!error) {
527         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
528                     dpif_name(dpif), port_no, port->name);
529     } else {
530         memset(port, 0, sizeof *port);
531         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
532                      dpif_name(dpif), port_no, strerror(error));
533     }
534     return error;
535 }
536
537 /* Looks up port named 'devname' in 'dpif'.  On success, returns 0 and
538  * initializes '*port' appropriately; on failure, returns a positive errno
539  * value.
540  *
541  * The caller owns the data in 'port' and must free it with
542  * dpif_port_destroy() when it is no longer needed. */
543 int
544 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
545                         struct dpif_port *port)
546 {
547     int error = dpif->dpif_class->port_query_by_name(dpif, devname, port);
548     if (!error) {
549         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
550                     dpif_name(dpif), devname, port->port_no);
551     } else {
552         memset(port, 0, sizeof *port);
553
554         /* Log level is DBG here because all the current callers are interested
555          * in whether 'dpif' actually has a port 'devname', so that it's not an
556          * issue worth logging if it doesn't. */
557         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
558                     dpif_name(dpif), devname, strerror(error));
559     }
560     return error;
561 }
562
563 /* Returns one greater than the maximum port number accepted in flow
564  * actions. */
565 int
566 dpif_get_max_ports(const struct dpif *dpif)
567 {
568     return dpif->dpif_class->get_max_ports(dpif);
569 }
570
571 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and copies
572  * the port's name into the 'name_size' bytes in 'name', ensuring that the
573  * result is null-terminated.  On failure, returns a positive errno value and
574  * makes 'name' the empty string. */
575 int
576 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
577                    char *name, size_t name_size)
578 {
579     struct dpif_port port;
580     int error;
581
582     assert(name_size > 0);
583
584     error = dpif_port_query_by_number(dpif, port_no, &port);
585     if (!error) {
586         ovs_strlcpy(name, port.name, name_size);
587         dpif_port_destroy(&port);
588     } else {
589         *name = '\0';
590     }
591     return error;
592 }
593
594 /* Initializes 'dump' to begin dumping the ports in a dpif.
595  *
596  * This function provides no status indication.  An error status for the entire
597  * dump operation is provided when it is completed by calling
598  * dpif_port_dump_done().
599  */
600 void
601 dpif_port_dump_start(struct dpif_port_dump *dump, const struct dpif *dpif)
602 {
603     dump->dpif = dpif;
604     dump->error = dpif->dpif_class->port_dump_start(dpif, &dump->state);
605     log_operation(dpif, "port_dump_start", dump->error);
606 }
607
608 /* Attempts to retrieve another port from 'dump', which must have been
609  * initialized with dpif_port_dump_start().  On success, stores a new dpif_port
610  * into 'port' and returns true.  On failure, returns false.
611  *
612  * Failure might indicate an actual error or merely that the last port has been
613  * dumped.  An error status for the entire dump operation is provided when it
614  * is completed by calling dpif_port_dump_done().
615  *
616  * The dpif owns the data stored in 'port'.  It will remain valid until at
617  * least the next time 'dump' is passed to dpif_port_dump_next() or
618  * dpif_port_dump_done(). */
619 bool
620 dpif_port_dump_next(struct dpif_port_dump *dump, struct dpif_port *port)
621 {
622     const struct dpif *dpif = dump->dpif;
623
624     if (dump->error) {
625         return false;
626     }
627
628     dump->error = dpif->dpif_class->port_dump_next(dpif, dump->state, port);
629     if (dump->error == EOF) {
630         VLOG_DBG_RL(&dpmsg_rl, "%s: dumped all ports", dpif_name(dpif));
631     } else {
632         log_operation(dpif, "port_dump_next", dump->error);
633     }
634
635     if (dump->error) {
636         dpif->dpif_class->port_dump_done(dpif, dump->state);
637         return false;
638     }
639     return true;
640 }
641
642 /* Completes port table dump operation 'dump', which must have been initialized
643  * with dpif_port_dump_start().  Returns 0 if the dump operation was
644  * error-free, otherwise a positive errno value describing the problem. */
645 int
646 dpif_port_dump_done(struct dpif_port_dump *dump)
647 {
648     const struct dpif *dpif = dump->dpif;
649     if (!dump->error) {
650         dump->error = dpif->dpif_class->port_dump_done(dpif, dump->state);
651         log_operation(dpif, "port_dump_done", dump->error);
652     }
653     return dump->error == EOF ? 0 : dump->error;
654 }
655
656 /* Polls for changes in the set of ports in 'dpif'.  If the set of ports in
657  * 'dpif' has changed, this function does one of the following:
658  *
659  * - Stores the name of the device that was added to or deleted from 'dpif' in
660  *   '*devnamep' and returns 0.  The caller is responsible for freeing
661  *   '*devnamep' (with free()) when it no longer needs it.
662  *
663  * - Returns ENOBUFS and sets '*devnamep' to NULL.
664  *
665  * This function may also return 'false positives', where it returns 0 and
666  * '*devnamep' names a device that was not actually added or deleted or it
667  * returns ENOBUFS without any change.
668  *
669  * Returns EAGAIN if the set of ports in 'dpif' has not changed.  May also
670  * return other positive errno values to indicate that something has gone
671  * wrong. */
672 int
673 dpif_port_poll(const struct dpif *dpif, char **devnamep)
674 {
675     int error = dpif->dpif_class->port_poll(dpif, devnamep);
676     if (error) {
677         *devnamep = NULL;
678     }
679     return error;
680 }
681
682 /* Arranges for the poll loop to wake up when port_poll(dpif) will return a
683  * value other than EAGAIN. */
684 void
685 dpif_port_poll_wait(const struct dpif *dpif)
686 {
687     dpif->dpif_class->port_poll_wait(dpif);
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.  The flow is specified by the Netlink
705  * attributes with types ODP_KEY_ATTR_* in the 'key_len' bytes starting at
706  * 'key'.
707  *
708  * Returns 0 if successful.  If no flow matches, returns ENOENT.  On other
709  * failure, returns a positive errno value.
710  *
711  * If 'actionsp' is nonnull, then on success '*actionsp' will be set to an
712  * ofpbuf owned by the caller that contains the Netlink attributes for the
713  * flow's actions.  The caller must free the ofpbuf (with ofpbuf_delete()) when
714  * it is no longer needed.
715  *
716  * If 'stats' is nonnull, then on success it will be updated with the flow's
717  * statistics. */
718 int
719 dpif_flow_get(const struct dpif *dpif, int flags,
720               const struct nlattr *key, size_t key_len,
721               struct ofpbuf **actionsp, struct odp_flow_stats *stats)
722 {
723     int error;
724
725     COVERAGE_INC(dpif_flow_get);
726
727     error = dpif->dpif_class->flow_get(dpif, flags, key, key_len, actionsp,
728                                        stats);
729     if (error) {
730         if (actionsp) {
731             *actionsp = NULL;
732         }
733         if (stats) {
734             memset(stats, 0, sizeof *stats);
735         }
736     }
737     if (should_log_flow_message(error)) {
738         const struct nlattr *actions;
739         size_t actions_len;
740
741         if (!error && actionsp) {
742             actions = (*actionsp)->data;
743             actions_len = (*actionsp)->size;
744         } else {
745             actions = NULL;
746             actions_len = 0;
747         }
748         log_flow_message(dpif, error, "flow_get", key, key_len, stats,
749                          actions, actions_len);
750     }
751     return error;
752 }
753
754 /* Adds or modifies a flow in 'dpif'.  The flow is specified by the Netlink
755  * attributes with types ODP_KEY_ATTR_* in the 'key_len' bytes starting at
756  * 'key'.  The associated actions are specified by the Netlink attributes with
757  * types ODPAT_* in the 'actions_len' bytes starting at 'actions'.
758  *
759  * - If the flow's key does not exist in 'dpif', then the flow will be added if
760  *   'flags' includes ODPPF_CREATE.  Otherwise the operation will fail with
761  *   ENOENT.
762  *
763  *   If the operation succeeds, then 'stats', if nonnull, will be zeroed.
764  *
765  * - If the flow's key does exist in 'dpif', then the flow's actions will be
766  *   updated if 'flags' includes ODPPF_MODIFY.  Otherwise the operation will
767  *   fail with EEXIST.  If the flow's actions are updated, then its statistics
768  *   will be zeroed if 'flags' includes ODPPF_ZERO_STATS, and left as-is
769  *   otherwise.
770  *
771  *   If the operation succeeds, then 'stats', if nonnull, will be set to the
772  *   flow's statistics before the update.
773  */
774 int
775 dpif_flow_put(struct dpif *dpif, int flags,
776               const struct nlattr *key, size_t key_len,
777               const struct nlattr *actions, size_t actions_len,
778               struct odp_flow_stats *stats)
779 {
780     int error;
781
782     COVERAGE_INC(dpif_flow_put);
783
784     error = dpif->dpif_class->flow_put(dpif, flags, key, key_len,
785                                        actions, actions_len, stats);
786     if (error && stats) {
787         memset(stats, 0, sizeof *stats);
788     }
789     if (should_log_flow_message(error)) {
790         enum { ODPPF_ALL = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS };
791         struct ds s;
792
793         ds_init(&s);
794         ds_put_cstr(&s, "put");
795         if (flags & ODPPF_CREATE) {
796             ds_put_cstr(&s, "[create]");
797         }
798         if (flags & ODPPF_MODIFY) {
799             ds_put_cstr(&s, "[modify]");
800         }
801         if (flags & ODPPF_ZERO_STATS) {
802             ds_put_cstr(&s, "[zero]");
803         }
804         if (flags & ~ODPPF_ALL) {
805             ds_put_format(&s, "[%x]", flags & ~ODPPF_ALL);
806         }
807         log_flow_message(dpif, error, ds_cstr(&s), key, key_len, stats,
808                          actions, actions_len);
809         ds_destroy(&s);
810     }
811     return error;
812 }
813
814 /* Deletes a flow from 'dpif' and returns 0, or returns ENOENT if 'dpif' does
815  * not contain such a flow.  The flow is specified by the Netlink attributes
816  * with types ODP_KEY_ATTR_* in the 'key_len' bytes starting at 'key'.
817  *
818  * If the operation succeeds, then 'stats', if nonnull, will be set to the
819  * flow's statistics before its deletion. */
820 int
821 dpif_flow_del(struct dpif *dpif,
822               const struct nlattr *key, size_t key_len,
823               struct odp_flow_stats *stats)
824 {
825     int error;
826
827     COVERAGE_INC(dpif_flow_del);
828
829     error = dpif->dpif_class->flow_del(dpif, key, key_len, stats);
830     if (error && stats) {
831         memset(stats, 0, sizeof *stats);
832     }
833     if (should_log_flow_message(error)) {
834         log_flow_message(dpif, error, "flow_del", key, key_len,
835                          !error ? stats : NULL, NULL, 0);
836     }
837     return error;
838 }
839
840 /* Initializes 'dump' to begin dumping the flows in a dpif.
841  *
842  * This function provides no status indication.  An error status for the entire
843  * dump operation is provided when it is completed by calling
844  * dpif_flow_dump_done().
845  */
846 void
847 dpif_flow_dump_start(struct dpif_flow_dump *dump, const struct dpif *dpif)
848 {
849     dump->dpif = dpif;
850     dump->error = dpif->dpif_class->flow_dump_start(dpif, &dump->state);
851     log_operation(dpif, "flow_dump_start", dump->error);
852 }
853
854 /* Attempts to retrieve another flow from 'dump', which must have been
855  * initialized with dpif_flow_dump_start().  On success, updates the output
856  * parameters as described below and returns true.  Otherwise, returns false.
857  * Failure might indicate an actual error or merely the end of the flow table.
858  * An error status for the entire dump operation is provided when it is
859  * completed by calling dpif_flow_dump_done().
860  *
861  * On success, if 'key' and 'key_len' are nonnull then '*key' and '*key_len'
862  * will be set to Netlink attributes with types ODP_KEY_ATTR_* representing the
863  * dumped flow's key.  If 'actions' and 'actions_len' are nonnull then they are
864  * set to Netlink attributes with types ODPAT_* representing the dumped flow's
865  * actions.  If 'stats' is nonnull then it will be set to the dumped flow's
866  * statistics.
867  *
868  * All of the returned data is owned by 'dpif', not by the caller, and the
869  * caller must not modify or free it.  'dpif' guarantees that it remains
870  * accessible and unchanging until at least the next call to 'flow_dump_next'
871  * or 'flow_dump_done' for 'dump'. */
872 bool
873 dpif_flow_dump_next(struct dpif_flow_dump *dump,
874                     const struct nlattr **key, size_t *key_len,
875                     const struct nlattr **actions, size_t *actions_len,
876                     const struct odp_flow_stats **stats)
877 {
878     const struct dpif *dpif = dump->dpif;
879     int error = dump->error;
880
881     if (!error) {
882         error = dpif->dpif_class->flow_dump_next(dpif, dump->state,
883                                                  key, key_len,
884                                                  actions, actions_len,
885                                                  stats);
886         if (error) {
887             dpif->dpif_class->flow_dump_done(dpif, dump->state);
888         }
889     }
890     if (error) {
891         if (key) {
892             *key = NULL;
893             *key_len = 0;
894         }
895         if (actions) {
896             *actions = NULL;
897             *actions_len = 0;
898         }
899         if (stats) {
900             *stats = NULL;
901         }
902     }
903     if (!dump->error) {
904         if (error == EOF) {
905             VLOG_DBG_RL(&dpmsg_rl, "%s: dumped all flows", dpif_name(dpif));
906         } else if (should_log_flow_message(error)) {
907             log_flow_message(dpif, error, "flow_dump",
908                              key ? *key : NULL, key ? *key_len : 0,
909                              stats ? *stats : NULL, actions ? *actions : NULL,
910                              actions ? *actions_len : 0);
911         }
912     }
913     dump->error = error;
914     return !error;
915 }
916
917 /* Completes flow table dump operation 'dump', which must have been initialized
918  * with dpif_flow_dump_start().  Returns 0 if the dump operation was
919  * error-free, otherwise a positive errno value describing the problem. */
920 int
921 dpif_flow_dump_done(struct dpif_flow_dump *dump)
922 {
923     const struct dpif *dpif = dump->dpif;
924     if (!dump->error) {
925         dump->error = dpif->dpif_class->flow_dump_done(dpif, dump->state);
926         log_operation(dpif, "flow_dump_done", dump->error);
927     }
928     return dump->error == EOF ? 0 : dump->error;
929 }
930
931 /* Causes 'dpif' to perform the 'actions_len' bytes of actions in 'actions' on
932  * the Ethernet frame specified in 'packet'.
933  *
934  * Returns 0 if successful, otherwise a positive errno value. */
935 int
936 dpif_execute(struct dpif *dpif,
937              const struct nlattr *actions, size_t actions_len,
938              const struct ofpbuf *buf)
939 {
940     int error;
941
942     COVERAGE_INC(dpif_execute);
943     if (actions_len > 0) {
944         error = dpif->dpif_class->execute(dpif, actions, actions_len, buf);
945     } else {
946         error = 0;
947     }
948
949     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
950         struct ds ds = DS_EMPTY_INITIALIZER;
951         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
952         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
953         format_odp_actions(&ds, actions, actions_len);
954         if (error) {
955             ds_put_format(&ds, " failed (%s)", strerror(error));
956         }
957         ds_put_format(&ds, " on packet %s", packet);
958         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
959         ds_destroy(&ds);
960         free(packet);
961     }
962     return error;
963 }
964
965 /* Retrieves 'dpif''s "listen mask" into '*listen_mask'.  Each ODPL_* bit set
966  * in '*listen_mask' indicates that dpif_recv() will receive messages of that
967  * type.  Returns 0 if successful, otherwise a positive errno value. */
968 int
969 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
970 {
971     int error = dpif->dpif_class->recv_get_mask(dpif, listen_mask);
972     if (error) {
973         *listen_mask = 0;
974     }
975     log_operation(dpif, "recv_get_mask", error);
976     return error;
977 }
978
979 /* Sets 'dpif''s "listen mask" to 'listen_mask'.  Each ODPL_* bit set in
980  * '*listen_mask' requests that dpif_recv() receive messages of that type.
981  * Returns 0 if successful, otherwise a positive errno value. */
982 int
983 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
984 {
985     int error = dpif->dpif_class->recv_set_mask(dpif, listen_mask);
986     log_operation(dpif, "recv_set_mask", error);
987     return error;
988 }
989
990 /* Retrieve the sFlow sampling probability.  '*probability' is expressed as the
991  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
992  * the probability of sampling a given packet.
993  *
994  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
995  * indicates that 'dpif' does not support sFlow sampling. */
996 int
997 dpif_get_sflow_probability(const struct dpif *dpif, uint32_t *probability)
998 {
999     int error = (dpif->dpif_class->get_sflow_probability
1000                  ? dpif->dpif_class->get_sflow_probability(dpif, probability)
1001                  : EOPNOTSUPP);
1002     if (error) {
1003         *probability = 0;
1004     }
1005     log_operation(dpif, "get_sflow_probability", error);
1006     return error;
1007 }
1008
1009 /* Set the sFlow sampling probability.  'probability' is expressed as the
1010  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
1011  * the probability of sampling a given packet.
1012  *
1013  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
1014  * indicates that 'dpif' does not support sFlow sampling. */
1015 int
1016 dpif_set_sflow_probability(struct dpif *dpif, uint32_t probability)
1017 {
1018     int error = (dpif->dpif_class->set_sflow_probability
1019                  ? dpif->dpif_class->set_sflow_probability(dpif, probability)
1020                  : EOPNOTSUPP);
1021     log_operation(dpif, "set_sflow_probability", error);
1022     return error;
1023 }
1024
1025 /* Polls for an upcall from 'dpif'.  If successful, stores the upcall into
1026  * '*upcall'.  Only upcalls of the types selected with the set_listen_mask
1027  * member function will ordinarily be received (but if a message type is
1028  * enabled and then later disabled, some stragglers might pop up).
1029  *
1030  * The caller takes ownership of the data that 'upcall' points to.
1031  * 'upcall->key' and 'upcall->actions' (if nonnull) point into data owned by
1032  * 'upcall->packet', so their memory cannot be freed separately.  (This is
1033  * hardly a great way to do things but it works out OK for the dpif providers
1034  * and clients that exist so far.)
1035  *
1036  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
1037  * if no upcall is immediately available. */
1038 int
1039 dpif_recv(struct dpif *dpif, struct dpif_upcall *upcall)
1040 {
1041     int error = dpif->dpif_class->recv(dpif, upcall);
1042     if (!error && !VLOG_DROP_DBG(&dpmsg_rl)) {
1043         struct flow flow;
1044         char *s;
1045
1046         s = ofp_packet_to_string(upcall->packet->data,
1047                                  upcall->packet->size, upcall->packet->size);
1048         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
1049
1050         VLOG_DBG("%s: %s upcall on port %"PRIu16": %s", dpif_name(dpif),
1051                  (upcall->type == _ODPL_MISS_NR ? "miss"
1052                   : upcall->type == _ODPL_ACTION_NR ? "action"
1053                   : upcall->type == _ODPL_SFLOW_NR ? "sFlow"
1054                   : "<unknown>"),
1055                  flow.in_port, s);
1056         free(s);
1057     }
1058     return error;
1059 }
1060
1061 /* Discards all messages that would otherwise be received by dpif_recv() on
1062  * 'dpif'. */
1063 void
1064 dpif_recv_purge(struct dpif *dpif)
1065 {
1066     COVERAGE_INC(dpif_purge);
1067     if (dpif->dpif_class->recv_purge) {
1068         dpif->dpif_class->recv_purge(dpif);
1069     }
1070 }
1071
1072 /* Arranges for the poll loop to wake up when 'dpif' has a message queued to be
1073  * received with dpif_recv(). */
1074 void
1075 dpif_recv_wait(struct dpif *dpif)
1076 {
1077     dpif->dpif_class->recv_wait(dpif);
1078 }
1079
1080 /* Obtains the NetFlow engine type and engine ID for 'dpif' into '*engine_type'
1081  * and '*engine_id', respectively. */
1082 void
1083 dpif_get_netflow_ids(const struct dpif *dpif,
1084                      uint8_t *engine_type, uint8_t *engine_id)
1085 {
1086     *engine_type = dpif->netflow_engine_type;
1087     *engine_id = dpif->netflow_engine_id;
1088 }
1089
1090 /* Translates OpenFlow queue ID 'queue_id' (in host byte order) into a priority
1091  * value for use in the ODPAT_SET_PRIORITY action.  On success, returns 0 and
1092  * stores the priority into '*priority'.  On failure, returns a positive errno
1093  * value and stores 0 into '*priority'. */
1094 int
1095 dpif_queue_to_priority(const struct dpif *dpif, uint32_t queue_id,
1096                        uint32_t *priority)
1097 {
1098     int error = (dpif->dpif_class->queue_to_priority
1099                  ? dpif->dpif_class->queue_to_priority(dpif, queue_id,
1100                                                        priority)
1101                  : EOPNOTSUPP);
1102     if (error) {
1103         *priority = 0;
1104     }
1105     log_operation(dpif, "queue_to_priority", error);
1106     return error;
1107 }
1108 \f
1109 void
1110 dpif_init(struct dpif *dpif, const struct dpif_class *dpif_class,
1111           const char *name,
1112           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
1113 {
1114     dpif->dpif_class = dpif_class;
1115     dpif->base_name = xstrdup(name);
1116     dpif->full_name = xasprintf("%s@%s", dpif_class->type, name);
1117     dpif->netflow_engine_type = netflow_engine_type;
1118     dpif->netflow_engine_id = netflow_engine_id;
1119 }
1120
1121 /* Undoes the results of initialization.
1122  *
1123  * Normally this function only needs to be called from dpif_close().
1124  * However, it may be called by providers due to an error on opening
1125  * that occurs after initialization.  It this case dpif_close() would
1126  * never be called. */
1127 void
1128 dpif_uninit(struct dpif *dpif, bool close)
1129 {
1130     char *base_name = dpif->base_name;
1131     char *full_name = dpif->full_name;
1132
1133     if (close) {
1134         dpif->dpif_class->close(dpif);
1135     }
1136
1137     free(base_name);
1138     free(full_name);
1139 }
1140 \f
1141 static void
1142 log_operation(const struct dpif *dpif, const char *operation, int error)
1143 {
1144     if (!error) {
1145         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", dpif_name(dpif), operation);
1146     } else if (is_errno(error)) {
1147         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
1148                      dpif_name(dpif), operation, strerror(error));
1149     } else {
1150         VLOG_WARN_RL(&error_rl, "%s: %s failed (%d/%d)",
1151                      dpif_name(dpif), operation,
1152                      get_ofp_err_type(error), get_ofp_err_code(error));
1153     }
1154 }
1155
1156 static enum vlog_level
1157 flow_message_log_level(int error)
1158 {
1159     return error ? VLL_WARN : VLL_DBG;
1160 }
1161
1162 static bool
1163 should_log_flow_message(int error)
1164 {
1165     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
1166                              error ? &error_rl : &dpmsg_rl);
1167 }
1168
1169 static void
1170 log_flow_message(const struct dpif *dpif, int error, const char *operation,
1171                  const struct nlattr *key, size_t key_len,
1172                  const struct odp_flow_stats *stats,
1173                  const struct nlattr *actions, size_t actions_len)
1174 {
1175     struct ds ds = DS_EMPTY_INITIALIZER;
1176     ds_put_format(&ds, "%s: ", dpif_name(dpif));
1177     if (error) {
1178         ds_put_cstr(&ds, "failed to ");
1179     }
1180     ds_put_format(&ds, "%s ", operation);
1181     if (error) {
1182         ds_put_format(&ds, "(%s) ", strerror(error));
1183     }
1184     odp_flow_key_format(key, key_len, &ds);
1185     if (stats) {
1186         ds_put_cstr(&ds, ", ");
1187         format_odp_flow_stats(&ds, stats);
1188     }
1189     if (actions || actions_len) {
1190         ds_put_cstr(&ds, ", actions:");
1191         format_odp_actions(&ds, actions, actions_len);
1192     }
1193     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
1194     ds_destroy(&ds);
1195 }