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