tunneling: Remove gre64 tunnel support.
[cascardo/ovs.git] / lib / dpif-netlink.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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-netlink.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 "openvswitch/vlog.h"
57
58 VLOG_DEFINE_THIS_MODULE(dpif_netlink);
59 #ifdef _WIN32
60 enum { WINDOWS = 1 };
61 #else
62 enum { WINDOWS = 0 };
63 #endif
64 enum { MAX_PORTS = USHRT_MAX };
65
66 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
67  * missing if we have old headers. */
68 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
69
70 struct dpif_netlink_dp {
71     /* Generic Netlink header. */
72     uint8_t cmd;
73
74     /* struct ovs_header. */
75     int dp_ifindex;
76
77     /* Attributes. */
78     const char *name;                  /* OVS_DP_ATTR_NAME. */
79     const uint32_t *upcall_pid;        /* OVS_DP_ATTR_UPCALL_PID. */
80     uint32_t user_features;            /* OVS_DP_ATTR_USER_FEATURES */
81     const struct ovs_dp_stats *stats;  /* OVS_DP_ATTR_STATS. */
82     const struct ovs_dp_megaflow_stats *megaflow_stats;
83                                        /* OVS_DP_ATTR_MEGAFLOW_STATS.*/
84 };
85
86 static void dpif_netlink_dp_init(struct dpif_netlink_dp *);
87 static int dpif_netlink_dp_from_ofpbuf(struct dpif_netlink_dp *,
88                                        const struct ofpbuf *);
89 static void dpif_netlink_dp_dump_start(struct nl_dump *);
90 static int dpif_netlink_dp_transact(const struct dpif_netlink_dp *request,
91                                     struct dpif_netlink_dp *reply,
92                                     struct ofpbuf **bufp);
93 static int dpif_netlink_dp_get(const struct dpif *,
94                                struct dpif_netlink_dp *reply,
95                                struct ofpbuf **bufp);
96
97 struct dpif_netlink_flow {
98     /* Generic Netlink header. */
99     uint8_t cmd;
100
101     /* struct ovs_header. */
102     unsigned int nlmsg_flags;
103     int dp_ifindex;
104
105     /* Attributes.
106      *
107      * The 'stats' member points to 64-bit data that might only be aligned on
108      * 32-bit boundaries, so get_unaligned_u64() should be used to access its
109      * values.
110      *
111      * If 'actions' is nonnull then OVS_FLOW_ATTR_ACTIONS will be included in
112      * the Netlink version of the command, even if actions_len is zero. */
113     const struct nlattr *key;           /* OVS_FLOW_ATTR_KEY. */
114     size_t key_len;
115     const struct nlattr *mask;          /* OVS_FLOW_ATTR_MASK. */
116     size_t mask_len;
117     const struct nlattr *actions;       /* OVS_FLOW_ATTR_ACTIONS. */
118     size_t actions_len;
119     ovs_u128 ufid;                      /* OVS_FLOW_ATTR_FLOW_ID. */
120     bool ufid_present;                  /* Is there a UFID? */
121     bool ufid_terse;                    /* Skip serializing key/mask/acts? */
122     const struct ovs_flow_stats *stats; /* OVS_FLOW_ATTR_STATS. */
123     const uint8_t *tcp_flags;           /* OVS_FLOW_ATTR_TCP_FLAGS. */
124     const ovs_32aligned_u64 *used;      /* OVS_FLOW_ATTR_USED. */
125     bool clear;                         /* OVS_FLOW_ATTR_CLEAR. */
126     bool probe;                         /* OVS_FLOW_ATTR_PROBE. */
127 };
128
129 static void dpif_netlink_flow_init(struct dpif_netlink_flow *);
130 static int dpif_netlink_flow_from_ofpbuf(struct dpif_netlink_flow *,
131                                          const struct ofpbuf *);
132 static void dpif_netlink_flow_to_ofpbuf(const struct dpif_netlink_flow *,
133                                         struct ofpbuf *);
134 static int dpif_netlink_flow_transact(struct dpif_netlink_flow *request,
135                                       struct dpif_netlink_flow *reply,
136                                       struct ofpbuf **bufp);
137 static void dpif_netlink_flow_get_stats(const struct dpif_netlink_flow *,
138                                         struct dpif_flow_stats *);
139 static void dpif_netlink_flow_to_dpif_flow(struct dpif *, struct dpif_flow *,
140                                            const struct dpif_netlink_flow *);
141
142 /* One of the dpif channels between the kernel and userspace. */
143 struct dpif_channel {
144     struct nl_sock *sock;       /* Netlink socket. */
145     long long int last_poll;    /* Last time this channel was polled. */
146 };
147
148 #ifdef _WIN32
149 #define VPORT_SOCK_POOL_SIZE 1
150 /* On Windows, there is no native support for epoll.  There are equivalent
151  * interfaces though, that are not used currently.  For simpicity, a pool of
152  * netlink sockets is used.  Each socket is represented by 'struct
153  * dpif_windows_vport_sock'.  Since it is a pool, multiple OVS ports may be
154  * sharing the same socket.  In the future, we can add a reference count and
155  * such fields. */
156 struct dpif_windows_vport_sock {
157     struct nl_sock *nl_sock;    /* netlink socket. */
158 };
159 #endif
160
161 struct dpif_handler {
162     struct dpif_channel *channels;/* Array of channels for each handler. */
163     struct epoll_event *epoll_events;
164     int epoll_fd;                 /* epoll fd that includes channel socks. */
165     int n_events;                 /* Num events returned by epoll_wait(). */
166     int event_offset;             /* Offset into 'epoll_events'. */
167
168 #ifdef _WIN32
169     /* Pool of sockets. */
170     struct dpif_windows_vport_sock *vport_sock_pool;
171     size_t last_used_pool_idx; /* Index to aid in allocating a
172                                   socket in the pool to a port. */
173 #endif
174 };
175
176 /* Datapath interface for the openvswitch Linux kernel module. */
177 struct dpif_netlink {
178     struct dpif dpif;
179     int dp_ifindex;
180
181     /* Upcall messages. */
182     struct fat_rwlock upcall_lock;
183     struct dpif_handler *handlers;
184     uint32_t n_handlers;           /* Num of upcall handlers. */
185     int uc_array_size;             /* Size of 'handler->channels' and */
186                                    /* 'handler->epoll_events'. */
187
188     /* Change notification. */
189     struct nl_sock *port_notifier; /* vport multicast group subscriber. */
190     bool refresh_channels;
191 };
192
193 static void report_loss(struct dpif_netlink *, struct dpif_channel *,
194                         uint32_t ch_idx, uint32_t handler_id);
195
196 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
197
198 /* Generic Netlink family numbers for OVS.
199  *
200  * Initialized by dpif_netlink_init(). */
201 static int ovs_datapath_family;
202 static int ovs_vport_family;
203 static int ovs_flow_family;
204 static int ovs_packet_family;
205
206 /* Generic Netlink multicast groups for OVS.
207  *
208  * Initialized by dpif_netlink_init(). */
209 static unsigned int ovs_vport_mcgroup;
210
211 static int dpif_netlink_init(void);
212 static int open_dpif(const struct dpif_netlink_dp *, struct dpif **);
213 static uint32_t dpif_netlink_port_get_pid(const struct dpif *,
214                                           odp_port_t port_no, uint32_t hash);
215 static void dpif_netlink_handler_uninit(struct dpif_handler *handler);
216 static int dpif_netlink_refresh_channels(struct dpif_netlink *,
217                                          uint32_t n_handlers);
218 static void dpif_netlink_vport_to_ofpbuf(const struct dpif_netlink_vport *,
219                                          struct ofpbuf *);
220 static int dpif_netlink_vport_from_ofpbuf(struct dpif_netlink_vport *,
221                                           const struct ofpbuf *);
222
223 static struct dpif_netlink *
224 dpif_netlink_cast(const struct dpif *dpif)
225 {
226     dpif_assert_class(dpif, &dpif_netlink_class);
227     return CONTAINER_OF(dpif, struct dpif_netlink, dpif);
228 }
229
230 static int
231 dpif_netlink_enumerate(struct sset *all_dps,
232                        const struct dpif_class *dpif_class OVS_UNUSED)
233 {
234     struct nl_dump dump;
235     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
236     struct ofpbuf msg, buf;
237     int error;
238
239     error = dpif_netlink_init();
240     if (error) {
241         return error;
242     }
243
244     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
245     dpif_netlink_dp_dump_start(&dump);
246     while (nl_dump_next(&dump, &msg, &buf)) {
247         struct dpif_netlink_dp dp;
248
249         if (!dpif_netlink_dp_from_ofpbuf(&dp, &msg)) {
250             sset_add(all_dps, dp.name);
251         }
252     }
253     ofpbuf_uninit(&buf);
254     return nl_dump_done(&dump);
255 }
256
257 static int
258 dpif_netlink_open(const struct dpif_class *class OVS_UNUSED, const char *name,
259                   bool create, struct dpif **dpifp)
260 {
261     struct dpif_netlink_dp dp_request, dp;
262     struct ofpbuf *buf;
263     uint32_t upcall_pid;
264     int error;
265
266     error = dpif_netlink_init();
267     if (error) {
268         return error;
269     }
270
271     /* Create or look up datapath. */
272     dpif_netlink_dp_init(&dp_request);
273     if (create) {
274         dp_request.cmd = OVS_DP_CMD_NEW;
275         upcall_pid = 0;
276         dp_request.upcall_pid = &upcall_pid;
277     } else {
278         /* Use OVS_DP_CMD_SET to report user features */
279         dp_request.cmd = OVS_DP_CMD_SET;
280     }
281     dp_request.name = name;
282     dp_request.user_features |= OVS_DP_F_UNALIGNED;
283     dp_request.user_features |= OVS_DP_F_VPORT_PIDS;
284     error = dpif_netlink_dp_transact(&dp_request, &dp, &buf);
285     if (error) {
286         return error;
287     }
288
289     error = open_dpif(&dp, dpifp);
290     ofpbuf_delete(buf);
291     return error;
292 }
293
294 static int
295 open_dpif(const struct dpif_netlink_dp *dp, struct dpif **dpifp)
296 {
297     struct dpif_netlink *dpif;
298
299     dpif = xzalloc(sizeof *dpif);
300     dpif->port_notifier = NULL;
301     fat_rwlock_init(&dpif->upcall_lock);
302
303     dpif_init(&dpif->dpif, &dpif_netlink_class, dp->name,
304               dp->dp_ifindex, dp->dp_ifindex);
305
306     dpif->dp_ifindex = dp->dp_ifindex;
307     *dpifp = &dpif->dpif;
308
309     return 0;
310 }
311
312 /* Destroys the netlink sockets pointed by the elements in 'socksp'
313  * and frees the 'socksp'.  */
314 static void
315 vport_del_socksp__(struct nl_sock **socksp, uint32_t n_socks)
316 {
317     size_t i;
318
319     for (i = 0; i < n_socks; i++) {
320         nl_sock_destroy(socksp[i]);
321     }
322
323     free(socksp);
324 }
325
326 /* Creates an array of netlink sockets.  Returns an array of the
327  * corresponding pointers.  Records the error in 'error'. */
328 static struct nl_sock **
329 vport_create_socksp__(uint32_t n_socks, int *error)
330 {
331     struct nl_sock **socksp = xzalloc(n_socks * sizeof *socksp);
332     size_t i;
333
334     for (i = 0; i < n_socks; i++) {
335         *error = nl_sock_create(NETLINK_GENERIC, &socksp[i]);
336         if (*error) {
337             goto error;
338         }
339     }
340
341     return socksp;
342
343 error:
344     vport_del_socksp__(socksp, n_socks);
345
346     return NULL;
347 }
348
349 #ifdef _WIN32
350 static void
351 vport_delete_sock_pool(struct dpif_handler *handler)
352     OVS_REQ_WRLOCK(dpif->upcall_lock)
353 {
354     if (handler->vport_sock_pool) {
355         uint32_t i;
356         struct dpif_windows_vport_sock *sock_pool =
357             handler->vport_sock_pool;
358
359         for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
360             if (sock_pool[i].nl_sock) {
361                 nl_sock_unsubscribe_packets(sock_pool[i].nl_sock);
362                 nl_sock_destroy(sock_pool[i].nl_sock);
363                 sock_pool[i].nl_sock = NULL;
364             }
365         }
366
367         free(handler->vport_sock_pool);
368         handler->vport_sock_pool = NULL;
369     }
370 }
371
372 static int
373 vport_create_sock_pool(struct dpif_handler *handler)
374     OVS_REQ_WRLOCK(dpif->upcall_lock)
375 {
376     struct dpif_windows_vport_sock *sock_pool;
377     size_t i;
378     int error = 0;
379
380     sock_pool = xzalloc(VPORT_SOCK_POOL_SIZE * sizeof *sock_pool);
381     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
382         error = nl_sock_create(NETLINK_GENERIC, &sock_pool[i].nl_sock);
383         if (error) {
384             goto error;
385         }
386
387         /* Enable the netlink socket to receive packets.  This is equivalent to
388          * calling nl_sock_join_mcgroup() to receive events. */
389         error = nl_sock_subscribe_packets(sock_pool[i].nl_sock);
390         if (error) {
391            goto error;
392         }
393     }
394
395     handler->vport_sock_pool = sock_pool;
396     handler->last_used_pool_idx = 0;
397     return 0;
398
399 error:
400     vport_delete_sock_pool(handler);
401     return error;
402 }
403
404 /* Returns an array pointers to netlink sockets.  The sockets are picked from a
405  * pool. Records the error in 'error'. */
406 static struct nl_sock **
407 vport_create_socksp_windows(struct dpif_netlink *dpif, int *error)
408     OVS_REQ_WRLOCK(dpif->upcall_lock)
409 {
410     uint32_t n_socks = dpif->n_handlers;
411     struct nl_sock **socksp;
412     size_t i;
413
414     ovs_assert(n_socks <= 1);
415     socksp = xzalloc(n_socks * sizeof *socksp);
416
417     /* Pick netlink sockets to use in a round-robin fashion from each
418      * handler's pool of sockets. */
419     for (i = 0; i < n_socks; i++) {
420         struct dpif_handler *handler = &dpif->handlers[i];
421         struct dpif_windows_vport_sock *sock_pool = handler->vport_sock_pool;
422         size_t index = handler->last_used_pool_idx;
423
424         /* A pool of sockets is allocated when the handler is initialized. */
425         if (sock_pool == NULL) {
426             free(socksp);
427             *error = EINVAL;
428             return NULL;
429         }
430
431         ovs_assert(index < VPORT_SOCK_POOL_SIZE);
432         socksp[i] = sock_pool[index].nl_sock;
433         socksp[i] = sock_pool[index].nl_sock;
434         ovs_assert(socksp[i]);
435         index = (index == VPORT_SOCK_POOL_SIZE - 1) ? 0 : index + 1;
436         handler->last_used_pool_idx = index;
437     }
438
439     return socksp;
440 }
441
442 static void
443 vport_del_socksp_windows(struct dpif_netlink *dpif, struct nl_sock **socksp)
444 {
445     free(socksp);
446 }
447 #endif /* _WIN32 */
448
449 static struct nl_sock **
450 vport_create_socksp(struct dpif_netlink *dpif, int *error)
451 {
452 #ifdef _WIN32
453     return vport_create_socksp_windows(dpif, error);
454 #else
455     return vport_create_socksp__(dpif->n_handlers, error);
456 #endif
457 }
458
459 static void
460 vport_del_socksp(struct dpif_netlink *dpif, struct nl_sock **socksp)
461 {
462 #ifdef _WIN32
463     vport_del_socksp_windows(dpif, socksp);
464 #else
465     vport_del_socksp__(socksp, dpif->n_handlers);
466 #endif
467 }
468
469 /* Given the array of pointers to netlink sockets 'socksp', returns
470  * the array of corresponding pids. If the 'socksp' is NULL, returns
471  * a single-element array of value 0. */
472 static uint32_t *
473 vport_socksp_to_pids(struct nl_sock **socksp, uint32_t n_socks)
474 {
475     uint32_t *pids;
476
477     if (!socksp) {
478         pids = xzalloc(sizeof *pids);
479     } else {
480         size_t i;
481
482         pids = xzalloc(n_socks * sizeof *pids);
483         for (i = 0; i < n_socks; i++) {
484             pids[i] = nl_sock_pid(socksp[i]);
485         }
486     }
487
488     return pids;
489 }
490
491 /* Given the port number 'port_idx', extracts the pids of netlink sockets
492  * associated to the port and assigns it to 'upcall_pids'. */
493 static bool
494 vport_get_pids(struct dpif_netlink *dpif, uint32_t port_idx,
495                uint32_t **upcall_pids)
496 {
497     uint32_t *pids;
498     size_t i;
499
500     /* Since the nl_sock can only be assigned in either all
501      * or none "dpif->handlers" channels, the following check
502      * would suffice. */
503     if (!dpif->handlers[0].channels[port_idx].sock) {
504         return false;
505     }
506     ovs_assert(!WINDOWS || dpif->n_handlers <= 1);
507
508     pids = xzalloc(dpif->n_handlers * sizeof *pids);
509
510     for (i = 0; i < dpif->n_handlers; i++) {
511         pids[i] = nl_sock_pid(dpif->handlers[i].channels[port_idx].sock);
512     }
513
514     *upcall_pids = pids;
515
516     return true;
517 }
518
519 static int
520 vport_add_channels(struct dpif_netlink *dpif, odp_port_t port_no,
521                    struct nl_sock **socksp)
522 {
523     struct epoll_event event;
524     uint32_t port_idx = odp_to_u32(port_no);
525     size_t i, j;
526     int error;
527
528     if (dpif->handlers == NULL) {
529         return 0;
530     }
531
532     /* We assume that the datapath densely chooses port numbers, which can
533      * therefore be used as an index into 'channels' and 'epoll_events' of
534      * 'dpif->handler'. */
535     if (port_idx >= dpif->uc_array_size) {
536         uint32_t new_size = port_idx + 1;
537
538         if (new_size > MAX_PORTS) {
539             VLOG_WARN_RL(&error_rl, "%s: datapath port %"PRIu32" too big",
540                          dpif_name(&dpif->dpif), port_no);
541             return EFBIG;
542         }
543
544         for (i = 0; i < dpif->n_handlers; i++) {
545             struct dpif_handler *handler = &dpif->handlers[i];
546
547             handler->channels = xrealloc(handler->channels,
548                                          new_size * sizeof *handler->channels);
549
550             for (j = dpif->uc_array_size; j < new_size; j++) {
551                 handler->channels[j].sock = NULL;
552             }
553
554             handler->epoll_events = xrealloc(handler->epoll_events,
555                 new_size * sizeof *handler->epoll_events);
556
557         }
558         dpif->uc_array_size = new_size;
559     }
560
561     memset(&event, 0, sizeof event);
562     event.events = EPOLLIN;
563     event.data.u32 = port_idx;
564
565     for (i = 0; i < dpif->n_handlers; i++) {
566         struct dpif_handler *handler = &dpif->handlers[i];
567
568 #ifndef _WIN32
569         if (epoll_ctl(handler->epoll_fd, EPOLL_CTL_ADD, nl_sock_fd(socksp[i]),
570                       &event) < 0) {
571             error = errno;
572             goto error;
573         }
574 #endif
575         dpif->handlers[i].channels[port_idx].sock = socksp[i];
576         dpif->handlers[i].channels[port_idx].last_poll = LLONG_MIN;
577     }
578
579     return 0;
580
581 error:
582     for (j = 0; j < i; j++) {
583 #ifndef _WIN32
584         epoll_ctl(dpif->handlers[j].epoll_fd, EPOLL_CTL_DEL,
585                   nl_sock_fd(socksp[j]), NULL);
586 #endif
587         dpif->handlers[j].channels[port_idx].sock = NULL;
588     }
589
590     return error;
591 }
592
593 static void
594 vport_del_channels(struct dpif_netlink *dpif, odp_port_t port_no)
595 {
596     uint32_t port_idx = odp_to_u32(port_no);
597     size_t i;
598
599     if (!dpif->handlers || port_idx >= dpif->uc_array_size) {
600         return;
601     }
602
603     /* Since the sock can only be assigned in either all or none
604      * of "dpif->handlers" channels, the following check would
605      * suffice. */
606     if (!dpif->handlers[0].channels[port_idx].sock) {
607         return;
608     }
609
610     for (i = 0; i < dpif->n_handlers; i++) {
611         struct dpif_handler *handler = &dpif->handlers[i];
612 #ifndef _WIN32
613         epoll_ctl(handler->epoll_fd, EPOLL_CTL_DEL,
614                   nl_sock_fd(handler->channels[port_idx].sock), NULL);
615         nl_sock_destroy(handler->channels[port_idx].sock);
616 #endif
617         handler->channels[port_idx].sock = NULL;
618         handler->event_offset = handler->n_events = 0;
619     }
620 }
621
622 static void
623 destroy_all_channels(struct dpif_netlink *dpif)
624     OVS_REQ_WRLOCK(dpif->upcall_lock)
625 {
626     unsigned int i;
627
628     if (!dpif->handlers) {
629         return;
630     }
631
632     for (i = 0; i < dpif->uc_array_size; i++ ) {
633         struct dpif_netlink_vport vport_request;
634         uint32_t upcall_pids = 0;
635
636         /* Since the sock can only be assigned in either all or none
637          * of "dpif->handlers" channels, the following check would
638          * suffice. */
639         if (!dpif->handlers[0].channels[i].sock) {
640             continue;
641         }
642
643         /* Turn off upcalls. */
644         dpif_netlink_vport_init(&vport_request);
645         vport_request.cmd = OVS_VPORT_CMD_SET;
646         vport_request.dp_ifindex = dpif->dp_ifindex;
647         vport_request.port_no = u32_to_odp(i);
648         vport_request.n_upcall_pids = 1;
649         vport_request.upcall_pids = &upcall_pids;
650         dpif_netlink_vport_transact(&vport_request, NULL, NULL);
651
652         vport_del_channels(dpif, u32_to_odp(i));
653     }
654
655     for (i = 0; i < dpif->n_handlers; i++) {
656         struct dpif_handler *handler = &dpif->handlers[i];
657
658         dpif_netlink_handler_uninit(handler);
659         free(handler->epoll_events);
660         free(handler->channels);
661     }
662
663     free(dpif->handlers);
664     dpif->handlers = NULL;
665     dpif->n_handlers = 0;
666     dpif->uc_array_size = 0;
667 }
668
669 static void
670 dpif_netlink_close(struct dpif *dpif_)
671 {
672     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
673
674     nl_sock_destroy(dpif->port_notifier);
675
676     fat_rwlock_wrlock(&dpif->upcall_lock);
677     destroy_all_channels(dpif);
678     fat_rwlock_unlock(&dpif->upcall_lock);
679
680     fat_rwlock_destroy(&dpif->upcall_lock);
681     free(dpif);
682 }
683
684 static int
685 dpif_netlink_destroy(struct dpif *dpif_)
686 {
687     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
688     struct dpif_netlink_dp dp;
689
690     dpif_netlink_dp_init(&dp);
691     dp.cmd = OVS_DP_CMD_DEL;
692     dp.dp_ifindex = dpif->dp_ifindex;
693     return dpif_netlink_dp_transact(&dp, NULL, NULL);
694 }
695
696 static bool
697 dpif_netlink_run(struct dpif *dpif_)
698 {
699     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
700
701     if (dpif->refresh_channels) {
702         dpif->refresh_channels = false;
703         fat_rwlock_wrlock(&dpif->upcall_lock);
704         dpif_netlink_refresh_channels(dpif, dpif->n_handlers);
705         fat_rwlock_unlock(&dpif->upcall_lock);
706     }
707     return false;
708 }
709
710 static int
711 dpif_netlink_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
712 {
713     struct dpif_netlink_dp dp;
714     struct ofpbuf *buf;
715     int error;
716
717     error = dpif_netlink_dp_get(dpif_, &dp, &buf);
718     if (!error) {
719         memset(stats, 0, sizeof *stats);
720
721         if (dp.stats) {
722             stats->n_hit    = get_32aligned_u64(&dp.stats->n_hit);
723             stats->n_missed = get_32aligned_u64(&dp.stats->n_missed);
724             stats->n_lost   = get_32aligned_u64(&dp.stats->n_lost);
725             stats->n_flows  = get_32aligned_u64(&dp.stats->n_flows);
726         }
727
728         if (dp.megaflow_stats) {
729             stats->n_masks = dp.megaflow_stats->n_masks;
730             stats->n_mask_hit = get_32aligned_u64(
731                 &dp.megaflow_stats->n_mask_hit);
732         } else {
733             stats->n_masks = UINT32_MAX;
734             stats->n_mask_hit = UINT64_MAX;
735         }
736         ofpbuf_delete(buf);
737     }
738     return error;
739 }
740
741 static const char *
742 get_vport_type(const struct dpif_netlink_vport *vport)
743 {
744     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
745
746     switch (vport->type) {
747     case OVS_VPORT_TYPE_NETDEV: {
748         const char *type = netdev_get_type_from_name(vport->name);
749
750         return type ? type : "system";
751     }
752
753     case OVS_VPORT_TYPE_INTERNAL:
754         return "internal";
755
756     case OVS_VPORT_TYPE_GENEVE:
757         return "geneve";
758
759     case OVS_VPORT_TYPE_GRE:
760         return "gre";
761
762     case OVS_VPORT_TYPE_VXLAN:
763         return "vxlan";
764
765     case OVS_VPORT_TYPE_LISP:
766         return "lisp";
767
768     case OVS_VPORT_TYPE_STT:
769         return "stt";
770
771     case OVS_VPORT_TYPE_UNSPEC:
772     case __OVS_VPORT_TYPE_MAX:
773         break;
774     }
775
776     VLOG_WARN_RL(&rl, "dp%d: port `%s' has unsupported type %u",
777                  vport->dp_ifindex, vport->name, (unsigned int) vport->type);
778     return "unknown";
779 }
780
781 static enum ovs_vport_type
782 netdev_to_ovs_vport_type(const struct netdev *netdev)
783 {
784     const char *type = netdev_get_type(netdev);
785
786     if (!strcmp(type, "tap") || !strcmp(type, "system")) {
787         return OVS_VPORT_TYPE_NETDEV;
788     } else if (!strcmp(type, "internal")) {
789         return OVS_VPORT_TYPE_INTERNAL;
790     } else if (strstr(type, "stt")) {
791         return OVS_VPORT_TYPE_STT;
792     } else if (!strcmp(type, "geneve")) {
793         return OVS_VPORT_TYPE_GENEVE;
794     } else if (strstr(type, "gre")) {
795         return OVS_VPORT_TYPE_GRE;
796     } else if (!strcmp(type, "vxlan")) {
797         return OVS_VPORT_TYPE_VXLAN;
798     } else if (!strcmp(type, "lisp")) {
799         return OVS_VPORT_TYPE_LISP;
800     } else {
801         return OVS_VPORT_TYPE_UNSPEC;
802     }
803 }
804
805 static int
806 dpif_netlink_port_add__(struct dpif_netlink *dpif, struct netdev *netdev,
807                         odp_port_t *port_nop)
808     OVS_REQ_WRLOCK(dpif->upcall_lock)
809 {
810     const struct netdev_tunnel_config *tnl_cfg;
811     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
812     const char *name = netdev_vport_get_dpif_port(netdev,
813                                                   namebuf, sizeof namebuf);
814     const char *type = netdev_get_type(netdev);
815     struct dpif_netlink_vport request, reply;
816     struct ofpbuf *buf;
817     uint64_t options_stub[64 / 8];
818     struct ofpbuf options;
819     struct nl_sock **socksp = NULL;
820     uint32_t *upcall_pids;
821     int error = 0;
822
823     if (dpif->handlers) {
824         socksp = vport_create_socksp(dpif, &error);
825         if (!socksp) {
826             return error;
827         }
828     }
829
830     dpif_netlink_vport_init(&request);
831     request.cmd = OVS_VPORT_CMD_NEW;
832     request.dp_ifindex = dpif->dp_ifindex;
833     request.type = netdev_to_ovs_vport_type(netdev);
834     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
835         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
836                      "unsupported type `%s'",
837                      dpif_name(&dpif->dpif), name, type);
838         vport_del_socksp(dpif, socksp);
839         return EINVAL;
840     }
841     request.name = name;
842
843     if (request.type == OVS_VPORT_TYPE_NETDEV) {
844 #ifdef _WIN32
845         /* XXX : Map appropiate Windows handle */
846 #else
847         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
848 #endif
849     }
850
851     tnl_cfg = netdev_get_tunnel_config(netdev);
852     if (tnl_cfg && (tnl_cfg->dst_port != 0 || tnl_cfg->exts)) {
853         ofpbuf_use_stack(&options, options_stub, sizeof options_stub);
854         if (tnl_cfg->dst_port) {
855             nl_msg_put_u16(&options, OVS_TUNNEL_ATTR_DST_PORT,
856                            ntohs(tnl_cfg->dst_port));
857         }
858         if (tnl_cfg->exts) {
859             size_t ext_ofs;
860             int i;
861
862             ext_ofs = nl_msg_start_nested(&options, OVS_TUNNEL_ATTR_EXTENSION);
863             for (i = 0; i < 32; i++) {
864                 if (tnl_cfg->exts & (1 << i)) {
865                     nl_msg_put_flag(&options, i);
866                 }
867             }
868             nl_msg_end_nested(&options, ext_ofs);
869         }
870         request.options = options.data;
871         request.options_len = options.size;
872     }
873
874     request.port_no = *port_nop;
875     upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
876     request.n_upcall_pids = socksp ? dpif->n_handlers : 1;
877     request.upcall_pids = upcall_pids;
878
879     error = dpif_netlink_vport_transact(&request, &reply, &buf);
880     if (!error) {
881         *port_nop = reply.port_no;
882     } else {
883         if (error == EBUSY && *port_nop != ODPP_NONE) {
884             VLOG_INFO("%s: requested port %"PRIu32" is in use",
885                       dpif_name(&dpif->dpif), *port_nop);
886         }
887
888         vport_del_socksp(dpif, socksp);
889         goto exit;
890     }
891
892     if (socksp) {
893         error = vport_add_channels(dpif, *port_nop, socksp);
894         if (error) {
895             VLOG_INFO("%s: could not add channel for port %s",
896                       dpif_name(&dpif->dpif), name);
897
898             /* Delete the port. */
899             dpif_netlink_vport_init(&request);
900             request.cmd = OVS_VPORT_CMD_DEL;
901             request.dp_ifindex = dpif->dp_ifindex;
902             request.port_no = *port_nop;
903             dpif_netlink_vport_transact(&request, NULL, NULL);
904             vport_del_socksp(dpif, socksp);
905             goto exit;
906         }
907     }
908     free(socksp);
909
910 exit:
911     ofpbuf_delete(buf);
912     free(upcall_pids);
913
914     return error;
915 }
916
917 static int
918 dpif_netlink_port_add(struct dpif *dpif_, struct netdev *netdev,
919                       odp_port_t *port_nop)
920 {
921     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
922     int error;
923
924     fat_rwlock_wrlock(&dpif->upcall_lock);
925     error = dpif_netlink_port_add__(dpif, netdev, port_nop);
926     fat_rwlock_unlock(&dpif->upcall_lock);
927
928     return error;
929 }
930
931 static int
932 dpif_netlink_port_del__(struct dpif_netlink *dpif, odp_port_t port_no)
933     OVS_REQ_WRLOCK(dpif->upcall_lock)
934 {
935     struct dpif_netlink_vport vport;
936     int error;
937
938     dpif_netlink_vport_init(&vport);
939     vport.cmd = OVS_VPORT_CMD_DEL;
940     vport.dp_ifindex = dpif->dp_ifindex;
941     vport.port_no = port_no;
942     error = dpif_netlink_vport_transact(&vport, NULL, NULL);
943
944     vport_del_channels(dpif, port_no);
945
946     return error;
947 }
948
949 static int
950 dpif_netlink_port_del(struct dpif *dpif_, odp_port_t port_no)
951 {
952     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
953     int error;
954
955     fat_rwlock_wrlock(&dpif->upcall_lock);
956     error = dpif_netlink_port_del__(dpif, port_no);
957     fat_rwlock_unlock(&dpif->upcall_lock);
958
959     return error;
960 }
961
962 static int
963 dpif_netlink_port_query__(const struct dpif_netlink *dpif, odp_port_t port_no,
964                           const char *port_name, struct dpif_port *dpif_port)
965 {
966     struct dpif_netlink_vport request;
967     struct dpif_netlink_vport reply;
968     struct ofpbuf *buf;
969     int error;
970
971     dpif_netlink_vport_init(&request);
972     request.cmd = OVS_VPORT_CMD_GET;
973     request.dp_ifindex = dpif->dp_ifindex;
974     request.port_no = port_no;
975     request.name = port_name;
976
977     error = dpif_netlink_vport_transact(&request, &reply, &buf);
978     if (!error) {
979         if (reply.dp_ifindex != request.dp_ifindex) {
980             /* A query by name reported that 'port_name' is in some datapath
981              * other than 'dpif', but the caller wants to know about 'dpif'. */
982             error = ENODEV;
983         } else if (dpif_port) {
984             dpif_port->name = xstrdup(reply.name);
985             dpif_port->type = xstrdup(get_vport_type(&reply));
986             dpif_port->port_no = reply.port_no;
987         }
988         ofpbuf_delete(buf);
989     }
990     return error;
991 }
992
993 static int
994 dpif_netlink_port_query_by_number(const struct dpif *dpif_, odp_port_t port_no,
995                                   struct dpif_port *dpif_port)
996 {
997     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
998
999     return dpif_netlink_port_query__(dpif, port_no, NULL, dpif_port);
1000 }
1001
1002 static int
1003 dpif_netlink_port_query_by_name(const struct dpif *dpif_, const char *devname,
1004                               struct dpif_port *dpif_port)
1005 {
1006     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1007
1008     return dpif_netlink_port_query__(dpif, 0, devname, dpif_port);
1009 }
1010
1011 static uint32_t
1012 dpif_netlink_port_get_pid__(const struct dpif_netlink *dpif,
1013                             odp_port_t port_no, uint32_t hash)
1014     OVS_REQ_RDLOCK(dpif->upcall_lock)
1015 {
1016     uint32_t port_idx = odp_to_u32(port_no);
1017     uint32_t pid = 0;
1018
1019     if (dpif->handlers && dpif->uc_array_size > 0) {
1020         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
1021          * channel, since it is not heavily loaded. */
1022         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
1023         struct dpif_handler *h = &dpif->handlers[hash % dpif->n_handlers];
1024
1025         /* Needs to check in case the socket pointer is changed in between
1026          * the holding of upcall_lock.  A known case happens when the main
1027          * thread deletes the vport while the handler thread is handling
1028          * the upcall from that port. */
1029         if (h->channels[idx].sock) {
1030             pid = nl_sock_pid(h->channels[idx].sock);
1031         }
1032     }
1033
1034     return pid;
1035 }
1036
1037 static uint32_t
1038 dpif_netlink_port_get_pid(const struct dpif *dpif_, odp_port_t port_no,
1039                           uint32_t hash)
1040 {
1041     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1042     uint32_t ret;
1043
1044     fat_rwlock_rdlock(&dpif->upcall_lock);
1045     ret = dpif_netlink_port_get_pid__(dpif, port_no, hash);
1046     fat_rwlock_unlock(&dpif->upcall_lock);
1047
1048     return ret;
1049 }
1050
1051 static int
1052 dpif_netlink_flow_flush(struct dpif *dpif_)
1053 {
1054     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1055     struct dpif_netlink_flow flow;
1056
1057     dpif_netlink_flow_init(&flow);
1058     flow.cmd = OVS_FLOW_CMD_DEL;
1059     flow.dp_ifindex = dpif->dp_ifindex;
1060     return dpif_netlink_flow_transact(&flow, NULL, NULL);
1061 }
1062
1063 struct dpif_netlink_port_state {
1064     struct nl_dump dump;
1065     struct ofpbuf buf;
1066 };
1067
1068 static void
1069 dpif_netlink_port_dump_start__(const struct dpif_netlink *dpif,
1070                                struct nl_dump *dump)
1071 {
1072     struct dpif_netlink_vport request;
1073     struct ofpbuf *buf;
1074
1075     dpif_netlink_vport_init(&request);
1076     request.cmd = OVS_VPORT_CMD_GET;
1077     request.dp_ifindex = dpif->dp_ifindex;
1078
1079     buf = ofpbuf_new(1024);
1080     dpif_netlink_vport_to_ofpbuf(&request, buf);
1081     nl_dump_start(dump, NETLINK_GENERIC, buf);
1082     ofpbuf_delete(buf);
1083 }
1084
1085 static int
1086 dpif_netlink_port_dump_start(const struct dpif *dpif_, void **statep)
1087 {
1088     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1089     struct dpif_netlink_port_state *state;
1090
1091     *statep = state = xmalloc(sizeof *state);
1092     dpif_netlink_port_dump_start__(dpif, &state->dump);
1093
1094     ofpbuf_init(&state->buf, NL_DUMP_BUFSIZE);
1095     return 0;
1096 }
1097
1098 static int
1099 dpif_netlink_port_dump_next__(const struct dpif_netlink *dpif,
1100                               struct nl_dump *dump,
1101                               struct dpif_netlink_vport *vport,
1102                               struct ofpbuf *buffer)
1103 {
1104     struct ofpbuf buf;
1105     int error;
1106
1107     if (!nl_dump_next(dump, &buf, buffer)) {
1108         return EOF;
1109     }
1110
1111     error = dpif_netlink_vport_from_ofpbuf(vport, &buf);
1112     if (error) {
1113         VLOG_WARN_RL(&error_rl, "%s: failed to parse vport record (%s)",
1114                      dpif_name(&dpif->dpif), ovs_strerror(error));
1115     }
1116     return error;
1117 }
1118
1119 static int
1120 dpif_netlink_port_dump_next(const struct dpif *dpif_, void *state_,
1121                             struct dpif_port *dpif_port)
1122 {
1123     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1124     struct dpif_netlink_port_state *state = state_;
1125     struct dpif_netlink_vport vport;
1126     int error;
1127
1128     error = dpif_netlink_port_dump_next__(dpif, &state->dump, &vport,
1129                                           &state->buf);
1130     if (error) {
1131         return error;
1132     }
1133     dpif_port->name = CONST_CAST(char *, vport.name);
1134     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
1135     dpif_port->port_no = vport.port_no;
1136     return 0;
1137 }
1138
1139 static int
1140 dpif_netlink_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
1141 {
1142     struct dpif_netlink_port_state *state = state_;
1143     int error = nl_dump_done(&state->dump);
1144
1145     ofpbuf_uninit(&state->buf);
1146     free(state);
1147     return error;
1148 }
1149
1150 static int
1151 dpif_netlink_port_poll(const struct dpif *dpif_, char **devnamep)
1152 {
1153     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1154
1155     /* Lazily create the Netlink socket to listen for notifications. */
1156     if (!dpif->port_notifier) {
1157         struct nl_sock *sock;
1158         int error;
1159
1160         error = nl_sock_create(NETLINK_GENERIC, &sock);
1161         if (error) {
1162             return error;
1163         }
1164
1165         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
1166         if (error) {
1167             nl_sock_destroy(sock);
1168             return error;
1169         }
1170         dpif->port_notifier = sock;
1171
1172         /* We have no idea of the current state so report that everything
1173          * changed. */
1174         return ENOBUFS;
1175     }
1176
1177     for (;;) {
1178         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1179         uint64_t buf_stub[4096 / 8];
1180         struct ofpbuf buf;
1181         int error;
1182
1183         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
1184         error = nl_sock_recv(dpif->port_notifier, &buf, false);
1185         if (!error) {
1186             struct dpif_netlink_vport vport;
1187
1188             error = dpif_netlink_vport_from_ofpbuf(&vport, &buf);
1189             if (!error) {
1190                 if (vport.dp_ifindex == dpif->dp_ifindex
1191                     && (vport.cmd == OVS_VPORT_CMD_NEW
1192                         || vport.cmd == OVS_VPORT_CMD_DEL
1193                         || vport.cmd == OVS_VPORT_CMD_SET)) {
1194                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1195                              dpif->dpif.full_name, vport.name, vport.cmd);
1196                     if (vport.cmd == OVS_VPORT_CMD_DEL && dpif->handlers) {
1197                         dpif->refresh_channels = true;
1198                     }
1199                     *devnamep = xstrdup(vport.name);
1200                     ofpbuf_uninit(&buf);
1201                     return 0;
1202                 }
1203             }
1204         } else if (error != EAGAIN) {
1205             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
1206                          ovs_strerror(error));
1207             nl_sock_drain(dpif->port_notifier);
1208             error = ENOBUFS;
1209         }
1210
1211         ofpbuf_uninit(&buf);
1212         if (error) {
1213             return error;
1214         }
1215     }
1216 }
1217
1218 static void
1219 dpif_netlink_port_poll_wait(const struct dpif *dpif_)
1220 {
1221     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1222
1223     if (dpif->port_notifier) {
1224         nl_sock_wait(dpif->port_notifier, POLLIN);
1225     } else {
1226         poll_immediate_wake();
1227     }
1228 }
1229
1230 static void
1231 dpif_netlink_flow_init_ufid(struct dpif_netlink_flow *request,
1232                             const ovs_u128 *ufid, bool terse)
1233 {
1234     if (ufid) {
1235         request->ufid = *ufid;
1236         request->ufid_present = true;
1237     } else {
1238         request->ufid_present = false;
1239     }
1240     request->ufid_terse = terse;
1241 }
1242
1243 static void
1244 dpif_netlink_init_flow_get__(const struct dpif_netlink *dpif,
1245                              const struct nlattr *key, size_t key_len,
1246                              const ovs_u128 *ufid, bool terse,
1247                              struct dpif_netlink_flow *request)
1248 {
1249     dpif_netlink_flow_init(request);
1250     request->cmd = OVS_FLOW_CMD_GET;
1251     request->dp_ifindex = dpif->dp_ifindex;
1252     request->key = key;
1253     request->key_len = key_len;
1254     dpif_netlink_flow_init_ufid(request, ufid, terse);
1255 }
1256
1257 static void
1258 dpif_netlink_init_flow_get(const struct dpif_netlink *dpif,
1259                            const struct dpif_flow_get *get,
1260                            struct dpif_netlink_flow *request)
1261 {
1262     dpif_netlink_init_flow_get__(dpif, get->key, get->key_len, get->ufid,
1263                                  false, request);
1264 }
1265
1266 static int
1267 dpif_netlink_flow_get__(const struct dpif_netlink *dpif,
1268                         const struct nlattr *key, size_t key_len,
1269                         const ovs_u128 *ufid, bool terse,
1270                         struct dpif_netlink_flow *reply, struct ofpbuf **bufp)
1271 {
1272     struct dpif_netlink_flow request;
1273
1274     dpif_netlink_init_flow_get__(dpif, key, key_len, ufid, terse, &request);
1275     return dpif_netlink_flow_transact(&request, reply, bufp);
1276 }
1277
1278 static int
1279 dpif_netlink_flow_get(const struct dpif_netlink *dpif,
1280                       const struct dpif_netlink_flow *flow,
1281                       struct dpif_netlink_flow *reply, struct ofpbuf **bufp)
1282 {
1283     return dpif_netlink_flow_get__(dpif, flow->key, flow->key_len,
1284                                    flow->ufid_present ? &flow->ufid : NULL,
1285                                    false, reply, bufp);
1286 }
1287
1288 static void
1289 dpif_netlink_init_flow_put(struct dpif_netlink *dpif,
1290                            const struct dpif_flow_put *put,
1291                            struct dpif_netlink_flow *request)
1292 {
1293     static const struct nlattr dummy_action;
1294
1295     dpif_netlink_flow_init(request);
1296     request->cmd = (put->flags & DPIF_FP_CREATE
1297                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
1298     request->dp_ifindex = dpif->dp_ifindex;
1299     request->key = put->key;
1300     request->key_len = put->key_len;
1301     request->mask = put->mask;
1302     request->mask_len = put->mask_len;
1303     dpif_netlink_flow_init_ufid(request, put->ufid, false);
1304
1305     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
1306     request->actions = (put->actions
1307                         ? put->actions
1308                         : CONST_CAST(struct nlattr *, &dummy_action));
1309     request->actions_len = put->actions_len;
1310     if (put->flags & DPIF_FP_ZERO_STATS) {
1311         request->clear = true;
1312     }
1313     if (put->flags & DPIF_FP_PROBE) {
1314         request->probe = true;
1315     }
1316     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
1317 }
1318
1319 static void
1320 dpif_netlink_init_flow_del__(struct dpif_netlink *dpif,
1321                              const struct nlattr *key, size_t key_len,
1322                              const ovs_u128 *ufid, bool terse,
1323                              struct dpif_netlink_flow *request)
1324 {
1325     dpif_netlink_flow_init(request);
1326     request->cmd = OVS_FLOW_CMD_DEL;
1327     request->dp_ifindex = dpif->dp_ifindex;
1328     request->key = key;
1329     request->key_len = key_len;
1330     dpif_netlink_flow_init_ufid(request, ufid, terse);
1331 }
1332
1333 static void
1334 dpif_netlink_init_flow_del(struct dpif_netlink *dpif,
1335                            const struct dpif_flow_del *del,
1336                            struct dpif_netlink_flow *request)
1337 {
1338     dpif_netlink_init_flow_del__(dpif, del->key, del->key_len,
1339                                  del->ufid, del->terse, request);
1340 }
1341
1342 struct dpif_netlink_flow_dump {
1343     struct dpif_flow_dump up;
1344     struct nl_dump nl_dump;
1345     atomic_int status;
1346 };
1347
1348 static struct dpif_netlink_flow_dump *
1349 dpif_netlink_flow_dump_cast(struct dpif_flow_dump *dump)
1350 {
1351     return CONTAINER_OF(dump, struct dpif_netlink_flow_dump, up);
1352 }
1353
1354 static struct dpif_flow_dump *
1355 dpif_netlink_flow_dump_create(const struct dpif *dpif_, bool terse)
1356 {
1357     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1358     struct dpif_netlink_flow_dump *dump;
1359     struct dpif_netlink_flow request;
1360     struct ofpbuf *buf;
1361
1362     dump = xmalloc(sizeof *dump);
1363     dpif_flow_dump_init(&dump->up, dpif_);
1364
1365     dpif_netlink_flow_init(&request);
1366     request.cmd = OVS_FLOW_CMD_GET;
1367     request.dp_ifindex = dpif->dp_ifindex;
1368     request.ufid_present = false;
1369     request.ufid_terse = terse;
1370
1371     buf = ofpbuf_new(1024);
1372     dpif_netlink_flow_to_ofpbuf(&request, buf);
1373     nl_dump_start(&dump->nl_dump, NETLINK_GENERIC, buf);
1374     ofpbuf_delete(buf);
1375     atomic_init(&dump->status, 0);
1376     dump->up.terse = terse;
1377
1378     return &dump->up;
1379 }
1380
1381 static int
1382 dpif_netlink_flow_dump_destroy(struct dpif_flow_dump *dump_)
1383 {
1384     struct dpif_netlink_flow_dump *dump = dpif_netlink_flow_dump_cast(dump_);
1385     unsigned int nl_status = nl_dump_done(&dump->nl_dump);
1386     int dump_status;
1387
1388     /* No other thread has access to 'dump' at this point. */
1389     atomic_read_relaxed(&dump->status, &dump_status);
1390     free(dump);
1391     return dump_status ? dump_status : nl_status;
1392 }
1393
1394 struct dpif_netlink_flow_dump_thread {
1395     struct dpif_flow_dump_thread up;
1396     struct dpif_netlink_flow_dump *dump;
1397     struct dpif_netlink_flow flow;
1398     struct dpif_flow_stats stats;
1399     struct ofpbuf nl_flows;     /* Always used to store flows. */
1400     struct ofpbuf *nl_actions;  /* Used if kernel does not supply actions. */
1401 };
1402
1403 static struct dpif_netlink_flow_dump_thread *
1404 dpif_netlink_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1405 {
1406     return CONTAINER_OF(thread, struct dpif_netlink_flow_dump_thread, up);
1407 }
1408
1409 static struct dpif_flow_dump_thread *
1410 dpif_netlink_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1411 {
1412     struct dpif_netlink_flow_dump *dump = dpif_netlink_flow_dump_cast(dump_);
1413     struct dpif_netlink_flow_dump_thread *thread;
1414
1415     thread = xmalloc(sizeof *thread);
1416     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1417     thread->dump = dump;
1418     ofpbuf_init(&thread->nl_flows, NL_DUMP_BUFSIZE);
1419     thread->nl_actions = NULL;
1420
1421     return &thread->up;
1422 }
1423
1424 static void
1425 dpif_netlink_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1426 {
1427     struct dpif_netlink_flow_dump_thread *thread
1428         = dpif_netlink_flow_dump_thread_cast(thread_);
1429
1430     ofpbuf_uninit(&thread->nl_flows);
1431     ofpbuf_delete(thread->nl_actions);
1432     free(thread);
1433 }
1434
1435 static void
1436 dpif_netlink_flow_to_dpif_flow(struct dpif *dpif, struct dpif_flow *dpif_flow,
1437                                const struct dpif_netlink_flow *datapath_flow)
1438 {
1439     dpif_flow->key = datapath_flow->key;
1440     dpif_flow->key_len = datapath_flow->key_len;
1441     dpif_flow->mask = datapath_flow->mask;
1442     dpif_flow->mask_len = datapath_flow->mask_len;
1443     dpif_flow->actions = datapath_flow->actions;
1444     dpif_flow->actions_len = datapath_flow->actions_len;
1445     dpif_flow->ufid_present = datapath_flow->ufid_present;
1446     dpif_flow->pmd_id = PMD_ID_NULL;
1447     if (datapath_flow->ufid_present) {
1448         dpif_flow->ufid = datapath_flow->ufid;
1449     } else {
1450         ovs_assert(datapath_flow->key && datapath_flow->key_len);
1451         dpif_flow_hash(dpif, datapath_flow->key, datapath_flow->key_len,
1452                        &dpif_flow->ufid);
1453     }
1454     dpif_netlink_flow_get_stats(datapath_flow, &dpif_flow->stats);
1455 }
1456
1457 static int
1458 dpif_netlink_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1459                             struct dpif_flow *flows, int max_flows)
1460 {
1461     struct dpif_netlink_flow_dump_thread *thread
1462         = dpif_netlink_flow_dump_thread_cast(thread_);
1463     struct dpif_netlink_flow_dump *dump = thread->dump;
1464     struct dpif_netlink *dpif = dpif_netlink_cast(thread->up.dpif);
1465     int n_flows;
1466
1467     ofpbuf_delete(thread->nl_actions);
1468     thread->nl_actions = NULL;
1469
1470     n_flows = 0;
1471     while (!n_flows
1472            || (n_flows < max_flows && thread->nl_flows.size)) {
1473         struct dpif_netlink_flow datapath_flow;
1474         struct ofpbuf nl_flow;
1475         int error;
1476
1477         /* Try to grab another flow. */
1478         if (!nl_dump_next(&dump->nl_dump, &nl_flow, &thread->nl_flows)) {
1479             break;
1480         }
1481
1482         /* Convert the flow to our output format. */
1483         error = dpif_netlink_flow_from_ofpbuf(&datapath_flow, &nl_flow);
1484         if (error) {
1485             atomic_store_relaxed(&dump->status, error);
1486             break;
1487         }
1488
1489         if (dump->up.terse || datapath_flow.actions) {
1490             /* Common case: we don't want actions, or the flow includes
1491              * actions. */
1492             dpif_netlink_flow_to_dpif_flow(&dpif->dpif, &flows[n_flows++],
1493                                            &datapath_flow);
1494         } else {
1495             /* Rare case: the flow does not include actions.  Retrieve this
1496              * individual flow again to get the actions. */
1497             error = dpif_netlink_flow_get(dpif, &datapath_flow,
1498                                           &datapath_flow, &thread->nl_actions);
1499             if (error == ENOENT) {
1500                 VLOG_DBG("dumped flow disappeared on get");
1501                 continue;
1502             } else if (error) {
1503                 VLOG_WARN("error fetching dumped flow: %s",
1504                           ovs_strerror(error));
1505                 atomic_store_relaxed(&dump->status, error);
1506                 break;
1507             }
1508
1509             /* Save this flow.  Then exit, because we only have one buffer to
1510              * handle this case. */
1511             dpif_netlink_flow_to_dpif_flow(&dpif->dpif, &flows[n_flows++],
1512                                            &datapath_flow);
1513             break;
1514         }
1515     }
1516     return n_flows;
1517 }
1518
1519 static void
1520 dpif_netlink_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1521                             struct ofpbuf *buf)
1522 {
1523     struct ovs_header *k_exec;
1524     size_t key_ofs;
1525
1526     ofpbuf_prealloc_tailroom(buf, (64
1527                                    + dp_packet_size(d_exec->packet)
1528                                    + ODP_KEY_METADATA_SIZE
1529                                    + d_exec->actions_len));
1530
1531     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1532                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1533
1534     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1535     k_exec->dp_ifindex = dp_ifindex;
1536
1537     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1538                       dp_packet_data(d_exec->packet),
1539                       dp_packet_size(d_exec->packet));
1540
1541     key_ofs = nl_msg_start_nested(buf, OVS_PACKET_ATTR_KEY);
1542     odp_key_from_pkt_metadata(buf, &d_exec->packet->md);
1543     nl_msg_end_nested(buf, key_ofs);
1544
1545     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1546                       d_exec->actions, d_exec->actions_len);
1547     if (d_exec->probe) {
1548         nl_msg_put_flag(buf, OVS_PACKET_ATTR_PROBE);
1549     }
1550 }
1551
1552 /* Executes, against 'dpif', up to the first 'n_ops' operations in 'ops'.
1553  * Returns the number actually executed (at least 1, if 'n_ops' is
1554  * positive). */
1555 static size_t
1556 dpif_netlink_operate__(struct dpif_netlink *dpif,
1557                        struct dpif_op **ops, size_t n_ops)
1558 {
1559     enum { MAX_OPS = 50 };
1560
1561     struct op_auxdata {
1562         struct nl_transaction txn;
1563
1564         struct ofpbuf request;
1565         uint64_t request_stub[1024 / 8];
1566
1567         struct ofpbuf reply;
1568         uint64_t reply_stub[1024 / 8];
1569     } auxes[MAX_OPS];
1570
1571     struct nl_transaction *txnsp[MAX_OPS];
1572     size_t i;
1573
1574     n_ops = MIN(n_ops, MAX_OPS);
1575     for (i = 0; i < n_ops; i++) {
1576         struct op_auxdata *aux = &auxes[i];
1577         struct dpif_op *op = ops[i];
1578         struct dpif_flow_put *put;
1579         struct dpif_flow_del *del;
1580         struct dpif_flow_get *get;
1581         struct dpif_netlink_flow flow;
1582
1583         ofpbuf_use_stub(&aux->request,
1584                         aux->request_stub, sizeof aux->request_stub);
1585         aux->txn.request = &aux->request;
1586
1587         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1588         aux->txn.reply = NULL;
1589
1590         switch (op->type) {
1591         case DPIF_OP_FLOW_PUT:
1592             put = &op->u.flow_put;
1593             dpif_netlink_init_flow_put(dpif, put, &flow);
1594             if (put->stats) {
1595                 flow.nlmsg_flags |= NLM_F_ECHO;
1596                 aux->txn.reply = &aux->reply;
1597             }
1598             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1599             break;
1600
1601         case DPIF_OP_FLOW_DEL:
1602             del = &op->u.flow_del;
1603             dpif_netlink_init_flow_del(dpif, del, &flow);
1604             if (del->stats) {
1605                 flow.nlmsg_flags |= NLM_F_ECHO;
1606                 aux->txn.reply = &aux->reply;
1607             }
1608             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1609             break;
1610
1611         case DPIF_OP_EXECUTE:
1612             /* Can't execute a packet that won't fit in a Netlink attribute. */
1613             if (OVS_UNLIKELY(nl_attr_oversized(
1614                                  dp_packet_size(op->u.execute.packet)))) {
1615                 /* Report an error immediately if this is the first operation.
1616                  * Otherwise the easiest thing to do is to postpone to the next
1617                  * call (when this will be the first operation). */
1618                 if (i == 0) {
1619                     VLOG_ERR_RL(&error_rl,
1620                                 "dropping oversized %"PRIu32"-byte packet",
1621                                 dp_packet_size(op->u.execute.packet));
1622                     op->error = ENOBUFS;
1623                     return 1;
1624                 }
1625                 n_ops = i;
1626             } else {
1627                 dpif_netlink_encode_execute(dpif->dp_ifindex, &op->u.execute,
1628                                             &aux->request);
1629             }
1630             break;
1631
1632         case DPIF_OP_FLOW_GET:
1633             get = &op->u.flow_get;
1634             dpif_netlink_init_flow_get(dpif, get, &flow);
1635             aux->txn.reply = get->buffer;
1636             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1637             break;
1638
1639         default:
1640             OVS_NOT_REACHED();
1641         }
1642     }
1643
1644     for (i = 0; i < n_ops; i++) {
1645         txnsp[i] = &auxes[i].txn;
1646     }
1647     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1648
1649     for (i = 0; i < n_ops; i++) {
1650         struct op_auxdata *aux = &auxes[i];
1651         struct nl_transaction *txn = &auxes[i].txn;
1652         struct dpif_op *op = ops[i];
1653         struct dpif_flow_put *put;
1654         struct dpif_flow_del *del;
1655         struct dpif_flow_get *get;
1656
1657         op->error = txn->error;
1658
1659         switch (op->type) {
1660         case DPIF_OP_FLOW_PUT:
1661             put = &op->u.flow_put;
1662             if (put->stats) {
1663                 if (!op->error) {
1664                     struct dpif_netlink_flow reply;
1665
1666                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1667                                                               txn->reply);
1668                     if (!op->error) {
1669                         dpif_netlink_flow_get_stats(&reply, put->stats);
1670                     }
1671                 }
1672             }
1673             break;
1674
1675         case DPIF_OP_FLOW_DEL:
1676             del = &op->u.flow_del;
1677             if (del->stats) {
1678                 if (!op->error) {
1679                     struct dpif_netlink_flow reply;
1680
1681                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1682                                                               txn->reply);
1683                     if (!op->error) {
1684                         dpif_netlink_flow_get_stats(&reply, del->stats);
1685                     }
1686                 }
1687             }
1688             break;
1689
1690         case DPIF_OP_EXECUTE:
1691             break;
1692
1693         case DPIF_OP_FLOW_GET:
1694             get = &op->u.flow_get;
1695             if (!op->error) {
1696                 struct dpif_netlink_flow reply;
1697
1698                 op->error = dpif_netlink_flow_from_ofpbuf(&reply, txn->reply);
1699                 if (!op->error) {
1700                     dpif_netlink_flow_to_dpif_flow(&dpif->dpif, get->flow,
1701                                                    &reply);
1702                 }
1703             }
1704             break;
1705
1706         default:
1707             OVS_NOT_REACHED();
1708         }
1709
1710         ofpbuf_uninit(&aux->request);
1711         ofpbuf_uninit(&aux->reply);
1712     }
1713
1714     return n_ops;
1715 }
1716
1717 static void
1718 dpif_netlink_operate(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1719 {
1720     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1721
1722     while (n_ops > 0) {
1723         size_t chunk = dpif_netlink_operate__(dpif, ops, n_ops);
1724         ops += chunk;
1725         n_ops -= chunk;
1726     }
1727 }
1728
1729 #if _WIN32
1730 static void
1731 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1732 {
1733     vport_delete_sock_pool(handler);
1734 }
1735
1736 static int
1737 dpif_netlink_handler_init(struct dpif_handler *handler)
1738 {
1739     return vport_create_sock_pool(handler);
1740 }
1741 #else
1742
1743 static int
1744 dpif_netlink_handler_init(struct dpif_handler *handler)
1745 {
1746     handler->epoll_fd = epoll_create(10);
1747     return handler->epoll_fd < 0 ? errno : 0;
1748 }
1749
1750 static void
1751 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1752 {
1753     close(handler->epoll_fd);
1754 }
1755 #endif
1756
1757 /* Synchronizes 'channels' in 'dpif->handlers'  with the set of vports
1758  * currently in 'dpif' in the kernel, by adding a new set of channels for
1759  * any kernel vport that lacks one and deleting any channels that have no
1760  * backing kernel vports. */
1761 static int
1762 dpif_netlink_refresh_channels(struct dpif_netlink *dpif, uint32_t n_handlers)
1763     OVS_REQ_WRLOCK(dpif->upcall_lock)
1764 {
1765     unsigned long int *keep_channels;
1766     struct dpif_netlink_vport vport;
1767     size_t keep_channels_nbits;
1768     struct nl_dump dump;
1769     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
1770     struct ofpbuf buf;
1771     int retval = 0;
1772     size_t i;
1773
1774     ovs_assert(!WINDOWS || n_handlers <= 1);
1775     ovs_assert(!WINDOWS || dpif->n_handlers <= 1);
1776
1777     if (dpif->n_handlers != n_handlers) {
1778         destroy_all_channels(dpif);
1779         dpif->handlers = xzalloc(n_handlers * sizeof *dpif->handlers);
1780         for (i = 0; i < n_handlers; i++) {
1781             int error;
1782             struct dpif_handler *handler = &dpif->handlers[i];
1783
1784             error = dpif_netlink_handler_init(handler);
1785             if (error) {
1786                 size_t j;
1787                 struct dpif_handler *tmp = &dpif->handlers[i];
1788
1789
1790                 for (j = 0; j < i; j++) {
1791                     dpif_netlink_handler_uninit(tmp);
1792                 }
1793                 free(dpif->handlers);
1794                 dpif->handlers = NULL;
1795
1796                 return error;
1797             }
1798         }
1799         dpif->n_handlers = n_handlers;
1800     }
1801
1802     for (i = 0; i < n_handlers; i++) {
1803         struct dpif_handler *handler = &dpif->handlers[i];
1804
1805         handler->event_offset = handler->n_events = 0;
1806     }
1807
1808     keep_channels_nbits = dpif->uc_array_size;
1809     keep_channels = bitmap_allocate(keep_channels_nbits);
1810
1811     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
1812     dpif_netlink_port_dump_start__(dpif, &dump);
1813     while (!dpif_netlink_port_dump_next__(dpif, &dump, &vport, &buf)) {
1814         uint32_t port_no = odp_to_u32(vport.port_no);
1815         uint32_t *upcall_pids = NULL;
1816         int error;
1817
1818         if (port_no >= dpif->uc_array_size
1819             || !vport_get_pids(dpif, port_no, &upcall_pids)) {
1820             struct nl_sock **socksp = vport_create_socksp(dpif, &error);
1821
1822             if (!socksp) {
1823                 goto error;
1824             }
1825
1826             error = vport_add_channels(dpif, vport.port_no, socksp);
1827             if (error) {
1828                 VLOG_INFO("%s: could not add channels for port %s",
1829                           dpif_name(&dpif->dpif), vport.name);
1830                 vport_del_socksp(dpif, socksp);
1831                 retval = error;
1832                 goto error;
1833             }
1834             upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
1835             free(socksp);
1836         }
1837
1838         /* Configure the vport to deliver misses to 'sock'. */
1839         if (vport.upcall_pids[0] == 0
1840             || vport.n_upcall_pids != dpif->n_handlers
1841             || memcmp(upcall_pids, vport.upcall_pids, n_handlers * sizeof
1842                       *upcall_pids)) {
1843             struct dpif_netlink_vport vport_request;
1844
1845             dpif_netlink_vport_init(&vport_request);
1846             vport_request.cmd = OVS_VPORT_CMD_SET;
1847             vport_request.dp_ifindex = dpif->dp_ifindex;
1848             vport_request.port_no = vport.port_no;
1849             vport_request.n_upcall_pids = dpif->n_handlers;
1850             vport_request.upcall_pids = upcall_pids;
1851             error = dpif_netlink_vport_transact(&vport_request, NULL, NULL);
1852             if (error) {
1853                 VLOG_WARN_RL(&error_rl,
1854                              "%s: failed to set upcall pid on port: %s",
1855                              dpif_name(&dpif->dpif), ovs_strerror(error));
1856
1857                 if (error != ENODEV && error != ENOENT) {
1858                     retval = error;
1859                 } else {
1860                     /* The vport isn't really there, even though the dump says
1861                      * it is.  Probably we just hit a race after a port
1862                      * disappeared. */
1863                 }
1864                 goto error;
1865             }
1866         }
1867
1868         if (port_no < keep_channels_nbits) {
1869             bitmap_set1(keep_channels, port_no);
1870         }
1871         free(upcall_pids);
1872         continue;
1873
1874     error:
1875         free(upcall_pids);
1876         vport_del_channels(dpif, vport.port_no);
1877     }
1878     nl_dump_done(&dump);
1879     ofpbuf_uninit(&buf);
1880
1881     /* Discard any saved channels that we didn't reuse. */
1882     for (i = 0; i < keep_channels_nbits; i++) {
1883         if (!bitmap_is_set(keep_channels, i)) {
1884             vport_del_channels(dpif, u32_to_odp(i));
1885         }
1886     }
1887     free(keep_channels);
1888
1889     return retval;
1890 }
1891
1892 static int
1893 dpif_netlink_recv_set__(struct dpif_netlink *dpif, bool enable)
1894     OVS_REQ_WRLOCK(dpif->upcall_lock)
1895 {
1896     if ((dpif->handlers != NULL) == enable) {
1897         return 0;
1898     } else if (!enable) {
1899         destroy_all_channels(dpif);
1900         return 0;
1901     } else {
1902         return dpif_netlink_refresh_channels(dpif, 1);
1903     }
1904 }
1905
1906 static int
1907 dpif_netlink_recv_set(struct dpif *dpif_, bool enable)
1908 {
1909     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1910     int error;
1911
1912     fat_rwlock_wrlock(&dpif->upcall_lock);
1913     error = dpif_netlink_recv_set__(dpif, enable);
1914     fat_rwlock_unlock(&dpif->upcall_lock);
1915
1916     return error;
1917 }
1918
1919 static int
1920 dpif_netlink_handlers_set(struct dpif *dpif_, uint32_t n_handlers)
1921 {
1922     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1923     int error = 0;
1924
1925 #ifdef _WIN32
1926     /* Multiple upcall handlers will be supported once kernel datapath supports
1927      * it. */
1928     if (n_handlers > 1) {
1929         return error;
1930     }
1931 #endif
1932
1933     fat_rwlock_wrlock(&dpif->upcall_lock);
1934     if (dpif->handlers) {
1935         error = dpif_netlink_refresh_channels(dpif, n_handlers);
1936     }
1937     fat_rwlock_unlock(&dpif->upcall_lock);
1938
1939     return error;
1940 }
1941
1942 static int
1943 dpif_netlink_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1944                              uint32_t queue_id, uint32_t *priority)
1945 {
1946     if (queue_id < 0xf000) {
1947         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1948         return 0;
1949     } else {
1950         return EINVAL;
1951     }
1952 }
1953
1954 static int
1955 parse_odp_packet(const struct dpif_netlink *dpif, struct ofpbuf *buf,
1956                  struct dpif_upcall *upcall, int *dp_ifindex)
1957 {
1958     static const struct nl_policy ovs_packet_policy[] = {
1959         /* Always present. */
1960         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1961                                      .min_len = ETH_HEADER_LEN },
1962         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1963
1964         /* OVS_PACKET_CMD_ACTION only. */
1965         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1966         [OVS_PACKET_ATTR_EGRESS_TUN_KEY] = { .type = NL_A_NESTED, .optional = true },
1967         [OVS_PACKET_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1968     };
1969
1970     struct ovs_header *ovs_header;
1971     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1972     struct nlmsghdr *nlmsg;
1973     struct genlmsghdr *genl;
1974     struct ofpbuf b;
1975     int type;
1976
1977     ofpbuf_use_const(&b, buf->data, buf->size);
1978
1979     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1980     genl = ofpbuf_try_pull(&b, sizeof *genl);
1981     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1982     if (!nlmsg || !genl || !ovs_header
1983         || nlmsg->nlmsg_type != ovs_packet_family
1984         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1985                             ARRAY_SIZE(ovs_packet_policy))) {
1986         return EINVAL;
1987     }
1988
1989     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1990             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1991             : -1);
1992     if (type < 0) {
1993         return EINVAL;
1994     }
1995
1996     /* (Re)set ALL fields of '*upcall' on successful return. */
1997     upcall->type = type;
1998     upcall->key = CONST_CAST(struct nlattr *,
1999                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
2000     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
2001     dpif_flow_hash(&dpif->dpif, upcall->key, upcall->key_len, &upcall->ufid);
2002     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
2003     upcall->out_tun_key = a[OVS_PACKET_ATTR_EGRESS_TUN_KEY];
2004     upcall->actions = a[OVS_PACKET_ATTR_ACTIONS];
2005
2006     /* Allow overwriting the netlink attribute header without reallocating. */
2007     dp_packet_use_stub(&upcall->packet,
2008                     CONST_CAST(struct nlattr *,
2009                                nl_attr_get(a[OVS_PACKET_ATTR_PACKET])) - 1,
2010                     nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]) +
2011                     sizeof(struct nlattr));
2012     dp_packet_set_data(&upcall->packet,
2013                     (char *)dp_packet_data(&upcall->packet) + sizeof(struct nlattr));
2014     dp_packet_set_size(&upcall->packet, nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]));
2015
2016     *dp_ifindex = ovs_header->dp_ifindex;
2017
2018     return 0;
2019 }
2020
2021 #ifdef _WIN32
2022 #define PACKET_RECV_BATCH_SIZE 50
2023 static int
2024 dpif_netlink_recv_windows(struct dpif_netlink *dpif, uint32_t handler_id,
2025                           struct dpif_upcall *upcall, struct ofpbuf *buf)
2026     OVS_REQ_RDLOCK(dpif->upcall_lock)
2027 {
2028     struct dpif_handler *handler;
2029     int read_tries = 0;
2030     struct dpif_windows_vport_sock *sock_pool;
2031     uint32_t i;
2032
2033     if (!dpif->handlers) {
2034         return EAGAIN;
2035     }
2036
2037     /* Only one handler is supported currently. */
2038     if (handler_id >= 1) {
2039         return EAGAIN;
2040     }
2041
2042     if (handler_id >= dpif->n_handlers) {
2043         return EAGAIN;
2044     }
2045
2046     handler = &dpif->handlers[handler_id];
2047     sock_pool = handler->vport_sock_pool;
2048
2049     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2050         for (;;) {
2051             int dp_ifindex;
2052             int error;
2053
2054             if (++read_tries > PACKET_RECV_BATCH_SIZE) {
2055                 return EAGAIN;
2056             }
2057
2058             error = nl_sock_recv(sock_pool[i].nl_sock, buf, false);
2059             if (error == ENOBUFS) {
2060                 /* ENOBUFS typically means that we've received so many
2061                  * packets that the buffer overflowed.  Try again
2062                  * immediately because there's almost certainly a packet
2063                  * waiting for us. */
2064                 /* XXX: report_loss(dpif, ch, idx, handler_id); */
2065                 continue;
2066             }
2067
2068             /* XXX: ch->last_poll = time_msec(); */
2069             if (error) {
2070                 if (error == EAGAIN) {
2071                     break;
2072                 }
2073                 return error;
2074             }
2075
2076             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2077             if (!error && dp_ifindex == dpif->dp_ifindex) {
2078                 return 0;
2079             } else if (error) {
2080                 return error;
2081             }
2082         }
2083     }
2084
2085     return EAGAIN;
2086 }
2087 #else
2088 static int
2089 dpif_netlink_recv__(struct dpif_netlink *dpif, uint32_t handler_id,
2090                     struct dpif_upcall *upcall, struct ofpbuf *buf)
2091     OVS_REQ_RDLOCK(dpif->upcall_lock)
2092 {
2093     struct dpif_handler *handler;
2094     int read_tries = 0;
2095
2096     if (!dpif->handlers || handler_id >= dpif->n_handlers) {
2097         return EAGAIN;
2098     }
2099
2100     handler = &dpif->handlers[handler_id];
2101     if (handler->event_offset >= handler->n_events) {
2102         int retval;
2103
2104         handler->event_offset = handler->n_events = 0;
2105
2106         do {
2107             retval = epoll_wait(handler->epoll_fd, handler->epoll_events,
2108                                 dpif->uc_array_size, 0);
2109         } while (retval < 0 && errno == EINTR);
2110
2111         if (retval < 0) {
2112             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2113             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
2114         } else if (retval > 0) {
2115             handler->n_events = retval;
2116         }
2117     }
2118
2119     while (handler->event_offset < handler->n_events) {
2120         int idx = handler->epoll_events[handler->event_offset].data.u32;
2121         struct dpif_channel *ch = &dpif->handlers[handler_id].channels[idx];
2122
2123         handler->event_offset++;
2124
2125         for (;;) {
2126             int dp_ifindex;
2127             int error;
2128
2129             if (++read_tries > 50) {
2130                 return EAGAIN;
2131             }
2132
2133             error = nl_sock_recv(ch->sock, buf, false);
2134             if (error == ENOBUFS) {
2135                 /* ENOBUFS typically means that we've received so many
2136                  * packets that the buffer overflowed.  Try again
2137                  * immediately because there's almost certainly a packet
2138                  * waiting for us. */
2139                 report_loss(dpif, ch, idx, handler_id);
2140                 continue;
2141             }
2142
2143             ch->last_poll = time_msec();
2144             if (error) {
2145                 if (error == EAGAIN) {
2146                     break;
2147                 }
2148                 return error;
2149             }
2150
2151             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2152             if (!error && dp_ifindex == dpif->dp_ifindex) {
2153                 return 0;
2154             } else if (error) {
2155                 return error;
2156             }
2157         }
2158     }
2159
2160     return EAGAIN;
2161 }
2162 #endif
2163
2164 static int
2165 dpif_netlink_recv(struct dpif *dpif_, uint32_t handler_id,
2166                   struct dpif_upcall *upcall, struct ofpbuf *buf)
2167 {
2168     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2169     int error;
2170
2171     fat_rwlock_rdlock(&dpif->upcall_lock);
2172 #ifdef _WIN32
2173     error = dpif_netlink_recv_windows(dpif, handler_id, upcall, buf);
2174 #else
2175     error = dpif_netlink_recv__(dpif, handler_id, upcall, buf);
2176 #endif
2177     fat_rwlock_unlock(&dpif->upcall_lock);
2178
2179     return error;
2180 }
2181
2182 static void
2183 dpif_netlink_recv_wait__(struct dpif_netlink *dpif, uint32_t handler_id)
2184     OVS_REQ_RDLOCK(dpif->upcall_lock)
2185 {
2186 #ifdef _WIN32
2187     uint32_t i;
2188     struct dpif_windows_vport_sock *sock_pool =
2189         dpif->handlers[handler_id].vport_sock_pool;
2190
2191     /* Only one handler is supported currently. */
2192     if (handler_id >= 1) {
2193         return;
2194     }
2195
2196     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2197         nl_sock_wait(sock_pool[i].nl_sock, POLLIN);
2198     }
2199 #else
2200     if (dpif->handlers && handler_id < dpif->n_handlers) {
2201         struct dpif_handler *handler = &dpif->handlers[handler_id];
2202
2203         poll_fd_wait(handler->epoll_fd, POLLIN);
2204     }
2205 #endif
2206 }
2207
2208 static void
2209 dpif_netlink_recv_wait(struct dpif *dpif_, uint32_t handler_id)
2210 {
2211     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2212
2213     fat_rwlock_rdlock(&dpif->upcall_lock);
2214     dpif_netlink_recv_wait__(dpif, handler_id);
2215     fat_rwlock_unlock(&dpif->upcall_lock);
2216 }
2217
2218 static void
2219 dpif_netlink_recv_purge__(struct dpif_netlink *dpif)
2220     OVS_REQ_WRLOCK(dpif->upcall_lock)
2221 {
2222     if (dpif->handlers) {
2223         size_t i, j;
2224
2225         for (i = 0; i < dpif->uc_array_size; i++ ) {
2226             if (!dpif->handlers[0].channels[i].sock) {
2227                 continue;
2228             }
2229
2230             for (j = 0; j < dpif->n_handlers; j++) {
2231                 nl_sock_drain(dpif->handlers[j].channels[i].sock);
2232             }
2233         }
2234     }
2235 }
2236
2237 static void
2238 dpif_netlink_recv_purge(struct dpif *dpif_)
2239 {
2240     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2241
2242     fat_rwlock_wrlock(&dpif->upcall_lock);
2243     dpif_netlink_recv_purge__(dpif);
2244     fat_rwlock_unlock(&dpif->upcall_lock);
2245 }
2246
2247 static char *
2248 dpif_netlink_get_datapath_version(void)
2249 {
2250     char *version_str = NULL;
2251
2252 #ifdef __linux__
2253
2254 #define MAX_VERSION_STR_SIZE 80
2255 #define LINUX_DATAPATH_VERSION_FILE  "/sys/module/openvswitch/version"
2256     FILE *f;
2257
2258     f = fopen(LINUX_DATAPATH_VERSION_FILE, "r");
2259     if (f) {
2260         char *newline;
2261         char version[MAX_VERSION_STR_SIZE];
2262
2263         if (fgets(version, MAX_VERSION_STR_SIZE, f)) {
2264             newline = strchr(version, '\n');
2265             if (newline) {
2266                 *newline = '\0';
2267             }
2268             version_str = xstrdup(version);
2269         }
2270         fclose(f);
2271     }
2272 #endif
2273
2274     return version_str;
2275 }
2276
2277 const struct dpif_class dpif_netlink_class = {
2278     "system",
2279     NULL,                       /* init */
2280     dpif_netlink_enumerate,
2281     NULL,
2282     dpif_netlink_open,
2283     dpif_netlink_close,
2284     dpif_netlink_destroy,
2285     dpif_netlink_run,
2286     NULL,                       /* wait */
2287     dpif_netlink_get_stats,
2288     dpif_netlink_port_add,
2289     dpif_netlink_port_del,
2290     dpif_netlink_port_query_by_number,
2291     dpif_netlink_port_query_by_name,
2292     dpif_netlink_port_get_pid,
2293     dpif_netlink_port_dump_start,
2294     dpif_netlink_port_dump_next,
2295     dpif_netlink_port_dump_done,
2296     dpif_netlink_port_poll,
2297     dpif_netlink_port_poll_wait,
2298     dpif_netlink_flow_flush,
2299     dpif_netlink_flow_dump_create,
2300     dpif_netlink_flow_dump_destroy,
2301     dpif_netlink_flow_dump_thread_create,
2302     dpif_netlink_flow_dump_thread_destroy,
2303     dpif_netlink_flow_dump_next,
2304     dpif_netlink_operate,
2305     dpif_netlink_recv_set,
2306     dpif_netlink_handlers_set,
2307     NULL,                       /* poll_thread_set */
2308     dpif_netlink_queue_to_priority,
2309     dpif_netlink_recv,
2310     dpif_netlink_recv_wait,
2311     dpif_netlink_recv_purge,
2312     NULL,                       /* register_upcall_cb */
2313     NULL,                       /* enable_upcall */
2314     NULL,                       /* disable_upcall */
2315     dpif_netlink_get_datapath_version, /* get_datapath_version */
2316 };
2317
2318 static int
2319 dpif_netlink_init(void)
2320 {
2321     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2322     static int error;
2323
2324     if (ovsthread_once_start(&once)) {
2325         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
2326                                       &ovs_datapath_family);
2327         if (error) {
2328             VLOG_ERR("Generic Netlink family '%s' does not exist. "
2329                      "The Open vSwitch kernel module is probably not loaded.",
2330                      OVS_DATAPATH_FAMILY);
2331         }
2332         if (!error) {
2333             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
2334         }
2335         if (!error) {
2336             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
2337         }
2338         if (!error) {
2339             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
2340                                           &ovs_packet_family);
2341         }
2342         if (!error) {
2343             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
2344                                            &ovs_vport_mcgroup);
2345         }
2346
2347         ovsthread_once_done(&once);
2348     }
2349
2350     return error;
2351 }
2352
2353 bool
2354 dpif_netlink_is_internal_device(const char *name)
2355 {
2356     struct dpif_netlink_vport reply;
2357     struct ofpbuf *buf;
2358     int error;
2359
2360     error = dpif_netlink_vport_get(name, &reply, &buf);
2361     if (!error) {
2362         ofpbuf_delete(buf);
2363     } else if (error != ENODEV && error != ENOENT) {
2364         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
2365                      name, ovs_strerror(error));
2366     }
2367
2368     return reply.type == OVS_VPORT_TYPE_INTERNAL;
2369 }
2370 \f
2371 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2372  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
2373  * positive errno value.
2374  *
2375  * 'vport' will contain pointers into 'buf', so the caller should not free
2376  * 'buf' while 'vport' is still in use. */
2377 static int
2378 dpif_netlink_vport_from_ofpbuf(struct dpif_netlink_vport *vport,
2379                              const struct ofpbuf *buf)
2380 {
2381     static const struct nl_policy ovs_vport_policy[] = {
2382         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
2383         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
2384         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2385         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_UNSPEC },
2386         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
2387                                    .optional = true },
2388         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
2389     };
2390
2391     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
2392     struct ovs_header *ovs_header;
2393     struct nlmsghdr *nlmsg;
2394     struct genlmsghdr *genl;
2395     struct ofpbuf b;
2396
2397     dpif_netlink_vport_init(vport);
2398
2399     ofpbuf_use_const(&b, buf->data, buf->size);
2400     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2401     genl = ofpbuf_try_pull(&b, sizeof *genl);
2402     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2403     if (!nlmsg || !genl || !ovs_header
2404         || nlmsg->nlmsg_type != ovs_vport_family
2405         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
2406                             ARRAY_SIZE(ovs_vport_policy))) {
2407         return EINVAL;
2408     }
2409
2410     vport->cmd = genl->cmd;
2411     vport->dp_ifindex = ovs_header->dp_ifindex;
2412     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
2413     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2414     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
2415     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2416         vport->n_upcall_pids = nl_attr_get_size(a[OVS_VPORT_ATTR_UPCALL_PID])
2417                                / (sizeof *vport->upcall_pids);
2418         vport->upcall_pids = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
2419
2420     }
2421     if (a[OVS_VPORT_ATTR_STATS]) {
2422         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
2423     }
2424     if (a[OVS_VPORT_ATTR_OPTIONS]) {
2425         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
2426         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
2427     }
2428     return 0;
2429 }
2430
2431 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2432  * followed by Netlink attributes corresponding to 'vport'. */
2433 static void
2434 dpif_netlink_vport_to_ofpbuf(const struct dpif_netlink_vport *vport,
2435                              struct ofpbuf *buf)
2436 {
2437     struct ovs_header *ovs_header;
2438
2439     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
2440                           vport->cmd, OVS_VPORT_VERSION);
2441
2442     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2443     ovs_header->dp_ifindex = vport->dp_ifindex;
2444
2445     if (vport->port_no != ODPP_NONE) {
2446         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
2447     }
2448
2449     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
2450         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
2451     }
2452
2453     if (vport->name) {
2454         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
2455     }
2456
2457     if (vport->upcall_pids) {
2458         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_UPCALL_PID,
2459                           vport->upcall_pids,
2460                           vport->n_upcall_pids * sizeof *vport->upcall_pids);
2461     }
2462
2463     if (vport->stats) {
2464         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
2465                           vport->stats, sizeof *vport->stats);
2466     }
2467
2468     if (vport->options) {
2469         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
2470                           vport->options, vport->options_len);
2471     }
2472 }
2473
2474 /* Clears 'vport' to "empty" values. */
2475 void
2476 dpif_netlink_vport_init(struct dpif_netlink_vport *vport)
2477 {
2478     memset(vport, 0, sizeof *vport);
2479     vport->port_no = ODPP_NONE;
2480 }
2481
2482 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2483  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2484  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2485  * result of the command is expected to be an ovs_vport also, which is decoded
2486  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2487  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2488 int
2489 dpif_netlink_vport_transact(const struct dpif_netlink_vport *request,
2490                             struct dpif_netlink_vport *reply,
2491                             struct ofpbuf **bufp)
2492 {
2493     struct ofpbuf *request_buf;
2494     int error;
2495
2496     ovs_assert((reply != NULL) == (bufp != NULL));
2497
2498     error = dpif_netlink_init();
2499     if (error) {
2500         if (reply) {
2501             *bufp = NULL;
2502             dpif_netlink_vport_init(reply);
2503         }
2504         return error;
2505     }
2506
2507     request_buf = ofpbuf_new(1024);
2508     dpif_netlink_vport_to_ofpbuf(request, request_buf);
2509     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2510     ofpbuf_delete(request_buf);
2511
2512     if (reply) {
2513         if (!error) {
2514             error = dpif_netlink_vport_from_ofpbuf(reply, *bufp);
2515         }
2516         if (error) {
2517             dpif_netlink_vport_init(reply);
2518             ofpbuf_delete(*bufp);
2519             *bufp = NULL;
2520         }
2521     }
2522     return error;
2523 }
2524
2525 /* Obtains information about the kernel vport named 'name' and stores it into
2526  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
2527  * longer needed ('reply' will contain pointers into '*bufp').  */
2528 int
2529 dpif_netlink_vport_get(const char *name, struct dpif_netlink_vport *reply,
2530                        struct ofpbuf **bufp)
2531 {
2532     struct dpif_netlink_vport request;
2533
2534     dpif_netlink_vport_init(&request);
2535     request.cmd = OVS_VPORT_CMD_GET;
2536     request.name = name;
2537
2538     return dpif_netlink_vport_transact(&request, reply, bufp);
2539 }
2540
2541 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2542  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
2543  * positive errno value.
2544  *
2545  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
2546  * while 'dp' is still in use. */
2547 static int
2548 dpif_netlink_dp_from_ofpbuf(struct dpif_netlink_dp *dp, const struct ofpbuf *buf)
2549 {
2550     static const struct nl_policy ovs_datapath_policy[] = {
2551         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2552         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
2553                                 .optional = true },
2554         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
2555                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
2556                         .optional = true },
2557     };
2558
2559     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
2560     struct ovs_header *ovs_header;
2561     struct nlmsghdr *nlmsg;
2562     struct genlmsghdr *genl;
2563     struct ofpbuf b;
2564
2565     dpif_netlink_dp_init(dp);
2566
2567     ofpbuf_use_const(&b, buf->data, buf->size);
2568     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2569     genl = ofpbuf_try_pull(&b, sizeof *genl);
2570     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2571     if (!nlmsg || !genl || !ovs_header
2572         || nlmsg->nlmsg_type != ovs_datapath_family
2573         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
2574                             ARRAY_SIZE(ovs_datapath_policy))) {
2575         return EINVAL;
2576     }
2577
2578     dp->cmd = genl->cmd;
2579     dp->dp_ifindex = ovs_header->dp_ifindex;
2580     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
2581     if (a[OVS_DP_ATTR_STATS]) {
2582         dp->stats = nl_attr_get(a[OVS_DP_ATTR_STATS]);
2583     }
2584
2585     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
2586         dp->megaflow_stats = nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]);
2587     }
2588
2589     return 0;
2590 }
2591
2592 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
2593 static void
2594 dpif_netlink_dp_to_ofpbuf(const struct dpif_netlink_dp *dp, struct ofpbuf *buf)
2595 {
2596     struct ovs_header *ovs_header;
2597
2598     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
2599                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
2600                           OVS_DATAPATH_VERSION);
2601
2602     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2603     ovs_header->dp_ifindex = dp->dp_ifindex;
2604
2605     if (dp->name) {
2606         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
2607     }
2608
2609     if (dp->upcall_pid) {
2610         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
2611     }
2612
2613     if (dp->user_features) {
2614         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
2615     }
2616
2617     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
2618 }
2619
2620 /* Clears 'dp' to "empty" values. */
2621 static void
2622 dpif_netlink_dp_init(struct dpif_netlink_dp *dp)
2623 {
2624     memset(dp, 0, sizeof *dp);
2625 }
2626
2627 static void
2628 dpif_netlink_dp_dump_start(struct nl_dump *dump)
2629 {
2630     struct dpif_netlink_dp request;
2631     struct ofpbuf *buf;
2632
2633     dpif_netlink_dp_init(&request);
2634     request.cmd = OVS_DP_CMD_GET;
2635
2636     buf = ofpbuf_new(1024);
2637     dpif_netlink_dp_to_ofpbuf(&request, buf);
2638     nl_dump_start(dump, NETLINK_GENERIC, buf);
2639     ofpbuf_delete(buf);
2640 }
2641
2642 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2643  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2644  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2645  * result of the command is expected to be of the same form, which is decoded
2646  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2647  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2648 static int
2649 dpif_netlink_dp_transact(const struct dpif_netlink_dp *request,
2650                          struct dpif_netlink_dp *reply, struct ofpbuf **bufp)
2651 {
2652     struct ofpbuf *request_buf;
2653     int error;
2654
2655     ovs_assert((reply != NULL) == (bufp != NULL));
2656
2657     request_buf = ofpbuf_new(1024);
2658     dpif_netlink_dp_to_ofpbuf(request, request_buf);
2659     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2660     ofpbuf_delete(request_buf);
2661
2662     if (reply) {
2663         dpif_netlink_dp_init(reply);
2664         if (!error) {
2665             error = dpif_netlink_dp_from_ofpbuf(reply, *bufp);
2666         }
2667         if (error) {
2668             ofpbuf_delete(*bufp);
2669             *bufp = NULL;
2670         }
2671     }
2672     return error;
2673 }
2674
2675 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
2676  * The caller must free '*bufp' when the reply is no longer needed ('reply'
2677  * will contain pointers into '*bufp').  */
2678 static int
2679 dpif_netlink_dp_get(const struct dpif *dpif_, struct dpif_netlink_dp *reply,
2680                     struct ofpbuf **bufp)
2681 {
2682     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2683     struct dpif_netlink_dp request;
2684
2685     dpif_netlink_dp_init(&request);
2686     request.cmd = OVS_DP_CMD_GET;
2687     request.dp_ifindex = dpif->dp_ifindex;
2688
2689     return dpif_netlink_dp_transact(&request, reply, bufp);
2690 }
2691
2692 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2693  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2694  * positive errno value.
2695  *
2696  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2697  * while 'flow' is still in use. */
2698 static int
2699 dpif_netlink_flow_from_ofpbuf(struct dpif_netlink_flow *flow,
2700                               const struct ofpbuf *buf)
2701 {
2702     static const struct nl_policy ovs_flow_policy[__OVS_FLOW_ATTR_MAX] = {
2703         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED, .optional = true },
2704         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2705         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2706         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2707                                   .optional = true },
2708         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2709         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2710         [OVS_FLOW_ATTR_UFID] = { .type = NL_A_UNSPEC, .optional = true,
2711                                  .min_len = sizeof(ovs_u128) },
2712         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2713         /* The kernel never uses OVS_FLOW_ATTR_PROBE. */
2714         /* The kernel never uses OVS_FLOW_ATTR_UFID_FLAGS. */
2715     };
2716
2717     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2718     struct ovs_header *ovs_header;
2719     struct nlmsghdr *nlmsg;
2720     struct genlmsghdr *genl;
2721     struct ofpbuf b;
2722
2723     dpif_netlink_flow_init(flow);
2724
2725     ofpbuf_use_const(&b, buf->data, buf->size);
2726     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2727     genl = ofpbuf_try_pull(&b, sizeof *genl);
2728     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2729     if (!nlmsg || !genl || !ovs_header
2730         || nlmsg->nlmsg_type != ovs_flow_family
2731         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2732                             ARRAY_SIZE(ovs_flow_policy))) {
2733         return EINVAL;
2734     }
2735     if (!a[OVS_FLOW_ATTR_KEY] && !a[OVS_FLOW_ATTR_UFID]) {
2736         return EINVAL;
2737     }
2738
2739     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2740     flow->dp_ifindex = ovs_header->dp_ifindex;
2741     if (a[OVS_FLOW_ATTR_KEY]) {
2742         flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2743         flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2744     }
2745
2746     if (a[OVS_FLOW_ATTR_UFID]) {
2747         const ovs_u128 *ufid;
2748
2749         ufid = nl_attr_get_unspec(a[OVS_FLOW_ATTR_UFID],
2750                                   nl_attr_get_size(a[OVS_FLOW_ATTR_UFID]));
2751         flow->ufid = *ufid;
2752         flow->ufid_present = true;
2753     }
2754     if (a[OVS_FLOW_ATTR_MASK]) {
2755         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2756         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2757     }
2758     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2759         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2760         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2761     }
2762     if (a[OVS_FLOW_ATTR_STATS]) {
2763         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2764     }
2765     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2766         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2767     }
2768     if (a[OVS_FLOW_ATTR_USED]) {
2769         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2770     }
2771     return 0;
2772 }
2773
2774 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2775  * followed by Netlink attributes corresponding to 'flow'. */
2776 static void
2777 dpif_netlink_flow_to_ofpbuf(const struct dpif_netlink_flow *flow,
2778                             struct ofpbuf *buf)
2779 {
2780     struct ovs_header *ovs_header;
2781
2782     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2783                           NLM_F_REQUEST | flow->nlmsg_flags,
2784                           flow->cmd, OVS_FLOW_VERSION);
2785
2786     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2787     ovs_header->dp_ifindex = flow->dp_ifindex;
2788
2789     if (flow->ufid_present) {
2790         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_UFID, &flow->ufid,
2791                           sizeof flow->ufid);
2792     }
2793     if (flow->ufid_terse) {
2794         nl_msg_put_u32(buf, OVS_FLOW_ATTR_UFID_FLAGS,
2795                        OVS_UFID_F_OMIT_KEY | OVS_UFID_F_OMIT_MASK
2796                        | OVS_UFID_F_OMIT_ACTIONS);
2797     }
2798     if (!flow->ufid_terse || !flow->ufid_present) {
2799         if (flow->key_len) {
2800             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY,
2801                               flow->key, flow->key_len);
2802         }
2803
2804         if (flow->mask_len) {
2805             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK,
2806                               flow->mask, flow->mask_len);
2807         }
2808         if (flow->actions || flow->actions_len) {
2809             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2810                               flow->actions, flow->actions_len);
2811         }
2812     }
2813
2814     /* We never need to send these to the kernel. */
2815     ovs_assert(!flow->stats);
2816     ovs_assert(!flow->tcp_flags);
2817     ovs_assert(!flow->used);
2818
2819     if (flow->clear) {
2820         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2821     }
2822     if (flow->probe) {
2823         nl_msg_put_flag(buf, OVS_FLOW_ATTR_PROBE);
2824     }
2825 }
2826
2827 /* Clears 'flow' to "empty" values. */
2828 static void
2829 dpif_netlink_flow_init(struct dpif_netlink_flow *flow)
2830 {
2831     memset(flow, 0, sizeof *flow);
2832 }
2833
2834 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2835  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2836  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2837  * result of the command is expected to be a flow also, which is decoded and
2838  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2839  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2840 static int
2841 dpif_netlink_flow_transact(struct dpif_netlink_flow *request,
2842                            struct dpif_netlink_flow *reply,
2843                            struct ofpbuf **bufp)
2844 {
2845     struct ofpbuf *request_buf;
2846     int error;
2847
2848     ovs_assert((reply != NULL) == (bufp != NULL));
2849
2850     if (reply) {
2851         request->nlmsg_flags |= NLM_F_ECHO;
2852     }
2853
2854     request_buf = ofpbuf_new(1024);
2855     dpif_netlink_flow_to_ofpbuf(request, request_buf);
2856     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2857     ofpbuf_delete(request_buf);
2858
2859     if (reply) {
2860         if (!error) {
2861             error = dpif_netlink_flow_from_ofpbuf(reply, *bufp);
2862         }
2863         if (error) {
2864             dpif_netlink_flow_init(reply);
2865             ofpbuf_delete(*bufp);
2866             *bufp = NULL;
2867         }
2868     }
2869     return error;
2870 }
2871
2872 static void
2873 dpif_netlink_flow_get_stats(const struct dpif_netlink_flow *flow,
2874                             struct dpif_flow_stats *stats)
2875 {
2876     if (flow->stats) {
2877         stats->n_packets = get_32aligned_u64(&flow->stats->n_packets);
2878         stats->n_bytes = get_32aligned_u64(&flow->stats->n_bytes);
2879     } else {
2880         stats->n_packets = 0;
2881         stats->n_bytes = 0;
2882     }
2883     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2884     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2885 }
2886 \f
2887 /* Logs information about a packet that was recently lost in 'ch' (in
2888  * 'dpif_'). */
2889 static void
2890 report_loss(struct dpif_netlink *dpif, struct dpif_channel *ch, uint32_t ch_idx,
2891             uint32_t handler_id)
2892 {
2893     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2894     struct ds s;
2895
2896     if (VLOG_DROP_WARN(&rl)) {
2897         return;
2898     }
2899
2900     ds_init(&s);
2901     if (ch->last_poll != LLONG_MIN) {
2902         ds_put_format(&s, " (last polled %lld ms ago)",
2903                       time_msec() - ch->last_poll);
2904     }
2905
2906     VLOG_WARN("%s: lost packet on port channel %u of handler %u",
2907               dpif_name(&dpif->dpif), ch_idx, handler_id);
2908     ds_destroy(&s);
2909 }