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