dpif-linux: Generalize dpif_linux_recv_set() to synchronize channels.
[sliver-openvswitch.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 void
703 dpif_linux_port_dump_start__(const struct dpif *dpif_, struct nl_dump *dump)
704 {
705     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
706     struct dpif_linux_vport request;
707     struct ofpbuf *buf;
708
709     dpif_linux_vport_init(&request);
710     request.cmd = OVS_VPORT_CMD_GET;
711     request.dp_ifindex = dpif->dp_ifindex;
712
713     buf = ofpbuf_new(1024);
714     dpif_linux_vport_to_ofpbuf(&request, buf);
715     nl_dump_start(dump, NETLINK_GENERIC, buf);
716     ofpbuf_delete(buf);
717 }
718
719 static int
720 dpif_linux_port_dump_start(const struct dpif *dpif, void **statep)
721 {
722     struct dpif_linux_port_state *state;
723
724     *statep = state = xmalloc(sizeof *state);
725     dpif_linux_port_dump_start__(dpif, &state->dump);
726
727     return 0;
728 }
729
730 static bool
731 dpif_linux_port_dump_next__(const struct dpif *dpif_, struct nl_dump *dump,
732                             struct dpif_linux_vport *vport)
733 {
734     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
735     struct ofpbuf buf;
736     int error;
737
738     if (!nl_dump_next(dump, &buf)) {
739         return EOF;
740     }
741
742     error = dpif_linux_vport_from_ofpbuf(vport, &buf);
743     if (error) {
744         VLOG_WARN_RL(&error_rl, "%s: failed to parse vport record (%s)",
745                      dpif_name(&dpif->dpif), ovs_strerror(error));
746     }
747     return error;
748 }
749
750 static int
751 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
752                           struct dpif_port *dpif_port)
753 {
754     struct dpif_linux_port_state *state = state_;
755     struct dpif_linux_vport vport;
756     int error;
757
758     error = dpif_linux_port_dump_next__(dpif, &state->dump, &vport);
759     if (error) {
760         return error;
761     }
762     dpif_port->name = CONST_CAST(char *, vport.name);
763     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
764     dpif_port->port_no = vport.port_no;
765     return 0;
766 }
767
768 static int
769 dpif_linux_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
770 {
771     struct dpif_linux_port_state *state = state_;
772     int error = nl_dump_done(&state->dump);
773
774     free(state);
775     return error;
776 }
777
778 static int
779 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
780 {
781     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
782
783     /* Lazily create the Netlink socket to listen for notifications. */
784     if (!dpif->port_notifier) {
785         struct nl_sock *sock;
786         int error;
787
788         error = nl_sock_create(NETLINK_GENERIC, &sock);
789         if (error) {
790             return error;
791         }
792
793         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
794         if (error) {
795             nl_sock_destroy(sock);
796             return error;
797         }
798         dpif->port_notifier = sock;
799
800         /* We have no idea of the current state so report that everything
801          * changed. */
802         return ENOBUFS;
803     }
804
805     for (;;) {
806         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
807         uint64_t buf_stub[4096 / 8];
808         struct ofpbuf buf;
809         int error;
810
811         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
812         error = nl_sock_recv(dpif->port_notifier, &buf, false);
813         if (!error) {
814             struct dpif_linux_vport vport;
815
816             error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
817             if (!error) {
818                 if (vport.dp_ifindex == dpif->dp_ifindex
819                     && (vport.cmd == OVS_VPORT_CMD_NEW
820                         || vport.cmd == OVS_VPORT_CMD_DEL
821                         || vport.cmd == OVS_VPORT_CMD_SET)) {
822                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
823                              dpif->dpif.full_name, vport.name, vport.cmd);
824                     *devnamep = xstrdup(vport.name);
825                     ofpbuf_uninit(&buf);
826                     return 0;
827                 }
828             }
829         } else if (error != EAGAIN) {
830             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
831                          ovs_strerror(error));
832             nl_sock_drain(dpif->port_notifier);
833             error = ENOBUFS;
834         }
835
836         ofpbuf_uninit(&buf);
837         if (error) {
838             return error;
839         }
840     }
841 }
842
843 static void
844 dpif_linux_port_poll_wait(const struct dpif *dpif_)
845 {
846     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
847
848     if (dpif->port_notifier) {
849         nl_sock_wait(dpif->port_notifier, POLLIN);
850     } else {
851         poll_immediate_wake();
852     }
853 }
854
855 static int
856 dpif_linux_flow_get__(const struct dpif *dpif_,
857                       const struct nlattr *key, size_t key_len,
858                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
859 {
860     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
861     struct dpif_linux_flow request;
862
863     dpif_linux_flow_init(&request);
864     request.cmd = OVS_FLOW_CMD_GET;
865     request.dp_ifindex = dpif->dp_ifindex;
866     request.key = key;
867     request.key_len = key_len;
868     return dpif_linux_flow_transact(&request, reply, bufp);
869 }
870
871 static int
872 dpif_linux_flow_get(const struct dpif *dpif_,
873                     const struct nlattr *key, size_t key_len,
874                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
875 {
876     struct dpif_linux_flow reply;
877     struct ofpbuf *buf;
878     int error;
879
880     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
881     if (!error) {
882         if (stats) {
883             dpif_linux_flow_get_stats(&reply, stats);
884         }
885         if (actionsp) {
886             buf->data = CONST_CAST(struct nlattr *, reply.actions);
887             buf->size = reply.actions_len;
888             *actionsp = buf;
889         } else {
890             ofpbuf_delete(buf);
891         }
892     }
893     return error;
894 }
895
896 static void
897 dpif_linux_init_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put,
898                          struct dpif_linux_flow *request)
899 {
900     static const struct nlattr dummy_action;
901
902     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
903
904     dpif_linux_flow_init(request);
905     request->cmd = (put->flags & DPIF_FP_CREATE
906                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
907     request->dp_ifindex = dpif->dp_ifindex;
908     request->key = put->key;
909     request->key_len = put->key_len;
910     request->mask = put->mask;
911     request->mask_len = put->mask_len;
912     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
913     request->actions = (put->actions
914                         ? put->actions
915                         : CONST_CAST(struct nlattr *, &dummy_action));
916     request->actions_len = put->actions_len;
917     if (put->flags & DPIF_FP_ZERO_STATS) {
918         request->clear = true;
919     }
920     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
921 }
922
923 static int
924 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
925 {
926     struct dpif_linux_flow request, reply;
927     struct ofpbuf *buf;
928     int error;
929
930     dpif_linux_init_flow_put(dpif_, put, &request);
931     error = dpif_linux_flow_transact(&request,
932                                      put->stats ? &reply : NULL,
933                                      put->stats ? &buf : NULL);
934     if (!error && put->stats) {
935         dpif_linux_flow_get_stats(&reply, put->stats);
936         ofpbuf_delete(buf);
937     }
938     return error;
939 }
940
941 static void
942 dpif_linux_init_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del,
943                          struct dpif_linux_flow *request)
944 {
945     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
946
947     dpif_linux_flow_init(request);
948     request->cmd = OVS_FLOW_CMD_DEL;
949     request->dp_ifindex = dpif->dp_ifindex;
950     request->key = del->key;
951     request->key_len = del->key_len;
952 }
953
954 static int
955 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
956 {
957     struct dpif_linux_flow request, reply;
958     struct ofpbuf *buf;
959     int error;
960
961     dpif_linux_init_flow_del(dpif_, del, &request);
962     error = dpif_linux_flow_transact(&request,
963                                      del->stats ? &reply : NULL,
964                                      del->stats ? &buf : NULL);
965     if (!error && del->stats) {
966         dpif_linux_flow_get_stats(&reply, del->stats);
967         ofpbuf_delete(buf);
968     }
969     return error;
970 }
971
972 struct dpif_linux_flow_state {
973     struct nl_dump dump;
974     struct dpif_linux_flow flow;
975     struct dpif_flow_stats stats;
976     struct ofpbuf *buf;
977 };
978
979 static int
980 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
981 {
982     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
983     struct dpif_linux_flow_state *state;
984     struct dpif_linux_flow request;
985     struct ofpbuf *buf;
986
987     *statep = state = xmalloc(sizeof *state);
988
989     dpif_linux_flow_init(&request);
990     request.cmd = OVS_FLOW_CMD_GET;
991     request.dp_ifindex = dpif->dp_ifindex;
992
993     buf = ofpbuf_new(1024);
994     dpif_linux_flow_to_ofpbuf(&request, buf);
995     nl_dump_start(&state->dump, NETLINK_GENERIC, buf);
996     ofpbuf_delete(buf);
997
998     state->buf = NULL;
999
1000     return 0;
1001 }
1002
1003 static int
1004 dpif_linux_flow_dump_next(const struct dpif *dpif_ OVS_UNUSED, void *state_,
1005                           const struct nlattr **key, size_t *key_len,
1006                           const struct nlattr **mask, size_t *mask_len,
1007                           const struct nlattr **actions, size_t *actions_len,
1008                           const struct dpif_flow_stats **stats)
1009 {
1010     struct dpif_linux_flow_state *state = state_;
1011     struct ofpbuf buf;
1012     int error;
1013
1014     do {
1015         ofpbuf_delete(state->buf);
1016         state->buf = NULL;
1017
1018         if (!nl_dump_next(&state->dump, &buf)) {
1019             return EOF;
1020         }
1021
1022         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
1023         if (error) {
1024             return error;
1025         }
1026
1027         if (actions && !state->flow.actions) {
1028             error = dpif_linux_flow_get__(dpif_, state->flow.key,
1029                                           state->flow.key_len,
1030                                           &state->flow, &state->buf);
1031             if (error == ENOENT) {
1032                 VLOG_DBG("dumped flow disappeared on get");
1033             } else if (error) {
1034                 VLOG_WARN("error fetching dumped flow: %s",
1035                           ovs_strerror(error));
1036             }
1037         }
1038     } while (error);
1039
1040     if (actions) {
1041         *actions = state->flow.actions;
1042         *actions_len = state->flow.actions_len;
1043     }
1044     if (key) {
1045         *key = state->flow.key;
1046         *key_len = state->flow.key_len;
1047     }
1048     if (mask) {
1049         *mask = state->flow.mask;
1050         *mask_len = state->flow.mask ? state->flow.mask_len : 0;
1051     }
1052     if (stats) {
1053         dpif_linux_flow_get_stats(&state->flow, &state->stats);
1054         *stats = &state->stats;
1055     }
1056     return error;
1057 }
1058
1059 static int
1060 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1061 {
1062     struct dpif_linux_flow_state *state = state_;
1063     int error = nl_dump_done(&state->dump);
1064     ofpbuf_delete(state->buf);
1065     free(state);
1066     return error;
1067 }
1068
1069 static void
1070 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1071                           struct ofpbuf *buf)
1072 {
1073     struct ovs_header *k_exec;
1074
1075     ofpbuf_prealloc_tailroom(buf, (64
1076                                    + d_exec->packet->size
1077                                    + d_exec->key_len
1078                                    + d_exec->actions_len));
1079
1080     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1081                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1082
1083     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1084     k_exec->dp_ifindex = dp_ifindex;
1085
1086     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1087                       d_exec->packet->data, d_exec->packet->size);
1088     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_KEY, d_exec->key, d_exec->key_len);
1089     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1090                       d_exec->actions, d_exec->actions_len);
1091 }
1092
1093 static int
1094 dpif_linux_execute__(int dp_ifindex, const struct dpif_execute *execute)
1095 {
1096     uint64_t request_stub[1024 / 8];
1097     struct ofpbuf request;
1098     int error;
1099
1100     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1101     dpif_linux_encode_execute(dp_ifindex, execute, &request);
1102     error = nl_transact(NETLINK_GENERIC, &request, NULL);
1103     ofpbuf_uninit(&request);
1104
1105     return error;
1106 }
1107
1108 static int
1109 dpif_linux_execute(struct dpif *dpif_, const struct dpif_execute *execute)
1110 {
1111     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1112
1113     return dpif_linux_execute__(dpif->dp_ifindex, execute);
1114 }
1115
1116 #define MAX_OPS 50
1117
1118 static void
1119 dpif_linux_operate__(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1120 {
1121     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1122
1123     struct op_auxdata {
1124         struct nl_transaction txn;
1125
1126         struct ofpbuf request;
1127         uint64_t request_stub[1024 / 8];
1128
1129         struct ofpbuf reply;
1130         uint64_t reply_stub[1024 / 8];
1131     } auxes[MAX_OPS];
1132
1133     struct nl_transaction *txnsp[MAX_OPS];
1134     size_t i;
1135
1136     ovs_assert(n_ops <= MAX_OPS);
1137     for (i = 0; i < n_ops; i++) {
1138         struct op_auxdata *aux = &auxes[i];
1139         struct dpif_op *op = ops[i];
1140         struct dpif_flow_put *put;
1141         struct dpif_flow_del *del;
1142         struct dpif_execute *execute;
1143         struct dpif_linux_flow flow;
1144
1145         ofpbuf_use_stub(&aux->request,
1146                         aux->request_stub, sizeof aux->request_stub);
1147         aux->txn.request = &aux->request;
1148
1149         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1150         aux->txn.reply = NULL;
1151
1152         switch (op->type) {
1153         case DPIF_OP_FLOW_PUT:
1154             put = &op->u.flow_put;
1155             dpif_linux_init_flow_put(dpif_, put, &flow);
1156             if (put->stats) {
1157                 flow.nlmsg_flags |= NLM_F_ECHO;
1158                 aux->txn.reply = &aux->reply;
1159             }
1160             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1161             break;
1162
1163         case DPIF_OP_FLOW_DEL:
1164             del = &op->u.flow_del;
1165             dpif_linux_init_flow_del(dpif_, del, &flow);
1166             if (del->stats) {
1167                 flow.nlmsg_flags |= NLM_F_ECHO;
1168                 aux->txn.reply = &aux->reply;
1169             }
1170             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1171             break;
1172
1173         case DPIF_OP_EXECUTE:
1174             execute = &op->u.execute;
1175             dpif_linux_encode_execute(dpif->dp_ifindex, execute,
1176                                       &aux->request);
1177             break;
1178
1179         default:
1180             NOT_REACHED();
1181         }
1182     }
1183
1184     for (i = 0; i < n_ops; i++) {
1185         txnsp[i] = &auxes[i].txn;
1186     }
1187     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1188
1189     for (i = 0; i < n_ops; i++) {
1190         struct op_auxdata *aux = &auxes[i];
1191         struct nl_transaction *txn = &auxes[i].txn;
1192         struct dpif_op *op = ops[i];
1193         struct dpif_flow_put *put;
1194         struct dpif_flow_del *del;
1195
1196         op->error = txn->error;
1197
1198         switch (op->type) {
1199         case DPIF_OP_FLOW_PUT:
1200             put = &op->u.flow_put;
1201             if (put->stats) {
1202                 if (!op->error) {
1203                     struct dpif_linux_flow reply;
1204
1205                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1206                                                             txn->reply);
1207                     if (!op->error) {
1208                         dpif_linux_flow_get_stats(&reply, put->stats);
1209                     }
1210                 }
1211
1212                 if (op->error) {
1213                     memset(put->stats, 0, sizeof *put->stats);
1214                 }
1215             }
1216             break;
1217
1218         case DPIF_OP_FLOW_DEL:
1219             del = &op->u.flow_del;
1220             if (del->stats) {
1221                 if (!op->error) {
1222                     struct dpif_linux_flow reply;
1223
1224                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1225                                                             txn->reply);
1226                     if (!op->error) {
1227                         dpif_linux_flow_get_stats(&reply, del->stats);
1228                     }
1229                 }
1230
1231                 if (op->error) {
1232                     memset(del->stats, 0, sizeof *del->stats);
1233                 }
1234             }
1235             break;
1236
1237         case DPIF_OP_EXECUTE:
1238             break;
1239
1240         default:
1241             NOT_REACHED();
1242         }
1243
1244         ofpbuf_uninit(&aux->request);
1245         ofpbuf_uninit(&aux->reply);
1246     }
1247 }
1248
1249 static void
1250 dpif_linux_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1251 {
1252     while (n_ops > 0) {
1253         size_t chunk = MIN(n_ops, MAX_OPS);
1254         dpif_linux_operate__(dpif, ops, chunk);
1255         ops += chunk;
1256         n_ops -= chunk;
1257     }
1258 }
1259
1260 /* Synchronizes 'dpif->channels' with the set of vports currently in 'dpif' in
1261  * the kernel, by adding a new channel for any kernel vport that lacks one and
1262  * deleting any channels that have no backing kernel vports. */
1263 static int
1264 dpif_linux_refresh_channels(struct dpif *dpif_)
1265 {
1266     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1267     unsigned long int *keep_channels;
1268     struct dpif_linux_vport vport;
1269     size_t keep_channels_nbits;
1270     struct nl_dump dump;
1271     int retval = 0;
1272     size_t i;
1273
1274     /* To start with, we need an epoll fd. */
1275     if (dpif->epoll_fd < 0) {
1276         dpif->epoll_fd = epoll_create(10);
1277         if (dpif->epoll_fd < 0) {
1278             return errno;
1279         }
1280     }
1281
1282     keep_channels_nbits = dpif->uc_array_size;
1283     keep_channels = bitmap_allocate(keep_channels_nbits);
1284
1285     dpif->n_events = dpif->event_offset = 0;
1286
1287     dpif_linux_port_dump_start__(dpif_, &dump);
1288     while (dpif_linux_port_dump_next__(dpif_, &dump, &vport)) {
1289         uint32_t port_no = odp_to_u32(vport.port_no);
1290         struct nl_sock *sock = (port_no < dpif->uc_array_size
1291                                 ? dpif->channels[port_no].sock
1292                                 : NULL);
1293         bool new_sock = !sock;
1294         int error;
1295
1296         if (new_sock) {
1297             error = nl_sock_create(NETLINK_GENERIC, &sock);
1298             if (error) {
1299                 retval = error;
1300                 goto error;
1301             }
1302         }
1303
1304         /* Configure the vport to deliver misses to 'sock'. */
1305         if (!vport.upcall_pid || *vport.upcall_pid != nl_sock_pid(sock)) {
1306             uint32_t upcall_pid = nl_sock_pid(sock);
1307             struct dpif_linux_vport vport_request;
1308
1309             dpif_linux_vport_init(&vport_request);
1310             vport_request.cmd = OVS_VPORT_CMD_SET;
1311             vport_request.dp_ifindex = dpif->dp_ifindex;
1312             vport_request.port_no = vport.port_no;
1313             vport_request.upcall_pid = &upcall_pid;
1314             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1315             if (!error) {
1316                 VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
1317                          dpif_name(&dpif->dpif), vport_request.port_no,
1318                          upcall_pid);
1319             } else {
1320                 VLOG_WARN_RL(&error_rl,
1321                              "%s: failed to set upcall pid on port: %s",
1322                              dpif_name(&dpif->dpif), ovs_strerror(error));
1323
1324                 if (error != ENODEV && error != ENOENT) {
1325                     retval = error;
1326                 } else {
1327                     /* The vport isn't really there, even though the dump says
1328                      * it is.  Probably we just hit a race after a port
1329                      * disappeared. */
1330                 }
1331                 goto error;
1332             }
1333         }
1334
1335         if (new_sock) {
1336             error = add_channel(dpif, vport.port_no, sock);
1337             if (error) {
1338                 VLOG_INFO("%s: could not add channel for port %s",
1339                           dpif_name(dpif_), vport.name);
1340                 retval = error;
1341                 goto error;
1342             }
1343         }
1344
1345         if (port_no < keep_channels_nbits) {
1346             bitmap_set1(keep_channels, port_no);
1347         }
1348         continue;
1349
1350     error:
1351         nl_sock_destroy(sock);
1352     }
1353     nl_dump_done(&dump);
1354
1355     /* Discard any saved channels that we didn't reuse. */
1356     for (i = 0; i < keep_channels_nbits; i++) {
1357         if (!bitmap_is_set(keep_channels, i)) {
1358             nl_sock_destroy(dpif->channels[i].sock);
1359             dpif->channels[i].sock = NULL;
1360         }
1361     }
1362     free(keep_channels);
1363
1364     return retval;
1365 }
1366
1367 static int
1368 dpif_linux_recv_set__(struct dpif *dpif_, bool enable)
1369 {
1370     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1371
1372     if ((dpif->epoll_fd >= 0) == enable) {
1373         return 0;
1374     } else if (!enable) {
1375         destroy_channels(dpif);
1376         return 0;
1377     } else {
1378         return dpif_linux_refresh_channels(dpif_);
1379     }
1380 }
1381
1382 static int
1383 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1384 {
1385     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1386     int error;
1387
1388     ovs_mutex_lock(&dpif->upcall_lock);
1389     error = dpif_linux_recv_set__(dpif_, enable);
1390     ovs_mutex_unlock(&dpif->upcall_lock);
1391
1392     return error;
1393 }
1394
1395 static int
1396 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1397                              uint32_t queue_id, uint32_t *priority)
1398 {
1399     if (queue_id < 0xf000) {
1400         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1401         return 0;
1402     } else {
1403         return EINVAL;
1404     }
1405 }
1406
1407 static int
1408 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1409                  int *dp_ifindex)
1410 {
1411     static const struct nl_policy ovs_packet_policy[] = {
1412         /* Always present. */
1413         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1414                                      .min_len = ETH_HEADER_LEN },
1415         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1416
1417         /* OVS_PACKET_CMD_ACTION only. */
1418         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1419     };
1420
1421     struct ovs_header *ovs_header;
1422     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1423     struct nlmsghdr *nlmsg;
1424     struct genlmsghdr *genl;
1425     struct ofpbuf b;
1426     int type;
1427
1428     ofpbuf_use_const(&b, buf->data, buf->size);
1429
1430     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1431     genl = ofpbuf_try_pull(&b, sizeof *genl);
1432     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1433     if (!nlmsg || !genl || !ovs_header
1434         || nlmsg->nlmsg_type != ovs_packet_family
1435         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1436                             ARRAY_SIZE(ovs_packet_policy))) {
1437         return EINVAL;
1438     }
1439
1440     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1441             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1442             : -1);
1443     if (type < 0) {
1444         return EINVAL;
1445     }
1446
1447     memset(upcall, 0, sizeof *upcall);
1448     upcall->type = type;
1449     upcall->packet = buf;
1450     upcall->packet->data = CONST_CAST(struct nlattr *,
1451                                       nl_attr_get(a[OVS_PACKET_ATTR_PACKET]));
1452     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1453     upcall->key = CONST_CAST(struct nlattr *,
1454                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1455     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1456     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1457     *dp_ifindex = ovs_header->dp_ifindex;
1458
1459     return 0;
1460 }
1461
1462 static int
1463 dpif_linux_recv__(struct dpif *dpif_, struct dpif_upcall *upcall,
1464                   struct ofpbuf *buf)
1465 {
1466     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1467     int read_tries = 0;
1468
1469     if (dpif->epoll_fd < 0) {
1470        return EAGAIN;
1471     }
1472
1473     if (dpif->event_offset >= dpif->n_events) {
1474         int retval;
1475
1476         dpif->event_offset = dpif->n_events = 0;
1477
1478         do {
1479             retval = epoll_wait(dpif->epoll_fd, dpif->epoll_events,
1480                                 dpif->uc_array_size, 0);
1481         } while (retval < 0 && errno == EINTR);
1482         if (retval < 0) {
1483             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1484             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
1485         } else if (retval > 0) {
1486             dpif->n_events = retval;
1487         }
1488     }
1489
1490     while (dpif->event_offset < dpif->n_events) {
1491         int idx = dpif->epoll_events[dpif->event_offset].data.u32;
1492         struct dpif_channel *ch = &dpif->channels[idx];
1493
1494         dpif->event_offset++;
1495
1496         for (;;) {
1497             int dp_ifindex;
1498             int error;
1499
1500             if (++read_tries > 50) {
1501                 return EAGAIN;
1502             }
1503
1504             error = nl_sock_recv(ch->sock, buf, false);
1505             if (error == ENOBUFS) {
1506                 /* ENOBUFS typically means that we've received so many
1507                  * packets that the buffer overflowed.  Try again
1508                  * immediately because there's almost certainly a packet
1509                  * waiting for us. */
1510                 report_loss(dpif_, ch);
1511                 continue;
1512             }
1513
1514             ch->last_poll = time_msec();
1515             if (error) {
1516                 if (error == EAGAIN) {
1517                     break;
1518                 }
1519                 return error;
1520             }
1521
1522             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1523             if (!error && dp_ifindex == dpif->dp_ifindex) {
1524                 return 0;
1525             } else if (error) {
1526                 return error;
1527             }
1528         }
1529     }
1530
1531     return EAGAIN;
1532 }
1533
1534 static int
1535 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1536                 struct ofpbuf *buf)
1537 {
1538     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1539     int error;
1540
1541     ovs_mutex_lock(&dpif->upcall_lock);
1542     error = dpif_linux_recv__(dpif_, upcall, buf);
1543     ovs_mutex_unlock(&dpif->upcall_lock);
1544
1545     return error;
1546 }
1547
1548 static void
1549 dpif_linux_recv_wait(struct dpif *dpif_)
1550 {
1551     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1552
1553     ovs_mutex_lock(&dpif->upcall_lock);
1554     if (dpif->epoll_fd >= 0) {
1555         poll_fd_wait(dpif->epoll_fd, POLLIN);
1556     }
1557     ovs_mutex_unlock(&dpif->upcall_lock);
1558 }
1559
1560 static void
1561 dpif_linux_recv_purge(struct dpif *dpif_)
1562 {
1563     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1564
1565     ovs_mutex_lock(&dpif->upcall_lock);
1566     if (dpif->epoll_fd >= 0) {
1567         struct dpif_channel *ch;
1568
1569         for (ch = dpif->channels; ch < &dpif->channels[dpif->uc_array_size];
1570              ch++) {
1571             if (ch->sock) {
1572                 nl_sock_drain(ch->sock);
1573             }
1574         }
1575     }
1576     ovs_mutex_unlock(&dpif->upcall_lock);
1577 }
1578
1579 const struct dpif_class dpif_linux_class = {
1580     "system",
1581     dpif_linux_enumerate,
1582     NULL,
1583     dpif_linux_open,
1584     dpif_linux_close,
1585     dpif_linux_destroy,
1586     NULL,                       /* run */
1587     NULL,                       /* wait */
1588     dpif_linux_get_stats,
1589     dpif_linux_port_add,
1590     dpif_linux_port_del,
1591     dpif_linux_port_query_by_number,
1592     dpif_linux_port_query_by_name,
1593     dpif_linux_get_max_ports,
1594     dpif_linux_port_get_pid,
1595     dpif_linux_port_dump_start,
1596     dpif_linux_port_dump_next,
1597     dpif_linux_port_dump_done,
1598     dpif_linux_port_poll,
1599     dpif_linux_port_poll_wait,
1600     dpif_linux_flow_get,
1601     dpif_linux_flow_put,
1602     dpif_linux_flow_del,
1603     dpif_linux_flow_flush,
1604     dpif_linux_flow_dump_start,
1605     dpif_linux_flow_dump_next,
1606     dpif_linux_flow_dump_done,
1607     dpif_linux_execute,
1608     dpif_linux_operate,
1609     dpif_linux_recv_set,
1610     dpif_linux_queue_to_priority,
1611     dpif_linux_recv,
1612     dpif_linux_recv_wait,
1613     dpif_linux_recv_purge,
1614 };
1615 \f
1616 static int
1617 dpif_linux_init(void)
1618 {
1619     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1620     static int error;
1621
1622     if (ovsthread_once_start(&once)) {
1623         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1624                                       &ovs_datapath_family);
1625         if (error) {
1626             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1627                      "The Open vSwitch kernel module is probably not loaded.",
1628                      OVS_DATAPATH_FAMILY);
1629         }
1630         if (!error) {
1631             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1632         }
1633         if (!error) {
1634             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1635         }
1636         if (!error) {
1637             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1638                                           &ovs_packet_family);
1639         }
1640         if (!error) {
1641             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1642                                            &ovs_vport_mcgroup);
1643         }
1644
1645         ovsthread_once_done(&once);
1646     }
1647
1648     return error;
1649 }
1650
1651 bool
1652 dpif_linux_is_internal_device(const char *name)
1653 {
1654     struct dpif_linux_vport reply;
1655     struct ofpbuf *buf;
1656     int error;
1657
1658     error = dpif_linux_vport_get(name, &reply, &buf);
1659     if (!error) {
1660         ofpbuf_delete(buf);
1661     } else if (error != ENODEV && error != ENOENT) {
1662         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1663                      name, ovs_strerror(error));
1664     }
1665
1666     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1667 }
1668 \f
1669 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1670  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1671  * positive errno value.
1672  *
1673  * 'vport' will contain pointers into 'buf', so the caller should not free
1674  * 'buf' while 'vport' is still in use. */
1675 static int
1676 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1677                              const struct ofpbuf *buf)
1678 {
1679     static const struct nl_policy ovs_vport_policy[] = {
1680         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1681         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1682         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1683         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1684         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1685                                    .optional = true },
1686         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1687     };
1688
1689     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1690     struct ovs_header *ovs_header;
1691     struct nlmsghdr *nlmsg;
1692     struct genlmsghdr *genl;
1693     struct ofpbuf b;
1694
1695     dpif_linux_vport_init(vport);
1696
1697     ofpbuf_use_const(&b, buf->data, buf->size);
1698     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1699     genl = ofpbuf_try_pull(&b, sizeof *genl);
1700     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1701     if (!nlmsg || !genl || !ovs_header
1702         || nlmsg->nlmsg_type != ovs_vport_family
1703         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1704                             ARRAY_SIZE(ovs_vport_policy))) {
1705         return EINVAL;
1706     }
1707
1708     vport->cmd = genl->cmd;
1709     vport->dp_ifindex = ovs_header->dp_ifindex;
1710     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
1711     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1712     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1713     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1714         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1715     }
1716     if (a[OVS_VPORT_ATTR_STATS]) {
1717         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1718     }
1719     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1720         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1721         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1722     }
1723     return 0;
1724 }
1725
1726 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1727  * followed by Netlink attributes corresponding to 'vport'. */
1728 static void
1729 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1730                            struct ofpbuf *buf)
1731 {
1732     struct ovs_header *ovs_header;
1733
1734     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1735                           vport->cmd, OVS_VPORT_VERSION);
1736
1737     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1738     ovs_header->dp_ifindex = vport->dp_ifindex;
1739
1740     if (vport->port_no != ODPP_NONE) {
1741         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1742     }
1743
1744     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1745         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1746     }
1747
1748     if (vport->name) {
1749         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1750     }
1751
1752     if (vport->upcall_pid) {
1753         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1754     }
1755
1756     if (vport->stats) {
1757         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1758                           vport->stats, sizeof *vport->stats);
1759     }
1760
1761     if (vport->options) {
1762         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1763                           vport->options, vport->options_len);
1764     }
1765 }
1766
1767 /* Clears 'vport' to "empty" values. */
1768 void
1769 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1770 {
1771     memset(vport, 0, sizeof *vport);
1772     vport->port_no = ODPP_NONE;
1773 }
1774
1775 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1776  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1777  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1778  * result of the command is expected to be an ovs_vport also, which is decoded
1779  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1780  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1781 int
1782 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1783                           struct dpif_linux_vport *reply,
1784                           struct ofpbuf **bufp)
1785 {
1786     struct ofpbuf *request_buf;
1787     int error;
1788
1789     ovs_assert((reply != NULL) == (bufp != NULL));
1790
1791     error = dpif_linux_init();
1792     if (error) {
1793         if (reply) {
1794             *bufp = NULL;
1795             dpif_linux_vport_init(reply);
1796         }
1797         return error;
1798     }
1799
1800     request_buf = ofpbuf_new(1024);
1801     dpif_linux_vport_to_ofpbuf(request, request_buf);
1802     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1803     ofpbuf_delete(request_buf);
1804
1805     if (reply) {
1806         if (!error) {
1807             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1808         }
1809         if (error) {
1810             dpif_linux_vport_init(reply);
1811             ofpbuf_delete(*bufp);
1812             *bufp = NULL;
1813         }
1814     }
1815     return error;
1816 }
1817
1818 /* Obtains information about the kernel vport named 'name' and stores it into
1819  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1820  * longer needed ('reply' will contain pointers into '*bufp').  */
1821 int
1822 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1823                      struct ofpbuf **bufp)
1824 {
1825     struct dpif_linux_vport request;
1826
1827     dpif_linux_vport_init(&request);
1828     request.cmd = OVS_VPORT_CMD_GET;
1829     request.name = name;
1830
1831     return dpif_linux_vport_transact(&request, reply, bufp);
1832 }
1833 \f
1834 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1835  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1836  * positive errno value.
1837  *
1838  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1839  * while 'dp' is still in use. */
1840 static int
1841 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1842 {
1843     static const struct nl_policy ovs_datapath_policy[] = {
1844         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1845         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1846                                 .optional = true },
1847         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
1848                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
1849                         .optional = true },
1850     };
1851
1852     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1853     struct ovs_header *ovs_header;
1854     struct nlmsghdr *nlmsg;
1855     struct genlmsghdr *genl;
1856     struct ofpbuf b;
1857
1858     dpif_linux_dp_init(dp);
1859
1860     ofpbuf_use_const(&b, buf->data, buf->size);
1861     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1862     genl = ofpbuf_try_pull(&b, sizeof *genl);
1863     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1864     if (!nlmsg || !genl || !ovs_header
1865         || nlmsg->nlmsg_type != ovs_datapath_family
1866         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1867                             ARRAY_SIZE(ovs_datapath_policy))) {
1868         return EINVAL;
1869     }
1870
1871     dp->cmd = genl->cmd;
1872     dp->dp_ifindex = ovs_header->dp_ifindex;
1873     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1874     if (a[OVS_DP_ATTR_STATS]) {
1875         /* Can't use structure assignment because Netlink doesn't ensure
1876          * sufficient alignment for 64-bit members. */
1877         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1878                sizeof dp->stats);
1879     }
1880
1881     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
1882         /* Can't use structure assignment because Netlink doesn't ensure
1883          * sufficient alignment for 64-bit members. */
1884         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
1885                sizeof dp->megaflow_stats);
1886     }
1887
1888     return 0;
1889 }
1890
1891 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1892 static void
1893 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1894 {
1895     struct ovs_header *ovs_header;
1896
1897     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1898                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1899                           OVS_DATAPATH_VERSION);
1900
1901     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1902     ovs_header->dp_ifindex = dp->dp_ifindex;
1903
1904     if (dp->name) {
1905         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1906     }
1907
1908     if (dp->upcall_pid) {
1909         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1910     }
1911
1912     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1913 }
1914
1915 /* Clears 'dp' to "empty" values. */
1916 static void
1917 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1918 {
1919     memset(dp, 0, sizeof *dp);
1920     dp->megaflow_stats.n_masks = UINT32_MAX;
1921     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
1922 }
1923
1924 static void
1925 dpif_linux_dp_dump_start(struct nl_dump *dump)
1926 {
1927     struct dpif_linux_dp request;
1928     struct ofpbuf *buf;
1929
1930     dpif_linux_dp_init(&request);
1931     request.cmd = OVS_DP_CMD_GET;
1932
1933     buf = ofpbuf_new(1024);
1934     dpif_linux_dp_to_ofpbuf(&request, buf);
1935     nl_dump_start(dump, NETLINK_GENERIC, buf);
1936     ofpbuf_delete(buf);
1937 }
1938
1939 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1940  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1941  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1942  * result of the command is expected to be of the same form, which is decoded
1943  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1944  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1945 static int
1946 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1947                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1948 {
1949     struct ofpbuf *request_buf;
1950     int error;
1951
1952     ovs_assert((reply != NULL) == (bufp != NULL));
1953
1954     request_buf = ofpbuf_new(1024);
1955     dpif_linux_dp_to_ofpbuf(request, request_buf);
1956     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1957     ofpbuf_delete(request_buf);
1958
1959     if (reply) {
1960         dpif_linux_dp_init(reply);
1961         if (!error) {
1962             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1963         }
1964         if (error) {
1965             ofpbuf_delete(*bufp);
1966             *bufp = NULL;
1967         }
1968     }
1969     return error;
1970 }
1971
1972 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1973  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1974  * will contain pointers into '*bufp').  */
1975 static int
1976 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1977                   struct ofpbuf **bufp)
1978 {
1979     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1980     struct dpif_linux_dp request;
1981
1982     dpif_linux_dp_init(&request);
1983     request.cmd = OVS_DP_CMD_GET;
1984     request.dp_ifindex = dpif->dp_ifindex;
1985
1986     return dpif_linux_dp_transact(&request, reply, bufp);
1987 }
1988 \f
1989 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1990  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1991  * positive errno value.
1992  *
1993  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1994  * while 'flow' is still in use. */
1995 static int
1996 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1997                             const struct ofpbuf *buf)
1998 {
1999     static const struct nl_policy ovs_flow_policy[] = {
2000         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
2001         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2002         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2003         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2004                                   .optional = true },
2005         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2006         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2007         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2008     };
2009
2010     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2011     struct ovs_header *ovs_header;
2012     struct nlmsghdr *nlmsg;
2013     struct genlmsghdr *genl;
2014     struct ofpbuf b;
2015
2016     dpif_linux_flow_init(flow);
2017
2018     ofpbuf_use_const(&b, buf->data, buf->size);
2019     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2020     genl = ofpbuf_try_pull(&b, sizeof *genl);
2021     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2022     if (!nlmsg || !genl || !ovs_header
2023         || nlmsg->nlmsg_type != ovs_flow_family
2024         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2025                             ARRAY_SIZE(ovs_flow_policy))) {
2026         return EINVAL;
2027     }
2028
2029     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2030     flow->dp_ifindex = ovs_header->dp_ifindex;
2031     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2032     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2033
2034     if (a[OVS_FLOW_ATTR_MASK]) {
2035         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2036         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2037     }
2038     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2039         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2040         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2041     }
2042     if (a[OVS_FLOW_ATTR_STATS]) {
2043         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2044     }
2045     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2046         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2047     }
2048     if (a[OVS_FLOW_ATTR_USED]) {
2049         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2050     }
2051     return 0;
2052 }
2053
2054 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2055  * followed by Netlink attributes corresponding to 'flow'. */
2056 static void
2057 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
2058                           struct ofpbuf *buf)
2059 {
2060     struct ovs_header *ovs_header;
2061
2062     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2063                           NLM_F_REQUEST | flow->nlmsg_flags,
2064                           flow->cmd, OVS_FLOW_VERSION);
2065
2066     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2067     ovs_header->dp_ifindex = flow->dp_ifindex;
2068
2069     if (flow->key_len) {
2070         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2071     }
2072
2073     if (flow->mask_len) {
2074         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2075     }
2076
2077     if (flow->actions || flow->actions_len) {
2078         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2079                           flow->actions, flow->actions_len);
2080     }
2081
2082     /* We never need to send these to the kernel. */
2083     ovs_assert(!flow->stats);
2084     ovs_assert(!flow->tcp_flags);
2085     ovs_assert(!flow->used);
2086
2087     if (flow->clear) {
2088         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2089     }
2090 }
2091
2092 /* Clears 'flow' to "empty" values. */
2093 static void
2094 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2095 {
2096     memset(flow, 0, sizeof *flow);
2097 }
2098
2099 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2100  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2101  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2102  * result of the command is expected to be a flow also, which is decoded and
2103  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2104  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2105 static int
2106 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2107                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2108 {
2109     struct ofpbuf *request_buf;
2110     int error;
2111
2112     ovs_assert((reply != NULL) == (bufp != NULL));
2113
2114     if (reply) {
2115         request->nlmsg_flags |= NLM_F_ECHO;
2116     }
2117
2118     request_buf = ofpbuf_new(1024);
2119     dpif_linux_flow_to_ofpbuf(request, request_buf);
2120     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2121     ofpbuf_delete(request_buf);
2122
2123     if (reply) {
2124         if (!error) {
2125             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2126         }
2127         if (error) {
2128             dpif_linux_flow_init(reply);
2129             ofpbuf_delete(*bufp);
2130             *bufp = NULL;
2131         }
2132     }
2133     return error;
2134 }
2135
2136 static void
2137 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2138                           struct dpif_flow_stats *stats)
2139 {
2140     if (flow->stats) {
2141         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2142         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2143     } else {
2144         stats->n_packets = 0;
2145         stats->n_bytes = 0;
2146     }
2147     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2148     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2149 }
2150 \f
2151 /* Logs information about a packet that was recently lost in 'ch' (in
2152  * 'dpif_'). */
2153 static void
2154 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
2155 {
2156     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2157     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2158     struct ds s;
2159
2160     if (VLOG_DROP_WARN(&rl)) {
2161         return;
2162     }
2163
2164     ds_init(&s);
2165     if (ch->last_poll != LLONG_MIN) {
2166         ds_put_format(&s, " (last polled %lld ms ago)",
2167                       time_msec() - ch->last_poll);
2168     }
2169
2170     VLOG_WARN("%s: lost packet on channel %"PRIdPTR"%s",
2171               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2172     ds_destroy(&s);
2173 }