Merge branch 'mainstream'
[sliver-openvswitch.git] / lib / dpif.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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 "netdev.h"
31 #include "netlink.h"
32 #include "odp-util.h"
33 #include "ofp-errors.h"
34 #include "ofp-print.h"
35 #include "ofp-util.h"
36 #include "ofpbuf.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "shash.h"
40 #include "sset.h"
41 #include "timeval.h"
42 #include "util.h"
43 #include "valgrind.h"
44 #include "vlog.h"
45
46 VLOG_DEFINE_THIS_MODULE(dpif);
47
48 COVERAGE_DEFINE(dpif_destroy);
49 COVERAGE_DEFINE(dpif_port_add);
50 COVERAGE_DEFINE(dpif_port_del);
51 COVERAGE_DEFINE(dpif_flow_flush);
52 COVERAGE_DEFINE(dpif_flow_get);
53 COVERAGE_DEFINE(dpif_flow_put);
54 COVERAGE_DEFINE(dpif_flow_del);
55 COVERAGE_DEFINE(dpif_flow_query_list);
56 COVERAGE_DEFINE(dpif_flow_query_list_n);
57 COVERAGE_DEFINE(dpif_execute);
58 COVERAGE_DEFINE(dpif_purge);
59
60 static const struct dpif_class *base_dpif_classes[] = {
61 #ifdef LINUX_DATAPATH
62     &dpif_linux_class,
63 #endif
64     &dpif_netdev_class,
65     &dpif_planetlab_class,
66 };
67
68 struct registered_dpif_class {
69     const struct dpif_class *dpif_class;
70     int refcount;
71 };
72 static struct shash dpif_classes = SHASH_INITIALIZER(&dpif_classes);
73 static struct sset dpif_blacklist = SSET_INITIALIZER(&dpif_blacklist);
74
75 /* Rate limit for individual messages going to or from the datapath, output at
76  * DBG level.  This is very high because, if these are enabled, it is because
77  * we really need to see them. */
78 static struct vlog_rate_limit dpmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
79
80 /* Not really much point in logging many dpif errors. */
81 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(60, 5);
82
83 static void log_flow_message(const struct dpif *dpif, int error,
84                              const char *operation,
85                              const struct nlattr *key, size_t key_len,
86                              const struct dpif_flow_stats *stats,
87                              const struct nlattr *actions, size_t actions_len);
88 static void log_operation(const struct dpif *, const char *operation,
89                           int error);
90 static bool should_log_flow_message(int error);
91 static void log_flow_put_message(struct dpif *, const struct dpif_flow_put *,
92                                  int error);
93 static void log_flow_del_message(struct dpif *, const struct dpif_flow_del *,
94                                  int error);
95 static void log_execute_message(struct dpif *, const struct dpif_execute *,
96                                 int error);
97
98 static void
99 dp_initialize(void)
100 {
101     static int status = -1;
102
103     if (status < 0) {
104         int i;
105
106         status = 0;
107         for (i = 0; i < ARRAY_SIZE(base_dpif_classes); i++) {
108             dp_register_provider(base_dpif_classes[i]);
109         }
110     }
111 }
112
113 /* Registers a new datapath provider.  After successful registration, new
114  * datapaths of that type can be opened using dpif_open(). */
115 int
116 dp_register_provider(const struct dpif_class *new_class)
117 {
118     struct registered_dpif_class *registered_class;
119
120     if (sset_contains(&dpif_blacklist, new_class->type)) {
121         VLOG_DBG("attempted to register blacklisted provider: %s",
122                  new_class->type);
123         return EINVAL;
124     }
125
126     if (shash_find(&dpif_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     registered_class->dpif_class = new_class;
134     registered_class->refcount = 0;
135
136     shash_add(&dpif_classes, new_class->type, registered_class);
137
138     return 0;
139 }
140
141 /* Unregisters a datapath provider.  'type' must have been previously
142  * registered and not currently be in use by any dpifs.  After unregistration
143  * new datapaths of that type cannot be opened using dpif_open(). */
144 int
145 dp_unregister_provider(const char *type)
146 {
147     struct shash_node *node;
148     struct registered_dpif_class *registered_class;
149
150     node = shash_find(&dpif_classes, type);
151     if (!node) {
152         VLOG_WARN("attempted to unregister a datapath provider that is not "
153                   "registered: %s", type);
154         return EAFNOSUPPORT;
155     }
156
157     registered_class = node->data;
158     if (registered_class->refcount) {
159         VLOG_WARN("attempted to unregister in use datapath provider: %s", type);
160         return EBUSY;
161     }
162
163     shash_delete(&dpif_classes, node);
164     free(registered_class);
165
166     return 0;
167 }
168
169 /* Blacklists a provider.  Causes future calls of dp_register_provider() with
170  * a dpif_class which implements 'type' to fail. */
171 void
172 dp_blacklist_provider(const char *type)
173 {
174     sset_add(&dpif_blacklist, type);
175 }
176
177 /* Clears 'types' and enumerates the types of all currently registered datapath
178  * providers into it.  The caller must first initialize the sset. */
179 void
180 dp_enumerate_types(struct sset *types)
181 {
182     struct shash_node *node;
183
184     dp_initialize();
185     sset_clear(types);
186
187     SHASH_FOR_EACH(node, &dpif_classes) {
188         const struct registered_dpif_class *registered_class = node->data;
189         sset_add(types, registered_class->dpif_class->type);
190     }
191 }
192
193 /* Clears 'names' and enumerates the names of all known created datapaths with
194  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
195  * successful, otherwise a positive errno value.
196  *
197  * Some kinds of datapaths might not be practically enumerable.  This is not
198  * considered an error. */
199 int
200 dp_enumerate_names(const char *type, struct sset *names)
201 {
202     const struct registered_dpif_class *registered_class;
203     const struct dpif_class *dpif_class;
204     int error;
205
206     dp_initialize();
207     sset_clear(names);
208
209     registered_class = shash_find_data(&dpif_classes, type);
210     if (!registered_class) {
211         VLOG_WARN("could not enumerate unknown type: %s", type);
212         return EAFNOSUPPORT;
213     }
214
215     dpif_class = registered_class->dpif_class;
216     error = dpif_class->enumerate ? dpif_class->enumerate(names) : 0;
217
218     if (error) {
219         VLOG_WARN("failed to enumerate %s datapaths: %s", dpif_class->type,
220                    strerror(error));
221     }
222
223     return error;
224 }
225
226 /* Parses 'datapath_name_', which is of the form [type@]name into its
227  * component pieces.  'name' and 'type' must be freed by the caller.
228  *
229  * The returned 'type' is normalized, as if by dpif_normalize_type(). */
230 void
231 dp_parse_name(const char *datapath_name_, char **name, char **type)
232 {
233     char *datapath_name = xstrdup(datapath_name_);
234     char *separator;
235
236     separator = strchr(datapath_name, '@');
237     if (separator) {
238         *separator = '\0';
239         *type = datapath_name;
240         *name = xstrdup(dpif_normalize_type(separator + 1));
241     } else {
242         *name = datapath_name;
243         *type = xstrdup(dpif_normalize_type(NULL));
244     }
245 }
246
247 static int
248 do_open(const char *name, const char *type, bool create, struct dpif **dpifp)
249 {
250     struct dpif *dpif = NULL;
251     int error;
252     struct registered_dpif_class *registered_class;
253
254     dp_initialize();
255
256     type = dpif_normalize_type(type);
257
258     registered_class = shash_find_data(&dpif_classes, type);
259     if (!registered_class) {
260         VLOG_WARN("could not create datapath %s of unknown type %s", name,
261                   type);
262         error = EAFNOSUPPORT;
263         goto exit;
264     }
265
266     error = registered_class->dpif_class->open(registered_class->dpif_class,
267                                                name, create, &dpif);
268     if (!error) {
269         assert(dpif->dpif_class == registered_class->dpif_class);
270         registered_class->refcount++;
271     }
272
273 exit:
274     *dpifp = error ? NULL : dpif;
275     return error;
276 }
277
278 /* Tries to open an existing datapath named 'name' and type 'type'.  Will fail
279  * if no datapath with 'name' and 'type' exists.  'type' may be either NULL or
280  * the empty string to specify the default system type.  Returns 0 if
281  * successful, otherwise a positive errno value.  On success stores a pointer
282  * to the datapath in '*dpifp', otherwise a null pointer. */
283 int
284 dpif_open(const char *name, const char *type, struct dpif **dpifp)
285 {
286     return do_open(name, type, false, dpifp);
287 }
288
289 /* Tries to create and open a new datapath with the given 'name' and 'type'.
290  * 'type' may be either NULL or the empty string to specify the default system
291  * type.  Will fail if a datapath with 'name' and 'type' already exists.
292  * Returns 0 if successful, otherwise a positive errno value.  On success
293  * stores a pointer to the datapath in '*dpifp', otherwise a null pointer. */
294 int
295 dpif_create(const char *name, const char *type, struct dpif **dpifp)
296 {
297     return do_open(name, type, true, dpifp);
298 }
299
300 /* Tries to open a datapath with the given 'name' and 'type', creating it if it
301  * does not exist.  'type' may be either NULL or the empty string to specify
302  * the default system type.  Returns 0 if successful, otherwise a positive
303  * errno value. On success stores a pointer to the datapath in '*dpifp',
304  * otherwise a null pointer. */
305 int
306 dpif_create_and_open(const char *name, const char *type, struct dpif **dpifp)
307 {
308     int error;
309
310     error = dpif_create(name, type, dpifp);
311     if (error == EEXIST || error == EBUSY) {
312         error = dpif_open(name, type, dpifp);
313         if (error) {
314             VLOG_WARN("datapath %s already exists but cannot be opened: %s",
315                       name, strerror(error));
316         }
317     } else if (error) {
318         VLOG_WARN("failed to create datapath %s: %s", name, strerror(error));
319     }
320     return error;
321 }
322
323 /* Closes and frees the connection to 'dpif'.  Does not destroy the datapath
324  * itself; call dpif_delete() first, instead, if that is desirable. */
325 void
326 dpif_close(struct dpif *dpif)
327 {
328     if (dpif) {
329         struct registered_dpif_class *registered_class;
330
331         registered_class = shash_find_data(&dpif_classes,
332                 dpif->dpif_class->type);
333         assert(registered_class);
334         assert(registered_class->refcount);
335
336         registered_class->refcount--;
337         dpif_uninit(dpif, true);
338     }
339 }
340
341 /* Performs periodic work needed by 'dpif'. */
342 void
343 dpif_run(struct dpif *dpif)
344 {
345     if (dpif->dpif_class->run) {
346         dpif->dpif_class->run(dpif);
347     }
348 }
349
350 /* Arranges for poll_block() to wake up when dp_run() needs to be called for
351  * 'dpif'. */
352 void
353 dpif_wait(struct dpif *dpif)
354 {
355     if (dpif->dpif_class->wait) {
356         dpif->dpif_class->wait(dpif);
357     }
358 }
359
360 /* Returns the name of datapath 'dpif' prefixed with the type
361  * (for use in log messages). */
362 const char *
363 dpif_name(const struct dpif *dpif)
364 {
365     return dpif->full_name;
366 }
367
368 /* Returns the name of datapath 'dpif' without the type
369  * (for use in device names). */
370 const char *
371 dpif_base_name(const struct dpif *dpif)
372 {
373     return dpif->base_name;
374 }
375
376 /* Returns the fully spelled out name for the given datapath 'type'.
377  *
378  * Normalized type string can be compared with strcmp().  Unnormalized type
379  * string might be the same even if they have different spellings. */
380 const char *
381 dpif_normalize_type(const char *type)
382 {
383     return type && type[0] ? type : "system";
384 }
385
386 /* Destroys the datapath that 'dpif' is connected to, first removing all of its
387  * ports.  After calling this function, it does not make sense to pass 'dpif'
388  * to any functions other than dpif_name() or dpif_close(). */
389 int
390 dpif_delete(struct dpif *dpif)
391 {
392     int error;
393
394     COVERAGE_INC(dpif_destroy);
395
396     error = dpif->dpif_class->destroy(dpif);
397     log_operation(dpif, "delete", error);
398     return error;
399 }
400
401 /* Retrieves statistics for 'dpif' into 'stats'.  Returns 0 if successful,
402  * otherwise a positive errno value. */
403 int
404 dpif_get_dp_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
405 {
406     int error = dpif->dpif_class->get_stats(dpif, stats);
407     if (error) {
408         memset(stats, 0, sizeof *stats);
409     }
410     log_operation(dpif, "get_stats", error);
411     return error;
412 }
413
414 /* Attempts to add 'netdev' as a port on 'dpif'.  If 'port_nop' is
415  * non-null and its value is not UINT16_MAX, then attempts to use the
416  * value as the port number.
417  *
418  * If successful, returns 0 and sets '*port_nop' to the new port's port
419  * number (if 'port_nop' is non-null).  On failure, returns a positive
420  * errno value and sets '*port_nop' to UINT16_MAX (if 'port_nop' is
421  * non-null). */
422 int
423 dpif_port_add(struct dpif *dpif, struct netdev *netdev, uint16_t *port_nop)
424 {
425     const char *netdev_name = netdev_get_name(netdev);
426     uint16_t port_no = UINT16_MAX;
427     int error;
428
429     COVERAGE_INC(dpif_port_add);
430
431     if (port_nop) {
432         port_no = *port_nop;
433     }
434
435     error = dpif->dpif_class->port_add(dpif, netdev, &port_no);
436     if (!error) {
437         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
438                     dpif_name(dpif), netdev_name, port_no);
439     } else {
440         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
441                      dpif_name(dpif), netdev_name, strerror(error));
442         port_no = UINT16_MAX;
443     }
444     if (port_nop) {
445         *port_nop = port_no;
446     }
447     return error;
448 }
449
450 /* Attempts to remove 'dpif''s port number 'port_no'.  Returns 0 if successful,
451  * otherwise a positive errno value. */
452 int
453 dpif_port_del(struct dpif *dpif, uint16_t port_no)
454 {
455     int error;
456
457     COVERAGE_INC(dpif_port_del);
458
459     error = dpif->dpif_class->port_del(dpif, port_no);
460     if (!error) {
461         VLOG_DBG_RL(&dpmsg_rl, "%s: port_del(%"PRIu16")",
462                     dpif_name(dpif), port_no);
463     } else {
464         log_operation(dpif, "port_del", error);
465     }
466     return error;
467 }
468
469 /* Makes a deep copy of 'src' into 'dst'. */
470 void
471 dpif_port_clone(struct dpif_port *dst, const struct dpif_port *src)
472 {
473     dst->name = xstrdup(src->name);
474     dst->type = xstrdup(src->type);
475     dst->port_no = src->port_no;
476 }
477
478 /* Frees memory allocated to members of 'dpif_port'.
479  *
480  * Do not call this function on a dpif_port obtained from
481  * dpif_port_dump_next(): that function retains ownership of the data in the
482  * dpif_port. */
483 void
484 dpif_port_destroy(struct dpif_port *dpif_port)
485 {
486     free(dpif_port->name);
487     free(dpif_port->type);
488 }
489
490 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and
491  * initializes '*port' appropriately; on failure, returns a positive errno
492  * value.
493  *
494  * The caller owns the data in 'port' and must free it with
495  * dpif_port_destroy() when it is no longer needed. */
496 int
497 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
498                           struct dpif_port *port)
499 {
500     int error = dpif->dpif_class->port_query_by_number(dpif, port_no, port);
501     if (!error) {
502         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
503                     dpif_name(dpif), port_no, port->name);
504     } else {
505         memset(port, 0, sizeof *port);
506         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
507                      dpif_name(dpif), port_no, strerror(error));
508     }
509     return error;
510 }
511
512 /* Looks up port named 'devname' in 'dpif'.  On success, returns 0 and
513  * initializes '*port' appropriately; on failure, returns a positive errno
514  * value.
515  *
516  * The caller owns the data in 'port' and must free it with
517  * dpif_port_destroy() when it is no longer needed. */
518 int
519 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
520                         struct dpif_port *port)
521 {
522     int error = dpif->dpif_class->port_query_by_name(dpif, devname, port);
523     if (!error) {
524         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
525                     dpif_name(dpif), devname, port->port_no);
526     } else {
527         memset(port, 0, sizeof *port);
528
529         /* For ENOENT or ENODEV we use DBG level because the caller is probably
530          * interested in whether 'dpif' actually has a port 'devname', so that
531          * it's not an issue worth logging if it doesn't.  Other errors are
532          * uncommon and more likely to indicate a real problem. */
533         VLOG_RL(&error_rl,
534                 error == ENOENT || error == ENODEV ? VLL_DBG : VLL_WARN,
535                 "%s: failed to query port %s: %s",
536                 dpif_name(dpif), devname, strerror(error));
537     }
538     return error;
539 }
540
541 /* Returns one greater than the maximum port number accepted in flow
542  * actions. */
543 int
544 dpif_get_max_ports(const struct dpif *dpif)
545 {
546     return dpif->dpif_class->get_max_ports(dpif);
547 }
548
549 /* Returns the Netlink PID value to supply in OVS_ACTION_ATTR_USERSPACE actions
550  * as the OVS_USERSPACE_ATTR_PID attribute's value, for use in flows whose
551  * packets arrived on port 'port_no'.
552  *
553  * A 'port_no' of UINT16_MAX is a special case: it returns a reserved PID, not
554  * allocated to any port, that the client may use for special purposes.
555  *
556  * The return value is only meaningful when DPIF_UC_ACTION has been enabled in
557  * the 'dpif''s listen mask.  It is allowed to change when DPIF_UC_ACTION is
558  * disabled and then re-enabled, so a client that does that must be prepared to
559  * update all of the flows that it installed that contain
560  * OVS_ACTION_ATTR_USERSPACE actions. */
561 uint32_t
562 dpif_port_get_pid(const struct dpif *dpif, uint16_t port_no)
563 {
564     return (dpif->dpif_class->port_get_pid
565             ? (dpif->dpif_class->port_get_pid)(dpif, port_no)
566             : 0);
567 }
568
569 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and copies
570  * the port's name into the 'name_size' bytes in 'name', ensuring that the
571  * result is null-terminated.  On failure, returns a positive errno value and
572  * makes 'name' the empty string. */
573 int
574 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
575                    char *name, size_t name_size)
576 {
577     struct dpif_port port;
578     int error;
579
580     assert(name_size > 0);
581
582     error = dpif_port_query_by_number(dpif, port_no, &port);
583     if (!error) {
584         ovs_strlcpy(name, port.name, name_size);
585         dpif_port_destroy(&port);
586     } else {
587         *name = '\0';
588     }
589     return error;
590 }
591
592 /* Initializes 'dump' to begin dumping the ports in a dpif.
593  *
594  * This function provides no status indication.  An error status for the entire
595  * dump operation is provided when it is completed by calling
596  * dpif_port_dump_done().
597  */
598 void
599 dpif_port_dump_start(struct dpif_port_dump *dump, const struct dpif *dpif)
600 {
601     dump->dpif = dpif;
602     dump->error = dpif->dpif_class->port_dump_start(dpif, &dump->state);
603     log_operation(dpif, "port_dump_start", dump->error);
604 }
605
606 /* Attempts to retrieve another port from 'dump', which must have been
607  * initialized with dpif_port_dump_start().  On success, stores a new dpif_port
608  * into 'port' and returns true.  On failure, returns false.
609  *
610  * Failure might indicate an actual error or merely that the last port has been
611  * dumped.  An error status for the entire dump operation is provided when it
612  * is completed by calling dpif_port_dump_done().
613  *
614  * The dpif owns the data stored in 'port'.  It will remain valid until at
615  * least the next time 'dump' is passed to dpif_port_dump_next() or
616  * dpif_port_dump_done(). */
617 bool
618 dpif_port_dump_next(struct dpif_port_dump *dump, struct dpif_port *port)
619 {
620     const struct dpif *dpif = dump->dpif;
621
622     if (dump->error) {
623         return false;
624     }
625
626     dump->error = dpif->dpif_class->port_dump_next(dpif, dump->state, port);
627     if (dump->error == EOF) {
628         VLOG_DBG_RL(&dpmsg_rl, "%s: dumped all ports", dpif_name(dpif));
629     } else {
630         log_operation(dpif, "port_dump_next", dump->error);
631     }
632
633     if (dump->error) {
634         dpif->dpif_class->port_dump_done(dpif, dump->state);
635         return false;
636     }
637     return true;
638 }
639
640 /* Completes port table dump operation 'dump', which must have been initialized
641  * with dpif_port_dump_start().  Returns 0 if the dump operation was
642  * error-free, otherwise a positive errno value describing the problem. */
643 int
644 dpif_port_dump_done(struct dpif_port_dump *dump)
645 {
646     const struct dpif *dpif = dump->dpif;
647     if (!dump->error) {
648         dump->error = dpif->dpif_class->port_dump_done(dpif, dump->state);
649         log_operation(dpif, "port_dump_done", dump->error);
650     }
651     return dump->error == EOF ? 0 : dump->error;
652 }
653
654 /* Polls for changes in the set of ports in 'dpif'.  If the set of ports in
655  * 'dpif' has changed, this function does one of the following:
656  *
657  * - Stores the name of the device that was added to or deleted from 'dpif' in
658  *   '*devnamep' and returns 0.  The caller is responsible for freeing
659  *   '*devnamep' (with free()) when it no longer needs it.
660  *
661  * - Returns ENOBUFS and sets '*devnamep' to NULL.
662  *
663  * This function may also return 'false positives', where it returns 0 and
664  * '*devnamep' names a device that was not actually added or deleted or it
665  * returns ENOBUFS without any change.
666  *
667  * Returns EAGAIN if the set of ports in 'dpif' has not changed.  May also
668  * return other positive errno values to indicate that something has gone
669  * wrong. */
670 int
671 dpif_port_poll(const struct dpif *dpif, char **devnamep)
672 {
673     int error = dpif->dpif_class->port_poll(dpif, devnamep);
674     if (error) {
675         *devnamep = NULL;
676     }
677     return error;
678 }
679
680 /* Arranges for the poll loop to wake up when port_poll(dpif) will return a
681  * value other than EAGAIN. */
682 void
683 dpif_port_poll_wait(const struct dpif *dpif)
684 {
685     dpif->dpif_class->port_poll_wait(dpif);
686 }
687
688 /* Extracts the flow stats for a packet.  The 'flow' and 'packet'
689  * arguments must have been initialized through a call to flow_extract().
690  * 'used' is stored into stats->used. */
691 void
692 dpif_flow_stats_extract(const struct flow *flow, const struct ofpbuf *packet,
693                         long long int used, struct dpif_flow_stats *stats)
694 {
695     stats->tcp_flags = packet_get_tcp_flags(packet, flow);
696     stats->n_bytes = packet->size;
697     stats->n_packets = 1;
698     stats->used = used;
699 }
700
701 /* Appends a human-readable representation of 'stats' to 's'. */
702 void
703 dpif_flow_stats_format(const struct dpif_flow_stats *stats, struct ds *s)
704 {
705     ds_put_format(s, "packets:%"PRIu64", bytes:%"PRIu64", used:",
706                   stats->n_packets, stats->n_bytes);
707     if (stats->used) {
708         ds_put_format(s, "%.3fs", (time_msec() - stats->used) / 1000.0);
709     } else {
710         ds_put_format(s, "never");
711     }
712     if (stats->tcp_flags) {
713         ds_put_cstr(s, ", flags:");
714         packet_format_tcp_flags(s, stats->tcp_flags);
715     }
716 }
717
718 /* Deletes all flows from 'dpif'.  Returns 0 if successful, otherwise a
719  * positive errno value.  */
720 int
721 dpif_flow_flush(struct dpif *dpif)
722 {
723     int error;
724
725     COVERAGE_INC(dpif_flow_flush);
726
727     error = dpif->dpif_class->flow_flush(dpif);
728     log_operation(dpif, "flow_flush", error);
729     return error;
730 }
731
732 /* Queries 'dpif' for a flow entry.  The flow is specified by the Netlink
733  * attributes with types OVS_KEY_ATTR_* in the 'key_len' bytes starting at
734  * 'key'.
735  *
736  * Returns 0 if successful.  If no flow matches, returns ENOENT.  On other
737  * failure, returns a positive errno value.
738  *
739  * If 'actionsp' is nonnull, then on success '*actionsp' will be set to an
740  * ofpbuf owned by the caller that contains the Netlink attributes for the
741  * flow's actions.  The caller must free the ofpbuf (with ofpbuf_delete()) when
742  * it is no longer needed.
743  *
744  * If 'stats' is nonnull, then on success it will be updated with the flow's
745  * statistics. */
746 int
747 dpif_flow_get(const struct dpif *dpif,
748               const struct nlattr *key, size_t key_len,
749               struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
750 {
751     int error;
752
753     COVERAGE_INC(dpif_flow_get);
754
755     error = dpif->dpif_class->flow_get(dpif, key, key_len, actionsp, stats);
756     if (error) {
757         if (actionsp) {
758             *actionsp = NULL;
759         }
760         if (stats) {
761             memset(stats, 0, sizeof *stats);
762         }
763     }
764     if (should_log_flow_message(error)) {
765         const struct nlattr *actions;
766         size_t actions_len;
767
768         if (!error && actionsp) {
769             actions = (*actionsp)->data;
770             actions_len = (*actionsp)->size;
771         } else {
772             actions = NULL;
773             actions_len = 0;
774         }
775         log_flow_message(dpif, error, "flow_get", key, key_len, stats,
776                          actions, actions_len);
777     }
778     return error;
779 }
780
781 static int
782 dpif_flow_put__(struct dpif *dpif, const struct dpif_flow_put *put)
783 {
784     int error;
785
786     COVERAGE_INC(dpif_flow_put);
787     assert(!(put->flags & ~(DPIF_FP_CREATE | DPIF_FP_MODIFY
788                             | DPIF_FP_ZERO_STATS)));
789
790     error = dpif->dpif_class->flow_put(dpif, put);
791     if (error && put->stats) {
792         memset(put->stats, 0, sizeof *put->stats);
793     }
794     log_flow_put_message(dpif, put, error);
795     return error;
796 }
797
798 /* Adds or modifies a flow in 'dpif'.  The flow is specified by the Netlink
799  * attributes with types OVS_KEY_ATTR_* in the 'key_len' bytes starting at
800  * 'key'.  The associated actions are specified by the Netlink attributes with
801  * types OVS_ACTION_ATTR_* in the 'actions_len' bytes starting at 'actions'.
802  *
803  * - If the flow's key does not exist in 'dpif', then the flow will be added if
804  *   'flags' includes DPIF_FP_CREATE.  Otherwise the operation will fail with
805  *   ENOENT.
806  *
807  *   If the operation succeeds, then 'stats', if nonnull, will be zeroed.
808  *
809  * - If the flow's key does exist in 'dpif', then the flow's actions will be
810  *   updated if 'flags' includes DPIF_FP_MODIFY.  Otherwise the operation will
811  *   fail with EEXIST.  If the flow's actions are updated, then its statistics
812  *   will be zeroed if 'flags' includes DPIF_FP_ZERO_STATS, and left as-is
813  *   otherwise.
814  *
815  *   If the operation succeeds, then 'stats', if nonnull, will be set to the
816  *   flow's statistics before the update.
817  */
818 int
819 dpif_flow_put(struct dpif *dpif, enum dpif_flow_put_flags flags,
820               const struct nlattr *key, size_t key_len,
821               const struct nlattr *actions, size_t actions_len,
822               struct dpif_flow_stats *stats)
823 {
824     struct dpif_flow_put put;
825
826     put.flags = flags;
827     put.key = key;
828     put.key_len = key_len;
829     put.actions = actions;
830     put.actions_len = actions_len;
831     put.stats = stats;
832     return dpif_flow_put__(dpif, &put);
833 }
834
835 static int
836 dpif_flow_del__(struct dpif *dpif, struct dpif_flow_del *del)
837 {
838     int error;
839
840     COVERAGE_INC(dpif_flow_del);
841
842     error = dpif->dpif_class->flow_del(dpif, del);
843     if (error && del->stats) {
844         memset(del->stats, 0, sizeof *del->stats);
845     }
846     log_flow_del_message(dpif, del, error);
847     return error;
848 }
849
850 /* Deletes a flow from 'dpif' and returns 0, or returns ENOENT if 'dpif' does
851  * not contain such a flow.  The flow is specified by the Netlink attributes
852  * with types OVS_KEY_ATTR_* in the 'key_len' bytes starting at 'key'.
853  *
854  * If the operation succeeds, then 'stats', if nonnull, will be set to the
855  * flow's statistics before its deletion. */
856 int
857 dpif_flow_del(struct dpif *dpif,
858               const struct nlattr *key, size_t key_len,
859               struct dpif_flow_stats *stats)
860 {
861     struct dpif_flow_del del;
862
863     del.key = key;
864     del.key_len = key_len;
865     del.stats = stats;
866     return dpif_flow_del__(dpif, &del);
867 }
868
869 /* Initializes 'dump' to begin dumping the flows in a dpif.
870  *
871  * This function provides no status indication.  An error status for the entire
872  * dump operation is provided when it is completed by calling
873  * dpif_flow_dump_done().
874  */
875 void
876 dpif_flow_dump_start(struct dpif_flow_dump *dump, const struct dpif *dpif)
877 {
878     dump->dpif = dpif;
879     dump->error = dpif->dpif_class->flow_dump_start(dpif, &dump->state);
880     log_operation(dpif, "flow_dump_start", dump->error);
881 }
882
883 /* Attempts to retrieve another flow from 'dump', which must have been
884  * initialized with dpif_flow_dump_start().  On success, updates the output
885  * parameters as described below and returns true.  Otherwise, returns false.
886  * Failure might indicate an actual error or merely the end of the flow table.
887  * An error status for the entire dump operation is provided when it is
888  * completed by calling dpif_flow_dump_done().
889  *
890  * On success, if 'key' and 'key_len' are nonnull then '*key' and '*key_len'
891  * will be set to Netlink attributes with types OVS_KEY_ATTR_* representing the
892  * dumped flow's key.  If 'actions' and 'actions_len' are nonnull then they are
893  * set to Netlink attributes with types OVS_ACTION_ATTR_* representing the
894  * dumped flow's actions.  If 'stats' is nonnull then it will be set to the
895  * dumped flow's statistics.
896  *
897  * All of the returned data is owned by 'dpif', not by the caller, and the
898  * caller must not modify or free it.  'dpif' guarantees that it remains
899  * accessible and unchanging until at least the next call to 'flow_dump_next'
900  * or 'flow_dump_done' for 'dump'. */
901 bool
902 dpif_flow_dump_next(struct dpif_flow_dump *dump,
903                     const struct nlattr **key, size_t *key_len,
904                     const struct nlattr **actions, size_t *actions_len,
905                     const struct dpif_flow_stats **stats)
906 {
907     const struct dpif *dpif = dump->dpif;
908     int error = dump->error;
909
910     if (!error) {
911         error = dpif->dpif_class->flow_dump_next(dpif, dump->state,
912                                                  key, key_len,
913                                                  actions, actions_len,
914                                                  stats);
915         if (error) {
916             dpif->dpif_class->flow_dump_done(dpif, dump->state);
917         }
918     }
919     if (error) {
920         if (key) {
921             *key = NULL;
922             *key_len = 0;
923         }
924         if (actions) {
925             *actions = NULL;
926             *actions_len = 0;
927         }
928         if (stats) {
929             *stats = NULL;
930         }
931     }
932     if (!dump->error) {
933         if (error == EOF) {
934             VLOG_DBG_RL(&dpmsg_rl, "%s: dumped all flows", dpif_name(dpif));
935         } else if (should_log_flow_message(error)) {
936             log_flow_message(dpif, error, "flow_dump",
937                              key ? *key : NULL, key ? *key_len : 0,
938                              stats ? *stats : NULL, actions ? *actions : NULL,
939                              actions ? *actions_len : 0);
940         }
941     }
942     dump->error = error;
943     return !error;
944 }
945
946 /* Completes flow table dump operation 'dump', which must have been initialized
947  * with dpif_flow_dump_start().  Returns 0 if the dump operation was
948  * error-free, otherwise a positive errno value describing the problem. */
949 int
950 dpif_flow_dump_done(struct dpif_flow_dump *dump)
951 {
952     const struct dpif *dpif = dump->dpif;
953     if (!dump->error) {
954         dump->error = dpif->dpif_class->flow_dump_done(dpif, dump->state);
955         log_operation(dpif, "flow_dump_done", dump->error);
956     }
957     return dump->error == EOF ? 0 : dump->error;
958 }
959
960 static int
961 dpif_execute__(struct dpif *dpif, const struct dpif_execute *execute)
962 {
963     int error;
964
965     COVERAGE_INC(dpif_execute);
966     if (execute->actions_len > 0) {
967         error = dpif->dpif_class->execute(dpif, execute);
968     } else {
969         error = 0;
970     }
971
972     log_execute_message(dpif, execute, error);
973
974     return error;
975 }
976
977 /* Causes 'dpif' to perform the 'actions_len' bytes of actions in 'actions' on
978  * the Ethernet frame specified in 'packet' taken from the flow specified in
979  * the 'key_len' bytes of 'key'.  ('key' is mostly redundant with 'packet', but
980  * it contains some metadata that cannot be recovered from 'packet', such as
981  * tunnel and in_port.)
982  *
983  * Returns 0 if successful, otherwise a positive errno value. */
984 int
985 dpif_execute(struct dpif *dpif,
986              const struct nlattr *key, size_t key_len,
987              const struct nlattr *actions, size_t actions_len,
988              const struct ofpbuf *buf)
989 {
990     struct dpif_execute execute;
991
992     execute.key = key;
993     execute.key_len = key_len;
994     execute.actions = actions;
995     execute.actions_len = actions_len;
996     execute.packet = buf;
997     return dpif_execute__(dpif, &execute);
998 }
999
1000 /* Executes each of the 'n_ops' operations in 'ops' on 'dpif', in the order in
1001  * which they are specified, placing each operation's results in the "output"
1002  * members documented in comments.
1003  *
1004  * This function exists because some datapaths can perform batched operations
1005  * faster than individual operations. */
1006 void
1007 dpif_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1008 {
1009     size_t i;
1010
1011     if (dpif->dpif_class->operate) {
1012         dpif->dpif_class->operate(dpif, ops, n_ops);
1013
1014         for (i = 0; i < n_ops; i++) {
1015             struct dpif_op *op = ops[i];
1016
1017             switch (op->type) {
1018             case DPIF_OP_FLOW_PUT:
1019                 log_flow_put_message(dpif, &op->u.flow_put, op->error);
1020                 break;
1021
1022             case DPIF_OP_FLOW_DEL:
1023                 log_flow_del_message(dpif, &op->u.flow_del, op->error);
1024                 break;
1025
1026             case DPIF_OP_EXECUTE:
1027                 log_execute_message(dpif, &op->u.execute, op->error);
1028                 break;
1029             }
1030         }
1031         return;
1032     }
1033
1034     for (i = 0; i < n_ops; i++) {
1035         struct dpif_op *op = ops[i];
1036
1037         switch (op->type) {
1038         case DPIF_OP_FLOW_PUT:
1039             op->error = dpif_flow_put__(dpif, &op->u.flow_put);
1040             break;
1041
1042         case DPIF_OP_FLOW_DEL:
1043             op->error = dpif_flow_del__(dpif, &op->u.flow_del);
1044             break;
1045
1046         case DPIF_OP_EXECUTE:
1047             op->error = dpif_execute__(dpif, &op->u.execute);
1048             break;
1049
1050         default:
1051             NOT_REACHED();
1052         }
1053     }
1054 }
1055
1056
1057 /* Returns a string that represents 'type', for use in log messages. */
1058 const char *
1059 dpif_upcall_type_to_string(enum dpif_upcall_type type)
1060 {
1061     switch (type) {
1062     case DPIF_UC_MISS: return "miss";
1063     case DPIF_UC_ACTION: return "action";
1064     case DPIF_N_UC_TYPES: default: return "<unknown>";
1065     }
1066 }
1067
1068 /* Enables or disables receiving packets with dpif_recv() on 'dpif'.  Returns 0
1069  * if successful, otherwise a positive errno value.
1070  *
1071  * Turning packet receive off and then back on may change the Netlink PID
1072  * assignments returned by dpif_port_get_pid().  If the client does this, it
1073  * must update all of the flows that have OVS_ACTION_ATTR_USERSPACE actions
1074  * using the new PID assignment. */
1075 int
1076 dpif_recv_set(struct dpif *dpif, bool enable)
1077 {
1078     int error = dpif->dpif_class->recv_set(dpif, enable);
1079     log_operation(dpif, "recv_set", error);
1080     return error;
1081 }
1082
1083 /* Polls for an upcall from 'dpif'.  If successful, stores the upcall into
1084  * '*upcall', using 'buf' for storage.  Should only be called if
1085  * dpif_recv_set() has been used to enable receiving packets on 'dpif'.
1086  *
1087  * 'upcall->packet' and 'upcall->key' point into data in the caller-provided
1088  * 'buf', so their memory cannot be freed separately from 'buf'.  (This is
1089  * hardly a great way to do things but it works out OK for the dpif providers
1090  * and clients that exist so far.)
1091  *
1092  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
1093  * if no upcall is immediately available. */
1094 int
1095 dpif_recv(struct dpif *dpif, struct dpif_upcall *upcall, struct ofpbuf *buf)
1096 {
1097     int error = dpif->dpif_class->recv(dpif, upcall, buf);
1098     if (!error && !VLOG_DROP_DBG(&dpmsg_rl)) {
1099         struct ds flow;
1100         char *packet;
1101
1102         packet = ofp_packet_to_string(upcall->packet->data,
1103                                       upcall->packet->size);
1104
1105         ds_init(&flow);
1106         odp_flow_key_format(upcall->key, upcall->key_len, &flow);
1107
1108         VLOG_DBG("%s: %s upcall:\n%s\n%s",
1109                  dpif_name(dpif), dpif_upcall_type_to_string(upcall->type),
1110                  ds_cstr(&flow), packet);
1111
1112         ds_destroy(&flow);
1113         free(packet);
1114     } else if (error && error != EAGAIN) {
1115         log_operation(dpif, "recv", error);
1116     }
1117     return error;
1118 }
1119
1120 /* Discards all messages that would otherwise be received by dpif_recv() on
1121  * 'dpif'. */
1122 void
1123 dpif_recv_purge(struct dpif *dpif)
1124 {
1125     COVERAGE_INC(dpif_purge);
1126     if (dpif->dpif_class->recv_purge) {
1127         dpif->dpif_class->recv_purge(dpif);
1128     }
1129 }
1130
1131 /* Arranges for the poll loop to wake up when 'dpif' has a message queued to be
1132  * received with dpif_recv(). */
1133 void
1134 dpif_recv_wait(struct dpif *dpif)
1135 {
1136     dpif->dpif_class->recv_wait(dpif);
1137 }
1138
1139 /* Obtains the NetFlow engine type and engine ID for 'dpif' into '*engine_type'
1140  * and '*engine_id', respectively. */
1141 void
1142 dpif_get_netflow_ids(const struct dpif *dpif,
1143                      uint8_t *engine_type, uint8_t *engine_id)
1144 {
1145     *engine_type = dpif->netflow_engine_type;
1146     *engine_id = dpif->netflow_engine_id;
1147 }
1148
1149 /* Translates OpenFlow queue ID 'queue_id' (in host byte order) into a priority
1150  * value used for setting packet priority.
1151  * On success, returns 0 and stores the priority into '*priority'.
1152  * On failure, returns a positive errno value and stores 0 into '*priority'. */
1153 int
1154 dpif_queue_to_priority(const struct dpif *dpif, uint32_t queue_id,
1155                        uint32_t *priority)
1156 {
1157     int error = (dpif->dpif_class->queue_to_priority
1158                  ? dpif->dpif_class->queue_to_priority(dpif, queue_id,
1159                                                        priority)
1160                  : EOPNOTSUPP);
1161     if (error) {
1162         *priority = 0;
1163     }
1164     log_operation(dpif, "queue_to_priority", error);
1165     return error;
1166 }
1167 \f
1168 void
1169 dpif_init(struct dpif *dpif, const struct dpif_class *dpif_class,
1170           const char *name,
1171           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
1172 {
1173     dpif->dpif_class = dpif_class;
1174     dpif->base_name = xstrdup(name);
1175     dpif->full_name = xasprintf("%s@%s", dpif_class->type, name);
1176     dpif->netflow_engine_type = netflow_engine_type;
1177     dpif->netflow_engine_id = netflow_engine_id;
1178 }
1179
1180 /* Undoes the results of initialization.
1181  *
1182  * Normally this function only needs to be called from dpif_close().
1183  * However, it may be called by providers due to an error on opening
1184  * that occurs after initialization.  It this case dpif_close() would
1185  * never be called. */
1186 void
1187 dpif_uninit(struct dpif *dpif, bool close)
1188 {
1189     char *base_name = dpif->base_name;
1190     char *full_name = dpif->full_name;
1191
1192     if (close) {
1193         dpif->dpif_class->close(dpif);
1194     }
1195
1196     free(base_name);
1197     free(full_name);
1198 }
1199 \f
1200 static void
1201 log_operation(const struct dpif *dpif, const char *operation, int error)
1202 {
1203     if (!error) {
1204         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", dpif_name(dpif), operation);
1205     } else if (ofperr_is_valid(error)) {
1206         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
1207                      dpif_name(dpif), operation, ofperr_get_name(error));
1208     } else {
1209         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
1210                      dpif_name(dpif), operation, strerror(error));
1211     }
1212 }
1213
1214 static enum vlog_level
1215 flow_message_log_level(int error)
1216 {
1217     return error ? VLL_WARN : VLL_DBG;
1218 }
1219
1220 static bool
1221 should_log_flow_message(int error)
1222 {
1223     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
1224                              error ? &error_rl : &dpmsg_rl);
1225 }
1226
1227 static void
1228 log_flow_message(const struct dpif *dpif, int error, const char *operation,
1229                  const struct nlattr *key, size_t key_len,
1230                  const struct dpif_flow_stats *stats,
1231                  const struct nlattr *actions, size_t actions_len)
1232 {
1233     struct ds ds = DS_EMPTY_INITIALIZER;
1234     ds_put_format(&ds, "%s: ", dpif_name(dpif));
1235     if (error) {
1236         ds_put_cstr(&ds, "failed to ");
1237     }
1238     ds_put_format(&ds, "%s ", operation);
1239     if (error) {
1240         ds_put_format(&ds, "(%s) ", strerror(error));
1241     }
1242     odp_flow_key_format(key, key_len, &ds);
1243     if (stats) {
1244         ds_put_cstr(&ds, ", ");
1245         dpif_flow_stats_format(stats, &ds);
1246     }
1247     if (actions || actions_len) {
1248         ds_put_cstr(&ds, ", actions:");
1249         format_odp_actions(&ds, actions, actions_len);
1250     }
1251     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
1252     ds_destroy(&ds);
1253 }
1254
1255 static void
1256 log_flow_put_message(struct dpif *dpif, const struct dpif_flow_put *put,
1257                      int error)
1258 {
1259     if (should_log_flow_message(error)) {
1260         struct ds s;
1261
1262         ds_init(&s);
1263         ds_put_cstr(&s, "put");
1264         if (put->flags & DPIF_FP_CREATE) {
1265             ds_put_cstr(&s, "[create]");
1266         }
1267         if (put->flags & DPIF_FP_MODIFY) {
1268             ds_put_cstr(&s, "[modify]");
1269         }
1270         if (put->flags & DPIF_FP_ZERO_STATS) {
1271             ds_put_cstr(&s, "[zero]");
1272         }
1273         log_flow_message(dpif, error, ds_cstr(&s),
1274                          put->key, put->key_len, put->stats,
1275                          put->actions, put->actions_len);
1276         ds_destroy(&s);
1277     }
1278 }
1279
1280 static void
1281 log_flow_del_message(struct dpif *dpif, const struct dpif_flow_del *del,
1282                      int error)
1283 {
1284     if (should_log_flow_message(error)) {
1285         log_flow_message(dpif, error, "flow_del", del->key, del->key_len,
1286                          !error ? del->stats : NULL, NULL, 0);
1287     }
1288 }
1289
1290 static void
1291 log_execute_message(struct dpif *dpif, const struct dpif_execute *execute,
1292                     int error)
1293 {
1294     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
1295         struct ds ds = DS_EMPTY_INITIALIZER;
1296         char *packet;
1297
1298         packet = ofp_packet_to_string(execute->packet->data,
1299                                       execute->packet->size);
1300         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
1301         format_odp_actions(&ds, execute->actions, execute->actions_len);
1302         if (error) {
1303             ds_put_format(&ds, " failed (%s)", strerror(error));
1304         }
1305         ds_put_format(&ds, " on packet %s", packet);
1306         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
1307         ds_destroy(&ds);
1308         free(packet);
1309     }
1310 }