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