datapath: Convert upcalls and ODP_EXECUTE to use AF_NETLINK socket layer.
[sliver-openvswitch.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 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
19 #include "dpif-linux.h"
20
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
26 #include <net/if.h>
27 #include <linux/types.h>
28 #include <linux/ethtool.h>
29 #include <linux/pkt_sched.h>
30 #include <linux/rtnetlink.h>
31 #include <linux/sockios.h>
32 #include <stdlib.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "dpif-provider.h"
38 #include "netdev.h"
39 #include "netdev-vport.h"
40 #include "netlink-socket.h"
41 #include "netlink.h"
42 #include "odp-util.h"
43 #include "ofpbuf.h"
44 #include "openvswitch/tunnel.h"
45 #include "packets.h"
46 #include "poll-loop.h"
47 #include "rtnetlink.h"
48 #include "rtnetlink-link.h"
49 #include "shash.h"
50 #include "svec.h"
51 #include "unaligned.h"
52 #include "util.h"
53 #include "vlog.h"
54
55 VLOG_DEFINE_THIS_MODULE(dpif_linux);
56
57 struct dpif_linux_dp {
58     /* ioctl command argument. */
59     int cmd;
60
61     /* struct odp_datapath header. */
62     uint32_t dp_idx;
63
64     /* Attributes. */
65     const char *name;                  /* ODP_DP_ATTR_NAME. */
66     struct odp_stats stats;            /* ODP_DP_ATTR_STATS. */
67     enum odp_frag_handling ipv4_frags; /* ODP_DP_ATTR_IPV4_FRAGS. */
68     const uint32_t *sampling;          /* ODP_DP_ATTR_SAMPLING. */
69     uint32_t mcgroups[DPIF_N_UC_TYPES]; /* ODP_DP_ATTR_MCGROUPS. */
70 };
71
72 static void dpif_linux_dp_init(struct dpif_linux_dp *);
73 static int dpif_linux_dp_transact(const struct dpif_linux_dp *request,
74                                   struct dpif_linux_dp *reply,
75                                   struct ofpbuf **bufp);
76 static int dpif_linux_dp_get(const struct dpif *, struct dpif_linux_dp *reply,
77                              struct ofpbuf **bufp);
78
79 struct dpif_linux_flow {
80     /* ioctl command argument. */
81     int cmd;
82
83     /* struct odp_flow header. */
84     unsigned int nlmsg_flags;
85     uint32_t dp_idx;
86
87     /* Attributes.
88      *
89      * The 'stats', 'used', and 'state' members point to 64-bit data that might
90      * only be aligned on 32-bit boundaries, so get_unaligned_u64() should be
91      * used to access their values. */
92     const struct nlattr *key;           /* ODP_FLOW_ATTR_KEY. */
93     size_t key_len;
94     const struct nlattr *actions;       /* ODP_FLOW_ATTR_ACTIONS. */
95     size_t actions_len;
96     const struct odp_flow_stats *stats; /* ODP_FLOW_ATTR_STATS. */
97     const uint8_t *tcp_flags;           /* ODP_FLOW_ATTR_TCP_FLAGS. */
98     const uint64_t *used;               /* ODP_FLOW_ATTR_USED. */
99     bool clear;                         /* ODP_FLOW_ATTR_CLEAR. */
100     const uint64_t *state;              /* ODP_FLOW_ATTR_STATE. */
101 };
102
103 static void dpif_linux_flow_init(struct dpif_linux_flow *);
104 static int dpif_linux_flow_transact(const struct dpif_linux_flow *request,
105                                     struct dpif_linux_flow *reply,
106                                     struct ofpbuf **bufp);
107 static void dpif_linux_flow_get_stats(const struct dpif_linux_flow *,
108                                       struct dpif_flow_stats *);
109
110 /* Datapath interface for the openvswitch Linux kernel module. */
111 struct dpif_linux {
112     struct dpif dpif;
113     int fd;
114
115     /* Multicast group messages. */
116     struct nl_sock *mc_sock;
117     uint32_t mcgroups[DPIF_N_UC_TYPES];
118     unsigned int listen_mask;
119
120     /* Used by dpif_linux_get_all_names(). */
121     char *local_ifname;
122     int minor;
123
124     /* Change notification. */
125     int local_ifindex;          /* Ifindex of local port. */
126     struct shash changed_ports;  /* Ports that have changed. */
127     struct rtnetlink_notifier port_notifier;
128     bool change_error;
129 };
130
131 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
132
133 /* Generic Netlink family numbers for ODP. */
134 static int odp_packet_family;
135
136 /* Generic Netlink socket. */
137 static struct nl_sock *genl_sock;
138
139 static int dpif_linux_init(void);
140 static int open_dpif(const struct dpif_linux_dp *,
141                      const struct dpif_linux_vport *local_vport,
142                      struct dpif **);
143 static int get_openvswitch_major(void);
144 static int open_minor(int minor, int *fdp);
145 static int make_openvswitch_device(int minor, char **fnp);
146 static void dpif_linux_port_changed(const struct rtnetlink_link_change *,
147                                     void *dpif);
148
149 static struct dpif_linux *
150 dpif_linux_cast(const struct dpif *dpif)
151 {
152     dpif_assert_class(dpif, &dpif_linux_class);
153     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
154 }
155
156 static int
157 dpif_linux_enumerate(struct svec *all_dps)
158 {
159     uint32_t dp_idx;
160     int major;
161     int err;
162
163     err = dpif_linux_init();
164     if (err) {
165         return err;
166     }
167
168     /* Check that the Open vSwitch module is loaded. */
169     major = get_openvswitch_major();
170     if (major < 0) {
171         return -major;
172     }
173
174     dp_idx = 0;
175     for (;;) {
176         struct dpif_linux_dp request, reply;
177         struct ofpbuf *buf;
178         char devname[16];
179         int error;
180
181         dpif_linux_dp_init(&request);
182         request.dp_idx = dp_idx;
183         request.cmd = ODP_DP_DUMP;
184
185         error = dpif_linux_dp_transact(&request, &reply, &buf);
186         if (error) {
187             return error == ENODEV ? 0 : error;
188         }
189         ofpbuf_delete(buf);
190
191         sprintf(devname, "dp%d", reply.dp_idx);
192         svec_add(all_dps, devname);
193
194         dp_idx = reply.dp_idx + 1;
195     }
196 }
197
198 static int
199 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
200                 bool create, struct dpif **dpifp)
201 {
202     struct dpif_linux_vport vport_request, vport;
203     struct dpif_linux_dp dp_request, dp;
204     struct ofpbuf *buf;
205     int minor;
206     int error;
207
208     error = dpif_linux_init();
209     if (error) {
210         return error;
211     }
212
213     minor = !strncmp(name, "dp", 2)
214             && isdigit((unsigned char)name[2]) ? atoi(name + 2) : -1;
215
216     /* Create or look up datapath. */
217     dpif_linux_dp_init(&dp_request);
218     dp_request.cmd = create ? ODP_DP_NEW : ODP_DP_GET;
219     dp_request.dp_idx = minor;
220     dp_request.name = minor < 0 ? name : NULL;
221     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
222     if (error) {
223         return error;
224     }
225     ofpbuf_delete(buf);         /* Pointers inside 'dp' are now invalid! */
226
227     /* Look up local port. */
228     dpif_linux_vport_init(&vport_request);
229     vport_request.cmd = ODP_VPORT_GET;
230     vport_request.dp_idx = dp.dp_idx;
231     vport_request.port_no = ODPP_LOCAL;
232     vport_request.name = minor < 0 ? name : NULL;
233     error = dpif_linux_vport_transact(&vport_request, &vport, &buf);
234     if (error) {
235         return error;
236     } else if (vport.port_no != ODPP_LOCAL) {
237         /* This is an Open vSwitch device but not the local port.  We
238          * intentionally support only using the name of the local port as the
239          * name of a datapath; otherwise, it would be too difficult to
240          * enumerate all the names of a datapath. */
241         error = EOPNOTSUPP;
242     } else {
243         error = open_dpif(&dp, &vport, dpifp);
244     }
245     ofpbuf_delete(buf);
246     return error;
247 }
248
249 static int
250 open_dpif(const struct dpif_linux_dp *dp,
251           const struct dpif_linux_vport *local_vport, struct dpif **dpifp)
252 {
253     int dp_idx = local_vport->dp_idx;
254     struct dpif_linux *dpif;
255     char *name;
256     int error;
257     int fd;
258     int i;
259
260     error = open_minor(dp_idx, &fd);
261     if (error) {
262         goto error;
263     }
264
265     dpif = xmalloc(sizeof *dpif);
266     error = rtnetlink_link_notifier_register(&dpif->port_notifier,
267                                              dpif_linux_port_changed, dpif);
268     if (error) {
269         goto error_free;
270     }
271
272     name = xasprintf("dp%d", dp_idx);
273     dpif_init(&dpif->dpif, &dpif_linux_class, name, dp_idx, dp_idx);
274     free(name);
275
276     dpif->fd = fd;
277     dpif->mc_sock = NULL;
278     for (i = 0; i < DPIF_N_UC_TYPES; i++) {
279         dpif->mcgroups[i] = dp->mcgroups[i];
280     }
281     dpif->listen_mask = 0;
282     dpif->local_ifname = xstrdup(local_vport->name);
283     dpif->local_ifindex = local_vport->ifindex;
284     dpif->minor = dp_idx;
285     shash_init(&dpif->changed_ports);
286     dpif->change_error = false;
287     *dpifp = &dpif->dpif;
288
289     return 0;
290
291 error_free:
292     free(dpif);
293     close(fd);
294 error:
295     return error;
296 }
297
298 static void
299 dpif_linux_close(struct dpif *dpif_)
300 {
301     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
302     rtnetlink_link_notifier_unregister(&dpif->port_notifier);
303     shash_destroy(&dpif->changed_ports);
304     free(dpif->local_ifname);
305     close(dpif->fd);
306     free(dpif);
307 }
308
309 static int
310 dpif_linux_get_all_names(const struct dpif *dpif_, struct svec *all_names)
311 {
312     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
313
314     svec_add_nocopy(all_names, xasprintf("dp%d", dpif->minor));
315     svec_add(all_names, dpif->local_ifname);
316     return 0;
317 }
318
319 static int
320 dpif_linux_destroy(struct dpif *dpif_)
321 {
322     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
323     struct dpif_linux_dp dp;
324
325     dpif_linux_dp_init(&dp);
326     dp.cmd = ODP_DP_DEL;
327     dp.dp_idx = dpif->minor;
328     return dpif_linux_dp_transact(&dp, NULL, NULL);
329 }
330
331 static int
332 dpif_linux_get_stats(const struct dpif *dpif_, struct odp_stats *stats)
333 {
334     struct dpif_linux_dp dp;
335     struct ofpbuf *buf;
336     int error;
337
338     error = dpif_linux_dp_get(dpif_, &dp, &buf);
339     if (!error) {
340         *stats = dp.stats;
341         ofpbuf_delete(buf);
342     }
343     return error;
344 }
345
346 static int
347 dpif_linux_get_drop_frags(const struct dpif *dpif_, bool *drop_fragsp)
348 {
349     struct dpif_linux_dp dp;
350     struct ofpbuf *buf;
351     int error;
352
353     error = dpif_linux_dp_get(dpif_, &dp, &buf);
354     if (!error) {
355         *drop_fragsp = dp.ipv4_frags == ODP_DP_FRAG_DROP;
356         ofpbuf_delete(buf);
357     }
358     return error;
359 }
360
361 static int
362 dpif_linux_set_drop_frags(struct dpif *dpif_, bool drop_frags)
363 {
364     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
365     struct dpif_linux_dp dp;
366
367     dpif_linux_dp_init(&dp);
368     dp.cmd = ODP_DP_SET;
369     dp.dp_idx = dpif->minor;
370     dp.ipv4_frags = drop_frags ? ODP_DP_FRAG_DROP : ODP_DP_FRAG_ZERO;
371     return dpif_linux_dp_transact(&dp, NULL, NULL);
372 }
373
374 static int
375 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
376                     uint16_t *port_nop)
377 {
378     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
379     const char *name = netdev_get_name(netdev);
380     const char *type = netdev_get_type(netdev);
381     struct dpif_linux_vport request, reply;
382     const struct ofpbuf *options;
383     struct ofpbuf *buf;
384     int error;
385
386     dpif_linux_vport_init(&request);
387     request.cmd = ODP_VPORT_NEW;
388     request.dp_idx = dpif->minor;
389     request.type = netdev_vport_get_vport_type(netdev);
390     if (request.type == ODP_VPORT_TYPE_UNSPEC) {
391         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
392                      "unsupported type `%s'",
393                      dpif_name(dpif_), name, type);
394         return EINVAL;
395     }
396     request.name = name;
397
398     options = netdev_vport_get_options(netdev);
399     if (options && options->size) {
400         request.options = options->data;
401         request.options_len = options->size;
402     }
403
404     error = dpif_linux_vport_transact(&request, &reply, &buf);
405     if (!error) {
406         *port_nop = reply.port_no;
407         ofpbuf_delete(buf);
408     }
409
410     return error;
411 }
412
413 static int
414 dpif_linux_port_del(struct dpif *dpif_, uint16_t port_no)
415 {
416     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
417     struct dpif_linux_vport vport;
418
419     dpif_linux_vport_init(&vport);
420     vport.cmd = ODP_VPORT_DEL;
421     vport.dp_idx = dpif->minor;
422     vport.port_no = port_no;
423     return dpif_linux_vport_transact(&vport, NULL, NULL);
424 }
425
426 static int
427 dpif_linux_port_query__(const struct dpif *dpif, uint32_t port_no,
428                         const char *port_name, struct dpif_port *dpif_port)
429 {
430     struct dpif_linux_vport request;
431     struct dpif_linux_vport reply;
432     struct ofpbuf *buf;
433     int error;
434
435     dpif_linux_vport_init(&request);
436     request.cmd = ODP_VPORT_GET;
437     request.dp_idx = dpif_linux_cast(dpif)->minor;
438     request.port_no = port_no;
439     request.name = port_name;
440
441     error = dpif_linux_vport_transact(&request, &reply, &buf);
442     if (!error) {
443         dpif_port->name = xstrdup(reply.name);
444         dpif_port->type = xstrdup(netdev_vport_get_netdev_type(&reply));
445         dpif_port->port_no = reply.port_no;
446         ofpbuf_delete(buf);
447     }
448     return error;
449 }
450
451 static int
452 dpif_linux_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
453                                 struct dpif_port *dpif_port)
454 {
455     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
456 }
457
458 static int
459 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
460                               struct dpif_port *dpif_port)
461 {
462     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
463 }
464
465 static int
466 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
467 {
468     /* If the datapath increases its range of supported ports, then it should
469      * start reporting that. */
470     return 1024;
471 }
472
473 static int
474 dpif_linux_flow_flush(struct dpif *dpif_)
475 {
476     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
477     return ioctl(dpif->fd, ODP_FLOW_FLUSH, dpif->minor) ? errno : 0;
478 }
479
480 struct dpif_linux_port_state {
481     struct ofpbuf *buf;
482     uint32_t next;
483 };
484
485 static int
486 dpif_linux_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
487 {
488     *statep = xzalloc(sizeof(struct dpif_linux_port_state));
489     return 0;
490 }
491
492 static int
493 dpif_linux_port_dump_next(const struct dpif *dpif, void *state_,
494                           struct dpif_port *dpif_port)
495 {
496     struct dpif_linux_port_state *state = state_;
497     struct dpif_linux_vport request, reply;
498     struct ofpbuf *buf;
499     int error;
500
501     ofpbuf_delete(state->buf);
502     state->buf = NULL;
503
504     dpif_linux_vport_init(&request);
505     request.cmd = ODP_VPORT_DUMP;
506     request.dp_idx = dpif_linux_cast(dpif)->minor;
507     request.port_no = state->next;
508     error = dpif_linux_vport_transact(&request, &reply, &buf);
509     if (error) {
510         return error == ENODEV ? EOF : error;
511     } else {
512         dpif_port->name = (char *) reply.name;
513         dpif_port->type = (char *) netdev_vport_get_netdev_type(&reply);
514         dpif_port->port_no = reply.port_no;
515         state->buf = buf;
516         state->next = reply.port_no + 1;
517         return 0;
518     }
519 }
520
521 static int
522 dpif_linux_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
523 {
524     struct dpif_linux_port_state *state = state_;
525     ofpbuf_delete(state->buf);
526     free(state);
527     return 0;
528 }
529
530 static int
531 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
532 {
533     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
534
535     if (dpif->change_error) {
536         dpif->change_error = false;
537         shash_clear(&dpif->changed_ports);
538         return ENOBUFS;
539     } else if (!shash_is_empty(&dpif->changed_ports)) {
540         struct shash_node *node = shash_first(&dpif->changed_ports);
541         *devnamep = shash_steal(&dpif->changed_ports, node);
542         return 0;
543     } else {
544         return EAGAIN;
545     }
546 }
547
548 static void
549 dpif_linux_port_poll_wait(const struct dpif *dpif_)
550 {
551     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
552     if (!shash_is_empty(&dpif->changed_ports) || dpif->change_error) {
553         poll_immediate_wake();
554     } else {
555         rtnetlink_link_notifier_wait();
556     }
557 }
558
559 static int
560 dpif_linux_flow_get(const struct dpif *dpif_,
561                     const struct nlattr *key, size_t key_len,
562                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
563 {
564     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
565     struct dpif_linux_flow request, reply;
566     struct ofpbuf *buf;
567     int error;
568
569     dpif_linux_flow_init(&request);
570     request.cmd = ODP_FLOW_GET;
571     request.dp_idx = dpif->minor;
572     request.key = key;
573     request.key_len = key_len;
574     error = dpif_linux_flow_transact(&request, &reply, &buf);
575     if (!error) {
576         if (stats) {
577             dpif_linux_flow_get_stats(&reply, stats);
578         }
579         if (actionsp) {
580             buf->data = (void *) reply.actions;
581             buf->size = reply.actions_len;
582             *actionsp = buf;
583         } else {
584             ofpbuf_delete(buf);
585         }
586     }
587     return error;
588 }
589
590 static int
591 dpif_linux_flow_put(struct dpif *dpif_, enum dpif_flow_put_flags flags,
592                     const struct nlattr *key, size_t key_len,
593                     const struct nlattr *actions, size_t actions_len,
594                     struct dpif_flow_stats *stats)
595 {
596     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
597     struct dpif_linux_flow request, reply;
598     struct ofpbuf *buf;
599     int error;
600
601     dpif_linux_flow_init(&request);
602     request.cmd = flags & DPIF_FP_CREATE ? ODP_FLOW_NEW : ODP_FLOW_SET;
603     request.dp_idx = dpif->minor;
604     request.key = key;
605     request.key_len = key_len;
606     request.actions = actions;
607     request.actions_len = actions_len;
608     if (flags & DPIF_FP_ZERO_STATS) {
609         request.clear = true;
610     }
611     request.nlmsg_flags = flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
612     error = dpif_linux_flow_transact(&request,
613                                      stats ? &reply : NULL,
614                                      stats ? &buf : NULL);
615     if (!error && stats) {
616         dpif_linux_flow_get_stats(&reply, stats);
617         ofpbuf_delete(buf);
618     }
619     return error;
620 }
621
622 static int
623 dpif_linux_flow_del(struct dpif *dpif_,
624                     const struct nlattr *key, size_t key_len,
625                     struct dpif_flow_stats *stats)
626 {
627     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
628     struct dpif_linux_flow request, reply;
629     struct ofpbuf *buf;
630     int error;
631
632     dpif_linux_flow_init(&request);
633     request.cmd = ODP_FLOW_DEL;
634     request.dp_idx = dpif->minor;
635     request.key = key;
636     request.key_len = key_len;
637     error = dpif_linux_flow_transact(&request,
638                                      stats ? &reply : NULL,
639                                      stats ? &buf : NULL);
640     if (!error && stats) {
641         dpif_linux_flow_get_stats(&reply, stats);
642         ofpbuf_delete(buf);
643     }
644     return error;
645 }
646
647 struct dpif_linux_flow_state {
648     struct dpif_linux_flow flow;
649     struct ofpbuf *buf;
650     struct dpif_flow_stats stats;
651 };
652
653 static int
654 dpif_linux_flow_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
655 {
656     *statep = xzalloc(sizeof(struct dpif_linux_flow_state));
657     return 0;
658 }
659
660 static int
661 dpif_linux_flow_dump_next(const struct dpif *dpif_, void *state_,
662                           const struct nlattr **key, size_t *key_len,
663                           const struct nlattr **actions, size_t *actions_len,
664                           const struct dpif_flow_stats **stats)
665 {
666     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
667     struct dpif_linux_flow_state *state = state_;
668     struct ofpbuf *old_buf = state->buf;
669     struct dpif_linux_flow request;
670     int error;
671
672     dpif_linux_flow_init(&request);
673     request.cmd = ODP_FLOW_DUMP;
674     request.dp_idx = dpif->minor;
675     request.state = state->flow.state;
676     error = dpif_linux_flow_transact(&request, &state->flow, &state->buf);
677     ofpbuf_delete(old_buf);
678
679     if (!error) {
680         if (key) {
681             *key = state->flow.key;
682             *key_len = state->flow.key_len;
683         }
684         if (actions) {
685             *actions = state->flow.actions;
686             *actions_len = state->flow.actions_len;
687         }
688         if (stats) {
689             dpif_linux_flow_get_stats(&state->flow, &state->stats);
690             *stats = &state->stats;
691         }
692     }
693     return error == ENODEV ? EOF : error;
694 }
695
696 static int
697 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
698 {
699     struct dpif_linux_flow_state *state = state_;
700
701     ofpbuf_delete(state->buf);
702     free(state);
703     return 0;
704 }
705
706 static int
707 dpif_linux_execute(struct dpif *dpif_,
708                    const struct nlattr *actions, size_t actions_len,
709                    const struct ofpbuf *packet)
710 {
711     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
712     struct odp_header *execute;
713     struct ofpbuf *buf;
714     int error;
715
716     buf = ofpbuf_new(128 + actions_len + packet->size);
717
718     nl_msg_put_genlmsghdr(buf, 0, odp_packet_family, NLM_F_REQUEST,
719                           ODP_PACKET_CMD_EXECUTE, 1);
720
721     execute = ofpbuf_put_uninit(buf, sizeof *execute);
722     execute->dp_idx = dpif->minor;
723
724     nl_msg_put_unspec(buf, ODP_PACKET_ATTR_PACKET, packet->data, packet->size);
725     nl_msg_put_unspec(buf, ODP_PACKET_ATTR_ACTIONS, actions, actions_len);
726
727     error = nl_sock_transact(genl_sock, buf, NULL);
728     ofpbuf_delete(buf);
729     return error;
730 }
731
732 static int
733 dpif_linux_recv_get_mask(const struct dpif *dpif_, int *listen_mask)
734 {
735     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
736     *listen_mask = dpif->listen_mask;
737     return 0;
738 }
739
740 static int
741 dpif_linux_recv_set_mask(struct dpif *dpif_, int listen_mask)
742 {
743     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
744     int error;
745     int i;
746
747     if (listen_mask == dpif->listen_mask) {
748         return 0;
749     } else if (!listen_mask) {
750         nl_sock_destroy(dpif->mc_sock);
751         dpif->mc_sock = NULL;
752         dpif->listen_mask = 0;
753         return 0;
754     } else if (!dpif->mc_sock) {
755         error = nl_sock_create(NETLINK_GENERIC, &dpif->mc_sock);
756         if (error) {
757             return error;
758         }
759     }
760
761     /* Unsubscribe from old groups. */
762     for (i = 0; i < DPIF_N_UC_TYPES; i++) {
763         if (dpif->listen_mask & (1u << i)) {
764             nl_sock_leave_mcgroup(dpif->mc_sock, dpif->mcgroups[i]);
765         }
766     }
767
768     /* Update listen_mask. */
769     dpif->listen_mask = listen_mask;
770
771     /* Subscribe to new groups. */
772     error = 0;
773     for (i = 0; i < DPIF_N_UC_TYPES; i++) {
774         if (dpif->listen_mask & (1u << i)) {
775             int retval;
776
777             retval = nl_sock_join_mcgroup(dpif->mc_sock, dpif->mcgroups[i]);
778             if (retval) {
779                 error = retval;
780             }
781         }
782     }
783     return error;
784 }
785
786 static int
787 dpif_linux_get_sflow_probability(const struct dpif *dpif_,
788                                  uint32_t *probability)
789 {
790     struct dpif_linux_dp dp;
791     struct ofpbuf *buf;
792     int error;
793
794     error = dpif_linux_dp_get(dpif_, &dp, &buf);
795     if (!error) {
796         *probability = dp.sampling ? *dp.sampling : 0;
797         ofpbuf_delete(buf);
798     }
799     return error;
800 }
801
802 static int
803 dpif_linux_set_sflow_probability(struct dpif *dpif_, uint32_t probability)
804 {
805     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
806     struct dpif_linux_dp dp;
807
808     dpif_linux_dp_init(&dp);
809     dp.cmd = ODP_DP_SET;
810     dp.dp_idx = dpif->minor;
811     dp.sampling = &probability;
812     return dpif_linux_dp_transact(&dp, NULL, NULL);
813 }
814
815 static int
816 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
817                              uint32_t queue_id, uint32_t *priority)
818 {
819     if (queue_id < 0xf000) {
820         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
821         return 0;
822     } else {
823         return EINVAL;
824     }
825 }
826
827 static int
828 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
829                  uint32_t *dp_idx)
830 {
831     static const struct nl_policy odp_packet_policy[] = {
832         /* Always present. */
833         [ODP_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
834                                      .min_len = ETH_HEADER_LEN },
835         [ODP_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
836
837         /* ODP_PACKET_CMD_ACTION only. */
838         [ODP_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
839
840         /* ODP_PACKET_CMD_SAMPLE only. */
841         [ODP_PACKET_ATTR_SAMPLE_POOL] = { .type = NL_A_U32, .optional = true },
842         [ODP_PACKET_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
843     };
844
845     struct odp_header *odp_header;
846     struct nlattr *a[ARRAY_SIZE(odp_packet_policy)];
847     struct nlmsghdr *nlmsg;
848     struct genlmsghdr *genl;
849     struct ofpbuf b;
850
851     ofpbuf_use_const(&b, buf->data, buf->size);
852
853     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
854     genl = ofpbuf_try_pull(&b, sizeof *genl);
855     odp_header = ofpbuf_try_pull(&b, sizeof *odp_header);
856     if (!nlmsg || !genl || !odp_header
857         || !nl_policy_parse(&b, 0, odp_packet_policy, a,
858                             ARRAY_SIZE(odp_packet_policy))) {
859         return EINVAL;
860     }
861
862     memset(upcall, 0, sizeof *upcall);
863
864     upcall->type = (genl->cmd == ODP_PACKET_CMD_MISS ? DPIF_UC_MISS
865                     : genl->cmd == ODP_PACKET_CMD_ACTION ? DPIF_UC_ACTION
866                     : genl->cmd == ODP_PACKET_CMD_SAMPLE ? DPIF_UC_SAMPLE
867                     : -1);
868
869     upcall->packet = buf;
870     upcall->packet->data = (void *) nl_attr_get(a[ODP_PACKET_ATTR_PACKET]);
871     upcall->packet->size = nl_attr_get_size(a[ODP_PACKET_ATTR_PACKET]);
872     upcall->key = (void *) nl_attr_get(a[ODP_PACKET_ATTR_KEY]);
873     upcall->key_len = nl_attr_get_size(a[ODP_PACKET_ATTR_KEY]);
874     upcall->userdata = (a[ODP_PACKET_ATTR_USERDATA]
875                         ? nl_attr_get_u64(a[ODP_PACKET_ATTR_USERDATA])
876                         : 0);
877     upcall->sample_pool = (a[ODP_PACKET_ATTR_SAMPLE_POOL]
878                         ? nl_attr_get_u32(a[ODP_PACKET_ATTR_SAMPLE_POOL])
879                            : 0);
880     if (a[ODP_PACKET_ATTR_ACTIONS]) {
881         upcall->actions = (void *) nl_attr_get(a[ODP_PACKET_ATTR_ACTIONS]);
882         upcall->actions_len = nl_attr_get_size(a[ODP_PACKET_ATTR_ACTIONS]);
883     }
884
885     *dp_idx = odp_header->dp_idx;
886
887     return 0;
888 }
889
890 static int
891 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
892 {
893     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
894     struct ofpbuf *buf;
895     int error;
896     int i;
897
898     if (!dpif->mc_sock) {
899         return EAGAIN;
900     }
901
902     for (i = 0; i < 50; i++) {
903         uint32_t dp_idx;
904
905         error = nl_sock_recv(dpif->mc_sock, &buf, false);
906         if (error) {
907             return error;
908         }
909
910         error = parse_odp_packet(buf, upcall, &dp_idx);
911         if (!error
912             && dp_idx == dpif->minor
913             && dpif->listen_mask & (1u << upcall->type)) {
914             return 0;
915         }
916
917         ofpbuf_delete(buf);
918         if (error) {
919             return error;
920         }
921     }
922
923     return EAGAIN;
924 }
925
926 static void
927 dpif_linux_recv_wait(struct dpif *dpif_)
928 {
929     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
930     if (dpif->mc_sock) {
931         nl_sock_wait(dpif->mc_sock, POLLIN);
932     }
933 }
934
935 static void
936 dpif_linux_recv_purge(struct dpif *dpif_)
937 {
938     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
939
940     if (dpif->mc_sock) {
941         nl_sock_drain(dpif->mc_sock);
942     }
943 }
944
945 const struct dpif_class dpif_linux_class = {
946     "system",
947     NULL,                       /* run */
948     NULL,                       /* wait */
949     dpif_linux_enumerate,
950     dpif_linux_open,
951     dpif_linux_close,
952     dpif_linux_get_all_names,
953     dpif_linux_destroy,
954     dpif_linux_get_stats,
955     dpif_linux_get_drop_frags,
956     dpif_linux_set_drop_frags,
957     dpif_linux_port_add,
958     dpif_linux_port_del,
959     dpif_linux_port_query_by_number,
960     dpif_linux_port_query_by_name,
961     dpif_linux_get_max_ports,
962     dpif_linux_port_dump_start,
963     dpif_linux_port_dump_next,
964     dpif_linux_port_dump_done,
965     dpif_linux_port_poll,
966     dpif_linux_port_poll_wait,
967     dpif_linux_flow_get,
968     dpif_linux_flow_put,
969     dpif_linux_flow_del,
970     dpif_linux_flow_flush,
971     dpif_linux_flow_dump_start,
972     dpif_linux_flow_dump_next,
973     dpif_linux_flow_dump_done,
974     dpif_linux_execute,
975     dpif_linux_recv_get_mask,
976     dpif_linux_recv_set_mask,
977     dpif_linux_get_sflow_probability,
978     dpif_linux_set_sflow_probability,
979     dpif_linux_queue_to_priority,
980     dpif_linux_recv,
981     dpif_linux_recv_wait,
982     dpif_linux_recv_purge,
983 };
984 \f
985 static int get_major(const char *target);
986
987 static int
988 dpif_linux_init(void)
989 {
990     static int error = -1;
991
992     if (error < 0) {
993         error = nl_lookup_genl_family(ODP_PACKET_FAMILY, &odp_packet_family);
994         if (!error) {
995             error = nl_sock_create(NETLINK_GENERIC, &genl_sock);
996         }
997     }
998
999     return error;
1000 }
1001
1002 bool
1003 dpif_linux_is_internal_device(const char *name)
1004 {
1005     struct dpif_linux_vport reply;
1006     struct ofpbuf *buf;
1007     int error;
1008
1009     error = dpif_linux_vport_get(name, &reply, &buf);
1010     if (!error) {
1011         ofpbuf_delete(buf);
1012     } else if (error != ENODEV) {
1013         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1014                      name, strerror(error));
1015     }
1016
1017     return reply.type == ODP_VPORT_TYPE_INTERNAL;
1018 }
1019
1020 static int
1021 make_openvswitch_device(int minor, char **fnp)
1022 {
1023     const char dirname[] = "/dev/net";
1024     int major;
1025     dev_t dev;
1026     struct stat s;
1027     char fn[128];
1028
1029     *fnp = NULL;
1030
1031     major = get_openvswitch_major();
1032     if (major < 0) {
1033         return -major;
1034     }
1035     dev = makedev(major, minor);
1036
1037     sprintf(fn, "%s/dp%d", dirname, minor);
1038     if (!stat(fn, &s)) {
1039         if (!S_ISCHR(s.st_mode)) {
1040             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
1041                          fn);
1042         } else if (s.st_rdev != dev) {
1043             VLOG_WARN_RL(&error_rl,
1044                          "%s is device %u:%u but should be %u:%u, fixing",
1045                          fn, major(s.st_rdev), minor(s.st_rdev),
1046                          major(dev), minor(dev));
1047         } else {
1048             goto success;
1049         }
1050         if (unlink(fn)) {
1051             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
1052                          fn, strerror(errno));
1053             return errno;
1054         }
1055     } else if (errno == ENOENT) {
1056         if (stat(dirname, &s)) {
1057             if (errno == ENOENT) {
1058                 if (mkdir(dirname, 0755)) {
1059                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
1060                                  dirname, strerror(errno));
1061                     return errno;
1062                 }
1063             } else {
1064                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
1065                              dirname, strerror(errno));
1066                 return errno;
1067             }
1068         }
1069     } else {
1070         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
1071         return errno;
1072     }
1073
1074     /* The device needs to be created. */
1075     if (mknod(fn, S_IFCHR | 0700, dev)) {
1076         VLOG_WARN_RL(&error_rl,
1077                      "%s: creating character device %u:%u failed (%s)",
1078                      fn, major(dev), minor(dev), strerror(errno));
1079         return errno;
1080     }
1081
1082 success:
1083     *fnp = xstrdup(fn);
1084     return 0;
1085 }
1086
1087 /* Return the major device number of the Open vSwitch device.  If it
1088  * cannot be determined, a negative errno is returned. */
1089 static int
1090 get_openvswitch_major(void)
1091 {
1092     static int openvswitch_major = -1;
1093     if (openvswitch_major < 0) {
1094         openvswitch_major = get_major("openvswitch");
1095     }
1096     return openvswitch_major;
1097 }
1098
1099 static int
1100 get_major(const char *target)
1101 {
1102     const char fn[] = "/proc/devices";
1103     char line[128];
1104     FILE *file;
1105     int ln;
1106
1107     file = fopen(fn, "r");
1108     if (!file) {
1109         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
1110         return -errno;
1111     }
1112
1113     for (ln = 1; fgets(line, sizeof line, file); ln++) {
1114         char name[64];
1115         int major;
1116
1117         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
1118             /* Nothing to do. */
1119         } else if (!strncmp(line, "Block", 5)) {
1120             /* We only want character devices, so skip the rest of the file. */
1121             break;
1122         } else if (sscanf(line, "%d %63s", &major, name)) {
1123             if (!strcmp(name, target)) {
1124                 fclose(file);
1125                 return major;
1126             }
1127         } else {
1128             VLOG_WARN_ONCE("%s:%d: syntax error", fn, ln);
1129         }
1130     }
1131
1132     fclose(file);
1133
1134     VLOG_ERR("%s: %s major not found (is the module loaded?)", fn, target);
1135     return -ENODEV;
1136 }
1137
1138 static int
1139 open_minor(int minor, int *fdp)
1140 {
1141     int error;
1142     char *fn;
1143
1144     error = make_openvswitch_device(minor, &fn);
1145     if (error) {
1146         return error;
1147     }
1148
1149     *fdp = open(fn, O_RDONLY | O_NONBLOCK);
1150     if (*fdp < 0) {
1151         error = errno;
1152         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
1153         free(fn);
1154         return error;
1155     }
1156     free(fn);
1157     return 0;
1158 }
1159
1160 static void
1161 dpif_linux_port_changed(const struct rtnetlink_link_change *change,
1162                         void *dpif_)
1163 {
1164     struct dpif_linux *dpif = dpif_;
1165
1166     if (change) {
1167         if (change->master_ifindex == dpif->local_ifindex
1168             && (change->nlmsg_type == RTM_NEWLINK
1169                 || change->nlmsg_type == RTM_DELLINK))
1170         {
1171             /* Our datapath changed, either adding a new port or deleting an
1172              * existing one. */
1173             shash_add_once(&dpif->changed_ports, change->ifname, NULL);
1174         }
1175     } else {
1176         dpif->change_error = true;
1177     }
1178 }
1179
1180 static int
1181 get_dp0_fd(int *dp0_fdp)
1182 {
1183     static int dp0_fd = -1;
1184     if (dp0_fd < 0) {
1185         int error;
1186         int fd;
1187
1188         error = open_minor(0, &fd);
1189         if (error) {
1190             return error;
1191         }
1192         dp0_fd = fd;
1193     }
1194     *dp0_fdp = dp0_fd;
1195     return 0;
1196 }
1197 \f
1198 /* Parses the contents of 'buf', which contains a "struct odp_vport" followed
1199  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1200  * positive errno value.
1201  *
1202  * 'vport' will contain pointers into 'buf', so the caller should not free
1203  * 'buf' while 'vport' is still in use. */
1204 static int
1205 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1206                              const struct ofpbuf *buf)
1207 {
1208     static const struct nl_policy odp_vport_policy[] = {
1209         [ODP_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1210         [ODP_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1211         [ODP_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1212         [ODP_VPORT_ATTR_STATS] = { .type = NL_A_UNSPEC,
1213                                    .min_len = sizeof(struct rtnl_link_stats64),
1214                                    .max_len = sizeof(struct rtnl_link_stats64),
1215                                    .optional = true },
1216         [ODP_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
1217                                      .min_len = ETH_ADDR_LEN,
1218                                      .max_len = ETH_ADDR_LEN,
1219                                      .optional = true },
1220         [ODP_VPORT_ATTR_MTU] = { .type = NL_A_U32, .optional = true },
1221         [ODP_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1222         [ODP_VPORT_ATTR_IFINDEX] = { .type = NL_A_U32, .optional = true },
1223         [ODP_VPORT_ATTR_IFLINK] = { .type = NL_A_U32, .optional = true },
1224     };
1225
1226     struct odp_vport *odp_vport;
1227     struct nlattr *a[ARRAY_SIZE(odp_vport_policy)];
1228
1229     dpif_linux_vport_init(vport);
1230
1231     if (!nl_policy_parse(buf, sizeof *odp_vport, odp_vport_policy,
1232                          a, ARRAY_SIZE(odp_vport_policy))) {
1233         return EINVAL;
1234     }
1235     odp_vport = buf->data;
1236
1237     vport->dp_idx = odp_vport->dp_idx;
1238     vport->port_no = nl_attr_get_u32(a[ODP_VPORT_ATTR_PORT_NO]);
1239     vport->type = nl_attr_get_u32(a[ODP_VPORT_ATTR_TYPE]);
1240     vport->name = nl_attr_get_string(a[ODP_VPORT_ATTR_NAME]);
1241     if (a[ODP_VPORT_ATTR_STATS]) {
1242         vport->stats = nl_attr_get(a[ODP_VPORT_ATTR_STATS]);
1243     }
1244     if (a[ODP_VPORT_ATTR_ADDRESS]) {
1245         vport->address = nl_attr_get(a[ODP_VPORT_ATTR_ADDRESS]);
1246     }
1247     if (a[ODP_VPORT_ATTR_MTU]) {
1248         vport->mtu = nl_attr_get_u32(a[ODP_VPORT_ATTR_MTU]);
1249     }
1250     if (a[ODP_VPORT_ATTR_OPTIONS]) {
1251         vport->options = nl_attr_get(a[ODP_VPORT_ATTR_OPTIONS]);
1252         vport->options_len = nl_attr_get_size(a[ODP_VPORT_ATTR_OPTIONS]);
1253     }
1254     if (a[ODP_VPORT_ATTR_IFINDEX]) {
1255         vport->ifindex = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFINDEX]);
1256     }
1257     if (a[ODP_VPORT_ATTR_IFLINK]) {
1258         vport->iflink = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFLINK]);
1259     }
1260     return 0;
1261 }
1262
1263 /* Appends to 'buf' (which must initially be empty) a "struct odp_vport"
1264  * followed by Netlink attributes corresponding to 'vport'. */
1265 static void
1266 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1267                            struct ofpbuf *buf)
1268 {
1269     struct odp_vport *odp_vport;
1270
1271     ofpbuf_reserve(buf, sizeof odp_vport);
1272
1273     if (vport->port_no != UINT32_MAX) {
1274         nl_msg_put_u32(buf, ODP_VPORT_ATTR_PORT_NO, vport->port_no);
1275     }
1276
1277     if (vport->type != ODP_VPORT_TYPE_UNSPEC) {
1278         nl_msg_put_u32(buf, ODP_VPORT_ATTR_TYPE, vport->type);
1279     }
1280
1281     if (vport->name) {
1282         nl_msg_put_string(buf, ODP_VPORT_ATTR_NAME, vport->name);
1283     }
1284
1285     if (vport->stats) {
1286         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_STATS,
1287                           vport->stats, sizeof *vport->stats);
1288     }
1289
1290     if (vport->address) {
1291         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_ADDRESS,
1292                           vport->address, ETH_ADDR_LEN);
1293     }
1294
1295     if (vport->mtu) {
1296         nl_msg_put_u32(buf, ODP_VPORT_ATTR_MTU, vport->mtu);
1297     }
1298
1299     if (vport->options) {
1300         nl_msg_put_nested(buf, ODP_VPORT_ATTR_OPTIONS,
1301                           vport->options, vport->options_len);
1302     }
1303
1304     if (vport->ifindex) {
1305         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFINDEX, vport->ifindex);
1306     }
1307
1308     if (vport->iflink) {
1309         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFLINK, vport->iflink);
1310     }
1311
1312     odp_vport = ofpbuf_push_uninit(buf, sizeof *odp_vport);
1313     odp_vport->dp_idx = vport->dp_idx;
1314     odp_vport->len = buf->size;
1315     odp_vport->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1316 }
1317
1318 /* Clears 'vport' to "empty" values. */
1319 void
1320 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1321 {
1322     memset(vport, 0, sizeof *vport);
1323     vport->dp_idx = UINT32_MAX;
1324     vport->port_no = UINT32_MAX;
1325 }
1326
1327 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1328  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1329  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1330  * result of the command is expected to be an odp_vport also, which is decoded
1331  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1332  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1333 int
1334 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1335                           struct dpif_linux_vport *reply,
1336                           struct ofpbuf **bufp)
1337 {
1338     struct ofpbuf *buf = NULL;
1339     int error;
1340     int fd;
1341
1342     assert((reply != NULL) == (bufp != NULL));
1343
1344     error = get_dp0_fd(&fd);
1345     if (error) {
1346         goto error;
1347     }
1348
1349     buf = ofpbuf_new(1024);
1350     dpif_linux_vport_to_ofpbuf(request, buf);
1351
1352     error = ioctl(fd, request->cmd, buf->data) ? errno : 0;
1353     if (error) {
1354         goto error;
1355     }
1356
1357     if (bufp) {
1358         buf->size = ((struct odp_vport *) buf->data)->len;
1359         error = dpif_linux_vport_from_ofpbuf(reply, buf);
1360         if (error) {
1361             goto error;
1362         }
1363         *bufp = buf;
1364     } else {
1365         ofpbuf_delete(buf);
1366     }
1367     return 0;
1368
1369 error:
1370     ofpbuf_delete(buf);
1371     if (bufp) {
1372         memset(reply, 0, sizeof *reply);
1373         *bufp = NULL;
1374     }
1375     return error;
1376 }
1377
1378 /* Obtains information about the kernel vport named 'name' and stores it into
1379  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1380  * longer needed ('reply' will contain pointers into '*bufp').  */
1381 int
1382 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1383                      struct ofpbuf **bufp)
1384 {
1385     struct dpif_linux_vport request;
1386
1387     dpif_linux_vport_init(&request);
1388     request.cmd = ODP_VPORT_GET;
1389     request.name = name;
1390
1391     return dpif_linux_vport_transact(&request, reply, bufp);
1392 }
1393 \f
1394 /* Parses the contents of 'buf', which contains a "struct odp_datapath"
1395  * followed by Netlink attributes, into 'dp'.  Returns 0 if successful,
1396  * otherwise a positive errno value.
1397  *
1398  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1399  * while 'dp' is still in use. */
1400 static int
1401 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1402 {
1403     static const struct nl_policy odp_datapath_policy[] = {
1404         [ODP_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1405         [ODP_DP_ATTR_STATS] = { .type = NL_A_UNSPEC,
1406                                 .min_len = sizeof(struct odp_stats),
1407                                 .max_len = sizeof(struct odp_stats),
1408                                 .optional = true },
1409         [ODP_DP_ATTR_IPV4_FRAGS] = { .type = NL_A_U32, .optional = true },
1410         [ODP_DP_ATTR_SAMPLING] = { .type = NL_A_U32, .optional = true },
1411         [ODP_DP_ATTR_MCGROUPS] = { .type = NL_A_NESTED, .optional = true },
1412     };
1413
1414     struct odp_datapath *odp_dp;
1415     struct nlattr *a[ARRAY_SIZE(odp_datapath_policy)];
1416
1417     dpif_linux_dp_init(dp);
1418
1419     if (!nl_policy_parse(buf, sizeof *odp_dp, odp_datapath_policy,
1420                          a, ARRAY_SIZE(odp_datapath_policy))) {
1421         return EINVAL;
1422     }
1423     odp_dp = buf->data;
1424
1425     dp->dp_idx = odp_dp->dp_idx;
1426     dp->name = nl_attr_get_string(a[ODP_DP_ATTR_NAME]);
1427     if (a[ODP_DP_ATTR_STATS]) {
1428         /* Can't use structure assignment because Netlink doesn't ensure
1429          * sufficient alignment for 64-bit members. */
1430         memcpy(&dp->stats, nl_attr_get(a[ODP_DP_ATTR_STATS]),
1431                sizeof dp->stats);
1432     }
1433     if (a[ODP_DP_ATTR_IPV4_FRAGS]) {
1434         dp->ipv4_frags = nl_attr_get_u32(a[ODP_DP_ATTR_IPV4_FRAGS]);
1435     }
1436     if (a[ODP_DP_ATTR_SAMPLING]) {
1437         dp->sampling = nl_attr_get(a[ODP_DP_ATTR_SAMPLING]);
1438     }
1439
1440     if (a[ODP_DP_ATTR_MCGROUPS]) {
1441         static const struct nl_policy odp_mcgroup_policy[] = {
1442             [ODP_PACKET_CMD_MISS] = { .type = NL_A_U32, .optional = true },
1443             [ODP_PACKET_CMD_ACTION] = { .type = NL_A_U32, .optional = true },
1444             [ODP_PACKET_CMD_SAMPLE] = { .type = NL_A_U32, .optional = true },
1445         };
1446
1447         struct nlattr *mcgroups[ARRAY_SIZE(odp_mcgroup_policy)];
1448
1449         if (!nl_parse_nested(a[ODP_DP_ATTR_MCGROUPS], odp_mcgroup_policy,
1450                              mcgroups, ARRAY_SIZE(odp_mcgroup_policy))) {
1451             return EINVAL;
1452         }
1453
1454         if (mcgroups[ODP_PACKET_CMD_MISS]) {
1455             dp->mcgroups[DPIF_UC_MISS]
1456                 = nl_attr_get_u32(mcgroups[ODP_PACKET_CMD_MISS]);
1457         }
1458         if (mcgroups[ODP_PACKET_CMD_ACTION]) {
1459             dp->mcgroups[DPIF_UC_ACTION]
1460                 = nl_attr_get_u32(mcgroups[ODP_PACKET_CMD_ACTION]);
1461         }
1462         if (mcgroups[ODP_PACKET_CMD_SAMPLE]) {
1463             dp->mcgroups[DPIF_UC_SAMPLE]
1464                 = nl_attr_get_u32(mcgroups[ODP_PACKET_CMD_SAMPLE]);
1465         }
1466     }
1467
1468     return 0;
1469 }
1470
1471 /* Appends to 'buf' (which must initially be empty) a "struct odp_datapath"
1472  * followed by Netlink attributes corresponding to 'dp'. */
1473 static void
1474 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1475 {
1476     struct odp_datapath *odp_dp;
1477
1478     ofpbuf_reserve(buf, sizeof odp_dp);
1479
1480     if (dp->name) {
1481         nl_msg_put_string(buf, ODP_DP_ATTR_NAME, dp->name);
1482     }
1483
1484     /* Skip ODP_DP_ATTR_STATS since we never have a reason to serialize it. */
1485
1486     if (dp->ipv4_frags) {
1487         nl_msg_put_u32(buf, ODP_DP_ATTR_IPV4_FRAGS, dp->ipv4_frags);
1488     }
1489
1490     if (dp->sampling) {
1491         nl_msg_put_u32(buf, ODP_DP_ATTR_SAMPLING, *dp->sampling);
1492     }
1493
1494     odp_dp = ofpbuf_push_uninit(buf, sizeof *odp_dp);
1495     odp_dp->dp_idx = dp->dp_idx;
1496     odp_dp->len = buf->size;
1497     odp_dp->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1498 }
1499
1500 /* Clears 'dp' to "empty" values. */
1501 void
1502 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1503 {
1504     memset(dp, 0, sizeof *dp);
1505     dp->dp_idx = -1;
1506 }
1507
1508 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1509  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1510  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1511  * result of the command is expected to be an odp_datapath also, which is
1512  * decoded and stored in '*reply' and '*bufp'.  The caller must free '*bufp'
1513  * when the reply is no longer needed ('reply' will contain pointers into
1514  * '*bufp'). */
1515 int
1516 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1517                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1518 {
1519     struct ofpbuf *buf = NULL;
1520     int error;
1521     int fd;
1522
1523     assert((reply != NULL) == (bufp != NULL));
1524
1525     error = get_dp0_fd(&fd);
1526     if (error) {
1527         goto error;
1528     }
1529
1530     buf = ofpbuf_new(1024);
1531     dpif_linux_dp_to_ofpbuf(request, buf);
1532
1533     error = ioctl(fd, request->cmd, buf->data) ? errno : 0;
1534     if (error) {
1535         goto error;
1536     }
1537
1538     if (bufp) {
1539         buf->size = ((struct odp_datapath *) buf->data)->len;
1540         error = dpif_linux_dp_from_ofpbuf(reply, buf);
1541         if (error) {
1542             goto error;
1543         }
1544         *bufp = buf;
1545     } else {
1546         ofpbuf_delete(buf);
1547     }
1548     return 0;
1549
1550 error:
1551     ofpbuf_delete(buf);
1552     if (bufp) {
1553         memset(reply, 0, sizeof *reply);
1554         *bufp = NULL;
1555     }
1556     return error;
1557 }
1558
1559 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1560  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1561  * will contain pointers into '*bufp').  */
1562 int
1563 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1564                   struct ofpbuf **bufp)
1565 {
1566     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1567     struct dpif_linux_dp request;
1568
1569     dpif_linux_dp_init(&request);
1570     request.cmd = ODP_DP_GET;
1571     request.dp_idx = dpif->minor;
1572
1573     return dpif_linux_dp_transact(&request, reply, bufp);
1574 }
1575 \f
1576 /* Parses the contents of 'buf', which contains a "struct odp_flow" followed by
1577  * Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1578  * positive errno value.
1579  *
1580  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1581  * while 'flow' is still in use. */
1582 static int
1583 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1584                             const struct ofpbuf *buf)
1585 {
1586     static const struct nl_policy odp_flow_policy[] = {
1587         [ODP_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1588         [ODP_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1589         [ODP_FLOW_ATTR_STATS] = { .type = NL_A_UNSPEC,
1590                                   .min_len = sizeof(struct odp_flow_stats),
1591                                   .max_len = sizeof(struct odp_flow_stats),
1592                                   .optional = true },
1593         [ODP_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1594         [ODP_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1595         /* The kernel never uses ODP_FLOW_ATTR_CLEAR. */
1596         [ODP_FLOW_ATTR_STATE] = { .type = NL_A_U64, .optional = true },
1597     };
1598
1599     struct odp_flow *odp_flow;
1600     struct nlattr *a[ARRAY_SIZE(odp_flow_policy)];
1601
1602     dpif_linux_flow_init(flow);
1603
1604     if (!nl_policy_parse(buf, sizeof *odp_flow, odp_flow_policy,
1605                          a, ARRAY_SIZE(odp_flow_policy))) {
1606         return EINVAL;
1607     }
1608     odp_flow = buf->data;
1609
1610     flow->nlmsg_flags = odp_flow->nlmsg_flags;
1611     flow->dp_idx = odp_flow->dp_idx;
1612     flow->key = nl_attr_get(a[ODP_FLOW_ATTR_KEY]);
1613     flow->key_len = nl_attr_get_size(a[ODP_FLOW_ATTR_KEY]);
1614     if (a[ODP_FLOW_ATTR_ACTIONS]) {
1615         flow->actions = nl_attr_get(a[ODP_FLOW_ATTR_ACTIONS]);
1616         flow->actions_len = nl_attr_get_size(a[ODP_FLOW_ATTR_ACTIONS]);
1617     }
1618     if (a[ODP_FLOW_ATTR_STATS]) {
1619         flow->stats = nl_attr_get(a[ODP_FLOW_ATTR_STATS]);
1620     }
1621     if (a[ODP_FLOW_ATTR_TCP_FLAGS]) {
1622         flow->tcp_flags = nl_attr_get(a[ODP_FLOW_ATTR_TCP_FLAGS]);
1623     }
1624     if (a[ODP_FLOW_ATTR_STATE]) {
1625         flow->state = nl_attr_get(a[ODP_FLOW_ATTR_STATE]);
1626     }
1627     return 0;
1628 }
1629
1630 /* Appends to 'buf' (which must initially be empty) a "struct odp_flow"
1631  * followed by Netlink attributes corresponding to 'flow'. */
1632 static void
1633 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1634                           struct ofpbuf *buf)
1635 {
1636     struct odp_flow *odp_flow;
1637
1638     ofpbuf_reserve(buf, sizeof odp_flow);
1639
1640     if (flow->key_len) {
1641         nl_msg_put_unspec(buf, ODP_FLOW_ATTR_KEY, flow->key, flow->key_len);
1642     }
1643
1644     if (flow->actions_len) {
1645         nl_msg_put_unspec(buf, ODP_FLOW_ATTR_ACTIONS,
1646                           flow->actions, flow->actions_len);
1647     }
1648
1649     /* We never need to send these to the kernel. */
1650     assert(!flow->stats);
1651     assert(!flow->tcp_flags);
1652     assert(!flow->used);
1653
1654     if (flow->clear) {
1655         nl_msg_put_flag(buf, ODP_FLOW_ATTR_CLEAR);
1656     }
1657
1658     if (flow->state) {
1659         nl_msg_put_u64(buf, ODP_FLOW_ATTR_STATE,
1660                        get_unaligned_u64(flow->state));
1661     }
1662
1663     odp_flow = ofpbuf_push_uninit(buf, sizeof *odp_flow);
1664     odp_flow->nlmsg_flags = flow->nlmsg_flags;
1665     odp_flow->dp_idx = flow->dp_idx;
1666     odp_flow->len = buf->size;
1667     odp_flow->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1668 }
1669
1670 /* Clears 'flow' to "empty" values. */
1671 void
1672 dpif_linux_flow_init(struct dpif_linux_flow *flow)
1673 {
1674     memset(flow, 0, sizeof *flow);
1675 }
1676
1677 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1678  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1679  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1680  * result of the command is expected to be an odp_flow also, which is decoded
1681  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1682  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1683 int
1684 dpif_linux_flow_transact(const struct dpif_linux_flow *request,
1685                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
1686 {
1687     struct ofpbuf *buf = NULL;
1688     int error;
1689     int fd;
1690
1691     assert((reply != NULL) == (bufp != NULL));
1692
1693     error = get_dp0_fd(&fd);
1694     if (error) {
1695         goto error;
1696     }
1697
1698     buf = ofpbuf_new(1024);
1699     dpif_linux_flow_to_ofpbuf(request, buf);
1700
1701     error = ioctl(fd, request->cmd, buf->data) ? errno : 0;
1702     if (error) {
1703         goto error;
1704     }
1705
1706     if (bufp) {
1707         buf->size = ((struct odp_flow *) buf->data)->len;
1708         error = dpif_linux_flow_from_ofpbuf(reply, buf);
1709         if (error) {
1710             goto error;
1711         }
1712         *bufp = buf;
1713     } else {
1714         ofpbuf_delete(buf);
1715     }
1716     return 0;
1717
1718 error:
1719     ofpbuf_delete(buf);
1720     if (bufp) {
1721         memset(reply, 0, sizeof *reply);
1722         *bufp = NULL;
1723     }
1724     return error;
1725 }
1726
1727 static void
1728 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
1729                           struct dpif_flow_stats *stats)
1730 {
1731     if (flow->stats) {
1732         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
1733         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
1734     } else {
1735         stats->n_packets = 0;
1736         stats->n_bytes = 0;
1737     }
1738     stats->used = flow->used ? get_unaligned_u64(flow->used) : 0;
1739     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
1740 }
1741