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