dpif-linux: Minor style fixes.
[cascardo/ovs.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "dpif-linux.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/types.h>
27 #include <linux/pkt_sched.h>
28 #include <poll.h>
29 #include <stdlib.h>
30 #include <strings.h>
31 #include <sys/epoll.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34
35 #include "bitmap.h"
36 #include "dpif-provider.h"
37 #include "dynamic-string.h"
38 #include "flow.h"
39 #include "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                      const struct dpif_class *dpif_class OVS_UNUSED)
200 {
201     struct nl_dump dump;
202     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
203     struct ofpbuf msg, buf;
204     int error;
205
206     error = dpif_linux_init();
207     if (error) {
208         return error;
209     }
210
211     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
212     dpif_linux_dp_dump_start(&dump);
213     while (nl_dump_next(&dump, &msg, &buf)) {
214         struct dpif_linux_dp dp;
215
216         if (!dpif_linux_dp_from_ofpbuf(&dp, &msg)) {
217             sset_add(all_dps, dp.name);
218         }
219     }
220     ofpbuf_uninit(&buf);
221     return nl_dump_done(&dump);
222 }
223
224 static int
225 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
226                 bool create, struct dpif **dpifp)
227 {
228     struct dpif_linux_dp dp_request, dp;
229     struct ofpbuf *buf;
230     uint32_t upcall_pid;
231     int error;
232
233     error = dpif_linux_init();
234     if (error) {
235         return error;
236     }
237
238     /* Create or look up datapath. */
239     dpif_linux_dp_init(&dp_request);
240     if (create) {
241         dp_request.cmd = OVS_DP_CMD_NEW;
242         upcall_pid = 0;
243         dp_request.upcall_pid = &upcall_pid;
244     } else {
245         /* Use OVS_DP_CMD_SET to report user features */
246         dp_request.cmd = OVS_DP_CMD_SET;
247     }
248     dp_request.name = name;
249     dp_request.user_features |= OVS_DP_F_UNALIGNED;
250     dp_request.user_features |= OVS_DP_F_VPORT_PIDS;
251     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
252     if (error) {
253         return error;
254     }
255
256     error = open_dpif(&dp, dpifp);
257     ofpbuf_delete(buf);
258     return error;
259 }
260
261 static int
262 open_dpif(const struct dpif_linux_dp *dp, struct dpif **dpifp)
263 {
264     struct dpif_linux *dpif;
265
266     dpif = xzalloc(sizeof *dpif);
267     dpif->port_notifier = NULL;
268     fat_rwlock_init(&dpif->upcall_lock);
269
270     dpif_init(&dpif->dpif, &dpif_linux_class, dp->name,
271               dp->dp_ifindex, dp->dp_ifindex);
272
273     dpif->dp_ifindex = dp->dp_ifindex;
274     *dpifp = &dpif->dpif;
275
276     return 0;
277 }
278
279 /* Destroys the netlink sockets pointed by the elements in 'socksp'
280  * and frees the 'socksp'.  */
281 static void
282 vport_del_socksp(struct nl_sock **socksp, uint32_t n_socks)
283 {
284     size_t i;
285
286     for (i = 0; i < n_socks; i++) {
287         nl_sock_destroy(socksp[i]);
288     }
289
290     free(socksp);
291 }
292
293 /* Creates an array of netlink sockets.  Returns an array of the
294  * corresponding pointers.  Records the error in 'error'. */
295 static struct nl_sock **
296 vport_create_socksp(uint32_t n_socks, int *error)
297 {
298     struct nl_sock **socksp = xzalloc(n_socks * sizeof *socksp);
299     size_t i;
300
301     for (i = 0; i < n_socks; i++) {
302         *error = nl_sock_create(NETLINK_GENERIC, &socksp[i]);
303         if (*error) {
304             goto error;
305         }
306     }
307
308     return socksp;
309
310 error:
311     vport_del_socksp(socksp, n_socks);
312
313     return NULL;
314 }
315
316 /* Given the array of pointers to netlink sockets 'socksp', returns
317  * the array of corresponding pids. If the 'socksp' is NULL, returns
318  * a single-element array of value 0. */
319 static uint32_t *
320 vport_socksp_to_pids(struct nl_sock **socksp, uint32_t n_socks)
321 {
322     uint32_t *pids;
323
324     if (!socksp) {
325         pids = xzalloc(sizeof *pids);
326     } else {
327         size_t i;
328
329         pids = xzalloc(n_socks * sizeof *pids);
330         for (i = 0; i < n_socks; i++) {
331             pids[i] = nl_sock_pid(socksp[i]);
332         }
333     }
334
335     return pids;
336 }
337
338 /* Given the port number 'port_idx', extracts the pids of netlink sockets
339  * associated to the port and assigns it to 'upcall_pids'. */
340 static bool
341 vport_get_pids(struct dpif_linux *dpif, uint32_t port_idx,
342                uint32_t **upcall_pids)
343 {
344     uint32_t *pids;
345     size_t i;
346
347     /* Since the nl_sock can only be assigned in either all
348      * or none "dpif->handlers" channels, the following check
349      * would suffice. */
350     if (!dpif->handlers[0].channels[port_idx].sock) {
351         return false;
352     }
353
354     pids = xzalloc(dpif->n_handlers * sizeof *pids);
355
356     for (i = 0; i < dpif->n_handlers; i++) {
357         pids[i] = nl_sock_pid(dpif->handlers[i].channels[port_idx].sock);
358     }
359
360     *upcall_pids = pids;
361
362     return true;
363 }
364
365 static int
366 vport_add_channels(struct dpif_linux *dpif, odp_port_t port_no,
367                    struct nl_sock **socksp)
368 {
369     struct epoll_event event;
370     uint32_t port_idx = odp_to_u32(port_no);
371     size_t i, j;
372     int error;
373
374     if (dpif->handlers == NULL) {
375         return 0;
376     }
377
378     /* We assume that the datapath densely chooses port numbers, which can
379      * therefore be used as an index into 'channels' and 'epoll_events' of
380      * 'dpif->handler'. */
381     if (port_idx >= dpif->uc_array_size) {
382         uint32_t new_size = port_idx + 1;
383
384         if (new_size > MAX_PORTS) {
385             VLOG_WARN_RL(&error_rl, "%s: datapath port %"PRIu32" too big",
386                          dpif_name(&dpif->dpif), port_no);
387             return EFBIG;
388         }
389
390         for (i = 0; i < dpif->n_handlers; i++) {
391             struct dpif_handler *handler = &dpif->handlers[i];
392
393             handler->channels = xrealloc(handler->channels,
394                                          new_size * sizeof *handler->channels);
395
396             for (j = dpif->uc_array_size; j < new_size; j++) {
397                 handler->channels[j].sock = NULL;
398             }
399
400             handler->epoll_events = xrealloc(handler->epoll_events,
401                 new_size * sizeof *handler->epoll_events);
402
403         }
404         dpif->uc_array_size = new_size;
405     }
406
407     memset(&event, 0, sizeof event);
408     event.events = EPOLLIN;
409     event.data.u32 = port_idx;
410
411     for (i = 0; i < dpif->n_handlers; i++) {
412         struct dpif_handler *handler = &dpif->handlers[i];
413
414         if (epoll_ctl(handler->epoll_fd, EPOLL_CTL_ADD, nl_sock_fd(socksp[i]),
415                       &event) < 0) {
416             error = errno;
417             goto error;
418         }
419         dpif->handlers[i].channels[port_idx].sock = socksp[i];
420         dpif->handlers[i].channels[port_idx].last_poll = LLONG_MIN;
421     }
422
423     return 0;
424
425 error:
426     for (j = 0; j < i; j++) {
427         epoll_ctl(dpif->handlers[j].epoll_fd, EPOLL_CTL_DEL,
428                   nl_sock_fd(socksp[j]), NULL);
429         dpif->handlers[j].channels[port_idx].sock = NULL;
430     }
431
432     return error;
433 }
434
435 static void
436 vport_del_channels(struct dpif_linux *dpif, odp_port_t port_no)
437 {
438     uint32_t port_idx = odp_to_u32(port_no);
439     size_t i;
440
441     if (!dpif->handlers || port_idx >= dpif->uc_array_size) {
442         return;
443     }
444
445     /* Since the sock can only be assigned in either all or none
446      * of "dpif->handlers" channels, the following check would
447      * suffice. */
448     if (!dpif->handlers[0].channels[port_idx].sock) {
449         return;
450     }
451
452     for (i = 0; i < dpif->n_handlers; i++) {
453         struct dpif_handler *handler = &dpif->handlers[i];
454
455         epoll_ctl(handler->epoll_fd, EPOLL_CTL_DEL,
456                   nl_sock_fd(handler->channels[port_idx].sock), NULL);
457         nl_sock_destroy(handler->channels[port_idx].sock);
458         handler->channels[port_idx].sock = NULL;
459         handler->event_offset = handler->n_events = 0;
460     }
461 }
462
463 static void
464 destroy_all_channels(struct dpif_linux *dpif) OVS_REQ_WRLOCK(dpif->upcall_lock)
465 {
466     unsigned int i;
467
468     if (!dpif->handlers) {
469         return;
470     }
471
472     for (i = 0; i < dpif->uc_array_size; i++ ) {
473         struct dpif_linux_vport vport_request;
474         uint32_t upcall_pids = 0;
475
476         /* Since the sock can only be assigned in either all or none
477          * of "dpif->handlers" channels, the following check would
478          * suffice. */
479         if (!dpif->handlers[0].channels[i].sock) {
480             continue;
481         }
482
483         /* Turn off upcalls. */
484         dpif_linux_vport_init(&vport_request);
485         vport_request.cmd = OVS_VPORT_CMD_SET;
486         vport_request.dp_ifindex = dpif->dp_ifindex;
487         vport_request.port_no = u32_to_odp(i);
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_GENEVE:
584         return "geneve";
585
586     case OVS_VPORT_TYPE_GRE:
587         return "gre";
588
589     case OVS_VPORT_TYPE_GRE64:
590         return "gre64";
591
592     case OVS_VPORT_TYPE_VXLAN:
593         return "vxlan";
594
595     case OVS_VPORT_TYPE_LISP:
596         return "lisp";
597
598     case OVS_VPORT_TYPE_UNSPEC:
599     case __OVS_VPORT_TYPE_MAX:
600         break;
601     }
602
603     VLOG_WARN_RL(&rl, "dp%d: port `%s' has unsupported type %u",
604                  vport->dp_ifindex, vport->name, (unsigned int) vport->type);
605     return "unknown";
606 }
607
608 static enum ovs_vport_type
609 netdev_to_ovs_vport_type(const struct netdev *netdev)
610 {
611     const char *type = netdev_get_type(netdev);
612
613     if (!strcmp(type, "tap") || !strcmp(type, "system")) {
614         return OVS_VPORT_TYPE_NETDEV;
615     } else if (!strcmp(type, "internal")) {
616         return OVS_VPORT_TYPE_INTERNAL;
617     } else if (!strcmp(type, "geneve")) {
618         return OVS_VPORT_TYPE_GENEVE;
619     } else if (strstr(type, "gre64")) {
620         return OVS_VPORT_TYPE_GRE64;
621     } else if (strstr(type, "gre")) {
622         return OVS_VPORT_TYPE_GRE;
623     } else if (!strcmp(type, "vxlan")) {
624         return OVS_VPORT_TYPE_VXLAN;
625     } else if (!strcmp(type, "lisp")) {
626         return OVS_VPORT_TYPE_LISP;
627     } else {
628         return OVS_VPORT_TYPE_UNSPEC;
629     }
630 }
631
632 static int
633 dpif_linux_port_add__(struct dpif_linux *dpif, struct netdev *netdev,
634                       odp_port_t *port_nop)
635     OVS_REQ_WRLOCK(dpif->upcall_lock)
636 {
637     const struct netdev_tunnel_config *tnl_cfg;
638     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
639     const char *name = netdev_vport_get_dpif_port(netdev,
640                                                   namebuf, sizeof namebuf);
641     const char *type = netdev_get_type(netdev);
642     struct dpif_linux_vport request, reply;
643     struct ofpbuf *buf;
644     uint64_t options_stub[64 / 8];
645     struct ofpbuf options;
646     struct nl_sock **socksp = NULL;
647     uint32_t *upcall_pids;
648     int error = 0;
649
650     if (dpif->handlers) {
651         socksp = vport_create_socksp(dpif->n_handlers, &error);
652         if (!socksp) {
653             return error;
654         }
655     }
656
657     dpif_linux_vport_init(&request);
658     request.cmd = OVS_VPORT_CMD_NEW;
659     request.dp_ifindex = dpif->dp_ifindex;
660     request.type = netdev_to_ovs_vport_type(netdev);
661     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
662         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
663                      "unsupported type `%s'",
664                      dpif_name(&dpif->dpif), name, type);
665         vport_del_socksp(socksp, dpif->n_handlers);
666         return EINVAL;
667     }
668     request.name = name;
669
670     if (request.type == OVS_VPORT_TYPE_NETDEV) {
671         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
672     }
673
674     tnl_cfg = netdev_get_tunnel_config(netdev);
675     if (tnl_cfg && tnl_cfg->dst_port != 0) {
676         ofpbuf_use_stack(&options, options_stub, sizeof options_stub);
677         nl_msg_put_u16(&options, OVS_TUNNEL_ATTR_DST_PORT,
678                        ntohs(tnl_cfg->dst_port));
679         request.options = ofpbuf_data(&options);
680         request.options_len = ofpbuf_size(&options);
681     }
682
683     request.port_no = *port_nop;
684     upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
685     request.n_upcall_pids = socksp ? dpif->n_handlers : 1;
686     request.upcall_pids = upcall_pids;
687
688     error = dpif_linux_vport_transact(&request, &reply, &buf);
689     if (!error) {
690         *port_nop = reply.port_no;
691     } else {
692         if (error == EBUSY && *port_nop != ODPP_NONE) {
693             VLOG_INFO("%s: requested port %"PRIu32" is in use",
694                       dpif_name(&dpif->dpif), *port_nop);
695         }
696
697         vport_del_socksp(socksp, dpif->n_handlers);
698         goto exit;
699     }
700
701     if (socksp) {
702         error = vport_add_channels(dpif, *port_nop, socksp);
703         if (error) {
704             VLOG_INFO("%s: could not add channel for port %s",
705                       dpif_name(&dpif->dpif), name);
706
707             /* Delete the port. */
708             dpif_linux_vport_init(&request);
709             request.cmd = OVS_VPORT_CMD_DEL;
710             request.dp_ifindex = dpif->dp_ifindex;
711             request.port_no = *port_nop;
712             dpif_linux_vport_transact(&request, NULL, NULL);
713             vport_del_socksp(socksp, dpif->n_handlers);
714             goto exit;
715         }
716     }
717     free(socksp);
718
719 exit:
720     ofpbuf_delete(buf);
721     free(upcall_pids);
722
723     return error;
724 }
725
726 static int
727 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
728                     odp_port_t *port_nop)
729 {
730     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
731     int error;
732
733     fat_rwlock_wrlock(&dpif->upcall_lock);
734     error = dpif_linux_port_add__(dpif, netdev, port_nop);
735     fat_rwlock_unlock(&dpif->upcall_lock);
736
737     return error;
738 }
739
740 static int
741 dpif_linux_port_del__(struct dpif_linux *dpif, odp_port_t port_no)
742     OVS_REQ_WRLOCK(dpif->upcall_lock)
743 {
744     struct dpif_linux_vport vport;
745     int error;
746
747     dpif_linux_vport_init(&vport);
748     vport.cmd = OVS_VPORT_CMD_DEL;
749     vport.dp_ifindex = dpif->dp_ifindex;
750     vport.port_no = port_no;
751     error = dpif_linux_vport_transact(&vport, NULL, NULL);
752
753     vport_del_channels(dpif, port_no);
754
755     return error;
756 }
757
758 static int
759 dpif_linux_port_del(struct dpif *dpif_, odp_port_t port_no)
760 {
761     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
762     int error;
763
764     fat_rwlock_wrlock(&dpif->upcall_lock);
765     error = dpif_linux_port_del__(dpif, port_no);
766     fat_rwlock_unlock(&dpif->upcall_lock);
767
768     return error;
769 }
770
771 static int
772 dpif_linux_port_query__(const struct dpif_linux *dpif, odp_port_t port_no,
773                         const char *port_name, struct dpif_port *dpif_port)
774 {
775     struct dpif_linux_vport request;
776     struct dpif_linux_vport reply;
777     struct ofpbuf *buf;
778     int error;
779
780     dpif_linux_vport_init(&request);
781     request.cmd = OVS_VPORT_CMD_GET;
782     request.dp_ifindex = dpif->dp_ifindex;
783     request.port_no = port_no;
784     request.name = port_name;
785
786     error = dpif_linux_vport_transact(&request, &reply, &buf);
787     if (!error) {
788         if (reply.dp_ifindex != request.dp_ifindex) {
789             /* A query by name reported that 'port_name' is in some datapath
790              * other than 'dpif', but the caller wants to know about 'dpif'. */
791             error = ENODEV;
792         } else if (dpif_port) {
793             dpif_port->name = xstrdup(reply.name);
794             dpif_port->type = xstrdup(get_vport_type(&reply));
795             dpif_port->port_no = reply.port_no;
796         }
797         ofpbuf_delete(buf);
798     }
799     return error;
800 }
801
802 static int
803 dpif_linux_port_query_by_number(const struct dpif *dpif_, odp_port_t port_no,
804                                 struct dpif_port *dpif_port)
805 {
806     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
807
808     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
809 }
810
811 static int
812 dpif_linux_port_query_by_name(const struct dpif *dpif_, const char *devname,
813                               struct dpif_port *dpif_port)
814 {
815     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
816
817     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
818 }
819
820 static uint32_t
821 dpif_linux_port_get_pid__(const struct dpif_linux *dpif, odp_port_t port_no,
822                           uint32_t hash)
823     OVS_REQ_RDLOCK(dpif->upcall_lock)
824 {
825     uint32_t port_idx = odp_to_u32(port_no);
826     uint32_t pid = 0;
827
828     if (dpif->handlers) {
829         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
830          * channel, since it is not heavily loaded. */
831         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
832         struct dpif_handler *h = &dpif->handlers[hash % dpif->n_handlers];
833
834         pid = nl_sock_pid(h->channels[idx].sock);
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 **actionsp, struct dpif_flow_stats *stats)
1051 {
1052     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1053     struct dpif_linux_flow reply;
1054     struct ofpbuf *buf;
1055     int error;
1056
1057     error = dpif_linux_flow_get__(dpif, key, key_len, &reply, &buf);
1058     if (!error) {
1059         if (stats) {
1060             dpif_linux_flow_get_stats(&reply, stats);
1061         }
1062         if (actionsp) {
1063             ofpbuf_set_data(buf, CONST_CAST(struct nlattr *, reply.actions));
1064             ofpbuf_set_size(buf, reply.actions_len);
1065             *actionsp = buf;
1066         } else {
1067             ofpbuf_delete(buf);
1068         }
1069     }
1070     return error;
1071 }
1072
1073 static void
1074 dpif_linux_init_flow_put(struct dpif_linux *dpif, const struct dpif_flow_put *put,
1075                          struct dpif_linux_flow *request)
1076 {
1077     static const struct nlattr dummy_action;
1078
1079     dpif_linux_flow_init(request);
1080     request->cmd = (put->flags & DPIF_FP_CREATE
1081                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
1082     request->dp_ifindex = dpif->dp_ifindex;
1083     request->key = put->key;
1084     request->key_len = put->key_len;
1085     request->mask = put->mask;
1086     request->mask_len = put->mask_len;
1087     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
1088     request->actions = (put->actions
1089                         ? put->actions
1090                         : CONST_CAST(struct nlattr *, &dummy_action));
1091     request->actions_len = put->actions_len;
1092     if (put->flags & DPIF_FP_ZERO_STATS) {
1093         request->clear = true;
1094     }
1095     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
1096 }
1097
1098 static int
1099 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
1100 {
1101     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1102     struct dpif_linux_flow request, reply;
1103     struct ofpbuf *buf;
1104     int error;
1105
1106     dpif_linux_init_flow_put(dpif, put, &request);
1107     error = dpif_linux_flow_transact(&request,
1108                                      put->stats ? &reply : NULL,
1109                                      put->stats ? &buf : NULL);
1110     if (!error && put->stats) {
1111         dpif_linux_flow_get_stats(&reply, put->stats);
1112         ofpbuf_delete(buf);
1113     }
1114     return error;
1115 }
1116
1117 static void
1118 dpif_linux_init_flow_del(struct dpif_linux *dpif, const struct dpif_flow_del *del,
1119                          struct dpif_linux_flow *request)
1120 {
1121     dpif_linux_flow_init(request);
1122     request->cmd = OVS_FLOW_CMD_DEL;
1123     request->dp_ifindex = dpif->dp_ifindex;
1124     request->key = del->key;
1125     request->key_len = del->key_len;
1126 }
1127
1128 static int
1129 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
1130 {
1131     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1132     struct dpif_linux_flow request, reply;
1133     struct ofpbuf *buf;
1134     int error;
1135
1136     dpif_linux_init_flow_del(dpif, del, &request);
1137     error = dpif_linux_flow_transact(&request,
1138                                      del->stats ? &reply : NULL,
1139                                      del->stats ? &buf : NULL);
1140     if (!error && del->stats) {
1141         dpif_linux_flow_get_stats(&reply, del->stats);
1142         ofpbuf_delete(buf);
1143     }
1144     return error;
1145 }
1146
1147 struct dpif_linux_flow_dump {
1148     struct dpif_flow_dump up;
1149     struct nl_dump nl_dump;
1150     atomic_int status;
1151 };
1152
1153 static struct dpif_linux_flow_dump *
1154 dpif_linux_flow_dump_cast(struct dpif_flow_dump *dump)
1155 {
1156     return CONTAINER_OF(dump, struct dpif_linux_flow_dump, up);
1157 }
1158
1159 static struct dpif_flow_dump *
1160 dpif_linux_flow_dump_create(const struct dpif *dpif_)
1161 {
1162     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1163     struct dpif_linux_flow_dump *dump;
1164     struct dpif_linux_flow request;
1165     struct ofpbuf *buf;
1166
1167     dump = xmalloc(sizeof *dump);
1168     dpif_flow_dump_init(&dump->up, dpif_);
1169
1170     dpif_linux_flow_init(&request);
1171     request.cmd = OVS_FLOW_CMD_GET;
1172     request.dp_ifindex = dpif->dp_ifindex;
1173
1174     buf = ofpbuf_new(1024);
1175     dpif_linux_flow_to_ofpbuf(&request, buf);
1176     nl_dump_start(&dump->nl_dump, NETLINK_GENERIC, buf);
1177     ofpbuf_delete(buf);
1178     atomic_init(&dump->status, 0);
1179
1180     return &dump->up;
1181 }
1182
1183 static int
1184 dpif_linux_flow_dump_destroy(struct dpif_flow_dump *dump_)
1185 {
1186     struct dpif_linux_flow_dump *dump = dpif_linux_flow_dump_cast(dump_);
1187     unsigned int nl_status = nl_dump_done(&dump->nl_dump);
1188     int dump_status;
1189
1190     atomic_read(&dump->status, &dump_status);
1191     free(dump);
1192     return dump_status ? dump_status : nl_status;
1193 }
1194
1195 struct dpif_linux_flow_dump_thread {
1196     struct dpif_flow_dump_thread up;
1197     struct dpif_linux_flow_dump *dump;
1198     struct dpif_linux_flow flow;
1199     struct dpif_flow_stats stats;
1200     struct ofpbuf nl_flows;     /* Always used to store flows. */
1201     struct ofpbuf *nl_actions;  /* Used if kernel does not supply actions. */
1202 };
1203
1204 static struct dpif_linux_flow_dump_thread *
1205 dpif_linux_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1206 {
1207     return CONTAINER_OF(thread, struct dpif_linux_flow_dump_thread, up);
1208 }
1209
1210 static struct dpif_flow_dump_thread *
1211 dpif_linux_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1212 {
1213     struct dpif_linux_flow_dump *dump = dpif_linux_flow_dump_cast(dump_);
1214     struct dpif_linux_flow_dump_thread *thread;
1215
1216     thread = xmalloc(sizeof *thread);
1217     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1218     thread->dump = dump;
1219     ofpbuf_init(&thread->nl_flows, NL_DUMP_BUFSIZE);
1220     thread->nl_actions = NULL;
1221
1222     return &thread->up;
1223 }
1224
1225 static void
1226 dpif_linux_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1227 {
1228     struct dpif_linux_flow_dump_thread *thread
1229         = dpif_linux_flow_dump_thread_cast(thread_);
1230
1231     ofpbuf_uninit(&thread->nl_flows);
1232     ofpbuf_delete(thread->nl_actions);
1233     free(thread);
1234 }
1235
1236 static void
1237 dpif_linux_flow_to_dpif_flow(struct dpif_flow *dpif_flow,
1238                              struct dpif_linux_flow *linux_flow)
1239 {
1240     dpif_flow->key = linux_flow->key;
1241     dpif_flow->key_len = linux_flow->key_len;
1242     dpif_flow->mask = linux_flow->mask;
1243     dpif_flow->mask_len = linux_flow->mask_len;
1244     dpif_flow->actions = linux_flow->actions;
1245     dpif_flow->actions_len = linux_flow->actions_len;
1246     dpif_linux_flow_get_stats(linux_flow, &dpif_flow->stats);
1247 }
1248
1249 static int
1250 dpif_linux_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1251                           struct dpif_flow *flows, int max_flows)
1252 {
1253     struct dpif_linux_flow_dump_thread *thread
1254         = dpif_linux_flow_dump_thread_cast(thread_);
1255     struct dpif_linux_flow_dump *dump = thread->dump;
1256     struct dpif_linux *dpif = dpif_linux_cast(thread->up.dpif);
1257     int n_flows;
1258
1259     ofpbuf_delete(thread->nl_actions);
1260     thread->nl_actions = NULL;
1261
1262     n_flows = 0;
1263     while (!n_flows
1264            || (n_flows < max_flows && ofpbuf_size(&thread->nl_flows))) {
1265         struct dpif_linux_flow linux_flow;
1266         struct ofpbuf nl_flow;
1267         int error;
1268
1269         /* Try to grab another flow. */
1270         if (!nl_dump_next(&dump->nl_dump, &nl_flow, &thread->nl_flows)) {
1271             break;
1272         }
1273
1274         /* Convert the flow to our output format. */
1275         error = dpif_linux_flow_from_ofpbuf(&linux_flow, &nl_flow);
1276         if (error) {
1277             atomic_store(&dump->status, error);
1278             break;
1279         }
1280
1281         if (linux_flow.actions) {
1282             /* Common case: the flow includes actions. */
1283             dpif_linux_flow_to_dpif_flow(&flows[n_flows++], &linux_flow);
1284         } else {
1285             /* Rare case: the flow does not include actions.  Retrieve this
1286              * individual flow again to get the actions. */
1287             error = dpif_linux_flow_get__(dpif, linux_flow.key,
1288                                           linux_flow.key_len, &linux_flow,
1289                                           &thread->nl_actions);
1290             if (error == ENOENT) {
1291                 VLOG_DBG("dumped flow disappeared on get");
1292                 continue;
1293             } else if (error) {
1294                 VLOG_WARN("error fetching dumped flow: %s",
1295                           ovs_strerror(error));
1296                 atomic_store(&dump->status, error);
1297                 break;
1298             }
1299
1300             /* Save this flow.  Then exit, because we only have one buffer to
1301              * handle this case. */
1302             dpif_linux_flow_to_dpif_flow(&flows[n_flows++], &linux_flow);
1303             break;
1304         }
1305     }
1306     return n_flows;
1307 }
1308
1309 static void
1310 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1311                           struct ofpbuf *buf)
1312 {
1313     struct ovs_header *k_exec;
1314     size_t key_ofs;
1315
1316     ofpbuf_prealloc_tailroom(buf, (64
1317                                    + ofpbuf_size(d_exec->packet)
1318                                    + ODP_KEY_METADATA_SIZE
1319                                    + d_exec->actions_len));
1320
1321     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1322                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1323
1324     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1325     k_exec->dp_ifindex = dp_ifindex;
1326
1327     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1328                       ofpbuf_data(d_exec->packet),
1329                       ofpbuf_size(d_exec->packet));
1330
1331     key_ofs = nl_msg_start_nested(buf, OVS_PACKET_ATTR_KEY);
1332     odp_key_from_pkt_metadata(buf, &d_exec->md);
1333     nl_msg_end_nested(buf, key_ofs);
1334
1335     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1336                       d_exec->actions, d_exec->actions_len);
1337 }
1338
1339 static int
1340 dpif_linux_execute__(int dp_ifindex, const struct dpif_execute *execute)
1341 {
1342     uint64_t request_stub[1024 / 8];
1343     struct ofpbuf request;
1344     int error;
1345
1346     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1347     dpif_linux_encode_execute(dp_ifindex, execute, &request);
1348     error = nl_transact(NETLINK_GENERIC, &request, NULL);
1349     ofpbuf_uninit(&request);
1350
1351     return error;
1352 }
1353
1354 static int
1355 dpif_linux_execute(struct dpif *dpif_, struct dpif_execute *execute)
1356 {
1357     const struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1358
1359     return dpif_linux_execute__(dpif->dp_ifindex, execute);
1360 }
1361
1362 #define MAX_OPS 50
1363
1364 static void
1365 dpif_linux_operate__(struct dpif_linux *dpif,
1366                      struct dpif_op **ops, size_t n_ops)
1367 {
1368     struct op_auxdata {
1369         struct nl_transaction txn;
1370
1371         struct ofpbuf request;
1372         uint64_t request_stub[1024 / 8];
1373
1374         struct ofpbuf reply;
1375         uint64_t reply_stub[1024 / 8];
1376     } auxes[MAX_OPS];
1377
1378     struct nl_transaction *txnsp[MAX_OPS];
1379     size_t i;
1380
1381     ovs_assert(n_ops <= MAX_OPS);
1382     for (i = 0; i < n_ops; i++) {
1383         struct op_auxdata *aux = &auxes[i];
1384         struct dpif_op *op = ops[i];
1385         struct dpif_flow_put *put;
1386         struct dpif_flow_del *del;
1387         struct dpif_execute *execute;
1388         struct dpif_linux_flow flow;
1389
1390         ofpbuf_use_stub(&aux->request,
1391                         aux->request_stub, sizeof aux->request_stub);
1392         aux->txn.request = &aux->request;
1393
1394         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1395         aux->txn.reply = NULL;
1396
1397         switch (op->type) {
1398         case DPIF_OP_FLOW_PUT:
1399             put = &op->u.flow_put;
1400             dpif_linux_init_flow_put(dpif, put, &flow);
1401             if (put->stats) {
1402                 flow.nlmsg_flags |= NLM_F_ECHO;
1403                 aux->txn.reply = &aux->reply;
1404             }
1405             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1406             break;
1407
1408         case DPIF_OP_FLOW_DEL:
1409             del = &op->u.flow_del;
1410             dpif_linux_init_flow_del(dpif, del, &flow);
1411             if (del->stats) {
1412                 flow.nlmsg_flags |= NLM_F_ECHO;
1413                 aux->txn.reply = &aux->reply;
1414             }
1415             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
1416             break;
1417
1418         case DPIF_OP_EXECUTE:
1419             execute = &op->u.execute;
1420             dpif_linux_encode_execute(dpif->dp_ifindex, execute,
1421                                       &aux->request);
1422             break;
1423
1424         default:
1425             OVS_NOT_REACHED();
1426         }
1427     }
1428
1429     for (i = 0; i < n_ops; i++) {
1430         txnsp[i] = &auxes[i].txn;
1431     }
1432     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1433
1434     for (i = 0; i < n_ops; i++) {
1435         struct op_auxdata *aux = &auxes[i];
1436         struct nl_transaction *txn = &auxes[i].txn;
1437         struct dpif_op *op = ops[i];
1438         struct dpif_flow_put *put;
1439         struct dpif_flow_del *del;
1440
1441         op->error = txn->error;
1442
1443         switch (op->type) {
1444         case DPIF_OP_FLOW_PUT:
1445             put = &op->u.flow_put;
1446             if (put->stats) {
1447                 if (!op->error) {
1448                     struct dpif_linux_flow reply;
1449
1450                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1451                                                             txn->reply);
1452                     if (!op->error) {
1453                         dpif_linux_flow_get_stats(&reply, put->stats);
1454                     }
1455                 }
1456
1457                 if (op->error) {
1458                     memset(put->stats, 0, sizeof *put->stats);
1459                 }
1460             }
1461             break;
1462
1463         case DPIF_OP_FLOW_DEL:
1464             del = &op->u.flow_del;
1465             if (del->stats) {
1466                 if (!op->error) {
1467                     struct dpif_linux_flow reply;
1468
1469                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1470                                                             txn->reply);
1471                     if (!op->error) {
1472                         dpif_linux_flow_get_stats(&reply, del->stats);
1473                     }
1474                 }
1475
1476                 if (op->error) {
1477                     memset(del->stats, 0, sizeof *del->stats);
1478                 }
1479             }
1480             break;
1481
1482         case DPIF_OP_EXECUTE:
1483             break;
1484
1485         default:
1486             OVS_NOT_REACHED();
1487         }
1488
1489         ofpbuf_uninit(&aux->request);
1490         ofpbuf_uninit(&aux->reply);
1491     }
1492 }
1493
1494 static void
1495 dpif_linux_operate(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1496 {
1497     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1498
1499     while (n_ops > 0) {
1500         size_t chunk = MIN(n_ops, MAX_OPS);
1501         dpif_linux_operate__(dpif, ops, chunk);
1502         ops += chunk;
1503         n_ops -= chunk;
1504     }
1505 }
1506
1507 /* Synchronizes 'channels' in 'dpif->handlers'  with the set of vports
1508  * currently in 'dpif' in the kernel, by adding a new set of channels for
1509  * any kernel vport that lacks one and deleting any channels that have no
1510  * backing kernel vports. */
1511 static int
1512 dpif_linux_refresh_channels(struct dpif_linux *dpif, uint32_t n_handlers)
1513     OVS_REQ_WRLOCK(dpif->upcall_lock)
1514 {
1515     unsigned long int *keep_channels;
1516     struct dpif_linux_vport vport;
1517     size_t keep_channels_nbits;
1518     struct nl_dump dump;
1519     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
1520     struct ofpbuf buf;
1521     int retval = 0;
1522     size_t i;
1523
1524     if (dpif->n_handlers != n_handlers) {
1525         destroy_all_channels(dpif);
1526         dpif->handlers = xzalloc(n_handlers * sizeof *dpif->handlers);
1527         for (i = 0; i < n_handlers; i++) {
1528             struct dpif_handler *handler = &dpif->handlers[i];
1529
1530             handler->epoll_fd = epoll_create(10);
1531             if (handler->epoll_fd < 0) {
1532                 size_t j;
1533
1534                 for (j = 0; j < i; j++) {
1535                     close(dpif->handlers[j].epoll_fd);
1536                 }
1537                 free(dpif->handlers);
1538                 dpif->handlers = NULL;
1539
1540                 return errno;
1541             }
1542         }
1543         dpif->n_handlers = n_handlers;
1544     }
1545
1546     for (i = 0; i < n_handlers; i++) {
1547         struct dpif_handler *handler = &dpif->handlers[i];
1548
1549         handler->event_offset = handler->n_events = 0;
1550     }
1551
1552     keep_channels_nbits = dpif->uc_array_size;
1553     keep_channels = bitmap_allocate(keep_channels_nbits);
1554
1555     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
1556     dpif_linux_port_dump_start__(dpif, &dump);
1557     while (!dpif_linux_port_dump_next__(dpif, &dump, &vport, &buf)) {
1558         uint32_t port_no = odp_to_u32(vport.port_no);
1559         uint32_t *upcall_pids = NULL;
1560         int error;
1561
1562         if (port_no >= dpif->uc_array_size
1563             || !vport_get_pids(dpif, port_no, &upcall_pids)) {
1564             struct nl_sock **socksp = vport_create_socksp(dpif->n_handlers,
1565                                                           &error);
1566
1567             if (!socksp) {
1568                 goto error;
1569             }
1570
1571             error = vport_add_channels(dpif, vport.port_no, socksp);
1572             if (error) {
1573                 VLOG_INFO("%s: could not add channels for port %s",
1574                           dpif_name(&dpif->dpif), vport.name);
1575                 vport_del_socksp(socksp, dpif->n_handlers);
1576                 retval = error;
1577                 goto error;
1578             }
1579             upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
1580             free(socksp);
1581         }
1582
1583         /* Configure the vport to deliver misses to 'sock'. */
1584         if (vport.upcall_pids[0] == 0
1585             || vport.n_upcall_pids != dpif->n_handlers
1586             || memcmp(upcall_pids, vport.upcall_pids, n_handlers * sizeof
1587                       *upcall_pids)) {
1588             struct dpif_linux_vport vport_request;
1589
1590             dpif_linux_vport_init(&vport_request);
1591             vport_request.cmd = OVS_VPORT_CMD_SET;
1592             vport_request.dp_ifindex = dpif->dp_ifindex;
1593             vport_request.port_no = vport.port_no;
1594             vport_request.n_upcall_pids = dpif->n_handlers;
1595             vport_request.upcall_pids = upcall_pids;
1596             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1597             if (error) {
1598                 VLOG_WARN_RL(&error_rl,
1599                              "%s: failed to set upcall pid on port: %s",
1600                              dpif_name(&dpif->dpif), ovs_strerror(error));
1601
1602                 if (error != ENODEV && error != ENOENT) {
1603                     retval = error;
1604                 } else {
1605                     /* The vport isn't really there, even though the dump says
1606                      * it is.  Probably we just hit a race after a port
1607                      * disappeared. */
1608                 }
1609                 goto error;
1610             }
1611         }
1612
1613         if (port_no < keep_channels_nbits) {
1614             bitmap_set1(keep_channels, port_no);
1615         }
1616         free(upcall_pids);
1617         continue;
1618
1619     error:
1620         free(upcall_pids);
1621         vport_del_channels(dpif, vport.port_no);
1622     }
1623     nl_dump_done(&dump);
1624     ofpbuf_uninit(&buf);
1625
1626     /* Discard any saved channels that we didn't reuse. */
1627     for (i = 0; i < keep_channels_nbits; i++) {
1628         if (!bitmap_is_set(keep_channels, i)) {
1629             vport_del_channels(dpif, u32_to_odp(i));
1630         }
1631     }
1632     free(keep_channels);
1633
1634     return retval;
1635 }
1636
1637 static int
1638 dpif_linux_recv_set__(struct dpif_linux *dpif, bool enable)
1639     OVS_REQ_WRLOCK(dpif->upcall_lock)
1640 {
1641     if ((dpif->handlers != NULL) == enable) {
1642         return 0;
1643     } else if (!enable) {
1644         destroy_all_channels(dpif);
1645         return 0;
1646     } else {
1647         return dpif_linux_refresh_channels(dpif, 1);
1648     }
1649 }
1650
1651 static int
1652 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1653 {
1654     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1655     int error;
1656
1657     fat_rwlock_wrlock(&dpif->upcall_lock);
1658     error = dpif_linux_recv_set__(dpif, enable);
1659     fat_rwlock_unlock(&dpif->upcall_lock);
1660
1661     return error;
1662 }
1663
1664 static int
1665 dpif_linux_handlers_set(struct dpif *dpif_, uint32_t n_handlers)
1666 {
1667     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1668     int error = 0;
1669
1670     fat_rwlock_wrlock(&dpif->upcall_lock);
1671     if (dpif->handlers) {
1672         error = dpif_linux_refresh_channels(dpif, n_handlers);
1673     }
1674     fat_rwlock_unlock(&dpif->upcall_lock);
1675
1676     return error;
1677 }
1678
1679 static int
1680 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1681                              uint32_t queue_id, uint32_t *priority)
1682 {
1683     if (queue_id < 0xf000) {
1684         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1685         return 0;
1686     } else {
1687         return EINVAL;
1688     }
1689 }
1690
1691 static int
1692 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1693                  int *dp_ifindex)
1694 {
1695     static const struct nl_policy ovs_packet_policy[] = {
1696         /* Always present. */
1697         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1698                                      .min_len = ETH_HEADER_LEN },
1699         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1700
1701         /* OVS_PACKET_CMD_ACTION only. */
1702         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1703     };
1704
1705     struct ovs_header *ovs_header;
1706     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1707     struct nlmsghdr *nlmsg;
1708     struct genlmsghdr *genl;
1709     struct ofpbuf b;
1710     int type;
1711
1712     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
1713
1714     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1715     genl = ofpbuf_try_pull(&b, sizeof *genl);
1716     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1717     if (!nlmsg || !genl || !ovs_header
1718         || nlmsg->nlmsg_type != ovs_packet_family
1719         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1720                             ARRAY_SIZE(ovs_packet_policy))) {
1721         return EINVAL;
1722     }
1723
1724     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1725             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1726             : -1);
1727     if (type < 0) {
1728         return EINVAL;
1729     }
1730
1731     /* (Re)set ALL fields of '*upcall' on successful return. */
1732     upcall->type = type;
1733     upcall->key = CONST_CAST(struct nlattr *,
1734                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1735     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1736     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1737
1738     /* Allow overwriting the netlink attribute header without reallocating. */
1739     ofpbuf_use_stub(&upcall->packet,
1740                     CONST_CAST(struct nlattr *,
1741                                nl_attr_get(a[OVS_PACKET_ATTR_PACKET])) - 1,
1742                     nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]) +
1743                     sizeof(struct nlattr));
1744     ofpbuf_set_data(&upcall->packet,
1745                     (char *)ofpbuf_data(&upcall->packet) + sizeof(struct nlattr));
1746     ofpbuf_set_size(&upcall->packet, nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]));
1747
1748     *dp_ifindex = ovs_header->dp_ifindex;
1749
1750     return 0;
1751 }
1752
1753 static int
1754 dpif_linux_recv__(struct dpif_linux *dpif, uint32_t handler_id,
1755                   struct dpif_upcall *upcall, struct ofpbuf *buf)
1756     OVS_REQ_RDLOCK(dpif->upcall_lock)
1757 {
1758     struct dpif_handler *handler;
1759     int read_tries = 0;
1760
1761     if (!dpif->handlers || handler_id >= dpif->n_handlers) {
1762         return EAGAIN;
1763     }
1764
1765     handler = &dpif->handlers[handler_id];
1766     if (handler->event_offset >= handler->n_events) {
1767         int retval;
1768
1769         handler->event_offset = handler->n_events = 0;
1770
1771         do {
1772             retval = epoll_wait(handler->epoll_fd, handler->epoll_events,
1773                                 dpif->uc_array_size, 0);
1774         } while (retval < 0 && errno == EINTR);
1775         if (retval < 0) {
1776             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1777             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
1778         } else if (retval > 0) {
1779             handler->n_events = retval;
1780         }
1781     }
1782
1783     while (handler->event_offset < handler->n_events) {
1784         int idx = handler->epoll_events[handler->event_offset].data.u32;
1785         struct dpif_channel *ch = &dpif->handlers[handler_id].channels[idx];
1786
1787         handler->event_offset++;
1788
1789         for (;;) {
1790             int dp_ifindex;
1791             int error;
1792
1793             if (++read_tries > 50) {
1794                 return EAGAIN;
1795             }
1796
1797             error = nl_sock_recv(ch->sock, buf, false);
1798             if (error == ENOBUFS) {
1799                 /* ENOBUFS typically means that we've received so many
1800                  * packets that the buffer overflowed.  Try again
1801                  * immediately because there's almost certainly a packet
1802                  * waiting for us. */
1803                 report_loss(dpif, ch, idx, handler_id);
1804                 continue;
1805             }
1806
1807             ch->last_poll = time_msec();
1808             if (error) {
1809                 if (error == EAGAIN) {
1810                     break;
1811                 }
1812                 return error;
1813             }
1814
1815             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1816             if (!error && dp_ifindex == dpif->dp_ifindex) {
1817                 return 0;
1818             } else if (error) {
1819                 return error;
1820             }
1821         }
1822     }
1823
1824     return EAGAIN;
1825 }
1826
1827 static int
1828 dpif_linux_recv(struct dpif *dpif_, uint32_t handler_id,
1829                 struct dpif_upcall *upcall, struct ofpbuf *buf)
1830 {
1831     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1832     int error;
1833
1834     fat_rwlock_rdlock(&dpif->upcall_lock);
1835     error = dpif_linux_recv__(dpif, handler_id, upcall, buf);
1836     fat_rwlock_unlock(&dpif->upcall_lock);
1837
1838     return error;
1839 }
1840
1841 static void
1842 dpif_linux_recv_wait__(struct dpif_linux *dpif, uint32_t handler_id)
1843     OVS_REQ_RDLOCK(dpif->upcall_lock)
1844 {
1845     if (dpif->handlers && handler_id < dpif->n_handlers) {
1846         struct dpif_handler *handler = &dpif->handlers[handler_id];
1847
1848         poll_fd_wait(handler->epoll_fd, POLLIN);
1849     }
1850 }
1851
1852 static void
1853 dpif_linux_recv_wait(struct dpif *dpif_, uint32_t handler_id)
1854 {
1855     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1856
1857     fat_rwlock_rdlock(&dpif->upcall_lock);
1858     dpif_linux_recv_wait__(dpif, handler_id);
1859     fat_rwlock_unlock(&dpif->upcall_lock);
1860 }
1861
1862 static void
1863 dpif_linux_recv_purge__(struct dpif_linux *dpif)
1864     OVS_REQ_WRLOCK(dpif->upcall_lock)
1865 {
1866     if (dpif->handlers) {
1867         size_t i, j;
1868
1869         for (i = 0; i < dpif->uc_array_size; i++ ) {
1870             if (!dpif->handlers[0].channels[i].sock) {
1871                 continue;
1872             }
1873
1874             for (j = 0; j < dpif->n_handlers; j++) {
1875                 nl_sock_drain(dpif->handlers[j].channels[i].sock);
1876             }
1877         }
1878     }
1879 }
1880
1881 static void
1882 dpif_linux_recv_purge(struct dpif *dpif_)
1883 {
1884     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1885
1886     fat_rwlock_wrlock(&dpif->upcall_lock);
1887     dpif_linux_recv_purge__(dpif);
1888     fat_rwlock_unlock(&dpif->upcall_lock);
1889 }
1890
1891 const struct dpif_class dpif_linux_class = {
1892     "system",
1893     dpif_linux_enumerate,
1894     NULL,
1895     dpif_linux_open,
1896     dpif_linux_close,
1897     dpif_linux_destroy,
1898     dpif_linux_run,
1899     NULL,                       /* wait */
1900     dpif_linux_get_stats,
1901     dpif_linux_port_add,
1902     dpif_linux_port_del,
1903     dpif_linux_port_query_by_number,
1904     dpif_linux_port_query_by_name,
1905     dpif_linux_port_get_pid,
1906     dpif_linux_port_dump_start,
1907     dpif_linux_port_dump_next,
1908     dpif_linux_port_dump_done,
1909     dpif_linux_port_poll,
1910     dpif_linux_port_poll_wait,
1911     dpif_linux_flow_get,
1912     dpif_linux_flow_put,
1913     dpif_linux_flow_del,
1914     dpif_linux_flow_flush,
1915     dpif_linux_flow_dump_create,
1916     dpif_linux_flow_dump_destroy,
1917     dpif_linux_flow_dump_thread_create,
1918     dpif_linux_flow_dump_thread_destroy,
1919     dpif_linux_flow_dump_next,
1920     dpif_linux_execute,
1921     dpif_linux_operate,
1922     dpif_linux_recv_set,
1923     dpif_linux_handlers_set,
1924     dpif_linux_queue_to_priority,
1925     dpif_linux_recv,
1926     dpif_linux_recv_wait,
1927     dpif_linux_recv_purge,
1928 };
1929 \f
1930 static int
1931 dpif_linux_init(void)
1932 {
1933     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1934     static int error;
1935
1936     if (ovsthread_once_start(&once)) {
1937         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1938                                       &ovs_datapath_family);
1939         if (error) {
1940             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1941                      "The Open vSwitch kernel module is probably not loaded.",
1942                      OVS_DATAPATH_FAMILY);
1943         }
1944         if (!error) {
1945             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1946         }
1947         if (!error) {
1948             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1949         }
1950         if (!error) {
1951             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1952                                           &ovs_packet_family);
1953         }
1954         if (!error) {
1955             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1956                                            &ovs_vport_mcgroup);
1957         }
1958
1959         ovsthread_once_done(&once);
1960     }
1961
1962     return error;
1963 }
1964
1965 bool
1966 dpif_linux_is_internal_device(const char *name)
1967 {
1968     struct dpif_linux_vport reply;
1969     struct ofpbuf *buf;
1970     int error;
1971
1972     error = dpif_linux_vport_get(name, &reply, &buf);
1973     if (!error) {
1974         ofpbuf_delete(buf);
1975     } else if (error != ENODEV && error != ENOENT) {
1976         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1977                      name, ovs_strerror(error));
1978     }
1979
1980     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1981 }
1982 \f
1983 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1984  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1985  * positive errno value.
1986  *
1987  * 'vport' will contain pointers into 'buf', so the caller should not free
1988  * 'buf' while 'vport' is still in use. */
1989 static int
1990 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1991                              const struct ofpbuf *buf)
1992 {
1993     static const struct nl_policy ovs_vport_policy[] = {
1994         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1995         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1996         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1997         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_UNSPEC },
1998         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1999                                    .optional = true },
2000         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
2001     };
2002
2003     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
2004     struct ovs_header *ovs_header;
2005     struct nlmsghdr *nlmsg;
2006     struct genlmsghdr *genl;
2007     struct ofpbuf b;
2008
2009     dpif_linux_vport_init(vport);
2010
2011     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2012     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2013     genl = ofpbuf_try_pull(&b, sizeof *genl);
2014     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2015     if (!nlmsg || !genl || !ovs_header
2016         || nlmsg->nlmsg_type != ovs_vport_family
2017         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
2018                             ARRAY_SIZE(ovs_vport_policy))) {
2019         return EINVAL;
2020     }
2021
2022     vport->cmd = genl->cmd;
2023     vport->dp_ifindex = ovs_header->dp_ifindex;
2024     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
2025     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2026     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
2027     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2028         vport->n_upcall_pids = nl_attr_get_size(a[OVS_VPORT_ATTR_UPCALL_PID])
2029                                / (sizeof *vport->upcall_pids);
2030         vport->upcall_pids = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
2031
2032     }
2033     if (a[OVS_VPORT_ATTR_STATS]) {
2034         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
2035     }
2036     if (a[OVS_VPORT_ATTR_OPTIONS]) {
2037         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
2038         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
2039     }
2040     return 0;
2041 }
2042
2043 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2044  * followed by Netlink attributes corresponding to 'vport'. */
2045 static void
2046 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
2047                            struct ofpbuf *buf)
2048 {
2049     struct ovs_header *ovs_header;
2050
2051     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
2052                           vport->cmd, OVS_VPORT_VERSION);
2053
2054     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2055     ovs_header->dp_ifindex = vport->dp_ifindex;
2056
2057     if (vport->port_no != ODPP_NONE) {
2058         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
2059     }
2060
2061     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
2062         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
2063     }
2064
2065     if (vport->name) {
2066         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
2067     }
2068
2069     if (vport->upcall_pids) {
2070         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_UPCALL_PID,
2071                           vport->upcall_pids,
2072                           vport->n_upcall_pids * sizeof *vport->upcall_pids);
2073     }
2074
2075     if (vport->stats) {
2076         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
2077                           vport->stats, sizeof *vport->stats);
2078     }
2079
2080     if (vport->options) {
2081         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
2082                           vport->options, vport->options_len);
2083     }
2084 }
2085
2086 /* Clears 'vport' to "empty" values. */
2087 void
2088 dpif_linux_vport_init(struct dpif_linux_vport *vport)
2089 {
2090     memset(vport, 0, sizeof *vport);
2091     vport->port_no = ODPP_NONE;
2092 }
2093
2094 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2095  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2096  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2097  * result of the command is expected to be an ovs_vport also, which is decoded
2098  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2099  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2100 int
2101 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
2102                           struct dpif_linux_vport *reply,
2103                           struct ofpbuf **bufp)
2104 {
2105     struct ofpbuf *request_buf;
2106     int error;
2107
2108     ovs_assert((reply != NULL) == (bufp != NULL));
2109
2110     error = dpif_linux_init();
2111     if (error) {
2112         if (reply) {
2113             *bufp = NULL;
2114             dpif_linux_vport_init(reply);
2115         }
2116         return error;
2117     }
2118
2119     request_buf = ofpbuf_new(1024);
2120     dpif_linux_vport_to_ofpbuf(request, request_buf);
2121     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2122     ofpbuf_delete(request_buf);
2123
2124     if (reply) {
2125         if (!error) {
2126             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
2127         }
2128         if (error) {
2129             dpif_linux_vport_init(reply);
2130             ofpbuf_delete(*bufp);
2131             *bufp = NULL;
2132         }
2133     }
2134     return error;
2135 }
2136
2137 /* Obtains information about the kernel vport named 'name' and stores it into
2138  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
2139  * longer needed ('reply' will contain pointers into '*bufp').  */
2140 int
2141 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
2142                      struct ofpbuf **bufp)
2143 {
2144     struct dpif_linux_vport request;
2145
2146     dpif_linux_vport_init(&request);
2147     request.cmd = OVS_VPORT_CMD_GET;
2148     request.name = name;
2149
2150     return dpif_linux_vport_transact(&request, reply, bufp);
2151 }
2152 \f
2153 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2154  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
2155  * positive errno value.
2156  *
2157  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
2158  * while 'dp' is still in use. */
2159 static int
2160 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
2161 {
2162     static const struct nl_policy ovs_datapath_policy[] = {
2163         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2164         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
2165                                 .optional = true },
2166         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
2167                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
2168                         .optional = true },
2169     };
2170
2171     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
2172     struct ovs_header *ovs_header;
2173     struct nlmsghdr *nlmsg;
2174     struct genlmsghdr *genl;
2175     struct ofpbuf b;
2176
2177     dpif_linux_dp_init(dp);
2178
2179     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2180     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2181     genl = ofpbuf_try_pull(&b, sizeof *genl);
2182     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2183     if (!nlmsg || !genl || !ovs_header
2184         || nlmsg->nlmsg_type != ovs_datapath_family
2185         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
2186                             ARRAY_SIZE(ovs_datapath_policy))) {
2187         return EINVAL;
2188     }
2189
2190     dp->cmd = genl->cmd;
2191     dp->dp_ifindex = ovs_header->dp_ifindex;
2192     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
2193     if (a[OVS_DP_ATTR_STATS]) {
2194         /* Can't use structure assignment because Netlink doesn't ensure
2195          * sufficient alignment for 64-bit members. */
2196         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
2197                sizeof dp->stats);
2198     }
2199
2200     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
2201         /* Can't use structure assignment because Netlink doesn't ensure
2202          * sufficient alignment for 64-bit members. */
2203         memcpy(&dp->megaflow_stats, nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]),
2204                sizeof dp->megaflow_stats);
2205     }
2206
2207     return 0;
2208 }
2209
2210 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
2211 static void
2212 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
2213 {
2214     struct ovs_header *ovs_header;
2215
2216     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
2217                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
2218                           OVS_DATAPATH_VERSION);
2219
2220     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2221     ovs_header->dp_ifindex = dp->dp_ifindex;
2222
2223     if (dp->name) {
2224         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
2225     }
2226
2227     if (dp->upcall_pid) {
2228         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
2229     }
2230
2231     if (dp->user_features) {
2232         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
2233     }
2234
2235     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
2236 }
2237
2238 /* Clears 'dp' to "empty" values. */
2239 static void
2240 dpif_linux_dp_init(struct dpif_linux_dp *dp)
2241 {
2242     memset(dp, 0, sizeof *dp);
2243     dp->megaflow_stats.n_masks = UINT32_MAX;
2244     dp->megaflow_stats.n_mask_hit = UINT64_MAX;
2245 }
2246
2247 static void
2248 dpif_linux_dp_dump_start(struct nl_dump *dump)
2249 {
2250     struct dpif_linux_dp request;
2251     struct ofpbuf *buf;
2252
2253     dpif_linux_dp_init(&request);
2254     request.cmd = OVS_DP_CMD_GET;
2255
2256     buf = ofpbuf_new(1024);
2257     dpif_linux_dp_to_ofpbuf(&request, buf);
2258     nl_dump_start(dump, NETLINK_GENERIC, buf);
2259     ofpbuf_delete(buf);
2260 }
2261
2262 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2263  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2264  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2265  * result of the command is expected to be of the same form, which is decoded
2266  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2267  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2268 static int
2269 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
2270                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
2271 {
2272     struct ofpbuf *request_buf;
2273     int error;
2274
2275     ovs_assert((reply != NULL) == (bufp != NULL));
2276
2277     request_buf = ofpbuf_new(1024);
2278     dpif_linux_dp_to_ofpbuf(request, request_buf);
2279     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2280     ofpbuf_delete(request_buf);
2281
2282     if (reply) {
2283         dpif_linux_dp_init(reply);
2284         if (!error) {
2285             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
2286         }
2287         if (error) {
2288             ofpbuf_delete(*bufp);
2289             *bufp = NULL;
2290         }
2291     }
2292     return error;
2293 }
2294
2295 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
2296  * The caller must free '*bufp' when the reply is no longer needed ('reply'
2297  * will contain pointers into '*bufp').  */
2298 static int
2299 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
2300                   struct ofpbuf **bufp)
2301 {
2302     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
2303     struct dpif_linux_dp request;
2304
2305     dpif_linux_dp_init(&request);
2306     request.cmd = OVS_DP_CMD_GET;
2307     request.dp_ifindex = dpif->dp_ifindex;
2308
2309     return dpif_linux_dp_transact(&request, reply, bufp);
2310 }
2311 \f
2312 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2313  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2314  * positive errno value.
2315  *
2316  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2317  * while 'flow' is still in use. */
2318 static int
2319 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
2320                             const struct ofpbuf *buf)
2321 {
2322     static const struct nl_policy ovs_flow_policy[] = {
2323         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
2324         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2325         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2326         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2327                                   .optional = true },
2328         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2329         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2330         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2331     };
2332
2333     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2334     struct ovs_header *ovs_header;
2335     struct nlmsghdr *nlmsg;
2336     struct genlmsghdr *genl;
2337     struct ofpbuf b;
2338
2339     dpif_linux_flow_init(flow);
2340
2341     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2342     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2343     genl = ofpbuf_try_pull(&b, sizeof *genl);
2344     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2345     if (!nlmsg || !genl || !ovs_header
2346         || nlmsg->nlmsg_type != ovs_flow_family
2347         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2348                             ARRAY_SIZE(ovs_flow_policy))) {
2349         return EINVAL;
2350     }
2351
2352     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2353     flow->dp_ifindex = ovs_header->dp_ifindex;
2354     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2355     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2356
2357     if (a[OVS_FLOW_ATTR_MASK]) {
2358         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2359         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2360     }
2361     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2362         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2363         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2364     }
2365     if (a[OVS_FLOW_ATTR_STATS]) {
2366         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2367     }
2368     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2369         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2370     }
2371     if (a[OVS_FLOW_ATTR_USED]) {
2372         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2373     }
2374     return 0;
2375 }
2376
2377 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2378  * followed by Netlink attributes corresponding to 'flow'. */
2379 static void
2380 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
2381                           struct ofpbuf *buf)
2382 {
2383     struct ovs_header *ovs_header;
2384
2385     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2386                           NLM_F_REQUEST | flow->nlmsg_flags,
2387                           flow->cmd, OVS_FLOW_VERSION);
2388
2389     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2390     ovs_header->dp_ifindex = flow->dp_ifindex;
2391
2392     if (flow->key_len) {
2393         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
2394     }
2395
2396     if (flow->mask_len) {
2397         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK, flow->mask, flow->mask_len);
2398     }
2399
2400     if (flow->actions || flow->actions_len) {
2401         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2402                           flow->actions, flow->actions_len);
2403     }
2404
2405     /* We never need to send these to the kernel. */
2406     ovs_assert(!flow->stats);
2407     ovs_assert(!flow->tcp_flags);
2408     ovs_assert(!flow->used);
2409
2410     if (flow->clear) {
2411         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2412     }
2413 }
2414
2415 /* Clears 'flow' to "empty" values. */
2416 static void
2417 dpif_linux_flow_init(struct dpif_linux_flow *flow)
2418 {
2419     memset(flow, 0, sizeof *flow);
2420 }
2421
2422 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2423  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2424  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2425  * result of the command is expected to be a flow also, which is decoded and
2426  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2427  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2428 static int
2429 dpif_linux_flow_transact(struct dpif_linux_flow *request,
2430                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
2431 {
2432     struct ofpbuf *request_buf;
2433     int error;
2434
2435     ovs_assert((reply != NULL) == (bufp != NULL));
2436
2437     if (reply) {
2438         request->nlmsg_flags |= NLM_F_ECHO;
2439     }
2440
2441     request_buf = ofpbuf_new(1024);
2442     dpif_linux_flow_to_ofpbuf(request, request_buf);
2443     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2444     ofpbuf_delete(request_buf);
2445
2446     if (reply) {
2447         if (!error) {
2448             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
2449         }
2450         if (error) {
2451             dpif_linux_flow_init(reply);
2452             ofpbuf_delete(*bufp);
2453             *bufp = NULL;
2454         }
2455     }
2456     return error;
2457 }
2458
2459 static void
2460 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
2461                           struct dpif_flow_stats *stats)
2462 {
2463     if (flow->stats) {
2464         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
2465         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
2466     } else {
2467         stats->n_packets = 0;
2468         stats->n_bytes = 0;
2469     }
2470     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2471     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2472 }
2473 \f
2474 /* Logs information about a packet that was recently lost in 'ch' (in
2475  * 'dpif_'). */
2476 static void
2477 report_loss(struct dpif_linux *dpif, struct dpif_channel *ch, uint32_t ch_idx,
2478             uint32_t handler_id)
2479 {
2480     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2481     struct ds s;
2482
2483     if (VLOG_DROP_WARN(&rl)) {
2484         return;
2485     }
2486
2487     ds_init(&s);
2488     if (ch->last_poll != LLONG_MIN) {
2489         ds_put_format(&s, " (last polled %lld ms ago)",
2490                       time_msec() - ch->last_poll);
2491     }
2492
2493     VLOG_WARN("%s: lost packet on port channel %u of handler %u",
2494               dpif_name(&dpif->dpif), ch_idx, handler_id);
2495     ds_destroy(&s);
2496 }