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