Avoid printf type modifiers not supported by MSVC C runtime library.
[cascardo/ovs.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/types.h>
27 #include <linux/pkt_sched.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <poll.h>
31 #include <stdlib.h>
32 #include <strings.h>
33 #include <sys/epoll.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "bitmap.h"
38 #include "dpif-provider.h"
39 #include "dynamic-string.h"
40 #include "flow.h"
41 #include "netdev.h"
42 #include "netdev-linux.h"
43 #include "netdev-vport.h"
44 #include "netlink-notifier.h"
45 #include "netlink-socket.h"
46 #include "netlink.h"
47 #include "odp-util.h"
48 #include "ofpbuf.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "shash.h"
53 #include "sset.h"
54 #include "timeval.h"
55 #include "unaligned.h"
56 #include "util.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(dpif_linux);
60 enum { MAX_PORTS = USHRT_MAX };
61
62 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
63  * missing if we have old headers. */
64 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
65
66 struct dpif_linux_dp {
67     /* Generic Netlink header. */
68     uint8_t cmd;
69
70     /* struct ovs_header. */
71     int dp_ifindex;
72
73     /* Attributes. */
74     const char *name;                  /* OVS_DP_ATTR_NAME. */
75     const uint32_t *upcall_pid;        /* OVS_DP_ATTR_UPCALL_PID. */
76     struct ovs_dp_stats stats;         /* OVS_DP_ATTR_STATS. */
77     struct ovs_dp_megaflow_stats megaflow_stats;
78                                        /* OVS_DP_ATTR_MEGAFLOW_STATS.*/
79 };
80
81 static void dpif_linux_dp_init(struct dpif_linux_dp *);
82 static int dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *,
83                                      const struct ofpbuf *);
84 static void dpif_linux_dp_dump_start(struct nl_dump *);
85 static int dpif_linux_dp_transact(const struct dpif_linux_dp *request,
86                                   struct dpif_linux_dp *reply,
87                                   struct ofpbuf **bufp);
88 static int dpif_linux_dp_get(const struct dpif *, struct dpif_linux_dp *reply,
89                              struct ofpbuf **bufp);
90
91 struct dpif_linux_flow {
92     /* Generic Netlink header. */
93     uint8_t cmd;
94
95     /* struct ovs_header. */
96     unsigned int nlmsg_flags;
97     int dp_ifindex;
98
99     /* Attributes.
100      *
101      * The 'stats' member points to 64-bit data that might only be aligned on
102      * 32-bit boundaries, so get_unaligned_u64() should be used to access its
103      * values.
104      *
105      * If 'actions' is nonnull then OVS_FLOW_ATTR_ACTIONS will be included in
106      * the Netlink version of the command, even if actions_len is zero. */
107     const struct nlattr *key;           /* OVS_FLOW_ATTR_KEY. */
108     size_t key_len;
109     const struct nlattr *mask;          /* OVS_FLOW_ATTR_MASK. */
110     size_t mask_len;
111     const struct nlattr *actions;       /* OVS_FLOW_ATTR_ACTIONS. */
112     size_t actions_len;
113     const struct ovs_flow_stats *stats; /* OVS_FLOW_ATTR_STATS. */
114     const uint8_t *tcp_flags;           /* OVS_FLOW_ATTR_TCP_FLAGS. */
115     const ovs_32aligned_u64 *used;      /* OVS_FLOW_ATTR_USED. */
116     bool clear;                         /* OVS_FLOW_ATTR_CLEAR. */
117 };
118
119 static void dpif_linux_flow_init(struct dpif_linux_flow *);
120 static int dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *,
121                                        const struct ofpbuf *);
122 static void dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *,
123                                       struct ofpbuf *);
124 static int dpif_linux_flow_transact(struct dpif_linux_flow *request,
125                                     struct dpif_linux_flow *reply,
126                                     struct ofpbuf **bufp);
127 static void dpif_linux_flow_get_stats(const struct dpif_linux_flow *,
128                                       struct dpif_flow_stats *);
129
130 /* One of the dpif channels between the kernel and userspace. */
131 struct dpif_channel {
132     struct nl_sock *sock;       /* Netlink socket. */
133     long long int last_poll;    /* Last time this channel was polled. */
134 };
135
136 static void report_loss(struct dpif *, struct dpif_channel *);
137
138 /* Datapath interface for the openvswitch Linux kernel module. */
139 struct dpif_linux {
140     struct dpif dpif;
141     int dp_ifindex;
142
143     /* Upcall messages. */
144     struct ovs_mutex upcall_lock;
145     int uc_array_size;          /* Size of 'channels' and 'epoll_events'. */
146     struct dpif_channel *channels;
147     struct epoll_event *epoll_events;
148     int epoll_fd;               /* epoll fd that includes channel socks. */
149     int n_events;               /* Num events returned by epoll_wait(). */
150     int event_offset;           /* Offset into 'epoll_events'. */
151
152     /* Change notification. */
153     struct nl_sock *port_notifier; /* vport multicast group subscriber. */
154 };
155
156 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
157
158 /* Generic Netlink family numbers for OVS.
159  *
160  * Initialized by dpif_linux_init(). */
161 static int ovs_datapath_family;
162 static int ovs_vport_family;
163 static int ovs_flow_family;
164 static int ovs_packet_family;
165
166 /* Generic Netlink multicast groups for OVS.
167  *
168  * Initialized by dpif_linux_init(). */
169 static unsigned int ovs_vport_mcgroup;
170
171 static int dpif_linux_init(void);
172 static int open_dpif(const struct dpif_linux_dp *, struct dpif **);
173 static uint32_t dpif_linux_port_get_pid(const struct dpif *,
174                                         odp_port_t port_no);
175
176 static void dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *,
177                                        struct ofpbuf *);
178 static int dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *,
179                                         const struct ofpbuf *);
180
181 static struct dpif_linux *
182 dpif_linux_cast(const struct dpif *dpif)
183 {
184     dpif_assert_class(dpif, &dpif_linux_class);
185     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
186 }
187
188 static int
189 dpif_linux_enumerate(struct sset *all_dps)
190 {
191     struct nl_dump dump;
192     struct ofpbuf msg;
193     int error;
194
195     error = dpif_linux_init();
196     if (error) {
197         return error;
198     }
199
200     dpif_linux_dp_dump_start(&dump);
201     while (nl_dump_next(&dump, &msg)) {
202         struct dpif_linux_dp dp;
203
204         if (!dpif_linux_dp_from_ofpbuf(&dp, &msg)) {
205             sset_add(all_dps, dp.name);
206         }
207     }
208     return nl_dump_done(&dump);
209 }
210
211 static int
212 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
213                 bool create, struct dpif **dpifp)
214 {
215     struct dpif_linux_dp dp_request, dp;
216     struct ofpbuf *buf;
217     uint32_t upcall_pid;
218     int error;
219
220     error = dpif_linux_init();
221     if (error) {
222         return error;
223     }
224
225     /* Create or look up datapath. */
226     dpif_linux_dp_init(&dp_request);
227     if (create) {
228         dp_request.cmd = OVS_DP_CMD_NEW;
229         upcall_pid = 0;
230         dp_request.upcall_pid = &upcall_pid;
231     } else {
232         dp_request.cmd = OVS_DP_CMD_GET;
233     }
234     dp_request.name = name;
235     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
236     if (error) {
237         return error;
238     }
239
240     error = open_dpif(&dp, dpifp);
241     ofpbuf_delete(buf);
242     return error;
243 }
244
245 static int
246 open_dpif(const struct dpif_linux_dp *dp, struct dpif **dpifp)
247 {
248     struct dpif_linux *dpif;
249
250     dpif = xzalloc(sizeof *dpif);
251     dpif->port_notifier = NULL;
252     ovs_mutex_init(&dpif->upcall_lock);
253     dpif->epoll_fd = -1;
254
255     dpif_init(&dpif->dpif, &dpif_linux_class, dp->name,
256               dp->dp_ifindex, dp->dp_ifindex);
257
258     dpif->dp_ifindex = dp->dp_ifindex;
259     *dpifp = &dpif->dpif;
260
261     return 0;
262 }
263
264 static void
265 destroy_channels(struct dpif_linux *dpif)
266 {
267     unsigned int i;
268
269     if (dpif->epoll_fd < 0) {
270         return;
271     }
272
273     for (i = 0; i < dpif->uc_array_size; i++ ) {
274         struct dpif_linux_vport vport_request;
275         struct dpif_channel *ch = &dpif->channels[i];
276         uint32_t upcall_pid = 0;
277
278         if (!ch->sock) {
279             continue;
280         }
281
282         epoll_ctl(dpif->epoll_fd, EPOLL_CTL_DEL, nl_sock_fd(ch->sock), NULL);
283
284         /* Turn off upcalls. */
285         dpif_linux_vport_init(&vport_request);
286         vport_request.cmd = OVS_VPORT_CMD_SET;
287         vport_request.dp_ifindex = dpif->dp_ifindex;
288         vport_request.port_no = u32_to_odp(i);
289         vport_request.upcall_pid = &upcall_pid;
290         dpif_linux_vport_transact(&vport_request, NULL, NULL);
291
292         nl_sock_destroy(ch->sock);
293     }
294
295     free(dpif->channels);
296     dpif->channels = NULL;
297     dpif->uc_array_size = 0;
298
299     free(dpif->epoll_events);
300     dpif->epoll_events = NULL;
301     dpif->n_events = dpif->event_offset = 0;
302
303     /* Don't close dpif->epoll_fd since that would cause other threads that
304      * call dpif_recv_wait(dpif) to wait on an arbitrary fd or a closed fd. */
305 }
306
307 static int
308 add_channel(struct dpif_linux *dpif, odp_port_t port_no, struct nl_sock *sock)
309 {
310     struct epoll_event event;
311     uint32_t port_idx = odp_to_u32(port_no);
312
313     if (dpif->epoll_fd < 0) {
314         return 0;
315     }
316
317     /* We assume that the datapath densely chooses port numbers, which
318      * can therefore be used as an index into an array of channels. */
319     if (port_idx >= dpif->uc_array_size) {
320         uint32_t new_size = port_idx + 1;
321         uint32_t i;
322
323         if (new_size > MAX_PORTS) {
324             VLOG_WARN_RL(&error_rl, "%s: datapath port %"PRIu32" too big",
325                          dpif_name(&dpif->dpif), port_no);
326             return EFBIG;
327         }
328
329         dpif->channels = xrealloc(dpif->channels,
330                                   new_size * sizeof *dpif->channels);
331         for (i = dpif->uc_array_size; i < new_size; i++) {
332             dpif->channels[i].sock = NULL;
333         }
334
335         dpif->epoll_events = xrealloc(dpif->epoll_events,
336                                       new_size * sizeof *dpif->epoll_events);
337         dpif->uc_array_size = new_size;
338     }
339
340     memset(&event, 0, sizeof event);
341     event.events = EPOLLIN;
342     event.data.u32 = port_idx;
343     if (epoll_ctl(dpif->epoll_fd, EPOLL_CTL_ADD, nl_sock_fd(sock),
344                   &event) < 0) {
345         return errno;
346     }
347
348     nl_sock_destroy(dpif->channels[port_idx].sock);
349     dpif->channels[port_idx].sock = sock;
350     dpif->channels[port_idx].last_poll = LLONG_MIN;
351
352     return 0;
353 }
354
355 static void
356 del_channel(struct dpif_linux *dpif, odp_port_t port_no)
357 {
358     struct dpif_channel *ch;
359     uint32_t port_idx = odp_to_u32(port_no);
360
361     if (dpif->epoll_fd < 0 || port_idx >= dpif->uc_array_size) {
362         return;
363     }
364
365     ch = &dpif->channels[port_idx];
366     if (!ch->sock) {
367         return;
368     }
369
370     epoll_ctl(dpif->epoll_fd, EPOLL_CTL_DEL, nl_sock_fd(ch->sock), NULL);
371     dpif->event_offset = dpif->n_events = 0;
372
373     nl_sock_destroy(ch->sock);
374     ch->sock = NULL;
375 }
376
377 static void
378 dpif_linux_close(struct dpif *dpif_)
379 {
380     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
381
382     nl_sock_destroy(dpif->port_notifier);
383     destroy_channels(dpif);
384     if (dpif->epoll_fd >= 0) {
385         close(dpif->epoll_fd);
386     }
387     ovs_mutex_destroy(&dpif->upcall_lock);
388     free(dpif);
389 }
390
391 static int
392 dpif_linux_destroy(struct dpif *dpif_)
393 {
394     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
395     struct dpif_linux_dp dp;
396
397     dpif_linux_dp_init(&dp);
398     dp.cmd = OVS_DP_CMD_DEL;
399     dp.dp_ifindex = dpif->dp_ifindex;
400     return dpif_linux_dp_transact(&dp, NULL, NULL);
401 }
402
403 static int
404 dpif_linux_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
405 {
406     struct dpif_linux_dp dp;
407     struct ofpbuf *buf;
408     int error;
409
410     error = dpif_linux_dp_get(dpif_, &dp, &buf);
411     if (!error) {
412         stats->n_hit    = dp.stats.n_hit;
413         stats->n_missed = dp.stats.n_missed;
414         stats->n_lost   = dp.stats.n_lost;
415         stats->n_flows  = dp.stats.n_flows;
416         stats->n_masks  = dp.megaflow_stats.n_masks;
417         stats->n_mask_hit  = dp.megaflow_stats.n_mask_hit;
418         ofpbuf_delete(buf);
419     }
420     return error;
421 }
422
423 static const char *
424 get_vport_type(const struct dpif_linux_vport *vport)
425 {
426     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
427
428     switch (vport->type) {
429     case OVS_VPORT_TYPE_NETDEV:
430         return "system";
431
432     case OVS_VPORT_TYPE_INTERNAL:
433         return "internal";
434
435     case OVS_VPORT_TYPE_GRE:
436         return "gre";
437
438     case OVS_VPORT_TYPE_GRE64:
439         return "gre64";
440
441     case OVS_VPORT_TYPE_VXLAN:
442         return "vxlan";
443
444     case OVS_VPORT_TYPE_LISP:
445         return "lisp";
446
447     case OVS_VPORT_TYPE_UNSPEC:
448     case __OVS_VPORT_TYPE_MAX:
449         break;
450     }
451
452     VLOG_WARN_RL(&rl, "dp%d: port `%s' has unsupported type %u",
453                  vport->dp_ifindex, vport->name, (unsigned int) vport->type);
454     return "unknown";
455 }
456
457 static enum ovs_vport_type
458 netdev_to_ovs_vport_type(const struct netdev *netdev)
459 {
460     const char *type = netdev_get_type(netdev);
461
462     if (!strcmp(type, "tap") || !strcmp(type, "system")) {
463         return OVS_VPORT_TYPE_NETDEV;
464     } else if (!strcmp(type, "internal")) {
465         return OVS_VPORT_TYPE_INTERNAL;
466     } else if (strstr(type, "gre64")) {
467         return OVS_VPORT_TYPE_GRE64;
468     } else if (strstr(type, "gre")) {
469         return OVS_VPORT_TYPE_GRE;
470     } else if (!strcmp(type, "vxlan")) {
471         return OVS_VPORT_TYPE_VXLAN;
472     } else if (!strcmp(type, "lisp")) {
473         return OVS_VPORT_TYPE_LISP;
474     } else {
475         return OVS_VPORT_TYPE_UNSPEC;
476     }
477 }
478
479 static int
480 dpif_linux_port_add__(struct dpif *dpif_, struct netdev *netdev,
481                       odp_port_t *port_nop)
482 {
483     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
484     const struct netdev_tunnel_config *tnl_cfg;
485     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
486     const char *name = netdev_vport_get_dpif_port(netdev,
487                                                   namebuf, sizeof namebuf);
488     const char *type = netdev_get_type(netdev);
489     struct dpif_linux_vport request, reply;
490     struct nl_sock *sock = NULL;
491     uint32_t upcall_pid;
492     struct ofpbuf *buf;
493     uint64_t options_stub[64 / 8];
494     struct ofpbuf options;
495     int error;
496
497     if (dpif->epoll_fd >= 0) {
498         error = nl_sock_create(NETLINK_GENERIC, &sock);
499         if (error) {
500             return error;
501         }
502     }
503
504     dpif_linux_vport_init(&request);
505     request.cmd = OVS_VPORT_CMD_NEW;
506     request.dp_ifindex = dpif->dp_ifindex;
507     request.type = netdev_to_ovs_vport_type(netdev);
508     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
509         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
510                      "unsupported type `%s'",
511                      dpif_name(dpif_), name, type);
512         nl_sock_destroy(sock);
513         return EINVAL;
514     }
515     request.name = name;
516
517     if (request.type == OVS_VPORT_TYPE_NETDEV) {
518         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
519     }
520
521     tnl_cfg = netdev_get_tunnel_config(netdev);
522     if (tnl_cfg && tnl_cfg->dst_port != 0) {
523         ofpbuf_use_stack(&options, options_stub, sizeof options_stub);
524         nl_msg_put_u16(&options, OVS_TUNNEL_ATTR_DST_PORT,
525                        ntohs(tnl_cfg->dst_port));
526         request.options = options.data;
527         request.options_len = options.size;
528     }
529
530     request.port_no = *port_nop;
531     upcall_pid = sock ? nl_sock_pid(sock) : 0;
532     request.upcall_pid = &upcall_pid;
533
534     error = dpif_linux_vport_transact(&request, &reply, &buf);
535     if (!error) {
536         *port_nop = reply.port_no;
537         VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
538                  dpif_name(dpif_), reply.port_no, upcall_pid);
539     } else {
540         if (error == EBUSY && *port_nop != ODPP_NONE) {
541             VLOG_INFO("%s: requested port %"PRIu32" is in use",
542                       dpif_name(dpif_), *port_nop);
543         }
544         nl_sock_destroy(sock);
545         ofpbuf_delete(buf);
546         return error;
547     }
548     ofpbuf_delete(buf);
549
550     if (sock) {
551         error = add_channel(dpif, *port_nop, sock);
552         if (error) {
553             VLOG_INFO("%s: could not add channel for port %s",
554                       dpif_name(dpif_), name);
555
556             /* Delete the port. */
557             dpif_linux_vport_init(&request);
558             request.cmd = OVS_VPORT_CMD_DEL;
559             request.dp_ifindex = dpif->dp_ifindex;
560             request.port_no = *port_nop;
561             dpif_linux_vport_transact(&request, NULL, NULL);
562
563             nl_sock_destroy(sock);
564             return error;
565         }
566     }
567
568     return 0;
569 }
570
571 static int
572 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
573                     odp_port_t *port_nop)
574 {
575     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
576     int error;
577
578     ovs_mutex_lock(&dpif->upcall_lock);
579     error = dpif_linux_port_add__(dpif_, netdev, port_nop);
580     ovs_mutex_unlock(&dpif->upcall_lock);
581
582     return error;
583 }
584
585 static int
586 dpif_linux_port_del__(struct dpif *dpif_, odp_port_t port_no)
587 {
588     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
589     struct dpif_linux_vport vport;
590     int error;
591
592     dpif_linux_vport_init(&vport);
593     vport.cmd = OVS_VPORT_CMD_DEL;
594     vport.dp_ifindex = dpif->dp_ifindex;
595     vport.port_no = port_no;
596     error = dpif_linux_vport_transact(&vport, NULL, NULL);
597
598     del_channel(dpif, port_no);
599
600     return error;
601 }
602
603 static int
604 dpif_linux_port_del(struct dpif *dpif_, odp_port_t port_no)
605 {
606     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
607     int error;
608
609     ovs_mutex_lock(&dpif->upcall_lock);
610     error = dpif_linux_port_del__(dpif_, port_no);
611     ovs_mutex_unlock(&dpif->upcall_lock);
612
613     return error;
614 }
615
616 static int
617 dpif_linux_port_query__(const struct dpif *dpif, odp_port_t port_no,
618                         const char *port_name, struct dpif_port *dpif_port)
619 {
620     struct dpif_linux_vport request;
621     struct dpif_linux_vport reply;
622     struct ofpbuf *buf;
623     int error;
624
625     dpif_linux_vport_init(&request);
626     request.cmd = OVS_VPORT_CMD_GET;
627     request.dp_ifindex = dpif_linux_cast(dpif)->dp_ifindex;
628     request.port_no = port_no;
629     request.name = port_name;
630
631     error = dpif_linux_vport_transact(&request, &reply, &buf);
632     if (!error) {
633         if (reply.dp_ifindex != request.dp_ifindex) {
634             /* A query by name reported that 'port_name' is in some datapath
635              * other than 'dpif', but the caller wants to know about 'dpif'. */
636             error = ENODEV;
637         } else if (dpif_port) {
638             dpif_port->name = xstrdup(reply.name);
639             dpif_port->type = xstrdup(get_vport_type(&reply));
640             dpif_port->port_no = reply.port_no;
641         }
642         ofpbuf_delete(buf);
643     }
644     return error;
645 }
646
647 static int
648 dpif_linux_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
649                                 struct dpif_port *dpif_port)
650 {
651     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
652 }
653
654 static int
655 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
656                               struct dpif_port *dpif_port)
657 {
658     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
659 }
660
661 static uint32_t
662 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
663 {
664     return MAX_PORTS;
665 }
666
667 static uint32_t
668 dpif_linux_port_get_pid(const struct dpif *dpif_, odp_port_t port_no)
669 {
670     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
671     uint32_t port_idx = odp_to_u32(port_no);
672     uint32_t pid = 0;
673
674     ovs_mutex_lock(&dpif->upcall_lock);
675     if (dpif->epoll_fd >= 0) {
676         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
677          * channel, since it is not heavily loaded. */
678         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
679         pid = nl_sock_pid(dpif->channels[idx].sock);
680     }
681     ovs_mutex_unlock(&dpif->upcall_lock);
682
683     return pid;
684 }
685
686 static int
687 dpif_linux_flow_flush(struct dpif *dpif_)
688 {
689     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
690     struct dpif_linux_flow flow;
691
692     dpif_linux_flow_init(&flow);
693     flow.cmd = OVS_FLOW_CMD_DEL;
694     flow.dp_ifindex = dpif->dp_ifindex;
695     return dpif_linux_flow_transact(&flow, NULL, NULL);
696 }
697
698 struct dpif_linux_port_state {
699     struct nl_dump dump;
700 };
701
702 static int
703 dpif_linux_port_dump_start(const struct dpif *dpif_, void **statep)
704 {
705     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
706     struct dpif_linux_port_state *state;
707     struct dpif_linux_vport request;
708     struct ofpbuf *buf;
709
710     *statep = state = xmalloc(sizeof *state);
711
712     dpif_linux_vport_init(&request);
713     request.cmd = OVS_VPORT_CMD_GET;
714     request.dp_ifindex = dpif->dp_ifindex;
715
716     buf = ofpbuf_new(1024);
717     dpif_linux_vport_to_ofpbuf(&request, buf);
718     nl_dump_start(&state->dump, NETLINK_GENERIC, buf);
719     ofpbuf_delete(buf);
720
721     return 0;
722 }
723
724 static int
725 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
726                           struct dpif_port *dpif_port)
727 {
728     struct dpif_linux_port_state *state = state_;
729     struct dpif_linux_vport vport;
730     struct ofpbuf buf;
731     int error;
732
733     if (!nl_dump_next(&state->dump, &buf)) {
734         return EOF;
735     }
736
737     error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
738     if (error) {
739         return error;
740     }
741
742     dpif_port->name = CONST_CAST(char *, vport.name);
743     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
744     dpif_port->port_no = vport.port_no;
745     return 0;
746 }
747
748 static int
749 dpif_linux_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
750 {
751     struct dpif_linux_port_state *state = state_;
752     int error = nl_dump_done(&state->dump);
753
754     free(state);
755     return error;
756 }
757
758 static int
759 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
760 {
761     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
762
763     /* Lazily create the Netlink socket to listen for notifications. */
764     if (!dpif->port_notifier) {
765         struct nl_sock *sock;
766         int error;
767
768         error = nl_sock_create(NETLINK_GENERIC, &sock);
769         if (error) {
770             return error;
771         }
772
773         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
774         if (error) {
775             nl_sock_destroy(sock);
776             return error;
777         }
778         dpif->port_notifier = sock;
779
780         /* We have no idea of the current state so report that everything
781          * changed. */
782         return ENOBUFS;
783     }
784
785     for (;;) {
786         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
787         uint64_t buf_stub[4096 / 8];
788         struct ofpbuf buf;
789         int error;
790
791         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
792         error = nl_sock_recv(dpif->port_notifier, &buf, false);
793         if (!error) {
794             struct dpif_linux_vport vport;
795
796             error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
797             if (!error) {
798                 if (vport.dp_ifindex == dpif->dp_ifindex
799                     && (vport.cmd == OVS_VPORT_CMD_NEW
800                         || vport.cmd == OVS_VPORT_CMD_DEL
801                         || vport.cmd == OVS_VPORT_CMD_SET)) {
802                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
803                              dpif->dpif.full_name, vport.name, vport.cmd);
804                     *devnamep = xstrdup(vport.name);
805                     ofpbuf_uninit(&buf);
806                     return 0;
807                 }
808             }
809         } else if (error != EAGAIN) {
810             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
811                          ovs_strerror(error));
812             nl_sock_drain(dpif->port_notifier);
813             error = ENOBUFS;
814         }
815
816         ofpbuf_uninit(&buf);
817         if (error) {
818             return error;
819         }
820     }
821 }
822
823 static void
824 dpif_linux_port_poll_wait(const struct dpif *dpif_)
825 {
826     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
827
828     if (dpif->port_notifier) {
829         nl_sock_wait(dpif->port_notifier, POLLIN);
830     } else {
831         poll_immediate_wake();
832     }
833 }
834
835 static int
836 dpif_linux_flow_get__(const struct dpif *dpif_,
837                       const struct nlattr *key, size_t key_len,
838                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
839 {
840     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
841     struct dpif_linux_flow request;
842
843     dpif_linux_flow_init(&request);
844     request.cmd = OVS_FLOW_CMD_GET;
845     request.dp_ifindex = dpif->dp_ifindex;
846     request.key = key;
847     request.key_len = key_len;
848     return dpif_linux_flow_transact(&request, reply, bufp);
849 }
850
851 static int
852 dpif_linux_flow_get(const struct dpif *dpif_,
853                     const struct nlattr *key, size_t key_len,
854                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
855 {
856     struct dpif_linux_flow reply;
857     struct ofpbuf *buf;
858     int error;
859
860     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
861     if (!error) {
862         if (stats) {
863             dpif_linux_flow_get_stats(&reply, stats);
864         }
865         if (actionsp) {
866             buf->data = CONST_CAST(struct nlattr *, reply.actions);
867             buf->size = reply.actions_len;
868             *actionsp = buf;
869         } else {
870             ofpbuf_delete(buf);
871         }
872     }
873     return error;
874 }
875
876 static void
877 dpif_linux_init_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put,
878                          struct dpif_linux_flow *request)
879 {
880     static const struct nlattr dummy_action;
881
882     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
883
884     dpif_linux_flow_init(request);
885     request->cmd = (put->flags & DPIF_FP_CREATE
886                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
887     request->dp_ifindex = dpif->dp_ifindex;
888     request->key = put->key;
889     request->key_len = put->key_len;
890     request->mask = put->mask;
891     request->mask_len = put->mask_len;
892     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
893     request->actions = (put->actions
894                         ? put->actions
895                         : CONST_CAST(struct nlattr *, &dummy_action));
896     request->actions_len = put->actions_len;
897     if (put->flags & DPIF_FP_ZERO_STATS) {
898         request->clear = true;
899     }
900     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
901 }
902
903 static int
904 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
905 {
906     struct dpif_linux_flow request, reply;
907     struct ofpbuf *buf;
908     int error;
909
910     dpif_linux_init_flow_put(dpif_, put, &request);
911     error = dpif_linux_flow_transact(&request,
912                                      put->stats ? &reply : NULL,
913                                      put->stats ? &buf : NULL);
914     if (!error && put->stats) {
915         dpif_linux_flow_get_stats(&reply, put->stats);
916         ofpbuf_delete(buf);
917     }
918     return error;
919 }
920
921 static void
922 dpif_linux_init_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del,
923                          struct dpif_linux_flow *request)
924 {
925     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
926
927     dpif_linux_flow_init(request);
928     request->cmd = OVS_FLOW_CMD_DEL;
929     request->dp_ifindex = dpif->dp_ifindex;
930     request->key = del->key;
931     request->key_len = del->key_len;
932 }
933
934 static int
935 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
936 {
937     struct dpif_linux_flow request, reply;
938     struct ofpbuf *buf;
939     int error;
940
941     dpif_linux_init_flow_del(dpif_, del, &request);
942     error = dpif_linux_flow_transact(&request,
943                                      del->stats ? &reply : NULL,
944                                      del->stats ? &buf : NULL);
945     if (!error && del->stats) {
946         dpif_linux_flow_get_stats(&reply, del->stats);
947         ofpbuf_delete(buf);
948     }
949     return error;
950 }
951
952 struct dpif_linux_flow_state {
953     struct nl_dump dump;
954     struct dpif_linux_flow flow;
955     struct dpif_flow_stats stats;
956     struct ofpbuf *buf;
957 };
958
959 static int
960 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
961 {
962     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
963     struct dpif_linux_flow_state *state;
964     struct dpif_linux_flow request;
965     struct ofpbuf *buf;
966
967     *statep = state = xmalloc(sizeof *state);
968
969     dpif_linux_flow_init(&request);
970     request.cmd = OVS_FLOW_CMD_GET;
971     request.dp_ifindex = dpif->dp_ifindex;
972
973     buf = ofpbuf_new(1024);
974     dpif_linux_flow_to_ofpbuf(&request, buf);
975     nl_dump_start(&state->dump, NETLINK_GENERIC, buf);
976     ofpbuf_delete(buf);
977
978     state->buf = NULL;
979
980     return 0;
981 }
982
983 static int
984 dpif_linux_flow_dump_next(const struct dpif *dpif_ OVS_UNUSED, void *state_,
985                           const struct nlattr **key, size_t *key_len,
986                           const struct nlattr **mask, size_t *mask_len,
987                           const struct nlattr **actions, size_t *actions_len,
988                           const struct dpif_flow_stats **stats)
989 {
990     struct dpif_linux_flow_state *state = state_;
991     struct ofpbuf buf;
992     int error;
993
994     do {
995         ofpbuf_delete(state->buf);
996         state->buf = NULL;
997
998         if (!nl_dump_next(&state->dump, &buf)) {
999             return EOF;
1000         }
1001
1002         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
1003         if (error) {
1004             return error;
1005         }
1006
1007         if (actions && !state->flow.actions) {
1008             error = dpif_linux_flow_get__(dpif_, state->flow.key,
1009                                           state->flow.key_len,
1010                                           &state->flow, &state->buf);
1011             if (error == ENOENT) {
1012                 VLOG_DBG("dumped flow disappeared on get");
1013             } else if (error) {
1014                 VLOG_WARN("error fetching dumped flow: %s",
1015                           ovs_strerror(error));
1016             }
1017         }
1018     } while (error);
1019
1020     if (actions) {
1021         *actions = state->flow.actions;
1022         *actions_len = state->flow.actions_len;
1023     }
1024     if (key) {
1025         *key = state->flow.key;
1026         *key_len = state->flow.key_len;
1027     }
1028     if (mask) {
1029         *mask = state->flow.mask;
1030         *mask_len = state->flow.mask ? state->flow.mask_len : 0;
1031     }
1032     if (stats) {
1033         dpif_linux_flow_get_stats(&state->flow, &state->stats);
1034         *stats = &state->stats;
1035     }
1036     return error;
1037 }
1038
1039 static int
1040 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1041 {
1042     struct dpif_linux_flow_state *state = state_;
1043     int error = nl_dump_done(&state->dump);
1044     ofpbuf_delete(state->buf);
1045     free(state);
1046     return error;
1047 }
1048
1049 static void
1050 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1051                           struct ofpbuf *buf)
1052 {
1053     struct ovs_header *k_exec;
1054
1055     ofpbuf_prealloc_tailroom(buf, (64
1056                                    + d_exec->packet->size
1057                                    + d_exec->key_len
1058                                    + d_exec->actions_len));
1059
1060     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1061                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1062
1063     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1064     k_exec->dp_ifindex = dp_ifindex;
1065
1066     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1067                       d_exec->packet->data, d_exec->packet->size);
1068     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_KEY, d_exec->key, d_exec->key_len);
1069     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1070                       d_exec->actions, d_exec->actions_len);
1071 }
1072
1073 static int
1074 dpif_linux_execute__(int dp_ifindex, const struct dpif_execute *execute)
1075 {
1076     uint64_t request_stub[1024 / 8];
1077     struct ofpbuf request;
1078     int error;
1079
1080     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1081     dpif_linux_encode_execute(dp_ifindex, execute, &request);
1082     error = nl_transact(NETLINK_GENERIC, &request, NULL);
1083     ofpbuf_uninit(&request);
1084
1085     return error;
1086 }
1087
1088 static int
1089 dpif_linux_execute(struct dpif *dpif_, const struct dpif_execute *execute)
1090 {
1091     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1092
1093     return dpif_linux_execute__(dpif->dp_ifindex, execute);
1094 }
1095
1096 #define MAX_OPS 50
1097
1098 static void
1099 dpif_linux_operate__(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1100 {
1101     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1102
1103     struct op_auxdata {
1104         struct nl_transaction txn;
1105
1106         struct ofpbuf request;
1107         uint64_t request_stub[1024 / 8];
1108
1109         struct ofpbuf reply;
1110         uint64_t reply_stub[1024 / 8];
1111     } auxes[MAX_OPS];
1112
1113     struct nl_transaction *txnsp[MAX_OPS];
1114     size_t i;
1115
1116     ovs_assert(n_ops <= MAX_OPS);
1117     for (i = 0; i < n_ops; i++) {
1118         struct op_auxdata *aux = &auxes[i];
1119         struct dpif_op *op = ops[i];
1120         struct dpif_flow_put *put;
1121         struct dpif_flow_del *del;
1122         struct dpif_execute *execute;
1123         struct dpif_linux_flow flow;
1124
1125         ofpbuf_use_stub(&aux->request,
1126                         aux->request_stub, sizeof aux->request_stub);
1127         aux->txn.request = &aux->request;
1128
1129         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1130         aux->txn.reply = NULL;
1131
1132         switch (op->type) {
1133         case DPIF_OP_FLOW_PUT:
1134             put = &op->u.flow_put;
1135             dpif_linux_init_flow_put(dpif_, put, &flow);
1136             if (put->stats) {
1137                 flow.nlmsg_flags |= NLM_F_ECHO;
1138                 aux->txn.reply = &aux->reply;
1139             }
1140             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1141             break;
1142
1143         case DPIF_OP_FLOW_DEL:
1144             del = &op->u.flow_del;
1145             dpif_linux_init_flow_del(dpif_, del, &flow);
1146             if (del->stats) {
1147                 flow.nlmsg_flags |= NLM_F_ECHO;
1148                 aux->txn.reply = &aux->reply;
1149             }
1150             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1151             break;
1152
1153         case DPIF_OP_EXECUTE:
1154             execute = &op->u.execute;
1155             dpif_linux_encode_execute(dpif->dp_ifindex, execute,
1156                                       &aux->request);
1157             break;
1158
1159         default:
1160             NOT_REACHED();
1161         }
1162     }
1163
1164     for (i = 0; i < n_ops; i++) {
1165         txnsp[i] = &auxes[i].txn;
1166     }
1167     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1168
1169     for (i = 0; i < n_ops; i++) {
1170         struct op_auxdata *aux = &auxes[i];
1171         struct nl_transaction *txn = &auxes[i].txn;
1172         struct dpif_op *op = ops[i];
1173         struct dpif_flow_put *put;
1174         struct dpif_flow_del *del;
1175
1176         op->error = txn->error;
1177
1178         switch (op->type) {
1179         case DPIF_OP_FLOW_PUT:
1180             put = &op->u.flow_put;
1181             if (put->stats) {
1182                 if (!op->error) {
1183                     struct dpif_linux_flow reply;
1184
1185                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1186                                                             txn->reply);
1187                     if (!op->error) {
1188                         dpif_linux_flow_get_stats(&reply, put->stats);
1189                     }
1190                 }
1191
1192                 if (op->error) {
1193                     memset(put->stats, 0, sizeof *put->stats);
1194                 }
1195             }
1196             break;
1197
1198         case DPIF_OP_FLOW_DEL:
1199             del = &op->u.flow_del;
1200             if (del->stats) {
1201                 if (!op->error) {
1202                     struct dpif_linux_flow reply;
1203
1204                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1205                                                             txn->reply);
1206                     if (!op->error) {
1207                         dpif_linux_flow_get_stats(&reply, del->stats);
1208                     }
1209                 }
1210
1211                 if (op->error) {
1212                     memset(del->stats, 0, sizeof *del->stats);
1213                 }
1214             }
1215             break;
1216
1217         case DPIF_OP_EXECUTE:
1218             break;
1219
1220         default:
1221             NOT_REACHED();
1222         }
1223
1224         ofpbuf_uninit(&aux->request);
1225         ofpbuf_uninit(&aux->reply);
1226     }
1227 }
1228
1229 static void
1230 dpif_linux_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1231 {
1232     while (n_ops > 0) {
1233         size_t chunk = MIN(n_ops, MAX_OPS);
1234         dpif_linux_operate__(dpif, ops, chunk);
1235         ops += chunk;
1236         n_ops -= chunk;
1237     }
1238 }
1239
1240 static int
1241 dpif_linux_recv_set__(struct dpif *dpif_, bool enable)
1242 {
1243     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1244
1245     if ((dpif->epoll_fd >= 0) == enable) {
1246         return 0;
1247     }
1248
1249     if (!enable) {
1250         destroy_channels(dpif);
1251     } else {
1252         struct dpif_port_dump port_dump;
1253         struct dpif_port port;
1254
1255         if (dpif->epoll_fd < 0) {
1256             dpif->epoll_fd = epoll_create(10);
1257             if (dpif->epoll_fd < 0) {
1258                 return errno;
1259             }
1260         }
1261
1262         DPIF_PORT_FOR_EACH (&port, &port_dump, &dpif->dpif) {
1263             struct dpif_linux_vport vport_request;
1264             struct nl_sock *sock;
1265             uint32_t upcall_pid;
1266             int error;
1267
1268             error = nl_sock_create(NETLINK_GENERIC, &sock);
1269             if (error) {
1270                 return error;
1271             }
1272
1273             upcall_pid = nl_sock_pid(sock);
1274
1275             dpif_linux_vport_init(&vport_request);
1276             vport_request.cmd = OVS_VPORT_CMD_SET;
1277             vport_request.dp_ifindex = dpif->dp_ifindex;
1278             vport_request.port_no = port.port_no;
1279             vport_request.upcall_pid = &upcall_pid;
1280             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1281             if (!error) {
1282                 VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
1283                          dpif_name(&dpif->dpif), vport_request.port_no,
1284                          upcall_pid);
1285             } else {
1286                 VLOG_WARN_RL(&error_rl,
1287                              "%s: failed to set upcall pid on port: %s",
1288                              dpif_name(&dpif->dpif), ovs_strerror(error));
1289                 nl_sock_destroy(sock);
1290
1291                 if (error == ENODEV || error == ENOENT) {
1292                     /* This device isn't there, but keep trying the others. */
1293                     continue;
1294                 } else {
1295                     return error;
1296                 }
1297             }
1298
1299             error = add_channel(dpif, port.port_no, sock);
1300             if (error) {
1301                 VLOG_INFO("%s: could not add channel for port %s",
1302                           dpif_name(dpif_), port.name);
1303                 nl_sock_destroy(sock);
1304                 return error;
1305             }
1306         }
1307     }
1308
1309     return 0;
1310 }
1311
1312 static int
1313 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1314 {
1315     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1316     int error;
1317
1318     ovs_mutex_lock(&dpif->upcall_lock);
1319     error = dpif_linux_recv_set__(dpif_, enable);
1320     ovs_mutex_unlock(&dpif->upcall_lock);
1321
1322     return error;
1323 }
1324
1325 static int
1326 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1327                              uint32_t queue_id, uint32_t *priority)
1328 {
1329     if (queue_id < 0xf000) {
1330         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1331         return 0;
1332     } else {
1333         return EINVAL;
1334     }
1335 }
1336
1337 static int
1338 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1339                  int *dp_ifindex)
1340 {
1341     static const struct nl_policy ovs_packet_policy[] = {
1342         /* Always present. */
1343         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1344                                      .min_len = ETH_HEADER_LEN },
1345         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1346
1347         /* OVS_PACKET_CMD_ACTION only. */
1348         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1349     };
1350
1351     struct ovs_header *ovs_header;
1352     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1353     struct nlmsghdr *nlmsg;
1354     struct genlmsghdr *genl;
1355     struct ofpbuf b;
1356     int type;
1357
1358     ofpbuf_use_const(&b, buf->data, buf->size);
1359
1360     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1361     genl = ofpbuf_try_pull(&b, sizeof *genl);
1362     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1363     if (!nlmsg || !genl || !ovs_header
1364         || nlmsg->nlmsg_type != ovs_packet_family
1365         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1366                             ARRAY_SIZE(ovs_packet_policy))) {
1367         return EINVAL;
1368     }
1369
1370     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1371             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1372             : -1);
1373     if (type < 0) {
1374         return EINVAL;
1375     }
1376
1377     memset(upcall, 0, sizeof *upcall);
1378     upcall->type = type;
1379     upcall->packet = buf;
1380     upcall->packet->data = CONST_CAST(struct nlattr *,
1381                                       nl_attr_get(a[OVS_PACKET_ATTR_PACKET]));
1382     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1383     upcall->key = CONST_CAST(struct nlattr *,
1384                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1385     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1386     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1387     *dp_ifindex = ovs_header->dp_ifindex;
1388
1389     return 0;
1390 }
1391
1392 static int
1393 dpif_linux_recv__(struct dpif *dpif_, struct dpif_upcall *upcall,
1394                   struct ofpbuf *buf)
1395 {
1396     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1397     int read_tries = 0;
1398
1399     if (dpif->epoll_fd < 0) {
1400        return EAGAIN;
1401     }
1402
1403     if (dpif->event_offset >= dpif->n_events) {
1404         int retval;
1405
1406         dpif->event_offset = dpif->n_events = 0;
1407
1408         do {
1409             retval = epoll_wait(dpif->epoll_fd, dpif->epoll_events,
1410                                 dpif->uc_array_size, 0);
1411         } while (retval < 0 && errno == EINTR);
1412         if (retval < 0) {
1413             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1414             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
1415         } else if (retval > 0) {
1416             dpif->n_events = retval;
1417         }
1418     }
1419
1420     while (dpif->event_offset < dpif->n_events) {
1421         int idx = dpif->epoll_events[dpif->event_offset].data.u32;
1422         struct dpif_channel *ch = &dpif->channels[idx];
1423
1424         dpif->event_offset++;
1425
1426         for (;;) {
1427             int dp_ifindex;
1428             int error;
1429
1430             if (++read_tries > 50) {
1431                 return EAGAIN;
1432             }
1433
1434             error = nl_sock_recv(ch->sock, buf, false);
1435             if (error == ENOBUFS) {
1436                 /* ENOBUFS typically means that we've received so many
1437                  * packets that the buffer overflowed.  Try again
1438                  * immediately because there's almost certainly a packet
1439                  * waiting for us. */
1440                 report_loss(dpif_, ch);
1441                 continue;
1442             }
1443
1444             ch->last_poll = time_msec();
1445             if (error) {
1446                 if (error == EAGAIN) {
1447                     break;
1448                 }
1449                 return error;
1450             }
1451
1452             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1453             if (!error && dp_ifindex == dpif->dp_ifindex) {
1454                 return 0;
1455             } else if (error) {
1456                 return error;
1457             }
1458         }
1459     }
1460
1461     return EAGAIN;
1462 }
1463
1464 static int
1465 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1466                 struct ofpbuf *buf)
1467 {
1468     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1469     int error;
1470
1471     ovs_mutex_lock(&dpif->upcall_lock);
1472     error = dpif_linux_recv__(dpif_, upcall, buf);
1473     ovs_mutex_unlock(&dpif->upcall_lock);
1474
1475     return error;
1476 }
1477
1478 static void
1479 dpif_linux_recv_wait(struct dpif *dpif_)
1480 {
1481     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1482
1483     ovs_mutex_lock(&dpif->upcall_lock);
1484     if (dpif->epoll_fd >= 0) {
1485         poll_fd_wait(dpif->epoll_fd, POLLIN);
1486     }
1487     ovs_mutex_unlock(&dpif->upcall_lock);
1488 }
1489
1490 static void
1491 dpif_linux_recv_purge(struct dpif *dpif_)
1492 {
1493     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1494
1495     ovs_mutex_lock(&dpif->upcall_lock);
1496     if (dpif->epoll_fd >= 0) {
1497         struct dpif_channel *ch;
1498
1499         for (ch = dpif->channels; ch < &dpif->channels[dpif->uc_array_size];
1500              ch++) {
1501             if (ch->sock) {
1502                 nl_sock_drain(ch->sock);
1503             }
1504         }
1505     }
1506     ovs_mutex_unlock(&dpif->upcall_lock);
1507 }
1508
1509 const struct dpif_class dpif_linux_class = {
1510     "system",
1511     dpif_linux_enumerate,
1512     NULL,
1513     dpif_linux_open,
1514     dpif_linux_close,
1515     dpif_linux_destroy,
1516     NULL,                       /* run */
1517     NULL,                       /* wait */
1518     dpif_linux_get_stats,
1519     dpif_linux_port_add,
1520     dpif_linux_port_del,
1521     dpif_linux_port_query_by_number,
1522     dpif_linux_port_query_by_name,
1523     dpif_linux_get_max_ports,
1524     dpif_linux_port_get_pid,
1525     dpif_linux_port_dump_start,
1526     dpif_linux_port_dump_next,
1527     dpif_linux_port_dump_done,
1528     dpif_linux_port_poll,
1529     dpif_linux_port_poll_wait,
1530     dpif_linux_flow_get,
1531     dpif_linux_flow_put,
1532     dpif_linux_flow_del,
1533     dpif_linux_flow_flush,
1534     dpif_linux_flow_dump_start,
1535     dpif_linux_flow_dump_next,
1536     dpif_linux_flow_dump_done,
1537     dpif_linux_execute,
1538     dpif_linux_operate,
1539     dpif_linux_recv_set,
1540     dpif_linux_queue_to_priority,
1541     dpif_linux_recv,
1542     dpif_linux_recv_wait,
1543     dpif_linux_recv_purge,
1544 };
1545 \f
1546 static int
1547 dpif_linux_init(void)
1548 {
1549     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1550     static int error;
1551
1552     if (ovsthread_once_start(&once)) {
1553         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1554                                       &ovs_datapath_family);
1555         if (error) {
1556             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1557                      "The Open vSwitch kernel module is probably not loaded.",
1558                      OVS_DATAPATH_FAMILY);
1559         }
1560         if (!error) {
1561             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1562         }
1563         if (!error) {
1564             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1565         }
1566         if (!error) {
1567             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1568                                           &ovs_packet_family);
1569         }
1570         if (!error) {
1571             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1572                                            &ovs_vport_mcgroup);
1573         }
1574
1575         ovsthread_once_done(&once);
1576     }
1577
1578     return error;
1579 }
1580
1581 bool
1582 dpif_linux_is_internal_device(const char *name)
1583 {
1584     struct dpif_linux_vport reply;
1585     struct ofpbuf *buf;
1586     int error;
1587
1588     error = dpif_linux_vport_get(name, &reply, &buf);
1589     if (!error) {
1590         ofpbuf_delete(buf);
1591     } else if (error != ENODEV && error != ENOENT) {
1592         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1593                      name, ovs_strerror(error));
1594     }
1595
1596     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1597 }
1598 \f
1599 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1600  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1601  * positive errno value.
1602  *
1603  * 'vport' will contain pointers into 'buf', so the caller should not free
1604  * 'buf' while 'vport' is still in use. */
1605 static int
1606 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1607                              const struct ofpbuf *buf)
1608 {
1609     static const struct nl_policy ovs_vport_policy[] = {
1610         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1611         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1612         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1613         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1614         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1615                                    .optional = true },
1616         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1617     };
1618
1619     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1620     struct ovs_header *ovs_header;
1621     struct nlmsghdr *nlmsg;
1622     struct genlmsghdr *genl;
1623     struct ofpbuf b;
1624
1625     dpif_linux_vport_init(vport);
1626
1627     ofpbuf_use_const(&b, buf->data, buf->size);
1628     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1629     genl = ofpbuf_try_pull(&b, sizeof *genl);
1630     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1631     if (!nlmsg || !genl || !ovs_header
1632         || nlmsg->nlmsg_type != ovs_vport_family
1633         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1634                             ARRAY_SIZE(ovs_vport_policy))) {
1635         return EINVAL;
1636     }
1637
1638     vport->cmd = genl->cmd;
1639     vport->dp_ifindex = ovs_header->dp_ifindex;
1640     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
1641     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1642     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1643     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1644         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1645     }
1646     if (a[OVS_VPORT_ATTR_STATS]) {
1647         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1648     }
1649     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1650         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1651         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1652     }
1653     return 0;
1654 }
1655
1656 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1657  * followed by Netlink attributes corresponding to 'vport'. */
1658 static void
1659 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1660                            struct ofpbuf *buf)
1661 {
1662     struct ovs_header *ovs_header;
1663
1664     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1665                           vport->cmd, OVS_VPORT_VERSION);
1666
1667     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1668     ovs_header->dp_ifindex = vport->dp_ifindex;
1669
1670     if (vport->port_no != ODPP_NONE) {
1671         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1672     }
1673
1674     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1675         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1676     }
1677
1678     if (vport->name) {
1679         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1680     }
1681
1682     if (vport->upcall_pid) {
1683         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1684     }
1685
1686     if (vport->stats) {
1687         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1688                           vport->stats, sizeof *vport->stats);
1689     }
1690
1691     if (vport->options) {
1692         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1693                           vport->options, vport->options_len);
1694     }
1695 }
1696
1697 /* Clears 'vport' to "empty" values. */
1698 void
1699 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1700 {
1701     memset(vport, 0, sizeof *vport);
1702     vport->port_no = ODPP_NONE;
1703 }
1704
1705 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1706  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1707  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1708  * result of the command is expected to be an ovs_vport also, which is decoded
1709  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1710  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1711 int
1712 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1713                           struct dpif_linux_vport *reply,
1714                           struct ofpbuf **bufp)
1715 {
1716     struct ofpbuf *request_buf;
1717     int error;
1718
1719     ovs_assert((reply != NULL) == (bufp != NULL));
1720
1721     error = dpif_linux_init();
1722     if (error) {
1723         if (reply) {
1724             *bufp = NULL;
1725             dpif_linux_vport_init(reply);
1726         }
1727         return error;
1728     }
1729
1730     request_buf = ofpbuf_new(1024);
1731     dpif_linux_vport_to_ofpbuf(request, request_buf);
1732     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1733     ofpbuf_delete(request_buf);
1734
1735     if (reply) {
1736         if (!error) {
1737             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1738         }
1739         if (error) {
1740             dpif_linux_vport_init(reply);
1741             ofpbuf_delete(*bufp);
1742             *bufp = NULL;
1743         }
1744     }
1745     return error;
1746 }
1747
1748 /* Obtains information about the kernel vport named 'name' and stores it into
1749  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1750  * longer needed ('reply' will contain pointers into '*bufp').  */
1751 int
1752 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1753                      struct ofpbuf **bufp)
1754 {
1755     struct dpif_linux_vport request;
1756
1757     dpif_linux_vport_init(&request);
1758     request.cmd = OVS_VPORT_CMD_GET;
1759     request.name = name;
1760
1761     return dpif_linux_vport_transact(&request, reply, bufp);
1762 }
1763 \f
1764 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1765  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1766  * positive errno value.
1767  *
1768  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1769  * while 'dp' is still in use. */
1770 static int
1771 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1772 {
1773     static const struct nl_policy ovs_datapath_policy[] = {
1774         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1775         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1776                                 .optional = true },
1777         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
1778                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
1779                         .optional = true },
1780     };
1781
1782     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1783     struct ovs_header *ovs_header;
1784     struct nlmsghdr *nlmsg;
1785     struct genlmsghdr *genl;
1786     struct ofpbuf b;
1787
1788     dpif_linux_dp_init(dp);
1789
1790     ofpbuf_use_const(&b, buf->data, buf->size);
1791     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1792     genl = ofpbuf_try_pull(&b, sizeof *genl);
1793     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1794     if (!nlmsg || !genl || !ovs_header
1795         || nlmsg->nlmsg_type != ovs_datapath_family
1796         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1797                             ARRAY_SIZE(ovs_datapath_policy))) {
1798         return EINVAL;
1799     }
1800
1801     dp->cmd = genl->cmd;
1802     dp->dp_ifindex = ovs_header->dp_ifindex;
1803     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1804     if (a[OVS_DP_ATTR_STATS]) {
1805         /* Can't use structure assignment because Netlink doesn't ensure
1806          * sufficient alignment for 64-bit members. */
1807         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1808                sizeof dp->stats);
1809     }
1810
1811     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
1812         /* Can't use structure assignment because Netlink doesn't ensure
1813          * sufficient alignment for 64-bit members. */
1814         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
1815                sizeof dp->megaflow_stats);
1816     }
1817
1818     return 0;
1819 }
1820
1821 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1822 static void
1823 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1824 {
1825     struct ovs_header *ovs_header;
1826
1827     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1828                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1829                           OVS_DATAPATH_VERSION);
1830
1831     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1832     ovs_header->dp_ifindex = dp->dp_ifindex;
1833
1834     if (dp->name) {
1835         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1836     }
1837
1838     if (dp->upcall_pid) {
1839         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1840     }
1841
1842     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1843 }
1844
1845 /* Clears 'dp' to "empty" values. */
1846 static void
1847 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1848 {
1849     memset(dp, 0, sizeof *dp);
1850     dp->megaflow_stats.n_masks = UINT32_MAX;
1851     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
1852 }
1853
1854 static void
1855 dpif_linux_dp_dump_start(struct nl_dump *dump)
1856 {
1857     struct dpif_linux_dp request;
1858     struct ofpbuf *buf;
1859
1860     dpif_linux_dp_init(&request);
1861     request.cmd = OVS_DP_CMD_GET;
1862
1863     buf = ofpbuf_new(1024);
1864     dpif_linux_dp_to_ofpbuf(&request, buf);
1865     nl_dump_start(dump, NETLINK_GENERIC, buf);
1866     ofpbuf_delete(buf);
1867 }
1868
1869 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1870  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1871  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1872  * result of the command is expected to be of the same form, which is decoded
1873  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1874  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1875 static int
1876 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1877                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1878 {
1879     struct ofpbuf *request_buf;
1880     int error;
1881
1882     ovs_assert((reply != NULL) == (bufp != NULL));
1883
1884     request_buf = ofpbuf_new(1024);
1885     dpif_linux_dp_to_ofpbuf(request, request_buf);
1886     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1887     ofpbuf_delete(request_buf);
1888
1889     if (reply) {
1890         dpif_linux_dp_init(reply);
1891         if (!error) {
1892             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1893         }
1894         if (error) {
1895             ofpbuf_delete(*bufp);
1896             *bufp = NULL;
1897         }
1898     }
1899     return error;
1900 }
1901
1902 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1903  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1904  * will contain pointers into '*bufp').  */
1905 static int
1906 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1907                   struct ofpbuf **bufp)
1908 {
1909     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1910     struct dpif_linux_dp request;
1911
1912     dpif_linux_dp_init(&request);
1913     request.cmd = OVS_DP_CMD_GET;
1914     request.dp_ifindex = dpif->dp_ifindex;
1915
1916     return dpif_linux_dp_transact(&request, reply, bufp);
1917 }
1918 \f
1919 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1920  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1921  * positive errno value.
1922  *
1923  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1924  * while 'flow' is still in use. */
1925 static int
1926 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1927                             const struct ofpbuf *buf)
1928 {
1929     static const struct nl_policy ovs_flow_policy[] = {
1930         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1931         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
1932         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1933         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1934                                   .optional = true },
1935         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1936         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1937         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1938     };
1939
1940     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1941     struct ovs_header *ovs_header;
1942     struct nlmsghdr *nlmsg;
1943     struct genlmsghdr *genl;
1944     struct ofpbuf b;
1945
1946     dpif_linux_flow_init(flow);
1947
1948     ofpbuf_use_const(&b, buf->data, buf->size);
1949     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1950     genl = ofpbuf_try_pull(&b, sizeof *genl);
1951     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1952     if (!nlmsg || !genl || !ovs_header
1953         || nlmsg->nlmsg_type != ovs_flow_family
1954         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1955                             ARRAY_SIZE(ovs_flow_policy))) {
1956         return EINVAL;
1957     }
1958
1959     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1960     flow->dp_ifindex = ovs_header->dp_ifindex;
1961     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1962     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1963
1964     if (a[OVS_FLOW_ATTR_MASK]) {
1965         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
1966         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
1967     }
1968     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1969         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1970         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1971     }
1972     if (a[OVS_FLOW_ATTR_STATS]) {
1973         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1974     }
1975     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1976         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1977     }
1978     if (a[OVS_FLOW_ATTR_USED]) {
1979         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
1980     }
1981     return 0;
1982 }
1983
1984 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1985  * followed by Netlink attributes corresponding to 'flow'. */
1986 static void
1987 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1988                           struct ofpbuf *buf)
1989 {
1990     struct ovs_header *ovs_header;
1991
1992     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
1993                           NLM_F_REQUEST | flow->nlmsg_flags,
1994                           flow->cmd, OVS_FLOW_VERSION);
1995
1996     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1997     ovs_header->dp_ifindex = flow->dp_ifindex;
1998
1999     if (flow->key_len) {
2000         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2001     }
2002
2003     if (flow->mask_len) {
2004         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2005     }
2006
2007     if (flow->actions || flow->actions_len) {
2008         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2009                           flow->actions, flow->actions_len);
2010     }
2011
2012     /* We never need to send these to the kernel. */
2013     ovs_assert(!flow->stats);
2014     ovs_assert(!flow->tcp_flags);
2015     ovs_assert(!flow->used);
2016
2017     if (flow->clear) {
2018         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2019     }
2020 }
2021
2022 /* Clears 'flow' to "empty" values. */
2023 static void
2024 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2025 {
2026     memset(flow, 0, sizeof *flow);
2027 }
2028
2029 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2030  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2031  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2032  * result of the command is expected to be a flow also, which is decoded and
2033  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2034  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2035 static int
2036 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2037                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2038 {
2039     struct ofpbuf *request_buf;
2040     int error;
2041
2042     ovs_assert((reply != NULL) == (bufp != NULL));
2043
2044     if (reply) {
2045         request->nlmsg_flags |= NLM_F_ECHO;
2046     }
2047
2048     request_buf = ofpbuf_new(1024);
2049     dpif_linux_flow_to_ofpbuf(request, request_buf);
2050     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2051     ofpbuf_delete(request_buf);
2052
2053     if (reply) {
2054         if (!error) {
2055             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2056         }
2057         if (error) {
2058             dpif_linux_flow_init(reply);
2059             ofpbuf_delete(*bufp);
2060             *bufp = NULL;
2061         }
2062     }
2063     return error;
2064 }
2065
2066 static void
2067 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2068                           struct dpif_flow_stats *stats)
2069 {
2070     if (flow->stats) {
2071         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2072         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2073     } else {
2074         stats->n_packets = 0;
2075         stats->n_bytes = 0;
2076     }
2077     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2078     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2079 }
2080 \f
2081 /* Logs information about a packet that was recently lost in 'ch' (in
2082  * 'dpif_'). */
2083 static void
2084 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
2085 {
2086     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2087     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2088     struct ds s;
2089
2090     if (VLOG_DROP_WARN(&rl)) {
2091         return;
2092     }
2093
2094     ds_init(&s);
2095     if (ch->last_poll != LLONG_MIN) {
2096         ds_put_format(&s, " (last polled %lld ms ago)",
2097                       time_msec() - ch->last_poll);
2098     }
2099
2100     VLOG_WARN("%s: lost packet on channel %"PRIdPTR"%s",
2101               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2102     ds_destroy(&s);
2103 }