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