Merge "master" into "wdp".
[sliver-openvswitch.git] / ofproto / wdp.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 "wdp-provider.h"
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "flow.h"
30 #include "netdev.h"
31 #include "netlink.h"
32 #include "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 "timeval.h"
39 #include "util.h"
40 #include "valgrind.h"
41 #include "wdp-xflow.h"
42
43 #include "vlog.h"
44 #define THIS_MODULE VLM_wdp
45 \f
46 /* wdp_rule */
47
48 /* Initializes a new 'struct wdp_rule', copying in the 'n_actions' elements of
49  * 'actions'.
50  *
51  * The caller is responsible for initializing 'rule->cr'. */
52 void
53 wdp_rule_init(struct wdp_rule *rule, const union ofp_action *actions,
54               size_t n_actions)
55 {
56     rule->actions = xmemdup(actions, n_actions * sizeof *actions);
57     rule->n_actions = n_actions;
58     rule->created = time_msec();
59     rule->idle_timeout = 0;
60     rule->hard_timeout = 0;
61     rule->client_data = NULL;
62 }
63
64 /* Frees the data in 'rule'. */
65 void
66 wdp_rule_uninit(struct wdp_rule *rule)
67 {
68     free(rule->actions);
69 }
70 \f
71 /* wdp */
72
73 static const struct wdp_class *base_wdp_classes[] = {
74     /* XXX none yet */
75 };
76
77 struct registered_wdp_class {
78     const struct wdp_class *wdp_class;
79     int refcount;
80 };
81
82 static struct shash wdp_classes = SHASH_INITIALIZER(&wdp_classes);
83
84 /* Rate limit for individual messages going to or from the datapath, output at
85  * DBG level.  This is very high because, if these are enabled, it is because
86  * we really need to see them. */
87 static struct vlog_rate_limit wdpmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
88
89 /* Not really much point in logging many wdp errors. */
90 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
91
92 static void log_operation(const struct wdp *, const char *operation,
93                           int error);
94
95 static void
96 wdp_initialize(void)
97 {
98     static int status = -1;
99
100     if (status < 0) {
101         int i;
102
103         status = 0;
104         for (i = 0; i < ARRAY_SIZE(base_wdp_classes); i++) {
105             wdp_register_provider(base_wdp_classes[i]);
106         }
107         wdp_xflow_register();
108     }
109 }
110
111 /* Performs periodic work needed by all the various kinds of wdps.
112  *
113  * If your program opens any wdps, it must call both this function and
114  * netdev_run() within its main poll loop. */
115 void
116 wdp_run(void)
117 {
118     struct shash_node *node;
119     SHASH_FOR_EACH (node, &wdp_classes) {
120         const struct registered_wdp_class *registered_class = node->data;
121         if (registered_class->wdp_class->run) {
122             registered_class->wdp_class->run();
123         }
124     }
125 }
126
127 /* Arranges for poll_block() to wake up when wdp_run() needs to be called.
128  *
129  * If your program opens any wdps, it must call both this function and
130  * netdev_wait() within its main poll loop. */
131 void
132 wdp_wait(void)
133 {
134     struct shash_node *node;
135     SHASH_FOR_EACH(node, &wdp_classes) {
136         const struct registered_wdp_class *registered_class = node->data;
137         if (registered_class->wdp_class->wait) {
138             registered_class->wdp_class->wait();
139         }
140     }
141 }
142
143 /* Registers a new datapath provider.  After successful registration, new
144  * datapaths of that type can be opened using wdp_open(). */
145 int
146 wdp_register_provider(const struct wdp_class *new_class)
147 {
148     struct registered_wdp_class *registered_class;
149
150     if (shash_find(&wdp_classes, new_class->type)) {
151         VLOG_WARN("attempted to register duplicate datapath provider: %s",
152                   new_class->type);
153         return EEXIST;
154     }
155
156     registered_class = xmalloc(sizeof *registered_class);
157     registered_class->wdp_class = new_class;
158     registered_class->refcount = 0;
159
160     shash_add(&wdp_classes, new_class->type, registered_class);
161
162     return 0;
163 }
164
165 /* Unregisters a datapath provider.  'type' must have been previously
166  * registered and not currently be in use by any wdps.  After unregistration
167  * new datapaths of that type cannot be opened using wdp_open(). */
168 int
169 wdp_unregister_provider(const char *type)
170 {
171     struct shash_node *node;
172     struct registered_wdp_class *registered_class;
173
174     node = shash_find(&wdp_classes, type);
175     if (!node) {
176         VLOG_WARN("attempted to unregister a datapath provider that is not "
177                   "registered: %s", type);
178         return EAFNOSUPPORT;
179     }
180
181     registered_class = node->data;
182     if (registered_class->refcount) {
183         VLOG_WARN("attempted to unregister in use datapath provider: %s",
184                   type);
185         return EBUSY;
186     }
187
188     shash_delete(&wdp_classes, node);
189     free(registered_class);
190
191     return 0;
192 }
193
194 /* Clears 'types' and enumerates the types of all currently registered wdp
195  * providers into it.  The caller must first initialize the svec. */
196 void
197 wdp_enumerate_types(struct svec *types)
198 {
199     struct shash_node *node;
200
201     wdp_initialize();
202     svec_clear(types);
203
204     SHASH_FOR_EACH (node, &wdp_classes) {
205         const struct registered_wdp_class *registered_class = node->data;
206         svec_add(types, registered_class->wdp_class->type);
207     }
208 }
209
210 /* Clears 'names' and enumerates the names of all known created datapaths
211  * with the given 'type'.  The caller must first initialize the svec. Returns 0
212  * if successful, otherwise a positive errno value.
213  *
214  * Some kinds of datapaths might not be practically enumerable.  This is not
215  * considered an error. */
216 int
217 wdp_enumerate_names(const char *type, struct svec *names)
218 {
219     const struct registered_wdp_class *registered_class;
220     const struct wdp_class *wdp_class;
221     int error;
222
223     wdp_initialize();
224     svec_clear(names);
225
226     registered_class = shash_find_data(&wdp_classes, type);
227     if (!registered_class) {
228         VLOG_WARN("could not enumerate unknown type: %s", type);
229         return EAFNOSUPPORT;
230     }
231
232     wdp_class = registered_class->wdp_class;
233     error = (wdp_class->enumerate
234              ? wdp_class->enumerate(wdp_class, names)
235              : 0);
236
237     if (error) {
238         VLOG_WARN("failed to enumerate %s datapaths: %s", wdp_class->type,
239                   strerror(error));
240     }
241
242     return error;
243 }
244
245 /* Parses 'datapath_name', which is of the form type@name, into its
246  * component pieces.  'name' and 'type' must be freed by the caller. */
247 void
248 wdp_parse_name(const char *datapath_name_, char **name, char **type)
249 {
250     char *datapath_name = xstrdup(datapath_name_);
251     char *separator;
252
253     separator = strchr(datapath_name, '@');
254     if (separator) {
255         *separator = '\0';
256         *type = datapath_name;
257         *name = xstrdup(separator + 1);
258     } else {
259         *name = datapath_name;
260         *type = NULL;
261     }
262 }
263
264 static int
265 do_open(const char *name, const char *type, bool create, struct wdp **wdpp)
266 {
267     struct wdp *wdp = NULL;
268     int error;
269     struct registered_wdp_class *registered_class;
270
271     wdp_initialize();
272
273     if (!type || *type == '\0') {
274         type = "system";
275     }
276
277     registered_class = shash_find_data(&wdp_classes, type);
278     if (!registered_class) {
279         VLOG_WARN("could not create datapath %s of unknown type %s", name,
280                   type);
281         error = EAFNOSUPPORT;
282         goto exit;
283     }
284
285     error = registered_class->wdp_class->open(registered_class->wdp_class,
286                                               name, create, &wdp);
287     if (!error) {
288         registered_class->refcount++;
289     }
290
291 exit:
292     *wdpp = error ? NULL : wdp;
293     return error;
294 }
295
296 /* Tries to open an existing datapath named 'name' and type 'type'.  Will fail
297  * if no datapath with 'name' and 'type' exists.  'type' may be either NULL or
298  * the empty string to specify the default system type.  Returns 0 if
299  * successful, otherwise a positive errno value.  On success stores a pointer
300  * to the datapath in '*wdpp', otherwise a null pointer. */
301 int
302 wdp_open(const char *name, const char *type, struct wdp **wdpp)
303 {
304     return do_open(name, type, false, wdpp);
305 }
306
307 /* Tries to create and open a new datapath with the given 'name' and 'type'.
308  * 'type' may be either NULL or the empty string to specify the default system
309  * type.  Will fail if a datapath with 'name' and 'type' already exists.
310  * Returns 0 if successful, otherwise a positive errno value.  On success
311  * stores a pointer to the datapath in '*wdpp', otherwise a null pointer. */
312 int
313 wdp_create(const char *name, const char *type, struct wdp **wdpp)
314 {
315     return do_open(name, type, true, wdpp);
316 }
317
318 /* Tries to open a datapath with the given 'name' and 'type', creating it if it
319  * does not exist.  'type' may be either NULL or the empty string to specify
320  * the default system type.  Returns 0 if successful, otherwise a positive
321  * errno value. On success stores a pointer to the datapath in '*wdpp',
322  * otherwise a null pointer. */
323 int
324 wdp_create_and_open(const char *name, const char *type, struct wdp **wdpp)
325 {
326     int error;
327
328     error = wdp_create(name, type, wdpp);
329     if (error == EEXIST || error == EBUSY) {
330         error = wdp_open(name, type, wdpp);
331         if (error) {
332             VLOG_WARN("datapath %s already exists but cannot be opened: %s",
333                       name, strerror(error));
334         }
335     } else if (error) {
336         VLOG_WARN("failed to create datapath %s: %s", name, strerror(error));
337     }
338     return error;
339 }
340
341 /* Closes and frees the connection to 'wdp'.  Does not destroy the wdp
342  * itself; call wdp_delete() first, instead, if that is desirable. */
343 void
344 wdp_close(struct wdp *wdp)
345 {
346     if (wdp) {
347         struct registered_wdp_class *registered_class;
348
349         registered_class = shash_find_data(&wdp_classes, 
350                                            wdp->wdp_class->type);
351         assert(registered_class);
352         assert(registered_class->refcount);
353
354         registered_class->refcount--;
355         wdp_uninit(wdp, true);
356     }
357 }
358
359 /* Returns the name of datapath 'wdp' prefixed with the type
360  * (for use in log messages). */
361 const char *
362 wdp_name(const struct wdp *wdp)
363 {
364     return wdp->full_name;
365 }
366
367 /* Returns the name of datapath 'wdp' without the type
368  * (for use in device names). */
369 const char *
370 wdp_base_name(const struct wdp *wdp)
371 {
372     return wdp->base_name;
373 }
374
375 /* Enumerates all names that may be used to open 'wdp' into 'all_names'.  The
376  * Linux datapath, for example, supports opening a datapath both by number,
377  * e.g. "wdp0", and by the name of the datapath's local port.  For some
378  * datapaths, this might be an infinite set (e.g. in a file name, slashes may
379  * be duplicated any number of times), in which case only the names most likely
380  * to be used will be enumerated.
381  *
382  * The caller must already have initialized 'all_names'.  Any existing names in
383  * 'all_names' will not be disturbed. */
384 int
385 wdp_get_all_names(const struct wdp *wdp, struct svec *all_names)
386 {
387     if (wdp->wdp_class->get_all_names) {
388         int error = wdp->wdp_class->get_all_names(wdp, all_names);
389         if (error) {
390             VLOG_WARN_RL(&error_rl,
391                          "failed to retrieve names for datpath %s: %s",
392                          wdp_name(wdp), strerror(error));
393         }
394         return error;
395     } else {
396         svec_add(all_names, wdp_base_name(wdp));
397         return 0;
398     }
399 }
400
401 /* Destroys the datapath that 'wdp' is connected to, first removing all of
402  * its ports.  After calling this function, it does not make sense to pass
403  * 'wdp' to any functions other than wdp_name() or wdp_close(). */
404 int
405 wdp_delete(struct wdp *wdp)
406 {
407     int error;
408
409     COVERAGE_INC(wdp_destroy);
410
411     error = wdp->wdp_class->destroy(wdp);
412     log_operation(wdp, "delete", error);
413     return error;
414 }
415
416 /* Obtains the set of features supported by 'wdp'.
417  *
418  * If successful, returns 0 and stores in '*featuresp' a newly allocated
419  * "struct ofp_switch_features" that describes the features and ports supported
420  * by 'wdp'.  The caller is responsible for initializing the header,
421  * datapath_id, and n_buffers members of the returned "struct
422  * ofp_switch_features".  The caller must free the returned buffer (with
423  * ofpbuf_delete()) when it is no longer needed.
424  *
425  * On error, returns an OpenFlow error code (as constructed by ofp_mkerr()) and
426  * sets '*featuresp' to NULL. */
427 int
428 wdp_get_features(const struct wdp *wdp, struct ofpbuf **featuresp)
429 {
430     int error = wdp->wdp_class->get_features(wdp, featuresp);
431     if (error) {
432         *featuresp = NULL;
433     }
434     return error;
435 }
436
437 /* Retrieves statistics for 'wdp' into 'stats'.  Returns 0 if successful,
438  * otherwise a positive errno value.  On error, clears 'stats' to
439  * all-bits-zero. */
440 int
441 wdp_get_wdp_stats(const struct wdp *wdp, struct wdp_stats *stats)
442 {
443     int error = wdp->wdp_class->get_stats(wdp, stats);
444     if (error) {
445         memset(stats, 0, sizeof *stats);
446     }
447     log_operation(wdp, "get_stats", error);
448     return error;
449 }
450
451 /* Retrieves the current IP fragment handling policy for 'wdp' into
452  * '*drop_frags': true indicates that fragments are dropped, false indicates
453  * that fragments are treated in the same way as other IP packets (except that
454  * the L4 header cannot be read).  Returns 0 if successful, otherwise a
455  * positive errno value. */
456 int
457 wdp_get_drop_frags(const struct wdp *wdp, bool *drop_frags)
458 {
459     int error = wdp->wdp_class->get_drop_frags(wdp, drop_frags);
460     if (error) {
461         *drop_frags = false;
462     }
463     log_operation(wdp, "get_drop_frags", error);
464     return error;
465 }
466
467 /* Changes 'wdp''s treatment of IP fragments to 'drop_frags', whose meaning is
468  * the same as for the get_drop_frags member function.  Returns 0 if
469  * successful, otherwise a positive errno value.  EOPNOTSUPP indicates that
470  * 'wdp''s fragment dropping policy is not configurable. */
471 int
472 wdp_set_drop_frags(struct wdp *wdp, bool drop_frags)
473 {
474     int error;
475     error = (wdp->wdp_class->set_drop_frags
476              ? wdp->wdp_class->set_drop_frags(wdp, drop_frags)
477              : EOPNOTSUPP);
478     log_operation(wdp, "set_drop_frags", error);
479     return error;
480 }
481
482 /* Clears the contents of 'port'. */
483 void
484 wdp_port_clear(struct wdp_port *port)
485 {
486     memset(port, 0, sizeof *port);
487 }
488
489 /* Makes a deep copy of 'old' in 'port'.  The caller may free 'port''s data
490  * with wdp_port_free(). */
491 void
492 wdp_port_copy(struct wdp_port *port, const struct wdp_port *old)
493 {
494     port->netdev = old->netdev ? netdev_reopen(old->netdev) : NULL;
495     port->opp = old->opp;
496     port->devname = old->devname ? xstrdup(old->devname) : NULL;
497     port->internal = old->internal;
498 }
499
500 /* Frees the data that 'port' points to (but not 'port' itself). */
501 void
502 wdp_port_free(struct wdp_port *port)
503 {
504     if (port) {
505         netdev_close(port->netdev);
506         free(port->devname);
507     }
508 }
509
510 /* Frees the data that each of the 'n' ports in 'ports' points to, and then
511  * frees 'ports' itself. */
512 void
513 wdp_port_array_free(struct wdp_port *ports, size_t n)
514 {
515     size_t i;
516
517     for (i = 0; i < n; i++) {
518         wdp_port_free(&ports[i]);
519     }
520     free(ports);
521 }
522
523 /* Attempts to add 'devname' as a port on 'wdp':
524  *
525  *   - If 'internal' is true, attempts to create a new internal port (a virtual
526  *     port implemented in software) by that name.
527  *
528  *   - If 'internal' is false, 'devname' must name an existing network device.
529  *
530  * If successful, returns 0 and sets '*port_nop' to the new port's OpenFlow
531  * port number (if 'port_nop' is non-null).  On failure, returns a positive
532  * errno value and sets '*port_nop' to OFPP_NONE (if 'port_nop' is non-null).
533  *
534  * Some wildcarded datapaths might have fixed sets of ports.  For these
535  * datapaths this function will always fail.
536  *
537  * Possible error return values include:
538  *
539  *   - ENODEV: No device named 'devname' exists (if 'internal' is false).
540  *
541  *   - EEXIST: A device named 'devname' already exists (if 'internal' is true).
542  *
543  *   - EINVAL: Device 'devname' is not supported as part of a datapath (e.g. it
544  *     is not an Ethernet device), or 'devname' is too long for a network
545  *     device name (if 'internal' is true)
546  *
547  *   - EFBIG: The datapath already has as many ports as it can support.
548  *
549  *   - EOPNOTSUPP: 'wdp' has a fixed set of ports.
550  */
551 int
552 wdp_port_add(struct wdp *wdp, const char *devname,
553              bool internal, uint16_t *port_nop)
554 {
555     uint16_t port_no;
556     int error;
557
558     COVERAGE_INC(wdp_port_add);
559
560     error = (wdp->wdp_class->port_add
561              ? wdp->wdp_class->port_add(wdp, devname, internal, &port_no)
562              : EOPNOTSUPP);
563     if (!error) {
564         VLOG_DBG_RL(&wdpmsg_rl, "%s: added %s as port %"PRIu16,
565                     wdp_name(wdp), devname, port_no);
566     } else {
567         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
568                      wdp_name(wdp), devname, strerror(error));
569         port_no = OFPP_NONE;
570     }
571     if (port_nop) {
572         *port_nop = port_no;
573     }
574     return error;
575 }
576
577 /* Attempts to remove 'wdp''s port numbered 'port_no'.  Returns 0 if
578  * successful, otherwise a positive errno value.
579  *
580  * Some wildcarded datapaths might have fixed sets of ports.  For these
581  * datapaths this function will always fail.
582  *
583  * Possible error return values include:
584  *
585  *   - EINVAL: 'port_no' is outside the valid range, or this particular port is
586  *     not removable (e.g. it is the local port).
587  *
588  *   - ENOENT: 'wdp' currently has no port numbered 'port_no'.
589  *
590  *   - EOPNOTSUPP: 'wdp' has a fixed set of ports.
591  */
592 int
593 wdp_port_del(struct wdp *wdp, uint16_t port_no)
594 {
595     int error;
596
597     COVERAGE_INC(wdp_port_del);
598
599     error = (wdp->wdp_class->port_del
600              ? wdp->wdp_class->port_del(wdp, port_no)
601              : EOPNOTSUPP);
602     log_operation(wdp, "port_del", error);
603     return error;
604 }
605
606 /* Looks up port number 'port_no' in 'wdp'.  On success, returns 0 and
607  * initializes 'port' with port details.  On failure, returns a positive errno
608  * value and clears the contents of 'port' (with wdp_port_clear()).
609  *
610  * The caller must not modify or free the returned wdp_port.  Calling
611  * wdp_run() or wdp_port_poll() may free the returned wdp_port.
612  *
613  * Possible error return values include:
614  *
615  *   - EINVAL: 'port_no' is outside the valid range.
616  *
617  *   - ENOENT: 'wdp' currently has no port numbered 'port_no'.
618  */
619 int
620 wdp_port_query_by_number(const struct wdp *wdp, uint16_t port_no,
621                          struct wdp_port *port)
622 {
623     int error;
624
625     error = wdp->wdp_class->port_query_by_number(wdp, port_no, port);
626     if (!error) {
627         VLOG_DBG_RL(&wdpmsg_rl, "%s: port %"PRIu16" is device %s",
628                     wdp_name(wdp), port_no, port->devname);
629     } else {
630         wdp_port_clear(port);
631         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
632                      wdp_name(wdp), port_no, strerror(error));
633     }
634     return error;
635 }
636
637 /* Same as wdp_port_query_by_number() except that it look for a port named
638  * 'devname' in 'wdp'.
639  *
640  * Possible error return values include:
641  *
642  *   - ENODEV: No device named 'devname' exists.
643  *
644  *   - ENOENT: 'devname' exists but it is not attached as a port on 'wdp'.
645  */
646 int
647 wdp_port_query_by_name(const struct wdp *wdp, const char *devname,
648                        struct wdp_port *port)
649 {
650     int error = wdp->wdp_class->port_query_by_name(wdp, devname, port);
651     if (!error) {
652         VLOG_DBG_RL(&wdpmsg_rl, "%s: device %s is on port %"PRIu16,
653                     wdp_name(wdp), devname, port->opp.port_no);
654     } else {
655         wdp_port_clear(port);
656
657         /* Log level is DBG here because all the current callers are interested
658          * in whether 'wdp' actually has a port 'devname', so that it's not
659          * an issue worth logging if it doesn't. */
660         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
661                     wdp_name(wdp), devname, strerror(error));
662     }
663     return error;
664 }
665
666 /* Looks up port number 'port_no' in 'wdp'.  On success, returns 0 and stores
667  * a copy of the port's name in '*namep'.  On failure, returns a positive errno
668  * value and stores NULL in '*namep'.
669  *
670  * Error return values are the same as for wdp_port_query_by_name().
671  *
672  * The caller is responsible for freeing '*namep' (with free()). */
673 int
674 wdp_port_get_name(struct wdp *wdp, uint16_t port_no, char **namep)
675 {
676     struct wdp_port port;
677     int error;
678
679     error = wdp_port_query_by_number(wdp, port_no, &port);
680     *namep = port.devname;
681     port.devname = NULL;
682     wdp_port_free(&port);
683
684     return error;
685 }
686
687 /* Obtains a list of all the ports in 'wdp', in no particular order.
688  *
689  * If successful, returns 0 and sets '*portsp' to point to an array of struct
690  * wdp_port and '*n_portsp' to the number of pointers in the array.  On
691  * failure, returns a positive errno value and sets '*portsp' to NULL and
692  * '*n_portsp' to 0.
693  *
694  * The caller is responsible for freeing '*portsp' and the individual wdp_port
695  * structures, e.g. with wdp_port_array_free().  */
696 int
697 wdp_port_list(const struct wdp *wdp,
698               struct wdp_port **portsp, size_t *n_portsp)
699 {
700     int error;
701
702     error = wdp->wdp_class->port_list(wdp, portsp, n_portsp);
703     if (error) {
704         *portsp = NULL;
705         *n_portsp = 0;
706     }
707     log_operation(wdp, "port_list", error);
708     return error;
709 }
710
711 int
712 wdp_port_set_config(struct wdp *wdp, uint16_t port_no, uint32_t config)
713 {
714     return wdp->wdp_class->port_set_config(wdp, port_no, config);
715 }
716
717 /* Polls for changes in the set of ports in 'wdp'.  If the set of ports in
718  * 'wdp' has changed, this function does one of the following:
719  *
720  * - Stores the name of the device that was added to or deleted from 'wdp' in
721  *   '*devnamep' and returns 0.  The caller is responsible for freeing
722  *   '*devnamep' (with free()) when it no longer needs it.
723  *
724  * - Returns ENOBUFS and sets '*devnamep' to NULL.
725  *
726  * This function may also return 'false positives', where it returns 0 and
727  * '*devnamep' names a device that was not actually added or deleted or it
728  * returns ENOBUFS without any change.
729  *
730  * Returns EAGAIN if the set of ports in 'wdp' has not changed.  May also
731  * return other positive errno values to indicate that something has gone
732  * wrong. */
733 int
734 wdp_port_poll(const struct wdp *wdp, char **devnamep)
735 {
736     int error = (wdp->wdp_class->port_poll
737                  ? wdp->wdp_class->port_poll(wdp, devnamep)
738                  : EAGAIN);
739     if (error) {
740         *devnamep = NULL;
741     }
742     return error;
743 }
744
745 /* Arranges for the poll loop to wake up when port_poll(wdp) will return a
746  * value other than EAGAIN. */
747 void
748 wdp_port_poll_wait(const struct wdp *wdp)
749 {
750     if (wdp->wdp_class->port_poll_wait) {
751         wdp->wdp_class->port_poll_wait(wdp);
752     }
753 }
754
755 /* Deletes all flows from 'wdp'.  Returns 0 if successful, otherwise a
756  * positive errno value.  */
757 int
758 wdp_flow_flush(struct wdp *wdp)
759 {
760     int error;
761
762     COVERAGE_INC(wdp_flow_flush);
763
764     error = wdp->wdp_class->flow_flush(wdp);
765     log_operation(wdp, "flow_flush", error);
766     return error;
767 }
768
769 struct wdp_rule *
770 wdp_flow_get(struct wdp *wdp, const flow_t *flow)
771 {
772     return wdp->wdp_class->flow_get(wdp, flow);
773 }
774
775 struct wdp_rule *
776 wdp_flow_match(struct wdp *wdp, const flow_t *flow)
777 {
778     return wdp->wdp_class->flow_match(wdp, flow);
779 }
780
781 void
782 wdp_flow_for_each_match(const struct wdp *wdp, const flow_t *target,
783                         int include, wdp_flow_cb_func *callback, void *aux)
784 {
785     wdp->wdp_class->flow_for_each_match(wdp, target, include,
786                                         callback, aux); 
787 }
788
789 int
790 wdp_flow_get_stats(const struct wdp *wdp, const struct wdp_rule *rule,
791                    struct wdp_flow_stats *stats)
792 {
793     int error = wdp->wdp_class->flow_get_stats(wdp, rule, stats);
794     if (error) {
795         memset(stats, 0, sizeof *stats);
796     }
797     return error;
798 }
799
800 bool
801 wdp_flow_overlaps(const struct wdp *wdp, const flow_t *flow)
802 {
803     return wdp->wdp_class->flow_overlaps(wdp, flow);
804 }
805
806 int
807 wdp_flow_put(struct wdp *wdp, struct wdp_flow_put *put,
808              struct wdp_flow_stats *old_stats, struct wdp_rule **rulep)
809 {
810     int error = wdp->wdp_class->flow_put(wdp, put, old_stats, rulep);
811     if (error) {
812         if (old_stats) {
813             memset(old_stats, 0, sizeof *old_stats);
814         }
815         if (rulep) {
816             *rulep = NULL;
817         }
818     }
819     return error;
820 }
821
822 int
823 wdp_flow_delete(struct wdp *wdp, struct wdp_rule *rule,
824                 struct wdp_flow_stats *final_stats)
825 {
826     int error = wdp->wdp_class->flow_delete(wdp, rule, final_stats);
827     if (error && final_stats) {
828         memset(final_stats, 0, sizeof *final_stats);
829     }
830     return error;
831 }
832
833 int
834 wdp_flow_inject(struct wdp *wdp, struct wdp_rule *rule,
835                 uint16_t in_port, const struct ofpbuf *packet)
836 {
837     return wdp->wdp_class->flow_inject(wdp, rule, in_port, packet);
838 }
839
840 int
841 wdp_execute(struct wdp *wdp, uint16_t in_port,
842             const union ofp_action actions[], size_t n_actions,
843             const struct ofpbuf *buf)
844 {
845     int error;
846
847     COVERAGE_INC(wdp_execute);
848     if (n_actions > 0) {
849         error = wdp->wdp_class->execute(wdp, in_port, actions,
850                                         n_actions, buf);
851     } else {
852         error = 0;
853     }
854     return error;
855 }
856
857 /* Retrieves 'wdp''s "listen mask" into '*listen_mask'.  Each bit set in
858  * '*listen_mask' indicates that wdp_recv() will receive messages of the
859  * corresponding WDP_CHAN_* type.  Returns 0 if successful, otherwise a
860  * positive errno value. */
861 int
862 wdp_recv_get_mask(const struct wdp *wdp, int *listen_mask)
863 {
864     int error = wdp->wdp_class->recv_get_mask(wdp, listen_mask);
865     if (error) {
866         *listen_mask = 0;
867     }
868     log_operation(wdp, "recv_get_mask", error);
869     return error;
870 }
871
872 /* Sets 'wdp''s "listen mask" to 'listen_mask'.  Each bit set in
873  * '*listen_mask' requests that wdp_recv() receive messages of the
874  * corresponding WDP_CHAN_* type.  Returns 0 if successful, otherwise a
875  * positive errno value. */
876 int
877 wdp_recv_set_mask(struct wdp *wdp, int listen_mask)
878 {
879     int error = wdp->wdp_class->recv_set_mask(wdp, listen_mask);
880     log_operation(wdp, "recv_set_mask", error);
881     return error;
882 }
883
884 /* Retrieve the sFlow sampling probability.  '*probability' is expressed as the
885  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
886  * the probability of sampling a given packet.
887  *
888  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
889  * indicates that 'wdp' does not support sFlow sampling. */
890 int
891 wdp_get_sflow_probability(const struct wdp *wdp, uint32_t *probability)
892 {
893     int error = (wdp->wdp_class->get_sflow_probability
894                  ? wdp->wdp_class->get_sflow_probability(wdp, probability)
895                  : EOPNOTSUPP);
896     if (error) {
897         *probability = 0;
898     }
899     log_operation(wdp, "get_sflow_probability", error);
900     return error;
901 }
902
903 /* Set the sFlow sampling probability.  'probability' is expressed as the
904  * number of packets out of UINT_MAX to sample, e.g. probability/UINT_MAX is
905  * the probability of sampling a given packet.
906  *
907  * Returns 0 if successful, otherwise a positive errno value.  EOPNOTSUPP
908  * indicates that 'wdp' does not support sFlow sampling. */
909 int
910 wdp_set_sflow_probability(struct wdp *wdp, uint32_t probability)
911 {
912     int error = (wdp->wdp_class->set_sflow_probability
913                  ? wdp->wdp_class->set_sflow_probability(wdp, probability)
914                  : EOPNOTSUPP);
915     log_operation(wdp, "set_sflow_probability", error);
916     return error;
917 }
918
919 /* Attempts to receive a message from 'wdp'.  If successful, stores the
920  * message into '*packetp'.  Only messages of the types selected with
921  * wdp_set_listen_mask() will ordinarily be received (but if a message type
922  * is enabled and then later disabled, some stragglers might pop up).
923  *
924  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
925  * if no message is immediately available. */
926 int
927 wdp_recv(struct wdp *wdp, struct wdp_packet *packet)
928 {
929     int error = wdp->wdp_class->recv(wdp, packet);
930     if (!error) {
931         /* XXX vlog_dbg received packet */
932     } else {
933         memset(packet, 0, sizeof *packet);
934         packet->channel = -1;
935     }
936     return error;
937 }
938
939 /* Discards all messages that would otherwise be received by wdp_recv() on
940  * 'wdp'.  Returns 0 if successful, otherwise a positive errno value. */
941 int
942 wdp_recv_purge(struct wdp *wdp)
943 {
944     struct wdp_stats stats;
945     unsigned int i;
946     int error;
947
948     COVERAGE_INC(wdp_purge);
949
950     error = wdp_get_wdp_stats(wdp, &stats);
951     if (error) {
952         return error;
953     }
954
955     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue + stats.max_sflow_queue; i++) {
956         struct wdp_packet packet;
957
958         error = wdp_recv(wdp, &packet);
959         if (error) {
960             return error == EAGAIN ? 0 : error;
961         }
962         ofpbuf_delete(packet.payload);
963     }
964     return 0;
965 }
966
967 /* Arranges for the poll loop to wake up when 'wdp' has a message queued to be
968  * received with wdp_recv(). */
969 void
970 wdp_recv_wait(struct wdp *wdp)
971 {
972     wdp->wdp_class->recv_wait(wdp);
973 }
974
975 /* Obtains the NetFlow engine type and engine ID for 'wdp' into '*engine_type'
976  * and '*engine_id', respectively. */
977 void
978 wdp_get_netflow_ids(const struct wdp *wdp,
979                     uint8_t *engine_type, uint8_t *engine_id)
980 {
981     *engine_type = wdp->netflow_engine_type;
982     *engine_id = wdp->netflow_engine_id;
983 }
984 \f
985 /* Returns a copy of 'old'.  The packet's payload, if any, is copied as well,
986  * but if it is longer than 'trim' bytes it is truncated to that length. */
987 struct wdp_packet *
988 wdp_packet_clone(const struct wdp_packet *old, size_t trim)
989 {
990     struct wdp_packet *new = xmemdup(old, sizeof *old);
991     if (old->payload) {
992         new->payload = ofpbuf_clone_data(old->payload->data,
993                                          MIN(trim, old->payload->size));
994     }
995     return new;
996 }
997
998 void
999 wdp_packet_destroy(struct wdp_packet *packet)
1000 {
1001     if (packet) {
1002         ofpbuf_delete(packet->payload);
1003         free(packet);
1004     }
1005 }
1006
1007 void
1008 wdp_init(struct wdp *wdp, const struct wdp_class *wdp_class,
1009          const char *name,
1010          uint8_t netflow_engine_type, uint8_t netflow_engine_id)
1011 {
1012     wdp->wdp_class = wdp_class;
1013     wdp->base_name = xstrdup(name);
1014     wdp->full_name = xasprintf("%s@%s", wdp_class->type, name);
1015     wdp->netflow_engine_type = netflow_engine_type;
1016     wdp->netflow_engine_id = netflow_engine_id;
1017 }
1018
1019 /* Undoes the results of initialization.
1020  *
1021  * Normally this function only needs to be called from wdp_close().
1022  * However, it may be called by providers due to an error on opening
1023  * that occurs after initialization.  It this case wdp_close() would
1024  * never be called. */
1025 void
1026 wdp_uninit(struct wdp *wdp, bool close)
1027 {
1028     char *base_name = wdp->base_name;
1029     char *full_name = wdp->full_name;
1030
1031     if (close) {
1032         wdp->wdp_class->close(wdp);
1033     }
1034
1035     free(base_name);
1036     free(full_name);
1037 }
1038 \f
1039 static void
1040 log_operation(const struct wdp *wdp, const char *operation, int error)
1041 {
1042     if (!error) {
1043         VLOG_DBG_RL(&wdpmsg_rl, "%s: %s success", wdp_name(wdp), operation);
1044     } else {
1045         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
1046                      wdp_name(wdp), operation, strerror(error));
1047     }
1048 }