dpif-netdev: Add per-pmd flow-table/classifier.
[cascardo/ovs.git] / lib / dpif-netlink.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "dpif-netlink.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/types.h>
27 #include <linux/pkt_sched.h>
28 #include <poll.h>
29 #include <stdlib.h>
30 #include <strings.h>
31 #include <sys/epoll.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34
35 #include "bitmap.h"
36 #include "dpif-provider.h"
37 #include "dynamic-string.h"
38 #include "flow.h"
39 #include "fat-rwlock.h"
40 #include "netdev.h"
41 #include "netdev-linux.h"
42 #include "netdev-vport.h"
43 #include "netlink-notifier.h"
44 #include "netlink-socket.h"
45 #include "netlink.h"
46 #include "odp-util.h"
47 #include "ofpbuf.h"
48 #include "packets.h"
49 #include "poll-loop.h"
50 #include "random.h"
51 #include "shash.h"
52 #include "sset.h"
53 #include "timeval.h"
54 #include "unaligned.h"
55 #include "util.h"
56 #include "openvswitch/vlog.h"
57
58 VLOG_DEFINE_THIS_MODULE(dpif_netlink);
59 #ifdef _WIN32
60 enum { WINDOWS = 1 };
61 #else
62 enum { WINDOWS = 0 };
63 #endif
64 enum { MAX_PORTS = USHRT_MAX };
65
66 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
67  * missing if we have old headers. */
68 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
69
70 struct dpif_netlink_dp {
71     /* Generic Netlink header. */
72     uint8_t cmd;
73
74     /* struct ovs_header. */
75     int dp_ifindex;
76
77     /* Attributes. */
78     const char *name;                  /* OVS_DP_ATTR_NAME. */
79     const uint32_t *upcall_pid;        /* OVS_DP_ATTR_UPCALL_PID. */
80     uint32_t user_features;            /* OVS_DP_ATTR_USER_FEATURES */
81     const struct ovs_dp_stats *stats;  /* OVS_DP_ATTR_STATS. */
82     const struct ovs_dp_megaflow_stats *megaflow_stats;
83                                        /* OVS_DP_ATTR_MEGAFLOW_STATS.*/
84 };
85
86 static void dpif_netlink_dp_init(struct dpif_netlink_dp *);
87 static int dpif_netlink_dp_from_ofpbuf(struct dpif_netlink_dp *,
88                                        const struct ofpbuf *);
89 static void dpif_netlink_dp_dump_start(struct nl_dump *);
90 static int dpif_netlink_dp_transact(const struct dpif_netlink_dp *request,
91                                     struct dpif_netlink_dp *reply,
92                                     struct ofpbuf **bufp);
93 static int dpif_netlink_dp_get(const struct dpif *,
94                                struct dpif_netlink_dp *reply,
95                                struct ofpbuf **bufp);
96
97 struct dpif_netlink_flow {
98     /* Generic Netlink header. */
99     uint8_t cmd;
100
101     /* struct ovs_header. */
102     unsigned int nlmsg_flags;
103     int dp_ifindex;
104
105     /* Attributes.
106      *
107      * The 'stats' member points to 64-bit data that might only be aligned on
108      * 32-bit boundaries, so get_unaligned_u64() should be used to access its
109      * values.
110      *
111      * If 'actions' is nonnull then OVS_FLOW_ATTR_ACTIONS will be included in
112      * the Netlink version of the command, even if actions_len is zero. */
113     const struct nlattr *key;           /* OVS_FLOW_ATTR_KEY. */
114     size_t key_len;
115     const struct nlattr *mask;          /* OVS_FLOW_ATTR_MASK. */
116     size_t mask_len;
117     const struct nlattr *actions;       /* OVS_FLOW_ATTR_ACTIONS. */
118     size_t actions_len;
119     ovs_u128 ufid;                      /* OVS_FLOW_ATTR_FLOW_ID. */
120     bool ufid_present;                  /* Is there a UFID? */
121     bool ufid_terse;                    /* Skip serializing key/mask/acts? */
122     const struct ovs_flow_stats *stats; /* OVS_FLOW_ATTR_STATS. */
123     const uint8_t *tcp_flags;           /* OVS_FLOW_ATTR_TCP_FLAGS. */
124     const ovs_32aligned_u64 *used;      /* OVS_FLOW_ATTR_USED. */
125     bool clear;                         /* OVS_FLOW_ATTR_CLEAR. */
126     bool probe;                         /* OVS_FLOW_ATTR_PROBE. */
127 };
128
129 static void dpif_netlink_flow_init(struct dpif_netlink_flow *);
130 static int dpif_netlink_flow_from_ofpbuf(struct dpif_netlink_flow *,
131                                          const struct ofpbuf *);
132 static void dpif_netlink_flow_to_ofpbuf(const struct dpif_netlink_flow *,
133                                         struct ofpbuf *);
134 static int dpif_netlink_flow_transact(struct dpif_netlink_flow *request,
135                                       struct dpif_netlink_flow *reply,
136                                       struct ofpbuf **bufp);
137 static void dpif_netlink_flow_get_stats(const struct dpif_netlink_flow *,
138                                         struct dpif_flow_stats *);
139 static void dpif_netlink_flow_to_dpif_flow(struct dpif *, struct dpif_flow *,
140                                            const struct dpif_netlink_flow *);
141
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_FLOW_ATTR_PROBE);
1534     }
1535 }
1536
1537 #define MAX_OPS 50
1538
1539 static void
1540 dpif_netlink_operate__(struct dpif_netlink *dpif,
1541                        struct dpif_op **ops, size_t n_ops)
1542 {
1543     struct op_auxdata {
1544         struct nl_transaction txn;
1545
1546         struct ofpbuf request;
1547         uint64_t request_stub[1024 / 8];
1548
1549         struct ofpbuf reply;
1550         uint64_t reply_stub[1024 / 8];
1551     } auxes[MAX_OPS];
1552
1553     struct nl_transaction *txnsp[MAX_OPS];
1554     size_t i;
1555
1556     ovs_assert(n_ops <= MAX_OPS);
1557     for (i = 0; i < n_ops; i++) {
1558         struct op_auxdata *aux = &auxes[i];
1559         struct dpif_op *op = ops[i];
1560         struct dpif_flow_put *put;
1561         struct dpif_flow_del *del;
1562         struct dpif_execute *execute;
1563         struct dpif_flow_get *get;
1564         struct dpif_netlink_flow flow;
1565
1566         ofpbuf_use_stub(&aux->request,
1567                         aux->request_stub, sizeof aux->request_stub);
1568         aux->txn.request = &aux->request;
1569
1570         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
1571         aux->txn.reply = NULL;
1572
1573         switch (op->type) {
1574         case DPIF_OP_FLOW_PUT:
1575             put = &op->u.flow_put;
1576             dpif_netlink_init_flow_put(dpif, put, &flow);
1577             if (put->stats) {
1578                 flow.nlmsg_flags |= NLM_F_ECHO;
1579                 aux->txn.reply = &aux->reply;
1580             }
1581             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1582             break;
1583
1584         case DPIF_OP_FLOW_DEL:
1585             del = &op->u.flow_del;
1586             dpif_netlink_init_flow_del(dpif, del, &flow);
1587             if (del->stats) {
1588                 flow.nlmsg_flags |= NLM_F_ECHO;
1589                 aux->txn.reply = &aux->reply;
1590             }
1591             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1592             break;
1593
1594         case DPIF_OP_EXECUTE:
1595             execute = &op->u.execute;
1596             dpif_netlink_encode_execute(dpif->dp_ifindex, execute,
1597                                         &aux->request);
1598             break;
1599
1600         case DPIF_OP_FLOW_GET:
1601             get = &op->u.flow_get;
1602             dpif_netlink_init_flow_get(dpif, get, &flow);
1603             aux->txn.reply = get->buffer;
1604             dpif_netlink_flow_to_ofpbuf(&flow, &aux->request);
1605             break;
1606
1607         default:
1608             OVS_NOT_REACHED();
1609         }
1610     }
1611
1612     for (i = 0; i < n_ops; i++) {
1613         txnsp[i] = &auxes[i].txn;
1614     }
1615     nl_transact_multiple(NETLINK_GENERIC, txnsp, n_ops);
1616
1617     for (i = 0; i < n_ops; i++) {
1618         struct op_auxdata *aux = &auxes[i];
1619         struct nl_transaction *txn = &auxes[i].txn;
1620         struct dpif_op *op = ops[i];
1621         struct dpif_flow_put *put;
1622         struct dpif_flow_del *del;
1623         struct dpif_flow_get *get;
1624
1625         op->error = txn->error;
1626
1627         switch (op->type) {
1628         case DPIF_OP_FLOW_PUT:
1629             put = &op->u.flow_put;
1630             if (put->stats) {
1631                 if (!op->error) {
1632                     struct dpif_netlink_flow reply;
1633
1634                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1635                                                               txn->reply);
1636                     if (!op->error) {
1637                         dpif_netlink_flow_get_stats(&reply, put->stats);
1638                     }
1639                 }
1640             }
1641             break;
1642
1643         case DPIF_OP_FLOW_DEL:
1644             del = &op->u.flow_del;
1645             if (del->stats) {
1646                 if (!op->error) {
1647                     struct dpif_netlink_flow reply;
1648
1649                     op->error = dpif_netlink_flow_from_ofpbuf(&reply,
1650                                                               txn->reply);
1651                     if (!op->error) {
1652                         dpif_netlink_flow_get_stats(&reply, del->stats);
1653                     }
1654                 }
1655             }
1656             break;
1657
1658         case DPIF_OP_EXECUTE:
1659             break;
1660
1661         case DPIF_OP_FLOW_GET:
1662             get = &op->u.flow_get;
1663             if (!op->error) {
1664                 struct dpif_netlink_flow reply;
1665
1666                 op->error = dpif_netlink_flow_from_ofpbuf(&reply, txn->reply);
1667                 if (!op->error) {
1668                     dpif_netlink_flow_to_dpif_flow(&dpif->dpif, get->flow,
1669                                                    &reply);
1670                 }
1671             }
1672             break;
1673
1674         default:
1675             OVS_NOT_REACHED();
1676         }
1677
1678         ofpbuf_uninit(&aux->request);
1679         ofpbuf_uninit(&aux->reply);
1680     }
1681 }
1682
1683 static void
1684 dpif_netlink_operate(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
1685 {
1686     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1687
1688     while (n_ops > 0) {
1689         size_t chunk = MIN(n_ops, MAX_OPS);
1690         dpif_netlink_operate__(dpif, ops, chunk);
1691         ops += chunk;
1692         n_ops -= chunk;
1693     }
1694 }
1695
1696 #if _WIN32
1697 static void
1698 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1699 {
1700     vport_delete_sock_pool(handler);
1701 }
1702
1703 static int
1704 dpif_netlink_handler_init(struct dpif_handler *handler)
1705 {
1706     return vport_create_sock_pool(handler);
1707 }
1708 #else
1709
1710 static int
1711 dpif_netlink_handler_init(struct dpif_handler *handler)
1712 {
1713     handler->epoll_fd = epoll_create(10);
1714     return handler->epoll_fd < 0 ? errno : 0;
1715 }
1716
1717 static void
1718 dpif_netlink_handler_uninit(struct dpif_handler *handler)
1719 {
1720     close(handler->epoll_fd);
1721 }
1722 #endif
1723
1724 /* Synchronizes 'channels' in 'dpif->handlers'  with the set of vports
1725  * currently in 'dpif' in the kernel, by adding a new set of channels for
1726  * any kernel vport that lacks one and deleting any channels that have no
1727  * backing kernel vports. */
1728 static int
1729 dpif_netlink_refresh_channels(struct dpif_netlink *dpif, uint32_t n_handlers)
1730     OVS_REQ_WRLOCK(dpif->upcall_lock)
1731 {
1732     unsigned long int *keep_channels;
1733     struct dpif_netlink_vport vport;
1734     size_t keep_channels_nbits;
1735     struct nl_dump dump;
1736     uint64_t reply_stub[NL_DUMP_BUFSIZE / 8];
1737     struct ofpbuf buf;
1738     int retval = 0;
1739     size_t i;
1740
1741     ovs_assert(!WINDOWS || n_handlers <= 1);
1742     ovs_assert(!WINDOWS || dpif->n_handlers <= 1);
1743
1744     if (dpif->n_handlers != n_handlers) {
1745         destroy_all_channels(dpif);
1746         dpif->handlers = xzalloc(n_handlers * sizeof *dpif->handlers);
1747         for (i = 0; i < n_handlers; i++) {
1748             int error;
1749             struct dpif_handler *handler = &dpif->handlers[i];
1750
1751             error = dpif_netlink_handler_init(handler);
1752             if (error) {
1753                 size_t j;
1754                 struct dpif_handler *tmp = &dpif->handlers[i];
1755
1756
1757                 for (j = 0; j < i; j++) {
1758                     dpif_netlink_handler_uninit(tmp);
1759                 }
1760                 free(dpif->handlers);
1761                 dpif->handlers = NULL;
1762
1763                 return error;
1764             }
1765         }
1766         dpif->n_handlers = n_handlers;
1767     }
1768
1769     for (i = 0; i < n_handlers; i++) {
1770         struct dpif_handler *handler = &dpif->handlers[i];
1771
1772         handler->event_offset = handler->n_events = 0;
1773     }
1774
1775     keep_channels_nbits = dpif->uc_array_size;
1776     keep_channels = bitmap_allocate(keep_channels_nbits);
1777
1778     ofpbuf_use_stub(&buf, reply_stub, sizeof reply_stub);
1779     dpif_netlink_port_dump_start__(dpif, &dump);
1780     while (!dpif_netlink_port_dump_next__(dpif, &dump, &vport, &buf)) {
1781         uint32_t port_no = odp_to_u32(vport.port_no);
1782         uint32_t *upcall_pids = NULL;
1783         int error;
1784
1785         if (port_no >= dpif->uc_array_size
1786             || !vport_get_pids(dpif, port_no, &upcall_pids)) {
1787             struct nl_sock **socksp = vport_create_socksp(dpif, &error);
1788
1789             if (!socksp) {
1790                 goto error;
1791             }
1792
1793             error = vport_add_channels(dpif, vport.port_no, socksp);
1794             if (error) {
1795                 VLOG_INFO("%s: could not add channels for port %s",
1796                           dpif_name(&dpif->dpif), vport.name);
1797                 vport_del_socksp(dpif, socksp);
1798                 retval = error;
1799                 goto error;
1800             }
1801             upcall_pids = vport_socksp_to_pids(socksp, dpif->n_handlers);
1802             free(socksp);
1803         }
1804
1805         /* Configure the vport to deliver misses to 'sock'. */
1806         if (vport.upcall_pids[0] == 0
1807             || vport.n_upcall_pids != dpif->n_handlers
1808             || memcmp(upcall_pids, vport.upcall_pids, n_handlers * sizeof
1809                       *upcall_pids)) {
1810             struct dpif_netlink_vport vport_request;
1811
1812             dpif_netlink_vport_init(&vport_request);
1813             vport_request.cmd = OVS_VPORT_CMD_SET;
1814             vport_request.dp_ifindex = dpif->dp_ifindex;
1815             vport_request.port_no = vport.port_no;
1816             vport_request.n_upcall_pids = dpif->n_handlers;
1817             vport_request.upcall_pids = upcall_pids;
1818             error = dpif_netlink_vport_transact(&vport_request, NULL, NULL);
1819             if (error) {
1820                 VLOG_WARN_RL(&error_rl,
1821                              "%s: failed to set upcall pid on port: %s",
1822                              dpif_name(&dpif->dpif), ovs_strerror(error));
1823
1824                 if (error != ENODEV && error != ENOENT) {
1825                     retval = error;
1826                 } else {
1827                     /* The vport isn't really there, even though the dump says
1828                      * it is.  Probably we just hit a race after a port
1829                      * disappeared. */
1830                 }
1831                 goto error;
1832             }
1833         }
1834
1835         if (port_no < keep_channels_nbits) {
1836             bitmap_set1(keep_channels, port_no);
1837         }
1838         free(upcall_pids);
1839         continue;
1840
1841     error:
1842         free(upcall_pids);
1843         vport_del_channels(dpif, vport.port_no);
1844     }
1845     nl_dump_done(&dump);
1846     ofpbuf_uninit(&buf);
1847
1848     /* Discard any saved channels that we didn't reuse. */
1849     for (i = 0; i < keep_channels_nbits; i++) {
1850         if (!bitmap_is_set(keep_channels, i)) {
1851             vport_del_channels(dpif, u32_to_odp(i));
1852         }
1853     }
1854     free(keep_channels);
1855
1856     return retval;
1857 }
1858
1859 static int
1860 dpif_netlink_recv_set__(struct dpif_netlink *dpif, bool enable)
1861     OVS_REQ_WRLOCK(dpif->upcall_lock)
1862 {
1863     if ((dpif->handlers != NULL) == enable) {
1864         return 0;
1865     } else if (!enable) {
1866         destroy_all_channels(dpif);
1867         return 0;
1868     } else {
1869         return dpif_netlink_refresh_channels(dpif, 1);
1870     }
1871 }
1872
1873 static int
1874 dpif_netlink_recv_set(struct dpif *dpif_, bool enable)
1875 {
1876     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1877     int error;
1878
1879     fat_rwlock_wrlock(&dpif->upcall_lock);
1880     error = dpif_netlink_recv_set__(dpif, enable);
1881     fat_rwlock_unlock(&dpif->upcall_lock);
1882
1883     return error;
1884 }
1885
1886 static int
1887 dpif_netlink_handlers_set(struct dpif *dpif_, uint32_t n_handlers)
1888 {
1889     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
1890     int error = 0;
1891
1892 #ifdef _WIN32
1893     /* Multiple upcall handlers will be supported once kernel datapath supports
1894      * it. */
1895     if (n_handlers > 1) {
1896         return error;
1897     }
1898 #endif
1899
1900     fat_rwlock_wrlock(&dpif->upcall_lock);
1901     if (dpif->handlers) {
1902         error = dpif_netlink_refresh_channels(dpif, n_handlers);
1903     }
1904     fat_rwlock_unlock(&dpif->upcall_lock);
1905
1906     return error;
1907 }
1908
1909 static int
1910 dpif_netlink_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1911                              uint32_t queue_id, uint32_t *priority)
1912 {
1913     if (queue_id < 0xf000) {
1914         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1915         return 0;
1916     } else {
1917         return EINVAL;
1918     }
1919 }
1920
1921 static int
1922 parse_odp_packet(const struct dpif_netlink *dpif, struct ofpbuf *buf,
1923                  struct dpif_upcall *upcall, int *dp_ifindex)
1924 {
1925     static const struct nl_policy ovs_packet_policy[] = {
1926         /* Always present. */
1927         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1928                                      .min_len = ETH_HEADER_LEN },
1929         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1930
1931         /* OVS_PACKET_CMD_ACTION only. */
1932         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_UNSPEC, .optional = true },
1933         [OVS_PACKET_ATTR_EGRESS_TUN_KEY] = { .type = NL_A_NESTED, .optional = true },
1934     };
1935
1936     struct ovs_header *ovs_header;
1937     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1938     struct nlmsghdr *nlmsg;
1939     struct genlmsghdr *genl;
1940     struct ofpbuf b;
1941     int type;
1942
1943     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
1944
1945     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1946     genl = ofpbuf_try_pull(&b, sizeof *genl);
1947     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1948     if (!nlmsg || !genl || !ovs_header
1949         || nlmsg->nlmsg_type != ovs_packet_family
1950         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1951                             ARRAY_SIZE(ovs_packet_policy))) {
1952         return EINVAL;
1953     }
1954
1955     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1956             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1957             : -1);
1958     if (type < 0) {
1959         return EINVAL;
1960     }
1961
1962     /* (Re)set ALL fields of '*upcall' on successful return. */
1963     upcall->type = type;
1964     upcall->key = CONST_CAST(struct nlattr *,
1965                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1966     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1967     dpif_flow_hash(&dpif->dpif, upcall->key, upcall->key_len, &upcall->ufid);
1968     upcall->userdata = a[OVS_PACKET_ATTR_USERDATA];
1969     upcall->out_tun_key = a[OVS_PACKET_ATTR_EGRESS_TUN_KEY];
1970
1971     /* Allow overwriting the netlink attribute header without reallocating. */
1972     ofpbuf_use_stub(&upcall->packet,
1973                     CONST_CAST(struct nlattr *,
1974                                nl_attr_get(a[OVS_PACKET_ATTR_PACKET])) - 1,
1975                     nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]) +
1976                     sizeof(struct nlattr));
1977     ofpbuf_set_data(&upcall->packet,
1978                     (char *)ofpbuf_data(&upcall->packet) + sizeof(struct nlattr));
1979     ofpbuf_set_size(&upcall->packet, nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]));
1980
1981     *dp_ifindex = ovs_header->dp_ifindex;
1982
1983     return 0;
1984 }
1985
1986 #ifdef _WIN32
1987 #define PACKET_RECV_BATCH_SIZE 50
1988 static int
1989 dpif_netlink_recv_windows(struct dpif_netlink *dpif, uint32_t handler_id,
1990                           struct dpif_upcall *upcall, struct ofpbuf *buf)
1991     OVS_REQ_RDLOCK(dpif->upcall_lock)
1992 {
1993     struct dpif_handler *handler;
1994     int read_tries = 0;
1995     struct dpif_windows_vport_sock *sock_pool;
1996     uint32_t i;
1997
1998     if (!dpif->handlers) {
1999         return EAGAIN;
2000     }
2001
2002     /* Only one handler is supported currently. */
2003     if (handler_id >= 1) {
2004         return EAGAIN;
2005     }
2006
2007     if (handler_id >= dpif->n_handlers) {
2008         return EAGAIN;
2009     }
2010
2011     handler = &dpif->handlers[handler_id];
2012     sock_pool = handler->vport_sock_pool;
2013
2014     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2015         for (;;) {
2016             int dp_ifindex;
2017             int error;
2018
2019             if (++read_tries > PACKET_RECV_BATCH_SIZE) {
2020                 return EAGAIN;
2021             }
2022
2023             error = nl_sock_recv(sock_pool[i].nl_sock, buf, false);
2024             if (error == ENOBUFS) {
2025                 /* ENOBUFS typically means that we've received so many
2026                  * packets that the buffer overflowed.  Try again
2027                  * immediately because there's almost certainly a packet
2028                  * waiting for us. */
2029                 /* XXX: report_loss(dpif, ch, idx, handler_id); */
2030                 continue;
2031             }
2032
2033             /* XXX: ch->last_poll = time_msec(); */
2034             if (error) {
2035                 if (error == EAGAIN) {
2036                     break;
2037                 }
2038                 return error;
2039             }
2040
2041             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2042             if (!error && dp_ifindex == dpif->dp_ifindex) {
2043                 return 0;
2044             } else if (error) {
2045                 return error;
2046             }
2047         }
2048     }
2049
2050     return EAGAIN;
2051 }
2052 #else
2053 static int
2054 dpif_netlink_recv__(struct dpif_netlink *dpif, uint32_t handler_id,
2055                     struct dpif_upcall *upcall, struct ofpbuf *buf)
2056     OVS_REQ_RDLOCK(dpif->upcall_lock)
2057 {
2058     struct dpif_handler *handler;
2059     int read_tries = 0;
2060
2061     if (!dpif->handlers || handler_id >= dpif->n_handlers) {
2062         return EAGAIN;
2063     }
2064
2065     handler = &dpif->handlers[handler_id];
2066     if (handler->event_offset >= handler->n_events) {
2067         int retval;
2068
2069         handler->event_offset = handler->n_events = 0;
2070
2071         do {
2072             retval = epoll_wait(handler->epoll_fd, handler->epoll_events,
2073                                 dpif->uc_array_size, 0);
2074         } while (retval < 0 && errno == EINTR);
2075
2076         if (retval < 0) {
2077             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2078             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", ovs_strerror(errno));
2079         } else if (retval > 0) {
2080             handler->n_events = retval;
2081         }
2082     }
2083
2084     while (handler->event_offset < handler->n_events) {
2085         int idx = handler->epoll_events[handler->event_offset].data.u32;
2086         struct dpif_channel *ch = &dpif->handlers[handler_id].channels[idx];
2087
2088         handler->event_offset++;
2089
2090         for (;;) {
2091             int dp_ifindex;
2092             int error;
2093
2094             if (++read_tries > 50) {
2095                 return EAGAIN;
2096             }
2097
2098             error = nl_sock_recv(ch->sock, buf, false);
2099             if (error == ENOBUFS) {
2100                 /* ENOBUFS typically means that we've received so many
2101                  * packets that the buffer overflowed.  Try again
2102                  * immediately because there's almost certainly a packet
2103                  * waiting for us. */
2104                 report_loss(dpif, ch, idx, handler_id);
2105                 continue;
2106             }
2107
2108             ch->last_poll = time_msec();
2109             if (error) {
2110                 if (error == EAGAIN) {
2111                     break;
2112                 }
2113                 return error;
2114             }
2115
2116             error = parse_odp_packet(dpif, buf, upcall, &dp_ifindex);
2117             if (!error && dp_ifindex == dpif->dp_ifindex) {
2118                 return 0;
2119             } else if (error) {
2120                 return error;
2121             }
2122         }
2123     }
2124
2125     return EAGAIN;
2126 }
2127 #endif
2128
2129 static int
2130 dpif_netlink_recv(struct dpif *dpif_, uint32_t handler_id,
2131                   struct dpif_upcall *upcall, struct ofpbuf *buf)
2132 {
2133     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2134     int error;
2135
2136     fat_rwlock_rdlock(&dpif->upcall_lock);
2137 #ifdef _WIN32
2138     error = dpif_netlink_recv_windows(dpif, handler_id, upcall, buf);
2139 #else
2140     error = dpif_netlink_recv__(dpif, handler_id, upcall, buf);
2141 #endif
2142     fat_rwlock_unlock(&dpif->upcall_lock);
2143
2144     return error;
2145 }
2146
2147 static void
2148 dpif_netlink_recv_wait__(struct dpif_netlink *dpif, uint32_t handler_id)
2149     OVS_REQ_RDLOCK(dpif->upcall_lock)
2150 {
2151 #ifdef _WIN32
2152     uint32_t i;
2153     struct dpif_windows_vport_sock *sock_pool =
2154         dpif->handlers[handler_id].vport_sock_pool;
2155
2156     /* Only one handler is supported currently. */
2157     if (handler_id >= 1) {
2158         return;
2159     }
2160
2161     for (i = 0; i < VPORT_SOCK_POOL_SIZE; i++) {
2162         nl_sock_wait(sock_pool[i].nl_sock, POLLIN);
2163     }
2164 #else
2165     if (dpif->handlers && handler_id < dpif->n_handlers) {
2166         struct dpif_handler *handler = &dpif->handlers[handler_id];
2167
2168         poll_fd_wait(handler->epoll_fd, POLLIN);
2169     }
2170 #endif
2171 }
2172
2173 static void
2174 dpif_netlink_recv_wait(struct dpif *dpif_, uint32_t handler_id)
2175 {
2176     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2177
2178     fat_rwlock_rdlock(&dpif->upcall_lock);
2179     dpif_netlink_recv_wait__(dpif, handler_id);
2180     fat_rwlock_unlock(&dpif->upcall_lock);
2181 }
2182
2183 static void
2184 dpif_netlink_recv_purge__(struct dpif_netlink *dpif)
2185     OVS_REQ_WRLOCK(dpif->upcall_lock)
2186 {
2187     if (dpif->handlers) {
2188         size_t i, j;
2189
2190         for (i = 0; i < dpif->uc_array_size; i++ ) {
2191             if (!dpif->handlers[0].channels[i].sock) {
2192                 continue;
2193             }
2194
2195             for (j = 0; j < dpif->n_handlers; j++) {
2196                 nl_sock_drain(dpif->handlers[j].channels[i].sock);
2197             }
2198         }
2199     }
2200 }
2201
2202 static void
2203 dpif_netlink_recv_purge(struct dpif *dpif_)
2204 {
2205     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2206
2207     fat_rwlock_wrlock(&dpif->upcall_lock);
2208     dpif_netlink_recv_purge__(dpif);
2209     fat_rwlock_unlock(&dpif->upcall_lock);
2210 }
2211
2212 static char *
2213 dpif_netlink_get_datapath_version(void)
2214 {
2215     char *version_str = NULL;
2216
2217 #ifdef __linux__
2218
2219 #define MAX_VERSION_STR_SIZE 80
2220 #define LINUX_DATAPATH_VERSION_FILE  "/sys/module/openvswitch/version"
2221     FILE *f;
2222
2223     f = fopen(LINUX_DATAPATH_VERSION_FILE, "r");
2224     if (f) {
2225         char *newline;
2226         char version[MAX_VERSION_STR_SIZE];
2227
2228         if (fgets(version, MAX_VERSION_STR_SIZE, f)) {
2229             newline = strchr(version, '\n');
2230             if (newline) {
2231                 *newline = '\0';
2232             }
2233             version_str = xstrdup(version);
2234         }
2235         fclose(f);
2236     }
2237 #endif
2238
2239     return version_str;
2240 }
2241
2242 const struct dpif_class dpif_netlink_class = {
2243     "system",
2244     dpif_netlink_enumerate,
2245     NULL,
2246     dpif_netlink_open,
2247     dpif_netlink_close,
2248     dpif_netlink_destroy,
2249     dpif_netlink_run,
2250     NULL,                       /* wait */
2251     dpif_netlink_get_stats,
2252     dpif_netlink_port_add,
2253     dpif_netlink_port_del,
2254     dpif_netlink_port_query_by_number,
2255     dpif_netlink_port_query_by_name,
2256     dpif_netlink_port_get_pid,
2257     dpif_netlink_port_dump_start,
2258     dpif_netlink_port_dump_next,
2259     dpif_netlink_port_dump_done,
2260     dpif_netlink_port_poll,
2261     dpif_netlink_port_poll_wait,
2262     dpif_netlink_flow_flush,
2263     dpif_netlink_flow_dump_create,
2264     dpif_netlink_flow_dump_destroy,
2265     dpif_netlink_flow_dump_thread_create,
2266     dpif_netlink_flow_dump_thread_destroy,
2267     dpif_netlink_flow_dump_next,
2268     dpif_netlink_operate,
2269     dpif_netlink_recv_set,
2270     dpif_netlink_handlers_set,
2271     NULL,                       /* poll_thread_set */
2272     dpif_netlink_queue_to_priority,
2273     dpif_netlink_recv,
2274     dpif_netlink_recv_wait,
2275     dpif_netlink_recv_purge,
2276     NULL,                       /* register_upcall_cb */
2277     NULL,                       /* enable_upcall */
2278     NULL,                       /* disable_upcall */
2279     dpif_netlink_get_datapath_version, /* get_datapath_version */
2280 };
2281
2282 static int
2283 dpif_netlink_init(void)
2284 {
2285     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2286     static int error;
2287
2288     if (ovsthread_once_start(&once)) {
2289         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
2290                                       &ovs_datapath_family);
2291         if (error) {
2292             VLOG_ERR("Generic Netlink family '%s' does not exist. "
2293                      "The Open vSwitch kernel module is probably not loaded.",
2294                      OVS_DATAPATH_FAMILY);
2295         }
2296         if (!error) {
2297             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
2298         }
2299         if (!error) {
2300             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
2301         }
2302         if (!error) {
2303             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
2304                                           &ovs_packet_family);
2305         }
2306         if (!error) {
2307             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
2308                                            &ovs_vport_mcgroup);
2309         }
2310
2311         ovsthread_once_done(&once);
2312     }
2313
2314     return error;
2315 }
2316
2317 bool
2318 dpif_netlink_is_internal_device(const char *name)
2319 {
2320     struct dpif_netlink_vport reply;
2321     struct ofpbuf *buf;
2322     int error;
2323
2324     error = dpif_netlink_vport_get(name, &reply, &buf);
2325     if (!error) {
2326         ofpbuf_delete(buf);
2327     } else if (error != ENODEV && error != ENOENT) {
2328         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
2329                      name, ovs_strerror(error));
2330     }
2331
2332     return reply.type == OVS_VPORT_TYPE_INTERNAL;
2333 }
2334 \f
2335 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2336  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
2337  * positive errno value.
2338  *
2339  * 'vport' will contain pointers into 'buf', so the caller should not free
2340  * 'buf' while 'vport' is still in use. */
2341 static int
2342 dpif_netlink_vport_from_ofpbuf(struct dpif_netlink_vport *vport,
2343                              const struct ofpbuf *buf)
2344 {
2345     static const struct nl_policy ovs_vport_policy[] = {
2346         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
2347         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
2348         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2349         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_UNSPEC },
2350         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
2351                                    .optional = true },
2352         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
2353     };
2354
2355     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
2356     struct ovs_header *ovs_header;
2357     struct nlmsghdr *nlmsg;
2358     struct genlmsghdr *genl;
2359     struct ofpbuf b;
2360
2361     dpif_netlink_vport_init(vport);
2362
2363     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2364     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2365     genl = ofpbuf_try_pull(&b, sizeof *genl);
2366     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2367     if (!nlmsg || !genl || !ovs_header
2368         || nlmsg->nlmsg_type != ovs_vport_family
2369         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
2370                             ARRAY_SIZE(ovs_vport_policy))) {
2371         return EINVAL;
2372     }
2373
2374     vport->cmd = genl->cmd;
2375     vport->dp_ifindex = ovs_header->dp_ifindex;
2376     vport->port_no = nl_attr_get_odp_port(a[OVS_VPORT_ATTR_PORT_NO]);
2377     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2378     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
2379     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2380         vport->n_upcall_pids = nl_attr_get_size(a[OVS_VPORT_ATTR_UPCALL_PID])
2381                                / (sizeof *vport->upcall_pids);
2382         vport->upcall_pids = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
2383
2384     }
2385     if (a[OVS_VPORT_ATTR_STATS]) {
2386         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
2387     }
2388     if (a[OVS_VPORT_ATTR_OPTIONS]) {
2389         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
2390         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
2391     }
2392     return 0;
2393 }
2394
2395 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2396  * followed by Netlink attributes corresponding to 'vport'. */
2397 static void
2398 dpif_netlink_vport_to_ofpbuf(const struct dpif_netlink_vport *vport,
2399                              struct ofpbuf *buf)
2400 {
2401     struct ovs_header *ovs_header;
2402
2403     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
2404                           vport->cmd, OVS_VPORT_VERSION);
2405
2406     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2407     ovs_header->dp_ifindex = vport->dp_ifindex;
2408
2409     if (vport->port_no != ODPP_NONE) {
2410         nl_msg_put_odp_port(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
2411     }
2412
2413     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
2414         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
2415     }
2416
2417     if (vport->name) {
2418         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
2419     }
2420
2421     if (vport->upcall_pids) {
2422         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_UPCALL_PID,
2423                           vport->upcall_pids,
2424                           vport->n_upcall_pids * sizeof *vport->upcall_pids);
2425     }
2426
2427     if (vport->stats) {
2428         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
2429                           vport->stats, sizeof *vport->stats);
2430     }
2431
2432     if (vport->options) {
2433         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
2434                           vport->options, vport->options_len);
2435     }
2436 }
2437
2438 /* Clears 'vport' to "empty" values. */
2439 void
2440 dpif_netlink_vport_init(struct dpif_netlink_vport *vport)
2441 {
2442     memset(vport, 0, sizeof *vport);
2443     vport->port_no = ODPP_NONE;
2444 }
2445
2446 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2447  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2448  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2449  * result of the command is expected to be an ovs_vport also, which is decoded
2450  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2451  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2452 int
2453 dpif_netlink_vport_transact(const struct dpif_netlink_vport *request,
2454                             struct dpif_netlink_vport *reply,
2455                             struct ofpbuf **bufp)
2456 {
2457     struct ofpbuf *request_buf;
2458     int error;
2459
2460     ovs_assert((reply != NULL) == (bufp != NULL));
2461
2462     error = dpif_netlink_init();
2463     if (error) {
2464         if (reply) {
2465             *bufp = NULL;
2466             dpif_netlink_vport_init(reply);
2467         }
2468         return error;
2469     }
2470
2471     request_buf = ofpbuf_new(1024);
2472     dpif_netlink_vport_to_ofpbuf(request, request_buf);
2473     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2474     ofpbuf_delete(request_buf);
2475
2476     if (reply) {
2477         if (!error) {
2478             error = dpif_netlink_vport_from_ofpbuf(reply, *bufp);
2479         }
2480         if (error) {
2481             dpif_netlink_vport_init(reply);
2482             ofpbuf_delete(*bufp);
2483             *bufp = NULL;
2484         }
2485     }
2486     return error;
2487 }
2488
2489 /* Obtains information about the kernel vport named 'name' and stores it into
2490  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
2491  * longer needed ('reply' will contain pointers into '*bufp').  */
2492 int
2493 dpif_netlink_vport_get(const char *name, struct dpif_netlink_vport *reply,
2494                        struct ofpbuf **bufp)
2495 {
2496     struct dpif_netlink_vport request;
2497
2498     dpif_netlink_vport_init(&request);
2499     request.cmd = OVS_VPORT_CMD_GET;
2500     request.name = name;
2501
2502     return dpif_netlink_vport_transact(&request, reply, bufp);
2503 }
2504
2505 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2506  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
2507  * positive errno value.
2508  *
2509  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
2510  * while 'dp' is still in use. */
2511 static int
2512 dpif_netlink_dp_from_ofpbuf(struct dpif_netlink_dp *dp, const struct ofpbuf *buf)
2513 {
2514     static const struct nl_policy ovs_datapath_policy[] = {
2515         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
2516         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
2517                                 .optional = true },
2518         [OVS_DP_ATTR_MEGAFLOW_STATS] = {
2519                         NL_POLICY_FOR(struct ovs_dp_megaflow_stats),
2520                         .optional = true },
2521     };
2522
2523     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
2524     struct ovs_header *ovs_header;
2525     struct nlmsghdr *nlmsg;
2526     struct genlmsghdr *genl;
2527     struct ofpbuf b;
2528
2529     dpif_netlink_dp_init(dp);
2530
2531     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2532     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2533     genl = ofpbuf_try_pull(&b, sizeof *genl);
2534     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2535     if (!nlmsg || !genl || !ovs_header
2536         || nlmsg->nlmsg_type != ovs_datapath_family
2537         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
2538                             ARRAY_SIZE(ovs_datapath_policy))) {
2539         return EINVAL;
2540     }
2541
2542     dp->cmd = genl->cmd;
2543     dp->dp_ifindex = ovs_header->dp_ifindex;
2544     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
2545     if (a[OVS_DP_ATTR_STATS]) {
2546         dp->stats = nl_attr_get(a[OVS_DP_ATTR_STATS]);
2547     }
2548
2549     if (a[OVS_DP_ATTR_MEGAFLOW_STATS]) {
2550         dp->megaflow_stats = nl_attr_get(a[OVS_DP_ATTR_MEGAFLOW_STATS]);
2551     }
2552
2553     return 0;
2554 }
2555
2556 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
2557 static void
2558 dpif_netlink_dp_to_ofpbuf(const struct dpif_netlink_dp *dp, struct ofpbuf *buf)
2559 {
2560     struct ovs_header *ovs_header;
2561
2562     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
2563                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
2564                           OVS_DATAPATH_VERSION);
2565
2566     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2567     ovs_header->dp_ifindex = dp->dp_ifindex;
2568
2569     if (dp->name) {
2570         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
2571     }
2572
2573     if (dp->upcall_pid) {
2574         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
2575     }
2576
2577     if (dp->user_features) {
2578         nl_msg_put_u32(buf, OVS_DP_ATTR_USER_FEATURES, dp->user_features);
2579     }
2580
2581     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
2582 }
2583
2584 /* Clears 'dp' to "empty" values. */
2585 static void
2586 dpif_netlink_dp_init(struct dpif_netlink_dp *dp)
2587 {
2588     memset(dp, 0, sizeof *dp);
2589 }
2590
2591 static void
2592 dpif_netlink_dp_dump_start(struct nl_dump *dump)
2593 {
2594     struct dpif_netlink_dp request;
2595     struct ofpbuf *buf;
2596
2597     dpif_netlink_dp_init(&request);
2598     request.cmd = OVS_DP_CMD_GET;
2599
2600     buf = ofpbuf_new(1024);
2601     dpif_netlink_dp_to_ofpbuf(&request, buf);
2602     nl_dump_start(dump, NETLINK_GENERIC, buf);
2603     ofpbuf_delete(buf);
2604 }
2605
2606 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2607  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2608  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2609  * result of the command is expected to be of the same form, which is decoded
2610  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
2611  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
2612 static int
2613 dpif_netlink_dp_transact(const struct dpif_netlink_dp *request,
2614                          struct dpif_netlink_dp *reply, struct ofpbuf **bufp)
2615 {
2616     struct ofpbuf *request_buf;
2617     int error;
2618
2619     ovs_assert((reply != NULL) == (bufp != NULL));
2620
2621     request_buf = ofpbuf_new(1024);
2622     dpif_netlink_dp_to_ofpbuf(request, request_buf);
2623     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2624     ofpbuf_delete(request_buf);
2625
2626     if (reply) {
2627         dpif_netlink_dp_init(reply);
2628         if (!error) {
2629             error = dpif_netlink_dp_from_ofpbuf(reply, *bufp);
2630         }
2631         if (error) {
2632             ofpbuf_delete(*bufp);
2633             *bufp = NULL;
2634         }
2635     }
2636     return error;
2637 }
2638
2639 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
2640  * The caller must free '*bufp' when the reply is no longer needed ('reply'
2641  * will contain pointers into '*bufp').  */
2642 static int
2643 dpif_netlink_dp_get(const struct dpif *dpif_, struct dpif_netlink_dp *reply,
2644                     struct ofpbuf **bufp)
2645 {
2646     struct dpif_netlink *dpif = dpif_netlink_cast(dpif_);
2647     struct dpif_netlink_dp request;
2648
2649     dpif_netlink_dp_init(&request);
2650     request.cmd = OVS_DP_CMD_GET;
2651     request.dp_ifindex = dpif->dp_ifindex;
2652
2653     return dpif_netlink_dp_transact(&request, reply, bufp);
2654 }
2655
2656 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
2657  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
2658  * positive errno value.
2659  *
2660  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
2661  * while 'flow' is still in use. */
2662 static int
2663 dpif_netlink_flow_from_ofpbuf(struct dpif_netlink_flow *flow,
2664                               const struct ofpbuf *buf)
2665 {
2666     static const struct nl_policy ovs_flow_policy[__OVS_FLOW_ATTR_MAX] = {
2667         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED, .optional = true },
2668         [OVS_FLOW_ATTR_MASK] = { .type = NL_A_NESTED, .optional = true },
2669         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
2670         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
2671                                   .optional = true },
2672         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
2673         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
2674         [OVS_FLOW_ATTR_UFID] = { .type = NL_A_UNSPEC, .optional = true,
2675                                  .min_len = sizeof(ovs_u128) },
2676         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
2677         /* The kernel never uses OVS_FLOW_ATTR_PROBE. */
2678         /* The kernel never uses OVS_FLOW_ATTR_UFID_FLAGS. */
2679     };
2680
2681     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
2682     struct ovs_header *ovs_header;
2683     struct nlmsghdr *nlmsg;
2684     struct genlmsghdr *genl;
2685     struct ofpbuf b;
2686
2687     dpif_netlink_flow_init(flow);
2688
2689     ofpbuf_use_const(&b, ofpbuf_data(buf), ofpbuf_size(buf));
2690     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
2691     genl = ofpbuf_try_pull(&b, sizeof *genl);
2692     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
2693     if (!nlmsg || !genl || !ovs_header
2694         || nlmsg->nlmsg_type != ovs_flow_family
2695         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
2696                             ARRAY_SIZE(ovs_flow_policy))) {
2697         return EINVAL;
2698     }
2699     if (!a[OVS_FLOW_ATTR_KEY] && !a[OVS_FLOW_ATTR_UFID]) {
2700         return EINVAL;
2701     }
2702
2703     flow->nlmsg_flags = nlmsg->nlmsg_flags;
2704     flow->dp_ifindex = ovs_header->dp_ifindex;
2705     if (a[OVS_FLOW_ATTR_KEY]) {
2706         flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
2707         flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
2708     }
2709
2710     if (a[OVS_FLOW_ATTR_UFID]) {
2711         const ovs_u128 *ufid;
2712
2713         ufid = nl_attr_get_unspec(a[OVS_FLOW_ATTR_UFID],
2714                                   nl_attr_get_size(a[OVS_FLOW_ATTR_UFID]));
2715         flow->ufid = *ufid;
2716         flow->ufid_present = true;
2717     }
2718     if (a[OVS_FLOW_ATTR_MASK]) {
2719         flow->mask = nl_attr_get(a[OVS_FLOW_ATTR_MASK]);
2720         flow->mask_len = nl_attr_get_size(a[OVS_FLOW_ATTR_MASK]);
2721     }
2722     if (a[OVS_FLOW_ATTR_ACTIONS]) {
2723         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
2724         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
2725     }
2726     if (a[OVS_FLOW_ATTR_STATS]) {
2727         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
2728     }
2729     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
2730         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
2731     }
2732     if (a[OVS_FLOW_ATTR_USED]) {
2733         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
2734     }
2735     return 0;
2736 }
2737
2738 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
2739  * followed by Netlink attributes corresponding to 'flow'. */
2740 static void
2741 dpif_netlink_flow_to_ofpbuf(const struct dpif_netlink_flow *flow,
2742                             struct ofpbuf *buf)
2743 {
2744     struct ovs_header *ovs_header;
2745
2746     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
2747                           NLM_F_REQUEST | flow->nlmsg_flags,
2748                           flow->cmd, OVS_FLOW_VERSION);
2749
2750     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
2751     ovs_header->dp_ifindex = flow->dp_ifindex;
2752
2753     if (flow->ufid_present) {
2754         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_UFID, &flow->ufid,
2755                           sizeof flow->ufid);
2756     }
2757     if (flow->ufid_terse) {
2758         nl_msg_put_u32(buf, OVS_FLOW_ATTR_UFID_FLAGS,
2759                        OVS_UFID_F_OMIT_KEY | OVS_UFID_F_OMIT_MASK
2760                        | OVS_UFID_F_OMIT_ACTIONS);
2761     }
2762     if (!flow->ufid_terse || !flow->ufid_present) {
2763         if (flow->key_len) {
2764             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY,
2765                               flow->key, flow->key_len);
2766         }
2767
2768         if (flow->mask_len) {
2769             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_MASK,
2770                               flow->mask, flow->mask_len);
2771         }
2772         if (flow->actions || flow->actions_len) {
2773             nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
2774                               flow->actions, flow->actions_len);
2775         }
2776     }
2777
2778     /* We never need to send these to the kernel. */
2779     ovs_assert(!flow->stats);
2780     ovs_assert(!flow->tcp_flags);
2781     ovs_assert(!flow->used);
2782
2783     if (flow->clear) {
2784         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
2785     }
2786     if (flow->probe) {
2787         nl_msg_put_flag(buf, OVS_FLOW_ATTR_PROBE);
2788     }
2789 }
2790
2791 /* Clears 'flow' to "empty" values. */
2792 static void
2793 dpif_netlink_flow_init(struct dpif_netlink_flow *flow)
2794 {
2795     memset(flow, 0, sizeof *flow);
2796 }
2797
2798 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
2799  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
2800  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
2801  * result of the command is expected to be a flow also, which is decoded and
2802  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
2803  * is no longer needed ('reply' will contain pointers into '*bufp'). */
2804 static int
2805 dpif_netlink_flow_transact(struct dpif_netlink_flow *request,
2806                            struct dpif_netlink_flow *reply,
2807                            struct ofpbuf **bufp)
2808 {
2809     struct ofpbuf *request_buf;
2810     int error;
2811
2812     ovs_assert((reply != NULL) == (bufp != NULL));
2813
2814     if (reply) {
2815         request->nlmsg_flags |= NLM_F_ECHO;
2816     }
2817
2818     request_buf = ofpbuf_new(1024);
2819     dpif_netlink_flow_to_ofpbuf(request, request_buf);
2820     error = nl_transact(NETLINK_GENERIC, request_buf, bufp);
2821     ofpbuf_delete(request_buf);
2822
2823     if (reply) {
2824         if (!error) {
2825             error = dpif_netlink_flow_from_ofpbuf(reply, *bufp);
2826         }
2827         if (error) {
2828             dpif_netlink_flow_init(reply);
2829             ofpbuf_delete(*bufp);
2830             *bufp = NULL;
2831         }
2832     }
2833     return error;
2834 }
2835
2836 static void
2837 dpif_netlink_flow_get_stats(const struct dpif_netlink_flow *flow,
2838                             struct dpif_flow_stats *stats)
2839 {
2840     if (flow->stats) {
2841         stats->n_packets = get_32aligned_u64(&flow->stats->n_packets);
2842         stats->n_bytes = get_32aligned_u64(&flow->stats->n_bytes);
2843     } else {
2844         stats->n_packets = 0;
2845         stats->n_bytes = 0;
2846     }
2847     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
2848     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
2849 }
2850 \f
2851 /* Logs information about a packet that was recently lost in 'ch' (in
2852  * 'dpif_'). */
2853 static void
2854 report_loss(struct dpif_netlink *dpif, struct dpif_channel *ch, uint32_t ch_idx,
2855             uint32_t handler_id)
2856 {
2857     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2858     struct ds s;
2859
2860     if (VLOG_DROP_WARN(&rl)) {
2861         return;
2862     }
2863
2864     ds_init(&s);
2865     if (ch->last_poll != LLONG_MIN) {
2866         ds_put_format(&s, " (last polled %lld ms ago)",
2867                       time_msec() - ch->last_poll);
2868     }
2869
2870     VLOG_WARN("%s: lost packet on port channel %u of handler %u",
2871               dpif_name(&dpif->dpif), ch_idx, handler_id);
2872     ds_destroy(&s);
2873 }