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