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