dpif: Make dpifs abstract, to allow multiple datapath implementations.
[sliver-openvswitch.git] / lib / dpif.c
1 /*
2  * Copyright (c) 2008, 2009 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 "util.h"
37 #include "valgrind.h"
38
39 #include "vlog.h"
40 #define THIS_MODULE VLM_dpif
41
42 static struct dpif_class *dpif_classes[] = {
43     &dpif_linux_class,
44 };
45 enum { N_DPIF_CLASSES = ARRAY_SIZE(dpif_classes) };
46
47 /* Rate limit for individual messages going to or from the datapath, output at
48  * DBG level.  This is very high because, if these are enabled, it is because
49  * we really need to see them. */
50 static struct vlog_rate_limit dpmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
51
52 /* Not really much point in logging many dpif errors. */
53 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
54
55 static void log_operation(const struct dpif *, const char *operation,
56                           int error);
57 static void log_flow_operation(const struct dpif *, const char *operation,
58                                int error, struct odp_flow *flow);
59 static void log_flow_put(struct dpif *, int error,
60                          const struct odp_flow_put *);
61 static bool should_log_flow_message(int error);
62 static void check_rw_odp_flow(struct odp_flow *);
63
64 static int
65 do_open(const char *name_, bool create, struct dpif **dpifp)
66 {
67     char *name = xstrdup(name_);
68     char *prefix, *suffix, *colon;
69     struct dpif *dpif = NULL;
70     int error;
71     int i;
72
73     colon = strchr(name, ':');
74     if (colon) {
75         *colon = '\0';
76         prefix = name;
77         suffix = colon + 1;
78     } else {
79         prefix = "";
80         suffix = name;
81     }
82
83     for (i = 0; i < N_DPIF_CLASSES; i++) {
84         const struct dpif_class *class = dpif_classes[i];
85         if (!strcmp(prefix, class->prefix)) {
86             error = class->open(name_, suffix, create, &dpif);
87             goto exit;
88         }
89     }
90     error = EAFNOSUPPORT;
91
92 exit:
93     *dpifp = error ? NULL : dpif;
94     return error;
95 }
96
97 /* Tries to open an existing datapath named 'name'.  Will fail if no datapath
98  * named 'name' exists.  Returns 0 if successful, otherwise a positive errno
99  * value.  On success stores a pointer to the datapath in '*dpifp', otherwise a
100  * null pointer. */
101 int
102 dpif_open(const char *name, struct dpif **dpifp)
103 {
104     return do_open(name, false, dpifp);
105 }
106
107 /* Tries to create and open a new datapath with the given 'name'.  Will fail if
108  * a datapath named 'name' already exists.  Returns 0 if successful, otherwise
109  * a positive errno value.  On success stores a pointer to the datapath in
110  * '*dpifp', otherwise a null pointer.*/
111 int
112 dpif_create(const char *name, struct dpif **dpifp)
113 {
114     return do_open(name, true, dpifp);
115 }
116
117 /* Closes and frees the connection to 'dpif'.  Does not destroy the datapath
118  * itself; call dpif_delete() first, instead, if that is desirable. */
119 void
120 dpif_close(struct dpif *dpif)
121 {
122     if (dpif) {
123         char *name = dpif->name;
124         dpif->class->close(dpif);
125         free(name);
126     }
127 }
128
129 /* Returns the name of datapath 'dpif' (for use in log messages). */
130 const char *
131 dpif_name(const struct dpif *dpif)
132 {
133     return dpif->name;
134 }
135
136 /* Destroys the datapath that 'dpif' is connected to, first removing all of its
137  * ports.  After calling this function, it does not make sense to pass 'dpif'
138  * to any functions other than dpif_name() or dpif_close(). */
139 int
140 dpif_delete(struct dpif *dpif)
141 {
142     int error;
143
144     COVERAGE_INC(dpif_destroy);
145
146     error = dpif->class->delete(dpif);
147     log_operation(dpif, "delete", error);
148     return error;
149 }
150
151 /* Retrieves statistics for 'dpif' into 'stats'.  Returns 0 if successful,
152  * otherwise a positive errno value. */
153 int
154 dpif_get_dp_stats(const struct dpif *dpif, struct odp_stats *stats)
155 {
156     int error = dpif->class->get_stats(dpif, stats);
157     if (error) {
158         memset(stats, 0, sizeof *stats);
159     }
160     log_operation(dpif, "get_stats", error);
161     return error;
162 }
163
164 /* Retrieves the current IP fragment handling policy for 'dpif' into
165  * '*drop_frags': true indicates that fragments are dropped, false indicates
166  * that fragments are treated in the same way as other IP packets (except that
167  * the L4 header cannot be read).  Returns 0 if successful, otherwise a
168  * positive errno value. */
169 int
170 dpif_get_drop_frags(const struct dpif *dpif, bool *drop_frags)
171 {
172     int error = dpif->class->get_drop_frags(dpif, drop_frags);
173     if (error) {
174         *drop_frags = false;
175     }
176     log_operation(dpif, "get_drop_frags", error);
177     return error;
178 }
179
180 /* Changes 'dpif''s treatment of IP fragments to 'drop_frags', whose meaning is
181  * the same as for the get_drop_frags member function.  Returns 0 if
182  * successful, otherwise a positive errno value. */
183 int
184 dpif_set_drop_frags(struct dpif *dpif, bool drop_frags)
185 {
186     int error = dpif->class->set_drop_frags(dpif, drop_frags);
187     log_operation(dpif, "set_drop_frags", error);
188     return error;
189 }
190
191 /* Attempts to add 'devname' as a port on 'dpif', given the combination of
192  * ODP_PORT_* flags in 'flags'.  If successful, returns 0 and sets '*port_nop'
193  * to the new port's port number (if 'port_nop' is non-null).  On failure,
194  * returns a positive errno value and sets '*port_nop' to UINT16_MAX (if
195  * 'port_nop' is non-null). */
196 int
197 dpif_port_add(struct dpif *dpif, const char *devname, uint16_t flags,
198               uint16_t *port_nop)
199 {
200     uint16_t port_no;
201     int error;
202
203     COVERAGE_INC(dpif_port_add);
204
205     error = dpif->class->port_add(dpif, devname, flags, &port_no);
206     if (!error) {
207         VLOG_DBG_RL(&dpmsg_rl, "%s: added %s as port %"PRIu16,
208                     dpif_name(dpif), devname, port_no);
209     } else {
210         VLOG_WARN_RL(&error_rl, "%s: failed to add %s as port: %s",
211                      dpif_name(dpif), devname, strerror(error));
212         port_no = UINT16_MAX;
213     }
214     if (port_nop) {
215         *port_nop = port_no;
216     }
217     return error;
218 }
219
220 /* Attempts to remove 'dpif''s port number 'port_no'.  Returns 0 if successful,
221  * otherwise a positive errno value. */
222 int
223 dpif_port_del(struct dpif *dpif, uint16_t port_no)
224 {
225     int error;
226
227     COVERAGE_INC(dpif_port_del);
228
229     error = dpif->class->port_del(dpif, port_no);
230     log_operation(dpif, "port_del", error);
231     return error;
232 }
233
234 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and
235  * initializes '*port' appropriately; on failure, returns a positive errno
236  * value. */
237 int
238 dpif_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
239                           struct odp_port *port)
240 {
241     int error = dpif->class->port_query_by_number(dpif, port_no, port);
242     if (!error) {
243         VLOG_DBG_RL(&dpmsg_rl, "%s: port %"PRIu16" is device %s",
244                     dpif_name(dpif), port_no, port->devname);
245     } else {
246         memset(port, 0, sizeof *port);
247         VLOG_WARN_RL(&error_rl, "%s: failed to query port %"PRIu16": %s",
248                      dpif_name(dpif), port_no, strerror(error));
249     }
250     return error;
251 }
252
253 /* Looks up port named 'devname' in 'dpif'.  On success, returns 0 and
254  * initializes '*port' appropriately; on failure, returns a positive errno
255  * value. */
256 int
257 dpif_port_query_by_name(const struct dpif *dpif, const char *devname,
258                         struct odp_port *port)
259 {
260     int error = dpif->class->port_query_by_name(dpif, devname, port);
261     if (!error) {
262         VLOG_DBG_RL(&dpmsg_rl, "%s: device %s is on port %"PRIu16,
263                     dpif_name(dpif), devname, port->port);
264     } else {
265         memset(port, 0, sizeof *port);
266
267         /* Log level is DBG here because all the current callers are interested
268          * in whether 'dpif' actually has a port 'devname', so that it's not an
269          * issue worth logging if it doesn't. */
270         VLOG_DBG_RL(&error_rl, "%s: failed to query port %s: %s",
271                     dpif_name(dpif), devname, strerror(error));
272     }
273     return error;
274 }
275
276 /* Looks up port number 'port_no' in 'dpif'.  On success, returns 0 and copies
277  * the port's name into the 'name_size' bytes in 'name', ensuring that the
278  * result is null-terminated.  On failure, returns a positive errno value and
279  * makes 'name' the empty string. */
280 int
281 dpif_port_get_name(struct dpif *dpif, uint16_t port_no,
282                    char *name, size_t name_size)
283 {
284     struct odp_port port;
285     int error;
286
287     assert(name_size > 0);
288
289     error = dpif_port_query_by_number(dpif, port_no, &port);
290     if (!error) {
291         ovs_strlcpy(name, port.devname, name_size);
292     } else {
293         *name = '\0';
294     }
295     return error;
296 }
297
298 /* Obtains a list of all the ports in 'dpif'.
299  *
300  * If successful, returns 0 and sets '*portsp' to point to an array of
301  * appropriately initialized port structures and '*n_portsp' to the number of
302  * ports in the array.  The caller is responsible for freeing '*portp' by
303  * calling free().
304  *
305  * On failure, returns a positive errno value and sets '*portsp' to NULL and
306  * '*n_portsp' to 0. */
307 int
308 dpif_port_list(const struct dpif *dpif,
309                struct odp_port **portsp, size_t *n_portsp)
310 {
311     struct odp_port *ports;
312     size_t n_ports;
313     int error;
314
315     for (;;) {
316         struct odp_stats stats;
317         int retval;
318
319         error = dpif_get_dp_stats(dpif, &stats);
320         if (error) {
321             goto exit;
322         }
323
324         ports = xcalloc(stats.n_ports, sizeof *ports);
325         retval = dpif->class->port_list(dpif, ports, stats.n_ports);
326         if (retval < 0) {
327             /* Hard error. */
328             error = -retval;
329             free(ports);
330             goto exit;
331         } else if (retval <= stats.n_ports) {
332             /* Success. */
333             error = 0;
334             n_ports = retval;
335             goto exit;
336         } else {
337             /* Soft error: port count increased behind our back.  Try again. */
338             free(ports);
339         }
340     }
341
342 exit:
343     if (error) {
344         *portsp = NULL;
345         *n_portsp = 0;
346     } else {
347         *portsp = ports;
348         *n_portsp = n_ports;
349     }
350     log_operation(dpif, "port_list", error);
351     return error;
352 }
353
354 /* Retrieves a list of the port numbers in port group 'group' in 'dpif'.
355  *
356  * On success, returns 0 and points '*ports' to a newly allocated array of
357  * integers, each of which is a 'dpif' port number for a port in
358  * 'group'.  Stores the number of elements in the array in '*n_ports'.  The
359  * caller is responsible for freeing '*ports' by calling free().
360  *
361  * On failure, returns a positive errno value and sets '*ports' to NULL and
362  * '*n_ports' to 0. */
363 int
364 dpif_port_group_get(const struct dpif *dpif, uint16_t group,
365                     uint16_t **ports, size_t *n_ports)
366 {
367     int error;
368
369     *ports = NULL;
370     *n_ports = 0;
371     for (;;) {
372         int retval = dpif->class->port_group_get(dpif, group,
373                                                  *ports, *n_ports);
374         if (retval < 0) {
375             /* Hard error. */
376             error = -retval;
377             free(*ports);
378             *ports = NULL;
379             *n_ports = 0;
380             break;
381         } else if (retval <= *n_ports) {
382             /* Success. */
383             error = 0;
384             *n_ports = retval;
385             break;
386         } else {
387             /* Soft error: there were more ports than we expected in the
388              * group.  Try again. */
389             free(*ports);
390             *ports = xcalloc(retval, sizeof **ports);
391             *n_ports = retval;
392         }
393     }
394     log_operation(dpif, "port_group_get", error);
395     return error;
396 }
397
398 /* Updates port group 'group' in 'dpif', making it contain the 'n_ports' ports
399  * whose 'dpif' port numbers are given in 'n_ports'.  Returns 0 if
400  * successful, otherwise a positive errno value.
401  *
402  * Behavior is undefined if the values in ports[] are not unique. */
403 int
404 dpif_port_group_set(struct dpif *dpif, uint16_t group,
405                     const uint16_t ports[], size_t n_ports)
406 {
407     int error;
408
409     COVERAGE_INC(dpif_port_group_set);
410
411     error = dpif->class->port_group_set(dpif, group, ports, n_ports);
412     log_operation(dpif, "port_group_set", error);
413     return error;
414 }
415
416 /* Deletes all flows from 'dpif'.  Returns 0 if successful, otherwise a
417  * positive errno value.  */
418 int
419 dpif_flow_flush(struct dpif *dpif)
420 {
421     int error;
422
423     COVERAGE_INC(dpif_flow_flush);
424
425     error = dpif->class->flow_flush(dpif);
426     log_operation(dpif, "flow_flush", error);
427     return error;
428 }
429
430 /* Queries 'dpif' for a flow entry matching 'flow->key'.
431  *
432  * If a flow matching 'flow->key' exists in 'dpif', stores statistics for the
433  * flow into 'flow->stats'.  If 'flow->n_actions' is zero, then 'flow->actions'
434  * is ignored.  If 'flow->n_actions' is nonzero, then 'flow->actions' should
435  * point to an array of the specified number of actions.  At most that many of
436  * the flow's actions will be copied into that array.  'flow->n_actions' will
437  * be updated to the number of actions actually present in the flow, which may
438  * be greater than the number stored if the flow has more actions than space
439  * available in the array.
440  *
441  * If no flow matching 'flow->key' exists in 'dpif', returns ENOENT.  On other
442  * failure, returns a positive errno value. */
443 int
444 dpif_flow_get(const struct dpif *dpif, struct odp_flow *flow)
445 {
446     int error;
447
448     COVERAGE_INC(dpif_flow_get);
449
450     check_rw_odp_flow(flow);
451     error = dpif->class->flow_get(dpif, flow, 1);
452     if (!error) {
453         error = flow->stats.error;
454     }
455     if (should_log_flow_message(error)) {
456         log_flow_operation(dpif, "flow_get", error, flow);
457     }
458     return error;
459 }
460
461 /* For each flow 'flow' in the 'n' flows in 'flows':
462  *
463  * - If a flow matching 'flow->key' exists in 'dpif':
464  *
465  *     Stores 0 into 'flow->stats.error' and stores statistics for the flow
466  *     into 'flow->stats'.
467  *
468  *     If 'flow->n_actions' is zero, then 'flow->actions' is ignored.  If
469  *     'flow->n_actions' is nonzero, then 'flow->actions' should point to an
470  *     array of the specified number of actions.  At most that many of the
471  *     flow's actions will be copied into that array.  'flow->n_actions' will
472  *     be updated to the number of actions actually present in the flow, which
473  *     may be greater than the number stored if the flow has more actions than
474  *     space available in the array.
475  *
476  * - Flow-specific errors are indicated by a positive errno value in
477  *   'flow->stats.error'.  In particular, ENOENT indicates that no flow
478  *   matching 'flow->key' exists in 'dpif'.  When an error value is stored, the
479  *   contents of 'flow->key' are preserved but other members of 'flow' should
480  *   be treated as indeterminate.
481  *
482  * Returns 0 if all 'n' flows in 'flows' were updated (whether they were
483  * individually successful or not is indicated by 'flow->stats.error',
484  * however).  Returns a positive errno value if an error that prevented this
485  * update occurred, in which the caller must not depend on any elements in
486  * 'flows' being updated or not updated.
487  */
488 int
489 dpif_flow_get_multiple(const struct dpif *dpif,
490                        struct odp_flow flows[], size_t n)
491 {
492     int error;
493     size_t i;
494
495     COVERAGE_ADD(dpif_flow_get, n);
496
497     for (i = 0; i < n; i++) {
498         check_rw_odp_flow(&flows[i]);
499     }
500
501     error = dpif->class->flow_get(dpif, flows, n);
502     log_operation(dpif, "flow_get_multiple", error);
503     return error;
504 }
505
506 /* Adds or modifies a flow in 'dpif' as specified in 'put':
507  *
508  * - If the flow specified in 'put->flow' does not exist in 'dpif', then
509  *   behavior depends on whether ODPPF_CREATE is specified in 'put->flags': if
510  *   it is, the flow will be added, otherwise the operation will fail with
511  *   ENOENT.
512  *
513  * - Otherwise, the flow specified in 'put->flow' does exist in 'dpif'.
514  *   Behavior in this case depends on whether ODPPF_MODIFY is specified in
515  *   'put->flags': if it is, the flow's actions will be updated, otherwise the
516  *   operation will fail with EEXIST.  If the flow's actions are updated, then
517  *   its statistics will be zeroed if ODPPF_ZERO_STATS is set in 'put->flags',
518  *   left as-is otherwise.
519  *
520  * Returns 0 if successful, otherwise a positive errno value.
521  */
522 int
523 dpif_flow_put(struct dpif *dpif, struct odp_flow_put *put)
524 {
525     int error;
526
527     COVERAGE_INC(dpif_flow_put);
528
529     error = dpif->class->flow_put(dpif, put);
530     if (should_log_flow_message(error)) {
531         log_flow_put(dpif, error, put);
532     }
533     return error;
534 }
535
536 /* Deletes a flow matching 'flow->key' from 'dpif' or returns ENOENT if 'dpif'
537  * does not contain such a flow.
538  *
539  * If successful, updates 'flow->stats', 'flow->n_actions', and 'flow->actions'
540  * as described for dpif_flow_get(). */
541 int
542 dpif_flow_del(struct dpif *dpif, struct odp_flow *flow)
543 {
544     int error;
545
546     COVERAGE_INC(dpif_flow_del);
547
548     check_rw_odp_flow(flow);
549     memset(&flow->stats, 0, sizeof flow->stats);
550
551     error = dpif->class->flow_del(dpif, flow);
552     if (should_log_flow_message(error)) {
553         log_flow_operation(dpif, "delete flow", error, flow);
554     }
555     return error;
556 }
557
558 /* Stores up to 'n' flows in 'dpif' into 'flows', including their statistics
559  * but not including any information about their actions.  If successful,
560  * returns 0 and sets '*n_out' to the number of flows actually present in
561  * 'dpif', which might be greater than the number stored (if 'dpif' has more
562  * than 'n' flows).  On failure, returns a negative errno value and sets
563  * '*n_out' to 0. */
564 int
565 dpif_flow_list(const struct dpif *dpif, struct odp_flow flows[], size_t n,
566                size_t *n_out)
567 {
568     uint32_t i;
569     int retval;
570
571     COVERAGE_INC(dpif_flow_query_list);
572     if (RUNNING_ON_VALGRIND) {
573         memset(flows, 0, n * sizeof *flows);
574     } else {
575         for (i = 0; i < n; i++) {
576             flows[i].actions = NULL;
577             flows[i].n_actions = 0;
578         }
579     }
580     retval = dpif->class->flow_list(dpif, flows, n);
581     if (retval < 0) {
582         *n_out = 0;
583         VLOG_WARN_RL(&error_rl, "%s: flow list failed (%s)",
584                      dpif_name(dpif), strerror(-retval));
585         return -retval;
586     } else {
587         COVERAGE_ADD(dpif_flow_query_list_n, retval);
588         *n_out = MIN(n, retval);
589         VLOG_DBG_RL(&dpmsg_rl, "%s: listed %zu flows (of %d)",
590                     dpif_name(dpif), *n_out, retval);
591         return 0;
592     }
593 }
594
595 /* Retrieves all of the flows in 'dpif'.
596  *
597  * If successful, returns 0 and stores in '*flowsp' a pointer to a newly
598  * allocated array of flows, including their statistics but not including any
599  * information about their actions, and sets '*np' to the number of flows in
600  * '*flowsp'.  The caller is responsible for freeing '*flowsp' by calling
601  * free().
602  *
603  * On failure, returns a positive errno value and sets '*flowsp' to NULL and
604  * '*np' to 0. */
605 int
606 dpif_flow_list_all(const struct dpif *dpif,
607                    struct odp_flow **flowsp, size_t *np)
608 {
609     struct odp_stats stats;
610     struct odp_flow *flows;
611     size_t n_flows;
612     int error;
613
614     *flowsp = NULL;
615     *np = 0;
616
617     error = dpif_get_dp_stats(dpif, &stats);
618     if (error) {
619         return error;
620     }
621
622     flows = xmalloc(sizeof *flows * stats.n_flows);
623     error = dpif_flow_list(dpif, flows, stats.n_flows, &n_flows);
624     if (error) {
625         free(flows);
626         return error;
627     }
628
629     if (stats.n_flows != n_flows) {
630         VLOG_WARN_RL(&error_rl, "%s: datapath stats reported %"PRIu32" "
631                      "flows but flow listing reported %zu",
632                      dpif_name(dpif), stats.n_flows, n_flows);
633     }
634     *flowsp = flows;
635     *np = n_flows;
636     return 0;
637 }
638
639 /* Causes 'dpif' to perform the 'n_actions' actions in 'actions' on the
640  * Ethernet frame specified in 'packet'.
641  *
642  * Pretends that the frame was originally received on the port numbered
643  * 'in_port'.  This affects only ODPAT_OUTPUT_GROUP actions, which will not
644  * send a packet out their input port.  Specify the number of an unused port
645  * (e.g. UINT16_MAX is currently always unused) to avoid this behavior.
646  *
647  * Returns 0 if successful, otherwise a positive errno value. */
648 int
649 dpif_execute(struct dpif *dpif, uint16_t in_port,
650              const union odp_action actions[], size_t n_actions,
651              const struct ofpbuf *buf)
652 {
653     int error;
654
655     COVERAGE_INC(dpif_execute);
656     if (n_actions > 0) {
657         error = dpif->class->execute(dpif, in_port, actions, n_actions, buf);
658     } else {
659         error = 0;
660     }
661
662     if (!(error ? VLOG_DROP_WARN(&error_rl) : VLOG_DROP_DBG(&dpmsg_rl))) {
663         struct ds ds = DS_EMPTY_INITIALIZER;
664         char *packet = ofp_packet_to_string(buf->data, buf->size, buf->size);
665         ds_put_format(&ds, "%s: execute ", dpif_name(dpif));
666         format_odp_actions(&ds, actions, n_actions);
667         if (error) {
668             ds_put_format(&ds, " failed (%s)", strerror(error));
669         }
670         ds_put_format(&ds, " on packet %s", packet);
671         vlog(THIS_MODULE, error ? VLL_WARN : VLL_DBG, "%s", ds_cstr(&ds));
672         ds_destroy(&ds);
673         free(packet);
674     }
675     return error;
676 }
677
678 /* Retrieves 'dpif''s "listen mask" into '*listen_mask'.  Each ODPL_* bit set
679  * in '*listen_mask' indicates that dpif_recv() will receive messages of that
680  * type.  Returns 0 if successful, otherwise a positive errno value. */
681 int
682 dpif_recv_get_mask(const struct dpif *dpif, int *listen_mask)
683 {
684     int error = dpif->class->recv_get_mask(dpif, listen_mask);
685     if (error) {
686         *listen_mask = 0;
687     }
688     log_operation(dpif, "recv_get_mask", error);
689     return error;
690 }
691
692 /* Sets 'dpif''s "listen mask" to 'listen_mask'.  Each ODPL_* bit set in
693  * '*listen_mask' requests that dpif_recv() receive messages of that type.
694  * Returns 0 if successful, otherwise a positive errno value. */
695 int
696 dpif_recv_set_mask(struct dpif *dpif, int listen_mask)
697 {
698     int error = dpif->class->recv_set_mask(dpif, listen_mask);
699     log_operation(dpif, "recv_set_mask", error);
700     return error;
701 }
702
703 /* Attempts to receive a message from 'dpif'.  If successful, stores the
704  * message into '*packetp'.  The message, if one is received, will begin with
705  * 'struct odp_msg' as a header.  Only messages of the types selected with
706  * dpif_set_listen_mask() will ordinarily be received (but if a message type is
707  * enabled and then later disabled, some stragglers might pop up).
708  *
709  * Returns 0 if successful, otherwise a positive errno value.  Returns EAGAIN
710  * if no message is immediately available. */
711 int
712 dpif_recv(struct dpif *dpif, struct ofpbuf **packetp)
713 {
714     int error = dpif->class->recv(dpif, packetp);
715     if (!error) {
716         if (VLOG_IS_DBG_ENABLED()) {
717             struct ofpbuf *buf = *packetp;
718             struct odp_msg *msg = buf->data;
719             void *payload = msg + 1;
720             size_t payload_len = buf->size - sizeof *msg;
721             char *s = ofp_packet_to_string(payload, payload_len, payload_len);
722             VLOG_DBG_RL(&dpmsg_rl, "%s: received %s message of length "
723                         "%zu on port %"PRIu16": %s", dpif_name(dpif),
724                         (msg->type == _ODPL_MISS_NR ? "miss"
725                          : msg->type == _ODPL_ACTION_NR ? "action"
726                          : "<unknown>"),
727                         payload_len, msg->port, s);
728             free(s);
729         }
730     } else {
731         *packetp = NULL;
732     }
733     return error;
734 }
735
736 /* Discards all messages that would otherwise be received by dpif_recv() on
737  * 'dpif'.  Returns 0 if successful, otherwise a positive errno value. */
738 int
739 dpif_recv_purge(struct dpif *dpif)
740 {
741     struct odp_stats stats;
742     unsigned int i;
743     int error;
744
745     COVERAGE_INC(dpif_purge);
746
747     error = dpif_get_dp_stats(dpif, &stats);
748     if (error) {
749         return error;
750     }
751
752     for (i = 0; i < stats.max_miss_queue + stats.max_action_queue; i++) {
753         struct ofpbuf *buf;
754         error = dpif_recv(dpif, &buf);
755         if (error) {
756             return error == EAGAIN ? 0 : error;
757         }
758         ofpbuf_delete(buf);
759     }
760     return 0;
761 }
762
763 /* Arranges for the poll loop to wake up when 'dpif' has a message queued to be
764  * received with dpif_recv(). */
765 void
766 dpif_recv_wait(struct dpif *dpif)
767 {
768     dpif->class->recv_wait(dpif);
769 }
770
771 /* Obtains the NetFlow engine type and engine ID for 'dpif' into '*engine_type'
772  * and '*engine_id', respectively. */
773 void
774 dpif_get_netflow_ids(const struct dpif *dpif,
775                      uint8_t *engine_type, uint8_t *engine_id)
776 {
777     *engine_type = dpif->netflow_engine_type;
778     *engine_id = dpif->netflow_engine_id;
779 }
780 \f
781 void
782 dpif_init(struct dpif *dpif, const struct dpif_class *class, const char *name,
783           uint8_t netflow_engine_type, uint8_t netflow_engine_id)
784 {
785     dpif->class = class;
786     dpif->name = xstrdup(name);
787     dpif->netflow_engine_type = netflow_engine_type;
788     dpif->netflow_engine_id = netflow_engine_id;
789 }
790 \f
791 static void
792 log_operation(const struct dpif *dpif, const char *operation, int error)
793 {
794     if (!error) {
795         VLOG_DBG_RL(&dpmsg_rl, "%s: %s success", dpif_name(dpif), operation);
796     } else {
797         VLOG_WARN_RL(&error_rl, "%s: %s failed (%s)",
798                      dpif_name(dpif), operation, strerror(error));
799     }
800 }
801
802 static enum vlog_level
803 flow_message_log_level(int error)
804 {
805     return error ? VLL_WARN : VLL_DBG;
806 }
807
808 static bool
809 should_log_flow_message(int error)
810 {
811     return !vlog_should_drop(THIS_MODULE, flow_message_log_level(error),
812                              error ? &error_rl : &dpmsg_rl);
813 }
814
815 static void
816 log_flow_message(const struct dpif *dpif, int error, const char *operation,
817                  const flow_t *flow, const struct odp_flow_stats *stats,
818                  const union odp_action *actions, size_t n_actions)
819 {
820     struct ds ds = DS_EMPTY_INITIALIZER;
821     ds_put_format(&ds, "%s: ", dpif_name(dpif));
822     if (error) {
823         ds_put_cstr(&ds, "failed to ");
824     }
825     ds_put_format(&ds, "%s ", operation);
826     if (error) {
827         ds_put_format(&ds, "(%s) ", strerror(error));
828     }
829     flow_format(&ds, flow);
830     if (stats) {
831         ds_put_cstr(&ds, ", ");
832         format_odp_flow_stats(&ds, stats);
833     }
834     if (actions || n_actions) {
835         ds_put_cstr(&ds, ", actions:");
836         format_odp_actions(&ds, actions, n_actions);
837     }
838     vlog(THIS_MODULE, flow_message_log_level(error), "%s", ds_cstr(&ds));
839     ds_destroy(&ds);
840 }
841
842 static void
843 log_flow_operation(const struct dpif *dpif, const char *operation, int error,
844                    struct odp_flow *flow)
845 {
846     if (error) {
847         flow->n_actions = 0;
848     }
849     log_flow_message(dpif, error, operation, &flow->key,
850                      !error ? &flow->stats : NULL,
851                      flow->actions, flow->n_actions);
852 }
853
854 static void
855 log_flow_put(struct dpif *dpif, int error, const struct odp_flow_put *put)
856 {
857     enum { ODPPF_ALL = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS };
858     struct ds s;
859
860     ds_init(&s);
861     ds_put_cstr(&s, "put");
862     if (put->flags & ODPPF_CREATE) {
863         ds_put_cstr(&s, "[create]");
864     }
865     if (put->flags & ODPPF_MODIFY) {
866         ds_put_cstr(&s, "[modify]");
867     }
868     if (put->flags & ODPPF_ZERO_STATS) {
869         ds_put_cstr(&s, "[zero]");
870     }
871     if (put->flags & ~ODPPF_ALL) {
872         ds_put_format(&s, "[%x]", put->flags & ~ODPPF_ALL);
873     }
874     log_flow_message(dpif, error, ds_cstr(&s), &put->flow.key,
875                      !error ? &put->flow.stats : NULL,
876                      put->flow.actions, put->flow.n_actions);
877     ds_destroy(&s);
878 }
879
880 /* There is a tendency to construct odp_flow objects on the stack and to
881  * forget to properly initialize their "actions" and "n_actions" members.
882  * When this happens, we get memory corruption because the kernel
883  * writes through the random pointer that is in the "actions" member.
884  *
885  * This function attempts to combat the problem by:
886  *
887  *      - Forcing a segfault if "actions" points to an invalid region (instead
888  *        of just getting back EFAULT, which can be easily missed in the log).
889  *
890  *      - Storing a distinctive value that is likely to cause an
891  *        easy-to-identify error later if it is dereferenced, etc.
892  *
893  *      - Triggering a warning on uninitialized memory from Valgrind if
894  *        "actions" or "n_actions" was not initialized.
895  */
896 static void
897 check_rw_odp_flow(struct odp_flow *flow)
898 {
899     if (flow->n_actions) {
900         memset(&flow->actions[0], 0xcc, sizeof flow->actions[0]);
901     }
902 }
903 \f
904 #include <net/if.h>
905 #include <linux/rtnetlink.h>
906 #include <linux/ethtool.h>
907 #include <linux/sockios.h>
908 #include <netinet/in.h>
909 #include <sys/ioctl.h>
910 #include <sys/stat.h>
911 #include <sys/sysmacros.h>
912 #include <unistd.h>
913
914 struct dpifmon {
915     struct dpif *dpif;
916     struct nl_sock *sock;
917     int local_ifindex;
918 };
919
920 int
921 dpifmon_create(const char *datapath_name, struct dpifmon **monp)
922 {
923     struct dpifmon *mon;
924     char local_name[IFNAMSIZ];
925     int error;
926
927     mon = *monp = xmalloc(sizeof *mon);
928
929     error = dpif_open(datapath_name, &mon->dpif);
930     if (error) {
931         goto error;
932     }
933     error = dpif_port_get_name(mon->dpif, ODPP_LOCAL,
934                                local_name, sizeof local_name);
935     if (error) {
936         goto error_close_dpif;
937     }
938
939     mon->local_ifindex = if_nametoindex(local_name);
940     if (!mon->local_ifindex) {
941         error = errno;
942         VLOG_WARN("could not get ifindex of %s device: %s",
943                   local_name, strerror(errno));
944         goto error_close_dpif;
945     }
946
947     error = nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &mon->sock);
948     if (error) {
949         VLOG_WARN("could not create rtnetlink socket: %s", strerror(error));
950         goto error_close_dpif;
951     }
952
953     return 0;
954
955 error_close_dpif:
956     dpif_close(mon->dpif);
957 error:
958     free(mon);
959     *monp = NULL;
960     return error;
961 }
962
963 void
964 dpifmon_destroy(struct dpifmon *mon)
965 {
966     if (mon) {
967         dpif_close(mon->dpif);
968         nl_sock_destroy(mon->sock);
969     }
970 }
971
972 int
973 dpifmon_poll(struct dpifmon *mon, char **devnamep)
974 {
975     static struct vlog_rate_limit slow_rl = VLOG_RATE_LIMIT_INIT(1, 5);
976     static const struct nl_policy rtnlgrp_link_policy[] = {
977         [IFLA_IFNAME] = { .type = NL_A_STRING },
978         [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
979     };
980     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
981     struct ofpbuf *buf;
982     int error;
983
984     *devnamep = NULL;
985 again:
986     error = nl_sock_recv(mon->sock, &buf, false);
987     switch (error) {
988     case 0:
989         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
990                              rtnlgrp_link_policy,
991                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
992             VLOG_WARN_RL(&slow_rl, "received bad rtnl message");
993             error = ENOBUFS;
994         } else {
995             const char *devname = nl_attr_get_string(attrs[IFLA_IFNAME]);
996             bool for_us;
997
998             if (attrs[IFLA_MASTER]) {
999                 uint32_t master_ifindex = nl_attr_get_u32(attrs[IFLA_MASTER]);
1000                 for_us = master_ifindex == mon->local_ifindex;
1001             } else {
1002                 /* It's for us if that device is one of our ports. */
1003                 struct odp_port port;
1004                 for_us = !dpif_port_query_by_name(mon->dpif, devname, &port);
1005             }
1006
1007             if (!for_us) {
1008                 /* Not for us, try again. */
1009                 ofpbuf_delete(buf);
1010                 COVERAGE_INC(dpifmon_poll_false_wakeup);
1011                 goto again;
1012             }
1013             COVERAGE_INC(dpifmon_poll_changed);
1014             *devnamep = xstrdup(devname);
1015         }
1016         ofpbuf_delete(buf);
1017         break;
1018
1019     case EAGAIN:
1020         /* Nothing to do. */
1021         break;
1022
1023     case ENOBUFS:
1024         VLOG_WARN_RL(&slow_rl, "dpifmon socket overflowed");
1025         break;
1026
1027     default:
1028         VLOG_WARN_RL(&slow_rl, "error on dpifmon socket: %s", strerror(error));
1029         break;
1030     }
1031     return error;
1032 }
1033
1034 void
1035 dpifmon_run(struct dpifmon *mon UNUSED)
1036 {
1037     /* Nothing to do in this implementation. */
1038 }
1039
1040 void
1041 dpifmon_wait(struct dpifmon *mon)
1042 {
1043     nl_sock_wait(mon->sock, POLLIN);
1044 }