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