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