dpif-linux: Factor out port dumping helper functions.
[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 static int
1261 dpif_linux_recv_set__(struct dpif *dpif_, bool enable)
1262 {
1263     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1264
1265     if ((dpif->epoll_fd >= 0) == enable) {
1266         return 0;
1267     }
1268
1269     if (!enable) {
1270         destroy_channels(dpif);
1271     } else {
1272         struct dpif_port_dump port_dump;
1273         struct dpif_port port;
1274
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         DPIF_PORT_FOR_EACH (&port, &port_dump, &dpif->dpif) {
1283             struct dpif_linux_vport vport_request;
1284             struct nl_sock *sock;
1285             uint32_t upcall_pid;
1286             int error;
1287
1288             error = nl_sock_create(NETLINK_GENERIC, &sock);
1289             if (error) {
1290                 return error;
1291             }
1292
1293             upcall_pid = nl_sock_pid(sock);
1294
1295             dpif_linux_vport_init(&vport_request);
1296             vport_request.cmd = OVS_VPORT_CMD_SET;
1297             vport_request.dp_ifindex = dpif->dp_ifindex;
1298             vport_request.port_no = port.port_no;
1299             vport_request.upcall_pid = &upcall_pid;
1300             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1301             if (!error) {
1302                 VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
1303                          dpif_name(&dpif->dpif), vport_request.port_no,
1304                          upcall_pid);
1305             } else {
1306                 VLOG_WARN_RL(&error_rl,
1307                              "%s: failed to set upcall pid on port: %s",
1308                              dpif_name(&dpif->dpif), ovs_strerror(error));
1309                 nl_sock_destroy(sock);
1310
1311                 if (error == ENODEV || error == ENOENT) {
1312                     /* This device isn't there, but keep trying the others. */
1313                     continue;
1314                 } else {
1315                     return error;
1316                 }
1317             }
1318
1319             error = add_channel(dpif, port.port_no, sock);
1320             if (error) {
1321                 VLOG_INFO("%s: could not add channel for port %s",
1322                           dpif_name(dpif_), port.name);
1323                 nl_sock_destroy(sock);
1324                 return error;
1325             }
1326         }
1327     }
1328
1329     return 0;
1330 }
1331
1332 static int
1333 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1334 {
1335     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1336     int error;
1337
1338     ovs_mutex_lock(&dpif->upcall_lock);
1339     error = dpif_linux_recv_set__(dpif_, enable);
1340     ovs_mutex_unlock(&dpif->upcall_lock);
1341
1342     return error;
1343 }
1344
1345 static int
1346 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1347                              uint32_t queue_id, uint32_t *priority)
1348 {
1349     if (queue_id < 0xf000) {
1350         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1351         return 0;
1352     } else {
1353         return EINVAL;
1354     }
1355 }
1356
1357 static int
1358 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1359                  int *dp_ifindex)
1360 {
1361     static const struct nl_policy ovs_packet_policy[] = {
1362         /* Always present. */
1363         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1364                                      .min_len = ETH_HEADER_LEN },
1365         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1366
1367         /* OVS_PACKET_CMD_ACTION only. */
1368         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1369     };
1370
1371     struct ovs_header *ovs_header;
1372     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1373     struct nlmsghdr *nlmsg;
1374     struct genlmsghdr *genl;
1375     struct ofpbuf b;
1376     int type;
1377
1378     ofpbuf_use_const(&b, buf->data, buf->size);
1379
1380     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1381     genl = ofpbuf_try_pull(&b, sizeof *genl);
1382     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1383     if (!nlmsg || !genl || !ovs_header
1384         || nlmsg->nlmsg_type != ovs_packet_family
1385         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1386                             ARRAY_SIZE(ovs_packet_policy))) {
1387         return EINVAL;
1388     }
1389
1390     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1391             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1392             : -1);
1393     if (type < 0) {
1394         return EINVAL;
1395     }
1396
1397     memset(upcall, 0, sizeof *upcall);
1398     upcall->type = type;
1399     upcall->packet = buf;
1400     upcall->packet->data = CONST_CAST(struct nlattr *,
1401                                       nl_attr_get(a[OVS_PACKET_ATTR_PACKET]));
1402     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1403     upcall->key = CONST_CAST(struct nlattr *,
1404                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1405     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1406     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1407     *dp_ifindex = ovs_header->dp_ifindex;
1408
1409     return 0;
1410 }
1411
1412 static int
1413 dpif_linux_recv__(struct dpif *dpif_, struct dpif_upcall *upcall,
1414                   struct ofpbuf *buf)
1415 {
1416     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1417     int read_tries = 0;
1418
1419     if (dpif->epoll_fd < 0) {
1420        return EAGAIN;
1421     }
1422
1423     if (dpif->event_offset >= dpif->n_events) {
1424         int retval;
1425
1426         dpif->event_offset = dpif->n_events = 0;
1427
1428         do {
1429             retval = epoll_wait(dpif->epoll_fd, dpif->epoll_events,
1430                                 dpif->uc_array_size, 0);
1431         } while (retval < 0 && errno == EINTR);
1432         if (retval < 0) {
1433             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1434             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
1435         } else if (retval > 0) {
1436             dpif->n_events = retval;
1437         }
1438     }
1439
1440     while (dpif->event_offset < dpif->n_events) {
1441         int idx = dpif->epoll_events[dpif->event_offset].data.u32;
1442         struct dpif_channel *ch = &dpif->channels[idx];
1443
1444         dpif->event_offset++;
1445
1446         for (;;) {
1447             int dp_ifindex;
1448             int error;
1449
1450             if (++read_tries > 50) {
1451                 return EAGAIN;
1452             }
1453
1454             error = nl_sock_recv(ch->sock, buf, false);
1455             if (error == ENOBUFS) {
1456                 /* ENOBUFS typically means that we've received so many
1457                  * packets that the buffer overflowed.  Try again
1458                  * immediately because there's almost certainly a packet
1459                  * waiting for us. */
1460                 report_loss(dpif_, ch);
1461                 continue;
1462             }
1463
1464             ch->last_poll = time_msec();
1465             if (error) {
1466                 if (error == EAGAIN) {
1467                     break;
1468                 }
1469                 return error;
1470             }
1471
1472             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1473             if (!error && dp_ifindex == dpif->dp_ifindex) {
1474                 return 0;
1475             } else if (error) {
1476                 return error;
1477             }
1478         }
1479     }
1480
1481     return EAGAIN;
1482 }
1483
1484 static int
1485 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1486                 struct ofpbuf *buf)
1487 {
1488     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1489     int error;
1490
1491     ovs_mutex_lock(&dpif->upcall_lock);
1492     error = dpif_linux_recv__(dpif_, upcall, buf);
1493     ovs_mutex_unlock(&dpif->upcall_lock);
1494
1495     return error;
1496 }
1497
1498 static void
1499 dpif_linux_recv_wait(struct dpif *dpif_)
1500 {
1501     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1502
1503     ovs_mutex_lock(&dpif->upcall_lock);
1504     if (dpif->epoll_fd >= 0) {
1505         poll_fd_wait(dpif->epoll_fd, POLLIN);
1506     }
1507     ovs_mutex_unlock(&dpif->upcall_lock);
1508 }
1509
1510 static void
1511 dpif_linux_recv_purge(struct dpif *dpif_)
1512 {
1513     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1514
1515     ovs_mutex_lock(&dpif->upcall_lock);
1516     if (dpif->epoll_fd >= 0) {
1517         struct dpif_channel *ch;
1518
1519         for (ch = dpif->channels; ch < &dpif->channels[dpif->uc_array_size];
1520              ch++) {
1521             if (ch->sock) {
1522                 nl_sock_drain(ch->sock);
1523             }
1524         }
1525     }
1526     ovs_mutex_unlock(&dpif->upcall_lock);
1527 }
1528
1529 const struct dpif_class dpif_linux_class = {
1530     "system",
1531     dpif_linux_enumerate,
1532     NULL,
1533     dpif_linux_open,
1534     dpif_linux_close,
1535     dpif_linux_destroy,
1536     NULL,                       /* run */
1537     NULL,                       /* wait */
1538     dpif_linux_get_stats,
1539     dpif_linux_port_add,
1540     dpif_linux_port_del,
1541     dpif_linux_port_query_by_number,
1542     dpif_linux_port_query_by_name,
1543     dpif_linux_get_max_ports,
1544     dpif_linux_port_get_pid,
1545     dpif_linux_port_dump_start,
1546     dpif_linux_port_dump_next,
1547     dpif_linux_port_dump_done,
1548     dpif_linux_port_poll,
1549     dpif_linux_port_poll_wait,
1550     dpif_linux_flow_get,
1551     dpif_linux_flow_put,
1552     dpif_linux_flow_del,
1553     dpif_linux_flow_flush,
1554     dpif_linux_flow_dump_start,
1555     dpif_linux_flow_dump_next,
1556     dpif_linux_flow_dump_done,
1557     dpif_linux_execute,
1558     dpif_linux_operate,
1559     dpif_linux_recv_set,
1560     dpif_linux_queue_to_priority,
1561     dpif_linux_recv,
1562     dpif_linux_recv_wait,
1563     dpif_linux_recv_purge,
1564 };
1565 \f
1566 static int
1567 dpif_linux_init(void)
1568 {
1569     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1570     static int error;
1571
1572     if (ovsthread_once_start(&once)) {
1573         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1574                                       &ovs_datapath_family);
1575         if (error) {
1576             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1577                      "The Open vSwitch kernel module is probably not loaded.",
1578                      OVS_DATAPATH_FAMILY);
1579         }
1580         if (!error) {
1581             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1582         }
1583         if (!error) {
1584             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1585         }
1586         if (!error) {
1587             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1588                                           &ovs_packet_family);
1589         }
1590         if (!error) {
1591             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1592                                            &ovs_vport_mcgroup);
1593         }
1594
1595         ovsthread_once_done(&once);
1596     }
1597
1598     return error;
1599 }
1600
1601 bool
1602 dpif_linux_is_internal_device(const char *name)
1603 {
1604     struct dpif_linux_vport reply;
1605     struct ofpbuf *buf;
1606     int error;
1607
1608     error = dpif_linux_vport_get(name, &reply, &buf);
1609     if (!error) {
1610         ofpbuf_delete(buf);
1611     } else if (error != ENODEV && error != ENOENT) {
1612         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1613                      name, ovs_strerror(error));
1614     }
1615
1616     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1617 }
1618 \f
1619 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1620  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1621  * positive errno value.
1622  *
1623  * 'vport' will contain pointers into 'buf', so the caller should not free
1624  * 'buf' while 'vport' is still in use. */
1625 static int
1626 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1627                              const struct ofpbuf *buf)
1628 {
1629     static const struct nl_policy ovs_vport_policy[] = {
1630         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1631         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1632         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1633         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1634         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1635                                    .optional = true },
1636         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1637     };
1638
1639     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1640     struct ovs_header *ovs_header;
1641     struct nlmsghdr *nlmsg;
1642     struct genlmsghdr *genl;
1643     struct ofpbuf b;
1644
1645     dpif_linux_vport_init(vport);
1646
1647     ofpbuf_use_const(&b, buf->data, buf->size);
1648     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1649     genl = ofpbuf_try_pull(&b, sizeof *genl);
1650     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1651     if (!nlmsg || !genl || !ovs_header
1652         || nlmsg->nlmsg_type != ovs_vport_family
1653         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1654                             ARRAY_SIZE(ovs_vport_policy))) {
1655         return EINVAL;
1656     }
1657
1658     vport->cmd = genl->cmd;
1659     vport->dp_ifindex = ovs_header->dp_ifindex;
1660     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
1661     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1662     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1663     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1664         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1665     }
1666     if (a[OVS_VPORT_ATTR_STATS]) {
1667         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1668     }
1669     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1670         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1671         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1672     }
1673     return 0;
1674 }
1675
1676 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1677  * followed by Netlink attributes corresponding to 'vport'. */
1678 static void
1679 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1680                            struct ofpbuf *buf)
1681 {
1682     struct ovs_header *ovs_header;
1683
1684     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1685                           vport->cmd, OVS_VPORT_VERSION);
1686
1687     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1688     ovs_header->dp_ifindex = vport->dp_ifindex;
1689
1690     if (vport->port_no != ODPP_NONE) {
1691         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1692     }
1693
1694     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1695         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1696     }
1697
1698     if (vport->name) {
1699         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1700     }
1701
1702     if (vport->upcall_pid) {
1703         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1704     }
1705
1706     if (vport->stats) {
1707         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1708                           vport->stats, sizeof *vport->stats);
1709     }
1710
1711     if (vport->options) {
1712         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1713                           vport->options, vport->options_len);
1714     }
1715 }
1716
1717 /* Clears 'vport' to "empty" values. */
1718 void
1719 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1720 {
1721     memset(vport, 0, sizeof *vport);
1722     vport->port_no = ODPP_NONE;
1723 }
1724
1725 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1726  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1727  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1728  * result of the command is expected to be an ovs_vport also, which is decoded
1729  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1730  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1731 int
1732 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1733                           struct dpif_linux_vport *reply,
1734                           struct ofpbuf **bufp)
1735 {
1736     struct ofpbuf *request_buf;
1737     int error;
1738
1739     ovs_assert((reply != NULL) == (bufp != NULL));
1740
1741     error = dpif_linux_init();
1742     if (error) {
1743         if (reply) {
1744             *bufp = NULL;
1745             dpif_linux_vport_init(reply);
1746         }
1747         return error;
1748     }
1749
1750     request_buf = ofpbuf_new(1024);
1751     dpif_linux_vport_to_ofpbuf(request, request_buf);
1752     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1753     ofpbuf_delete(request_buf);
1754
1755     if (reply) {
1756         if (!error) {
1757             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1758         }
1759         if (error) {
1760             dpif_linux_vport_init(reply);
1761             ofpbuf_delete(*bufp);
1762             *bufp = NULL;
1763         }
1764     }
1765     return error;
1766 }
1767
1768 /* Obtains information about the kernel vport named 'name' and stores it into
1769  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1770  * longer needed ('reply' will contain pointers into '*bufp').  */
1771 int
1772 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1773                      struct ofpbuf **bufp)
1774 {
1775     struct dpif_linux_vport request;
1776
1777     dpif_linux_vport_init(&request);
1778     request.cmd = OVS_VPORT_CMD_GET;
1779     request.name = name;
1780
1781     return dpif_linux_vport_transact(&request, reply, bufp);
1782 }
1783 \f
1784 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1785  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1786  * positive errno value.
1787  *
1788  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1789  * while 'dp' is still in use. */
1790 static int
1791 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1792 {
1793     static const struct nl_policy ovs_datapath_policy[] = {
1794         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1795         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1796                                 .optional = true },
1797         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
1798                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
1799                         .optional = true },
1800     };
1801
1802     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1803     struct ovs_header *ovs_header;
1804     struct nlmsghdr *nlmsg;
1805     struct genlmsghdr *genl;
1806     struct ofpbuf b;
1807
1808     dpif_linux_dp_init(dp);
1809
1810     ofpbuf_use_const(&b, buf->data, buf->size);
1811     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1812     genl = ofpbuf_try_pull(&b, sizeof *genl);
1813     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1814     if (!nlmsg || !genl || !ovs_header
1815         || nlmsg->nlmsg_type != ovs_datapath_family
1816         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1817                             ARRAY_SIZE(ovs_datapath_policy))) {
1818         return EINVAL;
1819     }
1820
1821     dp->cmd = genl->cmd;
1822     dp->dp_ifindex = ovs_header->dp_ifindex;
1823     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1824     if (a[OVS_DP_ATTR_STATS]) {
1825         /* Can't use structure assignment because Netlink doesn't ensure
1826          * sufficient alignment for 64-bit members. */
1827         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1828                sizeof dp->stats);
1829     }
1830
1831     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
1832         /* Can't use structure assignment because Netlink doesn't ensure
1833          * sufficient alignment for 64-bit members. */
1834         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
1835                sizeof dp->megaflow_stats);
1836     }
1837
1838     return 0;
1839 }
1840
1841 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1842 static void
1843 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1844 {
1845     struct ovs_header *ovs_header;
1846
1847     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1848                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1849                           OVS_DATAPATH_VERSION);
1850
1851     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1852     ovs_header->dp_ifindex = dp->dp_ifindex;
1853
1854     if (dp->name) {
1855         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1856     }
1857
1858     if (dp->upcall_pid) {
1859         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1860     }
1861
1862     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1863 }
1864
1865 /* Clears 'dp' to "empty" values. */
1866 static void
1867 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1868 {
1869     memset(dp, 0, sizeof *dp);
1870     dp->megaflow_stats.n_masks = UINT32_MAX;
1871     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
1872 }
1873
1874 static void
1875 dpif_linux_dp_dump_start(struct nl_dump *dump)
1876 {
1877     struct dpif_linux_dp request;
1878     struct ofpbuf *buf;
1879
1880     dpif_linux_dp_init(&request);
1881     request.cmd = OVS_DP_CMD_GET;
1882
1883     buf = ofpbuf_new(1024);
1884     dpif_linux_dp_to_ofpbuf(&request, buf);
1885     nl_dump_start(dump, NETLINK_GENERIC, buf);
1886     ofpbuf_delete(buf);
1887 }
1888
1889 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1890  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1891  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1892  * result of the command is expected to be of the same form, which is decoded
1893  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1894  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1895 static int
1896 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1897                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1898 {
1899     struct ofpbuf *request_buf;
1900     int error;
1901
1902     ovs_assert((reply != NULL) == (bufp != NULL));
1903
1904     request_buf = ofpbuf_new(1024);
1905     dpif_linux_dp_to_ofpbuf(request, request_buf);
1906     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1907     ofpbuf_delete(request_buf);
1908
1909     if (reply) {
1910         dpif_linux_dp_init(reply);
1911         if (!error) {
1912             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1913         }
1914         if (error) {
1915             ofpbuf_delete(*bufp);
1916             *bufp = NULL;
1917         }
1918     }
1919     return error;
1920 }
1921
1922 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1923  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1924  * will contain pointers into '*bufp').  */
1925 static int
1926 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1927                   struct ofpbuf **bufp)
1928 {
1929     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1930     struct dpif_linux_dp request;
1931
1932     dpif_linux_dp_init(&request);
1933     request.cmd = OVS_DP_CMD_GET;
1934     request.dp_ifindex = dpif->dp_ifindex;
1935
1936     return dpif_linux_dp_transact(&request, reply, bufp);
1937 }
1938 \f
1939 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1940  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1941  * positive errno value.
1942  *
1943  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1944  * while 'flow' is still in use. */
1945 static int
1946 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1947                             const struct ofpbuf *buf)
1948 {
1949     static const struct nl_policy ovs_flow_policy[] = {
1950         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1951         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
1952         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1953         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1954                                   .optional = true },
1955         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1956         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1957         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1958     };
1959
1960     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1961     struct ovs_header *ovs_header;
1962     struct nlmsghdr *nlmsg;
1963     struct genlmsghdr *genl;
1964     struct ofpbuf b;
1965
1966     dpif_linux_flow_init(flow);
1967
1968     ofpbuf_use_const(&b, buf->data, buf->size);
1969     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1970     genl = ofpbuf_try_pull(&b, sizeof *genl);
1971     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1972     if (!nlmsg || !genl || !ovs_header
1973         || nlmsg->nlmsg_type != ovs_flow_family
1974         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1975                             ARRAY_SIZE(ovs_flow_policy))) {
1976         return EINVAL;
1977     }
1978
1979     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1980     flow->dp_ifindex = ovs_header->dp_ifindex;
1981     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1982     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1983
1984     if (a[OVS_FLOW_ATTR_MASK]) {
1985         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
1986         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
1987     }
1988     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1989         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1990         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1991     }
1992     if (a[OVS_FLOW_ATTR_STATS]) {
1993         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1994     }
1995     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1996         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1997     }
1998     if (a[OVS_FLOW_ATTR_USED]) {
1999         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2000     }
2001     return 0;
2002 }
2003
2004 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2005  * followed by Netlink attributes corresponding to 'flow'. */
2006 static void
2007 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
2008                           struct ofpbuf *buf)
2009 {
2010     struct ovs_header *ovs_header;
2011
2012     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2013                           NLM_F_REQUEST | flow->nlmsg_flags,
2014                           flow->cmd, OVS_FLOW_VERSION);
2015
2016     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2017     ovs_header->dp_ifindex = flow->dp_ifindex;
2018
2019     if (flow->key_len) {
2020         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2021     }
2022
2023     if (flow->mask_len) {
2024         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2025     }
2026
2027     if (flow->actions || flow->actions_len) {
2028         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2029                           flow->actions, flow->actions_len);
2030     }
2031
2032     /* We never need to send these to the kernel. */
2033     ovs_assert(!flow->stats);
2034     ovs_assert(!flow->tcp_flags);
2035     ovs_assert(!flow->used);
2036
2037     if (flow->clear) {
2038         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2039     }
2040 }
2041
2042 /* Clears 'flow' to "empty" values. */
2043 static void
2044 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2045 {
2046     memset(flow, 0, sizeof *flow);
2047 }
2048
2049 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2050  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2051  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2052  * result of the command is expected to be a flow also, which is decoded and
2053  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2054  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2055 static int
2056 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2057                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2058 {
2059     struct ofpbuf *request_buf;
2060     int error;
2061
2062     ovs_assert((reply != NULL) == (bufp != NULL));
2063
2064     if (reply) {
2065         request->nlmsg_flags |= NLM_F_ECHO;
2066     }
2067
2068     request_buf = ofpbuf_new(1024);
2069     dpif_linux_flow_to_ofpbuf(request, request_buf);
2070     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2071     ofpbuf_delete(request_buf);
2072
2073     if (reply) {
2074         if (!error) {
2075             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2076         }
2077         if (error) {
2078             dpif_linux_flow_init(reply);
2079             ofpbuf_delete(*bufp);
2080             *bufp = NULL;
2081         }
2082     }
2083     return error;
2084 }
2085
2086 static void
2087 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2088                           struct dpif_flow_stats *stats)
2089 {
2090     if (flow->stats) {
2091         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2092         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2093     } else {
2094         stats->n_packets = 0;
2095         stats->n_bytes = 0;
2096     }
2097     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2098     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2099 }
2100 \f
2101 /* Logs information about a packet that was recently lost in 'ch' (in
2102  * 'dpif_'). */
2103 static void
2104 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
2105 {
2106     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2107     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2108     struct ds s;
2109
2110     if (VLOG_DROP_WARN(&rl)) {
2111         return;
2112     }
2113
2114     ds_init(&s);
2115     if (ch->last_poll != LLONG_MIN) {
2116         ds_put_format(&s, " (last polled %lld ms ago)",
2117                       time_msec() - ch->last_poll);
2118     }
2119
2120     VLOG_WARN("%s: lost packet on channel %"PRIdPTR"%s",
2121               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2122     ds_destroy(&s);
2123 }