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