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