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