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