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