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