dpif: Factor 'type' and 'error' out of individual dpif_op members.
[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_, struct 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         struct dpif_op *op = ops[i];
887
888         if (op->type == DPIF_OP_FLOW_PUT) {
889             struct dpif_flow_put *put = &op->u.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->u.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         struct dpif_op *op = ops[i];
923
924         if (op->type == DPIF_OP_FLOW_PUT) {
925             struct dpif_flow_put *put = &op->u.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             op->error = error;
937         } else if (op->type == DPIF_OP_EXECUTE) {
938             op->error = txn->error;
939         } else {
940             NOT_REACHED();
941         }
942
943         ofpbuf_delete(txn->request);
944         ofpbuf_delete(txn->reply);
945     }
946     free(txns);
947 }
948
949 static void
950 set_upcall_pids(struct dpif *dpif_)
951 {
952     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
953     struct dpif_port_dump port_dump;
954     struct dpif_port port;
955     int error;
956
957     DPIF_PORT_FOR_EACH (&port, &port_dump, &dpif->dpif) {
958         uint32_t upcall_pid = dpif_linux_port_get_pid(dpif_, port.port_no);
959         struct dpif_linux_vport vport_request;
960
961         dpif_linux_vport_init(&vport_request);
962         vport_request.cmd = OVS_VPORT_CMD_SET;
963         vport_request.dp_ifindex = dpif->dp_ifindex;
964         vport_request.port_no = port.port_no;
965         vport_request.upcall_pid = &upcall_pid;
966         error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
967         if (!error) {
968             VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
969                      dpif_name(&dpif->dpif), vport_request.port_no,
970                      upcall_pid);
971         } else {
972             VLOG_WARN_RL(&error_rl, "%s: failed to set upcall pid on port: %s",
973                          dpif_name(&dpif->dpif), strerror(error));
974         }
975     }
976 }
977
978 static int
979 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
980 {
981     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
982
983     if ((dpif->epoll_fd >= 0) == enable) {
984         return 0;
985     }
986
987     if (!enable) {
988         destroy_upcall_socks(dpif);
989     } else {
990         int i;
991         int error;
992
993         dpif->epoll_fd = epoll_create(N_UPCALL_SOCKS);
994         if (dpif->epoll_fd < 0) {
995             return errno;
996         }
997
998         for (i = 0; i < N_UPCALL_SOCKS; i++) {
999             struct epoll_event event;
1000
1001             error = nl_sock_create(NETLINK_GENERIC, &dpif->upcall_socks[i]);
1002             if (error) {
1003                 destroy_upcall_socks(dpif);
1004                 return error;
1005             }
1006
1007             memset(&event, 0, sizeof event);
1008             event.events = EPOLLIN;
1009             event.data.u32 = i;
1010             if (epoll_ctl(dpif->epoll_fd, EPOLL_CTL_ADD,
1011                           nl_sock_fd(dpif->upcall_socks[i]), &event) < 0) {
1012                 error = errno;
1013                 destroy_upcall_socks(dpif);
1014                 return error;
1015             }
1016         }
1017
1018         dpif->ready_mask = 0;
1019     }
1020
1021     set_upcall_pids(dpif_);
1022
1023     return 0;
1024 }
1025
1026 static int
1027 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1028                              uint32_t queue_id, uint32_t *priority)
1029 {
1030     if (queue_id < 0xf000) {
1031         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1032         return 0;
1033     } else {
1034         return EINVAL;
1035     }
1036 }
1037
1038 static int
1039 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1040                  int *dp_ifindex)
1041 {
1042     static const struct nl_policy ovs_packet_policy[] = {
1043         /* Always present. */
1044         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1045                                      .min_len = ETH_HEADER_LEN },
1046         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1047
1048         /* OVS_PACKET_CMD_ACTION only. */
1049         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
1050     };
1051
1052     struct ovs_header *ovs_header;
1053     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1054     struct nlmsghdr *nlmsg;
1055     struct genlmsghdr *genl;
1056     struct ofpbuf b;
1057     int type;
1058
1059     ofpbuf_use_const(&b, buf->data, buf->size);
1060
1061     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1062     genl = ofpbuf_try_pull(&b, sizeof *genl);
1063     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1064     if (!nlmsg || !genl || !ovs_header
1065         || nlmsg->nlmsg_type != ovs_packet_family
1066         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1067                             ARRAY_SIZE(ovs_packet_policy))) {
1068         return EINVAL;
1069     }
1070
1071     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1072             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1073             : -1);
1074     if (type < 0) {
1075         return EINVAL;
1076     }
1077
1078     memset(upcall, 0, sizeof *upcall);
1079     upcall->type = type;
1080     upcall->packet = buf;
1081     upcall->packet->data = (void *) nl_attr_get(a[OVS_PACKET_ATTR_PACKET]);
1082     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1083     upcall->key = (void *) nl_attr_get(a[OVS_PACKET_ATTR_KEY]);
1084     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1085     upcall->userdata = (a[OVS_PACKET_ATTR_USERDATA]
1086                         ? nl_attr_get_u64(a[OVS_PACKET_ATTR_USERDATA])
1087                         : 0);
1088     *dp_ifindex = ovs_header->dp_ifindex;
1089
1090     return 0;
1091 }
1092
1093 static int
1094 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
1095 {
1096     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1097     int read_tries = 0;
1098
1099     if (dpif->epoll_fd < 0) {
1100        return EAGAIN;
1101     }
1102
1103     if (!dpif->ready_mask) {
1104         struct epoll_event events[N_UPCALL_SOCKS];
1105         int retval;
1106         int i;
1107
1108         do {
1109             retval = epoll_wait(dpif->epoll_fd, events, N_UPCALL_SOCKS, 0);
1110         } while (retval < 0 && errno == EINTR);
1111         if (retval < 0) {
1112             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1113             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", strerror(errno));
1114         }
1115
1116         for (i = 0; i < retval; i++) {
1117             dpif->ready_mask |= 1u << events[i].data.u32;
1118         }
1119     }
1120
1121     while (dpif->ready_mask) {
1122         int indx = ffs(dpif->ready_mask) - 1;
1123         struct nl_sock *upcall_sock = dpif->upcall_socks[indx];
1124
1125         dpif->ready_mask &= ~(1u << indx);
1126
1127         for (;;) {
1128             struct ofpbuf *buf;
1129             int dp_ifindex;
1130             int error;
1131
1132             if (++read_tries > 50) {
1133                 return EAGAIN;
1134             }
1135
1136             error = nl_sock_recv(upcall_sock, &buf, false);
1137             if (error == EAGAIN) {
1138                 break;
1139             } else if (error) {
1140                 return error;
1141             }
1142
1143             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1144             if (!error && dp_ifindex == dpif->dp_ifindex) {
1145                 return 0;
1146             }
1147
1148             ofpbuf_delete(buf);
1149             if (error) {
1150                 return error;
1151             }
1152         }
1153     }
1154
1155     return EAGAIN;
1156 }
1157
1158 static void
1159 dpif_linux_recv_wait(struct dpif *dpif_)
1160 {
1161     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1162
1163     if (dpif->epoll_fd < 0) {
1164        return;
1165     }
1166
1167     poll_fd_wait(dpif->epoll_fd, POLLIN);
1168 }
1169
1170 static void
1171 dpif_linux_recv_purge(struct dpif *dpif_)
1172 {
1173     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1174     int i;
1175
1176     if (dpif->epoll_fd < 0) {
1177        return;
1178     }
1179
1180     for (i = 0; i < N_UPCALL_SOCKS; i++) {
1181         nl_sock_drain(dpif->upcall_socks[i]);
1182     }
1183 }
1184
1185 const struct dpif_class dpif_linux_class = {
1186     "system",
1187     dpif_linux_enumerate,
1188     dpif_linux_open,
1189     dpif_linux_close,
1190     dpif_linux_destroy,
1191     dpif_linux_run,
1192     dpif_linux_wait,
1193     dpif_linux_get_stats,
1194     dpif_linux_port_add,
1195     dpif_linux_port_del,
1196     dpif_linux_port_query_by_number,
1197     dpif_linux_port_query_by_name,
1198     dpif_linux_get_max_ports,
1199     dpif_linux_port_get_pid,
1200     dpif_linux_port_dump_start,
1201     dpif_linux_port_dump_next,
1202     dpif_linux_port_dump_done,
1203     dpif_linux_port_poll,
1204     dpif_linux_port_poll_wait,
1205     dpif_linux_flow_get,
1206     dpif_linux_flow_put,
1207     dpif_linux_flow_del,
1208     dpif_linux_flow_flush,
1209     dpif_linux_flow_dump_start,
1210     dpif_linux_flow_dump_next,
1211     dpif_linux_flow_dump_done,
1212     dpif_linux_execute,
1213     dpif_linux_operate,
1214     dpif_linux_recv_set,
1215     dpif_linux_queue_to_priority,
1216     dpif_linux_recv,
1217     dpif_linux_recv_wait,
1218     dpif_linux_recv_purge,
1219 };
1220 \f
1221 static int
1222 dpif_linux_init(void)
1223 {
1224     static int error = -1;
1225
1226     if (error < 0) {
1227         unsigned int ovs_vport_mcgroup;
1228
1229         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1230                                       &ovs_datapath_family);
1231         if (error) {
1232             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1233                      "The Open vSwitch kernel module is probably not loaded.",
1234                      OVS_DATAPATH_FAMILY);
1235         }
1236         if (!error) {
1237             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1238         }
1239         if (!error) {
1240             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1241         }
1242         if (!error) {
1243             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1244                                           &ovs_packet_family);
1245         }
1246         if (!error) {
1247             error = nl_sock_create(NETLINK_GENERIC, &genl_sock);
1248         }
1249         if (!error) {
1250             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1251                                            &ovs_vport_mcgroup,
1252                                            OVS_VPORT_MCGROUP_FALLBACK_ID);
1253         }
1254         if (!error) {
1255             static struct dpif_linux_vport vport;
1256             nln = nln_create(NETLINK_GENERIC, ovs_vport_mcgroup,
1257                              dpif_linux_nln_parse, &vport);
1258         }
1259     }
1260
1261     return error;
1262 }
1263
1264 bool
1265 dpif_linux_is_internal_device(const char *name)
1266 {
1267     struct dpif_linux_vport reply;
1268     struct ofpbuf *buf;
1269     int error;
1270
1271     error = dpif_linux_vport_get(name, &reply, &buf);
1272     if (!error) {
1273         ofpbuf_delete(buf);
1274     } else if (error != ENODEV && error != ENOENT) {
1275         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1276                      name, strerror(error));
1277     }
1278
1279     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1280 }
1281
1282 int
1283 dpif_linux_vport_send(int dp_ifindex, uint32_t port_no,
1284                       const void *data, size_t size)
1285 {
1286     struct ofpbuf actions, key, packet;
1287     struct odputil_keybuf keybuf;
1288     struct flow flow;
1289     uint64_t action;
1290
1291     ofpbuf_use_const(&packet, data, size);
1292     flow_extract(&packet, 0, htonll(0), 0, &flow);
1293
1294     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1295     odp_flow_key_from_flow(&key, &flow);
1296
1297     ofpbuf_use_stack(&actions, &action, sizeof action);
1298     nl_msg_put_u32(&actions, OVS_ACTION_ATTR_OUTPUT, port_no);
1299
1300     return dpif_linux_execute__(dp_ifindex, key.data, key.size,
1301                                 actions.data, actions.size, &packet);
1302 }
1303
1304 static bool
1305 dpif_linux_nln_parse(struct ofpbuf *buf, void *vport_)
1306 {
1307     struct dpif_linux_vport *vport = vport_;
1308     return dpif_linux_vport_from_ofpbuf(vport, buf) == 0;
1309 }
1310
1311 static void
1312 dpif_linux_port_changed(const void *vport_, void *dpif_)
1313 {
1314     const struct dpif_linux_vport *vport = vport_;
1315     struct dpif_linux *dpif = dpif_;
1316
1317     if (vport) {
1318         if (vport->dp_ifindex == dpif->dp_ifindex
1319             && (vport->cmd == OVS_VPORT_CMD_NEW
1320                 || vport->cmd == OVS_VPORT_CMD_DEL
1321                 || vport->cmd == OVS_VPORT_CMD_SET)) {
1322             VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1323                      dpif->dpif.full_name, vport->name, vport->cmd);
1324             sset_add(&dpif->changed_ports, vport->name);
1325         }
1326     } else {
1327         dpif->change_error = true;
1328     }
1329 }
1330 \f
1331 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1332  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1333  * positive errno value.
1334  *
1335  * 'vport' will contain pointers into 'buf', so the caller should not free
1336  * 'buf' while 'vport' is still in use. */
1337 static int
1338 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1339                              const struct ofpbuf *buf)
1340 {
1341     static const struct nl_policy ovs_vport_policy[] = {
1342         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1343         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1344         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1345         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1346         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1347                                    .optional = true },
1348         [OVS_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
1349                                      .min_len = ETH_ADDR_LEN,
1350                                      .max_len = ETH_ADDR_LEN,
1351                                      .optional = true },
1352         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1353     };
1354
1355     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1356     struct ovs_header *ovs_header;
1357     struct nlmsghdr *nlmsg;
1358     struct genlmsghdr *genl;
1359     struct ofpbuf b;
1360
1361     dpif_linux_vport_init(vport);
1362
1363     ofpbuf_use_const(&b, buf->data, buf->size);
1364     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1365     genl = ofpbuf_try_pull(&b, sizeof *genl);
1366     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1367     if (!nlmsg || !genl || !ovs_header
1368         || nlmsg->nlmsg_type != ovs_vport_family
1369         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1370                             ARRAY_SIZE(ovs_vport_policy))) {
1371         return EINVAL;
1372     }
1373
1374     vport->cmd = genl->cmd;
1375     vport->dp_ifindex = ovs_header->dp_ifindex;
1376     vport->port_no = nl_attr_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
1377     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1378     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1379     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1380         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1381     }
1382     if (a[OVS_VPORT_ATTR_STATS]) {
1383         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1384     }
1385     if (a[OVS_VPORT_ATTR_ADDRESS]) {
1386         vport->address = nl_attr_get(a[OVS_VPORT_ATTR_ADDRESS]);
1387     }
1388     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1389         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1390         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1391     }
1392     return 0;
1393 }
1394
1395 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1396  * followed by Netlink attributes corresponding to 'vport'. */
1397 static void
1398 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1399                            struct ofpbuf *buf)
1400 {
1401     struct ovs_header *ovs_header;
1402
1403     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1404                           vport->cmd, OVS_VPORT_VERSION);
1405
1406     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1407     ovs_header->dp_ifindex = vport->dp_ifindex;
1408
1409     if (vport->port_no != UINT32_MAX) {
1410         nl_msg_put_u32(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1411     }
1412
1413     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1414         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1415     }
1416
1417     if (vport->name) {
1418         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1419     }
1420
1421     if (vport->upcall_pid) {
1422         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1423     }
1424
1425     if (vport->stats) {
1426         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1427                           vport->stats, sizeof *vport->stats);
1428     }
1429
1430     if (vport->address) {
1431         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_ADDRESS,
1432                           vport->address, ETH_ADDR_LEN);
1433     }
1434
1435     if (vport->options) {
1436         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1437                           vport->options, vport->options_len);
1438     }
1439 }
1440
1441 /* Clears 'vport' to "empty" values. */
1442 void
1443 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1444 {
1445     memset(vport, 0, sizeof *vport);
1446     vport->port_no = UINT32_MAX;
1447 }
1448
1449 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1450  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1451  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1452  * result of the command is expected to be an ovs_vport also, which is decoded
1453  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1454  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1455 int
1456 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1457                           struct dpif_linux_vport *reply,
1458                           struct ofpbuf **bufp)
1459 {
1460     struct ofpbuf *request_buf;
1461     int error;
1462
1463     assert((reply != NULL) == (bufp != NULL));
1464
1465     error = dpif_linux_init();
1466     if (error) {
1467         if (reply) {
1468             *bufp = NULL;
1469             dpif_linux_vport_init(reply);
1470         }
1471         return error;
1472     }
1473
1474     request_buf = ofpbuf_new(1024);
1475     dpif_linux_vport_to_ofpbuf(request, request_buf);
1476     error = nl_sock_transact(genl_sock, request_buf, bufp);
1477     ofpbuf_delete(request_buf);
1478
1479     if (reply) {
1480         if (!error) {
1481             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1482         }
1483         if (error) {
1484             dpif_linux_vport_init(reply);
1485             ofpbuf_delete(*bufp);
1486             *bufp = NULL;
1487         }
1488     }
1489     return error;
1490 }
1491
1492 /* Obtains information about the kernel vport named 'name' and stores it into
1493  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1494  * longer needed ('reply' will contain pointers into '*bufp').  */
1495 int
1496 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1497                      struct ofpbuf **bufp)
1498 {
1499     struct dpif_linux_vport request;
1500
1501     dpif_linux_vport_init(&request);
1502     request.cmd = OVS_VPORT_CMD_GET;
1503     request.name = name;
1504
1505     return dpif_linux_vport_transact(&request, reply, bufp);
1506 }
1507 \f
1508 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1509  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1510  * positive errno value.
1511  *
1512  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1513  * while 'dp' is still in use. */
1514 static int
1515 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1516 {
1517     static const struct nl_policy ovs_datapath_policy[] = {
1518         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1519         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1520                                 .optional = true },
1521     };
1522
1523     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1524     struct ovs_header *ovs_header;
1525     struct nlmsghdr *nlmsg;
1526     struct genlmsghdr *genl;
1527     struct ofpbuf b;
1528
1529     dpif_linux_dp_init(dp);
1530
1531     ofpbuf_use_const(&b, buf->data, buf->size);
1532     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1533     genl = ofpbuf_try_pull(&b, sizeof *genl);
1534     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1535     if (!nlmsg || !genl || !ovs_header
1536         || nlmsg->nlmsg_type != ovs_datapath_family
1537         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1538                             ARRAY_SIZE(ovs_datapath_policy))) {
1539         return EINVAL;
1540     }
1541
1542     dp->cmd = genl->cmd;
1543     dp->dp_ifindex = ovs_header->dp_ifindex;
1544     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1545     if (a[OVS_DP_ATTR_STATS]) {
1546         /* Can't use structure assignment because Netlink doesn't ensure
1547          * sufficient alignment for 64-bit members. */
1548         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1549                sizeof dp->stats);
1550     }
1551
1552     return 0;
1553 }
1554
1555 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1556 static void
1557 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1558 {
1559     struct ovs_header *ovs_header;
1560
1561     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1562                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1563                           OVS_DATAPATH_VERSION);
1564
1565     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1566     ovs_header->dp_ifindex = dp->dp_ifindex;
1567
1568     if (dp->name) {
1569         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1570     }
1571
1572     if (dp->upcall_pid) {
1573         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1574     }
1575
1576     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1577 }
1578
1579 /* Clears 'dp' to "empty" values. */
1580 static void
1581 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1582 {
1583     memset(dp, 0, sizeof *dp);
1584 }
1585
1586 static void
1587 dpif_linux_dp_dump_start(struct nl_dump *dump)
1588 {
1589     struct dpif_linux_dp request;
1590     struct ofpbuf *buf;
1591
1592     dpif_linux_dp_init(&request);
1593     request.cmd = OVS_DP_CMD_GET;
1594
1595     buf = ofpbuf_new(1024);
1596     dpif_linux_dp_to_ofpbuf(&request, buf);
1597     nl_dump_start(dump, genl_sock, buf);
1598     ofpbuf_delete(buf);
1599 }
1600
1601 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1602  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1603  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1604  * result of the command is expected to be of the same form, which is decoded
1605  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1606  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1607 static int
1608 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1609                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1610 {
1611     struct ofpbuf *request_buf;
1612     int error;
1613
1614     assert((reply != NULL) == (bufp != NULL));
1615
1616     request_buf = ofpbuf_new(1024);
1617     dpif_linux_dp_to_ofpbuf(request, request_buf);
1618     error = nl_sock_transact(genl_sock, request_buf, bufp);
1619     ofpbuf_delete(request_buf);
1620
1621     if (reply) {
1622         if (!error) {
1623             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1624         }
1625         if (error) {
1626             dpif_linux_dp_init(reply);
1627             ofpbuf_delete(*bufp);
1628             *bufp = NULL;
1629         }
1630     }
1631     return error;
1632 }
1633
1634 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1635  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1636  * will contain pointers into '*bufp').  */
1637 static int
1638 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1639                   struct ofpbuf **bufp)
1640 {
1641     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1642     struct dpif_linux_dp request;
1643
1644     dpif_linux_dp_init(&request);
1645     request.cmd = OVS_DP_CMD_GET;
1646     request.dp_ifindex = dpif->dp_ifindex;
1647
1648     return dpif_linux_dp_transact(&request, reply, bufp);
1649 }
1650 \f
1651 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1652  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1653  * positive errno value.
1654  *
1655  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1656  * while 'flow' is still in use. */
1657 static int
1658 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1659                             const struct ofpbuf *buf)
1660 {
1661     static const struct nl_policy ovs_flow_policy[] = {
1662         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1663         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1664         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1665                                   .optional = true },
1666         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1667         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1668         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1669     };
1670
1671     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1672     struct ovs_header *ovs_header;
1673     struct nlmsghdr *nlmsg;
1674     struct genlmsghdr *genl;
1675     struct ofpbuf b;
1676
1677     dpif_linux_flow_init(flow);
1678
1679     ofpbuf_use_const(&b, buf->data, buf->size);
1680     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1681     genl = ofpbuf_try_pull(&b, sizeof *genl);
1682     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1683     if (!nlmsg || !genl || !ovs_header
1684         || nlmsg->nlmsg_type != ovs_flow_family
1685         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1686                             ARRAY_SIZE(ovs_flow_policy))) {
1687         return EINVAL;
1688     }
1689
1690     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1691     flow->dp_ifindex = ovs_header->dp_ifindex;
1692     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1693     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1694     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1695         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1696         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1697     }
1698     if (a[OVS_FLOW_ATTR_STATS]) {
1699         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1700     }
1701     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1702         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1703     }
1704     if (a[OVS_FLOW_ATTR_USED]) {
1705         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
1706     }
1707     return 0;
1708 }
1709
1710 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1711  * followed by Netlink attributes corresponding to 'flow'. */
1712 static void
1713 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1714                           struct ofpbuf *buf)
1715 {
1716     struct ovs_header *ovs_header;
1717
1718     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
1719                           NLM_F_REQUEST | flow->nlmsg_flags,
1720                           flow->cmd, OVS_FLOW_VERSION);
1721
1722     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1723     ovs_header->dp_ifindex = flow->dp_ifindex;
1724
1725     if (flow->key_len) {
1726         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
1727     }
1728
1729     if (flow->actions || flow->actions_len) {
1730         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
1731                           flow->actions, flow->actions_len);
1732     }
1733
1734     /* We never need to send these to the kernel. */
1735     assert(!flow->stats);
1736     assert(!flow->tcp_flags);
1737     assert(!flow->used);
1738
1739     if (flow->clear) {
1740         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
1741     }
1742 }
1743
1744 /* Clears 'flow' to "empty" values. */
1745 static void
1746 dpif_linux_flow_init(struct dpif_linux_flow *flow)
1747 {
1748     memset(flow, 0, sizeof *flow);
1749 }
1750
1751 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1752  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1753  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1754  * result of the command is expected to be a flow also, which is decoded and
1755  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
1756  * is no longer needed ('reply' will contain pointers into '*bufp'). */
1757 static int
1758 dpif_linux_flow_transact(struct dpif_linux_flow *request,
1759                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
1760 {
1761     struct ofpbuf *request_buf;
1762     int error;
1763
1764     assert((reply != NULL) == (bufp != NULL));
1765
1766     if (reply) {
1767         request->nlmsg_flags |= NLM_F_ECHO;
1768     }
1769
1770     request_buf = ofpbuf_new(1024);
1771     dpif_linux_flow_to_ofpbuf(request, request_buf);
1772     error = nl_sock_transact(genl_sock, request_buf, bufp);
1773     ofpbuf_delete(request_buf);
1774
1775     if (reply) {
1776         if (!error) {
1777             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
1778         }
1779         if (error) {
1780             dpif_linux_flow_init(reply);
1781             ofpbuf_delete(*bufp);
1782             *bufp = NULL;
1783         }
1784     }
1785     return error;
1786 }
1787
1788 static void
1789 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
1790                           struct dpif_flow_stats *stats)
1791 {
1792     if (flow->stats) {
1793         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
1794         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
1795     } else {
1796         stats->n_packets = 0;
1797         stats->n_bytes = 0;
1798     }
1799     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
1800     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
1801 }