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