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