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