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