netlink-socket: User mode event read for Windows.
[cascardo/ovs.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "netlink-socket.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include <sys/uio.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "hash.h"
28 #include "hmap.h"
29 #include "netlink.h"
30 #include "netlink-protocol.h"
31 #include "odp-netlink.h"
32 #include "ofpbuf.h"
33 #include "ovs-thread.h"
34 #include "poll-loop.h"
35 #include "seq.h"
36 #include "socket-util.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(netlink_socket);
41
42 COVERAGE_DEFINE(netlink_overflow);
43 COVERAGE_DEFINE(netlink_received);
44 COVERAGE_DEFINE(netlink_recv_jumbo);
45 COVERAGE_DEFINE(netlink_sent);
46
47 /* Linux header file confusion causes this to be undefined. */
48 #ifndef SOL_NETLINK
49 #define SOL_NETLINK 270
50 #endif
51
52 #ifdef _WIN32
53 static struct ovs_mutex portid_mutex = OVS_MUTEX_INITIALIZER;
54 static uint32_t g_last_portid = 0;
55
56 /* Port IDs must be unique! */
57 static uint32_t
58 portid_next(void)
59     OVS_GUARDED_BY(portid_mutex)
60 {
61     g_last_portid++;
62     return g_last_portid;
63 }
64 #endif /* _WIN32 */
65
66 /* A single (bad) Netlink message can in theory dump out many, many log
67  * messages, so the burst size is set quite high here to avoid missing useful
68  * information.  Also, at high logging levels we log *all* Netlink messages. */
69 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
70
71 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
72 static void log_nlmsg(const char *function, int error,
73                       const void *message, size_t size, int protocol);
74 #ifdef _WIN32
75 static int get_sock_pid_from_kernel(struct nl_sock *sock);
76 #endif
77 \f
78 /* Netlink sockets. */
79
80 struct nl_sock {
81 #ifdef _WIN32
82     HANDLE handle;
83     OVERLAPPED overlapped;
84     DWORD read_ioctl;
85 #else
86     int fd;
87 #endif
88     uint32_t next_seq;
89     uint32_t pid;
90     int protocol;
91     unsigned int rcvbuf;        /* Receive buffer size (SO_RCVBUF). */
92 };
93
94 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
95  * of iovecs on the stack. */
96 #define MAX_IOVS 128
97
98 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
99  * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
100  *
101  * Initialized by nl_sock_create(). */
102 static int max_iovs;
103
104 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
105 static void nl_pool_release(struct nl_sock *);
106
107 /* Creates a new netlink socket for the given netlink 'protocol'
108  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
109  * new socket if successful, otherwise returns a positive errno value. */
110 int
111 nl_sock_create(int protocol, struct nl_sock **sockp)
112 {
113     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
114     struct nl_sock *sock;
115 #ifndef _WIN32
116     struct sockaddr_nl local, remote;
117 #endif
118     socklen_t local_size;
119     int rcvbuf;
120     int retval = 0;
121
122     if (ovsthread_once_start(&once)) {
123         int save_errno = errno;
124         errno = 0;
125
126         max_iovs = sysconf(_SC_UIO_MAXIOV);
127         if (max_iovs < _XOPEN_IOV_MAX) {
128             if (max_iovs == -1 && errno) {
129                 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
130             }
131             max_iovs = _XOPEN_IOV_MAX;
132         } else if (max_iovs > MAX_IOVS) {
133             max_iovs = MAX_IOVS;
134         }
135
136         errno = save_errno;
137         ovsthread_once_done(&once);
138     }
139
140     *sockp = NULL;
141     sock = xmalloc(sizeof *sock);
142
143 #ifdef _WIN32
144     sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
145                               GENERIC_READ | GENERIC_WRITE,
146                               FILE_SHARE_READ | FILE_SHARE_WRITE,
147                               NULL, OPEN_EXISTING,
148                               FILE_FLAG_OVERLAPPED, NULL);
149
150     if (sock->handle == INVALID_HANDLE_VALUE) {
151         VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
152         goto error;
153     }
154
155     memset(&sock->overlapped, 0, sizeof sock->overlapped);
156     sock->overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
157     if (sock->overlapped.hEvent == NULL) {
158         VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
159         goto error;
160     }
161     /* Initialize the type/ioctl to Generic */
162     sock->read_ioctl = OVS_IOCTL_READ;
163 #else
164     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
165     if (sock->fd < 0) {
166         VLOG_ERR("fcntl: %s", ovs_strerror(errno));
167         goto error;
168     }
169 #endif
170
171     sock->protocol = protocol;
172     sock->next_seq = 1;
173
174     rcvbuf = 1024 * 1024;
175 #ifdef _WIN32
176     sock->rcvbuf = rcvbuf;
177     retval = get_sock_pid_from_kernel(sock);
178     if (retval != 0) {
179         goto error;
180     }
181 #else
182     if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
183                    &rcvbuf, sizeof rcvbuf)) {
184         /* Only root can use SO_RCVBUFFORCE.  Everyone else gets EPERM.
185          * Warn only if the failure is therefore unexpected. */
186         if (errno != EPERM) {
187             VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
188                          "(%s)", rcvbuf, ovs_strerror(errno));
189         }
190     }
191
192     retval = get_socket_rcvbuf(sock->fd);
193     if (retval < 0) {
194         retval = -retval;
195         goto error;
196     }
197     sock->rcvbuf = retval;
198
199     /* Connect to kernel (pid 0) as remote address. */
200     memset(&remote, 0, sizeof remote);
201     remote.nl_family = AF_NETLINK;
202     remote.nl_pid = 0;
203     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
204         VLOG_ERR("connect(0): %s", ovs_strerror(errno));
205         goto error;
206     }
207
208     /* Obtain pid assigned by kernel. */
209     local_size = sizeof local;
210     if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
211         VLOG_ERR("getsockname: %s", ovs_strerror(errno));
212         goto error;
213     }
214     if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
215         VLOG_ERR("getsockname returned bad Netlink name");
216         retval = EINVAL;
217         goto error;
218     }
219     sock->pid = local.nl_pid;
220 #endif
221
222     *sockp = sock;
223     return 0;
224
225 error:
226     if (retval == 0) {
227         retval = errno;
228         if (retval == 0) {
229             retval = EINVAL;
230         }
231     }
232 #ifdef _WIN32
233     if (sock->overlapped.hEvent) {
234         CloseHandle(sock->overlapped.hEvent);
235     }
236     if (sock->handle != INVALID_HANDLE_VALUE) {
237         CloseHandle(sock->handle);
238     }
239 #else
240     if (sock->fd >= 0) {
241         close(sock->fd);
242     }
243 #endif
244     free(sock);
245     return retval;
246 }
247
248 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
249  * sets '*sockp' to the new socket if successful, otherwise returns a positive
250  * errno value.  */
251 int
252 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
253 {
254     return nl_sock_create(src->protocol, sockp);
255 }
256
257 /* Destroys netlink socket 'sock'. */
258 void
259 nl_sock_destroy(struct nl_sock *sock)
260 {
261     if (sock) {
262 #ifdef _WIN32
263         if (sock->overlapped.hEvent) {
264             CloseHandle(sock->overlapped.hEvent);
265         }
266         CloseHandle(sock->handle);
267 #else
268         close(sock->fd);
269 #endif
270         free(sock);
271     }
272 }
273
274 #ifdef _WIN32
275 /* Reads the pid for 'sock' generated in the kernel datapath. The function
276  * follows a transaction semantic. Eventually this function should call into
277  * nl_transact. */
278 static int
279 get_sock_pid_from_kernel(struct nl_sock *sock)
280 {
281     struct nl_transaction txn;
282     struct ofpbuf request;
283     uint64_t request_stub[128];
284     struct ofpbuf reply;
285     uint64_t reply_stub[128];
286     struct ovs_header *ovs_header;
287     struct nlmsghdr *nlmsg;
288     uint32_t seq;
289     int retval;
290     DWORD bytes;
291     int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
292                        sizeof (struct ovs_header);
293
294     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
295     txn.request = &request;
296     ofpbuf_use_stub(&reply, reply_stub, sizeof reply_stub);
297     txn.reply = &reply;
298
299     seq = nl_sock_allocate_seq(sock, 1);
300     nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
301                           OVS_CTRL_CMD_WIN_GET_PID, OVS_WIN_CONTROL_VERSION);
302     nlmsg = nl_msg_nlmsghdr(txn.request);
303     nlmsg->nlmsg_seq = seq;
304
305     ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
306     ovs_header->dp_ifindex = 0;
307     ovs_header = ofpbuf_put_uninit(&reply, ovs_msg_size);
308
309     if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
310                          ofpbuf_data(txn.request), ofpbuf_size(txn.request),
311                          ofpbuf_data(txn.reply), ofpbuf_size(txn.reply),
312                          &bytes, NULL)) {
313         retval = EINVAL;
314         goto done;
315     } else {
316         if (bytes < ovs_msg_size) {
317             retval = EINVAL;
318             goto done;
319         }
320
321         nlmsg = nl_msg_nlmsghdr(txn.reply);
322         if (nlmsg->nlmsg_seq != seq) {
323             retval = EINVAL;
324             goto done;
325         }
326         sock->pid = nlmsg->nlmsg_pid;
327     }
328     retval = 0;
329
330 done:
331     ofpbuf_uninit(&request);
332     ofpbuf_uninit(&reply);
333     return retval;
334 }
335 #endif  /* _WIN32 */
336
337 #ifdef _WIN32
338 static int __inline
339 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
340 {
341     struct ofpbuf request;
342     uint64_t request_stub[128];
343     struct ovs_header *ovs_header;
344     struct nlmsghdr *nlmsg;
345     int error;
346
347     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
348
349     nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
350                           OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
351                           OVS_WIN_CONTROL_VERSION);
352
353     ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
354     ovs_header->dp_ifindex = 0;
355
356     nl_msg_put_u32(&request, OVS_NL_ATTR_MCAST_GRP, multicast_group);
357     nl_msg_put_u8(&request, OVS_NL_ATTR_MCAST_JOIN, join ? 1 : 0);
358
359     error = nl_sock_send(sock, &request, true);
360     ofpbuf_uninit(&request);
361     return error;
362 }
363 #endif
364 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
365  * successful, otherwise a positive errno value.
366  *
367  * A socket that is subscribed to a multicast group that receives asynchronous
368  * notifications must not be used for Netlink transactions or dumps, because
369  * transactions and dumps can cause notifications to be lost.
370  *
371  * Multicast group numbers are always positive.
372  *
373  * It is not an error to attempt to join a multicast group to which a socket
374  * already belongs. */
375 int
376 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
377 {
378 #ifdef _WIN32
379     /* Set the socket type as a "multicast" socket */
380     sock->read_ioctl = OVS_IOCTL_READ_EVENT;
381     int error = nl_sock_mcgroup(sock, multicast_group, true);
382     if (error) {
383         sock->read_ioctl = OVS_IOCTL_READ;
384         VLOG_WARN("could not join multicast group %u (%s)",
385                   multicast_group, ovs_strerror(errno));
386         return errno;
387     }
388 #else
389     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
390                    &multicast_group, sizeof multicast_group) < 0) {
391         VLOG_WARN("could not join multicast group %u (%s)",
392                   multicast_group, ovs_strerror(errno));
393         return errno;
394     }
395 #endif
396     return 0;
397 }
398
399 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
400  * successful, otherwise a positive errno value.
401  *
402  * Multicast group numbers are always positive.
403  *
404  * It is not an error to attempt to leave a multicast group to which a socket
405  * does not belong.
406  *
407  * On success, reading from 'sock' will still return any messages that were
408  * received on 'multicast_group' before the group was left. */
409 int
410 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
411 {
412 #ifdef _WIN32
413     int error = nl_sock_mcgroup(sock, multicast_group, false);
414     if (error) {
415         VLOG_WARN("could not leave multicast group %u (%s)",
416                    multicast_group, ovs_strerror(errno));
417         return errno;
418     }
419     sock->read_ioctl = OVS_IOCTL_READ;
420 #else
421     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
422                    &multicast_group, sizeof multicast_group) < 0) {
423         VLOG_WARN("could not leave multicast group %u (%s)",
424                   multicast_group, ovs_strerror(errno));
425         return errno;
426     }
427 #endif
428     return 0;
429 }
430
431 static int
432 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
433                uint32_t nlmsg_seq, bool wait)
434 {
435     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
436     int error;
437
438     nlmsg->nlmsg_len = ofpbuf_size(msg);
439     nlmsg->nlmsg_seq = nlmsg_seq;
440     nlmsg->nlmsg_pid = sock->pid;
441     do {
442         int retval;
443 #ifdef _WIN32
444         DWORD bytes;
445
446         if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
447                              ofpbuf_data(msg), ofpbuf_size(msg), NULL, 0,
448                              &bytes, NULL)) {
449             retval = -1;
450             /* XXX: Map to a more appropriate error based on GetLastError(). */
451             errno = EINVAL;
452         } else {
453             retval = ofpbuf_size(msg);
454         }
455 #else
456         retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg),
457                       wait ? 0 : MSG_DONTWAIT);
458 #endif
459         error = retval < 0 ? errno : 0;
460     } while (error == EINTR);
461     log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
462     if (!error) {
463         COVERAGE_INC(netlink_sent);
464     }
465     return error;
466 }
467
468 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
469  * 'sock'.  nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
470  * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
471  * sequence number, before the message is sent.
472  *
473  * Returns 0 if successful, otherwise a positive errno value.  If
474  * 'wait' is true, then the send will wait until buffer space is ready;
475  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
476 int
477 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
478 {
479     return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
480 }
481
482 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
483  * 'sock'.  nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
484  * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
485  * 'nlmsg_seq', before the message is sent.
486  *
487  * Returns 0 if successful, otherwise a positive errno value.  If
488  * 'wait' is true, then the send will wait until buffer space is ready;
489  * otherwise, returns EAGAIN if the 'sock' send buffer is full.
490  *
491  * This function is suitable for sending a reply to a request that was received
492  * with sequence number 'nlmsg_seq'.  Otherwise, use nl_sock_send() instead. */
493 int
494 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
495                  uint32_t nlmsg_seq, bool wait)
496 {
497     return nl_sock_send__(sock, msg, nlmsg_seq, wait);
498 }
499
500 static int
501 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
502 {
503     /* We can't accurately predict the size of the data to be received.  The
504      * caller is supposed to have allocated enough space in 'buf' to handle the
505      * "typical" case.  To handle exceptions, we make available enough space in
506      * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
507      * figure since that's the maximum length of a Netlink attribute). */
508     struct nlmsghdr *nlmsghdr;
509     uint8_t tail[65536];
510     struct iovec iov[2];
511     struct msghdr msg;
512     ssize_t retval;
513     int error;
514
515     ovs_assert(buf->allocated >= sizeof *nlmsghdr);
516     ofpbuf_clear(buf);
517
518     iov[0].iov_base = ofpbuf_base(buf);
519     iov[0].iov_len = buf->allocated;
520     iov[1].iov_base = tail;
521     iov[1].iov_len = sizeof tail;
522
523     memset(&msg, 0, sizeof msg);
524     msg.msg_iov = iov;
525     msg.msg_iovlen = 2;
526
527     /* Receive a Netlink message from the kernel.
528      *
529      * This works around a kernel bug in which the kernel returns an error code
530      * as if it were the number of bytes read.  It doesn't actually modify
531      * anything in the receive buffer in that case, so we can initialize the
532      * Netlink header with an impossible message length and then, upon success,
533      * check whether it changed. */
534     nlmsghdr = ofpbuf_base(buf);
535     do {
536         nlmsghdr->nlmsg_len = UINT32_MAX;
537 #ifdef _WIN32
538         DWORD bytes;
539         if (!DeviceIoControl(sock->handle, sock->read_ioctl,
540                              NULL, 0, tail, sizeof tail, &bytes, NULL)) {
541             retval = -1;
542             errno = EINVAL;
543         } else {
544             retval = bytes;
545             if (retval == 0) {
546                 retval = -1;
547                 errno = EAGAIN;
548             } else {
549                 if (retval >= buf->allocated) {
550                     ofpbuf_reinit(buf, retval);
551                 }
552                 memcpy(ofpbuf_data(buf), tail, retval);
553                 ofpbuf_set_size(buf, retval);
554             }
555         }
556 #else
557         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
558 #endif
559         error = (retval < 0 ? errno
560                  : retval == 0 ? ECONNRESET /* not possible? */
561                  : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
562                  : retval);
563     } while (error == EINTR);
564     if (error) {
565         if (error == ENOBUFS) {
566             /* Socket receive buffer overflow dropped one or more messages that
567              * the kernel tried to send to us. */
568             COVERAGE_INC(netlink_overflow);
569         }
570         return error;
571     }
572
573     if (msg.msg_flags & MSG_TRUNC) {
574         VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
575                     sizeof tail);
576         return E2BIG;
577     }
578
579     if (retval < sizeof *nlmsghdr
580         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
581         || nlmsghdr->nlmsg_len > retval) {
582         VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
583                     retval, sizeof *nlmsghdr);
584         return EPROTO;
585     }
586 #ifndef _WIN32
587     ofpbuf_set_size(buf, MIN(retval, buf->allocated));
588     if (retval > buf->allocated) {
589         COVERAGE_INC(netlink_recv_jumbo);
590         ofpbuf_put(buf, tail, retval - buf->allocated);
591     }
592 #endif
593
594     log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
595     COVERAGE_INC(netlink_received);
596
597     return 0;
598 }
599
600 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'.  If
601  * 'wait' is true, waits for a message to be ready.  Otherwise, fails with
602  * EAGAIN if the 'sock' receive buffer is empty.
603  *
604  * The caller must have initialized 'buf' with an allocation of at least
605  * NLMSG_HDRLEN bytes.  For best performance, the caller should allocate enough
606  * space for a "typical" message.
607  *
608  * On success, returns 0 and replaces 'buf''s previous content by the received
609  * message.  This function expands 'buf''s allocated memory, as necessary, to
610  * hold the actual size of the received message.
611  *
612  * On failure, returns a positive errno value and clears 'buf' to zero length.
613  * 'buf' retains its previous memory allocation.
614  *
615  * Regardless of success or failure, this function resets 'buf''s headroom to
616  * 0. */
617 int
618 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
619 {
620     return nl_sock_recv__(sock, buf, wait);
621 }
622
623 static void
624 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
625                         int error)
626 {
627     size_t i;
628
629     for (i = 0; i < n; i++) {
630         struct nl_transaction *txn = transactions[i];
631
632         txn->error = error;
633         if (txn->reply) {
634             ofpbuf_clear(txn->reply);
635         }
636     }
637 }
638
639 static int
640 nl_sock_transact_multiple__(struct nl_sock *sock,
641                             struct nl_transaction **transactions, size_t n,
642                             size_t *done)
643 {
644     uint64_t tmp_reply_stub[1024 / 8];
645     struct nl_transaction tmp_txn;
646     struct ofpbuf tmp_reply;
647
648     uint32_t base_seq;
649     struct iovec iovs[MAX_IOVS];
650     struct msghdr msg;
651     int error;
652     int i;
653
654     base_seq = nl_sock_allocate_seq(sock, n);
655     *done = 0;
656     for (i = 0; i < n; i++) {
657         struct nl_transaction *txn = transactions[i];
658         struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
659
660         nlmsg->nlmsg_len = ofpbuf_size(txn->request);
661         nlmsg->nlmsg_seq = base_seq + i;
662         nlmsg->nlmsg_pid = sock->pid;
663
664         iovs[i].iov_base = ofpbuf_data(txn->request);
665         iovs[i].iov_len = ofpbuf_size(txn->request);
666     }
667
668 #ifndef _WIN32
669     memset(&msg, 0, sizeof msg);
670     msg.msg_iov = iovs;
671     msg.msg_iovlen = n;
672     do {
673         error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
674     } while (error == EINTR);
675
676     for (i = 0; i < n; i++) {
677         struct nl_transaction *txn = transactions[i];
678
679         log_nlmsg(__func__, error, ofpbuf_data(txn->request),
680                   ofpbuf_size(txn->request), sock->protocol);
681     }
682     if (!error) {
683         COVERAGE_ADD(netlink_sent, n);
684     }
685
686     if (error) {
687         return error;
688     }
689
690     ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
691     tmp_txn.request = NULL;
692     tmp_txn.reply = &tmp_reply;
693     tmp_txn.error = 0;
694     while (n > 0) {
695         struct nl_transaction *buf_txn, *txn;
696         uint32_t seq;
697
698         /* Find a transaction whose buffer we can use for receiving a reply.
699          * If no such transaction is left, use tmp_txn. */
700         buf_txn = &tmp_txn;
701         for (i = 0; i < n; i++) {
702             if (transactions[i]->reply) {
703                 buf_txn = transactions[i];
704                 break;
705             }
706         }
707
708         /* Receive a reply. */
709         error = nl_sock_recv__(sock, buf_txn->reply, false);
710         if (error) {
711             if (error == EAGAIN) {
712                 nl_sock_record_errors__(transactions, n, 0);
713                 *done += n;
714                 error = 0;
715             }
716             break;
717         }
718
719         /* Match the reply up with a transaction. */
720         seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
721         if (seq < base_seq || seq >= base_seq + n) {
722             VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
723             continue;
724         }
725         i = seq - base_seq;
726         txn = transactions[i];
727
728         /* Fill in the results for 'txn'. */
729         if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
730             if (txn->reply) {
731                 ofpbuf_clear(txn->reply);
732             }
733             if (txn->error) {
734                 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
735                             error, ovs_strerror(txn->error));
736             }
737         } else {
738             txn->error = 0;
739             if (txn->reply && txn != buf_txn) {
740                 /* Swap buffers. */
741                 struct ofpbuf *reply = buf_txn->reply;
742                 buf_txn->reply = txn->reply;
743                 txn->reply = reply;
744             }
745         }
746
747         /* Fill in the results for transactions before 'txn'.  (We have to do
748          * this after the results for 'txn' itself because of the buffer swap
749          * above.) */
750         nl_sock_record_errors__(transactions, i, 0);
751
752         /* Advance. */
753         *done += i + 1;
754         transactions += i + 1;
755         n -= i + 1;
756         base_seq += i + 1;
757     }
758     ofpbuf_uninit(&tmp_reply);
759 #else
760     error = 0;
761     for (i = 0; i < n; i++) {
762         DWORD reply_len;
763         uint8_t tail[65536];
764         struct nl_transaction *txn = transactions[i];
765         struct nlmsghdr *request_nlmsg, *reply_nlmsg;
766
767         if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
768                              ofpbuf_data(txn->request),
769                              ofpbuf_size(txn->request),
770                              txn->reply ? tail : 0,
771                              txn->reply ? sizeof tail : 0,
772                              &reply_len, NULL)) {
773             /* XXX: Map to a more appropriate error. */
774             error = EINVAL;
775             break;
776         }
777
778         if (txn->reply) {
779             if (reply_len < sizeof *reply_nlmsg) {
780                 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32,
781                             reply_len);
782                 break;
783             }
784
785             /* Validate the sequence number in the reply. */
786             request_nlmsg = nl_msg_nlmsghdr(txn->request);
787             reply_nlmsg = (struct nlmsghdr *)tail;
788
789             if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
790                 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
791                 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
792                     ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
793                     reply_nlmsg->nlmsg_seq);
794                 break;
795             }
796
797             /* If reply was expected, verify if there was indeed a reply
798              * received. */
799             if (reply_len == 0) {
800                 nl_sock_record_errors__(transactions, n, 0);
801                 VLOG_DBG_RL(&rl, "reply not seen when expected seq %#"PRIx32,
802                             request_nlmsg->nlmsg_seq);
803                 break;
804             }
805
806             /* Copy the reply to the buffer specified by the caller. */
807             if (reply_len > txn->reply->allocated) {
808                 ofpbuf_reinit(txn->reply, reply_len);
809             }
810             memcpy(ofpbuf_data(txn->reply), tail, reply_len);
811             ofpbuf_set_size(txn->reply, reply_len);
812
813             /* Handle errors embedded within the netlink message. */
814             if (nl_msg_nlmsgerr(txn->reply, &txn->error)) {
815                 if (txn->reply) {
816                     ofpbuf_clear(txn->reply);
817                 }
818                 if (txn->error) {
819                     VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
820                                 error, ovs_strerror(txn->error));
821                 }
822             } else {
823                 txn->error = 0;
824             }
825         }
826
827         /* Count the number of successful transactions. */
828         (*done)++;
829     }
830
831     if (!error) {
832         COVERAGE_ADD(netlink_sent, n);
833     }
834 #endif
835
836     return error;
837 }
838
839 static void
840 nl_sock_transact_multiple(struct nl_sock *sock,
841                           struct nl_transaction **transactions, size_t n)
842 {
843     int max_batch_count;
844     int error;
845
846     if (!n) {
847         return;
848     }
849
850     /* In theory, every request could have a 64 kB reply.  But the default and
851      * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
852      * be a bit below 128 kB, so that would only allow a single message in a
853      * "batch".  So we assume that replies average (at most) 4 kB, which allows
854      * a good deal of batching.
855      *
856      * In practice, most of the requests that we batch either have no reply at
857      * all or a brief reply. */
858     max_batch_count = MAX(sock->rcvbuf / 4096, 1);
859     max_batch_count = MIN(max_batch_count, max_iovs);
860
861     while (n > 0) {
862         size_t count, bytes;
863         size_t done;
864
865         /* Batch up to 'max_batch_count' transactions.  But cap it at about a
866          * page of requests total because big skbuffs are expensive to
867          * allocate in the kernel.  */
868 #if defined(PAGESIZE)
869         enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
870 #else
871         enum { MAX_BATCH_BYTES = 4096 - 512 };
872 #endif
873         bytes = ofpbuf_size(transactions[0]->request);
874         for (count = 1; count < n && count < max_batch_count; count++) {
875             if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
876                 break;
877             }
878             bytes += ofpbuf_size(transactions[count]->request);
879         }
880
881         error = nl_sock_transact_multiple__(sock, transactions, count, &done);
882         transactions += done;
883         n -= done;
884
885         if (error == ENOBUFS) {
886             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
887         } else if (error) {
888             VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
889             nl_sock_record_errors__(transactions, n, error);
890         }
891     }
892 }
893
894 static int
895 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
896                  struct ofpbuf **replyp)
897 {
898     struct nl_transaction *transactionp;
899     struct nl_transaction transaction;
900
901     transaction.request = CONST_CAST(struct ofpbuf *, request);
902     transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
903     transactionp = &transaction;
904
905     nl_sock_transact_multiple(sock, &transactionp, 1);
906
907     if (replyp) {
908         if (transaction.error) {
909             ofpbuf_delete(transaction.reply);
910             *replyp = NULL;
911         } else {
912             *replyp = transaction.reply;
913         }
914     }
915
916     return transaction.error;
917 }
918
919 /* Drain all the messages currently in 'sock''s receive queue. */
920 int
921 nl_sock_drain(struct nl_sock *sock)
922 {
923 #ifdef _WIN32
924     return 0;
925 #else
926     return drain_rcvbuf(sock->fd);
927 #endif
928 }
929
930 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
931  * Netlink socket created with the given 'protocol', and initializes 'dump' to
932  * reflect the state of the operation.
933  *
934  * 'request' must contain a Netlink message.  Before sending the message,
935  * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
936  * set to the Netlink socket's pid.  NLM_F_DUMP and NLM_F_ACK will be set in
937  * nlmsg_flags.
938  *
939  * The design of this Netlink socket library ensures that the dump is reliable.
940  *
941  * This function provides no status indication.  nl_dump_done() provides an
942  * error status for the entire dump operation.
943  *
944  * The caller must eventually destroy 'request'.
945  */
946 void
947 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
948 {
949     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
950
951     ovs_mutex_init(&dump->mutex);
952     ovs_mutex_lock(&dump->mutex);
953     dump->status = nl_pool_alloc(protocol, &dump->sock);
954     if (!dump->status) {
955         dump->status = nl_sock_send__(dump->sock, request,
956                                       nl_sock_allocate_seq(dump->sock, 1),
957                                       true);
958     }
959     dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
960     ovs_mutex_unlock(&dump->mutex);
961 }
962
963 static int
964 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
965     OVS_REQUIRES(dump->mutex)
966 {
967     struct nlmsghdr *nlmsghdr;
968     int error;
969
970     while (!ofpbuf_size(buffer)) {
971         error = nl_sock_recv__(dump->sock, buffer, false);
972         if (error) {
973             /* The kernel never blocks providing the results of a dump, so
974              * error == EAGAIN means that we've read the whole thing, and
975              * therefore transform it into EOF.  (The kernel always provides
976              * NLMSG_DONE as a sentinel.  Some other thread must have received
977              * that already but not yet signaled it in 'status'.)
978              *
979              * Any other error is just an error. */
980             return error == EAGAIN ? EOF : error;
981         }
982
983         nlmsghdr = nl_msg_nlmsghdr(buffer);
984         if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
985             VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
986                         nlmsghdr->nlmsg_seq, dump->nl_seq);
987             ofpbuf_clear(buffer);
988         }
989     }
990
991     if (nl_msg_nlmsgerr(buffer, &error) && error) {
992         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
993                      ovs_strerror(error));
994         ofpbuf_clear(buffer);
995         return error;
996     }
997
998     return 0;
999 }
1000
1001 static int
1002 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1003 {
1004     struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1005     if (!nlmsghdr) {
1006         VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1007         return EPROTO;
1008     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1009         return EOF;
1010     } else {
1011         return 0;
1012     }
1013 }
1014
1015 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1016  * have been initialized with nl_dump_start(), and 'buffer' must have been
1017  * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1018  *
1019  * If successful, returns true and points 'reply->data' and
1020  * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
1021  * modify 'reply' (because it points within 'buffer', which will be used by
1022  * future calls to this function).
1023  *
1024  * On failure, returns false and sets 'reply->data' to NULL and
1025  * 'ofpbuf_size(reply)' to 0.  Failure might indicate an actual error or merely
1026  * the end of replies.  An error status for the entire dump operation is
1027  * provided when it is completed by calling nl_dump_done().
1028  *
1029  * Multiple threads may call this function, passing the same nl_dump, however
1030  * each must provide independent buffers. This function may cache multiple
1031  * replies in the buffer, and these will be processed before more replies are
1032  * fetched. When this function returns false, other threads may continue to
1033  * process replies in their buffers, but they will not fetch more replies.
1034  */
1035 bool
1036 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1037 {
1038     int retval = 0;
1039
1040     /* If the buffer is empty, refill it.
1041      *
1042      * If the buffer is not empty, we don't check the dump's status.
1043      * Otherwise, we could end up skipping some of the dump results if thread A
1044      * hits EOF while thread B is in the midst of processing a batch. */
1045     if (!ofpbuf_size(buffer)) {
1046         ovs_mutex_lock(&dump->mutex);
1047         if (!dump->status) {
1048             /* Take the mutex here to avoid an in-kernel race.  If two threads
1049              * try to read from a Netlink dump socket at once, then the socket
1050              * error can be set to EINVAL, which will be encountered on the
1051              * next recv on that socket, which could be anywhere due to the way
1052              * that we pool Netlink sockets.  Serializing the recv calls avoids
1053              * the issue. */
1054             dump->status = nl_dump_refill(dump, buffer);
1055         }
1056         retval = dump->status;
1057         ovs_mutex_unlock(&dump->mutex);
1058     }
1059
1060     /* Fetch the next message from the buffer. */
1061     if (!retval) {
1062         retval = nl_dump_next__(reply, buffer);
1063         if (retval) {
1064             /* Record 'retval' as the dump status, but don't overwrite an error
1065              * with EOF.  */
1066             ovs_mutex_lock(&dump->mutex);
1067             if (dump->status <= 0) {
1068                 dump->status = retval;
1069             }
1070             ovs_mutex_unlock(&dump->mutex);
1071         }
1072     }
1073
1074     if (retval) {
1075         ofpbuf_set_data(reply, NULL);
1076         ofpbuf_set_size(reply, 0);
1077     }
1078     return !retval;
1079 }
1080
1081 /* Completes Netlink dump operation 'dump', which must have been initialized
1082  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
1083  * otherwise a positive errno value describing the problem. */
1084 int
1085 nl_dump_done(struct nl_dump *dump)
1086 {
1087     int status;
1088
1089     ovs_mutex_lock(&dump->mutex);
1090     status = dump->status;
1091     ovs_mutex_unlock(&dump->mutex);
1092
1093     /* Drain any remaining messages that the client didn't read.  Otherwise the
1094      * kernel will continue to queue them up and waste buffer space.
1095      *
1096      * XXX We could just destroy and discard the socket in this case. */
1097     if (!status) {
1098         uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1099         struct ofpbuf reply, buf;
1100
1101         ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1102         while (nl_dump_next(dump, &reply, &buf)) {
1103             /* Nothing to do. */
1104         }
1105         ofpbuf_uninit(&buf);
1106
1107         ovs_mutex_lock(&dump->mutex);
1108         status = dump->status;
1109         ovs_mutex_unlock(&dump->mutex);
1110         ovs_assert(status);
1111     }
1112
1113     nl_pool_release(dump->sock);
1114     ovs_mutex_destroy(&dump->mutex);
1115
1116     return status == EOF ? 0 : status;
1117 }
1118
1119 #ifdef _WIN32
1120 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1121  * an event or a packet is ready to be read. Once the I/O is completed
1122  * the overlapped structure event associated with the pending I/O will be set
1123  */
1124 static int
1125 pend_io_request(const struct nl_sock *sock)
1126 {
1127     struct ofpbuf request;
1128     uint64_t request_stub[128];
1129     struct ovs_header *ovs_header;
1130     struct nlmsghdr *nlmsg;
1131     uint32_t seq;
1132     int retval;
1133     int error;
1134     DWORD bytes;
1135     OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
1136
1137     int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1138                                sizeof (struct ovs_header);
1139
1140     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1141
1142     seq = nl_sock_allocate_seq(sock, 1);
1143     nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1144                           OVS_CTRL_CMD_WIN_PEND_REQ, OVS_WIN_CONTROL_VERSION);
1145     nlmsg = nl_msg_nlmsghdr(&request);
1146     nlmsg->nlmsg_seq = seq;
1147
1148     ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1149     ovs_header->dp_ifindex = 0;
1150
1151     if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1152                          ofpbuf_data(&request), ofpbuf_size(&request),
1153                          NULL, 0, &bytes, overlapped)) {
1154         error = GetLastError();
1155         /* Check if the I/O got pended */
1156         if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1157             VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1158             retval = EINVAL;
1159             goto done;
1160         }
1161     } else {
1162         /* The I/O was completed synchronously */
1163         poll_immediate_wake();
1164     }
1165     retval = 0;
1166
1167 done:
1168     ofpbuf_uninit(&request);
1169     return retval;
1170 }
1171 #endif  /* _WIN32 */
1172
1173 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1174  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
1175 void
1176 nl_sock_wait(const struct nl_sock *sock, short int events)
1177 {
1178 #ifdef _WIN32
1179     if (sock->overlapped.Internal != STATUS_PENDING) {
1180         pend_io_request(sock);
1181     }
1182     poll_fd_wait(sock->handle, events);
1183 #else
1184     poll_fd_wait(sock->fd, events);
1185 #endif
1186 }
1187
1188 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1189  * that can't use nl_sock_wait().
1190  *
1191  * It's a little tricky to use the returned fd correctly, because nl_sock does
1192  * "copy on write" to allow a single nl_sock to be used for notifications,
1193  * transactions, and dumps.  If 'sock' is used only for notifications and
1194  * transactions (and never for dump) then the usage is safe. */
1195 int
1196 nl_sock_fd(const struct nl_sock *sock)
1197 {
1198 #ifdef _WIN32
1199     return sock->handle;
1200 #else
1201     return sock->fd;
1202 #endif
1203 }
1204
1205 /* Returns the PID associated with this socket. */
1206 uint32_t
1207 nl_sock_pid(const struct nl_sock *sock)
1208 {
1209     return sock->pid;
1210 }
1211 \f
1212 /* Miscellaneous.  */
1213
1214 struct genl_family {
1215     struct hmap_node hmap_node;
1216     uint16_t id;
1217     char *name;
1218 };
1219
1220 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1221
1222 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1223     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1224     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1225 };
1226
1227 static struct genl_family *
1228 find_genl_family_by_id(uint16_t id)
1229 {
1230     struct genl_family *family;
1231
1232     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1233                              &genl_families) {
1234         if (family->id == id) {
1235             return family;
1236         }
1237     }
1238     return NULL;
1239 }
1240
1241 static void
1242 define_genl_family(uint16_t id, const char *name)
1243 {
1244     struct genl_family *family = find_genl_family_by_id(id);
1245
1246     if (family) {
1247         if (!strcmp(family->name, name)) {
1248             return;
1249         }
1250         free(family->name);
1251     } else {
1252         family = xmalloc(sizeof *family);
1253         family->id = id;
1254         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1255     }
1256     family->name = xstrdup(name);
1257 }
1258
1259 static const char *
1260 genl_family_to_name(uint16_t id)
1261 {
1262     if (id == GENL_ID_CTRL) {
1263         return "control";
1264     } else {
1265         struct genl_family *family = find_genl_family_by_id(id);
1266         return family ? family->name : "unknown";
1267     }
1268 }
1269
1270 #ifndef _WIN32
1271 static int
1272 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1273                       struct ofpbuf **replyp)
1274 {
1275     struct nl_sock *sock;
1276     struct ofpbuf request, *reply;
1277     int error;
1278
1279     *replyp = NULL;
1280     error = nl_sock_create(NETLINK_GENERIC, &sock);
1281     if (error) {
1282         return error;
1283     }
1284
1285     ofpbuf_init(&request, 0);
1286     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1287                           CTRL_CMD_GETFAMILY, 1);
1288     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1289     error = nl_sock_transact(sock, &request, &reply);
1290     ofpbuf_uninit(&request);
1291     if (error) {
1292         nl_sock_destroy(sock);
1293         return error;
1294     }
1295
1296     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1297                          family_policy, attrs, ARRAY_SIZE(family_policy))
1298         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1299         nl_sock_destroy(sock);
1300         ofpbuf_delete(reply);
1301         return EPROTO;
1302     }
1303
1304     nl_sock_destroy(sock);
1305     *replyp = reply;
1306     return 0;
1307 }
1308 #else
1309 static int
1310 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1311                       struct ofpbuf **replyp)
1312 {
1313     struct nlmsghdr *nlmsg;
1314     struct ofpbuf *reply;
1315     int error;
1316     uint16_t family_id;
1317     const char *family_name;
1318     uint32_t family_version;
1319     uint32_t family_attrmax;
1320     uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1321     const char *mcgrp_name = NULL;
1322
1323     *replyp = NULL;
1324     reply = ofpbuf_new(1024);
1325
1326     /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1327     if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1328         family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1329         family_name = OVS_WIN_CONTROL_FAMILY;
1330         family_version = OVS_WIN_CONTROL_VERSION;
1331         family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1332     } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1333         family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1334         family_name = OVS_DATAPATH_FAMILY;
1335         family_version = OVS_DATAPATH_VERSION;
1336         family_attrmax = OVS_DP_ATTR_MAX;
1337     } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1338         family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1339         family_name = OVS_PACKET_FAMILY;
1340         family_version = OVS_PACKET_VERSION;
1341         family_attrmax = OVS_PACKET_ATTR_MAX;
1342     } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1343         family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1344         family_name = OVS_VPORT_FAMILY;
1345         family_version = OVS_VPORT_VERSION;
1346         family_attrmax = OVS_VPORT_ATTR_MAX;
1347         mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1348         mcgrp_name = OVS_VPORT_MCGROUP;
1349     } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1350         family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1351         family_name = OVS_FLOW_FAMILY;
1352         family_version = OVS_FLOW_VERSION;
1353         family_attrmax = OVS_FLOW_ATTR_MAX;
1354     } else {
1355         ofpbuf_delete(reply);
1356         return EINVAL;
1357     }
1358
1359     nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1360                           CTRL_CMD_NEWFAMILY, family_version);
1361     /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1362      * callers do not seem to need them. */
1363     nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1364     nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1365     nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1366     nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1367
1368     if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1369         size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1370         size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1371             OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1372         nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1373         ovs_assert(mcgrp_name != NULL);
1374         nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1375         nl_msg_end_nested(reply, mcgrp_ofs2);
1376         nl_msg_end_nested(reply, mcgrp_ofs1);
1377     }
1378
1379     /* Set the total length of the netlink message. */
1380     nlmsg = nl_msg_nlmsghdr(reply);
1381     nlmsg->nlmsg_len = ofpbuf_size(reply);
1382
1383     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1384                          family_policy, attrs, ARRAY_SIZE(family_policy))
1385         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1386         ofpbuf_delete(reply);
1387         return EPROTO;
1388     }
1389
1390     *replyp = reply;
1391     return 0;
1392 }
1393 #endif
1394
1395 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1396  * When successful, writes its result to 'multicast_group' and returns 0.
1397  * Otherwise, clears 'multicast_group' and returns a positive error code.
1398  */
1399 int
1400 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1401                        unsigned int *multicast_group)
1402 {
1403     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1404     const struct nlattr *mc;
1405     struct ofpbuf *reply;
1406     unsigned int left;
1407     int error;
1408
1409     *multicast_group = 0;
1410     error = do_lookup_genl_family(family_name, family_attrs, &reply);
1411     if (error) {
1412         return error;
1413     }
1414
1415     if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1416         error = EPROTO;
1417         goto exit;
1418     }
1419
1420     NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1421         static const struct nl_policy mc_policy[] = {
1422             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1423             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1424         };
1425
1426         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1427         const char *mc_name;
1428
1429         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1430             error = EPROTO;
1431             goto exit;
1432         }
1433
1434         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1435         if (!strcmp(group_name, mc_name)) {
1436             *multicast_group =
1437                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1438             error = 0;
1439             goto exit;
1440         }
1441     }
1442     error = EPROTO;
1443
1444 exit:
1445     ofpbuf_delete(reply);
1446     return error;
1447 }
1448
1449 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1450  * number and stores it in '*number'.  If successful, returns 0 and the caller
1451  * may use '*number' as the family number.  On failure, returns a positive
1452  * errno value and '*number' caches the errno value. */
1453 int
1454 nl_lookup_genl_family(const char *name, int *number)
1455 {
1456     if (*number == 0) {
1457         struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1458         struct ofpbuf *reply;
1459         int error;
1460
1461         error = do_lookup_genl_family(name, attrs, &reply);
1462         if (!error) {
1463             *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1464             define_genl_family(*number, name);
1465         } else {
1466             *number = -error;
1467         }
1468         ofpbuf_delete(reply);
1469
1470         ovs_assert(*number != 0);
1471     }
1472     return *number > 0 ? 0 : -*number;
1473 }
1474 \f
1475 struct nl_pool {
1476     struct nl_sock *socks[16];
1477     int n;
1478 };
1479
1480 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1481 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1482
1483 static int
1484 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1485 {
1486     struct nl_sock *sock = NULL;
1487     struct nl_pool *pool;
1488
1489     ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1490
1491     ovs_mutex_lock(&pool_mutex);
1492     pool = &pools[protocol];
1493     if (pool->n > 0) {
1494         sock = pool->socks[--pool->n];
1495     }
1496     ovs_mutex_unlock(&pool_mutex);
1497
1498     if (sock) {
1499         *sockp = sock;
1500         return 0;
1501     } else {
1502         return nl_sock_create(protocol, sockp);
1503     }
1504 }
1505
1506 static void
1507 nl_pool_release(struct nl_sock *sock)
1508 {
1509     if (sock) {
1510         struct nl_pool *pool = &pools[sock->protocol];
1511
1512         ovs_mutex_lock(&pool_mutex);
1513         if (pool->n < ARRAY_SIZE(pool->socks)) {
1514             pool->socks[pool->n++] = sock;
1515             sock = NULL;
1516         }
1517         ovs_mutex_unlock(&pool_mutex);
1518
1519         nl_sock_destroy(sock);
1520     }
1521 }
1522
1523 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1524  * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response.  If
1525  * successful, returns 0.  On failure, returns a positive errno value.
1526  *
1527  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1528  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1529  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
1530  * reply, if any, is discarded.
1531  *
1532  * Before the message is sent, nlmsg_len in 'request' will be finalized to
1533  * match ofpbuf_size(msg), nlmsg_pid will be set to the pid of the socket used
1534  * for sending the request, and nlmsg_seq will be initialized.
1535  *
1536  * The caller is responsible for destroying 'request'.
1537  *
1538  * Bare Netlink is an unreliable transport protocol.  This function layers
1539  * reliable delivery and reply semantics on top of bare Netlink.
1540  *
1541  * In Netlink, sending a request to the kernel is reliable enough, because the
1542  * kernel will tell us if the message cannot be queued (and we will in that
1543  * case put it on the transmit queue and wait until it can be delivered).
1544  *
1545  * Receiving the reply is the real problem: if the socket buffer is full when
1546  * the kernel tries to send the reply, the reply will be dropped.  However, the
1547  * kernel sets a flag that a reply has been dropped.  The next call to recv
1548  * then returns ENOBUFS.  We can then re-send the request.
1549  *
1550  * Caveats:
1551  *
1552  *      1. Netlink depends on sequence numbers to match up requests and
1553  *         replies.  The sender of a request supplies a sequence number, and
1554  *         the reply echos back that sequence number.
1555  *
1556  *         This is fine, but (1) some kernel netlink implementations are
1557  *         broken, in that they fail to echo sequence numbers and (2) this
1558  *         function will drop packets with non-matching sequence numbers, so
1559  *         that only a single request can be usefully transacted at a time.
1560  *
1561  *      2. Resending the request causes it to be re-executed, so the request
1562  *         needs to be idempotent.
1563  */
1564 int
1565 nl_transact(int protocol, const struct ofpbuf *request,
1566             struct ofpbuf **replyp)
1567 {
1568     struct nl_sock *sock;
1569     int error;
1570
1571     error = nl_pool_alloc(protocol, &sock);
1572     if (error) {
1573         *replyp = NULL;
1574         return error;
1575     }
1576
1577     error = nl_sock_transact(sock, request, replyp);
1578
1579     nl_pool_release(sock);
1580     return error;
1581 }
1582
1583 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1584  * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1585  * NETLINK_GENERIC), in order, and receives responses to all of them.  Fills in
1586  * the 'error' member of each transaction with 0 if it was successful,
1587  * otherwise with a positive errno value.  If 'reply' is nonnull, then it will
1588  * be filled with the reply if the message receives a detailed reply.  In other
1589  * cases, i.e. where the request failed or had no reply beyond an indication of
1590  * success, 'reply' will be cleared if it is nonnull.
1591  *
1592  * The caller is responsible for destroying each request and reply, and the
1593  * transactions array itself.
1594  *
1595  * Before sending each message, this function will finalize nlmsg_len in each
1596  * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1597  * used for the transaction, and initialize nlmsg_seq.
1598  *
1599  * Bare Netlink is an unreliable transport protocol.  This function layers
1600  * reliable delivery and reply semantics on top of bare Netlink.  See
1601  * nl_transact() for some caveats.
1602  */
1603 void
1604 nl_transact_multiple(int protocol,
1605                      struct nl_transaction **transactions, size_t n)
1606 {
1607     struct nl_sock *sock;
1608     int error;
1609
1610     error = nl_pool_alloc(protocol, &sock);
1611     if (!error) {
1612         nl_sock_transact_multiple(sock, transactions, n);
1613         nl_pool_release(sock);
1614     } else {
1615         nl_sock_record_errors__(transactions, n, error);
1616     }
1617 }
1618
1619 \f
1620 static uint32_t
1621 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1622 {
1623     uint32_t seq = sock->next_seq;
1624
1625     sock->next_seq += n;
1626
1627     /* Make it impossible for the next request for sequence numbers to wrap
1628      * around to 0.  Start over with 1 to avoid ever using a sequence number of
1629      * 0, because the kernel uses sequence number 0 for notifications. */
1630     if (sock->next_seq >= UINT32_MAX / 2) {
1631         sock->next_seq = 1;
1632     }
1633
1634     return seq;
1635 }
1636
1637 static void
1638 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1639 {
1640     struct nlmsg_flag {
1641         unsigned int bits;
1642         const char *name;
1643     };
1644     static const struct nlmsg_flag flags[] = {
1645         { NLM_F_REQUEST, "REQUEST" },
1646         { NLM_F_MULTI, "MULTI" },
1647         { NLM_F_ACK, "ACK" },
1648         { NLM_F_ECHO, "ECHO" },
1649         { NLM_F_DUMP, "DUMP" },
1650         { NLM_F_ROOT, "ROOT" },
1651         { NLM_F_MATCH, "MATCH" },
1652         { NLM_F_ATOMIC, "ATOMIC" },
1653     };
1654     const struct nlmsg_flag *flag;
1655     uint16_t flags_left;
1656
1657     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1658                   h->nlmsg_len, h->nlmsg_type);
1659     if (h->nlmsg_type == NLMSG_NOOP) {
1660         ds_put_cstr(ds, "(no-op)");
1661     } else if (h->nlmsg_type == NLMSG_ERROR) {
1662         ds_put_cstr(ds, "(error)");
1663     } else if (h->nlmsg_type == NLMSG_DONE) {
1664         ds_put_cstr(ds, "(done)");
1665     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1666         ds_put_cstr(ds, "(overrun)");
1667     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1668         ds_put_cstr(ds, "(reserved)");
1669     } else if (protocol == NETLINK_GENERIC) {
1670         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1671     } else {
1672         ds_put_cstr(ds, "(family-defined)");
1673     }
1674     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1675     flags_left = h->nlmsg_flags;
1676     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1677         if ((flags_left & flag->bits) == flag->bits) {
1678             ds_put_format(ds, "[%s]", flag->name);
1679             flags_left &= ~flag->bits;
1680         }
1681     }
1682     if (flags_left) {
1683         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1684     }
1685     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1686                   h->nlmsg_seq, h->nlmsg_pid);
1687 }
1688
1689 static char *
1690 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1691 {
1692     struct ds ds = DS_EMPTY_INITIALIZER;
1693     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1694     if (h) {
1695         nlmsghdr_to_string(h, protocol, &ds);
1696         if (h->nlmsg_type == NLMSG_ERROR) {
1697             const struct nlmsgerr *e;
1698             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1699                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1700             if (e) {
1701                 ds_put_format(&ds, " error(%d", e->error);
1702                 if (e->error < 0) {
1703                     ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1704                 }
1705                 ds_put_cstr(&ds, ", in-reply-to(");
1706                 nlmsghdr_to_string(&e->msg, protocol, &ds);
1707                 ds_put_cstr(&ds, "))");
1708             } else {
1709                 ds_put_cstr(&ds, " error(truncated)");
1710             }
1711         } else if (h->nlmsg_type == NLMSG_DONE) {
1712             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1713             if (error) {
1714                 ds_put_format(&ds, " done(%d", *error);
1715                 if (*error < 0) {
1716                     ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1717                 }
1718                 ds_put_cstr(&ds, ")");
1719             } else {
1720                 ds_put_cstr(&ds, " done(truncated)");
1721             }
1722         } else if (protocol == NETLINK_GENERIC) {
1723             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1724             if (genl) {
1725                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1726                               genl->cmd, genl->version);
1727             }
1728         }
1729     } else {
1730         ds_put_cstr(&ds, "nl(truncated)");
1731     }
1732     return ds.string;
1733 }
1734
1735 static void
1736 log_nlmsg(const char *function, int error,
1737           const void *message, size_t size, int protocol)
1738 {
1739     struct ofpbuf buffer;
1740     char *nlmsg;
1741
1742     if (!VLOG_IS_DBG_ENABLED()) {
1743         return;
1744     }
1745
1746     ofpbuf_use_const(&buffer, message, size);
1747     nlmsg = nlmsg_to_string(&buffer, protocol);
1748     VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
1749     free(nlmsg);
1750 }