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