Fix typos in comments.
[sliver-openvswitch.git] / lib / xfif.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 "xfif-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 "xflow-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(xfif)
44
45 static const struct xfif_class *base_xfif_classes[] = {
46 #ifdef HAVE_NETLINK
47     &xfif_linux_class,
48 #endif
49     &xfif_netdev_class,
50 };
51
52 struct registered_xfif_class {
53     struct xfif_class xfif_class;
54     int refcount;
55 };
56 static struct shash xfif_classes = SHASH_INITIALIZER(&xfif_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 xfif errors. */
64 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(60, 5);
65
66 static void log_operation(const struct xfif *, const char *operation,
67                           int error);
68 static void log_flow_operation(const struct xfif *, const char *operation,
69                                int error, struct xflow_flow *flow);
70 static void log_flow_put(struct xfif *, int error,
71                          const struct xflow_flow_put *);
72 static bool should_log_flow_message(int error);
73 static void check_rw_xflow_flow(struct xflow_flow *);
74
75 static void
76 xf_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_xfif_classes); i++) {
85             xf_register_provider(base_xfif_classes[i]);
86         }
87     }
88 }
89
90 /* Performs periodic work needed by all the various kinds of xfifs.
91  *
92  * If your program opens any xfifs, it must call both this function and
93  * netdev_run() within its main poll loop. */
94 void
95 xf_run(void)
96 {
97     struct shash_node *node;
98     SHASH_FOR_EACH(node, &xfif_classes) {
99         const struct registered_xfif_class *registered_class = node->data;
100         if (registered_class->xfif_class.run) {
101             registered_class->xfif_class.run();
102         }
103     }
104 }
105
106 /* Arranges for poll_block() to wake up when xf_run() needs to be called.
107  *
108  * If your program opens any xfifs, it must call both this function and
109  * netdev_wait() within its main poll loop. */
110 void
111 xf_wait(void)
112 {
113     struct shash_node *node;
114     SHASH_FOR_EACH(node, &xfif_classes) {
115         const struct registered_xfif_class *registered_class = node->data;
116         if (registered_class->xfif_class.wait) {
117             registered_class->xfif_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 xfif_open(). */
124 int
125 xf_register_provider(const struct xfif_class *new_class)
126 {
127     struct registered_xfif_class *registered_class;
128
129     if (shash_find(&xfif_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->xfif_class, new_class,
137            sizeof registered_class->xfif_class);
138     registered_class->refcount = 0;
139
140     shash_add(&xfif_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 xfifs.  After unregistration
147  * new datapaths of that type cannot be opened using xfif_open(). */
148 int
149 xf_unregister_provider(const char *type)
150 {
151     struct shash_node *node;
152     struct registered_xfif_class *registered_class;
153
154     node = shash_find(&xfif_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(&xfif_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 xf_enumerate_types(struct svec *types)
177 {
178     struct shash_node *node;
179
180     xf_initialize();
181     svec_clear(types);
182
183     SHASH_FOR_EACH(node, &xfif_classes) {
184         const struct registered_xfif_class *registered_class = node->data;
185         svec_add(types, registered_class->xfif_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 xf_enumerate_names(const char *type, struct svec *names)
197 {
198     const struct registered_xfif_class *registered_class;
199     const struct xfif_class *xfif_class;
200     int error;
201
202     xf_initialize();
203     svec_clear(names);
204
205     registered_class = shash_find_data(&xfif_classes, type);
206     if (!registered_class) {
207         VLOG_WARN("could not enumerate unknown type: %s", type);
208         return EAFNOSUPPORT;
209     }
210
211     xfif_class = &registered_class->xfif_class;
212     error = xfif_class->enumerate ? xfif_class->enumerate(names) : 0;
213
214     if (error) {
215         VLOG_WARN("failed to enumerate %s datapaths: %s", xfif_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 xf_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 xfif **xfifp)
243 {
244     struct xfif *xfif = NULL;
245     int error;
246     struct registered_xfif_class *registered_class;
247
248     xf_initialize();
249
250     if (!type || *type == '\0') {
251         type = "system";
252     }
253
254     registered_class = shash_find_data(&xfif_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->xfif_class.open(name, type, create, &xfif);
263     if (!error) {
264         registered_class->refcount++;
265     }
266
267 exit:
268     *xfifp = error ? NULL : xfif;
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 '*xfifp', otherwise a null pointer. */
277 int
278 xfif_open(const char *name, const char *type, struct xfif **xfifp)
279 {
280     return do_open(name, type, false, xfifp);
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 '*xfifp', otherwise a null pointer. */
288 int
289 xfif_create(const char *name, const char *type, struct xfif **xfifp)
290 {
291     return do_open(name, type, true, xfifp);
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 '*xfifp',
298  * otherwise a null pointer. */
299 int
300 xfif_create_and_open(const char *name, const char *type, struct xfif **xfifp)
301 {
302     int error;
303
304     error = xfif_create(name, type, xfifp);
305     if (error == EEXIST || error == EBUSY) {
306         error = xfif_open(name, type, xfifp);
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 'xfif'.  Does not destroy the datapath
318  * itself; call xfif_delete() first, instead, if that is desirable. */
319 void
320 xfif_close(struct xfif *xfif)
321 {
322     if (xfif) {
323         struct registered_xfif_class *registered_class;
324
325         registered_class = shash_find_data(&xfif_classes,
326                 xfif->xfif_class->type);
327         assert(registered_class);
328         assert(registered_class->refcount);
329
330         registered_class->refcount--;
331         xfif_uninit(xfif, true);
332     }
333 }
334
335 /* Returns the name of datapath 'xfif' prefixed with the type
336  * (for use in log messages). */
337 const char *
338 xfif_name(const struct xfif *xfif)
339 {
340     return xfif->full_name;
341 }
342
343 /* Returns the name of datapath 'xfif' without the type
344  * (for use in device names). */
345 const char *
346 xfif_base_name(const struct xfif *xfif)
347 {
348     return xfif->base_name;
349 }
350
351 /* Enumerates all names that may be used to open 'xfif' 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 xfif_get_all_names(const struct xfif *xfif, struct svec *all_names)
362 {
363     if (xfif->xfif_class->get_all_names) {
364         int error = xfif->xfif_class->get_all_names(xfif, all_names);
365         if (error) {
366             VLOG_WARN_RL(&error_rl,
367                          "failed to retrieve names for datpath %s: %s",
368                          xfif_name(xfif), strerror(error));
369         }
370         return error;
371     } else {
372         svec_add(all_names, xfif_base_name(xfif));
373         return 0;
374     }
375 }
376
377 /* Destroys the datapath that 'xfif' is connected to, first removing all of its
378  * ports.  After calling this function, it does not make sense to pass 'xfif'
379  * to any functions other than xfif_name() or xfif_close(). */
380 int
381 xfif_delete(struct xfif *xfif)
382 {
383     int error;
384
385     COVERAGE_INC(xfif_destroy);
386
387     error = xfif->xfif_class->destroy(xfif);
388     log_operation(xfif, "delete", error);
389     return error;
390 }
391
392 /* Retrieves statistics for 'xfif' into 'stats'.  Returns 0 if successful,
393  * otherwise a positive errno value. */
394 int
395 xfif_get_xf_stats(const struct xfif *xfif, struct xflow_stats *stats)
396 {
397     int error = xfif->xfif_class->get_stats(xfif, stats);
398     if (error) {
399         memset(stats, 0, sizeof *stats);
400     }
401     log_operation(xfif, "get_stats", error);
402     return error;
403 }
404
405 /* Retrieves the current IP fragment handling policy for 'xfif' 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 xfif_get_drop_frags(const struct xfif *xfif, bool *drop_frags)
412 {
413     int error = xfif->xfif_class->get_drop_frags(xfif, drop_frags);
414     if (error) {
415         *drop_frags = false;
416     }
417     log_operation(xfif, "get_drop_frags", error);
418     return error;
419 }
420
421 /* Changes 'xfif''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 xfif_set_drop_frags(struct xfif *xfif, bool drop_frags)
426 {
427     int error = xfif->xfif_class->set_drop_frags(xfif, drop_frags);
428     log_operation(xfif, "set_drop_frags", error);
429     return error;
430 }
431
432 /* Attempts to add 'devname' as a port on 'xfif', given the combination of
433  * XFLOW_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 xfif_port_add(struct xfif *xfif, const char *devname, uint16_t flags,
439               uint16_t *port_nop)
440 {
441     uint16_t port_no;
442     int error;
443
444     COVERAGE_INC(xfif_port_add);
445
446     error = xfif->xfif_class->port_add(xfif, devname, flags, &port_no);
447     if (!error) {
448         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
449                     xfif_name(xfif), devname, port_no);
450     } else {
451         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
452                      xfif_name(xfif), 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 'xfif''s port number 'port_no'.  Returns 0 if successful,
462  * otherwise a positive errno value. */
463 int
464 xfif_port_del(struct xfif *xfif, uint16_t port_no)
465 {
466     int error;
467
468     COVERAGE_INC(xfif_port_del);
469
470     error = xfif->xfif_class->port_del(xfif, port_no);
471     log_operation(xfif, "port_del", error);
472     return error;
473 }
474
475 /* Looks up port number 'port_no' in 'xfif'.  On success, returns 0 and
476  * initializes '*port' appropriately; on failure, returns a positive errno
477  * value. */
478 int
479 xfif_port_query_by_number(const struct xfif *xfif, uint16_t port_no,
480                           struct xflow_port *port)
481 {
482     int error = xfif->xfif_class->port_query_by_number(xfif, port_no, port);
483     if (!error) {
484         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
485                     xfif_name(xfif), 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                      xfif_name(xfif), port_no, strerror(error));
490     }
491     return error;
492 }
493
494 /* Looks up port named 'devname' in 'xfif'.  On success, returns 0 and
495  * initializes '*port' appropriately; on failure, returns a positive errno
496  * value. */
497 int
498 xfif_port_query_by_name(const struct xfif *xfif, const char *devname,
499                         struct xflow_port *port)
500 {
501     int error = xfif->xfif_class->port_query_by_name(xfif, devname, port);
502     if (!error) {
503         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
504                     xfif_name(xfif), 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 'xfif' 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                     xfif_name(xfif), devname, strerror(error));
513     }
514     return error;
515 }
516
517 /* Looks up port number 'port_no' in 'xfif'.  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 xfif_port_get_name(struct xfif *xfif, uint16_t port_no,
523                    char *name, size_t name_size)
524 {
525     struct xflow_port port;
526     int error;
527
528     assert(name_size > 0);
529
530     error = xfif_port_query_by_number(xfif, 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 'xfif'.
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 xfif_port_list(const struct xfif *xfif,
550                struct xflow_port **portsp, size_t *n_portsp)
551 {
552     struct xflow_port *ports;
553     size_t n_ports = 0;
554     int error;
555
556     for (;;) {
557         struct xflow_stats stats;
558         int retval;
559
560         error = xfif_get_xf_stats(xfif, &stats);
561         if (error) {
562             goto exit;
563         }
564
565         ports = xcalloc(stats.n_ports, sizeof *ports);
566         retval = xfif->xfif_class->port_list(xfif, 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(xfif, "port_list", error);
592     return error;
593 }
594
595 /* Polls for changes in the set of ports in 'xfif'.  If the set of ports in
596  * 'xfif' has changed, this function does one of the following:
597  *
598  * - Stores the name of the device that was added to or deleted from 'xfif' 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 'xfif' has not changed.  May also
609  * return other positive errno values to indicate that something has gone
610  * wrong. */
611 int
612 xfif_port_poll(const struct xfif *xfif, char **devnamep)
613 {
614     int error = xfif->xfif_class->port_poll(xfif, 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(xfif) will return a
622  * value other than EAGAIN. */
623 void
624 xfif_port_poll_wait(const struct xfif *xfif)
625 {
626     xfif->xfif_class->port_poll_wait(xfif);
627 }
628
629 /* Retrieves a list of the port numbers in port group 'group' in 'xfif'.
630  *
631  * On success, returns 0 and points '*ports' to a newly allocated array of
632  * integers, each of which is a 'xfif' port number for a port in
633  * 'group'.  Stores the number of elements in the array in '*n_ports'.  The
634  * caller is responsible for freeing '*ports' by calling free().
635  *
636  * On failure, returns a positive errno value and sets '*ports' to NULL and
637  * '*n_ports' to 0. */
638 int
639 xfif_port_group_get(const struct xfif *xfif, uint16_t group,
640                     uint16_t **ports, size_t *n_ports)
641 {
642     int error;
643
644     *ports = NULL;
645     *n_ports = 0;
646     for (;;) {
647         int retval = xfif->xfif_class->port_group_get(xfif, group,
648                                                       *ports, *n_ports);
649         if (retval < 0) {
650             /* Hard error. */
651             error = -retval;
652             free(*ports);
653             *ports = NULL;
654             *n_ports = 0;
655             break;
656         } else if (retval <= *n_ports) {
657             /* Success. */
658             error = 0;
659             *n_ports = retval;
660             break;
661         } else {
662             /* Soft error: there were more ports than we expected in the
663              * group.  Try again. */
664             free(*ports);
665             *ports = xcalloc(retval, sizeof **ports);
666             *n_ports = retval;
667         }
668     }
669     log_operation(xfif, "port_group_get", error);
670     return error;
671 }
672
673 /* Updates port group 'group' in 'xfif', making it contain the 'n_ports' ports
674  * whose 'xfif' port numbers are given in 'n_ports'.  Returns 0 if
675  * successful, otherwise a positive errno value.
676  *
677  * Behavior is undefined if the values in ports[] are not unique. */
678 int
679 xfif_port_group_set(struct xfif *xfif, uint16_t group,
680                     const uint16_t ports[], size_t n_ports)
681 {
682     int error;
683
684     COVERAGE_INC(xfif_port_group_set);
685
686     error = xfif->xfif_class->port_group_set(xfif, group, ports, n_ports);
687     log_operation(xfif, "port_group_set", error);
688     return error;
689 }
690
691 /* Deletes all flows from 'xfif'.  Returns 0 if successful, otherwise a
692  * positive errno value.  */
693 int
694 xfif_flow_flush(struct xfif *xfif)
695 {
696     int error;
697
698     COVERAGE_INC(xfif_flow_flush);
699
700     error = xfif->xfif_class->flow_flush(xfif);
701     log_operation(xfif, "flow_flush", error);
702     return error;
703 }
704
705 /* Queries 'xfif' for a flow entry matching 'flow->key'.
706  *
707  * If a flow matching 'flow->key' exists in 'xfif', stores statistics for the
708  * flow into 'flow->stats'.  If 'flow->n_actions' is zero, then 'flow->actions'
709  * is ignored.  If 'flow->n_actions' is nonzero, then 'flow->actions' should
710  * point to an array of the specified number of actions.  At most that many of
711  * the flow's actions will be copied into that array.  'flow->n_actions' will
712  * be updated to the number of actions actually present in the flow, which may
713  * be greater than the number stored if the flow has more actions than space
714  * available in the array.
715  *
716  * If no flow matching 'flow->key' exists in 'xfif', returns ENOENT.  On other
717  * failure, returns a positive errno value. */
718 int
719 xfif_flow_get(const struct xfif *xfif, struct xflow_flow *flow)
720 {
721     int error;
722
723     COVERAGE_INC(xfif_flow_get);
724
725     check_rw_xflow_flow(flow);
726     error = xfif->xfif_class->flow_get(xfif, flow, 1);
727     if (!error) {
728         error = flow->stats.error;
729     }
730     if (error) {
731         /* Make the results predictable on error. */
732         memset(&flow->stats, 0, sizeof flow->stats);
733         flow->n_actions = 0;
734     }
735     if (should_log_flow_message(error)) {
736         log_flow_operation(xfif, "flow_get", error, flow);
737     }
738     return error;
739 }
740
741 /* For each flow 'flow' in the 'n' flows in 'flows':
742  *
743  * - If a flow matching 'flow->key' exists in 'xfif':
744  *
745  *     Stores 0 into 'flow->stats.error' and stores statistics for the flow
746  *     into 'flow->stats'.
747  *
748  *     If 'flow->n_actions' is zero, then 'flow->actions' is ignored.  If
749  *     'flow->n_actions' is nonzero, then 'flow->actions' should point to an
750  *     array of the specified number of actions.  At most that many of the
751  *     flow's actions will be copied into that array.  'flow->n_actions' will
752  *     be updated to the number of actions actually present in the flow, which
753  *     may be greater than the number stored if the flow has more actions than
754  *     space available in the array.
755  *
756  * - Flow-specific errors are indicated by a positive errno value in
757  *   'flow->stats.error'.  In particular, ENOENT indicates that no flow
758  *   matching 'flow->key' exists in 'xfif'.  When an error value is stored, the
759  *   contents of 'flow->key' are preserved but other members of 'flow' should
760  *   be treated as indeterminate.
761  *
762  * Returns 0 if all 'n' flows in 'flows' were updated (whether they were
763  * individually successful or not is indicated by 'flow->stats.error',
764  * however).  Returns a positive errno value if an error that prevented this
765  * update occurred, in which the caller must not depend on any elements in
766  * 'flows' being updated or not updated.
767  */
768 int
769 xfif_flow_get_multiple(const struct xfif *xfif,
770                        struct xflow_flow flows[], size_t n)
771 {
772     int error;
773     size_t i;
774
775     COVERAGE_ADD(xfif_flow_get, n);
776
777     for (i = 0; i < n; i++) {
778         check_rw_xflow_flow(&flows[i]);
779     }
780
781     error = xfif->xfif_class->flow_get(xfif, flows, n);
782     log_operation(xfif, "flow_get_multiple", error);
783     return error;
784 }
785
786 /* Adds or modifies a flow in 'xfif' as specified in 'put':
787  *
788  * - If the flow specified in 'put->flow' does not exist in 'xfif', then
789  *   behavior depends on whether XFLOWPF_CREATE is specified in 'put->flags': if
790  *   it is, the flow will be added, otherwise the operation will fail with
791  *   ENOENT.
792  *
793  * - Otherwise, the flow specified in 'put->flow' does exist in 'xfif'.
794  *   Behavior in this case depends on whether XFLOWPF_MODIFY is specified in
795  *   'put->flags': if it is, the flow's actions will be updated, otherwise the
796  *   operation will fail with EEXIST.  If the flow's actions are updated, then
797  *   its statistics will be zeroed if XFLOWPF_ZERO_STATS is set in 'put->flags',
798  *   left as-is otherwise.
799  *
800  * Returns 0 if successful, otherwise a positive errno value.
801  */
802 int
803 xfif_flow_put(struct xfif *xfif, struct xflow_flow_put *put)
804 {
805     int error;
806
807     COVERAGE_INC(xfif_flow_put);
808
809     error = xfif->xfif_class->flow_put(xfif, put);
810     if (should_log_flow_message(error)) {
811         log_flow_put(xfif, error, put);
812     }
813     return error;
814 }
815
816 /* Deletes a flow matching 'flow->key' from 'xfif' or returns ENOENT if 'xfif'
817  * does not contain such a flow.
818  *
819  * If successful, updates 'flow->stats', 'flow->n_actions', and 'flow->actions'
820  * as described for xfif_flow_get(). */
821 int
822 xfif_flow_del(struct xfif *xfif, struct xflow_flow *flow)
823 {
824     int error;
825
826     COVERAGE_INC(xfif_flow_del);
827
828     check_rw_xflow_flow(flow);
829     memset(&flow->stats, 0, sizeof flow->stats);
830
831     error = xfif->xfif_class->flow_del(xfif, flow);
832     if (should_log_flow_message(error)) {
833         log_flow_operation(xfif, "delete flow", error, flow);
834     }
835     return error;
836 }
837
838 /* Stores up to 'n' flows in 'xfif' into 'flows', including their statistics
839  * but not including any information about their actions.  If successful,
840  * returns 0 and sets '*n_out' to the number of flows actually present in
841  * 'xfif', which might be greater than the number stored (if 'xfif' has more
842  * than 'n' flows).  On failure, returns a negative errno value and sets
843  * '*n_out' to 0. */
844 int
845 xfif_flow_list(const struct xfif *xfif, struct xflow_flow flows[], size_t n,
846                size_t *n_out)
847 {
848     uint32_t i;
849     int retval;
850
851     COVERAGE_INC(xfif_flow_query_list);
852     if (RUNNING_ON_VALGRIND) {
853         memset(flows, 0, n * sizeof *flows);
854     } else {
855         for (i = 0; i < n; i++) {
856             flows[i].actions = NULL;
857             flows[i].n_actions = 0;
858         }
859     }
860     retval = xfif->xfif_class->flow_list(xfif, flows, n);
861     if (retval < 0) {
862         *n_out = 0;
863         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
864                      xfif_name(xfif), strerror(-retval));
865         return -retval;
866     } else {
867         COVERAGE_ADD(xfif_flow_query_list_n, retval);
868         *n_out = MIN(n, retval);
869         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows (of %d)",
870                     xfif_name(xfif), *n_out, retval);
871         return 0;
872     }
873 }
874
875 /* Retrieves all of the flows in 'xfif'.
876  *
877  * If successful, returns 0 and stores in '*flowsp' a pointer to a newly
878  * allocated array of flows, including their statistics but not including any
879  * information about their actions, and sets '*np' to the number of flows in
880  * '*flowsp'.  The caller is responsible for freeing '*flowsp' by calling
881  * free().
882  *
883  * On failure, returns a positive errno value and sets '*flowsp' to NULL and
884  * '*np' to 0. */
885 int
886 xfif_flow_list_all(const struct xfif *xfif,
887                    struct xflow_flow **flowsp, size_t *np)
888 {
889     struct xflow_stats stats;
890     struct xflow_flow *flows;
891     size_t n_flows;
892     int error;
893
894     *flowsp = NULL;
895     *np = 0;
896
897     error = xfif_get_xf_stats(xfif, &stats);
898     if (error) {
899         return error;
900     }
901
902     flows = xmalloc(sizeof *flows * stats.n_flows);
903     error = xfif_flow_list(xfif, flows, stats.n_flows, &n_flows);
904     if (error) {
905         free(flows);
906         return error;
907     }
908
909     if (stats.n_flows != n_flows) {
910         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
911                      "flows but flow listing reported %zu",
912                      xfif_name(xfif), stats.n_flows, n_flows);
913     }
914     *flowsp = flows;
915     *np = n_flows;
916     return 0;
917 }
918
919 /* Causes 'xfif' to perform the 'n_actions' actions in 'actions' on the
920  * Ethernet frame specified in 'packet'.
921  *
922  * Pretends that the frame was originally received on the port numbered
923  * 'in_port'.  This affects only XFLOWAT_OUTPUT_GROUP actions, which will not
924  * send a packet out their input port.  Specify the number of an unused port
925  * (e.g. UINT16_MAX is currently always unused) to avoid this behavior.
926  *
927  * Returns 0 if successful, otherwise a positive errno value. */
928 int
929 xfif_execute(struct xfif *xfif, uint16_t in_port,
930              const union xflow_action actions[], size_t n_actions,
931              const struct ofpbuf *buf)
932 {
933     int error;
934
935     COVERAGE_INC(xfif_execute);
936     if (n_actions > 0) {
937         error = xfif->xfif_class->execute(xfif, in_port, actions,
938                                           n_actions, buf);
939     } else {
940         error = 0;
941     }
942
943     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
944         struct ds ds = DS_EMPTY_INITIALIZER;
945         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
946         ds_put_format(&ds, "%s: execute ", xfif_name(xfif));
947         format_xflow_actions(&ds, actions, n_actions);
948         if (error) {
949             ds_put_format(&ds, " failed (%s)", strerror(error));
950         }
951         ds_put_format(&ds, " on packet %s", packet);
952         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
953         ds_destroy(&ds);
954         free(packet);
955     }
956     return error;
957 }
958
959 /* Retrieves 'xfif''s "listen mask" into '*listen_mask'.  Each XFLOWL_* bit set
960  * in '*listen_mask' indicates that xfif_recv() will receive messages of that
961  * type.  Returns 0 if successful, otherwise a positive errno value. */
962 int
963 xfif_recv_get_mask(const struct xfif *xfif, int *listen_mask)
964 {
965     int error = xfif->xfif_class->recv_get_mask(xfif, listen_mask);
966     if (error) {
967         *listen_mask = 0;
968     }
969     log_operation(xfif, "recv_get_mask", error);
970     return error;
971 }
972
973 /* Sets 'xfif''s "listen mask" to 'listen_mask'.  Each XFLOWL_* bit set in
974  * '*listen_mask' requests that xfif_recv() receive messages of that type.
975  * Returns 0 if successful, otherwise a positive errno value. */
976 int
977 xfif_recv_set_mask(struct xfif *xfif, int listen_mask)
978 {
979     int error = xfif->xfif_class->recv_set_mask(xfif, listen_mask);
980     log_operation(xfif, "recv_set_mask", error);
981     return error;
982 }
983
984 /* Retrieve the sFlow sampling probability.  '*probability' is expressed as the
985  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
986  * the probability of sampling a given packet.
987  *
988  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
989  * indicates that 'xfif' does not support sFlow sampling. */
990 int
991 xfif_get_sflow_probability(const struct xfif *xfif, uint32_t *probability)
992 {
993     int error = (xfif->xfif_class->get_sflow_probability
994                  ? xfif->xfif_class->get_sflow_probability(xfif, probability)
995                  : EOPNOTSUPP);
996     if (error) {
997         *probability = 0;
998     }
999     log_operation(xfif, "get_sflow_probability", error);
1000     return error;
1001 }
1002
1003 /* Set the sFlow sampling probability.  'probability' is expressed as the
1004  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
1005  * the probability of sampling a given packet.
1006  *
1007  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
1008  * indicates that 'xfif' does not support sFlow sampling. */
1009 int
1010 xfif_set_sflow_probability(struct xfif *xfif, uint32_t probability)
1011 {
1012     int error = (xfif->xfif_class->set_sflow_probability
1013                  ? xfif->xfif_class->set_sflow_probability(xfif, probability)
1014                  : EOPNOTSUPP);
1015     log_operation(xfif, "set_sflow_probability", error);
1016     return error;
1017 }
1018
1019 /* Attempts to receive a message from 'xfif'.  If successful, stores the
1020  * message into '*packetp'.  The message, if one is received, will begin with
1021  * 'struct xflow_msg' as a header, and will have at least XFIF_RECV_MSG_PADDING
1022  * bytes of headroom.  Only messages of the types selected with
1023  * xfif_set_listen_mask() will ordinarily be received (but if a message type is
1024  * enabled and then later disabled, some stragglers might pop up).
1025  *
1026  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
1027  * if no message is immediately available. */
1028 int
1029 xfif_recv(struct xfif *xfif, struct ofpbuf **packetp)
1030 {
1031     int error = xfif->xfif_class->recv(xfif, packetp);
1032     if (!error) {
1033         struct ofpbuf *buf = *packetp;
1034
1035         assert(ofpbuf_headroom(buf) >= XFIF_RECV_MSG_PADDING);
1036         if (VLOG_IS_DBG_ENABLED()) {
1037             struct xflow_msg *msg = buf->data;
1038             void *payload = msg + 1;
1039             size_t payload_len = buf->size - sizeof *msg;
1040             char *s = ofp_packet_to_string(payload, payload_len, payload_len);
1041             VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
1042                         "%zu on port %"PRIu16": %s", xfif_name(xfif),
1043                         (msg->type == _XFLOWL_MISS_NR ? "miss"
1044                          : msg->type == _XFLOWL_ACTION_NR ? "action"
1045                          : msg->type == _XFLOWL_SFLOW_NR ? "sFlow"
1046                          : "<unknown>"),
1047                         payload_len, msg->port, s);
1048             free(s);
1049         }
1050     } else {
1051         *packetp = NULL;
1052     }
1053     return error;
1054 }
1055
1056 /* Discards all messages that would otherwise be received by xfif_recv() on
1057  * 'xfif'.  Returns 0 if successful, otherwise a positive errno value. */
1058 int
1059 xfif_recv_purge(struct xfif *xfif)
1060 {
1061     struct xflow_stats stats;
1062     unsigned int i;
1063     int error;
1064
1065     COVERAGE_INC(xfif_purge);
1066
1067     error = xfif_get_xf_stats(xfif, &stats);
1068     if (error) {
1069         return error;
1070     }
1071
1072     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue + stats.max_sflow_queue; i++) {
1073         struct ofpbuf *buf;
1074         error = xfif_recv(xfif, &buf);
1075         if (error) {
1076             return error == EAGAIN ? 0 : error;
1077         }
1078         ofpbuf_delete(buf);
1079     }
1080     return 0;
1081 }
1082
1083 /* Arranges for the poll loop to wake up when 'xfif' has a message queued to be
1084  * received with xfif_recv(). */
1085 void
1086 xfif_recv_wait(struct xfif *xfif)
1087 {
1088     xfif->xfif_class->recv_wait(xfif);
1089 }
1090
1091 /* Obtains the NetFlow engine type and engine ID for 'xfif' into '*engine_type'
1092  * and '*engine_id', respectively. */
1093 void
1094 xfif_get_netflow_ids(const struct xfif *xfif,
1095                      uint8_t *engine_type, uint8_t *engine_id)
1096 {
1097     *engine_type = xfif->netflow_engine_type;
1098     *engine_id = xfif->netflow_engine_id;
1099 }
1100
1101 /* Translates OpenFlow queue ID 'queue_id' (in host byte order) into a priority
1102  * value for use in the ODPAT_SET_PRIORITY action.  On success, returns 0 and
1103  * stores the priority into '*priority'.  On failure, returns a positive errno
1104  * value and stores 0 into '*priority'. */
1105 int
1106 xfif_queue_to_priority(const struct xfif *xfif, uint32_t queue_id,
1107                        uint32_t *priority)
1108 {
1109     int error = (xfif->xfif_class->queue_to_priority
1110                  ? xfif->xfif_class->queue_to_priority(xfif, queue_id,
1111                                                        priority)
1112                  : EOPNOTSUPP);
1113     if (error) {
1114         *priority = 0;
1115     }
1116     log_operation(xfif, "queue_to_priority", error);
1117     return error;
1118 }
1119 \f
1120 void
1121 xfif_init(struct xfif *xfif, const struct xfif_class *xfif_class,
1122           const char *name,
1123           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
1124 {
1125     xfif->xfif_class = xfif_class;
1126     xfif->base_name = xstrdup(name);
1127     xfif->full_name = xasprintf("%s@%s", xfif_class->type, name);
1128     xfif->netflow_engine_type = netflow_engine_type;
1129     xfif->netflow_engine_id = netflow_engine_id;
1130 }
1131
1132 /* Undoes the results of initialization.
1133  *
1134  * Normally this function only needs to be called from xfif_close().
1135  * However, it may be called by providers due to an error on opening
1136  * that occurs after initialization.  In this case xfif_close() would
1137  * never be called. */
1138 void
1139 xfif_uninit(struct xfif *xfif, bool close)
1140 {
1141     char *base_name = xfif->base_name;
1142     char *full_name = xfif->full_name;
1143
1144     if (close) {
1145         xfif->xfif_class->close(xfif);
1146     }
1147
1148     free(base_name);
1149     free(full_name);
1150 }
1151 \f
1152 static void
1153 log_operation(const struct xfif *xfif, const char *operation, int error)
1154 {
1155     if (!error) {
1156         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", xfif_name(xfif), operation);
1157     } else if (is_errno(error)) {
1158         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
1159                      xfif_name(xfif), operation, strerror(error));
1160     } else {
1161         VLOG_WARN_RL(&error_rl, "%s: %s failed (%d/%d)",
1162                      xfif_name(xfif), operation,
1163                      get_ofp_err_type(error), get_ofp_err_code(error));
1164     }
1165 }
1166
1167 static enum vlog_level
1168 flow_message_log_level(int error)
1169 {
1170     return error ? VLL_WARN : VLL_DBG;
1171 }
1172
1173 static bool
1174 should_log_flow_message(int error)
1175 {
1176     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
1177                              error ? &error_rl : &dpmsg_rl);
1178 }
1179
1180 static void
1181 log_flow_message(const struct xfif *xfif, int error, const char *operation,
1182                  const struct xflow_key *flow,
1183                  const struct xflow_flow_stats *stats,
1184                  const union xflow_action *actions, size_t n_actions)
1185 {
1186     struct ds ds = DS_EMPTY_INITIALIZER;
1187     ds_put_format(&ds, "%s: ", xfif_name(xfif));
1188     if (error) {
1189         ds_put_cstr(&ds, "failed to ");
1190     }
1191     ds_put_format(&ds, "%s ", operation);
1192     if (error) {
1193         ds_put_format(&ds, "(%s) ", strerror(error));
1194     }
1195     format_xflow_key(&ds, flow);
1196     if (stats) {
1197         ds_put_cstr(&ds, ", ");
1198         format_xflow_flow_stats(&ds, stats);
1199     }
1200     if (actions || n_actions) {
1201         ds_put_cstr(&ds, ", actions:");
1202         format_xflow_actions(&ds, actions, n_actions);
1203     }
1204     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
1205     ds_destroy(&ds);
1206 }
1207
1208 static void
1209 log_flow_operation(const struct xfif *xfif, const char *operation, int error,
1210                    struct xflow_flow *flow)
1211 {
1212     if (error) {
1213         flow->n_actions = 0;
1214     }
1215     log_flow_message(xfif, error, operation, &flow->key,
1216                      !error ? &flow->stats : NULL,
1217                      flow->actions, flow->n_actions);
1218 }
1219
1220 static void
1221 log_flow_put(struct xfif *xfif, int error, const struct xflow_flow_put *put)
1222 {
1223     enum { XFLOWPF_ALL = XFLOWPF_CREATE | XFLOWPF_MODIFY | XFLOWPF_ZERO_STATS };
1224     struct ds s;
1225
1226     ds_init(&s);
1227     ds_put_cstr(&s, "put");
1228     if (put->flags & XFLOWPF_CREATE) {
1229         ds_put_cstr(&s, "[create]");
1230     }
1231     if (put->flags & XFLOWPF_MODIFY) {
1232         ds_put_cstr(&s, "[modify]");
1233     }
1234     if (put->flags & XFLOWPF_ZERO_STATS) {
1235         ds_put_cstr(&s, "[zero]");
1236     }
1237     if (put->flags & ~XFLOWPF_ALL) {
1238         ds_put_format(&s, "[%x]", put->flags & ~XFLOWPF_ALL);
1239     }
1240     log_flow_message(xfif, error, ds_cstr(&s), &put->flow.key,
1241                      !error ? &put->flow.stats : NULL,
1242                      put->flow.actions, put->flow.n_actions);
1243     ds_destroy(&s);
1244 }
1245
1246 /* There is a tendency to construct xflow_flow objects on the stack and to
1247  * forget to properly initialize their "actions" and "n_actions" members.
1248  * When this happens, we get memory corruption because the kernel
1249  * writes through the random pointer that is in the "actions" member.
1250  *
1251  * This function attempts to combat the problem by:
1252  *
1253  *      - Forcing a segfault if "actions" points to an invalid region (instead
1254  *        of just getting back EFAULT, which can be easily missed in the log).
1255  *
1256  *      - Storing a distinctive value that is likely to cause an
1257  *        easy-to-identify error later if it is dereferenced, etc.
1258  *
1259  *      - Triggering a warning on uninitialized memory from Valgrind if
1260  *        "actions" or "n_actions" was not initialized.
1261  */
1262 static void
1263 check_rw_xflow_flow(struct xflow_flow *flow)
1264 {
1265     if (flow->n_actions) {
1266         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
1267     }
1268 }