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