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