netlink-socket: remove local variable in do_lookup_genl_family.
[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         int last_error = GetLastError();
151         VLOG_ERR("fcntl: %s", ovs_strerror(last_error));
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         int last_error = GetLastError();
159         VLOG_ERR("fcntl: %s", ovs_strerror(last_error));
160         goto error;
161     }
162
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 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
338  * successful, otherwise a positive errno value.
339  *
340  * A socket that is subscribed to a multicast group that receives asynchronous
341  * notifications must not be used for Netlink transactions or dumps, because
342  * transactions and dumps can cause notifications to be lost.
343  *
344  * Multicast group numbers are always positive.
345  *
346  * It is not an error to attempt to join a multicast group to which a socket
347  * already belongs. */
348 int
349 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
350 {
351 #ifdef _WIN32
352 #define OVS_VPORT_MCGROUP_FALLBACK_ID 33
353     struct ofpbuf msg_buf;
354     struct message_multicast
355     {
356         struct nlmsghdr;
357         /* if true, join; if else, leave */
358         unsigned char join;
359         unsigned int groupId;
360     };
361
362     struct message_multicast msg = { 0 };
363
364     msg.nlmsg_len = sizeof(struct message_multicast);
365     msg.nlmsg_type = OVS_VPORT_MCGROUP_FALLBACK_ID;
366     msg.nlmsg_flags = 0;
367     msg.nlmsg_seq = 0;
368     msg.nlmsg_pid = sock->pid;
369
370     msg.join = 1;
371     msg.groupId = multicast_group;
372     msg_buf.base_ = &msg;
373     msg_buf.data_ = &msg;
374     msg_buf.size_ = msg.nlmsg_len;
375
376     nl_sock_send__(sock, &msg_buf, msg.nlmsg_seq, 0);
377 #else
378     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
379                    &multicast_group, sizeof multicast_group) < 0) {
380         VLOG_WARN("could not join multicast group %u (%s)",
381                   multicast_group, ovs_strerror(errno));
382         return errno;
383     }
384 #endif
385     return 0;
386 }
387
388 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
389  * successful, otherwise a positive errno value.
390  *
391  * Multicast group numbers are always positive.
392  *
393  * It is not an error to attempt to leave a multicast group to which a socket
394  * does not belong.
395  *
396  * On success, reading from 'sock' will still return any messages that were
397  * received on 'multicast_group' before the group was left. */
398 int
399 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
400 {
401 #ifdef _WIN32
402     struct ofpbuf msg_buf;
403     struct message_multicast
404     {
405         struct nlmsghdr;
406         /* if true, join; if else, leave*/
407         unsigned char join;
408     };
409
410     struct message_multicast msg = { 0 };
411     nl_msg_put_nlmsghdr(&msg, sizeof(struct message_multicast),
412                         multicast_group, 0);
413     msg.join = 0;
414
415     msg_buf.base_ = &msg;
416     msg_buf.data_ = &msg;
417     msg_buf.size_ = msg.nlmsg_len;
418
419     nl_sock_send__(sock, &msg_buf, msg.nlmsg_seq, 0);
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, OVS_IOCTL_READ,
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     memset(&msg, 0, sizeof msg);
669     msg.msg_iov = iovs;
670     msg.msg_iovlen = n;
671     do {
672 #ifdef _WIN32
673     DWORD last_error = 0;
674     bool result = FALSE;
675     for (i = 0; i < n; i++) {
676         result = WriteFile((HANDLE)sock->handle, iovs[i].iov_base, iovs[i].iov_len,
677                            &error, NULL);
678         last_error = GetLastError();
679         if (last_error != ERROR_SUCCESS && !result) {
680             error = EAGAIN;
681             errno = EAGAIN;
682         } else {
683             error = 0;
684         }
685     }
686 #else
687         error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
688 #endif
689     } while (error == EINTR);
690
691     for (i = 0; i < n; i++) {
692         struct nl_transaction *txn = transactions[i];
693
694         log_nlmsg(__func__, error, ofpbuf_data(txn->request), ofpbuf_size(txn->request),
695                   sock->protocol);
696     }
697     if (!error) {
698         COVERAGE_ADD(netlink_sent, n);
699     }
700
701     if (error) {
702         return error;
703     }
704
705     ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
706     tmp_txn.request = NULL;
707     tmp_txn.reply = &tmp_reply;
708     tmp_txn.error = 0;
709     while (n > 0) {
710         struct nl_transaction *buf_txn, *txn;
711         uint32_t seq;
712
713         /* Find a transaction whose buffer we can use for receiving a reply.
714          * If no such transaction is left, use tmp_txn. */
715         buf_txn = &tmp_txn;
716         for (i = 0; i < n; i++) {
717             if (transactions[i]->reply) {
718                 buf_txn = transactions[i];
719                 break;
720             }
721         }
722
723         /* Receive a reply. */
724         error = nl_sock_recv__(sock, buf_txn->reply, false);
725         if (error) {
726             if (error == EAGAIN) {
727                 nl_sock_record_errors__(transactions, n, 0);
728                 *done += n;
729                 error = 0;
730             }
731             break;
732         }
733
734         /* Match the reply up with a transaction. */
735         seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
736         if (seq < base_seq || seq >= base_seq + n) {
737             VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
738             continue;
739         }
740         i = seq - base_seq;
741         txn = transactions[i];
742
743         /* Fill in the results for 'txn'. */
744         if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
745             if (txn->reply) {
746                 ofpbuf_clear(txn->reply);
747             }
748             if (txn->error) {
749                 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
750                             error, ovs_strerror(txn->error));
751             }
752         } else {
753             txn->error = 0;
754             if (txn->reply && txn != buf_txn) {
755                 /* Swap buffers. */
756                 struct ofpbuf *reply = buf_txn->reply;
757                 buf_txn->reply = txn->reply;
758                 txn->reply = reply;
759             }
760         }
761
762         /* Fill in the results for transactions before 'txn'.  (We have to do
763          * this after the results for 'txn' itself because of the buffer swap
764          * above.) */
765         nl_sock_record_errors__(transactions, i, 0);
766
767         /* Advance. */
768         *done += i + 1;
769         transactions += i + 1;
770         n -= i + 1;
771         base_seq += i + 1;
772     }
773     ofpbuf_uninit(&tmp_reply);
774
775     return error;
776 }
777
778 static void
779 nl_sock_transact_multiple(struct nl_sock *sock,
780                           struct nl_transaction **transactions, size_t n)
781 {
782     int max_batch_count;
783     int error;
784
785     if (!n) {
786         return;
787     }
788
789     /* In theory, every request could have a 64 kB reply.  But the default and
790      * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
791      * be a bit below 128 kB, so that would only allow a single message in a
792      * "batch".  So we assume that replies average (at most) 4 kB, which allows
793      * a good deal of batching.
794      *
795      * In practice, most of the requests that we batch either have no reply at
796      * all or a brief reply. */
797     max_batch_count = MAX(sock->rcvbuf / 4096, 1);
798     max_batch_count = MIN(max_batch_count, max_iovs);
799
800     while (n > 0) {
801         size_t count, bytes;
802         size_t done;
803
804         /* Batch up to 'max_batch_count' transactions.  But cap it at about a
805          * page of requests total because big skbuffs are expensive to
806          * allocate in the kernel.  */
807 #if defined(PAGESIZE)
808         enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
809 #else
810         enum { MAX_BATCH_BYTES = 4096 - 512 };
811 #endif
812         bytes = ofpbuf_size(transactions[0]->request);
813         for (count = 1; count < n && count < max_batch_count; count++) {
814             if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
815                 break;
816             }
817             bytes += ofpbuf_size(transactions[count]->request);
818         }
819
820         error = nl_sock_transact_multiple__(sock, transactions, count, &done);
821         transactions += done;
822         n -= done;
823
824         if (error == ENOBUFS) {
825             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
826         } else if (error) {
827             VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
828             nl_sock_record_errors__(transactions, n, error);
829         }
830     }
831 }
832
833 static int
834 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
835                  struct ofpbuf **replyp)
836 {
837     struct nl_transaction *transactionp;
838     struct nl_transaction transaction;
839
840     transaction.request = CONST_CAST(struct ofpbuf *, request);
841     transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
842     transactionp = &transaction;
843
844     nl_sock_transact_multiple(sock, &transactionp, 1);
845
846     if (replyp) {
847         if (transaction.error) {
848             ofpbuf_delete(transaction.reply);
849             *replyp = NULL;
850         } else {
851             *replyp = transaction.reply;
852         }
853     }
854
855     return transaction.error;
856 }
857
858 /* Drain all the messages currently in 'sock''s receive queue. */
859 int
860 nl_sock_drain(struct nl_sock *sock)
861 {
862 #ifdef _WIN32
863     return 0;
864 #else
865     return drain_rcvbuf(sock->fd);
866 #endif
867 }
868
869 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
870  * Netlink socket created with the given 'protocol', and initializes 'dump' to
871  * reflect the state of the operation.
872  *
873  * 'request' must contain a Netlink message.  Before sending the message,
874  * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
875  * set to the Netlink socket's pid.  NLM_F_DUMP and NLM_F_ACK will be set in
876  * nlmsg_flags.
877  *
878  * The design of this Netlink socket library ensures that the dump is reliable.
879  *
880  * This function provides no status indication.  nl_dump_done() provides an
881  * error status for the entire dump operation.
882  *
883  * The caller must eventually destroy 'request'.
884  */
885 void
886 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
887 {
888     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
889
890     ovs_mutex_init(&dump->mutex);
891     ovs_mutex_lock(&dump->mutex);
892     dump->status = nl_pool_alloc(protocol, &dump->sock);
893     if (!dump->status) {
894         dump->status = nl_sock_send__(dump->sock, request,
895                                       nl_sock_allocate_seq(dump->sock, 1),
896                                       true);
897     }
898     dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
899     ovs_mutex_unlock(&dump->mutex);
900 }
901
902 static int
903 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
904     OVS_REQUIRES(dump->mutex)
905 {
906     struct nlmsghdr *nlmsghdr;
907     int error;
908
909     while (!ofpbuf_size(buffer)) {
910         error = nl_sock_recv__(dump->sock, buffer, false);
911         if (error) {
912             /* The kernel never blocks providing the results of a dump, so
913              * error == EAGAIN means that we've read the whole thing, and
914              * therefore transform it into EOF.  (The kernel always provides
915              * NLMSG_DONE as a sentinel.  Some other thread must have received
916              * that already but not yet signaled it in 'status'.)
917              *
918              * Any other error is just an error. */
919             return error == EAGAIN ? EOF : error;
920         }
921
922         nlmsghdr = nl_msg_nlmsghdr(buffer);
923         if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
924             VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
925                         nlmsghdr->nlmsg_seq, dump->nl_seq);
926             ofpbuf_clear(buffer);
927         }
928     }
929
930     if (nl_msg_nlmsgerr(buffer, &error) && error) {
931         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
932                      ovs_strerror(error));
933         ofpbuf_clear(buffer);
934         return error;
935     }
936
937     return 0;
938 }
939
940 static int
941 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
942 {
943     struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
944     if (!nlmsghdr) {
945         VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
946         return EPROTO;
947     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
948         return EOF;
949     } else {
950         return 0;
951     }
952 }
953
954 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
955  * have been initialized with nl_dump_start(), and 'buffer' must have been
956  * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
957  *
958  * If successful, returns true and points 'reply->data' and
959  * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
960  * modify 'reply' (because it points within 'buffer', which will be used by
961  * future calls to this function).
962  *
963  * On failure, returns false and sets 'reply->data' to NULL and
964  * 'ofpbuf_size(reply)' to 0.  Failure might indicate an actual error or merely
965  * the end of replies.  An error status for the entire dump operation is
966  * provided when it is completed by calling nl_dump_done().
967  *
968  * Multiple threads may call this function, passing the same nl_dump, however
969  * each must provide independent buffers. This function may cache multiple
970  * replies in the buffer, and these will be processed before more replies are
971  * fetched. When this function returns false, other threads may continue to
972  * process replies in their buffers, but they will not fetch more replies.
973  */
974 bool
975 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
976 {
977     int retval = 0;
978
979     /* If the buffer is empty, refill it.
980      *
981      * If the buffer is not empty, we don't check the dump's status.
982      * Otherwise, we could end up skipping some of the dump results if thread A
983      * hits EOF while thread B is in the midst of processing a batch. */
984     if (!ofpbuf_size(buffer)) {
985         ovs_mutex_lock(&dump->mutex);
986         if (!dump->status) {
987             /* Take the mutex here to avoid an in-kernel race.  If two threads
988              * try to read from a Netlink dump socket at once, then the socket
989              * error can be set to EINVAL, which will be encountered on the
990              * next recv on that socket, which could be anywhere due to the way
991              * that we pool Netlink sockets.  Serializing the recv calls avoids
992              * the issue. */
993             dump->status = nl_dump_refill(dump, buffer);
994         }
995         retval = dump->status;
996         ovs_mutex_unlock(&dump->mutex);
997     }
998
999     /* Fetch the next message from the buffer. */
1000     if (!retval) {
1001         retval = nl_dump_next__(reply, buffer);
1002         if (retval) {
1003             /* Record 'retval' as the dump status, but don't overwrite an error
1004              * with EOF.  */
1005             ovs_mutex_lock(&dump->mutex);
1006             if (dump->status <= 0) {
1007                 dump->status = retval;
1008             }
1009             ovs_mutex_unlock(&dump->mutex);
1010         }
1011     }
1012
1013     if (retval) {
1014         ofpbuf_set_data(reply, NULL);
1015         ofpbuf_set_size(reply, 0);
1016     }
1017     return !retval;
1018 }
1019
1020 /* Completes Netlink dump operation 'dump', which must have been initialized
1021  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
1022  * otherwise a positive errno value describing the problem. */
1023 int
1024 nl_dump_done(struct nl_dump *dump)
1025 {
1026     int status;
1027
1028     ovs_mutex_lock(&dump->mutex);
1029     status = dump->status;
1030     ovs_mutex_unlock(&dump->mutex);
1031
1032     /* Drain any remaining messages that the client didn't read.  Otherwise the
1033      * kernel will continue to queue them up and waste buffer space.
1034      *
1035      * XXX We could just destroy and discard the socket in this case. */
1036     if (!status) {
1037         uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1038         struct ofpbuf reply, buf;
1039
1040         ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1041         while (nl_dump_next(dump, &reply, &buf)) {
1042             /* Nothing to do. */
1043         }
1044         ofpbuf_uninit(&buf);
1045
1046         ovs_mutex_lock(&dump->mutex);
1047         status = dump->status;
1048         ovs_mutex_unlock(&dump->mutex);
1049         ovs_assert(status);
1050     }
1051
1052     nl_pool_release(dump->sock);
1053     ovs_mutex_destroy(&dump->mutex);
1054
1055     return status == EOF ? 0 : status;
1056 }
1057
1058 #ifdef _WIN32
1059 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1060  * an event or a packet is ready to be read. Once the I/O is completed
1061  * the overlapped structure event associated with the pending I/O will be set
1062  */
1063 static int
1064 pend_io_request(const struct nl_sock *sock)
1065 {
1066     struct ofpbuf request;
1067     uint64_t request_stub[128];
1068     struct ovs_header *ovs_header;
1069     struct nlmsghdr *nlmsg;
1070     uint32_t seq;
1071     int retval;
1072     int error;
1073     DWORD bytes;
1074     OVERLAPPED *overlapped = &sock->overlapped;
1075
1076     int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1077                                sizeof (struct ovs_header);
1078
1079     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1080
1081     seq = nl_sock_allocate_seq(sock, 1);
1082     nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1083                           OVS_CTRL_CMD_WIN_PEND_REQ, OVS_WIN_CONTROL_VERSION);
1084     nlmsg = nl_msg_nlmsghdr(&request);
1085     nlmsg->nlmsg_seq = seq;
1086
1087     ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1088     ovs_header->dp_ifindex = 0;
1089
1090     if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1091                          ofpbuf_data(&request), ofpbuf_size(&request),
1092                          NULL, 0, &bytes, overlapped)) {
1093         error = GetLastError();
1094         /* Check if the I/O got pended */
1095         if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1096             VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1097             retval = EINVAL;
1098             goto done;
1099         }
1100     } else {
1101         /* The I/O was completed synchronously */
1102         poll_immediate_wake();
1103     }
1104     retval = 0;
1105
1106 done:
1107     ofpbuf_uninit(&request);
1108     return retval;
1109 }
1110 #endif  /* _WIN32 */
1111
1112 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1113  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
1114 void
1115 nl_sock_wait(const struct nl_sock *sock, short int events)
1116 {
1117 #ifdef _WIN32
1118     if (sock->overlapped.Internal != STATUS_PENDING) {
1119         pend_io_request(sock);
1120     }
1121     poll_fd_wait(sock->handle, events);
1122 #else
1123     poll_fd_wait(sock->fd, events);
1124 #endif
1125 }
1126
1127 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1128  * that can't use nl_sock_wait().
1129  *
1130  * It's a little tricky to use the returned fd correctly, because nl_sock does
1131  * "copy on write" to allow a single nl_sock to be used for notifications,
1132  * transactions, and dumps.  If 'sock' is used only for notifications and
1133  * transactions (and never for dump) then the usage is safe. */
1134 int
1135 nl_sock_fd(const struct nl_sock *sock)
1136 {
1137 #ifdef _WIN32
1138     return sock->handle;
1139 #else
1140     return sock->fd;
1141 #endif
1142 }
1143
1144 /* Returns the PID associated with this socket. */
1145 uint32_t
1146 nl_sock_pid(const struct nl_sock *sock)
1147 {
1148     return sock->pid;
1149 }
1150 \f
1151 /* Miscellaneous.  */
1152
1153 struct genl_family {
1154     struct hmap_node hmap_node;
1155     uint16_t id;
1156     char *name;
1157 };
1158
1159 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1160
1161 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1162     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1163     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1164 };
1165
1166 static struct genl_family *
1167 find_genl_family_by_id(uint16_t id)
1168 {
1169     struct genl_family *family;
1170
1171     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1172                              &genl_families) {
1173         if (family->id == id) {
1174             return family;
1175         }
1176     }
1177     return NULL;
1178 }
1179
1180 static void
1181 define_genl_family(uint16_t id, const char *name)
1182 {
1183     struct genl_family *family = find_genl_family_by_id(id);
1184
1185     if (family) {
1186         if (!strcmp(family->name, name)) {
1187             return;
1188         }
1189         free(family->name);
1190     } else {
1191         family = xmalloc(sizeof *family);
1192         family->id = id;
1193         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1194     }
1195     family->name = xstrdup(name);
1196 }
1197
1198 static const char *
1199 genl_family_to_name(uint16_t id)
1200 {
1201     if (id == GENL_ID_CTRL) {
1202         return "control";
1203     } else {
1204         struct genl_family *family = find_genl_family_by_id(id);
1205         return family ? family->name : "unknown";
1206     }
1207 }
1208
1209 #ifndef _WIN32
1210 static int
1211 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1212                       struct ofpbuf **replyp)
1213 {
1214     struct nl_sock *sock;
1215     struct ofpbuf request, *reply;
1216     int error;
1217
1218     *replyp = NULL;
1219     error = nl_sock_create(NETLINK_GENERIC, &sock);
1220     if (error) {
1221         return error;
1222     }
1223
1224     ofpbuf_init(&request, 0);
1225     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1226                           CTRL_CMD_GETFAMILY, 1);
1227     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1228     error = nl_sock_transact(sock, &request, &reply);
1229     ofpbuf_uninit(&request);
1230     if (error) {
1231         nl_sock_destroy(sock);
1232         return error;
1233     }
1234
1235     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1236                          family_policy, attrs, ARRAY_SIZE(family_policy))
1237         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1238         nl_sock_destroy(sock);
1239         ofpbuf_delete(reply);
1240         return EPROTO;
1241     }
1242
1243     nl_sock_destroy(sock);
1244     *replyp = reply;
1245     return 0;
1246 }
1247 #else
1248 static int
1249 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1250                       struct ofpbuf **replyp)
1251 {
1252     struct nlmsghdr *nlmsg;
1253     struct ofpbuf *reply;
1254     int error;
1255     uint16_t family_id;
1256     const char *family_name;
1257     uint32_t family_version;
1258     uint32_t family_attrmax;
1259     uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1260     const char *mcgrp_name = NULL;
1261
1262     *replyp = NULL;
1263     reply = ofpbuf_new(1024);
1264
1265     /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1266     if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1267         family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1268         family_name = OVS_WIN_CONTROL_FAMILY;
1269         family_version = OVS_WIN_CONTROL_VERSION;
1270         family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1271     } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1272         family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1273         family_name = OVS_DATAPATH_FAMILY;
1274         family_version = OVS_DATAPATH_VERSION;
1275         family_attrmax = OVS_DP_ATTR_MAX;
1276     } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1277         family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1278         family_name = OVS_PACKET_FAMILY;
1279         family_version = OVS_PACKET_VERSION;
1280         family_attrmax = OVS_PACKET_ATTR_MAX;
1281     } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1282         family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1283         family_name = OVS_VPORT_FAMILY;
1284         family_version = OVS_VPORT_VERSION;
1285         family_attrmax = OVS_VPORT_ATTR_MAX;
1286         mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1287         mcgrp_name = OVS_VPORT_MCGROUP;
1288     } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1289         family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1290         family_name = OVS_FLOW_FAMILY;
1291         family_version = OVS_FLOW_VERSION;
1292         family_attrmax = OVS_FLOW_ATTR_MAX;
1293     } else {
1294         ofpbuf_delete(reply);
1295         return EINVAL;
1296     }
1297
1298     nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1299                           CTRL_CMD_NEWFAMILY, family_version);
1300     /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1301      * callers do not seem to need them. */
1302     nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1303     nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1304     nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1305     nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1306
1307     if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1308         size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1309         size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1310             OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1311         nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1312         ovs_assert(mcgrp_name != NULL);
1313         nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1314         nl_msg_end_nested(reply, mcgrp_ofs2);
1315         nl_msg_end_nested(reply, mcgrp_ofs1);
1316     }
1317
1318     /* Set the total length of the netlink message. */
1319     nlmsg = nl_msg_nlmsghdr(reply);
1320     nlmsg->nlmsg_len = ofpbuf_size(reply);
1321
1322     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1323                          family_policy, attrs, ARRAY_SIZE(family_policy))
1324         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1325         ofpbuf_delete(reply);
1326         return EPROTO;
1327     }
1328
1329     *replyp = reply;
1330     return 0;
1331 }
1332 #endif
1333
1334 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1335  * When successful, writes its result to 'multicast_group' and returns 0.
1336  * Otherwise, clears 'multicast_group' and returns a positive error code.
1337  */
1338 int
1339 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1340                        unsigned int *multicast_group)
1341 {
1342     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1343     const struct nlattr *mc;
1344     struct ofpbuf *reply;
1345     unsigned int left;
1346     int error;
1347
1348     *multicast_group = 0;
1349     error = do_lookup_genl_family(family_name, family_attrs, &reply);
1350     if (error) {
1351         return error;
1352     }
1353
1354     if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1355         error = EPROTO;
1356         goto exit;
1357     }
1358
1359     NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1360         static const struct nl_policy mc_policy[] = {
1361             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1362             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1363         };
1364
1365         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1366         const char *mc_name;
1367
1368         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1369             error = EPROTO;
1370             goto exit;
1371         }
1372
1373         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1374         if (!strcmp(group_name, mc_name)) {
1375             *multicast_group =
1376                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1377             error = 0;
1378             goto exit;
1379         }
1380     }
1381     error = EPROTO;
1382
1383 exit:
1384     ofpbuf_delete(reply);
1385     return error;
1386 }
1387
1388 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1389  * number and stores it in '*number'.  If successful, returns 0 and the caller
1390  * may use '*number' as the family number.  On failure, returns a positive
1391  * errno value and '*number' caches the errno value. */
1392 int
1393 nl_lookup_genl_family(const char *name, int *number)
1394 {
1395     if (*number == 0) {
1396         struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1397         struct ofpbuf *reply;
1398         int error;
1399
1400         error = do_lookup_genl_family(name, attrs, &reply);
1401         if (!error) {
1402             *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1403             define_genl_family(*number, name);
1404         } else {
1405             *number = -error;
1406         }
1407         ofpbuf_delete(reply);
1408
1409         ovs_assert(*number != 0);
1410     }
1411     return *number > 0 ? 0 : -*number;
1412 }
1413 \f
1414 struct nl_pool {
1415     struct nl_sock *socks[16];
1416     int n;
1417 };
1418
1419 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1420 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1421
1422 static int
1423 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1424 {
1425     struct nl_sock *sock = NULL;
1426     struct nl_pool *pool;
1427
1428     ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1429
1430     ovs_mutex_lock(&pool_mutex);
1431     pool = &pools[protocol];
1432     if (pool->n > 0) {
1433         sock = pool->socks[--pool->n];
1434     }
1435     ovs_mutex_unlock(&pool_mutex);
1436
1437     if (sock) {
1438         *sockp = sock;
1439         return 0;
1440     } else {
1441         return nl_sock_create(protocol, sockp);
1442     }
1443 }
1444
1445 static void
1446 nl_pool_release(struct nl_sock *sock)
1447 {
1448     if (sock) {
1449         struct nl_pool *pool = &pools[sock->protocol];
1450
1451         ovs_mutex_lock(&pool_mutex);
1452         if (pool->n < ARRAY_SIZE(pool->socks)) {
1453             pool->socks[pool->n++] = sock;
1454             sock = NULL;
1455         }
1456         ovs_mutex_unlock(&pool_mutex);
1457
1458         nl_sock_destroy(sock);
1459     }
1460 }
1461
1462 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1463  * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response.  If
1464  * successful, returns 0.  On failure, returns a positive errno value.
1465  *
1466  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1467  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1468  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
1469  * reply, if any, is discarded.
1470  *
1471  * Before the message is sent, nlmsg_len in 'request' will be finalized to
1472  * match ofpbuf_size(msg), nlmsg_pid will be set to the pid of the socket used
1473  * for sending the request, and nlmsg_seq will be initialized.
1474  *
1475  * The caller is responsible for destroying 'request'.
1476  *
1477  * Bare Netlink is an unreliable transport protocol.  This function layers
1478  * reliable delivery and reply semantics on top of bare Netlink.
1479  *
1480  * In Netlink, sending a request to the kernel is reliable enough, because the
1481  * kernel will tell us if the message cannot be queued (and we will in that
1482  * case put it on the transmit queue and wait until it can be delivered).
1483  *
1484  * Receiving the reply is the real problem: if the socket buffer is full when
1485  * the kernel tries to send the reply, the reply will be dropped.  However, the
1486  * kernel sets a flag that a reply has been dropped.  The next call to recv
1487  * then returns ENOBUFS.  We can then re-send the request.
1488  *
1489  * Caveats:
1490  *
1491  *      1. Netlink depends on sequence numbers to match up requests and
1492  *         replies.  The sender of a request supplies a sequence number, and
1493  *         the reply echos back that sequence number.
1494  *
1495  *         This is fine, but (1) some kernel netlink implementations are
1496  *         broken, in that they fail to echo sequence numbers and (2) this
1497  *         function will drop packets with non-matching sequence numbers, so
1498  *         that only a single request can be usefully transacted at a time.
1499  *
1500  *      2. Resending the request causes it to be re-executed, so the request
1501  *         needs to be idempotent.
1502  */
1503 int
1504 nl_transact(int protocol, const struct ofpbuf *request,
1505             struct ofpbuf **replyp)
1506 {
1507     struct nl_sock *sock;
1508     int error;
1509
1510     error = nl_pool_alloc(protocol, &sock);
1511     if (error) {
1512         *replyp = NULL;
1513         return error;
1514     }
1515
1516     error = nl_sock_transact(sock, request, replyp);
1517
1518     nl_pool_release(sock);
1519     return error;
1520 }
1521
1522 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1523  * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1524  * NETLINK_GENERIC), in order, and receives responses to all of them.  Fills in
1525  * the 'error' member of each transaction with 0 if it was successful,
1526  * otherwise with a positive errno value.  If 'reply' is nonnull, then it will
1527  * be filled with the reply if the message receives a detailed reply.  In other
1528  * cases, i.e. where the request failed or had no reply beyond an indication of
1529  * success, 'reply' will be cleared if it is nonnull.
1530  *
1531  * The caller is responsible for destroying each request and reply, and the
1532  * transactions array itself.
1533  *
1534  * Before sending each message, this function will finalize nlmsg_len in each
1535  * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1536  * used for the transaction, and initialize nlmsg_seq.
1537  *
1538  * Bare Netlink is an unreliable transport protocol.  This function layers
1539  * reliable delivery and reply semantics on top of bare Netlink.  See
1540  * nl_transact() for some caveats.
1541  */
1542 void
1543 nl_transact_multiple(int protocol,
1544                      struct nl_transaction **transactions, size_t n)
1545 {
1546     struct nl_sock *sock;
1547     int error;
1548
1549     error = nl_pool_alloc(protocol, &sock);
1550     if (!error) {
1551         nl_sock_transact_multiple(sock, transactions, n);
1552         nl_pool_release(sock);
1553     } else {
1554         nl_sock_record_errors__(transactions, n, error);
1555     }
1556 }
1557
1558 \f
1559 static uint32_t
1560 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1561 {
1562     uint32_t seq = sock->next_seq;
1563
1564     sock->next_seq += n;
1565
1566     /* Make it impossible for the next request for sequence numbers to wrap
1567      * around to 0.  Start over with 1 to avoid ever using a sequence number of
1568      * 0, because the kernel uses sequence number 0 for notifications. */
1569     if (sock->next_seq >= UINT32_MAX / 2) {
1570         sock->next_seq = 1;
1571     }
1572
1573     return seq;
1574 }
1575
1576 static void
1577 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1578 {
1579     struct nlmsg_flag {
1580         unsigned int bits;
1581         const char *name;
1582     };
1583     static const struct nlmsg_flag flags[] = {
1584         { NLM_F_REQUEST, "REQUEST" },
1585         { NLM_F_MULTI, "MULTI" },
1586         { NLM_F_ACK, "ACK" },
1587         { NLM_F_ECHO, "ECHO" },
1588         { NLM_F_DUMP, "DUMP" },
1589         { NLM_F_ROOT, "ROOT" },
1590         { NLM_F_MATCH, "MATCH" },
1591         { NLM_F_ATOMIC, "ATOMIC" },
1592     };
1593     const struct nlmsg_flag *flag;
1594     uint16_t flags_left;
1595
1596     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1597                   h->nlmsg_len, h->nlmsg_type);
1598     if (h->nlmsg_type == NLMSG_NOOP) {
1599         ds_put_cstr(ds, "(no-op)");
1600     } else if (h->nlmsg_type == NLMSG_ERROR) {
1601         ds_put_cstr(ds, "(error)");
1602     } else if (h->nlmsg_type == NLMSG_DONE) {
1603         ds_put_cstr(ds, "(done)");
1604     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1605         ds_put_cstr(ds, "(overrun)");
1606     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1607         ds_put_cstr(ds, "(reserved)");
1608     } else if (protocol == NETLINK_GENERIC) {
1609         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1610     } else {
1611         ds_put_cstr(ds, "(family-defined)");
1612     }
1613     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1614     flags_left = h->nlmsg_flags;
1615     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1616         if ((flags_left & flag->bits) == flag->bits) {
1617             ds_put_format(ds, "[%s]", flag->name);
1618             flags_left &= ~flag->bits;
1619         }
1620     }
1621     if (flags_left) {
1622         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1623     }
1624     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1625                   h->nlmsg_seq, h->nlmsg_pid);
1626 }
1627
1628 static char *
1629 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1630 {
1631     struct ds ds = DS_EMPTY_INITIALIZER;
1632     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1633     if (h) {
1634         nlmsghdr_to_string(h, protocol, &ds);
1635         if (h->nlmsg_type == NLMSG_ERROR) {
1636             const struct nlmsgerr *e;
1637             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1638                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1639             if (e) {
1640                 ds_put_format(&ds, " error(%d", e->error);
1641                 if (e->error < 0) {
1642                     ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1643                 }
1644                 ds_put_cstr(&ds, ", in-reply-to(");
1645                 nlmsghdr_to_string(&e->msg, protocol, &ds);
1646                 ds_put_cstr(&ds, "))");
1647             } else {
1648                 ds_put_cstr(&ds, " error(truncated)");
1649             }
1650         } else if (h->nlmsg_type == NLMSG_DONE) {
1651             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1652             if (error) {
1653                 ds_put_format(&ds, " done(%d", *error);
1654                 if (*error < 0) {
1655                     ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1656                 }
1657                 ds_put_cstr(&ds, ")");
1658             } else {
1659                 ds_put_cstr(&ds, " done(truncated)");
1660             }
1661         } else if (protocol == NETLINK_GENERIC) {
1662             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1663             if (genl) {
1664                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1665                               genl->cmd, genl->version);
1666             }
1667         }
1668     } else {
1669         ds_put_cstr(&ds, "nl(truncated)");
1670     }
1671     return ds.string;
1672 }
1673
1674 static void
1675 log_nlmsg(const char *function, int error,
1676           const void *message, size_t size, int protocol)
1677 {
1678     struct ofpbuf buffer;
1679     char *nlmsg;
1680
1681     if (!VLOG_IS_DBG_ENABLED()) {
1682         return;
1683     }
1684
1685     ofpbuf_use_const(&buffer, message, size);
1686     nlmsg = nlmsg_to_string(&buffer, protocol);
1687     VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
1688     free(nlmsg);
1689 }