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