2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 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 "openvswitch/dynamic-string.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"
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
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);
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);
61 static int get_sock_pid_from_kernel(struct nl_sock *sock);
64 /* Netlink sockets. */
69 OVERLAPPED overlapped;
77 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
80 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
81 * of iovecs on the stack. */
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.
87 * Initialized by nl_sock_create(). */
90 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
91 static void nl_pool_release(struct nl_sock *);
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. */
97 nl_sock_create(int protocol, struct nl_sock **sockp)
99 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
100 struct nl_sock *sock;
102 struct sockaddr_nl local, remote;
104 socklen_t local_size;
108 if (ovsthread_once_start(&once)) {
109 int save_errno = errno;
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));
117 max_iovs = _XOPEN_IOV_MAX;
118 } else if (max_iovs > MAX_IOVS) {
123 ovsthread_once_done(&once);
127 sock = xmalloc(sizeof *sock);
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,
135 FILE_FLAG_OVERLAPPED, NULL);
137 if (sock->handle == INVALID_HANDLE_VALUE) {
138 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
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());
148 /* Initialize the type/ioctl to Generic */
149 sock->read_ioctl = OVS_IOCTL_READ;
151 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
153 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
158 sock->protocol = protocol;
161 rcvbuf = 1024 * 1024;
163 sock->rcvbuf = rcvbuf;
164 retval = get_sock_pid_from_kernel(sock);
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));
179 retval = get_socket_rcvbuf(sock->fd);
184 sock->rcvbuf = retval;
187 /* Connect to kernel (pid 0) as remote address. */
188 memset(&remote, 0, sizeof remote);
189 remote.nl_family = AF_NETLINK;
191 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
192 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
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));
202 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
203 VLOG_ERR("getsockname returned bad Netlink name");
207 sock->pid = local.nl_pid;
221 if (sock->overlapped.hEvent) {
222 CloseHandle(sock->overlapped.hEvent);
224 if (sock->handle != INVALID_HANDLE_VALUE) {
225 CloseHandle(sock->handle);
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
240 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
242 return nl_sock_create(src->protocol, sockp);
245 /* Destroys netlink socket 'sock'. */
247 nl_sock_destroy(struct nl_sock *sock)
251 if (sock->overlapped.hEvent) {
252 CloseHandle(sock->overlapped.hEvent);
254 CloseHandle(sock->handle);
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. */
267 get_sock_pid_from_kernel(struct nl_sock *sock)
273 if (!DeviceIoControl(sock->handle, OVS_IOCTL_GET_PID,
274 NULL, 0, &pid, sizeof(pid),
278 if (bytes < sizeof(pid)) {
291 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
293 struct ofpbuf request;
294 uint64_t request_stub[128];
295 struct ovs_header *ovs_header;
296 struct nlmsghdr *nlmsg;
299 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
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);
305 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
306 ovs_header->dp_ifindex = 0;
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);
311 error = nl_sock_send(sock, &request, true);
312 ofpbuf_uninit(&request);
316 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
317 * successful, otherwise a positive errno value.
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.
323 * Multicast group numbers are always positive.
325 * It is not an error to attempt to join a multicast group to which a socket
326 * already belongs. */
328 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
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);
335 sock->read_ioctl = OVS_IOCTL_READ;
336 VLOG_WARN("could not join multicast group %u (%s)",
337 multicast_group, ovs_strerror(error));
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));
353 nl_sock_subscribe_packets(struct nl_sock *sock)
357 if (sock->read_ioctl != OVS_IOCTL_READ) {
361 error = nl_sock_subscribe_packet__(sock, true);
363 VLOG_WARN("could not subscribe packets (%s)",
364 ovs_strerror(error));
367 sock->read_ioctl = OVS_IOCTL_READ_PACKET;
373 nl_sock_unsubscribe_packets(struct nl_sock *sock)
375 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET);
377 int error = nl_sock_subscribe_packet__(sock, false);
379 VLOG_WARN("could not unsubscribe to packets (%s)",
380 ovs_strerror(error));
384 sock->read_ioctl = OVS_IOCTL_READ;
389 nl_sock_subscribe_packet__(struct nl_sock *sock, bool subscribe)
391 struct ofpbuf request;
392 uint64_t request_stub[128];
393 struct ovs_header *ovs_header;
394 struct nlmsghdr *nlmsg;
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);
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);
407 error = nl_sock_send(sock, &request, true);
408 ofpbuf_uninit(&request);
413 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
414 * successful, otherwise a positive errno value.
416 * Multicast group numbers are always positive.
418 * It is not an error to attempt to leave a multicast group to which a socket
421 * On success, reading from 'sock' will still return any messages that were
422 * received on 'multicast_group' before the group was left. */
424 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
427 int error = nl_sock_mcgroup(sock, multicast_group, false);
429 VLOG_WARN("could not leave multicast group %u (%s)",
430 multicast_group, ovs_strerror(error));
433 sock->read_ioctl = OVS_IOCTL_READ;
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));
446 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
447 uint32_t nlmsg_seq, bool wait)
449 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
452 nlmsg->nlmsg_len = msg->size;
453 nlmsg->nlmsg_seq = nlmsg_seq;
454 nlmsg->nlmsg_pid = sock->pid;
460 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
461 msg->data, msg->size, NULL, 0,
464 /* XXX: Map to a more appropriate error based on GetLastError(). */
466 VLOG_DBG_RL(&rl, "fatal driver failure in write: %s",
467 ovs_lasterror_to_string());
472 retval = send(sock->fd, msg->data, msg->size,
473 wait ? 0 : MSG_DONTWAIT);
475 error = retval < 0 ? errno : 0;
476 } while (error == EINTR);
477 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
479 COVERAGE_INC(netlink_sent);
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.
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. */
493 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
495 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
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.
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.
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. */
510 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
511 uint32_t nlmsg_seq, bool wait)
513 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
517 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
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;
531 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
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;
539 memset(&msg, 0, sizeof msg);
543 /* Receive a Netlink message from the kernel.
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;
552 nlmsghdr->nlmsg_len = UINT32_MAX;
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());
560 /* XXX: Map to a more appropriate error. */
568 if (retval >= buf->allocated) {
569 ofpbuf_reinit(buf, retval);
570 nlmsghdr = buf->base;
571 nlmsghdr->nlmsg_len = UINT32_MAX;
573 memcpy(buf->data, tail, retval);
578 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
580 error = (retval < 0 ? errno
581 : retval == 0 ? ECONNRESET /* not possible? */
582 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
584 } while (error == EINTR);
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);
594 if (msg.msg_flags & MSG_TRUNC) {
595 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
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);
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);
615 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
616 COVERAGE_INC(netlink_received);
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.
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.
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.
633 * On failure, returns a positive errno value and clears 'buf' to zero length.
634 * 'buf' retains its previous memory allocation.
636 * Regardless of success or failure, this function resets 'buf''s headroom to
639 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
641 return nl_sock_recv__(sock, buf, wait);
645 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
650 for (i = 0; i < n; i++) {
651 struct nl_transaction *txn = transactions[i];
655 ofpbuf_clear(txn->reply);
661 nl_sock_transact_multiple__(struct nl_sock *sock,
662 struct nl_transaction **transactions, size_t n,
665 uint64_t tmp_reply_stub[1024 / 8];
666 struct nl_transaction tmp_txn;
667 struct ofpbuf tmp_reply;
670 struct iovec iovs[MAX_IOVS];
675 base_seq = nl_sock_allocate_seq(sock, n);
677 for (i = 0; i < n; i++) {
678 struct nl_transaction *txn = transactions[i];
679 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
681 nlmsg->nlmsg_len = txn->request->size;
682 nlmsg->nlmsg_seq = base_seq + i;
683 nlmsg->nlmsg_pid = sock->pid;
685 iovs[i].iov_base = txn->request->data;
686 iovs[i].iov_len = txn->request->size;
690 memset(&msg, 0, sizeof msg);
694 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
695 } while (error == EINTR);
697 for (i = 0; i < n; i++) {
698 struct nl_transaction *txn = transactions[i];
700 log_nlmsg(__func__, error, txn->request->data,
701 txn->request->size, sock->protocol);
704 COVERAGE_ADD(netlink_sent, n);
711 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
712 tmp_txn.request = NULL;
713 tmp_txn.reply = &tmp_reply;
716 struct nl_transaction *buf_txn, *txn;
719 /* Find a transaction whose buffer we can use for receiving a reply.
720 * If no such transaction is left, use tmp_txn. */
722 for (i = 0; i < n; i++) {
723 if (transactions[i]->reply) {
724 buf_txn = transactions[i];
729 /* Receive a reply. */
730 error = nl_sock_recv__(sock, buf_txn->reply, false);
732 if (error == EAGAIN) {
733 nl_sock_record_errors__(transactions, n, 0);
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);
747 txn = transactions[i];
749 /* Fill in the results for 'txn'. */
750 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
752 ofpbuf_clear(txn->reply);
755 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
756 error, ovs_strerror(txn->error));
760 if (txn->reply && txn != buf_txn) {
762 struct ofpbuf *reply = buf_txn->reply;
763 buf_txn->reply = txn->reply;
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
771 nl_sock_record_errors__(transactions, i, 0);
775 transactions += i + 1;
779 ofpbuf_uninit(&tmp_reply);
782 uint8_t reply_buf[65536];
783 for (i = 0; i < n; i++) {
786 struct nl_transaction *txn = transactions[i];
787 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
789 ret = DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
792 reply_buf, sizeof reply_buf,
795 if (ret && reply_len == 0) {
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
803 ofpbuf_clear(txn->reply);
806 /* XXX: Map to a more appropriate error. */
808 VLOG_DBG_RL(&rl, "fatal driver failure: %s",
809 ovs_lasterror_to_string());
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);
821 /* Validate the sequence number in the reply. */
822 request_nlmsg = nl_msg_nlmsghdr(txn->request);
823 reply_nlmsg = (struct nlmsghdr *)reply_buf;
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);
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)) {
838 ofpbuf_clear(txn->reply);
841 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
842 error, ovs_strerror(txn->error));
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);
851 memcpy(txn->reply->data, reply_buf, reply_len);
852 txn->reply->size = reply_len;
855 ofpbuf_uninit(&tmp_reply);
858 /* Count the number of successful transactions. */
864 COVERAGE_ADD(netlink_sent, n);
872 nl_sock_transact_multiple(struct nl_sock *sock,
873 struct nl_transaction **transactions, size_t n)
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.
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);
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) };
903 enum { MAX_BATCH_BYTES = 4096 - 512 };
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) {
910 bytes += transactions[count]->request->size;
913 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
914 transactions += done;
917 if (error == ENOBUFS) {
918 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
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
932 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
933 struct ofpbuf **replyp)
935 struct nl_transaction *transactionp;
936 struct nl_transaction transaction;
938 transaction.request = CONST_CAST(struct ofpbuf *, request);
939 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
940 transactionp = &transaction;
942 nl_sock_transact_multiple(sock, &transactionp, 1);
945 if (transaction.error) {
946 ofpbuf_delete(transaction.reply);
949 *replyp = transaction.reply;
953 return transaction.error;
956 /* Drain all the messages currently in 'sock''s receive queue. */
958 nl_sock_drain(struct nl_sock *sock)
963 return drain_rcvbuf(sock->fd);
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.
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
976 * The design of this Netlink socket library ensures that the dump is reliable.
978 * This function provides no status indication. nl_dump_done() provides an
979 * error status for the entire dump operation.
981 * The caller must eventually destroy 'request'.
984 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
986 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
988 ovs_mutex_init(&dump->mutex);
989 ovs_mutex_lock(&dump->mutex);
990 dump->status = nl_pool_alloc(protocol, &dump->sock);
992 dump->status = nl_sock_send__(dump->sock, request,
993 nl_sock_allocate_seq(dump->sock, 1),
996 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
997 ovs_mutex_unlock(&dump->mutex);
1001 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
1002 OVS_REQUIRES(dump->mutex)
1004 struct nlmsghdr *nlmsghdr;
1007 while (!buffer->size) {
1008 error = nl_sock_recv__(dump->sock, buffer, false);
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'.)
1016 * Any other error is just an error. */
1017 return error == EAGAIN ? EOF : error;
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);
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);
1039 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1041 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1043 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1045 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
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.
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).
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().
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.
1073 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1077 /* If the buffer is empty, refill it.
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
1091 dump->status = nl_dump_refill(dump, buffer);
1093 retval = dump->status;
1094 ovs_mutex_unlock(&dump->mutex);
1097 /* Fetch the next message from the buffer. */
1099 retval = nl_dump_next__(reply, buffer);
1101 /* Record 'retval' as the dump status, but don't overwrite an error
1103 ovs_mutex_lock(&dump->mutex);
1104 if (dump->status <= 0) {
1105 dump->status = retval;
1107 ovs_mutex_unlock(&dump->mutex);
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. */
1122 nl_dump_done(struct nl_dump *dump)
1126 ovs_mutex_lock(&dump->mutex);
1127 status = dump->status;
1128 ovs_mutex_unlock(&dump->mutex);
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.
1133 * XXX We could just destroy and discard the socket in this case. */
1135 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1136 struct ofpbuf reply, buf;
1138 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1139 while (nl_dump_next(dump, &reply, &buf)) {
1140 /* Nothing to do. */
1142 ofpbuf_uninit(&buf);
1144 ovs_mutex_lock(&dump->mutex);
1145 status = dump->status;
1146 ovs_mutex_unlock(&dump->mutex);
1150 nl_pool_release(dump->sock);
1151 ovs_mutex_destroy(&dump->mutex);
1153 return status == EOF ? 0 : status;
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
1162 pend_io_request(struct nl_sock *sock)
1164 struct ofpbuf request;
1165 uint64_t request_stub[128];
1166 struct ovs_header *ovs_header;
1167 struct nlmsghdr *nlmsg;
1172 OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
1173 uint16_t cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ;
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;
1181 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1182 sizeof (struct ovs_header);
1184 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
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;
1193 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1194 ovs_header->dp_ifindex = 0;
1195 nlmsg->nlmsg_len = request.size;
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));
1211 ofpbuf_uninit(&request);
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. */
1220 nl_sock_wait(const struct nl_sock *sock, short int events)
1223 if (sock->overlapped.Internal != STATUS_PENDING) {
1224 int ret = pend_io_request(CONST_CAST(struct nl_sock *, sock));
1226 poll_wevent_wait(sock->overlapped.hEvent);
1228 poll_immediate_wake();
1231 poll_wevent_wait(sock->overlapped.hEvent);
1234 poll_fd_wait(sock->fd, events);
1239 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1240 * that can't use nl_sock_wait().
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. */
1247 nl_sock_fd(const struct nl_sock *sock)
1253 /* Returns the PID associated with this socket. */
1255 nl_sock_pid(const struct nl_sock *sock)
1260 /* Miscellaneous. */
1262 struct genl_family {
1263 struct hmap_node hmap_node;
1268 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
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},
1275 static struct genl_family *
1276 find_genl_family_by_id(uint16_t id)
1278 struct genl_family *family;
1280 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1282 if (family->id == id) {
1290 define_genl_family(uint16_t id, const char *name)
1292 struct genl_family *family = find_genl_family_by_id(id);
1295 if (!strcmp(family->name, name)) {
1300 family = xmalloc(sizeof *family);
1302 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1304 family->name = xstrdup(name);
1308 genl_family_to_name(uint16_t id)
1310 if (id == GENL_ID_CTRL) {
1313 struct genl_family *family = find_genl_family_by_id(id);
1314 return family ? family->name : "unknown";
1320 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1321 struct ofpbuf **replyp)
1323 struct nl_sock *sock;
1324 struct ofpbuf request, *reply;
1328 error = nl_sock_create(NETLINK_GENERIC, &sock);
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);
1340 nl_sock_destroy(sock);
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);
1352 nl_sock_destroy(sock);
1358 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1359 struct ofpbuf **replyp)
1361 struct nlmsghdr *nlmsg;
1362 struct ofpbuf *reply;
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;
1372 reply = ofpbuf_new(1024);
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;
1408 ofpbuf_delete(reply);
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);
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);
1432 /* Set the total length of the netlink message. */
1433 nlmsg = nl_msg_nlmsghdr(reply);
1434 nlmsg->nlmsg_len = reply->size;
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);
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.
1453 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1454 unsigned int *multicast_group)
1456 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1457 const struct nlattr *mc;
1458 struct ofpbuf *reply;
1462 *multicast_group = 0;
1463 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1468 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
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},
1479 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1480 const char *mc_name;
1482 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1487 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1488 if (!strcmp(group_name, mc_name)) {
1490 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1498 ofpbuf_delete(reply);
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. */
1507 nl_lookup_genl_family(const char *name, int *number)
1510 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1511 struct ofpbuf *reply;
1514 error = do_lookup_genl_family(name, attrs, &reply);
1516 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1517 define_genl_family(*number, name);
1521 ofpbuf_delete(reply);
1523 ovs_assert(*number != 0);
1525 return *number > 0 ? 0 : -*number;
1529 struct nl_sock *socks[16];
1533 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1534 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1537 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1539 struct nl_sock *sock = NULL;
1540 struct nl_pool *pool;
1542 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1544 ovs_mutex_lock(&pool_mutex);
1545 pool = &pools[protocol];
1547 sock = pool->socks[--pool->n];
1549 ovs_mutex_unlock(&pool_mutex);
1555 return nl_sock_create(protocol, sockp);
1560 nl_pool_release(struct nl_sock *sock)
1563 struct nl_pool *pool = &pools[sock->protocol];
1565 ovs_mutex_lock(&pool_mutex);
1566 if (pool->n < ARRAY_SIZE(pool->socks)) {
1567 pool->socks[pool->n++] = sock;
1570 ovs_mutex_unlock(&pool_mutex);
1572 nl_sock_destroy(sock);
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.
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.
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.
1589 * The caller is responsible for destroying 'request'.
1591 * Bare Netlink is an unreliable transport protocol. This function layers
1592 * reliable delivery and reply semantics on top of bare Netlink.
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).
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.
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.
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.
1614 * 2. Resending the request causes it to be re-executed, so the request
1615 * needs to be idempotent.
1618 nl_transact(int protocol, const struct ofpbuf *request,
1619 struct ofpbuf **replyp)
1621 struct nl_sock *sock;
1624 error = nl_pool_alloc(protocol, &sock);
1630 error = nl_sock_transact(sock, request, replyp);
1632 nl_pool_release(sock);
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.
1645 * The caller is responsible for destroying each request and reply, and the
1646 * transactions array itself.
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.
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.
1657 nl_transact_multiple(int protocol,
1658 struct nl_transaction **transactions, size_t n)
1660 struct nl_sock *sock;
1663 error = nl_pool_alloc(protocol, &sock);
1665 nl_sock_transact_multiple(sock, transactions, n);
1666 nl_pool_release(sock);
1668 nl_sock_record_errors__(transactions, n, error);
1674 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1676 uint32_t seq = sock->next_seq;
1678 sock->next_seq += n;
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) {
1691 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
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" },
1707 const struct nlmsg_flag *flag;
1708 uint16_t flags_left;
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));
1725 ds_put_cstr(ds, "(family-defined)");
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;
1736 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1738 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1739 h->nlmsg_seq, h->nlmsg_pid);
1743 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1745 struct ds ds = DS_EMPTY_INITIALIZER;
1746 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
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)));
1754 ds_put_format(&ds, " error(%d", e->error);
1756 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1758 ds_put_cstr(&ds, ", in-reply-to(");
1759 nlmsghdr_to_string(&e->msg, protocol, &ds);
1760 ds_put_cstr(&ds, "))");
1762 ds_put_cstr(&ds, " error(truncated)");
1764 } else if (h->nlmsg_type == NLMSG_DONE) {
1765 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1767 ds_put_format(&ds, " done(%d", *error);
1769 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1771 ds_put_cstr(&ds, ")");
1773 ds_put_cstr(&ds, " done(truncated)");
1775 } else if (protocol == NETLINK_GENERIC) {
1776 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1778 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1779 genl->cmd, genl->version);
1783 ds_put_cstr(&ds, "nl(truncated)");
1789 log_nlmsg(const char *function, int error,
1790 const void *message, size_t size, int protocol)
1792 if (!VLOG_IS_DBG_ENABLED()) {
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);