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