dpif: Use separate OVS_PACKET_ATTR_PROBE for packet messges
[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.upcall_pids = &upcall_pids;
649         dpif_netlink_vport_transact(&vport_request, NULL, NULL);
650
651         vport_del_channels(dpif, u32_to_odp(i));
652     }
653
654     for (i = 0; i < dpif->n_handlers; i++) {
655         struct dpif_handler *handler = &dpif->handlers[i];
656
657         dpif_netlink_handler_uninit(handler);
658         free(handler->epoll_events);
659         free(handler->channels);
660     }
661
662     free(dpif->handlers);
663     dpif->handlers = NULL;
664     dpif->n_handlers = 0;
665     dpif->uc_array_size = 0;
666 }
667
668 static void
669 dpif_netlink_close(struct dpif *dpif_)
670 {
671     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
672
673     nl_sock_destroy(dpif->port_notifier);
674
675     fat_rwlock_wrlock(&dpif->upcall_lock);
676     destroy_all_channels(dpif);
677     fat_rwlock_unlock(&dpif->upcall_lock);
678
679     fat_rwlock_destroy(&dpif->upcall_lock);
680     free(dpif);
681 }
682
683 static int
684 dpif_netlink_destroy(struct dpif *dpif_)
685 {
686     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
687     struct dpif_netlink_dp dp;
688
689     dpif_netlink_dp_init(&dp);
690     dp.cmd = OVS_DP_CMD_DEL;
691     dp.dp_ifindex = dpif->dp_ifindex;
692     return dpif_netlink_dp_transact(&dp, NULL, NULL);
693 }
694
695 static bool
696 dpif_netlink_run(struct dpif *dpif_)
697 {
698     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
699
700     if (dpif->refresh_channels) {
701         dpif->refresh_channels = false;
702         fat_rwlock_wrlock(&dpif->upcall_lock);
703         dpif_netlink_refresh_channels(dpif, dpif->n_handlers);
704         fat_rwlock_unlock(&dpif->upcall_lock);
705     }
706     return false;
707 }
708
709 static int
710 dpif_netlink_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
711 {
712     struct dpif_netlink_dp dp;
713     struct ofpbuf *buf;
714     int error;
715
716     error = dpif_netlink_dp_get(dpif_, &dp, &buf);
717     if (!error) {
718         memset(stats, 0, sizeof *stats);
719
720         if (dp.stats) {
721             stats->n_hit    = get_32aligned_u64(&dp.stats->n_hit);
722             stats->n_missed = get_32aligned_u64(&dp.stats->n_missed);
723             stats->n_lost   = get_32aligned_u64(&dp.stats->n_lost);
724             stats->n_flows  = get_32aligned_u64(&dp.stats->n_flows);
725         }
726
727         if (dp.megaflow_stats) {
728             stats->n_masks = dp.megaflow_stats->n_masks;
729             stats->n_mask_hit = get_32aligned_u64(
730                 &dp.megaflow_stats->n_mask_hit);
731         } else {
732             stats->n_masks = UINT32_MAX;
733             stats->n_mask_hit = UINT64_MAX;
734         }
735         ofpbuf_delete(buf);
736     }
737     return error;
738 }
739
740 static const char *
741 get_vport_type(const struct dpif_netlink_vport *vport)
742 {
743     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
744
745     switch (vport->type) {
746     case OVS_VPORT_TYPE_NETDEV: {
747         const char *type = netdev_get_type_from_name(vport->name);
748
749         return type ? type : "system";
750     }
751
752     case OVS_VPORT_TYPE_INTERNAL:
753         return "internal";
754
755     case OVS_VPORT_TYPE_GENEVE:
756         return "geneve";
757
758     case OVS_VPORT_TYPE_GRE:
759         return "gre";
760
761     case OVS_VPORT_TYPE_GRE64:
762         return "gre64";
763
764     case OVS_VPORT_TYPE_VXLAN:
765         return "vxlan";
766
767     case OVS_VPORT_TYPE_LISP:
768         return "lisp";
769
770     case OVS_VPORT_TYPE_UNSPEC:
771     case __OVS_VPORT_TYPE_MAX:
772         break;
773     }
774
775     VLOG_WARN_RL(&rl, "dp%d: port `%s' has unsupported type %u",
776                  vport->dp_ifindex, vport->name, (unsigned int) vport->type);
777     return "unknown";
778 }
779
780 static enum ovs_vport_type
781 netdev_to_ovs_vport_type(const struct netdev *netdev)
782 {
783     const char *type = netdev_get_type(netdev);
784
785     if (!strcmp(type, "tap") || !strcmp(type, "system")) {
786         return OVS_VPORT_TYPE_NETDEV;
787     } else if (!strcmp(type, "internal")) {
788         return OVS_VPORT_TYPE_INTERNAL;
789     } else if (!strcmp(type, "geneve")) {
790         return OVS_VPORT_TYPE_GENEVE;
791     } else if (strstr(type, "gre64")) {
792         return OVS_VPORT_TYPE_GRE64;
793     } else if (strstr(type, "gre")) {
794         return OVS_VPORT_TYPE_GRE;
795     } else if (!strcmp(type, "vxlan")) {
796         return OVS_VPORT_TYPE_VXLAN;
797     } else if (!strcmp(type, "lisp")) {
798         return OVS_VPORT_TYPE_LISP;
799     } else {
800         return OVS_VPORT_TYPE_UNSPEC;
801     }
802 }
803
804 static int
805 dpif_netlink_port_add__(struct dpif_netlink *dpif, struct netdev *netdev,
806                         odp_port_t *port_nop)
807     OVS_REQ_WRLOCK(dpif->upcall_lock)
808 {
809     const struct netdev_tunnel_config *tnl_cfg;
810     char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
811     const char *name = netdev_vport_get_dpif_port(netdev,
812                                                   namebuf, sizeof namebuf);
813     const char *type = netdev_get_type(netdev);
814     struct dpif_netlink_vport request, reply;
815     struct ofpbuf *buf;
816     uint64_t options_stub[64 / 8];
817     struct ofpbuf options;
818     struct nl_sock **socksp = NULL;
819     uint32_t *upcall_pids;
820     int error = 0;
821
822     if (dpif->handlers) {
823         socksp = vport_create_socksp(dpif, &error);
824         if (!socksp) {
825             return error;
826         }
827     }
828
829     dpif_netlink_vport_init(&request);
830     request.cmd = OVS_VPORT_CMD_NEW;
831     request.dp_ifindex = dpif->dp_ifindex;
832     request.type = netdev_to_ovs_vport_type(netdev);
833     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
834         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
835                      "unsupported type `%s'",
836                      dpif_name(&dpif->dpif), name, type);
837         vport_del_socksp(dpif, socksp);
838         return EINVAL;
839     }
840     request.name = name;
841
842     if (request.type == OVS_VPORT_TYPE_NETDEV) {
843 #ifdef _WIN32
844         /* XXX : Map appropiate Windows handle */
845 #else
846         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
847 #endif
848     }
849
850     tnl_cfg = netdev_get_tunnel_config(netdev);
851     if (tnl_cfg && tnl_cfg->dst_port != 0) {
852         ofpbuf_use_stack(&options, options_stub, sizeof options_stub);
853         nl_msg_put_u16(&options, OVS_TUNNEL_ATTR_DST_PORT,
854                        ntohs(tnl_cfg->dst_port));
855         request.options = ofpbuf_data(&options);
856         request.options_len = ofpbuf_size(&options);
857     }
858
859     request.port_no = *port_nop;
860     upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
861     request.n_upcall_pids = socksp ? dpif->n_handlers : 1;
862     request.upcall_pids = upcall_pids;
863
864     error = dpif_netlink_vport_transact(&request, &reply, &buf);
865     if (!error) {
866         *port_nop = reply.port_no;
867     } else {
868         if (error == EBUSY && *port_nop != ODPP_NONE) {
869             VLOG_INFO("%s: requested port %"PRIu32" is in use",
870                       dpif_name(&dpif->dpif), *port_nop);
871         }
872
873         vport_del_socksp(dpif, socksp);
874         goto exit;
875     }
876
877     if (socksp) {
878         error = vport_add_channels(dpif, *port_nop, socksp);
879         if (error) {
880             VLOG_INFO("%s: could not add channel for port %s",
881                       dpif_name(&dpif->dpif), name);
882
883             /* Delete the port. */
884             dpif_netlink_vport_init(&request);
885             request.cmd = OVS_VPORT_CMD_DEL;
886             request.dp_ifindex = dpif->dp_ifindex;
887             request.port_no = *port_nop;
888             dpif_netlink_vport_transact(&request, NULL, NULL);
889             vport_del_socksp(dpif, socksp);
890             goto exit;
891         }
892     }
893     free(socksp);
894
895 exit:
896     ofpbuf_delete(buf);
897     free(upcall_pids);
898
899     return error;
900 }
901
902 static int
903 dpif_netlink_port_add(struct dpif *dpif_, struct netdev *netdev,
904                       odp_port_t *port_nop)
905 {
906     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
907     int error;
908
909     fat_rwlock_wrlock(&dpif->upcall_lock);
910     error = dpif_netlink_port_add__(dpif, netdev, port_nop);
911     fat_rwlock_unlock(&dpif->upcall_lock);
912
913     return error;
914 }
915
916 static int
917 dpif_netlink_port_del__(struct dpif_netlink *dpif, odp_port_t port_no)
918     OVS_REQ_WRLOCK(dpif->upcall_lock)
919 {
920     struct dpif_netlink_vport vport;
921     int error;
922
923     dpif_netlink_vport_init(&vport);
924     vport.cmd = OVS_VPORT_CMD_DEL;
925     vport.dp_ifindex = dpif->dp_ifindex;
926     vport.port_no = port_no;
927     error = dpif_netlink_vport_transact(&vport, NULL, NULL);
928
929     vport_del_channels(dpif, port_no);
930
931     return error;
932 }
933
934 static int
935 dpif_netlink_port_del(struct dpif *dpif_, odp_port_t port_no)
936 {
937     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
938     int error;
939
940     fat_rwlock_wrlock(&dpif->upcall_lock);
941     error = dpif_netlink_port_del__(dpif, port_no);
942     fat_rwlock_unlock(&dpif->upcall_lock);
943
944     return error;
945 }
946
947 static int
948 dpif_netlink_port_query__(const struct dpif_netlink *dpif, odp_port_t port_no,
949                           const char *port_name, struct dpif_port *dpif_port)
950 {
951     struct dpif_netlink_vport request;
952     struct dpif_netlink_vport reply;
953     struct ofpbuf *buf;
954     int error;
955
956     dpif_netlink_vport_init(&request);
957     request.cmd = OVS_VPORT_CMD_GET;
958     request.dp_ifindex = dpif->dp_ifindex;
959     request.port_no = port_no;
960     request.name = port_name;
961
962     error = dpif_netlink_vport_transact(&request, &reply, &buf);
963     if (!error) {
964         if (reply.dp_ifindex != request.dp_ifindex) {
965             /* A query by name reported that 'port_name' is in some datapath
966              * other than 'dpif', but the caller wants to know about 'dpif'. */
967             error = ENODEV;
968         } else if (dpif_port) {
969             dpif_port->name = xstrdup(reply.name);
970             dpif_port->type = xstrdup(get_vport_type(&reply));
971             dpif_port->port_no = reply.port_no;
972         }
973         ofpbuf_delete(buf);
974     }
975     return error;
976 }
977
978 static int
979 dpif_netlink_port_query_by_number(const struct dpif *dpif_, odp_port_t port_no,
980                                   struct dpif_port *dpif_port)
981 {
982     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
983
984     return dpif_netlink_port_query__(dpif, port_no, NULL, dpif_port);
985 }
986
987 static int
988 dpif_netlink_port_query_by_name(const struct dpif *dpif_, const char *devname,
989                               struct dpif_port *dpif_port)
990 {
991     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
992
993     return dpif_netlink_port_query__(dpif, 0, devname, dpif_port);
994 }
995
996 static uint32_t
997 dpif_netlink_port_get_pid__(const struct dpif_netlink *dpif,
998                             odp_port_t port_no, uint32_t hash)
999     OVS_REQ_RDLOCK(dpif->upcall_lock)
1000 {
1001     uint32_t port_idx = odp_to_u32(port_no);
1002     uint32_t pid = 0;
1003
1004     if (dpif->handlers && dpif->uc_array_size > 0) {
1005         /* The ODPP_NONE "reserved" port number uses the "ovs-system"'s
1006          * channel, since it is not heavily loaded. */
1007         uint32_t idx = port_idx >= dpif->uc_array_size ? 0 : port_idx;
1008         struct dpif_handler *h = &dpif->handlers[hash % dpif->n_handlers];
1009
1010         /* Needs to check in case the socket pointer is changed in between
1011          * the holding of upcall_lock.  A known case happens when the main
1012          * thread deletes the vport while the handler thread is handling
1013          * the upcall from that port. */
1014         if (h->channels[idx].sock) {
1015             pid = nl_sock_pid(h->channels[idx].sock);
1016         }
1017     }
1018
1019     return pid;
1020 }
1021
1022 static uint32_t
1023 dpif_netlink_port_get_pid(const struct dpif *dpif_, odp_port_t port_no,
1024                           uint32_t hash)
1025 {
1026     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1027     uint32_t ret;
1028
1029     fat_rwlock_rdlock(&dpif->upcall_lock);
1030     ret = dpif_netlink_port_get_pid__(dpif, port_no, hash);
1031     fat_rwlock_unlock(&dpif->upcall_lock);
1032
1033     return ret;
1034 }
1035
1036 static int
1037 dpif_netlink_flow_flush(struct dpif *dpif_)
1038 {
1039     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1040     struct dpif_netlink_flow flow;
1041
1042     dpif_netlink_flow_init(&flow);
1043     flow.cmd = OVS_FLOW_CMD_DEL;
1044     flow.dp_ifindex = dpif->dp_ifindex;
1045     return dpif_netlink_flow_transact(&flow, NULL, NULL);
1046 }
1047
1048 struct dpif_netlink_port_state {
1049     struct nl_dump dump;
1050     struct ofpbuf buf;
1051 };
1052
1053 static void
1054 dpif_netlink_port_dump_start__(const struct dpif_netlink *dpif,
1055                                struct nl_dump *dump)
1056 {
1057     struct dpif_netlink_vport request;
1058     struct ofpbuf *buf;
1059
1060     dpif_netlink_vport_init(&request);
1061     request.cmd = OVS_VPORT_CMD_GET;
1062     request.dp_ifindex = dpif->dp_ifindex;
1063
1064     buf = ofpbuf_new(1024);
1065     dpif_netlink_vport_to_ofpbuf(&request, buf);
1066     nl_dump_start(dump, NETLINK_GENERIC, buf);
1067     ofpbuf_delete(buf);
1068 }
1069
1070 static int
1071 dpif_netlink_port_dump_start(const struct dpif *dpif_, void **statep)
1072 {
1073     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1074     struct dpif_netlink_port_state *state;
1075
1076     *statep = state = xmalloc(sizeof *state);
1077     dpif_netlink_port_dump_start__(dpif, &state->dump);
1078
1079     ofpbuf_init(&state->buf, NL_DUMP_BUFSIZE);
1080     return 0;
1081 }
1082
1083 static int
1084 dpif_netlink_port_dump_next__(const struct dpif_netlink *dpif,
1085                               struct nl_dump *dump,
1086                               struct dpif_netlink_vport *vport,
1087                               struct ofpbuf *buffer)
1088 {
1089     struct ofpbuf buf;
1090     int error;
1091
1092     if (!nl_dump_next(dump, &buf, buffer)) {
1093         return EOF;
1094     }
1095
1096     error = dpif_netlink_vport_from_ofpbuf(vport, &buf);
1097     if (error) {
1098         VLOG_WARN_RL(&error_rl, "%s: failed to parse vport record (%s)",
1099                      dpif_name(&dpif->dpif), ovs_strerror(error));
1100     }
1101     return error;
1102 }
1103
1104 static int
1105 dpif_netlink_port_dump_next(const struct dpif *dpif_, void *state_,
1106                             struct dpif_port *dpif_port)
1107 {
1108     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1109     struct dpif_netlink_port_state *state = state_;
1110     struct dpif_netlink_vport vport;
1111     int error;
1112
1113     error = dpif_netlink_port_dump_next__(dpif, &state->dump, &vport,
1114                                           &state->buf);
1115     if (error) {
1116         return error;
1117     }
1118     dpif_port->name = CONST_CAST(char *, vport.name);
1119     dpif_port->type = CONST_CAST(char *, get_vport_type(&vport));
1120     dpif_port->port_no = vport.port_no;
1121     return 0;
1122 }
1123
1124 static int
1125 dpif_netlink_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
1126 {
1127     struct dpif_netlink_port_state *state = state_;
1128     int error = nl_dump_done(&state->dump);
1129
1130     ofpbuf_uninit(&state->buf);
1131     free(state);
1132     return error;
1133 }
1134
1135 static int
1136 dpif_netlink_port_poll(const struct dpif *dpif_, char **devnamep)
1137 {
1138     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1139
1140     /* Lazily create the Netlink socket to listen for notifications. */
1141     if (!dpif->port_notifier) {
1142         struct nl_sock *sock;
1143         int error;
1144
1145         error = nl_sock_create(NETLINK_GENERIC, &sock);
1146         if (error) {
1147             return error;
1148         }
1149
1150         error = nl_sock_join_mcgroup(sock, ovs_vport_mcgroup);
1151         if (error) {
1152             nl_sock_destroy(sock);
1153             return error;
1154         }
1155         dpif->port_notifier = sock;
1156
1157         /* We have no idea of the current state so report that everything
1158          * changed. */
1159         return ENOBUFS;
1160     }
1161
1162     for (;;) {
1163         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1164         uint64_t buf_stub[4096 / 8];
1165         struct ofpbuf buf;
1166         int error;
1167
1168         ofpbuf_use_stub(&buf, buf_stub, sizeof buf_stub);
1169         error = nl_sock_recv(dpif->port_notifier, &buf, false);
1170         if (!error) {
1171             struct dpif_netlink_vport vport;
1172
1173             error = dpif_netlink_vport_from_ofpbuf(&vport, &buf);
1174             if (!error) {
1175                 if (vport.dp_ifindex == dpif->dp_ifindex
1176                     && (vport.cmd == OVS_VPORT_CMD_NEW
1177                         || vport.cmd == OVS_VPORT_CMD_DEL
1178                         || vport.cmd == OVS_VPORT_CMD_SET)) {
1179                     VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1180                              dpif->dpif.full_name, vport.name, vport.cmd);
1181                     if (vport.cmd == OVS_VPORT_CMD_DEL && dpif->handlers) {
1182                         dpif->refresh_channels = true;
1183                     }
1184                     *devnamep = xstrdup(vport.name);
1185                     ofpbuf_uninit(&buf);
1186                     return 0;
1187                 }
1188             }
1189         } else if (error != EAGAIN) {
1190             VLOG_WARN_RL(&rl, "error reading or parsing netlink (%s)",
1191                          ovs_strerror(error));
1192             nl_sock_drain(dpif->port_notifier);
1193             error = ENOBUFS;
1194         }
1195
1196         ofpbuf_uninit(&buf);
1197         if (error) {
1198             return error;
1199         }
1200     }
1201 }
1202
1203 static void
1204 dpif_netlink_port_poll_wait(const struct dpif *dpif_)
1205 {
1206     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1207
1208     if (dpif->port_notifier) {
1209         nl_sock_wait(dpif->port_notifier, POLLIN);
1210     } else {
1211         poll_immediate_wake();
1212     }
1213 }
1214
1215 static void
1216 dpif_netlink_flow_init_ufid(struct dpif_netlink_flow *request,
1217                             const ovs_u128 *ufid, bool terse)
1218 {
1219     if (ufid) {
1220         request->ufid = *ufid;
1221         request->ufid_present = true;
1222     } else {
1223         request->ufid_present = false;
1224     }
1225     request->ufid_terse = terse;
1226 }
1227
1228 static void
1229 dpif_netlink_init_flow_get__(const struct dpif_netlink *dpif,
1230                              const struct nlattr *key, size_t key_len,
1231                              const ovs_u128 *ufid, bool terse,
1232                              struct dpif_netlink_flow *request)
1233 {
1234     dpif_netlink_flow_init(request);
1235     request->cmd = OVS_FLOW_CMD_GET;
1236     request->dp_ifindex = dpif->dp_ifindex;
1237     request->key = key;
1238     request->key_len = key_len;
1239     dpif_netlink_flow_init_ufid(request, ufid, terse);
1240 }
1241
1242 static void
1243 dpif_netlink_init_flow_get(const struct dpif_netlink *dpif,
1244                            const struct dpif_flow_get *get,
1245                            struct dpif_netlink_flow *request)
1246 {
1247     dpif_netlink_init_flow_get__(dpif, get->key, get->key_len, get->ufid,
1248                                  false, request);
1249 }
1250
1251 static int
1252 dpif_netlink_flow_get__(const struct dpif_netlink *dpif,
1253                         const struct nlattr *key, size_t key_len,
1254                         const ovs_u128 *ufid, bool terse,
1255                         struct dpif_netlink_flow *reply, struct ofpbuf **bufp)
1256 {
1257     struct dpif_netlink_flow request;
1258
1259     dpif_netlink_init_flow_get__(dpif, key, key_len, ufid, terse, &request);
1260     return dpif_netlink_flow_transact(&request, reply, bufp);
1261 }
1262
1263 static int
1264 dpif_netlink_flow_get(const struct dpif_netlink *dpif,
1265                       const struct dpif_netlink_flow *flow,
1266                       struct dpif_netlink_flow *reply, struct ofpbuf **bufp)
1267 {
1268     return dpif_netlink_flow_get__(dpif, flow->key, flow->key_len,
1269                                    flow->ufid_present ? &flow->ufid : NULL,
1270                                    false, reply, bufp);
1271 }
1272
1273 static void
1274 dpif_netlink_init_flow_put(struct dpif_netlink *dpif,
1275                            const struct dpif_flow_put *put,
1276                            struct dpif_netlink_flow *request)
1277 {
1278     static const struct nlattr dummy_action;
1279
1280     dpif_netlink_flow_init(request);
1281     request->cmd = (put->flags & DPIF_FP_CREATE
1282                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
1283     request->dp_ifindex = dpif->dp_ifindex;
1284     request->key = put->key;
1285     request->key_len = put->key_len;
1286     request->mask = put->mask;
1287     request->mask_len = put->mask_len;
1288     dpif_netlink_flow_init_ufid(request, put->ufid, false);
1289
1290     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
1291     request->actions = (put->actions
1292                         ? put->actions
1293                         : CONST_CAST(struct nlattr *, &dummy_action));
1294     request->actions_len = put->actions_len;
1295     if (put->flags & DPIF_FP_ZERO_STATS) {
1296         request->clear = true;
1297     }
1298     if (put->flags & DPIF_FP_PROBE) {
1299         request->probe = true;
1300     }
1301     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
1302 }
1303
1304 static void
1305 dpif_netlink_init_flow_del__(struct dpif_netlink *dpif,
1306                              const struct nlattr *key, size_t key_len,
1307                              const ovs_u128 *ufid, bool terse,
1308                              struct dpif_netlink_flow *request)
1309 {
1310     dpif_netlink_flow_init(request);
1311     request->cmd = OVS_FLOW_CMD_DEL;
1312     request->dp_ifindex = dpif->dp_ifindex;
1313     request->key = key;
1314     request->key_len = key_len;
1315     dpif_netlink_flow_init_ufid(request, ufid, terse);
1316 }
1317
1318 static void
1319 dpif_netlink_init_flow_del(struct dpif_netlink *dpif,
1320                            const struct dpif_flow_del *del,
1321                            struct dpif_netlink_flow *request)
1322 {
1323     return dpif_netlink_init_flow_del__(dpif, del->key, del->key_len,
1324                                         del->ufid, del->terse, request);
1325 }
1326
1327 struct dpif_netlink_flow_dump {
1328     struct dpif_flow_dump up;
1329     struct nl_dump nl_dump;
1330     atomic_int status;
1331 };
1332
1333 static struct dpif_netlink_flow_dump *
1334 dpif_netlink_flow_dump_cast(struct dpif_flow_dump *dump)
1335 {
1336     return CONTAINER_OF(dump, struct dpif_netlink_flow_dump, up);
1337 }
1338
1339 static struct dpif_flow_dump *
1340 dpif_netlink_flow_dump_create(const struct dpif *dpif_, bool terse)
1341 {
1342     const struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1343     struct dpif_netlink_flow_dump *dump;
1344     struct dpif_netlink_flow request;
1345     struct ofpbuf *buf;
1346
1347     dump = xmalloc(sizeof *dump);
1348     dpif_flow_dump_init(&dump->up, dpif_);
1349
1350     dpif_netlink_flow_init(&request);
1351     request.cmd = OVS_FLOW_CMD_GET;
1352     request.dp_ifindex = dpif->dp_ifindex;
1353     request.ufid_present = false;
1354     request.ufid_terse = terse;
1355
1356     buf = ofpbuf_new(1024);
1357     dpif_netlink_flow_to_ofpbuf(&request, buf);
1358     nl_dump_start(&dump->nl_dump, NETLINK_GENERIC, buf);
1359     ofpbuf_delete(buf);
1360     atomic_init(&dump->status, 0);
1361     dump->up.terse = terse;
1362
1363     return &dump->up;
1364 }
1365
1366 static int
1367 dpif_netlink_flow_dump_destroy(struct dpif_flow_dump *dump_)
1368 {
1369     struct dpif_netlink_flow_dump *dump = dpif_netlink_flow_dump_cast(dump_);
1370     unsigned int nl_status = nl_dump_done(&dump->nl_dump);
1371     int dump_status;
1372
1373     /* No other thread has access to 'dump' at this point. */
1374     atomic_read_relaxed(&dump->status, &dump_status);
1375     free(dump);
1376     return dump_status ? dump_status : nl_status;
1377 }
1378
1379 struct dpif_netlink_flow_dump_thread {
1380     struct dpif_flow_dump_thread up;
1381     struct dpif_netlink_flow_dump *dump;
1382     struct dpif_netlink_flow flow;
1383     struct dpif_flow_stats stats;
1384     struct ofpbuf nl_flows;     /* Always used to store flows. */
1385     struct ofpbuf *nl_actions;  /* Used if kernel does not supply actions. */
1386 };
1387
1388 static struct dpif_netlink_flow_dump_thread *
1389 dpif_netlink_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
1390 {
1391     return CONTAINER_OF(thread, struct dpif_netlink_flow_dump_thread, up);
1392 }
1393
1394 static struct dpif_flow_dump_thread *
1395 dpif_netlink_flow_dump_thread_create(struct dpif_flow_dump *dump_)
1396 {
1397     struct dpif_netlink_flow_dump *dump = dpif_netlink_flow_dump_cast(dump_);
1398     struct dpif_netlink_flow_dump_thread *thread;
1399
1400     thread = xmalloc(sizeof *thread);
1401     dpif_flow_dump_thread_init(&thread->up, &dump->up);
1402     thread->dump = dump;
1403     ofpbuf_init(&thread->nl_flows, NL_DUMP_BUFSIZE);
1404     thread->nl_actions = NULL;
1405
1406     return &thread->up;
1407 }
1408
1409 static void
1410 dpif_netlink_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
1411 {
1412     struct dpif_netlink_flow_dump_thread *thread
1413         = dpif_netlink_flow_dump_thread_cast(thread_);
1414
1415     ofpbuf_uninit(&thread->nl_flows);
1416     ofpbuf_delete(thread->nl_actions);
1417     free(thread);
1418 }
1419
1420 static void
1421 dpif_netlink_flow_to_dpif_flow(struct dpif *dpif, struct dpif_flow *dpif_flow,
1422                                const struct dpif_netlink_flow *datapath_flow)
1423 {
1424     dpif_flow->key = datapath_flow->key;
1425     dpif_flow->key_len = datapath_flow->key_len;
1426     dpif_flow->mask = datapath_flow->mask;
1427     dpif_flow->mask_len = datapath_flow->mask_len;
1428     dpif_flow->actions = datapath_flow->actions;
1429     dpif_flow->actions_len = datapath_flow->actions_len;
1430     dpif_flow->ufid_present = datapath_flow->ufid_present;
1431     if (datapath_flow->ufid_present) {
1432         dpif_flow->ufid = datapath_flow->ufid;
1433     dpif_flow->pmd_id = PMD_ID_NULL;
1434     } else {
1435         ovs_assert(datapath_flow->key && datapath_flow->key_len);
1436         dpif_flow_hash(dpif, datapath_flow->key, datapath_flow->key_len,
1437                        &dpif_flow->ufid);
1438     }
1439     dpif_netlink_flow_get_stats(datapath_flow, &dpif_flow->stats);
1440 }
1441
1442 static int
1443 dpif_netlink_flow_dump_next(struct dpif_flow_dump_thread *thread_,
1444                             struct dpif_flow *flows, int max_flows)
1445 {
1446     struct dpif_netlink_flow_dump_thread *thread
1447         = dpif_netlink_flow_dump_thread_cast(thread_);
1448     struct dpif_netlink_flow_dump *dump = thread->dump;
1449     struct dpif_netlink *dpif = dpif_netlink_cast(thread->up.dpif);
1450     int n_flows;
1451
1452     ofpbuf_delete(thread->nl_actions);
1453     thread->nl_actions = NULL;
1454
1455     n_flows = 0;
1456     while (!n_flows
1457            || (n_flows < max_flows && ofpbuf_size(&thread->nl_flows))) {
1458         struct dpif_netlink_flow datapath_flow;
1459         struct ofpbuf nl_flow;
1460         int error;
1461
1462         /* Try to grab another flow. */
1463         if (!nl_dump_next(&dump->nl_dump, &nl_flow, &thread->nl_flows)) {
1464             break;
1465         }
1466
1467         /* Convert the flow to our output format. */
1468         error = dpif_netlink_flow_from_ofpbuf(&datapath_flow, &nl_flow);
1469         if (error) {
1470             atomic_store_relaxed(&dump->status, error);
1471             break;
1472         }
1473
1474         if (dump->up.terse || datapath_flow.actions) {
1475             /* Common case: we don't want actions, or the flow includes
1476              * actions. */
1477             dpif_netlink_flow_to_dpif_flow(&dpif->dpif, &flows[n_flows++],
1478                                            &datapath_flow);
1479         } else {
1480             /* Rare case: the flow does not include actions.  Retrieve this
1481              * individual flow again to get the actions. */
1482             error = dpif_netlink_flow_get(dpif, &datapath_flow,
1483                                           &datapath_flow, &thread->nl_actions);
1484             if (error == ENOENT) {
1485                 VLOG_DBG("dumped flow disappeared on get");
1486                 continue;
1487             } else if (error) {
1488                 VLOG_WARN("error fetching dumped flow: %s",
1489                           ovs_strerror(error));
1490                 atomic_store_relaxed(&dump->status, error);
1491                 break;
1492             }
1493
1494             /* Save this flow.  Then exit, because we only have one buffer to
1495              * handle this case. */
1496             dpif_netlink_flow_to_dpif_flow(&dpif->dpif, &flows[n_flows++],
1497                                            &datapath_flow);
1498             break;
1499         }
1500     }
1501     return n_flows;
1502 }
1503
1504 static void
1505 dpif_netlink_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
1506                             struct ofpbuf *buf)
1507 {
1508     struct ovs_header *k_exec;
1509     size_t key_ofs;
1510
1511     ofpbuf_prealloc_tailroom(buf, (64
1512                                    + ofpbuf_size(d_exec->packet)
1513                                    + ODP_KEY_METADATA_SIZE
1514                                    + d_exec->actions_len));
1515
1516     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
1517                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
1518
1519     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
1520     k_exec->dp_ifindex = dp_ifindex;
1521
1522     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
1523                       ofpbuf_data(d_exec->packet),
1524                       ofpbuf_size(d_exec->packet));
1525
1526     key_ofs = nl_msg_start_nested(buf, OVS_PACKET_ATTR_KEY);
1527     odp_key_from_pkt_metadata(buf, &d_exec->md);
1528     nl_msg_end_nested(buf, key_ofs);
1529
1530     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
1531                       d_exec->actions, d_exec->actions_len);
1532     if (d_exec->probe) {
1533         nl_msg_put_flag(buf, OVS_PACKET_ATTR_PROBE);
1534     }
1535 }
1536
1537 /* Executes, against 'dpif', up to the first 'n_ops' operations in 'ops'.
1538  * Returns the number actually executed (at least 1, if 'n_ops' is
1539  * positive). */
1540 static size_t
1541 dpif_netlink_operate__(struct dpif_netlink *dpif,
1542                        struct dpif_op **ops, size_t n_ops)
1543 {
1544     enum { MAX_OPS = 50 };
1545
1546     struct op_auxdata {
1547         struct nl_transaction txn;
1548
1549         struct ofpbuf request;
1550         uint64_t request_stub[1024 / 8];
1551
1552         struct ofpbuf reply;
1553         uint64_t reply_stub[1024 / 8];
1554     } auxes[MAX_OPS];
1555
1556     struct nl_transaction *txnsp[MAX_OPS];
1557     size_t i;
1558
1559     n_ops = MIN(n_ops, MAX_OPS);
1560     for (i = 0; i < n_ops; i++) {
1561         struct op_auxdata *aux = &auxes[i];
1562         struct dpif_op *op = ops[i];
1563         struct dpif_flow_put *put;
1564         struct dpif_flow_del *del;
1565         struct dpif_flow_get *get;
1566         struct dpif_netlink_flow flow;
1567
1568         ofpbuf_use_stub(&aux->request,
1569                         aux->request_stub, sizeof aux->request_stub);
1570         aux->txn.request = &aux->request;
1571
1572         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1573         aux->txn.reply = NULL;
1574
1575         switch (op->type) {
1576         case DPIF_OP_FLOW_PUT:
1577             put = &op->u.flow_put;
1578             dpif_netlink_init_flow_put(dpif, put, &flow);
1579             if (put->stats) {
1580                 flow.nlmsg_flags |= NLM_F_ECHO;
1581                 aux->txn.reply = &aux->reply;
1582             }
1583             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1584             break;
1585
1586         case DPIF_OP_FLOW_DEL:
1587             del = &op->u.flow_del;
1588             dpif_netlink_init_flow_del(dpif, del, &flow);
1589             if (del->stats) {
1590                 flow.nlmsg_flags |= NLM_F_ECHO;
1591                 aux->txn.reply = &aux->reply;
1592             }
1593             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1594             break;
1595
1596         case DPIF_OP_EXECUTE:
1597             /* Can't execute a packet that won't fit in a Netlink attribute. */
1598             if (OVS_UNLIKELY(nl_attr_oversized(
1599                                  ofpbuf_size(op->u.execute.packet)))) {
1600                 /* Report an error immediately if this is the first operation.
1601                  * Otherwise the easiest thing to do is to postpone to the next
1602                  * call (when this will be the first operation). */
1603                 if (i == 0) {
1604                     VLOG_ERR_RL(&error_rl,
1605                                 "dropping oversized %"PRIu32"-byte packet",
1606                                 ofpbuf_size(op->u.execute.packet));
1607                     op->error = ENOBUFS;
1608                     return 1;
1609                 }
1610                 n_ops = i;
1611             } else {
1612                 dpif_netlink_encode_execute(dpif->dp_ifindex, &op->u.execute,
1613                                             &aux->request);
1614             }
1615             break;
1616
1617         case DPIF_OP_FLOW_GET:
1618             get = &op->u.flow_get;
1619             dpif_netlink_init_flow_get(dpif, get, &flow);
1620             aux->txn.reply = get->buffer;
1621             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1622             break;
1623
1624         default:
1625             OVS_NOT_REACHED();
1626         }
1627     }
1628
1629     for (i = 0; i < n_ops; i++) {
1630         txnsp[i] = &auxes[i].txn;
1631     }
1632     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1633
1634     for (i = 0; i < n_ops; i++) {
1635         struct op_auxdata *aux = &auxes[i];
1636         struct nl_transaction *txn = &auxes[i].txn;
1637         struct dpif_op *op = ops[i];
1638         struct dpif_flow_put *put;
1639         struct dpif_flow_del *del;
1640         struct dpif_flow_get *get;
1641
1642         op->error = txn->error;
1643
1644         switch (op->type) {
1645         case DPIF_OP_FLOW_PUT:
1646             put = &op->u.flow_put;
1647             if (put->stats) {
1648                 if (!op->error) {
1649                     struct dpif_netlink_flow reply;
1650
1651                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1652                                                               txn->reply);
1653                     if (!op->error) {
1654                         dpif_netlink_flow_get_stats(&reply, put->stats);
1655                     }
1656                 }
1657             }
1658             break;
1659
1660         case DPIF_OP_FLOW_DEL:
1661             del = &op->u.flow_del;
1662             if (del->stats) {
1663                 if (!op->error) {
1664                     struct dpif_netlink_flow reply;
1665
1666                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1667                                                               txn->reply);
1668                     if (!op->error) {
1669                         dpif_netlink_flow_get_stats(&reply, del->stats);
1670                     }
1671                 }
1672             }
1673             break;
1674
1675         case DPIF_OP_EXECUTE:
1676             break;
1677
1678         case DPIF_OP_FLOW_GET:
1679             get = &op->u.flow_get;
1680             if (!op->error) {
1681                 struct dpif_netlink_flow reply;
1682
1683                 op->error = dpif_netlink_flow_from_ofpbuf(&reply, txn->reply);
1684                 if (!op->error) {
1685                     dpif_netlink_flow_to_dpif_flow(&dpif->dpif, get->flow,
1686                                                    &reply);
1687                 }
1688             }
1689             break;
1690
1691         default:
1692             OVS_NOT_REACHED();
1693         }
1694
1695         ofpbuf_uninit(&aux->request);
1696         ofpbuf_uninit(&aux->reply);
1697     }
1698
1699     return n_ops;
1700 }
1701
1702 static void
1703 dpif_netlink_operate(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1704 {
1705     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1706
1707     while (n_ops > 0) {
1708         size_t chunk = dpif_netlink_operate__(dpif, ops, n_ops);
1709         ops += chunk;
1710         n_ops -= chunk;
1711     }
1712 }
1713
1714 #if _WIN32
1715 static void
1716 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1717 {
1718     vport_delete_sock_pool(handler);
1719 }
1720
1721 static int
1722 dpif_netlink_handler_init(struct dpif_handler *handler)
1723 {
1724     return vport_create_sock_pool(handler);
1725 }
1726 #else
1727
1728 static int
1729 dpif_netlink_handler_init(struct dpif_handler *handler)
1730 {
1731     handler->epoll_fd = epoll_create(10);
1732     return handler->epoll_fd < 0 ? errno : 0;
1733 }
1734
1735 static void
1736 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1737 {
1738     close(handler->epoll_fd);
1739 }
1740 #endif
1741
1742 /* Synchronizes 'channels' in 'dpif->handlers'  with the set of vports
1743  * currently in 'dpif' in the kernel, by adding a new set of channels for
1744  * any kernel vport that lacks one and deleting any channels that have no
1745  * backing kernel vports. */
1746 static int
1747 dpif_netlink_refresh_channels(struct dpif_netlink *dpif, uint32_t n_handlers)
1748     OVS_REQ_WRLOCK(dpif->upcall_lock)
1749 {
1750     unsigned long int *keep_channels;
1751     struct dpif_netlink_vport vport;
1752     size_t keep_channels_nbits;
1753     struct nl_dump dump;
1754     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
1755     struct ofpbuf buf;
1756     int retval = 0;
1757     size_t i;
1758
1759     ovs_assert(!WINDOWS || n_handlers <= 1);
1760     ovs_assert(!WINDOWS || dpif->n_handlers <= 1);
1761
1762     if (dpif->n_handlers != n_handlers) {
1763         destroy_all_channels(dpif);
1764         dpif->handlers = xzalloc(n_handlers * sizeof *dpif->handlers);
1765         for (i = 0; i < n_handlers; i++) {
1766             int error;
1767             struct dpif_handler *handler = &dpif->handlers[i];
1768
1769             error = dpif_netlink_handler_init(handler);
1770             if (error) {
1771                 size_t j;
1772                 struct dpif_handler *tmp = &dpif->handlers[i];
1773
1774
1775                 for (j = 0; j < i; j++) {
1776                     dpif_netlink_handler_uninit(tmp);
1777                 }
1778                 free(dpif->handlers);
1779                 dpif->handlers = NULL;
1780
1781                 return error;
1782             }
1783         }
1784         dpif->n_handlers = n_handlers;
1785     }
1786
1787     for (i = 0; i < n_handlers; i++) {
1788         struct dpif_handler *handler = &dpif->handlers[i];
1789
1790         handler->event_offset = handler->n_events = 0;
1791     }
1792
1793     keep_channels_nbits = dpif->uc_array_size;
1794     keep_channels = bitmap_allocate(keep_channels_nbits);
1795
1796     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
1797     dpif_netlink_port_dump_start__(dpif, &dump);
1798     while (!dpif_netlink_port_dump_next__(dpif, &dump, &vport, &buf)) {
1799         uint32_t port_no = odp_to_u32(vport.port_no);
1800         uint32_t *upcall_pids = NULL;
1801         int error;
1802
1803         if (port_no >= dpif->uc_array_size
1804             || !vport_get_pids(dpif, port_no, &upcall_pids)) {
1805             struct nl_sock **socksp = vport_create_socksp(dpif, &error);
1806
1807             if (!socksp) {
1808                 goto error;
1809             }
1810
1811             error = vport_add_channels(dpif, vport.port_no, socksp);
1812             if (error) {
1813                 VLOG_INFO("%s: could not add channels for port %s",
1814                           dpif_name(&dpif->dpif), vport.name);
1815                 vport_del_socksp(dpif, socksp);
1816                 retval = error;
1817                 goto error;
1818             }
1819             upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
1820             free(socksp);
1821         }
1822
1823         /* Configure the vport to deliver misses to 'sock'. */
1824         if (vport.upcall_pids[0] == 0
1825             || vport.n_upcall_pids != dpif->n_handlers
1826             || memcmp(upcall_pids, vport.upcall_pids, n_handlers * sizeof
1827                       *upcall_pids)) {
1828             struct dpif_netlink_vport vport_request;
1829
1830             dpif_netlink_vport_init(&vport_request);
1831             vport_request.cmd = OVS_VPORT_CMD_SET;
1832             vport_request.dp_ifindex = dpif->dp_ifindex;
1833             vport_request.port_no = vport.port_no;
1834             vport_request.n_upcall_pids = dpif->n_handlers;
1835             vport_request.upcall_pids = upcall_pids;
1836             error = dpif_netlink_vport_transact(&vport_request, NULL, NULL);
1837             if (error) {
1838                 VLOG_WARN_RL(&error_rl,
1839                              "%s: failed to set upcall pid on port: %s",
1840                              dpif_name(&dpif->dpif), ovs_strerror(error));
1841
1842                 if (error != ENODEV && error != ENOENT) {
1843                     retval = error;
1844                 } else {
1845                     /* The vport isn't really there, even though the dump says
1846                      * it is.  Probably we just hit a race after a port
1847                      * disappeared. */
1848                 }
1849                 goto error;
1850             }
1851         }
1852
1853         if (port_no < keep_channels_nbits) {
1854             bitmap_set1(keep_channels, port_no);
1855         }
1856         free(upcall_pids);
1857         continue;
1858
1859     error:
1860         free(upcall_pids);
1861         vport_del_channels(dpif, vport.port_no);
1862     }
1863     nl_dump_done(&dump);
1864     ofpbuf_uninit(&buf);
1865
1866     /* Discard any saved channels that we didn't reuse. */
1867     for (i = 0; i < keep_channels_nbits; i++) {
1868         if (!bitmap_is_set(keep_channels, i)) {
1869             vport_del_channels(dpif, u32_to_odp(i));
1870         }
1871     }
1872     free(keep_channels);
1873
1874     return retval;
1875 }
1876
1877 static int
1878 dpif_netlink_recv_set__(struct dpif_netlink *dpif, bool enable)
1879     OVS_REQ_WRLOCK(dpif->upcall_lock)
1880 {
1881     if ((dpif->handlers != NULL) == enable) {
1882         return 0;
1883     } else if (!enable) {
1884         destroy_all_channels(dpif);
1885         return 0;
1886     } else {
1887         return dpif_netlink_refresh_channels(dpif, 1);
1888     }
1889 }
1890
1891 static int
1892 dpif_netlink_recv_set(struct dpif *dpif_, bool enable)
1893 {
1894     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1895     int error;
1896
1897     fat_rwlock_wrlock(&dpif->upcall_lock);
1898     error = dpif_netlink_recv_set__(dpif, enable);
1899     fat_rwlock_unlock(&dpif->upcall_lock);
1900
1901     return error;
1902 }
1903
1904 static int
1905 dpif_netlink_handlers_set(struct dpif *dpif_, uint32_t n_handlers)
1906 {
1907     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1908     int error = 0;
1909
1910 #ifdef _WIN32
1911     /* Multiple upcall handlers will be supported once kernel datapath supports
1912      * it. */
1913     if (n_handlers > 1) {
1914         return error;
1915     }
1916 #endif
1917
1918     fat_rwlock_wrlock(&dpif->upcall_lock);
1919     if (dpif->handlers) {
1920         error = dpif_netlink_refresh_channels(dpif, n_handlers);
1921     }
1922     fat_rwlock_unlock(&dpif->upcall_lock);
1923
1924     return error;
1925 }
1926
1927 static int
1928 dpif_netlink_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1929                              uint32_t queue_id, uint32_t *priority)
1930 {
1931     if (queue_id < 0xf000) {
1932         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1933         return 0;
1934     } else {
1935         return EINVAL;
1936     }
1937 }
1938
1939 static int
1940 parse_odp_packet(const struct dpif_netlink *dpif, struct ofpbuf *buf,
1941                  struct dpif_upcall *upcall, int *dp_ifindex)
1942 {
1943     static const struct nl_policy ovs_packet_policy[] = {
1944         /* Always present. */
1945         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1946                                      .min_len = ETH_HEADER_LEN },
1947         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1948
1949         /* OVS_PACKET_CMD_ACTION only. */
1950         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1951         [OVS_PACKET_ATTR_EGRESS_TUN_KEY] = { .type = NL_A_NESTED, .optional = true },
1952     };
1953
1954     struct ovs_header *ovs_header;
1955     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1956     struct nlmsghdr *nlmsg;
1957     struct genlmsghdr *genl;
1958     struct ofpbuf b;
1959     int type;
1960
1961     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
1962
1963     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1964     genl = ofpbuf_try_pull(&b, sizeof *genl);
1965     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1966     if (!nlmsg || !genl || !ovs_header
1967         || nlmsg->nlmsg_type != ovs_packet_family
1968         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1969                             ARRAY_SIZE(ovs_packet_policy))) {
1970         return EINVAL;
1971     }
1972
1973     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1974             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1975             : -1);
1976     if (type < 0) {
1977         return EINVAL;
1978     }
1979
1980     /* (Re)set ALL fields of '*upcall' on successful return. */
1981     upcall->type = type;
1982     upcall->key = CONST_CAST(struct nlattr *,
1983                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1984     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1985     dpif_flow_hash(&dpif->dpif, upcall->key, upcall->key_len, &upcall->ufid);
1986     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1987     upcall->out_tun_key = a[OVS_PACKET_ATTR_EGRESS_TUN_KEY];
1988
1989     /* Allow overwriting the netlink attribute header without reallocating. */
1990     ofpbuf_use_stub(&upcall->packet,
1991                     CONST_CAST(struct nlattr *,
1992                                nl_attr_get(a[OVS_PACKET_ATTR_PACKET])) - 1,
1993                     nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]) +
1994                     sizeof(struct nlattr));
1995     ofpbuf_set_data(&upcall->packet,
1996                     (char *)ofpbuf_data(&upcall->packet) + sizeof(struct nlattr));
1997     ofpbuf_set_size(&upcall->packet, nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]));
1998
1999     *dp_ifindex = ovs_header->dp_ifindex;
2000
2001     return 0;
2002 }
2003
2004 #ifdef _WIN32
2005 #define PACKET_RECV_BATCH_SIZE 50
2006 static int
2007 dpif_netlink_recv_windows(struct dpif_netlink *dpif, uint32_t handler_id,
2008                           struct dpif_upcall *upcall, struct ofpbuf *buf)
2009     OVS_REQ_RDLOCK(dpif->upcall_lock)
2010 {
2011     struct dpif_handler *handler;
2012     int read_tries = 0;
2013     struct dpif_windows_vport_sock *sock_pool;
2014     uint32_t i;
2015
2016     if (!dpif->handlers) {
2017         return EAGAIN;
2018     }
2019
2020     /* Only one handler is supported currently. */
2021     if (handler_id >= 1) {
2022         return EAGAIN;
2023     }
2024
2025     if (handler_id >= dpif->n_handlers) {
2026         return EAGAIN;
2027     }
2028
2029     handler = &dpif->handlers[handler_id];
2030     sock_pool = handler->vport_sock_pool;
2031
2032     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2033         for (;;) {
2034             int dp_ifindex;
2035             int error;
2036
2037             if (++read_tries > PACKET_RECV_BATCH_SIZE) {
2038                 return EAGAIN;
2039             }
2040
2041             error = nl_sock_recv(sock_pool[i].nl_sock, buf, false);
2042             if (error == ENOBUFS) {
2043                 /* ENOBUFS typically means that we've received so many
2044                  * packets that the buffer overflowed.  Try again
2045                  * immediately because there's almost certainly a packet
2046                  * waiting for us. */
2047                 /* XXX: report_loss(dpif, ch, idx, handler_id); */
2048                 continue;
2049             }
2050
2051             /* XXX: ch->last_poll = time_msec(); */
2052             if (error) {
2053                 if (error == EAGAIN) {
2054                     break;
2055                 }
2056                 return error;
2057             }
2058
2059             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2060             if (!error && dp_ifindex == dpif->dp_ifindex) {
2061                 return 0;
2062             } else if (error) {
2063                 return error;
2064             }
2065         }
2066     }
2067
2068     return EAGAIN;
2069 }
2070 #else
2071 static int
2072 dpif_netlink_recv__(struct dpif_netlink *dpif, uint32_t handler_id,
2073                     struct dpif_upcall *upcall, struct ofpbuf *buf)
2074     OVS_REQ_RDLOCK(dpif->upcall_lock)
2075 {
2076     struct dpif_handler *handler;
2077     int read_tries = 0;
2078
2079     if (!dpif->handlers || handler_id >= dpif->n_handlers) {
2080         return EAGAIN;
2081     }
2082
2083     handler = &dpif->handlers[handler_id];
2084     if (handler->event_offset >= handler->n_events) {
2085         int retval;
2086
2087         handler->event_offset = handler->n_events = 0;
2088
2089         do {
2090             retval = epoll_wait(handler->epoll_fd, handler->epoll_events,
2091                                 dpif->uc_array_size, 0);
2092         } while (retval < 0 && errno == EINTR);
2093
2094         if (retval < 0) {
2095             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2096             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
2097         } else if (retval > 0) {
2098             handler->n_events = retval;
2099         }
2100     }
2101
2102     while (handler->event_offset < handler->n_events) {
2103         int idx = handler->epoll_events[handler->event_offset].data.u32;
2104         struct dpif_channel *ch = &dpif->handlers[handler_id].channels[idx];
2105
2106         handler->event_offset++;
2107
2108         for (;;) {
2109             int dp_ifindex;
2110             int error;
2111
2112             if (++read_tries > 50) {
2113                 return EAGAIN;
2114             }
2115
2116             error = nl_sock_recv(ch->sock, buf, false);
2117             if (error == ENOBUFS) {
2118                 /* ENOBUFS typically means that we've received so many
2119                  * packets that the buffer overflowed.  Try again
2120                  * immediately because there's almost certainly a packet
2121                  * waiting for us. */
2122                 report_loss(dpif, ch, idx, handler_id);
2123                 continue;
2124             }
2125
2126             ch->last_poll = time_msec();
2127             if (error) {
2128                 if (error == EAGAIN) {
2129                     break;
2130                 }
2131                 return error;
2132             }
2133
2134             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2135             if (!error && dp_ifindex == dpif->dp_ifindex) {
2136                 return 0;
2137             } else if (error) {
2138                 return error;
2139             }
2140         }
2141     }
2142
2143     return EAGAIN;
2144 }
2145 #endif
2146
2147 static int
2148 dpif_netlink_recv(struct dpif *dpif_, uint32_t handler_id,
2149                   struct dpif_upcall *upcall, struct ofpbuf *buf)
2150 {
2151     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2152     int error;
2153
2154     fat_rwlock_rdlock(&dpif->upcall_lock);
2155 #ifdef _WIN32
2156     error = dpif_netlink_recv_windows(dpif, handler_id, upcall, buf);
2157 #else
2158     error = dpif_netlink_recv__(dpif, handler_id, upcall, buf);
2159 #endif
2160     fat_rwlock_unlock(&dpif->upcall_lock);
2161
2162     return error;
2163 }
2164
2165 static void
2166 dpif_netlink_recv_wait__(struct dpif_netlink *dpif, uint32_t handler_id)
2167     OVS_REQ_RDLOCK(dpif->upcall_lock)
2168 {
2169 #ifdef _WIN32
2170     uint32_t i;
2171     struct dpif_windows_vport_sock *sock_pool =
2172         dpif->handlers[handler_id].vport_sock_pool;
2173
2174     /* Only one handler is supported currently. */
2175     if (handler_id >= 1) {
2176         return;
2177     }
2178
2179     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2180         nl_sock_wait(sock_pool[i].nl_sock, POLLIN);
2181     }
2182 #else
2183     if (dpif->handlers && handler_id < dpif->n_handlers) {
2184         struct dpif_handler *handler = &dpif->handlers[handler_id];
2185
2186         poll_fd_wait(handler->epoll_fd, POLLIN);
2187     }
2188 #endif
2189 }
2190
2191 static void
2192 dpif_netlink_recv_wait(struct dpif *dpif_, uint32_t handler_id)
2193 {
2194     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2195
2196     fat_rwlock_rdlock(&dpif->upcall_lock);
2197     dpif_netlink_recv_wait__(dpif, handler_id);
2198     fat_rwlock_unlock(&dpif->upcall_lock);
2199 }
2200
2201 static void
2202 dpif_netlink_recv_purge__(struct dpif_netlink *dpif)
2203     OVS_REQ_WRLOCK(dpif->upcall_lock)
2204 {
2205     if (dpif->handlers) {
2206         size_t i, j;
2207
2208         for (i = 0; i < dpif->uc_array_size; i++ ) {
2209             if (!dpif->handlers[0].channels[i].sock) {
2210                 continue;
2211             }
2212
2213             for (j = 0; j < dpif->n_handlers; j++) {
2214                 nl_sock_drain(dpif->handlers[j].channels[i].sock);
2215             }
2216         }
2217     }
2218 }
2219
2220 static void
2221 dpif_netlink_recv_purge(struct dpif *dpif_)
2222 {
2223     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2224
2225     fat_rwlock_wrlock(&dpif->upcall_lock);
2226     dpif_netlink_recv_purge__(dpif);
2227     fat_rwlock_unlock(&dpif->upcall_lock);
2228 }
2229
2230 static char *
2231 dpif_netlink_get_datapath_version(void)
2232 {
2233     char *version_str = NULL;
2234
2235 #ifdef __linux__
2236
2237 #define MAX_VERSION_STR_SIZE 80
2238 #define LINUX_DATAPATH_VERSION_FILE  "/sys/module/openvswitch/version"
2239     FILE *f;
2240
2241     f = fopen(LINUX_DATAPATH_VERSION_FILE, "r");
2242     if (f) {
2243         char *newline;
2244         char version[MAX_VERSION_STR_SIZE];
2245
2246         if (fgets(version, MAX_VERSION_STR_SIZE, f)) {
2247             newline = strchr(version, '\n');
2248             if (newline) {
2249                 *newline = '\0';
2250             }
2251             version_str = xstrdup(version);
2252         }
2253         fclose(f);
2254     }
2255 #endif
2256
2257     return version_str;
2258 }
2259
2260 const struct dpif_class dpif_netlink_class = {
2261     "system",
2262     dpif_netlink_enumerate,
2263     NULL,
2264     dpif_netlink_open,
2265     dpif_netlink_close,
2266     dpif_netlink_destroy,
2267     dpif_netlink_run,
2268     NULL,                       /* wait */
2269     dpif_netlink_get_stats,
2270     dpif_netlink_port_add,
2271     dpif_netlink_port_del,
2272     dpif_netlink_port_query_by_number,
2273     dpif_netlink_port_query_by_name,
2274     dpif_netlink_port_get_pid,
2275     dpif_netlink_port_dump_start,
2276     dpif_netlink_port_dump_next,
2277     dpif_netlink_port_dump_done,
2278     dpif_netlink_port_poll,
2279     dpif_netlink_port_poll_wait,
2280     dpif_netlink_flow_flush,
2281     dpif_netlink_flow_dump_create,
2282     dpif_netlink_flow_dump_destroy,
2283     dpif_netlink_flow_dump_thread_create,
2284     dpif_netlink_flow_dump_thread_destroy,
2285     dpif_netlink_flow_dump_next,
2286     dpif_netlink_operate,
2287     dpif_netlink_recv_set,
2288     dpif_netlink_handlers_set,
2289     NULL,                       /* poll_thread_set */
2290     dpif_netlink_queue_to_priority,
2291     dpif_netlink_recv,
2292     dpif_netlink_recv_wait,
2293     dpif_netlink_recv_purge,
2294     NULL,                       /* register_upcall_cb */
2295     NULL,                       /* enable_upcall */
2296     NULL,                       /* disable_upcall */
2297     dpif_netlink_get_datapath_version, /* get_datapath_version */
2298 };
2299
2300 static int
2301 dpif_netlink_init(void)
2302 {
2303     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2304     static int error;
2305
2306     if (ovsthread_once_start(&once)) {
2307         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
2308                                       &ovs_datapath_family);
2309         if (error) {
2310             VLOG_ERR("Generic Netlink family '%s' does not exist. "
2311                      "The Open vSwitch kernel module is probably not loaded.",
2312                      OVS_DATAPATH_FAMILY);
2313         }
2314         if (!error) {
2315             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
2316         }
2317         if (!error) {
2318             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
2319         }
2320         if (!error) {
2321             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
2322                                           &ovs_packet_family);
2323         }
2324         if (!error) {
2325             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
2326                                            &ovs_vport_mcgroup);
2327         }
2328
2329         ovsthread_once_done(&once);
2330     }
2331
2332     return error;
2333 }
2334
2335 bool
2336 dpif_netlink_is_internal_device(const char *name)
2337 {
2338     struct dpif_netlink_vport reply;
2339     struct ofpbuf *buf;
2340     int error;
2341
2342     error = dpif_netlink_vport_get(name, &reply, &buf);
2343     if (!error) {
2344         ofpbuf_delete(buf);
2345     } else if (error != ENODEV && error != ENOENT) {
2346         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
2347                      name, ovs_strerror(error));
2348     }
2349
2350     return reply.type == OVS_VPORT_TYPE_INTERNAL;
2351 }
2352 \f
2353 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2354  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
2355  * positive errno value.
2356  *
2357  * 'vport' will contain pointers into 'buf', so the caller should not free
2358  * 'buf' while 'vport' is still in use. */
2359 static int
2360 dpif_netlink_vport_from_ofpbuf(struct dpif_netlink_vport *vport,
2361                              const struct ofpbuf *buf)
2362 {
2363     static const struct nl_policy ovs_vport_policy[] = {
2364         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
2365         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
2366         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2367         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_UNSPEC },
2368         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
2369                                    .optional = true },
2370         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
2371     };
2372
2373     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
2374     struct ovs_header *ovs_header;
2375     struct nlmsghdr *nlmsg;
2376     struct genlmsghdr *genl;
2377     struct ofpbuf b;
2378
2379     dpif_netlink_vport_init(vport);
2380
2381     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2382     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2383     genl = ofpbuf_try_pull(&b, sizeof *genl);
2384     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2385     if (!nlmsg || !genl || !ovs_header
2386         || nlmsg->nlmsg_type != ovs_vport_family
2387         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
2388                             ARRAY_SIZE(ovs_vport_policy))) {
2389         return EINVAL;
2390     }
2391
2392     vport->cmd = genl->cmd;
2393     vport->dp_ifindex = ovs_header->dp_ifindex;
2394     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
2395     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2396     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
2397     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2398         vport->n_upcall_pids = nl_attr_get_size(a[OVS_VPORT_ATTR_UPCALL_PID])
2399                                / (sizeof *vport->upcall_pids);
2400         vport->upcall_pids = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
2401
2402     }
2403     if (a[OVS_VPORT_ATTR_STATS]) {
2404         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
2405     }
2406     if (a[OVS_VPORT_ATTR_OPTIONS]) {
2407         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
2408         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
2409     }
2410     return 0;
2411 }
2412
2413 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2414  * followed by Netlink attributes corresponding to 'vport'. */
2415 static void
2416 dpif_netlink_vport_to_ofpbuf(const struct dpif_netlink_vport *vport,
2417                              struct ofpbuf *buf)
2418 {
2419     struct ovs_header *ovs_header;
2420
2421     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
2422                           vport->cmd, OVS_VPORT_VERSION);
2423
2424     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2425     ovs_header->dp_ifindex = vport->dp_ifindex;
2426
2427     if (vport->port_no != ODPP_NONE) {
2428         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
2429     }
2430
2431     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
2432         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
2433     }
2434
2435     if (vport->name) {
2436         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
2437     }
2438
2439     if (vport->upcall_pids) {
2440         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_UPCALL_PID,
2441                           vport->upcall_pids,
2442                           vport->n_upcall_pids * sizeof *vport->upcall_pids);
2443     }
2444
2445     if (vport->stats) {
2446         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
2447                           vport->stats, sizeof *vport->stats);
2448     }
2449
2450     if (vport->options) {
2451         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
2452                           vport->options, vport->options_len);
2453     }
2454 }
2455
2456 /* Clears 'vport' to "empty" values. */
2457 void
2458 dpif_netlink_vport_init(struct dpif_netlink_vport *vport)
2459 {
2460     memset(vport, 0, sizeof *vport);
2461     vport->port_no = ODPP_NONE;
2462 }
2463
2464 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2465  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2466  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2467  * result of the command is expected to be an ovs_vport also, which is decoded
2468  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2469  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2470 int
2471 dpif_netlink_vport_transact(const struct dpif_netlink_vport *request,
2472                             struct dpif_netlink_vport *reply,
2473                             struct ofpbuf **bufp)
2474 {
2475     struct ofpbuf *request_buf;
2476     int error;
2477
2478     ovs_assert((reply != NULL) == (bufp != NULL));
2479
2480     error = dpif_netlink_init();
2481     if (error) {
2482         if (reply) {
2483             *bufp = NULL;
2484             dpif_netlink_vport_init(reply);
2485         }
2486         return error;
2487     }
2488
2489     request_buf = ofpbuf_new(1024);
2490     dpif_netlink_vport_to_ofpbuf(request, request_buf);
2491     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2492     ofpbuf_delete(request_buf);
2493
2494     if (reply) {
2495         if (!error) {
2496             error = dpif_netlink_vport_from_ofpbuf(reply, *bufp);
2497         }
2498         if (error) {
2499             dpif_netlink_vport_init(reply);
2500             ofpbuf_delete(*bufp);
2501             *bufp = NULL;
2502         }
2503     }
2504     return error;
2505 }
2506
2507 /* Obtains information about the kernel vport named 'name' and stores it into
2508  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
2509  * longer needed ('reply' will contain pointers into '*bufp').  */
2510 int
2511 dpif_netlink_vport_get(const char *name, struct dpif_netlink_vport *reply,
2512                        struct ofpbuf **bufp)
2513 {
2514     struct dpif_netlink_vport request;
2515
2516     dpif_netlink_vport_init(&request);
2517     request.cmd = OVS_VPORT_CMD_GET;
2518     request.name = name;
2519
2520     return dpif_netlink_vport_transact(&request, reply, bufp);
2521 }
2522
2523 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2524  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
2525  * positive errno value.
2526  *
2527  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
2528  * while 'dp' is still in use. */
2529 static int
2530 dpif_netlink_dp_from_ofpbuf(struct dpif_netlink_dp *dp, const struct ofpbuf *buf)
2531 {
2532     static const struct nl_policy ovs_datapath_policy[] = {
2533         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2534         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
2535                                 .optional = true },
2536         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
2537                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
2538                         .optional = true },
2539     };
2540
2541     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
2542     struct ovs_header *ovs_header;
2543     struct nlmsghdr *nlmsg;
2544     struct genlmsghdr *genl;
2545     struct ofpbuf b;
2546
2547     dpif_netlink_dp_init(dp);
2548
2549     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2550     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2551     genl = ofpbuf_try_pull(&b, sizeof *genl);
2552     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2553     if (!nlmsg || !genl || !ovs_header
2554         || nlmsg->nlmsg_type != ovs_datapath_family
2555         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
2556                             ARRAY_SIZE(ovs_datapath_policy))) {
2557         return EINVAL;
2558     }
2559
2560     dp->cmd = genl->cmd;
2561     dp->dp_ifindex = ovs_header->dp_ifindex;
2562     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
2563     if (a[OVS_DP_ATTR_STATS]) {
2564         dp->stats = nl_attr_get(a[OVS_DP_ATTR_STATS]);
2565     }
2566
2567     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
2568         dp->megaflow_stats = nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]);
2569     }
2570
2571     return 0;
2572 }
2573
2574 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
2575 static void
2576 dpif_netlink_dp_to_ofpbuf(const struct dpif_netlink_dp *dp, struct ofpbuf *buf)
2577 {
2578     struct ovs_header *ovs_header;
2579
2580     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
2581                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
2582                           OVS_DATAPATH_VERSION);
2583
2584     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2585     ovs_header->dp_ifindex = dp->dp_ifindex;
2586
2587     if (dp->name) {
2588         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
2589     }
2590
2591     if (dp->upcall_pid) {
2592         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
2593     }
2594
2595     if (dp->user_features) {
2596         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
2597     }
2598
2599     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
2600 }
2601
2602 /* Clears 'dp' to "empty" values. */
2603 static void
2604 dpif_netlink_dp_init(struct dpif_netlink_dp *dp)
2605 {
2606     memset(dp, 0, sizeof *dp);
2607 }
2608
2609 static void
2610 dpif_netlink_dp_dump_start(struct nl_dump *dump)
2611 {
2612     struct dpif_netlink_dp request;
2613     struct ofpbuf *buf;
2614
2615     dpif_netlink_dp_init(&request);
2616     request.cmd = OVS_DP_CMD_GET;
2617
2618     buf = ofpbuf_new(1024);
2619     dpif_netlink_dp_to_ofpbuf(&request, buf);
2620     nl_dump_start(dump, NETLINK_GENERIC, buf);
2621     ofpbuf_delete(buf);
2622 }
2623
2624 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2625  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2626  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2627  * result of the command is expected to be of the same form, which is decoded
2628  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2629  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2630 static int
2631 dpif_netlink_dp_transact(const struct dpif_netlink_dp *request,
2632                          struct dpif_netlink_dp *reply, struct ofpbuf **bufp)
2633 {
2634     struct ofpbuf *request_buf;
2635     int error;
2636
2637     ovs_assert((reply != NULL) == (bufp != NULL));
2638
2639     request_buf = ofpbuf_new(1024);
2640     dpif_netlink_dp_to_ofpbuf(request, request_buf);
2641     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2642     ofpbuf_delete(request_buf);
2643
2644     if (reply) {
2645         dpif_netlink_dp_init(reply);
2646         if (!error) {
2647             error = dpif_netlink_dp_from_ofpbuf(reply, *bufp);
2648         }
2649         if (error) {
2650             ofpbuf_delete(*bufp);
2651             *bufp = NULL;
2652         }
2653     }
2654     return error;
2655 }
2656
2657 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
2658  * The caller must free '*bufp' when the reply is no longer needed ('reply'
2659  * will contain pointers into '*bufp').  */
2660 static int
2661 dpif_netlink_dp_get(const struct dpif *dpif_, struct dpif_netlink_dp *reply,
2662                     struct ofpbuf **bufp)
2663 {
2664     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2665     struct dpif_netlink_dp request;
2666
2667     dpif_netlink_dp_init(&request);
2668     request.cmd = OVS_DP_CMD_GET;
2669     request.dp_ifindex = dpif->dp_ifindex;
2670
2671     return dpif_netlink_dp_transact(&request, reply, bufp);
2672 }
2673
2674 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2675  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2676  * positive errno value.
2677  *
2678  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2679  * while 'flow' is still in use. */
2680 static int
2681 dpif_netlink_flow_from_ofpbuf(struct dpif_netlink_flow *flow,
2682                               const struct ofpbuf *buf)
2683 {
2684     static const struct nl_policy ovs_flow_policy[__OVS_FLOW_ATTR_MAX] = {
2685         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED, .optional = true },
2686         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2687         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2688         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2689                                   .optional = true },
2690         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2691         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2692         [OVS_FLOW_ATTR_UFID] = { .type = NL_A_UNSPEC, .optional = true,
2693                                  .min_len = sizeof(ovs_u128) },
2694         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2695         /* The kernel never uses OVS_FLOW_ATTR_PROBE. */
2696         /* The kernel never uses OVS_FLOW_ATTR_UFID_FLAGS. */
2697     };
2698
2699     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2700     struct ovs_header *ovs_header;
2701     struct nlmsghdr *nlmsg;
2702     struct genlmsghdr *genl;
2703     struct ofpbuf b;
2704
2705     dpif_netlink_flow_init(flow);
2706
2707     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2708     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2709     genl = ofpbuf_try_pull(&b, sizeof *genl);
2710     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2711     if (!nlmsg || !genl || !ovs_header
2712         || nlmsg->nlmsg_type != ovs_flow_family
2713         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2714                             ARRAY_SIZE(ovs_flow_policy))) {
2715         return EINVAL;
2716     }
2717     if (!a[OVS_FLOW_ATTR_KEY] && !a[OVS_FLOW_ATTR_UFID]) {
2718         return EINVAL;
2719     }
2720
2721     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2722     flow->dp_ifindex = ovs_header->dp_ifindex;
2723     if (a[OVS_FLOW_ATTR_KEY]) {
2724         flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2725         flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2726     }
2727
2728     if (a[OVS_FLOW_ATTR_UFID]) {
2729         const ovs_u128 *ufid;
2730
2731         ufid = nl_attr_get_unspec(a[OVS_FLOW_ATTR_UFID],
2732                                   nl_attr_get_size(a[OVS_FLOW_ATTR_UFID]));
2733         flow->ufid = *ufid;
2734         flow->ufid_present = true;
2735     }
2736     if (a[OVS_FLOW_ATTR_MASK]) {
2737         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2738         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2739     }
2740     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2741         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2742         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2743     }
2744     if (a[OVS_FLOW_ATTR_STATS]) {
2745         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2746     }
2747     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2748         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2749     }
2750     if (a[OVS_FLOW_ATTR_USED]) {
2751         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2752     }
2753     return 0;
2754 }
2755
2756 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2757  * followed by Netlink attributes corresponding to 'flow'. */
2758 static void
2759 dpif_netlink_flow_to_ofpbuf(const struct dpif_netlink_flow *flow,
2760                             struct ofpbuf *buf)
2761 {
2762     struct ovs_header *ovs_header;
2763
2764     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2765                           NLM_F_REQUEST | flow->nlmsg_flags,
2766                           flow->cmd, OVS_FLOW_VERSION);
2767
2768     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2769     ovs_header->dp_ifindex = flow->dp_ifindex;
2770
2771     if (flow->ufid_present) {
2772         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_UFID, &flow->ufid,
2773                           sizeof flow->ufid);
2774     }
2775     if (flow->ufid_terse) {
2776         nl_msg_put_u32(buf, OVS_FLOW_ATTR_UFID_FLAGS,
2777                        OVS_UFID_F_OMIT_KEY | OVS_UFID_F_OMIT_MASK
2778                        | OVS_UFID_F_OMIT_ACTIONS);
2779     }
2780     if (!flow->ufid_terse || !flow->ufid_present) {
2781         if (flow->key_len) {
2782             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY,
2783                               flow->key, flow->key_len);
2784         }
2785
2786         if (flow->mask_len) {
2787             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK,
2788                               flow->mask, flow->mask_len);
2789         }
2790         if (flow->actions || flow->actions_len) {
2791             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2792                               flow->actions, flow->actions_len);
2793         }
2794     }
2795
2796     /* We never need to send these to the kernel. */
2797     ovs_assert(!flow->stats);
2798     ovs_assert(!flow->tcp_flags);
2799     ovs_assert(!flow->used);
2800
2801     if (flow->clear) {
2802         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2803     }
2804     if (flow->probe) {
2805         nl_msg_put_flag(buf, OVS_FLOW_ATTR_PROBE);
2806     }
2807 }
2808
2809 /* Clears 'flow' to "empty" values. */
2810 static void
2811 dpif_netlink_flow_init(struct dpif_netlink_flow *flow)
2812 {
2813     memset(flow, 0, sizeof *flow);
2814 }
2815
2816 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2817  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2818  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2819  * result of the command is expected to be a flow also, which is decoded and
2820  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2821  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2822 static int
2823 dpif_netlink_flow_transact(struct dpif_netlink_flow *request,
2824                            struct dpif_netlink_flow *reply,
2825                            struct ofpbuf **bufp)
2826 {
2827     struct ofpbuf *request_buf;
2828     int error;
2829
2830     ovs_assert((reply != NULL) == (bufp != NULL));
2831
2832     if (reply) {
2833         request->nlmsg_flags |= NLM_F_ECHO;
2834     }
2835
2836     request_buf = ofpbuf_new(1024);
2837     dpif_netlink_flow_to_ofpbuf(request, request_buf);
2838     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2839     ofpbuf_delete(request_buf);
2840
2841     if (reply) {
2842         if (!error) {
2843             error = dpif_netlink_flow_from_ofpbuf(reply, *bufp);
2844         }
2845         if (error) {
2846             dpif_netlink_flow_init(reply);
2847             ofpbuf_delete(*bufp);
2848             *bufp = NULL;
2849         }
2850     }
2851     return error;
2852 }
2853
2854 static void
2855 dpif_netlink_flow_get_stats(const struct dpif_netlink_flow *flow,
2856                             struct dpif_flow_stats *stats)
2857 {
2858     if (flow->stats) {
2859         stats->n_packets = get_32aligned_u64(&flow->stats->n_packets);
2860         stats->n_bytes = get_32aligned_u64(&flow->stats->n_bytes);
2861     } else {
2862         stats->n_packets = 0;
2863         stats->n_bytes = 0;
2864     }
2865     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2866     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2867 }
2868 \f
2869 /* Logs information about a packet that was recently lost in 'ch' (in
2870  * 'dpif_'). */
2871 static void
2872 report_loss(struct dpif_netlink *dpif, struct dpif_channel *ch, uint32_t ch_idx,
2873             uint32_t handler_id)
2874 {
2875     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2876     struct ds s;
2877
2878     if (VLOG_DROP_WARN(&rl)) {
2879         return;
2880     }
2881
2882     ds_init(&s);
2883     if (ch->last_poll != LLONG_MIN) {
2884         ds_put_format(&s, " (last polled %lld ms ago)",
2885                       time_msec() - ch->last_poll);
2886     }
2887
2888     VLOG_WARN("%s: lost packet on port channel %u of handler %u",
2889               dpif_name(&dpif->dpif), ch_idx, handler_id);
2890     ds_destroy(&s);
2891 }