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