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