dpif-linux: Fix flow_dump_next annotation.
[sliver-openvswitch.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "dpif-linux.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/types.h>
27 #include <linux/pkt_sched.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <poll.h>
31 #include <stdlib.h>
32 #include <strings.h>
33 #include <sys/epoll.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "bitmap.h"
38 #include "dpif-provider.h"
39 #include "dynamic-string.h"
40 #include "flow.h"
41 #include "netdev.h"
42 #include "netdev-linux.h"
43 #include "netdev-vport.h"
44 #include "netlink-notifier.h"
45 #include "netlink-socket.h"
46 #include "netlink.h"
47 #include "odp-util.h"
48 #include "ofpbuf.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "shash.h"
53 #include "sset.h"
54 #include "timeval.h"
55 #include "unaligned.h"
56 #include "util.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(dpif_linux);
60 enum { MAX_PORTS = USHRT_MAX };
61
62 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
63  * missing if we have old headers. */
64 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
65
66 struct dpif_linux_dp {
67     /* Generic Netlink header. */
68     uint8_t cmd;
69
70     /* struct ovs_header. */
71     int dp_ifindex;
72
73     /* Attributes. */
74     const char *name;                  /* OVS_DP_ATTR_NAME. */
75     const uint32_t *upcall_pid;        /* OVS_DP_ATTR_UPCALL_PID. */
76     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_port_get_pid(const struct dpif *dpif_, odp_port_t port_no)
678 {
679     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
680     uint32_t port_idx = odp_to_u32(port_no);
681     uint32_t pid = 0;
682
683     ovs_mutex_lock(&dpif->upcall_lock);
684     if (dpif->epoll_fd >= 0) {
685         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
686          * channel, since it is not heavily loaded. */
687         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
688         const struct nl_sock *sock = dpif->channels[idx].sock;
689         pid = sock ? nl_sock_pid(sock) : 0;
690     }
691     ovs_mutex_unlock(&dpif->upcall_lock);
692
693     return pid;
694 }
695
696 static int
697 dpif_linux_flow_flush(struct dpif *dpif_)
698 {
699     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
700     struct dpif_linux_flow flow;
701
702     dpif_linux_flow_init(&flow);
703     flow.cmd = OVS_FLOW_CMD_DEL;
704     flow.dp_ifindex = dpif->dp_ifindex;
705     return dpif_linux_flow_transact(&flow, NULL, NULL);
706 }
707
708 struct dpif_linux_port_state {
709     struct nl_dump dump;
710 };
711
712 static void
713 dpif_linux_port_dump_start__(const struct dpif *dpif_, struct nl_dump *dump)
714 {
715     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
716     struct dpif_linux_vport request;
717     struct ofpbuf *buf;
718
719     dpif_linux_vport_init(&request);
720     request.cmd = OVS_VPORT_CMD_GET;
721     request.dp_ifindex = dpif->dp_ifindex;
722
723     buf = ofpbuf_new(1024);
724     dpif_linux_vport_to_ofpbuf(&request, buf);
725     nl_dump_start(dump, NETLINK_GENERIC, buf);
726     ofpbuf_delete(buf);
727 }
728
729 static int
730 dpif_linux_port_dump_start(const struct dpif *dpif, void **statep)
731 {
732     struct dpif_linux_port_state *state;
733
734     *statep = state = xmalloc(sizeof *state);
735     dpif_linux_port_dump_start__(dpif, &state->dump);
736
737     return 0;
738 }
739
740 static int
741 dpif_linux_port_dump_next__(const struct dpif *dpif_, struct nl_dump *dump,
742                             struct dpif_linux_vport *vport)
743 {
744     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
745     struct ofpbuf buf;
746     int error;
747
748     if (!nl_dump_next(dump, &buf)) {
749         return EOF;
750     }
751
752     error = dpif_linux_vport_from_ofpbuf(vport, &buf);
753     if (error) {
754         VLOG_WARN_RL(&error_rl, "%s: failed to parse vport record (%s)",
755                      dpif_name(&dpif->dpif), ovs_strerror(error));
756     }
757     return error;
758 }
759
760 static int
761 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
762                           struct dpif_port *dpif_port)
763 {
764     struct dpif_linux_port_state *state = state_;
765     struct dpif_linux_vport vport;
766     int error;
767
768     error = dpif_linux_port_dump_next__(dpif, &state->dump, &vport);
769     if (error) {
770         return error;
771     }
772     dpif_port->name = CONST_CAST(char *, vport.name);
773     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
774     dpif_port->port_no = vport.port_no;
775     return 0;
776 }
777
778 static int
779 dpif_linux_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
780 {
781     struct dpif_linux_port_state *state = state_;
782     int error = nl_dump_done(&state->dump);
783
784     free(state);
785     return error;
786 }
787
788 static int
789 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
790 {
791     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
792
793     /* Lazily create the Netlink socket to listen for notifications. */
794     if (!dpif->port_notifier) {
795         struct nl_sock *sock;
796         int error;
797
798         error = nl_sock_create(NETLINK_GENERIC, &sock);
799         if (error) {
800             return error;
801         }
802
803         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
804         if (error) {
805             nl_sock_destroy(sock);
806             return error;
807         }
808         dpif->port_notifier = sock;
809
810         /* We have no idea of the current state so report that everything
811          * changed. */
812         return ENOBUFS;
813     }
814
815     for (;;) {
816         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
817         uint64_t buf_stub[4096 / 8];
818         struct ofpbuf buf;
819         int error;
820
821         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
822         error = nl_sock_recv(dpif->port_notifier, &buf, false);
823         if (!error) {
824             struct dpif_linux_vport vport;
825
826             error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
827             if (!error) {
828                 if (vport.dp_ifindex == dpif->dp_ifindex
829                     && (vport.cmd == OVS_VPORT_CMD_NEW
830                         || vport.cmd == OVS_VPORT_CMD_DEL
831                         || vport.cmd == OVS_VPORT_CMD_SET)) {
832                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
833                              dpif->dpif.full_name, vport.name, vport.cmd);
834                     if (vport.cmd == OVS_VPORT_CMD_DEL) {
835                         dpif->refresh_channels = true;
836                     }
837                     *devnamep = xstrdup(vport.name);
838                     ofpbuf_uninit(&buf);
839                     return 0;
840                 }
841             }
842         } else if (error != EAGAIN) {
843             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
844                          ovs_strerror(error));
845             nl_sock_drain(dpif->port_notifier);
846             error = ENOBUFS;
847         }
848
849         ofpbuf_uninit(&buf);
850         if (error) {
851             return error;
852         }
853     }
854 }
855
856 static void
857 dpif_linux_port_poll_wait(const struct dpif *dpif_)
858 {
859     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
860
861     if (dpif->port_notifier) {
862         nl_sock_wait(dpif->port_notifier, POLLIN);
863     } else {
864         poll_immediate_wake();
865     }
866 }
867
868 static int
869 dpif_linux_flow_get__(const struct dpif *dpif_,
870                       const struct nlattr *key, size_t key_len,
871                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
872 {
873     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
874     struct dpif_linux_flow request;
875
876     dpif_linux_flow_init(&request);
877     request.cmd = OVS_FLOW_CMD_GET;
878     request.dp_ifindex = dpif->dp_ifindex;
879     request.key = key;
880     request.key_len = key_len;
881     return dpif_linux_flow_transact(&request, reply, bufp);
882 }
883
884 static int
885 dpif_linux_flow_get(const struct dpif *dpif_,
886                     const struct nlattr *key, size_t key_len,
887                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
888 {
889     struct dpif_linux_flow reply;
890     struct ofpbuf *buf;
891     int error;
892
893     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
894     if (!error) {
895         if (stats) {
896             dpif_linux_flow_get_stats(&reply, stats);
897         }
898         if (actionsp) {
899             buf->data = CONST_CAST(struct nlattr *, reply.actions);
900             buf->size = reply.actions_len;
901             *actionsp = buf;
902         } else {
903             ofpbuf_delete(buf);
904         }
905     }
906     return error;
907 }
908
909 static void
910 dpif_linux_init_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put,
911                          struct dpif_linux_flow *request)
912 {
913     static const struct nlattr dummy_action;
914
915     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
916
917     dpif_linux_flow_init(request);
918     request->cmd = (put->flags & DPIF_FP_CREATE
919                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
920     request->dp_ifindex = dpif->dp_ifindex;
921     request->key = put->key;
922     request->key_len = put->key_len;
923     request->mask = put->mask;
924     request->mask_len = put->mask_len;
925     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
926     request->actions = (put->actions
927                         ? put->actions
928                         : CONST_CAST(struct nlattr *, &dummy_action));
929     request->actions_len = put->actions_len;
930     if (put->flags & DPIF_FP_ZERO_STATS) {
931         request->clear = true;
932     }
933     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
934 }
935
936 static int
937 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
938 {
939     struct dpif_linux_flow request, reply;
940     struct ofpbuf *buf;
941     int error;
942
943     dpif_linux_init_flow_put(dpif_, put, &request);
944     error = dpif_linux_flow_transact(&request,
945                                      put->stats ? &reply : NULL,
946                                      put->stats ? &buf : NULL);
947     if (!error && put->stats) {
948         dpif_linux_flow_get_stats(&reply, put->stats);
949         ofpbuf_delete(buf);
950     }
951     return error;
952 }
953
954 static void
955 dpif_linux_init_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del,
956                          struct dpif_linux_flow *request)
957 {
958     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
959
960     dpif_linux_flow_init(request);
961     request->cmd = OVS_FLOW_CMD_DEL;
962     request->dp_ifindex = dpif->dp_ifindex;
963     request->key = del->key;
964     request->key_len = del->key_len;
965 }
966
967 static int
968 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
969 {
970     struct dpif_linux_flow request, reply;
971     struct ofpbuf *buf;
972     int error;
973
974     dpif_linux_init_flow_del(dpif_, del, &request);
975     error = dpif_linux_flow_transact(&request,
976                                      del->stats ? &reply : NULL,
977                                      del->stats ? &buf : NULL);
978     if (!error && del->stats) {
979         dpif_linux_flow_get_stats(&reply, del->stats);
980         ofpbuf_delete(buf);
981     }
982     return error;
983 }
984
985 struct dpif_linux_flow_state {
986     struct nl_dump dump;
987     struct dpif_linux_flow flow;
988     struct dpif_flow_stats stats;
989     struct ofpbuf *buf;
990 };
991
992 static int
993 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
994 {
995     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
996     struct dpif_linux_flow_state *state;
997     struct dpif_linux_flow request;
998     struct ofpbuf *buf;
999
1000     *statep = state = xmalloc(sizeof *state);
1001
1002     dpif_linux_flow_init(&request);
1003     request.cmd = OVS_FLOW_CMD_GET;
1004     request.dp_ifindex = dpif->dp_ifindex;
1005
1006     buf = ofpbuf_new(1024);
1007     dpif_linux_flow_to_ofpbuf(&request, buf);
1008     nl_dump_start(&state->dump, NETLINK_GENERIC, buf);
1009     ofpbuf_delete(buf);
1010
1011     state->buf = NULL;
1012
1013     return 0;
1014 }
1015
1016 static int
1017 dpif_linux_flow_dump_next(const struct dpif *dpif_, void *state_,
1018                           const struct nlattr **key, size_t *key_len,
1019                           const struct nlattr **mask, size_t *mask_len,
1020                           const struct nlattr **actions, size_t *actions_len,
1021                           const struct dpif_flow_stats **stats)
1022 {
1023     struct dpif_linux_flow_state *state = state_;
1024     struct ofpbuf buf;
1025     int error;
1026
1027     do {
1028         ofpbuf_delete(state->buf);
1029         state->buf = NULL;
1030
1031         if (!nl_dump_next(&state->dump, &buf)) {
1032             return EOF;
1033         }
1034
1035         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
1036         if (error) {
1037             return error;
1038         }
1039
1040         if (actions && !state->flow.actions) {
1041             error = dpif_linux_flow_get__(dpif_, state->flow.key,
1042                                           state->flow.key_len,
1043                                           &state->flow, &state->buf);
1044             if (error == ENOENT) {
1045                 VLOG_DBG("dumped flow disappeared on get");
1046             } else if (error) {
1047                 VLOG_WARN("error fetching dumped flow: %s",
1048                           ovs_strerror(error));
1049             }
1050         }
1051     } while (error);
1052
1053     if (actions) {
1054         *actions = state->flow.actions;
1055         *actions_len = state->flow.actions_len;
1056     }
1057     if (key) {
1058         *key = state->flow.key;
1059         *key_len = state->flow.key_len;
1060     }
1061     if (mask) {
1062         *mask = state->flow.mask;
1063         *mask_len = state->flow.mask ? state->flow.mask_len : 0;
1064     }
1065     if (stats) {
1066         dpif_linux_flow_get_stats(&state->flow, &state->stats);
1067         *stats = &state->stats;
1068     }
1069     return error;
1070 }
1071
1072 static int
1073 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
1074 {
1075     struct dpif_linux_flow_state *state = state_;
1076     int error = nl_dump_done(&state->dump);
1077     ofpbuf_delete(state->buf);
1078     free(state);
1079     return error;
1080 }
1081
1082 static void
1083 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1084                           struct ofpbuf *buf)
1085 {
1086     struct ovs_header *k_exec;
1087     size_t key_ofs;
1088
1089     ofpbuf_prealloc_tailroom(buf, (64
1090                                    + d_exec->packet->size
1091                                    + ODP_KEY_METADATA_SIZE
1092                                    + d_exec->actions_len));
1093
1094     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1095                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1096
1097     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1098     k_exec->dp_ifindex = dp_ifindex;
1099
1100     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1101                       d_exec->packet->data, d_exec->packet->size);
1102
1103     key_ofs = nl_msg_start_nested(buf, OVS_PACKET_ATTR_KEY);
1104     odp_key_from_pkt_metadata(buf, &d_exec->md);
1105     nl_msg_end_nested(buf, key_ofs);
1106
1107     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1108                       d_exec->actions, d_exec->actions_len);
1109 }
1110
1111 static int
1112 dpif_linux_execute__(int dp_ifindex, const struct dpif_execute *execute)
1113 {
1114     uint64_t request_stub[1024 / 8];
1115     struct ofpbuf request;
1116     int error;
1117
1118     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1119     dpif_linux_encode_execute(dp_ifindex, execute, &request);
1120     error = nl_transact(NETLINK_GENERIC, &request, NULL);
1121     ofpbuf_uninit(&request);
1122
1123     return error;
1124 }
1125
1126 static int
1127 dpif_linux_execute(struct dpif *dpif_, struct dpif_execute *execute)
1128 {
1129     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1130
1131     return dpif_linux_execute__(dpif->dp_ifindex, execute);
1132 }
1133
1134 #define MAX_OPS 50
1135
1136 static void
1137 dpif_linux_operate__(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1138 {
1139     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1140
1141     struct op_auxdata {
1142         struct nl_transaction txn;
1143
1144         struct ofpbuf request;
1145         uint64_t request_stub[1024 / 8];
1146
1147         struct ofpbuf reply;
1148         uint64_t reply_stub[1024 / 8];
1149     } auxes[MAX_OPS];
1150
1151     struct nl_transaction *txnsp[MAX_OPS];
1152     size_t i;
1153
1154     ovs_assert(n_ops <= MAX_OPS);
1155     for (i = 0; i < n_ops; i++) {
1156         struct op_auxdata *aux = &auxes[i];
1157         struct dpif_op *op = ops[i];
1158         struct dpif_flow_put *put;
1159         struct dpif_flow_del *del;
1160         struct dpif_execute *execute;
1161         struct dpif_linux_flow flow;
1162
1163         ofpbuf_use_stub(&aux->request,
1164                         aux->request_stub, sizeof aux->request_stub);
1165         aux->txn.request = &aux->request;
1166
1167         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1168         aux->txn.reply = NULL;
1169
1170         switch (op->type) {
1171         case DPIF_OP_FLOW_PUT:
1172             put = &op->u.flow_put;
1173             dpif_linux_init_flow_put(dpif_, put, &flow);
1174             if (put->stats) {
1175                 flow.nlmsg_flags |= NLM_F_ECHO;
1176                 aux->txn.reply = &aux->reply;
1177             }
1178             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1179             break;
1180
1181         case DPIF_OP_FLOW_DEL:
1182             del = &op->u.flow_del;
1183             dpif_linux_init_flow_del(dpif_, del, &flow);
1184             if (del->stats) {
1185                 flow.nlmsg_flags |= NLM_F_ECHO;
1186                 aux->txn.reply = &aux->reply;
1187             }
1188             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1189             break;
1190
1191         case DPIF_OP_EXECUTE:
1192             execute = &op->u.execute;
1193             dpif_linux_encode_execute(dpif->dp_ifindex, execute,
1194                                       &aux->request);
1195             break;
1196
1197         default:
1198             OVS_NOT_REACHED();
1199         }
1200     }
1201
1202     for (i = 0; i < n_ops; i++) {
1203         txnsp[i] = &auxes[i].txn;
1204     }
1205     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1206
1207     for (i = 0; i < n_ops; i++) {
1208         struct op_auxdata *aux = &auxes[i];
1209         struct nl_transaction *txn = &auxes[i].txn;
1210         struct dpif_op *op = ops[i];
1211         struct dpif_flow_put *put;
1212         struct dpif_flow_del *del;
1213
1214         op->error = txn->error;
1215
1216         switch (op->type) {
1217         case DPIF_OP_FLOW_PUT:
1218             put = &op->u.flow_put;
1219             if (put->stats) {
1220                 if (!op->error) {
1221                     struct dpif_linux_flow reply;
1222
1223                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1224                                                             txn->reply);
1225                     if (!op->error) {
1226                         dpif_linux_flow_get_stats(&reply, put->stats);
1227                     }
1228                 }
1229
1230                 if (op->error) {
1231                     memset(put->stats, 0, sizeof *put->stats);
1232                 }
1233             }
1234             break;
1235
1236         case DPIF_OP_FLOW_DEL:
1237             del = &op->u.flow_del;
1238             if (del->stats) {
1239                 if (!op->error) {
1240                     struct dpif_linux_flow reply;
1241
1242                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1243                                                             txn->reply);
1244                     if (!op->error) {
1245                         dpif_linux_flow_get_stats(&reply, del->stats);
1246                     }
1247                 }
1248
1249                 if (op->error) {
1250                     memset(del->stats, 0, sizeof *del->stats);
1251                 }
1252             }
1253             break;
1254
1255         case DPIF_OP_EXECUTE:
1256             break;
1257
1258         default:
1259             OVS_NOT_REACHED();
1260         }
1261
1262         ofpbuf_uninit(&aux->request);
1263         ofpbuf_uninit(&aux->reply);
1264     }
1265 }
1266
1267 static void
1268 dpif_linux_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1269 {
1270     while (n_ops > 0) {
1271         size_t chunk = MIN(n_ops, MAX_OPS);
1272         dpif_linux_operate__(dpif, ops, chunk);
1273         ops += chunk;
1274         n_ops -= chunk;
1275     }
1276 }
1277
1278 /* Synchronizes 'dpif->channels' with the set of vports currently in 'dpif' in
1279  * the kernel, by adding a new channel for any kernel vport that lacks one and
1280  * deleting any channels that have no backing kernel vports. */
1281 static int
1282 dpif_linux_refresh_channels(struct dpif *dpif_)
1283 {
1284     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1285     unsigned long int *keep_channels;
1286     struct dpif_linux_vport vport;
1287     size_t keep_channels_nbits;
1288     struct nl_dump dump;
1289     int retval = 0;
1290     size_t i;
1291
1292     /* To start with, we need an epoll fd. */
1293     if (dpif->epoll_fd < 0) {
1294         dpif->epoll_fd = epoll_create(10);
1295         if (dpif->epoll_fd < 0) {
1296             return errno;
1297         }
1298     }
1299
1300     keep_channels_nbits = dpif->uc_array_size;
1301     keep_channels = bitmap_allocate(keep_channels_nbits);
1302
1303     dpif->n_events = dpif->event_offset = 0;
1304
1305     dpif_linux_port_dump_start__(dpif_, &dump);
1306     while (!dpif_linux_port_dump_next__(dpif_, &dump, &vport)) {
1307         uint32_t port_no = odp_to_u32(vport.port_no);
1308         struct nl_sock *sock = (port_no < dpif->uc_array_size
1309                                 ? dpif->channels[port_no].sock
1310                                 : NULL);
1311         bool new_sock = !sock;
1312         int error;
1313
1314         if (new_sock) {
1315             error = nl_sock_create(NETLINK_GENERIC, &sock);
1316             if (error) {
1317                 retval = error;
1318                 goto error;
1319             }
1320         }
1321
1322         /* Configure the vport to deliver misses to 'sock'. */
1323         if (!vport.upcall_pid || *vport.upcall_pid != nl_sock_pid(sock)) {
1324             uint32_t upcall_pid = nl_sock_pid(sock);
1325             struct dpif_linux_vport vport_request;
1326
1327             dpif_linux_vport_init(&vport_request);
1328             vport_request.cmd = OVS_VPORT_CMD_SET;
1329             vport_request.dp_ifindex = dpif->dp_ifindex;
1330             vport_request.port_no = vport.port_no;
1331             vport_request.upcall_pid = &upcall_pid;
1332             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1333             if (!error) {
1334                 VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
1335                          dpif_name(&dpif->dpif), vport_request.port_no,
1336                          upcall_pid);
1337             } else {
1338                 VLOG_WARN_RL(&error_rl,
1339                              "%s: failed to set upcall pid on port: %s",
1340                              dpif_name(&dpif->dpif), ovs_strerror(error));
1341
1342                 if (error != ENODEV && error != ENOENT) {
1343                     retval = error;
1344                 } else {
1345                     /* The vport isn't really there, even though the dump says
1346                      * it is.  Probably we just hit a race after a port
1347                      * disappeared. */
1348                 }
1349                 goto error;
1350             }
1351         }
1352
1353         if (new_sock) {
1354             error = add_channel(dpif, vport.port_no, sock);
1355             if (error) {
1356                 VLOG_INFO("%s: could not add channel for port %s",
1357                           dpif_name(dpif_), vport.name);
1358                 retval = error;
1359                 goto error;
1360             }
1361         }
1362
1363         if (port_no < keep_channels_nbits) {
1364             bitmap_set1(keep_channels, port_no);
1365         }
1366         continue;
1367
1368     error:
1369         nl_sock_destroy(sock);
1370     }
1371     nl_dump_done(&dump);
1372
1373     /* Discard any saved channels that we didn't reuse. */
1374     for (i = 0; i < keep_channels_nbits; i++) {
1375         if (!bitmap_is_set(keep_channels, i)) {
1376             nl_sock_destroy(dpif->channels[i].sock);
1377             dpif->channels[i].sock = NULL;
1378         }
1379     }
1380     free(keep_channels);
1381
1382     return retval;
1383 }
1384
1385 static int
1386 dpif_linux_recv_set__(struct dpif *dpif_, bool enable)
1387 {
1388     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1389
1390     if ((dpif->epoll_fd >= 0) == enable) {
1391         return 0;
1392     } else if (!enable) {
1393         destroy_channels(dpif);
1394         return 0;
1395     } else {
1396         return dpif_linux_refresh_channels(dpif_);
1397     }
1398 }
1399
1400 static int
1401 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1402 {
1403     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1404     int error;
1405
1406     ovs_mutex_lock(&dpif->upcall_lock);
1407     error = dpif_linux_recv_set__(dpif_, enable);
1408     ovs_mutex_unlock(&dpif->upcall_lock);
1409
1410     return error;
1411 }
1412
1413 static int
1414 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1415                              uint32_t queue_id, uint32_t *priority)
1416 {
1417     if (queue_id < 0xf000) {
1418         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1419         return 0;
1420     } else {
1421         return EINVAL;
1422     }
1423 }
1424
1425 static int
1426 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1427                  int *dp_ifindex)
1428 {
1429     static const struct nl_policy ovs_packet_policy[] = {
1430         /* Always present. */
1431         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1432                                      .min_len = ETH_HEADER_LEN },
1433         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1434
1435         /* OVS_PACKET_CMD_ACTION only. */
1436         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1437     };
1438
1439     struct ovs_header *ovs_header;
1440     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1441     struct nlmsghdr *nlmsg;
1442     struct genlmsghdr *genl;
1443     struct ofpbuf b;
1444     int type;
1445
1446     ofpbuf_use_const(&b, buf->data, buf->size);
1447
1448     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1449     genl = ofpbuf_try_pull(&b, sizeof *genl);
1450     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1451     if (!nlmsg || !genl || !ovs_header
1452         || nlmsg->nlmsg_type != ovs_packet_family
1453         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1454                             ARRAY_SIZE(ovs_packet_policy))) {
1455         return EINVAL;
1456     }
1457
1458     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1459             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1460             : -1);
1461     if (type < 0) {
1462         return EINVAL;
1463     }
1464
1465     /* (Re)set ALL fields of '*upcall' on successful return. */
1466     upcall->type = type;
1467     upcall->key = CONST_CAST(struct nlattr *,
1468                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1469     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1470     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1471
1472     /* Allow overwriting the netlink attribute header without reallocating. */
1473     ofpbuf_use_stub(&upcall->packet,
1474                     CONST_CAST(struct nlattr *,
1475                                nl_attr_get(a[OVS_PACKET_ATTR_PACKET])) - 1,
1476                     nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]) +
1477                     sizeof(struct nlattr));
1478     upcall->packet.data = (char *)upcall->packet.data + sizeof(struct nlattr);
1479     upcall->packet.size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1480
1481     *dp_ifindex = ovs_header->dp_ifindex;
1482
1483     return 0;
1484 }
1485
1486 static int
1487 dpif_linux_recv__(struct dpif *dpif_, struct dpif_upcall *upcall,
1488                   struct ofpbuf *buf)
1489 {
1490     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1491     int read_tries = 0;
1492
1493     if (dpif->epoll_fd < 0) {
1494        return EAGAIN;
1495     }
1496
1497     if (dpif->event_offset >= dpif->n_events) {
1498         int retval;
1499
1500         dpif->event_offset = dpif->n_events = 0;
1501
1502         do {
1503             retval = epoll_wait(dpif->epoll_fd, dpif->epoll_events,
1504                                 dpif->uc_array_size, 0);
1505         } while (retval < 0 && errno == EINTR);
1506         if (retval < 0) {
1507             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1508             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
1509         } else if (retval > 0) {
1510             dpif->n_events = retval;
1511         }
1512     }
1513
1514     while (dpif->event_offset < dpif->n_events) {
1515         int idx = dpif->epoll_events[dpif->event_offset].data.u32;
1516         struct dpif_channel *ch = &dpif->channels[idx];
1517
1518         dpif->event_offset++;
1519
1520         for (;;) {
1521             int dp_ifindex;
1522             int error;
1523
1524             if (++read_tries > 50) {
1525                 return EAGAIN;
1526             }
1527
1528             error = nl_sock_recv(ch->sock, buf, false);
1529             if (error == ENOBUFS) {
1530                 /* ENOBUFS typically means that we've received so many
1531                  * packets that the buffer overflowed.  Try again
1532                  * immediately because there's almost certainly a packet
1533                  * waiting for us. */
1534                 report_loss(dpif_, ch);
1535                 continue;
1536             }
1537
1538             ch->last_poll = time_msec();
1539             if (error) {
1540                 if (error == EAGAIN) {
1541                     break;
1542                 }
1543                 return error;
1544             }
1545
1546             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1547             if (!error && dp_ifindex == dpif->dp_ifindex) {
1548                 return 0;
1549             } else if (error) {
1550                 return error;
1551             }
1552         }
1553     }
1554
1555     return EAGAIN;
1556 }
1557
1558 static int
1559 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1560                 struct ofpbuf *buf)
1561 {
1562     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1563     int error;
1564
1565     ovs_mutex_lock(&dpif->upcall_lock);
1566     error = dpif_linux_recv__(dpif_, upcall, buf);
1567     ovs_mutex_unlock(&dpif->upcall_lock);
1568
1569     return error;
1570 }
1571
1572 static void
1573 dpif_linux_recv_wait(struct dpif *dpif_)
1574 {
1575     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1576
1577     ovs_mutex_lock(&dpif->upcall_lock);
1578     if (dpif->epoll_fd >= 0) {
1579         poll_fd_wait(dpif->epoll_fd, POLLIN);
1580     }
1581     ovs_mutex_unlock(&dpif->upcall_lock);
1582 }
1583
1584 static void
1585 dpif_linux_recv_purge(struct dpif *dpif_)
1586 {
1587     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1588
1589     ovs_mutex_lock(&dpif->upcall_lock);
1590     if (dpif->epoll_fd >= 0) {
1591         struct dpif_channel *ch;
1592
1593         for (ch = dpif->channels; ch < &dpif->channels[dpif->uc_array_size];
1594              ch++) {
1595             if (ch->sock) {
1596                 nl_sock_drain(ch->sock);
1597             }
1598         }
1599     }
1600     ovs_mutex_unlock(&dpif->upcall_lock);
1601 }
1602
1603 const struct dpif_class dpif_linux_class = {
1604     "system",
1605     dpif_linux_enumerate,
1606     NULL,
1607     dpif_linux_open,
1608     dpif_linux_close,
1609     dpif_linux_destroy,
1610     dpif_linux_run,
1611     NULL,                       /* wait */
1612     dpif_linux_get_stats,
1613     dpif_linux_port_add,
1614     dpif_linux_port_del,
1615     dpif_linux_port_query_by_number,
1616     dpif_linux_port_query_by_name,
1617     dpif_linux_port_get_pid,
1618     dpif_linux_port_dump_start,
1619     dpif_linux_port_dump_next,
1620     dpif_linux_port_dump_done,
1621     dpif_linux_port_poll,
1622     dpif_linux_port_poll_wait,
1623     dpif_linux_flow_get,
1624     dpif_linux_flow_put,
1625     dpif_linux_flow_del,
1626     dpif_linux_flow_flush,
1627     dpif_linux_flow_dump_start,
1628     dpif_linux_flow_dump_next,
1629     dpif_linux_flow_dump_done,
1630     dpif_linux_execute,
1631     dpif_linux_operate,
1632     dpif_linux_recv_set,
1633     dpif_linux_queue_to_priority,
1634     dpif_linux_recv,
1635     dpif_linux_recv_wait,
1636     dpif_linux_recv_purge,
1637 };
1638 \f
1639 static int
1640 dpif_linux_init(void)
1641 {
1642     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1643     static int error;
1644
1645     if (ovsthread_once_start(&once)) {
1646         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1647                                       &ovs_datapath_family);
1648         if (error) {
1649             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1650                      "The Open vSwitch kernel module is probably not loaded.",
1651                      OVS_DATAPATH_FAMILY);
1652         }
1653         if (!error) {
1654             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1655         }
1656         if (!error) {
1657             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1658         }
1659         if (!error) {
1660             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1661                                           &ovs_packet_family);
1662         }
1663         if (!error) {
1664             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1665                                            &ovs_vport_mcgroup);
1666         }
1667
1668         ovsthread_once_done(&once);
1669     }
1670
1671     return error;
1672 }
1673
1674 bool
1675 dpif_linux_is_internal_device(const char *name)
1676 {
1677     struct dpif_linux_vport reply;
1678     struct ofpbuf *buf;
1679     int error;
1680
1681     error = dpif_linux_vport_get(name, &reply, &buf);
1682     if (!error) {
1683         ofpbuf_delete(buf);
1684     } else if (error != ENODEV && error != ENOENT) {
1685         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1686                      name, ovs_strerror(error));
1687     }
1688
1689     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1690 }
1691 \f
1692 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1693  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1694  * positive errno value.
1695  *
1696  * 'vport' will contain pointers into 'buf', so the caller should not free
1697  * 'buf' while 'vport' is still in use. */
1698 static int
1699 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1700                              const struct ofpbuf *buf)
1701 {
1702     static const struct nl_policy ovs_vport_policy[] = {
1703         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1704         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1705         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1706         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1707         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1708                                    .optional = true },
1709         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1710     };
1711
1712     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1713     struct ovs_header *ovs_header;
1714     struct nlmsghdr *nlmsg;
1715     struct genlmsghdr *genl;
1716     struct ofpbuf b;
1717
1718     dpif_linux_vport_init(vport);
1719
1720     ofpbuf_use_const(&b, buf->data, buf->size);
1721     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1722     genl = ofpbuf_try_pull(&b, sizeof *genl);
1723     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1724     if (!nlmsg || !genl || !ovs_header
1725         || nlmsg->nlmsg_type != ovs_vport_family
1726         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1727                             ARRAY_SIZE(ovs_vport_policy))) {
1728         return EINVAL;
1729     }
1730
1731     vport->cmd = genl->cmd;
1732     vport->dp_ifindex = ovs_header->dp_ifindex;
1733     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
1734     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1735     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1736     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1737         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1738     }
1739     if (a[OVS_VPORT_ATTR_STATS]) {
1740         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1741     }
1742     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1743         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1744         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1745     }
1746     return 0;
1747 }
1748
1749 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1750  * followed by Netlink attributes corresponding to 'vport'. */
1751 static void
1752 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1753                            struct ofpbuf *buf)
1754 {
1755     struct ovs_header *ovs_header;
1756
1757     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1758                           vport->cmd, OVS_VPORT_VERSION);
1759
1760     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1761     ovs_header->dp_ifindex = vport->dp_ifindex;
1762
1763     if (vport->port_no != ODPP_NONE) {
1764         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1765     }
1766
1767     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1768         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1769     }
1770
1771     if (vport->name) {
1772         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1773     }
1774
1775     if (vport->upcall_pid) {
1776         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1777     }
1778
1779     if (vport->stats) {
1780         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1781                           vport->stats, sizeof *vport->stats);
1782     }
1783
1784     if (vport->options) {
1785         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1786                           vport->options, vport->options_len);
1787     }
1788 }
1789
1790 /* Clears 'vport' to "empty" values. */
1791 void
1792 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1793 {
1794     memset(vport, 0, sizeof *vport);
1795     vport->port_no = ODPP_NONE;
1796 }
1797
1798 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1799  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1800  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1801  * result of the command is expected to be an ovs_vport also, which is decoded
1802  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1803  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1804 int
1805 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1806                           struct dpif_linux_vport *reply,
1807                           struct ofpbuf **bufp)
1808 {
1809     struct ofpbuf *request_buf;
1810     int error;
1811
1812     ovs_assert((reply != NULL) == (bufp != NULL));
1813
1814     error = dpif_linux_init();
1815     if (error) {
1816         if (reply) {
1817             *bufp = NULL;
1818             dpif_linux_vport_init(reply);
1819         }
1820         return error;
1821     }
1822
1823     request_buf = ofpbuf_new(1024);
1824     dpif_linux_vport_to_ofpbuf(request, request_buf);
1825     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1826     ofpbuf_delete(request_buf);
1827
1828     if (reply) {
1829         if (!error) {
1830             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1831         }
1832         if (error) {
1833             dpif_linux_vport_init(reply);
1834             ofpbuf_delete(*bufp);
1835             *bufp = NULL;
1836         }
1837     }
1838     return error;
1839 }
1840
1841 /* Obtains information about the kernel vport named 'name' and stores it into
1842  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1843  * longer needed ('reply' will contain pointers into '*bufp').  */
1844 int
1845 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1846                      struct ofpbuf **bufp)
1847 {
1848     struct dpif_linux_vport request;
1849
1850     dpif_linux_vport_init(&request);
1851     request.cmd = OVS_VPORT_CMD_GET;
1852     request.name = name;
1853
1854     return dpif_linux_vport_transact(&request, reply, bufp);
1855 }
1856 \f
1857 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1858  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1859  * positive errno value.
1860  *
1861  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1862  * while 'dp' is still in use. */
1863 static int
1864 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1865 {
1866     static const struct nl_policy ovs_datapath_policy[] = {
1867         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1868         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1869                                 .optional = true },
1870         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
1871                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
1872                         .optional = true },
1873     };
1874
1875     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1876     struct ovs_header *ovs_header;
1877     struct nlmsghdr *nlmsg;
1878     struct genlmsghdr *genl;
1879     struct ofpbuf b;
1880
1881     dpif_linux_dp_init(dp);
1882
1883     ofpbuf_use_const(&b, buf->data, buf->size);
1884     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1885     genl = ofpbuf_try_pull(&b, sizeof *genl);
1886     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1887     if (!nlmsg || !genl || !ovs_header
1888         || nlmsg->nlmsg_type != ovs_datapath_family
1889         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1890                             ARRAY_SIZE(ovs_datapath_policy))) {
1891         return EINVAL;
1892     }
1893
1894     dp->cmd = genl->cmd;
1895     dp->dp_ifindex = ovs_header->dp_ifindex;
1896     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1897     if (a[OVS_DP_ATTR_STATS]) {
1898         /* Can't use structure assignment because Netlink doesn't ensure
1899          * sufficient alignment for 64-bit members. */
1900         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1901                sizeof dp->stats);
1902     }
1903
1904     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
1905         /* Can't use structure assignment because Netlink doesn't ensure
1906          * sufficient alignment for 64-bit members. */
1907         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
1908                sizeof dp->megaflow_stats);
1909     }
1910
1911     return 0;
1912 }
1913
1914 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1915 static void
1916 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1917 {
1918     struct ovs_header *ovs_header;
1919
1920     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1921                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1922                           OVS_DATAPATH_VERSION);
1923
1924     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1925     ovs_header->dp_ifindex = dp->dp_ifindex;
1926
1927     if (dp->name) {
1928         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1929     }
1930
1931     if (dp->upcall_pid) {
1932         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1933     }
1934
1935     if (dp->user_features) {
1936         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
1937     }
1938
1939     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1940 }
1941
1942 /* Clears 'dp' to "empty" values. */
1943 static void
1944 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1945 {
1946     memset(dp, 0, sizeof *dp);
1947     dp->megaflow_stats.n_masks = UINT32_MAX;
1948     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
1949 }
1950
1951 static void
1952 dpif_linux_dp_dump_start(struct nl_dump *dump)
1953 {
1954     struct dpif_linux_dp request;
1955     struct ofpbuf *buf;
1956
1957     dpif_linux_dp_init(&request);
1958     request.cmd = OVS_DP_CMD_GET;
1959
1960     buf = ofpbuf_new(1024);
1961     dpif_linux_dp_to_ofpbuf(&request, buf);
1962     nl_dump_start(dump, NETLINK_GENERIC, buf);
1963     ofpbuf_delete(buf);
1964 }
1965
1966 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1967  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1968  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1969  * result of the command is expected to be of the same form, which is decoded
1970  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1971  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1972 static int
1973 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1974                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1975 {
1976     struct ofpbuf *request_buf;
1977     int error;
1978
1979     ovs_assert((reply != NULL) == (bufp != NULL));
1980
1981     request_buf = ofpbuf_new(1024);
1982     dpif_linux_dp_to_ofpbuf(request, request_buf);
1983     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
1984     ofpbuf_delete(request_buf);
1985
1986     if (reply) {
1987         dpif_linux_dp_init(reply);
1988         if (!error) {
1989             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1990         }
1991         if (error) {
1992             ofpbuf_delete(*bufp);
1993             *bufp = NULL;
1994         }
1995     }
1996     return error;
1997 }
1998
1999 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
2000  * The caller must free '*bufp' when the reply is no longer needed ('reply'
2001  * will contain pointers into '*bufp').  */
2002 static int
2003 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
2004                   struct ofpbuf **bufp)
2005 {
2006     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2007     struct dpif_linux_dp request;
2008
2009     dpif_linux_dp_init(&request);
2010     request.cmd = OVS_DP_CMD_GET;
2011     request.dp_ifindex = dpif->dp_ifindex;
2012
2013     return dpif_linux_dp_transact(&request, reply, bufp);
2014 }
2015 \f
2016 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2017  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2018  * positive errno value.
2019  *
2020  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2021  * while 'flow' is still in use. */
2022 static int
2023 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
2024                             const struct ofpbuf *buf)
2025 {
2026     static const struct nl_policy ovs_flow_policy[] = {
2027         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
2028         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2029         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2030         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2031                                   .optional = true },
2032         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2033         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2034         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2035     };
2036
2037     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2038     struct ovs_header *ovs_header;
2039     struct nlmsghdr *nlmsg;
2040     struct genlmsghdr *genl;
2041     struct ofpbuf b;
2042
2043     dpif_linux_flow_init(flow);
2044
2045     ofpbuf_use_const(&b, buf->data, buf->size);
2046     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2047     genl = ofpbuf_try_pull(&b, sizeof *genl);
2048     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2049     if (!nlmsg || !genl || !ovs_header
2050         || nlmsg->nlmsg_type != ovs_flow_family
2051         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2052                             ARRAY_SIZE(ovs_flow_policy))) {
2053         return EINVAL;
2054     }
2055
2056     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2057     flow->dp_ifindex = ovs_header->dp_ifindex;
2058     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2059     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2060
2061     if (a[OVS_FLOW_ATTR_MASK]) {
2062         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2063         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2064     }
2065     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2066         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2067         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2068     }
2069     if (a[OVS_FLOW_ATTR_STATS]) {
2070         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2071     }
2072     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2073         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2074     }
2075     if (a[OVS_FLOW_ATTR_USED]) {
2076         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2077     }
2078     return 0;
2079 }
2080
2081 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2082  * followed by Netlink attributes corresponding to 'flow'. */
2083 static void
2084 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
2085                           struct ofpbuf *buf)
2086 {
2087     struct ovs_header *ovs_header;
2088
2089     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2090                           NLM_F_REQUEST | flow->nlmsg_flags,
2091                           flow->cmd, OVS_FLOW_VERSION);
2092
2093     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2094     ovs_header->dp_ifindex = flow->dp_ifindex;
2095
2096     if (flow->key_len) {
2097         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2098     }
2099
2100     if (flow->mask_len) {
2101         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2102     }
2103
2104     if (flow->actions || flow->actions_len) {
2105         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2106                           flow->actions, flow->actions_len);
2107     }
2108
2109     /* We never need to send these to the kernel. */
2110     ovs_assert(!flow->stats);
2111     ovs_assert(!flow->tcp_flags);
2112     ovs_assert(!flow->used);
2113
2114     if (flow->clear) {
2115         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2116     }
2117 }
2118
2119 /* Clears 'flow' to "empty" values. */
2120 static void
2121 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2122 {
2123     memset(flow, 0, sizeof *flow);
2124 }
2125
2126 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2127  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2128  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2129  * result of the command is expected to be a flow also, which is decoded and
2130  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2131  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2132 static int
2133 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2134                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2135 {
2136     struct ofpbuf *request_buf;
2137     int error;
2138
2139     ovs_assert((reply != NULL) == (bufp != NULL));
2140
2141     if (reply) {
2142         request->nlmsg_flags |= NLM_F_ECHO;
2143     }
2144
2145     request_buf = ofpbuf_new(1024);
2146     dpif_linux_flow_to_ofpbuf(request, request_buf);
2147     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2148     ofpbuf_delete(request_buf);
2149
2150     if (reply) {
2151         if (!error) {
2152             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2153         }
2154         if (error) {
2155             dpif_linux_flow_init(reply);
2156             ofpbuf_delete(*bufp);
2157             *bufp = NULL;
2158         }
2159     }
2160     return error;
2161 }
2162
2163 static void
2164 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2165                           struct dpif_flow_stats *stats)
2166 {
2167     if (flow->stats) {
2168         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2169         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2170     } else {
2171         stats->n_packets = 0;
2172         stats->n_bytes = 0;
2173     }
2174     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2175     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2176 }
2177 \f
2178 /* Logs information about a packet that was recently lost in 'ch' (in
2179  * 'dpif_'). */
2180 static void
2181 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
2182 {
2183     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2184     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2185     struct ds s;
2186
2187     if (VLOG_DROP_WARN(&rl)) {
2188         return;
2189     }
2190
2191     ds_init(&s);
2192     if (ch->last_poll != LLONG_MIN) {
2193         ds_put_format(&s, " (last polled %lld ms ago)",
2194                       time_msec() - ch->last_poll);
2195     }
2196
2197     VLOG_WARN("%s: lost packet on channel %"PRIdPTR"%s",
2198               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2199     ds_destroy(&s);
2200 }