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