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