dpif: Simplify the "listen mask" concept.
[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/pkt_sched.h>
29 #include <linux/rtnetlink.h>
30 #include <linux/sockios.h>
31 #include <poll.h>
32 #include <stdlib.h>
33 #include <strings.h>
34 #include <sys/epoll.h>
35 #include <sys/stat.h>
36 #include <unistd.h>
37
38 #include "bitmap.h"
39 #include "dpif-provider.h"
40 #include "dynamic-string.h"
41 #include "flow.h"
42 #include "netdev.h"
43 #include "netdev-linux.h"
44 #include "netdev-vport.h"
45 #include "netlink-notifier.h"
46 #include "netlink-socket.h"
47 #include "netlink.h"
48 #include "odp-util.h"
49 #include "ofpbuf.h"
50 #include "openvswitch/datapath-compat.h"
51 #include "openvswitch/tunnel.h"
52 #include "packets.h"
53 #include "poll-loop.h"
54 #include "random.h"
55 #include "shash.h"
56 #include "sset.h"
57 #include "unaligned.h"
58 #include "util.h"
59 #include "vlog.h"
60
61 VLOG_DEFINE_THIS_MODULE(dpif_linux);
62
63 enum { LRU_MAX_PORTS = 1024 };
64 enum { LRU_MASK = LRU_MAX_PORTS - 1};
65 BUILD_ASSERT_DECL(IS_POW2(LRU_MAX_PORTS));
66
67 enum { N_UPCALL_SOCKS = 16 };
68 BUILD_ASSERT_DECL(IS_POW2(N_UPCALL_SOCKS));
69 BUILD_ASSERT_DECL(N_UPCALL_SOCKS <= 32); /* We use a 32-bit word as a mask. */
70
71 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
72  * missing if we have old headers. */
73 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
74
75 struct dpif_linux_dp {
76     /* Generic Netlink header. */
77     uint8_t cmd;
78
79     /* struct ovs_header. */
80     int dp_ifindex;
81
82     /* Attributes. */
83     const char *name;                  /* OVS_DP_ATTR_NAME. */
84     const uint32_t *upcall_pid;        /* OVS_DP_UPCALL_PID. */
85     struct ovs_dp_stats stats;         /* OVS_DP_ATTR_STATS. */
86 };
87
88 static void dpif_linux_dp_init(struct dpif_linux_dp *);
89 static int dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *,
90                                      const struct ofpbuf *);
91 static void dpif_linux_dp_dump_start(struct nl_dump *);
92 static int dpif_linux_dp_transact(const struct dpif_linux_dp *request,
93                                   struct dpif_linux_dp *reply,
94                                   struct ofpbuf **bufp);
95 static int dpif_linux_dp_get(const struct dpif *, struct dpif_linux_dp *reply,
96                              struct ofpbuf **bufp);
97
98 struct dpif_linux_flow {
99     /* Generic Netlink header. */
100     uint8_t cmd;
101
102     /* struct ovs_header. */
103     unsigned int nlmsg_flags;
104     int dp_ifindex;
105
106     /* Attributes.
107      *
108      * The 'stats' member points to 64-bit data that might only be aligned on
109      * 32-bit boundaries, so get_unaligned_u64() should be used to access its
110      * values.
111      *
112      * If 'actions' is nonnull then OVS_FLOW_ATTR_ACTIONS will be included in
113      * the Netlink version of the command, even if actions_len is zero. */
114     const struct nlattr *key;           /* OVS_FLOW_ATTR_KEY. */
115     size_t key_len;
116     const struct nlattr *actions;       /* OVS_FLOW_ATTR_ACTIONS. */
117     size_t actions_len;
118     const struct ovs_flow_stats *stats; /* OVS_FLOW_ATTR_STATS. */
119     const uint8_t *tcp_flags;           /* OVS_FLOW_ATTR_TCP_FLAGS. */
120     const ovs_32aligned_u64 *used;      /* OVS_FLOW_ATTR_USED. */
121     bool clear;                         /* OVS_FLOW_ATTR_CLEAR. */
122 };
123
124 static void dpif_linux_flow_init(struct dpif_linux_flow *);
125 static int dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *,
126                                        const struct ofpbuf *);
127 static void dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *,
128                                       struct ofpbuf *);
129 static int dpif_linux_flow_transact(struct dpif_linux_flow *request,
130                                     struct dpif_linux_flow *reply,
131                                     struct ofpbuf **bufp);
132 static void dpif_linux_flow_get_stats(const struct dpif_linux_flow *,
133                                       struct dpif_flow_stats *);
134
135 /* Datapath interface for the openvswitch Linux kernel module. */
136 struct dpif_linux {
137     struct dpif dpif;
138     int dp_ifindex;
139
140     /* Upcall messages. */
141     struct nl_sock *upcall_socks[N_UPCALL_SOCKS];
142     uint32_t ready_mask;        /* 1-bit for each sock with unread messages. */
143     int epoll_fd;               /* epoll fd that includes the upcall socks. */
144
145     /* Change notification. */
146     struct sset changed_ports;  /* Ports that have changed. */
147     struct nln_notifier *port_notifier;
148     bool change_error;
149
150     /* Queue of unused ports. */
151     unsigned long *lru_bitmap;
152     uint16_t lru_ports[LRU_MAX_PORTS];
153     size_t lru_head;
154     size_t lru_tail;
155 };
156
157 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
158
159 /* Generic Netlink family numbers for OVS. */
160 static int ovs_datapath_family;
161 static int ovs_vport_family;
162 static int ovs_flow_family;
163 static int ovs_packet_family;
164
165 /* Generic Netlink socket. */
166 static struct nl_sock *genl_sock;
167 static struct nln *nln = NULL;
168
169 static int dpif_linux_init(void);
170 static void open_dpif(const struct dpif_linux_dp *, struct dpif **);
171 static bool dpif_linux_nln_parse(struct ofpbuf *, void *);
172 static void dpif_linux_port_changed(const void *vport, void *dpif);
173 static uint32_t dpif_linux_port_get_pid(const struct dpif *, uint16_t port_no);
174
175 static void dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *,
176                                        struct ofpbuf *);
177 static int dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *,
178                                         const struct ofpbuf *);
179
180 static struct dpif_linux *
181 dpif_linux_cast(const struct dpif *dpif)
182 {
183     dpif_assert_class(dpif, &dpif_linux_class);
184     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
185 }
186
187 static void
188 dpif_linux_push_port(struct dpif_linux *dp, uint16_t port)
189 {
190     if (port < LRU_MAX_PORTS && !bitmap_is_set(dp->lru_bitmap, port)) {
191         bitmap_set1(dp->lru_bitmap, port);
192         dp->lru_ports[dp->lru_head++ & LRU_MASK] = port;
193     }
194 }
195
196 static uint32_t
197 dpif_linux_pop_port(struct dpif_linux *dp)
198 {
199     uint16_t port;
200
201     if (dp->lru_head == dp->lru_tail) {
202         return UINT32_MAX;
203     }
204
205     port = dp->lru_ports[dp->lru_tail++ & LRU_MASK];
206     bitmap_set0(dp->lru_bitmap, port);
207     return port;
208 }
209
210 static int
211 dpif_linux_enumerate(struct sset *all_dps)
212 {
213     struct nl_dump dump;
214     struct ofpbuf msg;
215     int error;
216
217     error = dpif_linux_init();
218     if (error) {
219         return error;
220     }
221
222     dpif_linux_dp_dump_start(&dump);
223     while (nl_dump_next(&dump, &msg)) {
224         struct dpif_linux_dp dp;
225
226         if (!dpif_linux_dp_from_ofpbuf(&dp, &msg)) {
227             sset_add(all_dps, dp.name);
228         }
229     }
230     return nl_dump_done(&dump);
231 }
232
233 static int
234 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
235                 bool create, struct dpif **dpifp)
236 {
237     struct dpif_linux_dp dp_request, dp;
238     struct ofpbuf *buf;
239     uint32_t upcall_pid;
240     int error;
241
242     error = dpif_linux_init();
243     if (error) {
244         return error;
245     }
246
247     /* Create or look up datapath. */
248     dpif_linux_dp_init(&dp_request);
249     if (create) {
250         dp_request.cmd = OVS_DP_CMD_NEW;
251         upcall_pid = 0;
252         dp_request.upcall_pid = &upcall_pid;
253     } else {
254         dp_request.cmd = OVS_DP_CMD_GET;
255     }
256     dp_request.name = name;
257     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
258     if (error) {
259         return error;
260     }
261
262     open_dpif(&dp, dpifp);
263     ofpbuf_delete(buf);
264     return 0;
265 }
266
267 static void
268 open_dpif(const struct dpif_linux_dp *dp, struct dpif **dpifp)
269 {
270     struct dpif_linux *dpif;
271     int i;
272
273     dpif = xzalloc(sizeof *dpif);
274     dpif->port_notifier = nln_notifier_create(nln, dpif_linux_port_changed,
275                                               dpif);
276     dpif->epoll_fd = -1;
277
278     dpif_init(&dpif->dpif, &dpif_linux_class, dp->name,
279               dp->dp_ifindex, dp->dp_ifindex);
280
281     dpif->dp_ifindex = dp->dp_ifindex;
282     sset_init(&dpif->changed_ports);
283     *dpifp = &dpif->dpif;
284
285     dpif->lru_bitmap = bitmap_allocate(LRU_MAX_PORTS);
286     bitmap_set1(dpif->lru_bitmap, OVSP_LOCAL);
287     for (i = 1; i < LRU_MAX_PORTS; i++) {
288         dpif_linux_push_port(dpif, i);
289     }
290 }
291
292 static void
293 destroy_upcall_socks(struct dpif_linux *dpif)
294 {
295     int i;
296
297     if (dpif->epoll_fd >= 0) {
298         close(dpif->epoll_fd);
299         dpif->epoll_fd = -1;
300     }
301     for (i = 0; i < N_UPCALL_SOCKS; i++) {
302         nl_sock_destroy(dpif->upcall_socks[i]);
303         dpif->upcall_socks[i] = NULL;
304     }
305 }
306
307 static void
308 dpif_linux_close(struct dpif *dpif_)
309 {
310     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
311
312     nln_notifier_destroy(dpif->port_notifier);
313     destroy_upcall_socks(dpif);
314     sset_destroy(&dpif->changed_ports);
315     free(dpif->lru_bitmap);
316     free(dpif);
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 = OVS_DP_CMD_DEL;
327     dp.dp_ifindex = dpif->dp_ifindex;
328     return dpif_linux_dp_transact(&dp, NULL, NULL);
329 }
330
331 static void
332 dpif_linux_run(struct dpif *dpif OVS_UNUSED)
333 {
334     if (nln) {
335         nln_run(nln);
336     }
337 }
338
339 static void
340 dpif_linux_wait(struct dpif *dpif OVS_UNUSED)
341 {
342     if (nln) {
343         nln_wait(nln);
344     }
345 }
346
347 static int
348 dpif_linux_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
349 {
350     struct dpif_linux_dp dp;
351     struct ofpbuf *buf;
352     int error;
353
354     error = dpif_linux_dp_get(dpif_, &dp, &buf);
355     if (!error) {
356         stats->n_hit    = dp.stats.n_hit;
357         stats->n_missed = dp.stats.n_missed;
358         stats->n_lost   = dp.stats.n_lost;
359         stats->n_flows  = dp.stats.n_flows;
360         ofpbuf_delete(buf);
361     }
362     return error;
363 }
364
365 static int
366 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
367                     uint16_t *port_nop)
368 {
369     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
370     const char *name = netdev_get_name(netdev);
371     const char *type = netdev_get_type(netdev);
372     struct dpif_linux_vport request, reply;
373     const struct ofpbuf *options;
374     struct ofpbuf *buf;
375     int error;
376
377     dpif_linux_vport_init(&request);
378     request.cmd = OVS_VPORT_CMD_NEW;
379     request.dp_ifindex = dpif->dp_ifindex;
380     request.type = netdev_vport_get_vport_type(netdev);
381     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
382         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
383                      "unsupported type `%s'",
384                      dpif_name(dpif_), name, type);
385         return EINVAL;
386     }
387     request.name = name;
388
389     options = netdev_vport_get_options(netdev);
390     if (options && options->size) {
391         request.options = options->data;
392         request.options_len = options->size;
393     }
394
395     if (request.type == OVS_VPORT_TYPE_NETDEV) {
396         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
397     }
398
399     /* Loop until we find a port that isn't used. */
400     do {
401         uint32_t upcall_pid;
402
403         request.port_no = dpif_linux_pop_port(dpif);
404         upcall_pid = dpif_linux_port_get_pid(dpif_, request.port_no);
405         request.upcall_pid = &upcall_pid;
406         error = dpif_linux_vport_transact(&request, &reply, &buf);
407
408         if (!error) {
409             *port_nop = reply.port_no;
410             VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
411                      dpif_name(dpif_), request.port_no, upcall_pid);
412         }
413         ofpbuf_delete(buf);
414     } while (request.port_no != UINT32_MAX
415              && (error == EBUSY || error == EFBIG));
416
417     return error;
418 }
419
420 static int
421 dpif_linux_port_del(struct dpif *dpif_, uint16_t port_no)
422 {
423     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
424     struct dpif_linux_vport vport;
425     int error;
426
427     dpif_linux_vport_init(&vport);
428     vport.cmd = OVS_VPORT_CMD_DEL;
429     vport.dp_ifindex = dpif->dp_ifindex;
430     vport.port_no = port_no;
431     error = dpif_linux_vport_transact(&vport, NULL, NULL);
432
433     if (!error) {
434         dpif_linux_push_port(dpif, port_no);
435     }
436     return error;
437 }
438
439 static int
440 dpif_linux_port_query__(const struct dpif *dpif, uint32_t port_no,
441                         const char *port_name, struct dpif_port *dpif_port)
442 {
443     struct dpif_linux_vport request;
444     struct dpif_linux_vport reply;
445     struct ofpbuf *buf;
446     int error;
447
448     dpif_linux_vport_init(&request);
449     request.cmd = OVS_VPORT_CMD_GET;
450     request.dp_ifindex = dpif_linux_cast(dpif)->dp_ifindex;
451     request.port_no = port_no;
452     request.name = port_name;
453
454     error = dpif_linux_vport_transact(&request, &reply, &buf);
455     if (!error) {
456         dpif_port->name = xstrdup(reply.name);
457         dpif_port->type = xstrdup(netdev_vport_get_netdev_type(&reply));
458         dpif_port->port_no = reply.port_no;
459         ofpbuf_delete(buf);
460     }
461     return error;
462 }
463
464 static int
465 dpif_linux_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
466                                 struct dpif_port *dpif_port)
467 {
468     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
469 }
470
471 static int
472 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
473                               struct dpif_port *dpif_port)
474 {
475     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
476 }
477
478 static int
479 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
480 {
481     /* If the datapath increases its range of supported ports, then it should
482      * start reporting that. */
483     return 1024;
484 }
485
486 static uint32_t
487 dpif_linux_port_get_pid(const struct dpif *dpif_, uint16_t port_no)
488 {
489     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
490
491     if (dpif->epoll_fd < 0) {
492         return 0;
493     } else {
494         int idx = port_no & (N_UPCALL_SOCKS - 1);
495         return nl_sock_pid(dpif->upcall_socks[idx]);
496     }
497 }
498
499 static int
500 dpif_linux_flow_flush(struct dpif *dpif_)
501 {
502     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
503     struct dpif_linux_flow flow;
504
505     dpif_linux_flow_init(&flow);
506     flow.cmd = OVS_FLOW_CMD_DEL;
507     flow.dp_ifindex = dpif->dp_ifindex;
508     return dpif_linux_flow_transact(&flow, NULL, NULL);
509 }
510
511 struct dpif_linux_port_state {
512     struct nl_dump dump;
513     unsigned long *port_bitmap; /* Ports in the datapath. */
514     bool complete;              /* Dump completed without error. */
515 };
516
517 static int
518 dpif_linux_port_dump_start(const struct dpif *dpif_, void **statep)
519 {
520     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
521     struct dpif_linux_port_state *state;
522     struct dpif_linux_vport request;
523     struct ofpbuf *buf;
524
525     *statep = state = xmalloc(sizeof *state);
526     state->port_bitmap = bitmap_allocate(LRU_MAX_PORTS);
527     state->complete = false;
528
529     dpif_linux_vport_init(&request);
530     request.cmd = OVS_DP_CMD_GET;
531     request.dp_ifindex = dpif->dp_ifindex;
532
533     buf = ofpbuf_new(1024);
534     dpif_linux_vport_to_ofpbuf(&request, buf);
535     nl_dump_start(&state->dump, genl_sock, buf);
536     ofpbuf_delete(buf);
537
538     return 0;
539 }
540
541 static int
542 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
543                           struct dpif_port *dpif_port)
544 {
545     struct dpif_linux_port_state *state = state_;
546     struct dpif_linux_vport vport;
547     struct ofpbuf buf;
548     int error;
549
550     if (!nl_dump_next(&state->dump, &buf)) {
551         state->complete = true;
552         return EOF;
553     }
554
555     error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
556     if (error) {
557         return error;
558     }
559
560     if (vport.port_no < LRU_MAX_PORTS) {
561         bitmap_set1(state->port_bitmap, vport.port_no);
562     }
563
564     dpif_port->name = (char *) vport.name;
565     dpif_port->type = (char *) netdev_vport_get_netdev_type(&vport);
566     dpif_port->port_no = vport.port_no;
567     return 0;
568 }
569
570 static int
571 dpif_linux_port_dump_done(const struct dpif *dpif_, void *state_)
572 {
573     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
574     struct dpif_linux_port_state *state = state_;
575     int error = nl_dump_done(&state->dump);
576
577     if (state->complete) {
578         uint16_t i;
579
580         for (i = 0; i < LRU_MAX_PORTS; i++) {
581             if (!bitmap_is_set(state->port_bitmap, i)) {
582                 dpif_linux_push_port(dpif, i);
583             }
584         }
585     }
586
587     free(state->port_bitmap);
588     free(state);
589     return error;
590 }
591
592 static int
593 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
594 {
595     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
596
597     if (dpif->change_error) {
598         dpif->change_error = false;
599         sset_clear(&dpif->changed_ports);
600         return ENOBUFS;
601     } else if (!sset_is_empty(&dpif->changed_ports)) {
602         *devnamep = sset_pop(&dpif->changed_ports);
603         return 0;
604     } else {
605         return EAGAIN;
606     }
607 }
608
609 static void
610 dpif_linux_port_poll_wait(const struct dpif *dpif_)
611 {
612     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
613     if (!sset_is_empty(&dpif->changed_ports) || dpif->change_error) {
614         poll_immediate_wake();
615     }
616 }
617
618 static int
619 dpif_linux_flow_get__(const struct dpif *dpif_,
620                       const struct nlattr *key, size_t key_len,
621                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
622 {
623     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
624     struct dpif_linux_flow request;
625
626     dpif_linux_flow_init(&request);
627     request.cmd = OVS_FLOW_CMD_GET;
628     request.dp_ifindex = dpif->dp_ifindex;
629     request.key = key;
630     request.key_len = key_len;
631     return dpif_linux_flow_transact(&request, reply, bufp);
632 }
633
634 static int
635 dpif_linux_flow_get(const struct dpif *dpif_,
636                     const struct nlattr *key, size_t key_len,
637                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
638 {
639     struct dpif_linux_flow reply;
640     struct ofpbuf *buf;
641     int error;
642
643     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
644     if (!error) {
645         if (stats) {
646             dpif_linux_flow_get_stats(&reply, stats);
647         }
648         if (actionsp) {
649             buf->data = (void *) reply.actions;
650             buf->size = reply.actions_len;
651             *actionsp = buf;
652         } else {
653             ofpbuf_delete(buf);
654         }
655     }
656     return error;
657 }
658
659 static void
660 dpif_linux_init_flow_put(struct dpif *dpif_, enum dpif_flow_put_flags flags,
661                          const struct nlattr *key, size_t key_len,
662                          const struct nlattr *actions, size_t actions_len,
663                          struct dpif_linux_flow *request)
664 {
665     static struct nlattr dummy_action;
666
667     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
668
669     dpif_linux_flow_init(request);
670     request->cmd = (flags & DPIF_FP_CREATE
671                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
672     request->dp_ifindex = dpif->dp_ifindex;
673     request->key = key;
674     request->key_len = key_len;
675     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
676     request->actions = actions ? actions : &dummy_action;
677     request->actions_len = actions_len;
678     if (flags & DPIF_FP_ZERO_STATS) {
679         request->clear = true;
680     }
681     request->nlmsg_flags = flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
682 }
683
684 static int
685 dpif_linux_flow_put(struct dpif *dpif_, enum dpif_flow_put_flags flags,
686                     const struct nlattr *key, size_t key_len,
687                     const struct nlattr *actions, size_t actions_len,
688                     struct dpif_flow_stats *stats)
689 {
690     struct dpif_linux_flow request, reply;
691     struct ofpbuf *buf;
692     int error;
693
694     dpif_linux_init_flow_put(dpif_, flags, key, key_len, actions, actions_len,
695                              &request);
696     error = dpif_linux_flow_transact(&request,
697                                      stats ? &reply : NULL,
698                                      stats ? &buf : NULL);
699     if (!error && stats) {
700         dpif_linux_flow_get_stats(&reply, stats);
701         ofpbuf_delete(buf);
702     }
703     return error;
704 }
705
706 static int
707 dpif_linux_flow_del(struct dpif *dpif_,
708                     const struct nlattr *key, size_t key_len,
709                     struct dpif_flow_stats *stats)
710 {
711     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
712     struct dpif_linux_flow request, reply;
713     struct ofpbuf *buf;
714     int error;
715
716     dpif_linux_flow_init(&request);
717     request.cmd = OVS_FLOW_CMD_DEL;
718     request.dp_ifindex = dpif->dp_ifindex;
719     request.key = key;
720     request.key_len = key_len;
721     error = dpif_linux_flow_transact(&request,
722                                      stats ? &reply : NULL,
723                                      stats ? &buf : NULL);
724     if (!error && stats) {
725         dpif_linux_flow_get_stats(&reply, stats);
726         ofpbuf_delete(buf);
727     }
728     return error;
729 }
730
731 struct dpif_linux_flow_state {
732     struct nl_dump dump;
733     struct dpif_linux_flow flow;
734     struct dpif_flow_stats stats;
735     struct ofpbuf *buf;
736 };
737
738 static int
739 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
740 {
741     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
742     struct dpif_linux_flow_state *state;
743     struct dpif_linux_flow request;
744     struct ofpbuf *buf;
745
746     *statep = state = xmalloc(sizeof *state);
747
748     dpif_linux_flow_init(&request);
749     request.cmd = OVS_DP_CMD_GET;
750     request.dp_ifindex = dpif->dp_ifindex;
751
752     buf = ofpbuf_new(1024);
753     dpif_linux_flow_to_ofpbuf(&request, buf);
754     nl_dump_start(&state->dump, genl_sock, buf);
755     ofpbuf_delete(buf);
756
757     state->buf = NULL;
758
759     return 0;
760 }
761
762 static int
763 dpif_linux_flow_dump_next(const struct dpif *dpif_ OVS_UNUSED, void *state_,
764                           const struct nlattr **key, size_t *key_len,
765                           const struct nlattr **actions, size_t *actions_len,
766                           const struct dpif_flow_stats **stats)
767 {
768     struct dpif_linux_flow_state *state = state_;
769     struct ofpbuf buf;
770     int error;
771
772     do {
773         ofpbuf_delete(state->buf);
774         state->buf = NULL;
775
776         if (!nl_dump_next(&state->dump, &buf)) {
777             return EOF;
778         }
779
780         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
781         if (error) {
782             return error;
783         }
784
785         if (actions && !state->flow.actions) {
786             error = dpif_linux_flow_get__(dpif_, state->flow.key,
787                                           state->flow.key_len,
788                                           &state->flow, &state->buf);
789             if (error == ENOENT) {
790                 VLOG_DBG("dumped flow disappeared on get");
791             } else if (error) {
792                 VLOG_WARN("error fetching dumped flow: %s", strerror(error));
793             }
794         }
795     } while (error);
796
797     if (actions) {
798         *actions = state->flow.actions;
799         *actions_len = state->flow.actions_len;
800     }
801     if (key) {
802         *key = state->flow.key;
803         *key_len = state->flow.key_len;
804     }
805     if (stats) {
806         dpif_linux_flow_get_stats(&state->flow, &state->stats);
807         *stats = &state->stats;
808     }
809     return error;
810 }
811
812 static int
813 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
814 {
815     struct dpif_linux_flow_state *state = state_;
816     int error = nl_dump_done(&state->dump);
817     ofpbuf_delete(state->buf);
818     free(state);
819     return error;
820 }
821
822 static struct ofpbuf *
823 dpif_linux_encode_execute(int dp_ifindex,
824                           const struct nlattr *key, size_t key_len,
825                           const struct nlattr *actions, size_t actions_len,
826                           const struct ofpbuf *packet)
827 {
828     struct ovs_header *execute;
829     struct ofpbuf *buf;
830
831     buf = ofpbuf_new(128 + actions_len + packet->size);
832
833     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
834                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
835
836     execute = ofpbuf_put_uninit(buf, sizeof *execute);
837     execute->dp_ifindex = dp_ifindex;
838
839     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET, packet->data, packet->size);
840     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_KEY, key, key_len);
841     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS, actions, actions_len);
842
843     return buf;
844 }
845
846 static int
847 dpif_linux_execute__(int dp_ifindex, const struct nlattr *key, size_t key_len,
848                      const struct nlattr *actions, size_t actions_len,
849                      const struct ofpbuf *packet)
850 {
851     struct ofpbuf *request;
852     int error;
853
854     request = dpif_linux_encode_execute(dp_ifindex,
855                                         key, key_len, actions, actions_len,
856                                         packet);
857     error = nl_sock_transact(genl_sock, request, NULL);
858     ofpbuf_delete(request);
859
860     return error;
861 }
862
863 static int
864 dpif_linux_execute(struct dpif *dpif_,
865                    const struct nlattr *key, size_t key_len,
866                    const struct nlattr *actions, size_t actions_len,
867                    const struct ofpbuf *packet)
868 {
869     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
870
871     return dpif_linux_execute__(dpif->dp_ifindex, key, key_len,
872                                 actions, actions_len, packet);
873 }
874
875 static void
876 dpif_linux_operate(struct dpif *dpif_, union dpif_op **ops, size_t n_ops)
877 {
878     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
879     struct nl_transaction **txnsp;
880     struct nl_transaction *txns;
881     size_t i;
882
883     txns = xmalloc(n_ops * sizeof *txns);
884     for (i = 0; i < n_ops; i++) {
885         struct nl_transaction *txn = &txns[i];
886         union dpif_op *op = ops[i];
887
888         if (op->type == DPIF_OP_FLOW_PUT) {
889             struct dpif_flow_put *put = &op->flow_put;
890             struct dpif_linux_flow request;
891
892             dpif_linux_init_flow_put(dpif_, put->flags, put->key, put->key_len,
893                                      put->actions, put->actions_len,
894                                      &request);
895             if (put->stats) {
896                 request.nlmsg_flags |= NLM_F_ECHO;
897             }
898             txn->request = ofpbuf_new(1024);
899             dpif_linux_flow_to_ofpbuf(&request, txn->request);
900         } else if (op->type == DPIF_OP_EXECUTE) {
901             struct dpif_execute *execute = &op->execute;
902
903             txn->request = dpif_linux_encode_execute(
904                 dpif->dp_ifindex, execute->key, execute->key_len,
905                 execute->actions, execute->actions_len, execute->packet);
906         } else {
907             NOT_REACHED();
908         }
909     }
910
911     txnsp = xmalloc(n_ops * sizeof *txnsp);
912     for (i = 0; i < n_ops; i++) {
913         txnsp[i] = &txns[i];
914     }
915
916     nl_sock_transact_multiple(genl_sock, txnsp, n_ops);
917
918     free(txnsp);
919
920     for (i = 0; i < n_ops; i++) {
921         struct nl_transaction *txn = &txns[i];
922         union dpif_op *op = ops[i];
923
924         if (op->type == DPIF_OP_FLOW_PUT) {
925             struct dpif_flow_put *put = &op->flow_put;
926             int error = txn->error;
927
928             if (!error && put->stats) {
929                 struct dpif_linux_flow reply;
930
931                 error = dpif_linux_flow_from_ofpbuf(&reply, txn->reply);
932                 if (!error) {
933                     dpif_linux_flow_get_stats(&reply, put->stats);
934                 }
935             }
936             put->error = error;
937         } else if (op->type == DPIF_OP_EXECUTE) {
938             struct dpif_execute *execute = &op->execute;
939
940             execute->error = txn->error;
941         } else {
942             NOT_REACHED();
943         }
944
945         ofpbuf_delete(txn->request);
946         ofpbuf_delete(txn->reply);
947     }
948     free(txns);
949 }
950
951 static void
952 set_upcall_pids(struct dpif *dpif_)
953 {
954     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
955     struct dpif_port_dump port_dump;
956     struct dpif_port port;
957     int error;
958
959     DPIF_PORT_FOR_EACH (&port, &port_dump, &dpif->dpif) {
960         uint32_t upcall_pid = dpif_linux_port_get_pid(dpif_, port.port_no);
961         struct dpif_linux_vport vport_request;
962
963         dpif_linux_vport_init(&vport_request);
964         vport_request.cmd = OVS_VPORT_CMD_SET;
965         vport_request.dp_ifindex = dpif->dp_ifindex;
966         vport_request.port_no = port.port_no;
967         vport_request.upcall_pid = &upcall_pid;
968         error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
969         if (!error) {
970             VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
971                      dpif_name(&dpif->dpif), vport_request.port_no,
972                      upcall_pid);
973         } else {
974             VLOG_WARN_RL(&error_rl, "%s: failed to set upcall pid on port: %s",
975                          dpif_name(&dpif->dpif), strerror(error));
976         }
977     }
978 }
979
980 static int
981 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
982 {
983     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
984
985     if ((dpif->epoll_fd >= 0) == enable) {
986         return 0;
987     }
988
989     if (!enable) {
990         destroy_upcall_socks(dpif);
991     } else {
992         int i;
993         int error;
994
995         dpif->epoll_fd = epoll_create(N_UPCALL_SOCKS);
996         if (dpif->epoll_fd < 0) {
997             return errno;
998         }
999
1000         for (i = 0; i < N_UPCALL_SOCKS; i++) {
1001             struct epoll_event event;
1002
1003             error = nl_sock_create(NETLINK_GENERIC, &dpif->upcall_socks[i]);
1004             if (error) {
1005                 destroy_upcall_socks(dpif);
1006                 return error;
1007             }
1008
1009             memset(&event, 0, sizeof event);
1010             event.events = EPOLLIN;
1011             event.data.u32 = i;
1012             if (epoll_ctl(dpif->epoll_fd, EPOLL_CTL_ADD,
1013                           nl_sock_fd(dpif->upcall_socks[i]), &event) < 0) {
1014                 error = errno;
1015                 destroy_upcall_socks(dpif);
1016                 return error;
1017             }
1018         }
1019
1020         dpif->ready_mask = 0;
1021     }
1022
1023     set_upcall_pids(dpif_);
1024
1025     return 0;
1026 }
1027
1028 static int
1029 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1030                              uint32_t queue_id, uint32_t *priority)
1031 {
1032     if (queue_id < 0xf000) {
1033         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1034         return 0;
1035     } else {
1036         return EINVAL;
1037     }
1038 }
1039
1040 static int
1041 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1042                  int *dp_ifindex)
1043 {
1044     static const struct nl_policy ovs_packet_policy[] = {
1045         /* Always present. */
1046         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1047                                      .min_len = ETH_HEADER_LEN },
1048         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1049
1050         /* OVS_PACKET_CMD_ACTION only. */
1051         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
1052     };
1053
1054     struct ovs_header *ovs_header;
1055     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1056     struct nlmsghdr *nlmsg;
1057     struct genlmsghdr *genl;
1058     struct ofpbuf b;
1059     int type;
1060
1061     ofpbuf_use_const(&b, buf->data, buf->size);
1062
1063     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1064     genl = ofpbuf_try_pull(&b, sizeof *genl);
1065     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1066     if (!nlmsg || !genl || !ovs_header
1067         || nlmsg->nlmsg_type != ovs_packet_family
1068         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1069                             ARRAY_SIZE(ovs_packet_policy))) {
1070         return EINVAL;
1071     }
1072
1073     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1074             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1075             : -1);
1076     if (type < 0) {
1077         return EINVAL;
1078     }
1079
1080     memset(upcall, 0, sizeof *upcall);
1081     upcall->type = type;
1082     upcall->packet = buf;
1083     upcall->packet->data = (void *) nl_attr_get(a[OVS_PACKET_ATTR_PACKET]);
1084     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1085     upcall->key = (void *) nl_attr_get(a[OVS_PACKET_ATTR_KEY]);
1086     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1087     upcall->userdata = (a[OVS_PACKET_ATTR_USERDATA]
1088                         ? nl_attr_get_u64(a[OVS_PACKET_ATTR_USERDATA])
1089                         : 0);
1090     *dp_ifindex = ovs_header->dp_ifindex;
1091
1092     return 0;
1093 }
1094
1095 static int
1096 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
1097 {
1098     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1099     int read_tries = 0;
1100
1101     if (dpif->epoll_fd < 0) {
1102        return EAGAIN;
1103     }
1104
1105     if (!dpif->ready_mask) {
1106         struct epoll_event events[N_UPCALL_SOCKS];
1107         int retval;
1108         int i;
1109
1110         do {
1111             retval = epoll_wait(dpif->epoll_fd, events, N_UPCALL_SOCKS, 0);
1112         } while (retval < 0 && errno == EINTR);
1113         if (retval < 0) {
1114             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1115             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", strerror(errno));
1116         }
1117
1118         for (i = 0; i < retval; i++) {
1119             dpif->ready_mask |= 1u << events[i].data.u32;
1120         }
1121     }
1122
1123     while (dpif->ready_mask) {
1124         int indx = ffs(dpif->ready_mask) - 1;
1125         struct nl_sock *upcall_sock = dpif->upcall_socks[indx];
1126
1127         dpif->ready_mask &= ~(1u << indx);
1128
1129         for (;;) {
1130             struct ofpbuf *buf;
1131             int dp_ifindex;
1132             int error;
1133
1134             if (++read_tries > 50) {
1135                 return EAGAIN;
1136             }
1137
1138             error = nl_sock_recv(upcall_sock, &buf, false);
1139             if (error == EAGAIN) {
1140                 break;
1141             } else if (error) {
1142                 return error;
1143             }
1144
1145             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1146             if (!error && dp_ifindex == dpif->dp_ifindex) {
1147                 return 0;
1148             }
1149
1150             ofpbuf_delete(buf);
1151             if (error) {
1152                 return error;
1153             }
1154         }
1155     }
1156
1157     return EAGAIN;
1158 }
1159
1160 static void
1161 dpif_linux_recv_wait(struct dpif *dpif_)
1162 {
1163     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1164
1165     if (dpif->epoll_fd < 0) {
1166        return;
1167     }
1168
1169     poll_fd_wait(dpif->epoll_fd, POLLIN);
1170 }
1171
1172 static void
1173 dpif_linux_recv_purge(struct dpif *dpif_)
1174 {
1175     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1176     int i;
1177
1178     if (dpif->epoll_fd < 0) {
1179        return;
1180     }
1181
1182     for (i = 0; i < N_UPCALL_SOCKS; i++) {
1183         nl_sock_drain(dpif->upcall_socks[i]);
1184     }
1185 }
1186
1187 const struct dpif_class dpif_linux_class = {
1188     "system",
1189     dpif_linux_enumerate,
1190     dpif_linux_open,
1191     dpif_linux_close,
1192     dpif_linux_destroy,
1193     dpif_linux_run,
1194     dpif_linux_wait,
1195     dpif_linux_get_stats,
1196     dpif_linux_port_add,
1197     dpif_linux_port_del,
1198     dpif_linux_port_query_by_number,
1199     dpif_linux_port_query_by_name,
1200     dpif_linux_get_max_ports,
1201     dpif_linux_port_get_pid,
1202     dpif_linux_port_dump_start,
1203     dpif_linux_port_dump_next,
1204     dpif_linux_port_dump_done,
1205     dpif_linux_port_poll,
1206     dpif_linux_port_poll_wait,
1207     dpif_linux_flow_get,
1208     dpif_linux_flow_put,
1209     dpif_linux_flow_del,
1210     dpif_linux_flow_flush,
1211     dpif_linux_flow_dump_start,
1212     dpif_linux_flow_dump_next,
1213     dpif_linux_flow_dump_done,
1214     dpif_linux_execute,
1215     dpif_linux_operate,
1216     dpif_linux_recv_set,
1217     dpif_linux_queue_to_priority,
1218     dpif_linux_recv,
1219     dpif_linux_recv_wait,
1220     dpif_linux_recv_purge,
1221 };
1222 \f
1223 static int
1224 dpif_linux_init(void)
1225 {
1226     static int error = -1;
1227
1228     if (error < 0) {
1229         unsigned int ovs_vport_mcgroup;
1230
1231         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1232                                       &ovs_datapath_family);
1233         if (error) {
1234             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1235                      "The Open vSwitch kernel module is probably not loaded.",
1236                      OVS_DATAPATH_FAMILY);
1237         }
1238         if (!error) {
1239             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1240         }
1241         if (!error) {
1242             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1243         }
1244         if (!error) {
1245             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1246                                           &ovs_packet_family);
1247         }
1248         if (!error) {
1249             error = nl_sock_create(NETLINK_GENERIC, &genl_sock);
1250         }
1251         if (!error) {
1252             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1253                                            &ovs_vport_mcgroup,
1254                                            OVS_VPORT_MCGROUP_FALLBACK_ID);
1255         }
1256         if (!error) {
1257             static struct dpif_linux_vport vport;
1258             nln = nln_create(NETLINK_GENERIC, ovs_vport_mcgroup,
1259                              dpif_linux_nln_parse, &vport);
1260         }
1261     }
1262
1263     return error;
1264 }
1265
1266 bool
1267 dpif_linux_is_internal_device(const char *name)
1268 {
1269     struct dpif_linux_vport reply;
1270     struct ofpbuf *buf;
1271     int error;
1272
1273     error = dpif_linux_vport_get(name, &reply, &buf);
1274     if (!error) {
1275         ofpbuf_delete(buf);
1276     } else if (error != ENODEV && error != ENOENT) {
1277         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1278                      name, strerror(error));
1279     }
1280
1281     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1282 }
1283
1284 int
1285 dpif_linux_vport_send(int dp_ifindex, uint32_t port_no,
1286                       const void *data, size_t size)
1287 {
1288     struct ofpbuf actions, key, packet;
1289     struct odputil_keybuf keybuf;
1290     struct flow flow;
1291     uint64_t action;
1292
1293     ofpbuf_use_const(&packet, data, size);
1294     flow_extract(&packet, 0, htonll(0), 0, &flow);
1295
1296     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1297     odp_flow_key_from_flow(&key, &flow);
1298
1299     ofpbuf_use_stack(&actions, &action, sizeof action);
1300     nl_msg_put_u32(&actions, OVS_ACTION_ATTR_OUTPUT, port_no);
1301
1302     return dpif_linux_execute__(dp_ifindex, key.data, key.size,
1303                                 actions.data, actions.size, &packet);
1304 }
1305
1306 static bool
1307 dpif_linux_nln_parse(struct ofpbuf *buf, void *vport_)
1308 {
1309     struct dpif_linux_vport *vport = vport_;
1310     return dpif_linux_vport_from_ofpbuf(vport, buf) == 0;
1311 }
1312
1313 static void
1314 dpif_linux_port_changed(const void *vport_, void *dpif_)
1315 {
1316     const struct dpif_linux_vport *vport = vport_;
1317     struct dpif_linux *dpif = dpif_;
1318
1319     if (vport) {
1320         if (vport->dp_ifindex == dpif->dp_ifindex
1321             && (vport->cmd == OVS_VPORT_CMD_NEW
1322                 || vport->cmd == OVS_VPORT_CMD_DEL
1323                 || vport->cmd == OVS_VPORT_CMD_SET)) {
1324             VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1325                      dpif->dpif.full_name, vport->name, vport->cmd);
1326             sset_add(&dpif->changed_ports, vport->name);
1327         }
1328     } else {
1329         dpif->change_error = true;
1330     }
1331 }
1332 \f
1333 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1334  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1335  * positive errno value.
1336  *
1337  * 'vport' will contain pointers into 'buf', so the caller should not free
1338  * 'buf' while 'vport' is still in use. */
1339 static int
1340 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1341                              const struct ofpbuf *buf)
1342 {
1343     static const struct nl_policy ovs_vport_policy[] = {
1344         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1345         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1346         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1347         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1348         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1349                                    .optional = true },
1350         [OVS_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
1351                                      .min_len = ETH_ADDR_LEN,
1352                                      .max_len = ETH_ADDR_LEN,
1353                                      .optional = true },
1354         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1355     };
1356
1357     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1358     struct ovs_header *ovs_header;
1359     struct nlmsghdr *nlmsg;
1360     struct genlmsghdr *genl;
1361     struct ofpbuf b;
1362
1363     dpif_linux_vport_init(vport);
1364
1365     ofpbuf_use_const(&b, buf->data, buf->size);
1366     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1367     genl = ofpbuf_try_pull(&b, sizeof *genl);
1368     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1369     if (!nlmsg || !genl || !ovs_header
1370         || nlmsg->nlmsg_type != ovs_vport_family
1371         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1372                             ARRAY_SIZE(ovs_vport_policy))) {
1373         return EINVAL;
1374     }
1375
1376     vport->cmd = genl->cmd;
1377     vport->dp_ifindex = ovs_header->dp_ifindex;
1378     vport->port_no = nl_attr_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
1379     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1380     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1381     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1382         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1383     }
1384     if (a[OVS_VPORT_ATTR_STATS]) {
1385         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1386     }
1387     if (a[OVS_VPORT_ATTR_ADDRESS]) {
1388         vport->address = nl_attr_get(a[OVS_VPORT_ATTR_ADDRESS]);
1389     }
1390     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1391         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1392         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1393     }
1394     return 0;
1395 }
1396
1397 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1398  * followed by Netlink attributes corresponding to 'vport'. */
1399 static void
1400 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1401                            struct ofpbuf *buf)
1402 {
1403     struct ovs_header *ovs_header;
1404
1405     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1406                           vport->cmd, OVS_VPORT_VERSION);
1407
1408     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1409     ovs_header->dp_ifindex = vport->dp_ifindex;
1410
1411     if (vport->port_no != UINT32_MAX) {
1412         nl_msg_put_u32(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1413     }
1414
1415     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1416         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1417     }
1418
1419     if (vport->name) {
1420         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1421     }
1422
1423     if (vport->upcall_pid) {
1424         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1425     }
1426
1427     if (vport->stats) {
1428         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1429                           vport->stats, sizeof *vport->stats);
1430     }
1431
1432     if (vport->address) {
1433         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_ADDRESS,
1434                           vport->address, ETH_ADDR_LEN);
1435     }
1436
1437     if (vport->options) {
1438         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1439                           vport->options, vport->options_len);
1440     }
1441 }
1442
1443 /* Clears 'vport' to "empty" values. */
1444 void
1445 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1446 {
1447     memset(vport, 0, sizeof *vport);
1448     vport->port_no = UINT32_MAX;
1449 }
1450
1451 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1452  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1453  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1454  * result of the command is expected to be an ovs_vport also, which is decoded
1455  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1456  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1457 int
1458 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1459                           struct dpif_linux_vport *reply,
1460                           struct ofpbuf **bufp)
1461 {
1462     struct ofpbuf *request_buf;
1463     int error;
1464
1465     assert((reply != NULL) == (bufp != NULL));
1466
1467     error = dpif_linux_init();
1468     if (error) {
1469         if (reply) {
1470             *bufp = NULL;
1471             dpif_linux_vport_init(reply);
1472         }
1473         return error;
1474     }
1475
1476     request_buf = ofpbuf_new(1024);
1477     dpif_linux_vport_to_ofpbuf(request, request_buf);
1478     error = nl_sock_transact(genl_sock, request_buf, bufp);
1479     ofpbuf_delete(request_buf);
1480
1481     if (reply) {
1482         if (!error) {
1483             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1484         }
1485         if (error) {
1486             dpif_linux_vport_init(reply);
1487             ofpbuf_delete(*bufp);
1488             *bufp = NULL;
1489         }
1490     }
1491     return error;
1492 }
1493
1494 /* Obtains information about the kernel vport named 'name' and stores it into
1495  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1496  * longer needed ('reply' will contain pointers into '*bufp').  */
1497 int
1498 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1499                      struct ofpbuf **bufp)
1500 {
1501     struct dpif_linux_vport request;
1502
1503     dpif_linux_vport_init(&request);
1504     request.cmd = OVS_VPORT_CMD_GET;
1505     request.name = name;
1506
1507     return dpif_linux_vport_transact(&request, reply, bufp);
1508 }
1509 \f
1510 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1511  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1512  * positive errno value.
1513  *
1514  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1515  * while 'dp' is still in use. */
1516 static int
1517 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1518 {
1519     static const struct nl_policy ovs_datapath_policy[] = {
1520         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1521         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1522                                 .optional = true },
1523     };
1524
1525     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1526     struct ovs_header *ovs_header;
1527     struct nlmsghdr *nlmsg;
1528     struct genlmsghdr *genl;
1529     struct ofpbuf b;
1530
1531     dpif_linux_dp_init(dp);
1532
1533     ofpbuf_use_const(&b, buf->data, buf->size);
1534     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1535     genl = ofpbuf_try_pull(&b, sizeof *genl);
1536     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1537     if (!nlmsg || !genl || !ovs_header
1538         || nlmsg->nlmsg_type != ovs_datapath_family
1539         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1540                             ARRAY_SIZE(ovs_datapath_policy))) {
1541         return EINVAL;
1542     }
1543
1544     dp->cmd = genl->cmd;
1545     dp->dp_ifindex = ovs_header->dp_ifindex;
1546     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1547     if (a[OVS_DP_ATTR_STATS]) {
1548         /* Can't use structure assignment because Netlink doesn't ensure
1549          * sufficient alignment for 64-bit members. */
1550         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1551                sizeof dp->stats);
1552     }
1553
1554     return 0;
1555 }
1556
1557 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1558 static void
1559 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1560 {
1561     struct ovs_header *ovs_header;
1562
1563     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1564                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1565                           OVS_DATAPATH_VERSION);
1566
1567     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1568     ovs_header->dp_ifindex = dp->dp_ifindex;
1569
1570     if (dp->name) {
1571         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1572     }
1573
1574     if (dp->upcall_pid) {
1575         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1576     }
1577
1578     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1579 }
1580
1581 /* Clears 'dp' to "empty" values. */
1582 static void
1583 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1584 {
1585     memset(dp, 0, sizeof *dp);
1586 }
1587
1588 static void
1589 dpif_linux_dp_dump_start(struct nl_dump *dump)
1590 {
1591     struct dpif_linux_dp request;
1592     struct ofpbuf *buf;
1593
1594     dpif_linux_dp_init(&request);
1595     request.cmd = OVS_DP_CMD_GET;
1596
1597     buf = ofpbuf_new(1024);
1598     dpif_linux_dp_to_ofpbuf(&request, buf);
1599     nl_dump_start(dump, genl_sock, buf);
1600     ofpbuf_delete(buf);
1601 }
1602
1603 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1604  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1605  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1606  * result of the command is expected to be of the same form, which is decoded
1607  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1608  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1609 static int
1610 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1611                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1612 {
1613     struct ofpbuf *request_buf;
1614     int error;
1615
1616     assert((reply != NULL) == (bufp != NULL));
1617
1618     request_buf = ofpbuf_new(1024);
1619     dpif_linux_dp_to_ofpbuf(request, request_buf);
1620     error = nl_sock_transact(genl_sock, request_buf, bufp);
1621     ofpbuf_delete(request_buf);
1622
1623     if (reply) {
1624         if (!error) {
1625             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1626         }
1627         if (error) {
1628             dpif_linux_dp_init(reply);
1629             ofpbuf_delete(*bufp);
1630             *bufp = NULL;
1631         }
1632     }
1633     return error;
1634 }
1635
1636 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1637  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1638  * will contain pointers into '*bufp').  */
1639 static int
1640 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1641                   struct ofpbuf **bufp)
1642 {
1643     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1644     struct dpif_linux_dp request;
1645
1646     dpif_linux_dp_init(&request);
1647     request.cmd = OVS_DP_CMD_GET;
1648     request.dp_ifindex = dpif->dp_ifindex;
1649
1650     return dpif_linux_dp_transact(&request, reply, bufp);
1651 }
1652 \f
1653 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1654  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1655  * positive errno value.
1656  *
1657  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1658  * while 'flow' is still in use. */
1659 static int
1660 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1661                             const struct ofpbuf *buf)
1662 {
1663     static const struct nl_policy ovs_flow_policy[] = {
1664         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1665         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1666         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1667                                   .optional = true },
1668         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1669         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1670         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1671     };
1672
1673     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1674     struct ovs_header *ovs_header;
1675     struct nlmsghdr *nlmsg;
1676     struct genlmsghdr *genl;
1677     struct ofpbuf b;
1678
1679     dpif_linux_flow_init(flow);
1680
1681     ofpbuf_use_const(&b, buf->data, buf->size);
1682     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1683     genl = ofpbuf_try_pull(&b, sizeof *genl);
1684     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1685     if (!nlmsg || !genl || !ovs_header
1686         || nlmsg->nlmsg_type != ovs_flow_family
1687         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1688                             ARRAY_SIZE(ovs_flow_policy))) {
1689         return EINVAL;
1690     }
1691
1692     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1693     flow->dp_ifindex = ovs_header->dp_ifindex;
1694     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1695     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1696     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1697         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1698         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1699     }
1700     if (a[OVS_FLOW_ATTR_STATS]) {
1701         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1702     }
1703     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1704         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1705     }
1706     if (a[OVS_FLOW_ATTR_USED]) {
1707         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
1708     }
1709     return 0;
1710 }
1711
1712 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1713  * followed by Netlink attributes corresponding to 'flow'. */
1714 static void
1715 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1716                           struct ofpbuf *buf)
1717 {
1718     struct ovs_header *ovs_header;
1719
1720     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
1721                           NLM_F_REQUEST | flow->nlmsg_flags,
1722                           flow->cmd, OVS_FLOW_VERSION);
1723
1724     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1725     ovs_header->dp_ifindex = flow->dp_ifindex;
1726
1727     if (flow->key_len) {
1728         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
1729     }
1730
1731     if (flow->actions || flow->actions_len) {
1732         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
1733                           flow->actions, flow->actions_len);
1734     }
1735
1736     /* We never need to send these to the kernel. */
1737     assert(!flow->stats);
1738     assert(!flow->tcp_flags);
1739     assert(!flow->used);
1740
1741     if (flow->clear) {
1742         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
1743     }
1744 }
1745
1746 /* Clears 'flow' to "empty" values. */
1747 static void
1748 dpif_linux_flow_init(struct dpif_linux_flow *flow)
1749 {
1750     memset(flow, 0, sizeof *flow);
1751 }
1752
1753 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1754  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1755  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1756  * result of the command is expected to be a flow also, which is decoded and
1757  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
1758  * is no longer needed ('reply' will contain pointers into '*bufp'). */
1759 static int
1760 dpif_linux_flow_transact(struct dpif_linux_flow *request,
1761                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
1762 {
1763     struct ofpbuf *request_buf;
1764     int error;
1765
1766     assert((reply != NULL) == (bufp != NULL));
1767
1768     if (reply) {
1769         request->nlmsg_flags |= NLM_F_ECHO;
1770     }
1771
1772     request_buf = ofpbuf_new(1024);
1773     dpif_linux_flow_to_ofpbuf(request, request_buf);
1774     error = nl_sock_transact(genl_sock, request_buf, bufp);
1775     ofpbuf_delete(request_buf);
1776
1777     if (reply) {
1778         if (!error) {
1779             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
1780         }
1781         if (error) {
1782             dpif_linux_flow_init(reply);
1783             ofpbuf_delete(*bufp);
1784             *bufp = NULL;
1785         }
1786     }
1787     return error;
1788 }
1789
1790 static void
1791 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
1792                           struct dpif_flow_stats *stats)
1793 {
1794     if (flow->stats) {
1795         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
1796         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
1797     } else {
1798         stats->n_packets = 0;
1799         stats->n_bytes = 0;
1800     }
1801     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
1802     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
1803 }