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