dpif-linux: remove useless includes
[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 <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     struct ofpbuf msg;
194     int error;
195
196     error = dpif_linux_init();
197     if (error) {
198         return error;
199     }
200
201     dpif_linux_dp_dump_start(&dump);
202     while (nl_dump_next(&dump, &msg)) {
203         struct dpif_linux_dp dp;
204
205         if (!dpif_linux_dp_from_ofpbuf(&dp, &msg)) {
206             sset_add(all_dps, dp.name);
207         }
208     }
209     return nl_dump_done(&dump);
210 }
211
212 static int
213 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
214                 bool create, struct dpif **dpifp)
215 {
216     struct dpif_linux_dp dp_request, dp;
217     struct ofpbuf *buf;
218     uint32_t upcall_pid;
219     int error;
220
221     error = dpif_linux_init();
222     if (error) {
223         return error;
224     }
225
226     /* Create or look up datapath. */
227     dpif_linux_dp_init(&dp_request);
228     if (create) {
229         dp_request.cmd = OVS_DP_CMD_NEW;
230         upcall_pid = 0;
231         dp_request.upcall_pid = &upcall_pid;
232     } else {
233         /* Use OVS_DP_CMD_SET to report user features */
234         dp_request.cmd = OVS_DP_CMD_SET;
235     }
236     dp_request.name = name;
237     dp_request.user_features |= OVS_DP_F_UNALIGNED;
238     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
239     if (error) {
240         return error;
241     }
242
243     error = open_dpif(&dp, dpifp);
244     ofpbuf_delete(buf);
245     return error;
246 }
247
248 static int
249 open_dpif(const struct dpif_linux_dp *dp, struct dpif **dpifp)
250 {
251     struct dpif_linux *dpif;
252
253     dpif = xzalloc(sizeof *dpif);
254     dpif->port_notifier = NULL;
255     ovs_mutex_init(&dpif->upcall_lock);
256     dpif->epoll_fd = -1;
257
258     dpif_init(&dpif->dpif, &dpif_linux_class, dp->name,
259               dp->dp_ifindex, dp->dp_ifindex);
260
261     dpif->dp_ifindex = dp->dp_ifindex;
262     *dpifp = &dpif->dpif;
263
264     return 0;
265 }
266
267 static void
268 destroy_channels(struct dpif_linux *dpif)
269 {
270     unsigned int i;
271
272     if (dpif->epoll_fd < 0) {
273         return;
274     }
275
276     for (i = 0; i < dpif->uc_array_size; i++ ) {
277         struct dpif_linux_vport vport_request;
278         struct dpif_channel *ch = &dpif->channels[i];
279         uint32_t upcall_pid = 0;
280
281         if (!ch->sock) {
282             continue;
283         }
284
285         epoll_ctl(dpif->epoll_fd, EPOLL_CTL_DEL, nl_sock_fd(ch->sock), NULL);
286
287         /* Turn off upcalls. */
288         dpif_linux_vport_init(&vport_request);
289         vport_request.cmd = OVS_VPORT_CMD_SET;
290         vport_request.dp_ifindex = dpif->dp_ifindex;
291         vport_request.port_no = u32_to_odp(i);
292         vport_request.upcall_pid = &upcall_pid;
293         dpif_linux_vport_transact(&vport_request, NULL, NULL);
294
295         nl_sock_destroy(ch->sock);
296     }
297
298     free(dpif->channels);
299     dpif->channels = NULL;
300     dpif->uc_array_size = 0;
301
302     free(dpif->epoll_events);
303     dpif->epoll_events = NULL;
304     dpif->n_events = dpif->event_offset = 0;
305
306     /* Don't close dpif->epoll_fd since that would cause other threads that
307      * call dpif_recv_wait(dpif) to wait on an arbitrary fd or a closed fd. */
308 }
309
310 static int
311 add_channel(struct dpif_linux *dpif, odp_port_t port_no, struct nl_sock *sock)
312 {
313     struct epoll_event event;
314     uint32_t port_idx = odp_to_u32(port_no);
315
316     if (dpif->epoll_fd < 0) {
317         return 0;
318     }
319
320     /* We assume that the datapath densely chooses port numbers, which
321      * can therefore be used as an index into an array of channels. */
322     if (port_idx >= dpif->uc_array_size) {
323         uint32_t new_size = port_idx + 1;
324         uint32_t i;
325
326         if (new_size > MAX_PORTS) {
327             VLOG_WARN_RL(&error_rl, "%s: datapath port %"PRIu32" too big",
328                          dpif_name(&dpif->dpif), port_no);
329             return EFBIG;
330         }
331
332         dpif->channels = xrealloc(dpif->channels,
333                                   new_size * sizeof *dpif->channels);
334         for (i = dpif->uc_array_size; i < new_size; i++) {
335             dpif->channels[i].sock = NULL;
336         }
337
338         dpif->epoll_events = xrealloc(dpif->epoll_events,
339                                       new_size * sizeof *dpif->epoll_events);
340         dpif->uc_array_size = new_size;
341     }
342
343     memset(&event, 0, sizeof event);
344     event.events = EPOLLIN;
345     event.data.u32 = port_idx;
346     if (epoll_ctl(dpif->epoll_fd, EPOLL_CTL_ADD, nl_sock_fd(sock),
347                   &event) < 0) {
348         return errno;
349     }
350
351     nl_sock_destroy(dpif->channels[port_idx].sock);
352     dpif->channels[port_idx].sock = sock;
353     dpif->channels[port_idx].last_poll = LLONG_MIN;
354
355     return 0;
356 }
357
358 static void
359 del_channel(struct dpif_linux *dpif, odp_port_t port_no)
360 {
361     struct dpif_channel *ch;
362     uint32_t port_idx = odp_to_u32(port_no);
363
364     if (dpif->epoll_fd < 0 || port_idx >= dpif->uc_array_size) {
365         return;
366     }
367
368     ch = &dpif->channels[port_idx];
369     if (!ch->sock) {
370         return;
371     }
372
373     epoll_ctl(dpif->epoll_fd, EPOLL_CTL_DEL, nl_sock_fd(ch->sock), NULL);
374     dpif->event_offset = dpif->n_events = 0;
375
376     nl_sock_destroy(ch->sock);
377     ch->sock = NULL;
378 }
379
380 static void
381 dpif_linux_close(struct dpif *dpif_)
382 {
383     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
384
385     nl_sock_destroy(dpif->port_notifier);
386     destroy_channels(dpif);
387     if (dpif->epoll_fd >= 0) {
388         close(dpif->epoll_fd);
389     }
390     ovs_mutex_destroy(&dpif->upcall_lock);
391     free(dpif);
392 }
393
394 static int
395 dpif_linux_destroy(struct dpif *dpif_)
396 {
397     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
398     struct dpif_linux_dp dp;
399
400     dpif_linux_dp_init(&dp);
401     dp.cmd = OVS_DP_CMD_DEL;
402     dp.dp_ifindex = dpif->dp_ifindex;
403     return dpif_linux_dp_transact(&dp, NULL, NULL);
404 }
405
406 static void
407 dpif_linux_run(struct dpif *dpif_)
408 {
409     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
410     if (dpif->refresh_channels) {
411         dpif->refresh_channels = false;
412         dpif_linux_refresh_channels(dpif_);
413     }
414 }
415
416 static int
417 dpif_linux_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
418 {
419     struct dpif_linux_dp dp;
420     struct ofpbuf *buf;
421     int error;
422
423     error = dpif_linux_dp_get(dpif_, &dp, &buf);
424     if (!error) {
425         stats->n_hit    = dp.stats.n_hit;
426         stats->n_missed = dp.stats.n_missed;
427         stats->n_lost   = dp.stats.n_lost;
428         stats->n_flows  = dp.stats.n_flows;
429         stats->n_masks  = dp.megaflow_stats.n_masks;
430         stats->n_mask_hit  = dp.megaflow_stats.n_mask_hit;
431         ofpbuf_delete(buf);
432     }
433     return error;
434 }
435
436 static const char *
437 get_vport_type(const struct dpif_linux_vport *vport)
438 {
439     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
440
441     switch (vport->type) {
442     case OVS_VPORT_TYPE_NETDEV:
443         return "system";
444
445     case OVS_VPORT_TYPE_INTERNAL:
446         return "internal";
447
448     case OVS_VPORT_TYPE_GRE:
449         return "gre";
450
451     case OVS_VPORT_TYPE_GRE64:
452         return "gre64";
453
454     case OVS_VPORT_TYPE_VXLAN:
455         return "vxlan";
456
457     case OVS_VPORT_TYPE_LISP:
458         return "lisp";
459
460     case OVS_VPORT_TYPE_UNSPEC:
461     case __OVS_VPORT_TYPE_MAX:
462         break;
463     }
464
465     VLOG_WARN_RL(&rl, "dp%d: port `%s' has unsupported type %u",
466                  vport->dp_ifindex, vport->name, (unsigned int) vport->type);
467     return "unknown";
468 }
469
470 static enum ovs_vport_type
471 netdev_to_ovs_vport_type(const struct netdev *netdev)
472 {
473     const char *type = netdev_get_type(netdev);
474
475     if (!strcmp(type, "tap") || !strcmp(type, "system")) {
476         return OVS_VPORT_TYPE_NETDEV;
477     } else if (!strcmp(type, "internal")) {
478         return OVS_VPORT_TYPE_INTERNAL;
479     } else if (strstr(type, "gre64")) {
480         return OVS_VPORT_TYPE_GRE64;
481     } else if (strstr(type, "gre")) {
482         return OVS_VPORT_TYPE_GRE;
483     } else if (!strcmp(type, "vxlan")) {
484         return OVS_VPORT_TYPE_VXLAN;
485     } else if (!strcmp(type, "lisp")) {
486         return OVS_VPORT_TYPE_LISP;
487     } else {
488         return OVS_VPORT_TYPE_UNSPEC;
489     }
490 }
491
492 static int
493 dpif_linux_port_add__(struct dpif *dpif_, struct netdev *netdev,
494                       odp_port_t *port_nop)
495 {
496     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
497     const struct netdev_tunnel_config *tnl_cfg;
498     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
499     const char *name = netdev_vport_get_dpif_port(netdev,
500                                                   namebuf, sizeof namebuf);
501     const char *type = netdev_get_type(netdev);
502     struct dpif_linux_vport request, reply;
503     struct nl_sock *sock = NULL;
504     uint32_t upcall_pid;
505     struct ofpbuf *buf;
506     uint64_t options_stub[64 / 8];
507     struct ofpbuf options;
508     int error;
509
510     if (dpif->epoll_fd >= 0) {
511         error = nl_sock_create(NETLINK_GENERIC, &sock);
512         if (error) {
513             return error;
514         }
515     }
516
517     dpif_linux_vport_init(&request);
518     request.cmd = OVS_VPORT_CMD_NEW;
519     request.dp_ifindex = dpif->dp_ifindex;
520     request.type = netdev_to_ovs_vport_type(netdev);
521     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
522         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
523                      "unsupported type `%s'",
524                      dpif_name(dpif_), name, type);
525         nl_sock_destroy(sock);
526         return EINVAL;
527     }
528     request.name = name;
529
530     if (request.type == OVS_VPORT_TYPE_NETDEV) {
531         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
532     }
533
534     tnl_cfg = netdev_get_tunnel_config(netdev);
535     if (tnl_cfg && tnl_cfg->dst_port != 0) {
536         ofpbuf_use_stack(&options, options_stub, sizeof options_stub);
537         nl_msg_put_u16(&options, OVS_TUNNEL_ATTR_DST_PORT,
538                        ntohs(tnl_cfg->dst_port));
539         request.options = options.data;
540         request.options_len = options.size;
541     }
542
543     request.port_no = *port_nop;
544     upcall_pid = sock ? nl_sock_pid(sock) : 0;
545     request.upcall_pid = &upcall_pid;
546
547     error = dpif_linux_vport_transact(&request, &reply, &buf);
548     if (!error) {
549         *port_nop = reply.port_no;
550         VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
551                  dpif_name(dpif_), reply.port_no, upcall_pid);
552     } else {
553         if (error == EBUSY && *port_nop != ODPP_NONE) {
554             VLOG_INFO("%s: requested port %"PRIu32" is in use",
555                       dpif_name(dpif_), *port_nop);
556         }
557         nl_sock_destroy(sock);
558         ofpbuf_delete(buf);
559         return error;
560     }
561     ofpbuf_delete(buf);
562
563     if (sock) {
564         error = add_channel(dpif, *port_nop, sock);
565         if (error) {
566             VLOG_INFO("%s: could not add channel for port %s",
567                       dpif_name(dpif_), name);
568
569             /* Delete the port. */
570             dpif_linux_vport_init(&request);
571             request.cmd = OVS_VPORT_CMD_DEL;
572             request.dp_ifindex = dpif->dp_ifindex;
573             request.port_no = *port_nop;
574             dpif_linux_vport_transact(&request, NULL, NULL);
575
576             nl_sock_destroy(sock);
577             return error;
578         }
579     }
580
581     return 0;
582 }
583
584 static int
585 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
586                     odp_port_t *port_nop)
587 {
588     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
589     int error;
590
591     ovs_mutex_lock(&dpif->upcall_lock);
592     error = dpif_linux_port_add__(dpif_, netdev, port_nop);
593     ovs_mutex_unlock(&dpif->upcall_lock);
594
595     return error;
596 }
597
598 static int
599 dpif_linux_port_del__(struct dpif *dpif_, odp_port_t port_no)
600 {
601     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
602     struct dpif_linux_vport vport;
603     int error;
604
605     dpif_linux_vport_init(&vport);
606     vport.cmd = OVS_VPORT_CMD_DEL;
607     vport.dp_ifindex = dpif->dp_ifindex;
608     vport.port_no = port_no;
609     error = dpif_linux_vport_transact(&vport, NULL, NULL);
610
611     del_channel(dpif, port_no);
612
613     return error;
614 }
615
616 static int
617 dpif_linux_port_del(struct dpif *dpif_, odp_port_t port_no)
618 {
619     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
620     int error;
621
622     ovs_mutex_lock(&dpif->upcall_lock);
623     error = dpif_linux_port_del__(dpif_, port_no);
624     ovs_mutex_unlock(&dpif->upcall_lock);
625
626     return error;
627 }
628
629 static int
630 dpif_linux_port_query__(const struct dpif *dpif, odp_port_t port_no,
631                         const char *port_name, struct dpif_port *dpif_port)
632 {
633     struct dpif_linux_vport request;
634     struct dpif_linux_vport reply;
635     struct ofpbuf *buf;
636     int error;
637
638     dpif_linux_vport_init(&request);
639     request.cmd = OVS_VPORT_CMD_GET;
640     request.dp_ifindex = dpif_linux_cast(dpif)->dp_ifindex;
641     request.port_no = port_no;
642     request.name = port_name;
643
644     error = dpif_linux_vport_transact(&request, &reply, &buf);
645     if (!error) {
646         if (reply.dp_ifindex != request.dp_ifindex) {
647             /* A query by name reported that 'port_name' is in some datapath
648              * other than 'dpif', but the caller wants to know about 'dpif'. */
649             error = ENODEV;
650         } else if (dpif_port) {
651             dpif_port->name = xstrdup(reply.name);
652             dpif_port->type = xstrdup(get_vport_type(&reply));
653             dpif_port->port_no = reply.port_no;
654         }
655         ofpbuf_delete(buf);
656     }
657     return error;
658 }
659
660 static int
661 dpif_linux_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
662                                 struct dpif_port *dpif_port)
663 {
664     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
665 }
666
667 static int
668 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
669                               struct dpif_port *dpif_port)
670 {
671     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
672 }
673
674 static uint32_t
675 dpif_linux_port_get_pid(const struct dpif *dpif_, odp_port_t port_no)
676 {
677     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
678     uint32_t port_idx = odp_to_u32(port_no);
679     uint32_t pid = 0;
680
681     ovs_mutex_lock(&dpif->upcall_lock);
682     if (dpif->epoll_fd >= 0) {
683         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
684          * channel, since it is not heavily loaded. */
685         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
686         const struct nl_sock *sock = dpif->channels[idx].sock;
687         pid = sock ? nl_sock_pid(sock) : 0;
688     }
689     ovs_mutex_unlock(&dpif->upcall_lock);
690
691     return pid;
692 }
693
694 static int
695 dpif_linux_flow_flush(struct dpif *dpif_)
696 {
697     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
698     struct dpif_linux_flow flow;
699
700     dpif_linux_flow_init(&flow);
701     flow.cmd = OVS_FLOW_CMD_DEL;
702     flow.dp_ifindex = dpif->dp_ifindex;
703     return dpif_linux_flow_transact(&flow, NULL, NULL);
704 }
705
706 struct dpif_linux_port_state {
707     struct nl_dump dump;
708 };
709
710 static void
711 dpif_linux_port_dump_start__(const struct dpif *dpif_, struct nl_dump *dump)
712 {
713     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
714     struct dpif_linux_vport request;
715     struct ofpbuf *buf;
716
717     dpif_linux_vport_init(&request);
718     request.cmd = OVS_VPORT_CMD_GET;
719     request.dp_ifindex = dpif->dp_ifindex;
720
721     buf = ofpbuf_new(1024);
722     dpif_linux_vport_to_ofpbuf(&request, buf);
723     nl_dump_start(dump, NETLINK_GENERIC, buf);
724     ofpbuf_delete(buf);
725 }
726
727 static int
728 dpif_linux_port_dump_start(const struct dpif *dpif, void **statep)
729 {
730     struct dpif_linux_port_state *state;
731
732     *statep = state = xmalloc(sizeof *state);
733     dpif_linux_port_dump_start__(dpif, &state->dump);
734
735     return 0;
736 }
737
738 static int
739 dpif_linux_port_dump_next__(const struct dpif *dpif_, struct nl_dump *dump,
740                             struct dpif_linux_vport *vport)
741 {
742     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
743     struct ofpbuf buf;
744     int error;
745
746     if (!nl_dump_next(dump, &buf)) {
747         return EOF;
748     }
749
750     error = dpif_linux_vport_from_ofpbuf(vport, &buf);
751     if (error) {
752         VLOG_WARN_RL(&error_rl, "%s: failed to parse vport record (%s)",
753                      dpif_name(&dpif->dpif), ovs_strerror(error));
754     }
755     return error;
756 }
757
758 static int
759 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
760                           struct dpif_port *dpif_port)
761 {
762     struct dpif_linux_port_state *state = state_;
763     struct dpif_linux_vport vport;
764     int error;
765
766     error = dpif_linux_port_dump_next__(dpif, &state->dump, &vport);
767     if (error) {
768         return error;
769     }
770     dpif_port->name = CONST_CAST(char *, vport.name);
771     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
772     dpif_port->port_no = vport.port_no;
773     return 0;
774 }
775
776 static int
777 dpif_linux_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
778 {
779     struct dpif_linux_port_state *state = state_;
780     int error = nl_dump_done(&state->dump);
781
782     free(state);
783     return error;
784 }
785
786 static int
787 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
788 {
789     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
790
791     /* Lazily create the Netlink socket to listen for notifications. */
792     if (!dpif->port_notifier) {
793         struct nl_sock *sock;
794         int error;
795
796         error = nl_sock_create(NETLINK_GENERIC, &sock);
797         if (error) {
798             return error;
799         }
800
801         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
802         if (error) {
803             nl_sock_destroy(sock);
804             return error;
805         }
806         dpif->port_notifier = sock;
807
808         /* We have no idea of the current state so report that everything
809          * changed. */
810         return ENOBUFS;
811     }
812
813     for (;;) {
814         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
815         uint64_t buf_stub[4096 / 8];
816         struct ofpbuf buf;
817         int error;
818
819         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
820         error = nl_sock_recv(dpif->port_notifier, &buf, false);
821         if (!error) {
822             struct dpif_linux_vport vport;
823
824             error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
825             if (!error) {
826                 if (vport.dp_ifindex == dpif->dp_ifindex
827                     && (vport.cmd == OVS_VPORT_CMD_NEW
828                         || vport.cmd == OVS_VPORT_CMD_DEL
829                         || vport.cmd == OVS_VPORT_CMD_SET)) {
830                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
831                              dpif->dpif.full_name, vport.name, vport.cmd);
832                     if (vport.cmd == OVS_VPORT_CMD_DEL) {
833                         dpif->refresh_channels = true;
834                     }
835                     *devnamep = xstrdup(vport.name);
836                     ofpbuf_uninit(&buf);
837                     return 0;
838                 }
839             }
840         } else if (error != EAGAIN) {
841             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
842                          ovs_strerror(error));
843             nl_sock_drain(dpif->port_notifier);
844             error = ENOBUFS;
845         }
846
847         ofpbuf_uninit(&buf);
848         if (error) {
849             return error;
850         }
851     }
852 }
853
854 static void
855 dpif_linux_port_poll_wait(const struct dpif *dpif_)
856 {
857     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
858
859     if (dpif->port_notifier) {
860         nl_sock_wait(dpif->port_notifier, POLLIN);
861     } else {
862         poll_immediate_wake();
863     }
864 }
865
866 static int
867 dpif_linux_flow_get__(const struct dpif *dpif_,
868                       const struct nlattr *key, size_t key_len,
869                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
870 {
871     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
872     struct dpif_linux_flow request;
873
874     dpif_linux_flow_init(&request);
875     request.cmd = OVS_FLOW_CMD_GET;
876     request.dp_ifindex = dpif->dp_ifindex;
877     request.key = key;
878     request.key_len = key_len;
879     return dpif_linux_flow_transact(&request, reply, bufp);
880 }
881
882 static int
883 dpif_linux_flow_get(const struct dpif *dpif_,
884                     const struct nlattr *key, size_t key_len,
885                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
886 {
887     struct dpif_linux_flow reply;
888     struct ofpbuf *buf;
889     int error;
890
891     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
892     if (!error) {
893         if (stats) {
894             dpif_linux_flow_get_stats(&reply, stats);
895         }
896         if (actionsp) {
897             buf->data = CONST_CAST(struct nlattr *, reply.actions);
898             buf->size = reply.actions_len;
899             *actionsp = buf;
900         } else {
901             ofpbuf_delete(buf);
902         }
903     }
904     return error;
905 }
906
907 static void
908 dpif_linux_init_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put,
909                          struct dpif_linux_flow *request)
910 {
911     static const struct nlattr dummy_action;
912
913     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
914
915     dpif_linux_flow_init(request);
916     request->cmd = (put->flags & DPIF_FP_CREATE
917                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
918     request->dp_ifindex = dpif->dp_ifindex;
919     request->key = put->key;
920     request->key_len = put->key_len;
921     request->mask = put->mask;
922     request->mask_len = put->mask_len;
923     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
924     request->actions = (put->actions
925                         ? put->actions
926                         : CONST_CAST(struct nlattr *, &dummy_action));
927     request->actions_len = put->actions_len;
928     if (put->flags & DPIF_FP_ZERO_STATS) {
929         request->clear = true;
930     }
931     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
932 }
933
934 static int
935 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
936 {
937     struct dpif_linux_flow request, reply;
938     struct ofpbuf *buf;
939     int error;
940
941     dpif_linux_init_flow_put(dpif_, put, &request);
942     error = dpif_linux_flow_transact(&request,
943                                      put->stats ? &reply : NULL,
944                                      put->stats ? &buf : NULL);
945     if (!error && put->stats) {
946         dpif_linux_flow_get_stats(&reply, put->stats);
947         ofpbuf_delete(buf);
948     }
949     return error;
950 }
951
952 static void
953 dpif_linux_init_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del,
954                          struct dpif_linux_flow *request)
955 {
956     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
957
958     dpif_linux_flow_init(request);
959     request->cmd = OVS_FLOW_CMD_DEL;
960     request->dp_ifindex = dpif->dp_ifindex;
961     request->key = del->key;
962     request->key_len = del->key_len;
963 }
964
965 static int
966 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
967 {
968     struct dpif_linux_flow request, reply;
969     struct ofpbuf *buf;
970     int error;
971
972     dpif_linux_init_flow_del(dpif_, del, &request);
973     error = dpif_linux_flow_transact(&request,
974                                      del->stats ? &reply : NULL,
975                                      del->stats ? &buf : NULL);
976     if (!error && del->stats) {
977         dpif_linux_flow_get_stats(&reply, del->stats);
978         ofpbuf_delete(buf);
979     }
980     return error;
981 }
982
983 struct dpif_linux_flow_state {
984     struct nl_dump dump;
985     struct dpif_linux_flow flow;
986     struct dpif_flow_stats stats;
987     struct ofpbuf *buf;
988 };
989
990 static int
991 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
992 {
993     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
994     struct dpif_linux_flow_state *state;
995     struct dpif_linux_flow request;
996     struct ofpbuf *buf;
997
998     *statep = state = xmalloc(sizeof *state);
999
1000     dpif_linux_flow_init(&request);
1001     request.cmd = OVS_FLOW_CMD_GET;
1002     request.dp_ifindex = dpif->dp_ifindex;
1003
1004     buf = ofpbuf_new(1024);
1005     dpif_linux_flow_to_ofpbuf(&request, buf);
1006     nl_dump_start(&state->dump, NETLINK_GENERIC, buf);
1007     ofpbuf_delete(buf);
1008
1009     state->buf = NULL;
1010
1011     return 0;
1012 }
1013
1014 static int
1015 dpif_linux_flow_dump_next(const struct dpif *dpif_, void *state_,
1016                           const struct nlattr **key, size_t *key_len,
1017                           const struct nlattr **mask, size_t *mask_len,
1018                           const struct nlattr **actions, size_t *actions_len,
1019                           const struct dpif_flow_stats **stats)
1020 {
1021     struct dpif_linux_flow_state *state = state_;
1022     struct ofpbuf buf;
1023     int error;
1024
1025     do {
1026         ofpbuf_delete(state->buf);
1027         state->buf = NULL;
1028
1029         if (!nl_dump_next(&state->dump, &buf)) {
1030             return EOF;
1031         }
1032
1033         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
1034         if (error) {
1035             return error;
1036         }
1037
1038         if (actions && !state->flow.actions) {
1039             error = dpif_linux_flow_get__(dpif_, state->flow.key,
1040                                           state->flow.key_len,
1041                                           &state->flow, &state->buf);
1042             if (error == ENOENT) {
1043                 VLOG_DBG("dumped flow disappeared on get");
1044             } else if (error) {
1045                 VLOG_WARN("error fetching dumped flow: %s",
1046                           ovs_strerror(error));
1047             }
1048         }
1049     } while (error);
1050
1051     if (actions) {
1052         *actions = state->flow.actions;
1053         *actions_len = state->flow.actions_len;
1054     }
1055     if (key) {
1056         *key = state->flow.key;
1057         *key_len = state->flow.key_len;
1058     }
1059     if (mask) {
1060         *mask = state->flow.mask;
1061         *mask_len = state->flow.mask ? state->flow.mask_len : 0;
1062     }
1063     if (stats) {
1064         dpif_linux_flow_get_stats(&state->flow, &state->stats);
1065         *stats = &state->stats;
1066     }
1067     return error;
1068 }
1069
1070 static int
1071 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1072 {
1073     struct dpif_linux_flow_state *state = state_;
1074     int error = nl_dump_done(&state->dump);
1075     ofpbuf_delete(state->buf);
1076     free(state);
1077     return error;
1078 }
1079
1080 static void
1081 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1082                           struct ofpbuf *buf)
1083 {
1084     struct ovs_header *k_exec;
1085     size_t key_ofs;
1086
1087     ofpbuf_prealloc_tailroom(buf, (64
1088                                    + d_exec->packet->size
1089                                    + ODP_KEY_METADATA_SIZE
1090                                    + d_exec->actions_len));
1091
1092     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1093                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1094
1095     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1096     k_exec->dp_ifindex = dp_ifindex;
1097
1098     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1099                       d_exec->packet->data, d_exec->packet->size);
1100
1101     key_ofs = nl_msg_start_nested(buf, OVS_PACKET_ATTR_KEY);
1102     odp_key_from_pkt_metadata(buf, &d_exec->md);
1103     nl_msg_end_nested(buf, key_ofs);
1104
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_, 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     /* (Re)set ALL fields of '*upcall' on successful return. */
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_port_get_pid,
1616     dpif_linux_port_dump_start,
1617     dpif_linux_port_dump_next,
1618     dpif_linux_port_dump_done,
1619     dpif_linux_port_poll,
1620     dpif_linux_port_poll_wait,
1621     dpif_linux_flow_get,
1622     dpif_linux_flow_put,
1623     dpif_linux_flow_del,
1624     dpif_linux_flow_flush,
1625     dpif_linux_flow_dump_start,
1626     dpif_linux_flow_dump_next,
1627     dpif_linux_flow_dump_done,
1628     dpif_linux_execute,
1629     dpif_linux_operate,
1630     dpif_linux_recv_set,
1631     dpif_linux_queue_to_priority,
1632     dpif_linux_recv,
1633     dpif_linux_recv_wait,
1634     dpif_linux_recv_purge,
1635 };
1636 \f
1637 static int
1638 dpif_linux_init(void)
1639 {
1640     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1641     static int error;
1642
1643     if (ovsthread_once_start(&once)) {
1644         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1645                                       &ovs_datapath_family);
1646         if (error) {
1647             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1648                      "The Open vSwitch kernel module is probably not loaded.",
1649                      OVS_DATAPATH_FAMILY);
1650         }
1651         if (!error) {
1652             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1653         }
1654         if (!error) {
1655             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1656         }
1657         if (!error) {
1658             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1659                                           &ovs_packet_family);
1660         }
1661         if (!error) {
1662             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1663                                            &ovs_vport_mcgroup);
1664         }
1665
1666         ovsthread_once_done(&once);
1667     }
1668
1669     return error;
1670 }
1671
1672 bool
1673 dpif_linux_is_internal_device(const char *name)
1674 {
1675     struct dpif_linux_vport reply;
1676     struct ofpbuf *buf;
1677     int error;
1678
1679     error = dpif_linux_vport_get(name, &reply, &buf);
1680     if (!error) {
1681         ofpbuf_delete(buf);
1682     } else if (error != ENODEV && error != ENOENT) {
1683         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1684                      name, ovs_strerror(error));
1685     }
1686
1687     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1688 }
1689 \f
1690 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1691  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1692  * positive errno value.
1693  *
1694  * 'vport' will contain pointers into 'buf', so the caller should not free
1695  * 'buf' while 'vport' is still in use. */
1696 static int
1697 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1698                              const struct ofpbuf *buf)
1699 {
1700     static const struct nl_policy ovs_vport_policy[] = {
1701         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1702         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1703         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1704         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1705         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1706                                    .optional = true },
1707         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1708     };
1709
1710     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1711     struct ovs_header *ovs_header;
1712     struct nlmsghdr *nlmsg;
1713     struct genlmsghdr *genl;
1714     struct ofpbuf b;
1715
1716     dpif_linux_vport_init(vport);
1717
1718     ofpbuf_use_const(&b, buf->data, buf->size);
1719     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1720     genl = ofpbuf_try_pull(&b, sizeof *genl);
1721     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1722     if (!nlmsg || !genl || !ovs_header
1723         || nlmsg->nlmsg_type != ovs_vport_family
1724         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1725                             ARRAY_SIZE(ovs_vport_policy))) {
1726         return EINVAL;
1727     }
1728
1729     vport->cmd = genl->cmd;
1730     vport->dp_ifindex = ovs_header->dp_ifindex;
1731     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
1732     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1733     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1734     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1735         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1736     }
1737     if (a[OVS_VPORT_ATTR_STATS]) {
1738         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1739     }
1740     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1741         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1742         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1743     }
1744     return 0;
1745 }
1746
1747 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1748  * followed by Netlink attributes corresponding to 'vport'. */
1749 static void
1750 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1751                            struct ofpbuf *buf)
1752 {
1753     struct ovs_header *ovs_header;
1754
1755     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1756                           vport->cmd, OVS_VPORT_VERSION);
1757
1758     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1759     ovs_header->dp_ifindex = vport->dp_ifindex;
1760
1761     if (vport->port_no != ODPP_NONE) {
1762         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1763     }
1764
1765     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1766         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1767     }
1768
1769     if (vport->name) {
1770         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1771     }
1772
1773     if (vport->upcall_pid) {
1774         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1775     }
1776
1777     if (vport->stats) {
1778         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1779                           vport->stats, sizeof *vport->stats);
1780     }
1781
1782     if (vport->options) {
1783         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1784                           vport->options, vport->options_len);
1785     }
1786 }
1787
1788 /* Clears 'vport' to "empty" values. */
1789 void
1790 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1791 {
1792     memset(vport, 0, sizeof *vport);
1793     vport->port_no = ODPP_NONE;
1794 }
1795
1796 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1797  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1798  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1799  * result of the command is expected to be an ovs_vport also, which is decoded
1800  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1801  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1802 int
1803 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1804                           struct dpif_linux_vport *reply,
1805                           struct ofpbuf **bufp)
1806 {
1807     struct ofpbuf *request_buf;
1808     int error;
1809
1810     ovs_assert((reply != NULL) == (bufp != NULL));
1811
1812     error = dpif_linux_init();
1813     if (error) {
1814         if (reply) {
1815             *bufp = NULL;
1816             dpif_linux_vport_init(reply);
1817         }
1818         return error;
1819     }
1820
1821     request_buf = ofpbuf_new(1024);
1822     dpif_linux_vport_to_ofpbuf(request, request_buf);
1823     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1824     ofpbuf_delete(request_buf);
1825
1826     if (reply) {
1827         if (!error) {
1828             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1829         }
1830         if (error) {
1831             dpif_linux_vport_init(reply);
1832             ofpbuf_delete(*bufp);
1833             *bufp = NULL;
1834         }
1835     }
1836     return error;
1837 }
1838
1839 /* Obtains information about the kernel vport named 'name' and stores it into
1840  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1841  * longer needed ('reply' will contain pointers into '*bufp').  */
1842 int
1843 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1844                      struct ofpbuf **bufp)
1845 {
1846     struct dpif_linux_vport request;
1847
1848     dpif_linux_vport_init(&request);
1849     request.cmd = OVS_VPORT_CMD_GET;
1850     request.name = name;
1851
1852     return dpif_linux_vport_transact(&request, reply, bufp);
1853 }
1854 \f
1855 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1856  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1857  * positive errno value.
1858  *
1859  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1860  * while 'dp' is still in use. */
1861 static int
1862 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1863 {
1864     static const struct nl_policy ovs_datapath_policy[] = {
1865         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1866         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1867                                 .optional = true },
1868         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
1869                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
1870                         .optional = true },
1871     };
1872
1873     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1874     struct ovs_header *ovs_header;
1875     struct nlmsghdr *nlmsg;
1876     struct genlmsghdr *genl;
1877     struct ofpbuf b;
1878
1879     dpif_linux_dp_init(dp);
1880
1881     ofpbuf_use_const(&b, buf->data, buf->size);
1882     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1883     genl = ofpbuf_try_pull(&b, sizeof *genl);
1884     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1885     if (!nlmsg || !genl || !ovs_header
1886         || nlmsg->nlmsg_type != ovs_datapath_family
1887         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1888                             ARRAY_SIZE(ovs_datapath_policy))) {
1889         return EINVAL;
1890     }
1891
1892     dp->cmd = genl->cmd;
1893     dp->dp_ifindex = ovs_header->dp_ifindex;
1894     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1895     if (a[OVS_DP_ATTR_STATS]) {
1896         /* Can't use structure assignment because Netlink doesn't ensure
1897          * sufficient alignment for 64-bit members. */
1898         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1899                sizeof dp->stats);
1900     }
1901
1902     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
1903         /* Can't use structure assignment because Netlink doesn't ensure
1904          * sufficient alignment for 64-bit members. */
1905         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
1906                sizeof dp->megaflow_stats);
1907     }
1908
1909     return 0;
1910 }
1911
1912 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1913 static void
1914 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1915 {
1916     struct ovs_header *ovs_header;
1917
1918     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1919                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1920                           OVS_DATAPATH_VERSION);
1921
1922     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1923     ovs_header->dp_ifindex = dp->dp_ifindex;
1924
1925     if (dp->name) {
1926         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1927     }
1928
1929     if (dp->upcall_pid) {
1930         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1931     }
1932
1933     if (dp->user_features) {
1934         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
1935     }
1936
1937     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1938 }
1939
1940 /* Clears 'dp' to "empty" values. */
1941 static void
1942 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1943 {
1944     memset(dp, 0, sizeof *dp);
1945     dp->megaflow_stats.n_masks = UINT32_MAX;
1946     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
1947 }
1948
1949 static void
1950 dpif_linux_dp_dump_start(struct nl_dump *dump)
1951 {
1952     struct dpif_linux_dp request;
1953     struct ofpbuf *buf;
1954
1955     dpif_linux_dp_init(&request);
1956     request.cmd = OVS_DP_CMD_GET;
1957
1958     buf = ofpbuf_new(1024);
1959     dpif_linux_dp_to_ofpbuf(&request, buf);
1960     nl_dump_start(dump, NETLINK_GENERIC, buf);
1961     ofpbuf_delete(buf);
1962 }
1963
1964 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1965  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1966  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1967  * result of the command is expected to be of the same form, which is decoded
1968  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1969  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1970 static int
1971 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1972                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1973 {
1974     struct ofpbuf *request_buf;
1975     int error;
1976
1977     ovs_assert((reply != NULL) == (bufp != NULL));
1978
1979     request_buf = ofpbuf_new(1024);
1980     dpif_linux_dp_to_ofpbuf(request, request_buf);
1981     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1982     ofpbuf_delete(request_buf);
1983
1984     if (reply) {
1985         dpif_linux_dp_init(reply);
1986         if (!error) {
1987             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1988         }
1989         if (error) {
1990             ofpbuf_delete(*bufp);
1991             *bufp = NULL;
1992         }
1993     }
1994     return error;
1995 }
1996
1997 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1998  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1999  * will contain pointers into '*bufp').  */
2000 static int
2001 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
2002                   struct ofpbuf **bufp)
2003 {
2004     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2005     struct dpif_linux_dp request;
2006
2007     dpif_linux_dp_init(&request);
2008     request.cmd = OVS_DP_CMD_GET;
2009     request.dp_ifindex = dpif->dp_ifindex;
2010
2011     return dpif_linux_dp_transact(&request, reply, bufp);
2012 }
2013 \f
2014 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2015  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2016  * positive errno value.
2017  *
2018  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2019  * while 'flow' is still in use. */
2020 static int
2021 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
2022                             const struct ofpbuf *buf)
2023 {
2024     static const struct nl_policy ovs_flow_policy[] = {
2025         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
2026         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2027         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2028         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2029                                   .optional = true },
2030         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2031         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2032         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2033     };
2034
2035     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2036     struct ovs_header *ovs_header;
2037     struct nlmsghdr *nlmsg;
2038     struct genlmsghdr *genl;
2039     struct ofpbuf b;
2040
2041     dpif_linux_flow_init(flow);
2042
2043     ofpbuf_use_const(&b, buf->data, buf->size);
2044     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2045     genl = ofpbuf_try_pull(&b, sizeof *genl);
2046     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2047     if (!nlmsg || !genl || !ovs_header
2048         || nlmsg->nlmsg_type != ovs_flow_family
2049         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2050                             ARRAY_SIZE(ovs_flow_policy))) {
2051         return EINVAL;
2052     }
2053
2054     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2055     flow->dp_ifindex = ovs_header->dp_ifindex;
2056     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2057     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2058
2059     if (a[OVS_FLOW_ATTR_MASK]) {
2060         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2061         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2062     }
2063     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2064         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2065         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2066     }
2067     if (a[OVS_FLOW_ATTR_STATS]) {
2068         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2069     }
2070     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2071         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2072     }
2073     if (a[OVS_FLOW_ATTR_USED]) {
2074         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2075     }
2076     return 0;
2077 }
2078
2079 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2080  * followed by Netlink attributes corresponding to 'flow'. */
2081 static void
2082 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
2083                           struct ofpbuf *buf)
2084 {
2085     struct ovs_header *ovs_header;
2086
2087     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2088                           NLM_F_REQUEST | flow->nlmsg_flags,
2089                           flow->cmd, OVS_FLOW_VERSION);
2090
2091     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2092     ovs_header->dp_ifindex = flow->dp_ifindex;
2093
2094     if (flow->key_len) {
2095         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2096     }
2097
2098     if (flow->mask_len) {
2099         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2100     }
2101
2102     if (flow->actions || flow->actions_len) {
2103         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2104                           flow->actions, flow->actions_len);
2105     }
2106
2107     /* We never need to send these to the kernel. */
2108     ovs_assert(!flow->stats);
2109     ovs_assert(!flow->tcp_flags);
2110     ovs_assert(!flow->used);
2111
2112     if (flow->clear) {
2113         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2114     }
2115 }
2116
2117 /* Clears 'flow' to "empty" values. */
2118 static void
2119 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2120 {
2121     memset(flow, 0, sizeof *flow);
2122 }
2123
2124 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2125  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2126  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2127  * result of the command is expected to be a flow also, which is decoded and
2128  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2129  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2130 static int
2131 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2132                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2133 {
2134     struct ofpbuf *request_buf;
2135     int error;
2136
2137     ovs_assert((reply != NULL) == (bufp != NULL));
2138
2139     if (reply) {
2140         request->nlmsg_flags |= NLM_F_ECHO;
2141     }
2142
2143     request_buf = ofpbuf_new(1024);
2144     dpif_linux_flow_to_ofpbuf(request, request_buf);
2145     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2146     ofpbuf_delete(request_buf);
2147
2148     if (reply) {
2149         if (!error) {
2150             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2151         }
2152         if (error) {
2153             dpif_linux_flow_init(reply);
2154             ofpbuf_delete(*bufp);
2155             *bufp = NULL;
2156         }
2157     }
2158     return error;
2159 }
2160
2161 static void
2162 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2163                           struct dpif_flow_stats *stats)
2164 {
2165     if (flow->stats) {
2166         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2167         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2168     } else {
2169         stats->n_packets = 0;
2170         stats->n_bytes = 0;
2171     }
2172     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2173     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2174 }
2175 \f
2176 /* Logs information about a packet that was recently lost in 'ch' (in
2177  * 'dpif_'). */
2178 static void
2179 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
2180 {
2181     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2182     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2183     struct ds s;
2184
2185     if (VLOG_DROP_WARN(&rl)) {
2186         return;
2187     }
2188
2189     ds_init(&s);
2190     if (ch->last_poll != LLONG_MIN) {
2191         ds_put_format(&s, " (last polled %lld ms ago)",
2192                       time_msec() - ch->last_poll);
2193     }
2194
2195     VLOG_WARN("%s: lost packet on channel %"PRIdPTR"%s",
2196               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2197     ds_destroy(&s);
2198 }