2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "netlink-socket.h"
22 #include <sys/types.h>
26 #include "dynamic-string.h"
30 #include "netlink-protocol.h"
31 #include "odp-netlink.h"
33 #include "ovs-thread.h"
34 #include "poll-loop.h"
36 #include "socket-util.h"
38 #include "openvswitch/vlog.h"
40 VLOG_DEFINE_THIS_MODULE(netlink_socket);
42 COVERAGE_DEFINE(netlink_overflow);
43 COVERAGE_DEFINE(netlink_received);
44 COVERAGE_DEFINE(netlink_recv_jumbo);
45 COVERAGE_DEFINE(netlink_sent);
47 /* Linux header file confusion causes this to be undefined. */
49 #define SOL_NETLINK 270
53 static struct ovs_mutex portid_mutex = OVS_MUTEX_INITIALIZER;
54 static uint32_t g_last_portid = 0;
56 /* Port IDs must be unique! */
59 OVS_GUARDED_BY(portid_mutex)
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);
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);
75 static int get_sock_pid_from_kernel(struct nl_sock *sock);
78 /* Netlink sockets. */
83 OVERLAPPED overlapped;
91 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
94 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
95 * of iovecs on the stack. */
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.
101 * Initialized by nl_sock_create(). */
104 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
105 static void nl_pool_release(struct nl_sock *);
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. */
111 nl_sock_create(int protocol, struct nl_sock **sockp)
113 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
114 struct nl_sock *sock;
116 struct sockaddr_nl local, remote;
118 socklen_t local_size;
122 if (ovsthread_once_start(&once)) {
123 int save_errno = errno;
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));
131 max_iovs = _XOPEN_IOV_MAX;
132 } else if (max_iovs > MAX_IOVS) {
137 ovsthread_once_done(&once);
141 sock = xmalloc(sizeof *sock);
144 sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
145 GENERIC_READ | GENERIC_WRITE,
146 FILE_SHARE_READ | FILE_SHARE_WRITE,
148 FILE_FLAG_OVERLAPPED, NULL);
150 if (sock->handle == INVALID_HANDLE_VALUE) {
151 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
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());
161 /* Initialize the type/ioctl to Generic */
162 sock->read_ioctl = OVS_IOCTL_READ;
164 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
166 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
171 sock->protocol = protocol;
174 rcvbuf = 1024 * 1024;
176 sock->rcvbuf = rcvbuf;
177 retval = get_sock_pid_from_kernel(sock);
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));
192 retval = get_socket_rcvbuf(sock->fd);
197 sock->rcvbuf = retval;
199 /* Connect to kernel (pid 0) as remote address. */
200 memset(&remote, 0, sizeof remote);
201 remote.nl_family = AF_NETLINK;
203 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
204 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
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));
214 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
215 VLOG_ERR("getsockname returned bad Netlink name");
219 sock->pid = local.nl_pid;
233 if (sock->overlapped.hEvent) {
234 CloseHandle(sock->overlapped.hEvent);
236 if (sock->handle != INVALID_HANDLE_VALUE) {
237 CloseHandle(sock->handle);
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
252 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
254 return nl_sock_create(src->protocol, sockp);
257 /* Destroys netlink socket 'sock'. */
259 nl_sock_destroy(struct nl_sock *sock)
263 if (sock->overlapped.hEvent) {
264 CloseHandle(sock->overlapped.hEvent);
266 CloseHandle(sock->handle);
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. */
279 get_sock_pid_from_kernel(struct nl_sock *sock)
285 if (!DeviceIoControl(sock->handle, OVS_IOCTL_GET_PID,
286 NULL, 0, &pid, sizeof(pid),
290 if (bytes < sizeof(pid)) {
303 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
305 struct ofpbuf request;
306 uint64_t request_stub[128];
307 struct ovs_header *ovs_header;
308 struct nlmsghdr *nlmsg;
311 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
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);
317 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
318 ovs_header->dp_ifindex = 0;
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);
323 error = nl_sock_send(sock, &request, true);
324 ofpbuf_uninit(&request);
328 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
329 * successful, otherwise a positive errno value.
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.
335 * Multicast group numbers are always positive.
337 * It is not an error to attempt to join a multicast group to which a socket
338 * already belongs. */
340 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
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);
347 sock->read_ioctl = OVS_IOCTL_READ;
348 VLOG_WARN("could not join multicast group %u (%s)",
349 multicast_group, ovs_strerror(error));
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));
365 nl_sock_subscribe_packets(struct nl_sock *sock)
369 if (sock->read_ioctl != OVS_IOCTL_READ) {
373 error = nl_sock_subscribe_packet__(sock, true);
375 VLOG_WARN("could not subscribe packets (%s)",
376 ovs_strerror(error));
379 sock->read_ioctl = OVS_IOCTL_READ_PACKET;
385 nl_sock_unsubscribe_packets(struct nl_sock *sock)
387 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET);
389 int error = nl_sock_subscribe_packet__(sock, false);
391 VLOG_WARN("could not unsubscribe to packets (%s)",
392 ovs_strerror(error));
396 sock->read_ioctl = OVS_IOCTL_READ;
401 nl_sock_subscribe_packet__(struct nl_sock *sock, bool subscribe)
403 struct ofpbuf request;
404 uint64_t request_stub[128];
405 struct ovs_header *ovs_header;
406 struct nlmsghdr *nlmsg;
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);
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);
419 error = nl_sock_send(sock, &request, true);
420 ofpbuf_uninit(&request);
425 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
426 * successful, otherwise a positive errno value.
428 * Multicast group numbers are always positive.
430 * It is not an error to attempt to leave a multicast group to which a socket
433 * On success, reading from 'sock' will still return any messages that were
434 * received on 'multicast_group' before the group was left. */
436 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
439 int error = nl_sock_mcgroup(sock, multicast_group, false);
441 VLOG_WARN("could not leave multicast group %u (%s)",
442 multicast_group, ovs_strerror(error));
445 sock->read_ioctl = OVS_IOCTL_READ;
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));
458 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
459 uint32_t nlmsg_seq, bool wait)
461 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
464 nlmsg->nlmsg_len = msg->size;
465 nlmsg->nlmsg_seq = nlmsg_seq;
466 nlmsg->nlmsg_pid = sock->pid;
472 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
473 msg->data, msg->size, NULL, 0,
476 /* XXX: Map to a more appropriate error based on GetLastError(). */
478 VLOG_DBG_RL(&rl, "fatal driver failure in write: %s",
479 ovs_lasterror_to_string());
484 retval = send(sock->fd, msg->data, msg->size,
485 wait ? 0 : MSG_DONTWAIT);
487 error = retval < 0 ? errno : 0;
488 } while (error == EINTR);
489 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
491 COVERAGE_INC(netlink_sent);
496 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
497 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
498 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
499 * sequence number, before the message is sent.
501 * Returns 0 if successful, otherwise a positive errno value. If
502 * 'wait' is true, then the send will wait until buffer space is ready;
503 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
505 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
507 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
510 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
511 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
512 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
513 * 'nlmsg_seq', before the message is sent.
515 * Returns 0 if successful, otherwise a positive errno value. If
516 * 'wait' is true, then the send will wait until buffer space is ready;
517 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
519 * This function is suitable for sending a reply to a request that was received
520 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
522 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
523 uint32_t nlmsg_seq, bool wait)
525 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
529 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
531 /* We can't accurately predict the size of the data to be received. The
532 * caller is supposed to have allocated enough space in 'buf' to handle the
533 * "typical" case. To handle exceptions, we make available enough space in
534 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
535 * figure since that's the maximum length of a Netlink attribute). */
536 struct nlmsghdr *nlmsghdr;
543 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
546 iov[0].iov_base = buf->base;
547 iov[0].iov_len = buf->allocated;
548 iov[1].iov_base = tail;
549 iov[1].iov_len = sizeof tail;
551 memset(&msg, 0, sizeof msg);
555 /* Receive a Netlink message from the kernel.
557 * This works around a kernel bug in which the kernel returns an error code
558 * as if it were the number of bytes read. It doesn't actually modify
559 * anything in the receive buffer in that case, so we can initialize the
560 * Netlink header with an impossible message length and then, upon success,
561 * check whether it changed. */
562 nlmsghdr = buf->base;
564 nlmsghdr->nlmsg_len = UINT32_MAX;
567 if (!DeviceIoControl(sock->handle, sock->read_ioctl,
568 NULL, 0, tail, sizeof tail, &bytes, NULL)) {
569 VLOG_DBG_RL(&rl, "fatal driver failure in transact: %s",
570 ovs_lasterror_to_string());
572 /* XXX: Map to a more appropriate error. */
580 if (retval >= buf->allocated) {
581 ofpbuf_reinit(buf, retval);
582 nlmsghdr = buf->base;
583 nlmsghdr->nlmsg_len = UINT32_MAX;
585 memcpy(buf->data, tail, retval);
590 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
592 error = (retval < 0 ? errno
593 : retval == 0 ? ECONNRESET /* not possible? */
594 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
596 } while (error == EINTR);
598 if (error == ENOBUFS) {
599 /* Socket receive buffer overflow dropped one or more messages that
600 * the kernel tried to send to us. */
601 COVERAGE_INC(netlink_overflow);
606 if (msg.msg_flags & MSG_TRUNC) {
607 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
612 if (retval < sizeof *nlmsghdr
613 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
614 || nlmsghdr->nlmsg_len > retval) {
615 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
616 retval, sizeof *nlmsghdr);
620 buf->size = MIN(retval, buf->allocated);
621 if (retval > buf->allocated) {
622 COVERAGE_INC(netlink_recv_jumbo);
623 ofpbuf_put(buf, tail, retval - buf->allocated);
627 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
628 COVERAGE_INC(netlink_received);
633 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
634 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
635 * EAGAIN if the 'sock' receive buffer is empty.
637 * The caller must have initialized 'buf' with an allocation of at least
638 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
639 * space for a "typical" message.
641 * On success, returns 0 and replaces 'buf''s previous content by the received
642 * message. This function expands 'buf''s allocated memory, as necessary, to
643 * hold the actual size of the received message.
645 * On failure, returns a positive errno value and clears 'buf' to zero length.
646 * 'buf' retains its previous memory allocation.
648 * Regardless of success or failure, this function resets 'buf''s headroom to
651 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
653 return nl_sock_recv__(sock, buf, wait);
657 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
662 for (i = 0; i < n; i++) {
663 struct nl_transaction *txn = transactions[i];
667 ofpbuf_clear(txn->reply);
673 nl_sock_transact_multiple__(struct nl_sock *sock,
674 struct nl_transaction **transactions, size_t n,
677 uint64_t tmp_reply_stub[1024 / 8];
678 struct nl_transaction tmp_txn;
679 struct ofpbuf tmp_reply;
682 struct iovec iovs[MAX_IOVS];
687 base_seq = nl_sock_allocate_seq(sock, n);
689 for (i = 0; i < n; i++) {
690 struct nl_transaction *txn = transactions[i];
691 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
693 nlmsg->nlmsg_len = txn->request->size;
694 nlmsg->nlmsg_seq = base_seq + i;
695 nlmsg->nlmsg_pid = sock->pid;
697 iovs[i].iov_base = txn->request->data;
698 iovs[i].iov_len = txn->request->size;
702 memset(&msg, 0, sizeof msg);
706 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
707 } while (error == EINTR);
709 for (i = 0; i < n; i++) {
710 struct nl_transaction *txn = transactions[i];
712 log_nlmsg(__func__, error, txn->request->data,
713 txn->request->size, sock->protocol);
716 COVERAGE_ADD(netlink_sent, n);
723 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
724 tmp_txn.request = NULL;
725 tmp_txn.reply = &tmp_reply;
728 struct nl_transaction *buf_txn, *txn;
731 /* Find a transaction whose buffer we can use for receiving a reply.
732 * If no such transaction is left, use tmp_txn. */
734 for (i = 0; i < n; i++) {
735 if (transactions[i]->reply) {
736 buf_txn = transactions[i];
741 /* Receive a reply. */
742 error = nl_sock_recv__(sock, buf_txn->reply, false);
744 if (error == EAGAIN) {
745 nl_sock_record_errors__(transactions, n, 0);
752 /* Match the reply up with a transaction. */
753 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
754 if (seq < base_seq || seq >= base_seq + n) {
755 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
759 txn = transactions[i];
761 /* Fill in the results for 'txn'. */
762 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
764 ofpbuf_clear(txn->reply);
767 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
768 error, ovs_strerror(txn->error));
772 if (txn->reply && txn != buf_txn) {
774 struct ofpbuf *reply = buf_txn->reply;
775 buf_txn->reply = txn->reply;
780 /* Fill in the results for transactions before 'txn'. (We have to do
781 * this after the results for 'txn' itself because of the buffer swap
783 nl_sock_record_errors__(transactions, i, 0);
787 transactions += i + 1;
791 ofpbuf_uninit(&tmp_reply);
794 uint8_t reply_buf[65536];
795 for (i = 0; i < n; i++) {
798 struct nl_transaction *txn = transactions[i];
799 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
801 ret = DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
804 reply_buf, sizeof reply_buf,
807 if (ret && reply_len == 0) {
809 * The current transaction did not produce any data to read and that
810 * is not an error as such. Continue with the remainder of the
815 ofpbuf_clear(txn->reply);
818 /* XXX: Map to a more appropriate error. */
820 VLOG_DBG_RL(&rl, "fatal driver failure: %s",
821 ovs_lasterror_to_string());
825 if (reply_len != 0) {
826 if (reply_len < sizeof *reply_nlmsg) {
827 nl_sock_record_errors__(transactions, n, 0);
828 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32
829 " for seq: %#"PRIx32, reply_len, request_nlmsg->nlmsg_seq);
833 /* Validate the sequence number in the reply. */
834 request_nlmsg = nl_msg_nlmsghdr(txn->request);
835 reply_nlmsg = (struct nlmsghdr *)reply_buf;
837 if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
838 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
839 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
840 ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
841 reply_nlmsg->nlmsg_seq);
845 /* Handle errors embedded within the netlink message. */
846 ofpbuf_use_stub(&tmp_reply, reply_buf, sizeof reply_buf);
847 tmp_reply.size = sizeof reply_buf;
848 if (nl_msg_nlmsgerr(&tmp_reply, &txn->error)) {
850 ofpbuf_clear(txn->reply);
853 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
854 error, ovs_strerror(txn->error));
859 /* Copy the reply to the buffer specified by the caller. */
860 if (reply_len > txn->reply->allocated) {
861 ofpbuf_reinit(txn->reply, reply_len);
863 memcpy(txn->reply->data, reply_buf, reply_len);
864 txn->reply->size = reply_len;
867 ofpbuf_uninit(&tmp_reply);
870 /* Count the number of successful transactions. */
876 COVERAGE_ADD(netlink_sent, n);
884 nl_sock_transact_multiple(struct nl_sock *sock,
885 struct nl_transaction **transactions, size_t n)
894 /* In theory, every request could have a 64 kB reply. But the default and
895 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
896 * be a bit below 128 kB, so that would only allow a single message in a
897 * "batch". So we assume that replies average (at most) 4 kB, which allows
898 * a good deal of batching.
900 * In practice, most of the requests that we batch either have no reply at
901 * all or a brief reply. */
902 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
903 max_batch_count = MIN(max_batch_count, max_iovs);
909 /* Batch up to 'max_batch_count' transactions. But cap it at about a
910 * page of requests total because big skbuffs are expensive to
911 * allocate in the kernel. */
912 #if defined(PAGESIZE)
913 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
915 enum { MAX_BATCH_BYTES = 4096 - 512 };
917 bytes = transactions[0]->request->size;
918 for (count = 1; count < n && count < max_batch_count; count++) {
919 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
922 bytes += transactions[count]->request->size;
925 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
926 transactions += done;
929 if (error == ENOBUFS) {
930 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
932 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
933 nl_sock_record_errors__(transactions, n, error);
934 if (error != EAGAIN) {
935 /* A fatal error has occurred. Abort the rest of
944 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
945 struct ofpbuf **replyp)
947 struct nl_transaction *transactionp;
948 struct nl_transaction transaction;
950 transaction.request = CONST_CAST(struct ofpbuf *, request);
951 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
952 transactionp = &transaction;
954 nl_sock_transact_multiple(sock, &transactionp, 1);
957 if (transaction.error) {
958 ofpbuf_delete(transaction.reply);
961 *replyp = transaction.reply;
965 return transaction.error;
968 /* Drain all the messages currently in 'sock''s receive queue. */
970 nl_sock_drain(struct nl_sock *sock)
975 return drain_rcvbuf(sock->fd);
979 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
980 * Netlink socket created with the given 'protocol', and initializes 'dump' to
981 * reflect the state of the operation.
983 * 'request' must contain a Netlink message. Before sending the message,
984 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
985 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
988 * The design of this Netlink socket library ensures that the dump is reliable.
990 * This function provides no status indication. nl_dump_done() provides an
991 * error status for the entire dump operation.
993 * The caller must eventually destroy 'request'.
996 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
998 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
1000 ovs_mutex_init(&dump->mutex);
1001 ovs_mutex_lock(&dump->mutex);
1002 dump->status = nl_pool_alloc(protocol, &dump->sock);
1003 if (!dump->status) {
1004 dump->status = nl_sock_send__(dump->sock, request,
1005 nl_sock_allocate_seq(dump->sock, 1),
1008 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
1009 ovs_mutex_unlock(&dump->mutex);
1013 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
1014 OVS_REQUIRES(dump->mutex)
1016 struct nlmsghdr *nlmsghdr;
1019 while (!buffer->size) {
1020 error = nl_sock_recv__(dump->sock, buffer, false);
1022 /* The kernel never blocks providing the results of a dump, so
1023 * error == EAGAIN means that we've read the whole thing, and
1024 * therefore transform it into EOF. (The kernel always provides
1025 * NLMSG_DONE as a sentinel. Some other thread must have received
1026 * that already but not yet signaled it in 'status'.)
1028 * Any other error is just an error. */
1029 return error == EAGAIN ? EOF : error;
1032 nlmsghdr = nl_msg_nlmsghdr(buffer);
1033 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
1034 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
1035 nlmsghdr->nlmsg_seq, dump->nl_seq);
1036 ofpbuf_clear(buffer);
1040 if (nl_msg_nlmsgerr(buffer, &error) && error) {
1041 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
1042 ovs_strerror(error));
1043 ofpbuf_clear(buffer);
1051 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1053 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1055 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1057 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1064 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1065 * have been initialized with nl_dump_start(), and 'buffer' must have been
1066 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1068 * If successful, returns true and points 'reply->data' and
1069 * 'reply->size' to the message that was retrieved. The caller must not
1070 * modify 'reply' (because it points within 'buffer', which will be used by
1071 * future calls to this function).
1073 * On failure, returns false and sets 'reply->data' to NULL and
1074 * 'reply->size' to 0. Failure might indicate an actual error or merely
1075 * the end of replies. An error status for the entire dump operation is
1076 * provided when it is completed by calling nl_dump_done().
1078 * Multiple threads may call this function, passing the same nl_dump, however
1079 * each must provide independent buffers. This function may cache multiple
1080 * replies in the buffer, and these will be processed before more replies are
1081 * fetched. When this function returns false, other threads may continue to
1082 * process replies in their buffers, but they will not fetch more replies.
1085 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1089 /* If the buffer is empty, refill it.
1091 * If the buffer is not empty, we don't check the dump's status.
1092 * Otherwise, we could end up skipping some of the dump results if thread A
1093 * hits EOF while thread B is in the midst of processing a batch. */
1094 if (!buffer->size) {
1095 ovs_mutex_lock(&dump->mutex);
1096 if (!dump->status) {
1097 /* Take the mutex here to avoid an in-kernel race. If two threads
1098 * try to read from a Netlink dump socket at once, then the socket
1099 * error can be set to EINVAL, which will be encountered on the
1100 * next recv on that socket, which could be anywhere due to the way
1101 * that we pool Netlink sockets. Serializing the recv calls avoids
1103 dump->status = nl_dump_refill(dump, buffer);
1105 retval = dump->status;
1106 ovs_mutex_unlock(&dump->mutex);
1109 /* Fetch the next message from the buffer. */
1111 retval = nl_dump_next__(reply, buffer);
1113 /* Record 'retval' as the dump status, but don't overwrite an error
1115 ovs_mutex_lock(&dump->mutex);
1116 if (dump->status <= 0) {
1117 dump->status = retval;
1119 ovs_mutex_unlock(&dump->mutex);
1130 /* Completes Netlink dump operation 'dump', which must have been initialized
1131 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1132 * otherwise a positive errno value describing the problem. */
1134 nl_dump_done(struct nl_dump *dump)
1138 ovs_mutex_lock(&dump->mutex);
1139 status = dump->status;
1140 ovs_mutex_unlock(&dump->mutex);
1142 /* Drain any remaining messages that the client didn't read. Otherwise the
1143 * kernel will continue to queue them up and waste buffer space.
1145 * XXX We could just destroy and discard the socket in this case. */
1147 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1148 struct ofpbuf reply, buf;
1150 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1151 while (nl_dump_next(dump, &reply, &buf)) {
1152 /* Nothing to do. */
1154 ofpbuf_uninit(&buf);
1156 ovs_mutex_lock(&dump->mutex);
1157 status = dump->status;
1158 ovs_mutex_unlock(&dump->mutex);
1162 nl_pool_release(dump->sock);
1163 ovs_mutex_destroy(&dump->mutex);
1165 return status == EOF ? 0 : status;
1169 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1170 * an event or a packet is ready to be read. Once the I/O is completed
1171 * the overlapped structure event associated with the pending I/O will be set
1174 pend_io_request(struct nl_sock *sock)
1176 struct ofpbuf request;
1177 uint64_t request_stub[128];
1178 struct ovs_header *ovs_header;
1179 struct nlmsghdr *nlmsg;
1184 OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
1185 uint16_t cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ;
1187 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET ||
1188 sock->read_ioctl == OVS_IOCTL_READ_EVENT);
1189 if (sock->read_ioctl == OVS_IOCTL_READ_EVENT) {
1190 cmd = OVS_CTRL_CMD_WIN_PEND_REQ;
1193 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1194 sizeof (struct ovs_header);
1196 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1198 seq = nl_sock_allocate_seq(sock, 1);
1199 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1200 cmd, OVS_WIN_CONTROL_VERSION);
1201 nlmsg = nl_msg_nlmsghdr(&request);
1202 nlmsg->nlmsg_seq = seq;
1203 nlmsg->nlmsg_pid = sock->pid;
1205 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1206 ovs_header->dp_ifindex = 0;
1208 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1209 request.data, request.size,
1210 NULL, 0, &bytes, overlapped)) {
1211 error = GetLastError();
1212 /* Check if the I/O got pended */
1213 if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1214 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1222 ofpbuf_uninit(&request);
1227 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1228 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'.
1229 * On Windows, 'sock' is not treated as const, and may be modified. */
1231 nl_sock_wait(const struct nl_sock *sock, short int events)
1234 if (sock->overlapped.Internal != STATUS_PENDING) {
1235 int ret = pend_io_request(CONST_CAST(struct nl_sock *, sock));
1237 poll_wevent_wait(sock->overlapped.hEvent);
1239 poll_immediate_wake();
1242 poll_wevent_wait(sock->overlapped.hEvent);
1245 poll_fd_wait(sock->fd, events);
1250 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1251 * that can't use nl_sock_wait().
1253 * It's a little tricky to use the returned fd correctly, because nl_sock does
1254 * "copy on write" to allow a single nl_sock to be used for notifications,
1255 * transactions, and dumps. If 'sock' is used only for notifications and
1256 * transactions (and never for dump) then the usage is safe. */
1258 nl_sock_fd(const struct nl_sock *sock)
1264 /* Returns the PID associated with this socket. */
1266 nl_sock_pid(const struct nl_sock *sock)
1271 /* Miscellaneous. */
1273 struct genl_family {
1274 struct hmap_node hmap_node;
1279 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1281 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1282 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1283 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1286 static struct genl_family *
1287 find_genl_family_by_id(uint16_t id)
1289 struct genl_family *family;
1291 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1293 if (family->id == id) {
1301 define_genl_family(uint16_t id, const char *name)
1303 struct genl_family *family = find_genl_family_by_id(id);
1306 if (!strcmp(family->name, name)) {
1311 family = xmalloc(sizeof *family);
1313 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1315 family->name = xstrdup(name);
1319 genl_family_to_name(uint16_t id)
1321 if (id == GENL_ID_CTRL) {
1324 struct genl_family *family = find_genl_family_by_id(id);
1325 return family ? family->name : "unknown";
1331 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1332 struct ofpbuf **replyp)
1334 struct nl_sock *sock;
1335 struct ofpbuf request, *reply;
1339 error = nl_sock_create(NETLINK_GENERIC, &sock);
1344 ofpbuf_init(&request, 0);
1345 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1346 CTRL_CMD_GETFAMILY, 1);
1347 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1348 error = nl_sock_transact(sock, &request, &reply);
1349 ofpbuf_uninit(&request);
1351 nl_sock_destroy(sock);
1355 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1356 family_policy, attrs, ARRAY_SIZE(family_policy))
1357 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1358 nl_sock_destroy(sock);
1359 ofpbuf_delete(reply);
1363 nl_sock_destroy(sock);
1369 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1370 struct ofpbuf **replyp)
1372 struct nlmsghdr *nlmsg;
1373 struct ofpbuf *reply;
1376 const char *family_name;
1377 uint32_t family_version;
1378 uint32_t family_attrmax;
1379 uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1380 const char *mcgrp_name = NULL;
1383 reply = ofpbuf_new(1024);
1385 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1386 if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1387 family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1388 family_name = OVS_WIN_CONTROL_FAMILY;
1389 family_version = OVS_WIN_CONTROL_VERSION;
1390 family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1391 } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1392 family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1393 family_name = OVS_DATAPATH_FAMILY;
1394 family_version = OVS_DATAPATH_VERSION;
1395 family_attrmax = OVS_DP_ATTR_MAX;
1396 } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1397 family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1398 family_name = OVS_PACKET_FAMILY;
1399 family_version = OVS_PACKET_VERSION;
1400 family_attrmax = OVS_PACKET_ATTR_MAX;
1401 } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1402 family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1403 family_name = OVS_VPORT_FAMILY;
1404 family_version = OVS_VPORT_VERSION;
1405 family_attrmax = OVS_VPORT_ATTR_MAX;
1406 mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1407 mcgrp_name = OVS_VPORT_MCGROUP;
1408 } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1409 family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1410 family_name = OVS_FLOW_FAMILY;
1411 family_version = OVS_FLOW_VERSION;
1412 family_attrmax = OVS_FLOW_ATTR_MAX;
1413 } else if (!strcmp(name, OVS_WIN_NETDEV_FAMILY)) {
1414 family_id = OVS_WIN_NL_NETDEV_FAMILY_ID;
1415 family_name = OVS_WIN_NETDEV_FAMILY;
1416 family_version = OVS_WIN_NETDEV_VERSION;
1417 family_attrmax = OVS_WIN_NETDEV_ATTR_MAX;
1419 ofpbuf_delete(reply);
1423 nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1424 CTRL_CMD_NEWFAMILY, family_version);
1425 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1426 * callers do not seem to need them. */
1427 nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1428 nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1429 nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1430 nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1432 if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1433 size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1434 size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1435 OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1436 nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1437 ovs_assert(mcgrp_name != NULL);
1438 nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1439 nl_msg_end_nested(reply, mcgrp_ofs2);
1440 nl_msg_end_nested(reply, mcgrp_ofs1);
1443 /* Set the total length of the netlink message. */
1444 nlmsg = nl_msg_nlmsghdr(reply);
1445 nlmsg->nlmsg_len = reply->size;
1447 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1448 family_policy, attrs, ARRAY_SIZE(family_policy))
1449 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1450 ofpbuf_delete(reply);
1459 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1460 * When successful, writes its result to 'multicast_group' and returns 0.
1461 * Otherwise, clears 'multicast_group' and returns a positive error code.
1464 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1465 unsigned int *multicast_group)
1467 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1468 const struct nlattr *mc;
1469 struct ofpbuf *reply;
1473 *multicast_group = 0;
1474 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1479 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1484 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1485 static const struct nl_policy mc_policy[] = {
1486 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1487 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1490 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1491 const char *mc_name;
1493 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1498 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1499 if (!strcmp(group_name, mc_name)) {
1501 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1509 ofpbuf_delete(reply);
1513 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1514 * number and stores it in '*number'. If successful, returns 0 and the caller
1515 * may use '*number' as the family number. On failure, returns a positive
1516 * errno value and '*number' caches the errno value. */
1518 nl_lookup_genl_family(const char *name, int *number)
1521 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1522 struct ofpbuf *reply;
1525 error = do_lookup_genl_family(name, attrs, &reply);
1527 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1528 define_genl_family(*number, name);
1532 ofpbuf_delete(reply);
1534 ovs_assert(*number != 0);
1536 return *number > 0 ? 0 : -*number;
1540 struct nl_sock *socks[16];
1544 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1545 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1548 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1550 struct nl_sock *sock = NULL;
1551 struct nl_pool *pool;
1553 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1555 ovs_mutex_lock(&pool_mutex);
1556 pool = &pools[protocol];
1558 sock = pool->socks[--pool->n];
1560 ovs_mutex_unlock(&pool_mutex);
1566 return nl_sock_create(protocol, sockp);
1571 nl_pool_release(struct nl_sock *sock)
1574 struct nl_pool *pool = &pools[sock->protocol];
1576 ovs_mutex_lock(&pool_mutex);
1577 if (pool->n < ARRAY_SIZE(pool->socks)) {
1578 pool->socks[pool->n++] = sock;
1581 ovs_mutex_unlock(&pool_mutex);
1583 nl_sock_destroy(sock);
1587 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1588 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1589 * successful, returns 0. On failure, returns a positive errno value.
1591 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1592 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1593 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1594 * reply, if any, is discarded.
1596 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1597 * match msg->size, nlmsg_pid will be set to the pid of the socket used
1598 * for sending the request, and nlmsg_seq will be initialized.
1600 * The caller is responsible for destroying 'request'.
1602 * Bare Netlink is an unreliable transport protocol. This function layers
1603 * reliable delivery and reply semantics on top of bare Netlink.
1605 * In Netlink, sending a request to the kernel is reliable enough, because the
1606 * kernel will tell us if the message cannot be queued (and we will in that
1607 * case put it on the transmit queue and wait until it can be delivered).
1609 * Receiving the reply is the real problem: if the socket buffer is full when
1610 * the kernel tries to send the reply, the reply will be dropped. However, the
1611 * kernel sets a flag that a reply has been dropped. The next call to recv
1612 * then returns ENOBUFS. We can then re-send the request.
1616 * 1. Netlink depends on sequence numbers to match up requests and
1617 * replies. The sender of a request supplies a sequence number, and
1618 * the reply echos back that sequence number.
1620 * This is fine, but (1) some kernel netlink implementations are
1621 * broken, in that they fail to echo sequence numbers and (2) this
1622 * function will drop packets with non-matching sequence numbers, so
1623 * that only a single request can be usefully transacted at a time.
1625 * 2. Resending the request causes it to be re-executed, so the request
1626 * needs to be idempotent.
1629 nl_transact(int protocol, const struct ofpbuf *request,
1630 struct ofpbuf **replyp)
1632 struct nl_sock *sock;
1635 error = nl_pool_alloc(protocol, &sock);
1641 error = nl_sock_transact(sock, request, replyp);
1643 nl_pool_release(sock);
1647 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1648 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1649 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1650 * the 'error' member of each transaction with 0 if it was successful,
1651 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1652 * be filled with the reply if the message receives a detailed reply. In other
1653 * cases, i.e. where the request failed or had no reply beyond an indication of
1654 * success, 'reply' will be cleared if it is nonnull.
1656 * The caller is responsible for destroying each request and reply, and the
1657 * transactions array itself.
1659 * Before sending each message, this function will finalize nlmsg_len in each
1660 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1661 * used for the transaction, and initialize nlmsg_seq.
1663 * Bare Netlink is an unreliable transport protocol. This function layers
1664 * reliable delivery and reply semantics on top of bare Netlink. See
1665 * nl_transact() for some caveats.
1668 nl_transact_multiple(int protocol,
1669 struct nl_transaction **transactions, size_t n)
1671 struct nl_sock *sock;
1674 error = nl_pool_alloc(protocol, &sock);
1676 nl_sock_transact_multiple(sock, transactions, n);
1677 nl_pool_release(sock);
1679 nl_sock_record_errors__(transactions, n, error);
1685 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1687 uint32_t seq = sock->next_seq;
1689 sock->next_seq += n;
1691 /* Make it impossible for the next request for sequence numbers to wrap
1692 * around to 0. Start over with 1 to avoid ever using a sequence number of
1693 * 0, because the kernel uses sequence number 0 for notifications. */
1694 if (sock->next_seq >= UINT32_MAX / 2) {
1702 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1708 static const struct nlmsg_flag flags[] = {
1709 { NLM_F_REQUEST, "REQUEST" },
1710 { NLM_F_MULTI, "MULTI" },
1711 { NLM_F_ACK, "ACK" },
1712 { NLM_F_ECHO, "ECHO" },
1713 { NLM_F_DUMP, "DUMP" },
1714 { NLM_F_ROOT, "ROOT" },
1715 { NLM_F_MATCH, "MATCH" },
1716 { NLM_F_ATOMIC, "ATOMIC" },
1718 const struct nlmsg_flag *flag;
1719 uint16_t flags_left;
1721 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1722 h->nlmsg_len, h->nlmsg_type);
1723 if (h->nlmsg_type == NLMSG_NOOP) {
1724 ds_put_cstr(ds, "(no-op)");
1725 } else if (h->nlmsg_type == NLMSG_ERROR) {
1726 ds_put_cstr(ds, "(error)");
1727 } else if (h->nlmsg_type == NLMSG_DONE) {
1728 ds_put_cstr(ds, "(done)");
1729 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1730 ds_put_cstr(ds, "(overrun)");
1731 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1732 ds_put_cstr(ds, "(reserved)");
1733 } else if (protocol == NETLINK_GENERIC) {
1734 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1736 ds_put_cstr(ds, "(family-defined)");
1738 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1739 flags_left = h->nlmsg_flags;
1740 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1741 if ((flags_left & flag->bits) == flag->bits) {
1742 ds_put_format(ds, "[%s]", flag->name);
1743 flags_left &= ~flag->bits;
1747 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1749 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1750 h->nlmsg_seq, h->nlmsg_pid);
1754 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1756 struct ds ds = DS_EMPTY_INITIALIZER;
1757 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1759 nlmsghdr_to_string(h, protocol, &ds);
1760 if (h->nlmsg_type == NLMSG_ERROR) {
1761 const struct nlmsgerr *e;
1762 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1763 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1765 ds_put_format(&ds, " error(%d", e->error);
1767 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1769 ds_put_cstr(&ds, ", in-reply-to(");
1770 nlmsghdr_to_string(&e->msg, protocol, &ds);
1771 ds_put_cstr(&ds, "))");
1773 ds_put_cstr(&ds, " error(truncated)");
1775 } else if (h->nlmsg_type == NLMSG_DONE) {
1776 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1778 ds_put_format(&ds, " done(%d", *error);
1780 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1782 ds_put_cstr(&ds, ")");
1784 ds_put_cstr(&ds, " done(truncated)");
1786 } else if (protocol == NETLINK_GENERIC) {
1787 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1789 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1790 genl->cmd, genl->version);
1794 ds_put_cstr(&ds, "nl(truncated)");
1800 log_nlmsg(const char *function, int error,
1801 const void *message, size_t size, int protocol)
1803 struct ofpbuf buffer;
1806 if (!VLOG_IS_DBG_ENABLED()) {
1810 ofpbuf_use_const(&buffer, message, size);
1811 nlmsg = nlmsg_to_string(&buffer, protocol);
1812 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);