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