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"
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;
90 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
93 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
94 * of iovecs on the stack. */
97 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
98 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
100 * Initialized by nl_sock_create(). */
103 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
104 static void nl_pool_release(struct nl_sock *);
106 /* Creates a new netlink socket for the given netlink 'protocol'
107 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
108 * new socket if successful, otherwise returns a positive errno value. */
110 nl_sock_create(int protocol, struct nl_sock **sockp)
112 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
113 struct nl_sock *sock;
115 struct sockaddr_nl local, remote;
117 socklen_t local_size;
121 if (ovsthread_once_start(&once)) {
122 int save_errno = errno;
125 max_iovs = sysconf(_SC_UIO_MAXIOV);
126 if (max_iovs < _XOPEN_IOV_MAX) {
127 if (max_iovs == -1 && errno) {
128 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
130 max_iovs = _XOPEN_IOV_MAX;
131 } else if (max_iovs > MAX_IOVS) {
136 ovsthread_once_done(&once);
140 sock = xmalloc(sizeof *sock);
143 sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
144 GENERIC_READ | GENERIC_WRITE,
145 FILE_SHARE_READ | FILE_SHARE_WRITE,
147 FILE_FLAG_OVERLAPPED, NULL);
149 if (sock->handle == INVALID_HANDLE_VALUE) {
150 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
154 memset(&sock->overlapped, 0, sizeof sock->overlapped);
155 sock->overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
156 if (sock->overlapped.hEvent == NULL) {
157 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
162 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
164 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
169 sock->protocol = protocol;
172 rcvbuf = 1024 * 1024;
174 sock->rcvbuf = rcvbuf;
175 retval = get_sock_pid_from_kernel(sock);
180 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
181 &rcvbuf, sizeof rcvbuf)) {
182 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
183 * Warn only if the failure is therefore unexpected. */
184 if (errno != EPERM) {
185 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
186 "(%s)", rcvbuf, ovs_strerror(errno));
190 retval = get_socket_rcvbuf(sock->fd);
195 sock->rcvbuf = retval;
197 /* Connect to kernel (pid 0) as remote address. */
198 memset(&remote, 0, sizeof remote);
199 remote.nl_family = AF_NETLINK;
201 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
202 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
206 /* Obtain pid assigned by kernel. */
207 local_size = sizeof local;
208 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
209 VLOG_ERR("getsockname: %s", ovs_strerror(errno));
212 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
213 VLOG_ERR("getsockname returned bad Netlink name");
217 sock->pid = local.nl_pid;
231 if (sock->overlapped.hEvent) {
232 CloseHandle(sock->overlapped.hEvent);
234 if (sock->handle != INVALID_HANDLE_VALUE) {
235 CloseHandle(sock->handle);
246 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
247 * sets '*sockp' to the new socket if successful, otherwise returns a positive
250 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
252 return nl_sock_create(src->protocol, sockp);
255 /* Destroys netlink socket 'sock'. */
257 nl_sock_destroy(struct nl_sock *sock)
261 if (sock->overlapped.hEvent) {
262 CloseHandle(sock->overlapped.hEvent);
264 CloseHandle(sock->handle);
273 /* Reads the pid for 'sock' generated in the kernel datapath. The function
274 * follows a transaction semantic. Eventually this function should call into
277 get_sock_pid_from_kernel(struct nl_sock *sock)
279 struct nl_transaction txn;
280 struct ofpbuf request;
281 uint64_t request_stub[128];
283 uint64_t reply_stub[128];
284 struct ovs_header *ovs_header;
285 struct nlmsghdr *nlmsg;
289 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
290 sizeof (struct ovs_header);
292 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
293 txn.request = &request;
294 ofpbuf_use_stub(&reply, reply_stub, sizeof reply_stub);
297 seq = nl_sock_allocate_seq(sock, 1);
298 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
299 OVS_CTRL_CMD_WIN_GET_PID, OVS_WIN_CONTROL_VERSION);
300 nlmsg = nl_msg_nlmsghdr(txn.request);
301 nlmsg->nlmsg_seq = seq;
303 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
304 ovs_header->dp_ifindex = 0;
305 ovs_header = ofpbuf_put_uninit(&reply, ovs_msg_size);
307 if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
308 ofpbuf_data(txn.request), ofpbuf_size(txn.request),
309 ofpbuf_data(txn.reply), ofpbuf_size(txn.reply),
314 if (bytes < ovs_msg_size) {
319 nlmsg = nl_msg_nlmsghdr(txn.reply);
320 if (nlmsg->nlmsg_seq != seq) {
324 sock->pid = nlmsg->nlmsg_pid;
329 ofpbuf_uninit(&request);
330 ofpbuf_uninit(&reply);
337 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
339 struct ofpbuf request;
340 uint64_t request_stub[128];
341 struct ovs_header *ovs_header;
342 struct nlmsghdr *nlmsg;
345 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
347 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
348 OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
349 OVS_WIN_CONTROL_VERSION);
351 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
352 ovs_header->dp_ifindex = 0;
354 nl_msg_put_u32(&request, OVS_NL_ATTR_MCAST_GRP, multicast_group);
355 nl_msg_put_u8(&request, OVS_NL_ATTR_MCAST_JOIN, join ? 1 : 0);
357 error = nl_sock_send(sock, &request, true);
358 ofpbuf_uninit(&request);
362 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
363 * successful, otherwise a positive errno value.
365 * A socket that is subscribed to a multicast group that receives asynchronous
366 * notifications must not be used for Netlink transactions or dumps, because
367 * transactions and dumps can cause notifications to be lost.
369 * Multicast group numbers are always positive.
371 * It is not an error to attempt to join a multicast group to which a socket
372 * already belongs. */
374 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
377 int error = nl_sock_mcgroup(sock, multicast_group, true);
379 VLOG_WARN("could not join multicast group %u (%s)",
380 multicast_group, ovs_strerror(errno));
384 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
385 &multicast_group, sizeof multicast_group) < 0) {
386 VLOG_WARN("could not join multicast group %u (%s)",
387 multicast_group, ovs_strerror(errno));
394 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
395 * successful, otherwise a positive errno value.
397 * Multicast group numbers are always positive.
399 * It is not an error to attempt to leave a multicast group to which a socket
402 * On success, reading from 'sock' will still return any messages that were
403 * received on 'multicast_group' before the group was left. */
405 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
408 int error = nl_sock_mcgroup(sock, multicast_group, false);
410 VLOG_WARN("could not leave multicast group %u (%s)",
411 multicast_group, ovs_strerror(errno));
415 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
416 &multicast_group, sizeof multicast_group) < 0) {
417 VLOG_WARN("could not leave multicast group %u (%s)",
418 multicast_group, ovs_strerror(errno));
426 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
427 uint32_t nlmsg_seq, bool wait)
429 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
432 nlmsg->nlmsg_len = ofpbuf_size(msg);
433 nlmsg->nlmsg_seq = nlmsg_seq;
434 nlmsg->nlmsg_pid = sock->pid;
440 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
441 ofpbuf_data(msg), ofpbuf_size(msg), NULL, 0,
444 /* XXX: Map to a more appropriate error based on GetLastError(). */
447 retval = ofpbuf_size(msg);
450 retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg),
451 wait ? 0 : MSG_DONTWAIT);
453 error = retval < 0 ? errno : 0;
454 } while (error == EINTR);
455 log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
457 COVERAGE_INC(netlink_sent);
462 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
463 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
464 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
465 * sequence number, before the message is sent.
467 * Returns 0 if successful, otherwise a positive errno value. If
468 * 'wait' is true, then the send will wait until buffer space is ready;
469 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
471 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
473 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
476 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
477 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
478 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
479 * 'nlmsg_seq', before the message is sent.
481 * Returns 0 if successful, otherwise a positive errno value. If
482 * 'wait' is true, then the send will wait until buffer space is ready;
483 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
485 * This function is suitable for sending a reply to a request that was received
486 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
488 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
489 uint32_t nlmsg_seq, bool wait)
491 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
495 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
497 /* We can't accurately predict the size of the data to be received. The
498 * caller is supposed to have allocated enough space in 'buf' to handle the
499 * "typical" case. To handle exceptions, we make available enough space in
500 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
501 * figure since that's the maximum length of a Netlink attribute). */
502 struct nlmsghdr *nlmsghdr;
509 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
512 iov[0].iov_base = ofpbuf_base(buf);
513 iov[0].iov_len = buf->allocated;
514 iov[1].iov_base = tail;
515 iov[1].iov_len = sizeof tail;
517 memset(&msg, 0, sizeof msg);
521 /* Receive a Netlink message from the kernel.
523 * This works around a kernel bug in which the kernel returns an error code
524 * as if it were the number of bytes read. It doesn't actually modify
525 * anything in the receive buffer in that case, so we can initialize the
526 * Netlink header with an impossible message length and then, upon success,
527 * check whether it changed. */
528 nlmsghdr = ofpbuf_base(buf);
530 nlmsghdr->nlmsg_len = UINT32_MAX;
533 if (!DeviceIoControl(sock->handle, OVS_IOCTL_READ,
534 NULL, 0, tail, sizeof tail, &bytes, NULL)) {
543 if (retval >= buf->allocated) {
544 ofpbuf_reinit(buf, retval);
546 memcpy(ofpbuf_data(buf), tail, retval);
547 ofpbuf_set_size(buf, retval);
551 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
553 error = (retval < 0 ? errno
554 : retval == 0 ? ECONNRESET /* not possible? */
555 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
557 } while (error == EINTR);
559 if (error == ENOBUFS) {
560 /* Socket receive buffer overflow dropped one or more messages that
561 * the kernel tried to send to us. */
562 COVERAGE_INC(netlink_overflow);
567 if (msg.msg_flags & MSG_TRUNC) {
568 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
573 if (retval < sizeof *nlmsghdr
574 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
575 || nlmsghdr->nlmsg_len > retval) {
576 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
577 retval, sizeof *nlmsghdr);
581 ofpbuf_set_size(buf, MIN(retval, buf->allocated));
582 if (retval > buf->allocated) {
583 COVERAGE_INC(netlink_recv_jumbo);
584 ofpbuf_put(buf, tail, retval - buf->allocated);
588 log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
589 COVERAGE_INC(netlink_received);
594 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
595 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
596 * EAGAIN if the 'sock' receive buffer is empty.
598 * The caller must have initialized 'buf' with an allocation of at least
599 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
600 * space for a "typical" message.
602 * On success, returns 0 and replaces 'buf''s previous content by the received
603 * message. This function expands 'buf''s allocated memory, as necessary, to
604 * hold the actual size of the received message.
606 * On failure, returns a positive errno value and clears 'buf' to zero length.
607 * 'buf' retains its previous memory allocation.
609 * Regardless of success or failure, this function resets 'buf''s headroom to
612 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
614 return nl_sock_recv__(sock, buf, wait);
618 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
623 for (i = 0; i < n; i++) {
624 struct nl_transaction *txn = transactions[i];
628 ofpbuf_clear(txn->reply);
634 nl_sock_transact_multiple__(struct nl_sock *sock,
635 struct nl_transaction **transactions, size_t n,
638 uint64_t tmp_reply_stub[1024 / 8];
639 struct nl_transaction tmp_txn;
640 struct ofpbuf tmp_reply;
643 struct iovec iovs[MAX_IOVS];
648 base_seq = nl_sock_allocate_seq(sock, n);
650 for (i = 0; i < n; i++) {
651 struct nl_transaction *txn = transactions[i];
652 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
654 nlmsg->nlmsg_len = ofpbuf_size(txn->request);
655 nlmsg->nlmsg_seq = base_seq + i;
656 nlmsg->nlmsg_pid = sock->pid;
658 iovs[i].iov_base = ofpbuf_data(txn->request);
659 iovs[i].iov_len = ofpbuf_size(txn->request);
663 memset(&msg, 0, sizeof msg);
667 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
668 } while (error == EINTR);
670 for (i = 0; i < n; i++) {
671 struct nl_transaction *txn = transactions[i];
673 log_nlmsg(__func__, error, ofpbuf_data(txn->request),
674 ofpbuf_size(txn->request), sock->protocol);
677 COVERAGE_ADD(netlink_sent, n);
684 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
685 tmp_txn.request = NULL;
686 tmp_txn.reply = &tmp_reply;
689 struct nl_transaction *buf_txn, *txn;
692 /* Find a transaction whose buffer we can use for receiving a reply.
693 * If no such transaction is left, use tmp_txn. */
695 for (i = 0; i < n; i++) {
696 if (transactions[i]->reply) {
697 buf_txn = transactions[i];
702 /* Receive a reply. */
703 error = nl_sock_recv__(sock, buf_txn->reply, false);
705 if (error == EAGAIN) {
706 nl_sock_record_errors__(transactions, n, 0);
713 /* Match the reply up with a transaction. */
714 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
715 if (seq < base_seq || seq >= base_seq + n) {
716 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
720 txn = transactions[i];
722 /* Fill in the results for 'txn'. */
723 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
725 ofpbuf_clear(txn->reply);
728 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
729 error, ovs_strerror(txn->error));
733 if (txn->reply && txn != buf_txn) {
735 struct ofpbuf *reply = buf_txn->reply;
736 buf_txn->reply = txn->reply;
741 /* Fill in the results for transactions before 'txn'. (We have to do
742 * this after the results for 'txn' itself because of the buffer swap
744 nl_sock_record_errors__(transactions, i, 0);
748 transactions += i + 1;
752 ofpbuf_uninit(&tmp_reply);
755 for (i = 0; i < n; i++) {
758 struct nl_transaction *txn = transactions[i];
759 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
761 if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
762 ofpbuf_data(txn->request),
763 ofpbuf_size(txn->request),
764 txn->reply ? tail : 0,
765 txn->reply ? sizeof tail : 0,
767 /* XXX: Map to a more appropriate error. */
773 if (reply_len < sizeof *reply_nlmsg) {
774 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32,
779 /* Validate the sequence number in the reply. */
780 request_nlmsg = nl_msg_nlmsghdr(txn->request);
781 reply_nlmsg = (struct nlmsghdr *)tail;
783 if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
784 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
785 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
786 ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
787 reply_nlmsg->nlmsg_seq);
791 /* If reply was expected, verify if there was indeed a reply
793 if (reply_len == 0) {
794 nl_sock_record_errors__(transactions, n, 0);
795 VLOG_DBG_RL(&rl, "reply not seen when expected seq %#"PRIx32,
796 request_nlmsg->nlmsg_seq);
800 /* Copy the reply to the buffer specified by the caller. */
801 if (reply_len > txn->reply->allocated) {
802 ofpbuf_reinit(txn->reply, reply_len);
804 memcpy(ofpbuf_data(txn->reply), tail, reply_len);
805 ofpbuf_set_size(txn->reply, reply_len);
807 /* Handle errors embedded within the netlink message. */
808 if (nl_msg_nlmsgerr(txn->reply, &txn->error)) {
810 ofpbuf_clear(txn->reply);
813 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
814 error, ovs_strerror(txn->error));
821 /* Count the number of successful transactions. */
826 COVERAGE_ADD(netlink_sent, n);
834 nl_sock_transact_multiple(struct nl_sock *sock,
835 struct nl_transaction **transactions, size_t n)
844 /* In theory, every request could have a 64 kB reply. But the default and
845 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
846 * be a bit below 128 kB, so that would only allow a single message in a
847 * "batch". So we assume that replies average (at most) 4 kB, which allows
848 * a good deal of batching.
850 * In practice, most of the requests that we batch either have no reply at
851 * all or a brief reply. */
852 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
853 max_batch_count = MIN(max_batch_count, max_iovs);
859 /* Batch up to 'max_batch_count' transactions. But cap it at about a
860 * page of requests total because big skbuffs are expensive to
861 * allocate in the kernel. */
862 #if defined(PAGESIZE)
863 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
865 enum { MAX_BATCH_BYTES = 4096 - 512 };
867 bytes = ofpbuf_size(transactions[0]->request);
868 for (count = 1; count < n && count < max_batch_count; count++) {
869 if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
872 bytes += ofpbuf_size(transactions[count]->request);
875 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
876 transactions += done;
879 if (error == ENOBUFS) {
880 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
882 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
883 nl_sock_record_errors__(transactions, n, error);
889 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
890 struct ofpbuf **replyp)
892 struct nl_transaction *transactionp;
893 struct nl_transaction transaction;
895 transaction.request = CONST_CAST(struct ofpbuf *, request);
896 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
897 transactionp = &transaction;
899 nl_sock_transact_multiple(sock, &transactionp, 1);
902 if (transaction.error) {
903 ofpbuf_delete(transaction.reply);
906 *replyp = transaction.reply;
910 return transaction.error;
913 /* Drain all the messages currently in 'sock''s receive queue. */
915 nl_sock_drain(struct nl_sock *sock)
920 return drain_rcvbuf(sock->fd);
924 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
925 * Netlink socket created with the given 'protocol', and initializes 'dump' to
926 * reflect the state of the operation.
928 * 'request' must contain a Netlink message. Before sending the message,
929 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
930 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
933 * The design of this Netlink socket library ensures that the dump is reliable.
935 * This function provides no status indication. nl_dump_done() provides an
936 * error status for the entire dump operation.
938 * The caller must eventually destroy 'request'.
941 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
943 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
945 ovs_mutex_init(&dump->mutex);
946 ovs_mutex_lock(&dump->mutex);
947 dump->status = nl_pool_alloc(protocol, &dump->sock);
949 dump->status = nl_sock_send__(dump->sock, request,
950 nl_sock_allocate_seq(dump->sock, 1),
953 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
954 ovs_mutex_unlock(&dump->mutex);
958 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
959 OVS_REQUIRES(dump->mutex)
961 struct nlmsghdr *nlmsghdr;
964 while (!ofpbuf_size(buffer)) {
965 error = nl_sock_recv__(dump->sock, buffer, false);
967 /* The kernel never blocks providing the results of a dump, so
968 * error == EAGAIN means that we've read the whole thing, and
969 * therefore transform it into EOF. (The kernel always provides
970 * NLMSG_DONE as a sentinel. Some other thread must have received
971 * that already but not yet signaled it in 'status'.)
973 * Any other error is just an error. */
974 return error == EAGAIN ? EOF : error;
977 nlmsghdr = nl_msg_nlmsghdr(buffer);
978 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
979 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
980 nlmsghdr->nlmsg_seq, dump->nl_seq);
981 ofpbuf_clear(buffer);
985 if (nl_msg_nlmsgerr(buffer, &error) && error) {
986 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
987 ovs_strerror(error));
988 ofpbuf_clear(buffer);
996 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
998 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1000 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1002 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1009 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1010 * have been initialized with nl_dump_start(), and 'buffer' must have been
1011 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1013 * If successful, returns true and points 'reply->data' and
1014 * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
1015 * modify 'reply' (because it points within 'buffer', which will be used by
1016 * future calls to this function).
1018 * On failure, returns false and sets 'reply->data' to NULL and
1019 * 'ofpbuf_size(reply)' to 0. Failure might indicate an actual error or merely
1020 * the end of replies. An error status for the entire dump operation is
1021 * provided when it is completed by calling nl_dump_done().
1023 * Multiple threads may call this function, passing the same nl_dump, however
1024 * each must provide independent buffers. This function may cache multiple
1025 * replies in the buffer, and these will be processed before more replies are
1026 * fetched. When this function returns false, other threads may continue to
1027 * process replies in their buffers, but they will not fetch more replies.
1030 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1034 /* If the buffer is empty, refill it.
1036 * If the buffer is not empty, we don't check the dump's status.
1037 * Otherwise, we could end up skipping some of the dump results if thread A
1038 * hits EOF while thread B is in the midst of processing a batch. */
1039 if (!ofpbuf_size(buffer)) {
1040 ovs_mutex_lock(&dump->mutex);
1041 if (!dump->status) {
1042 /* Take the mutex here to avoid an in-kernel race. If two threads
1043 * try to read from a Netlink dump socket at once, then the socket
1044 * error can be set to EINVAL, which will be encountered on the
1045 * next recv on that socket, which could be anywhere due to the way
1046 * that we pool Netlink sockets. Serializing the recv calls avoids
1048 dump->status = nl_dump_refill(dump, buffer);
1050 retval = dump->status;
1051 ovs_mutex_unlock(&dump->mutex);
1054 /* Fetch the next message from the buffer. */
1056 retval = nl_dump_next__(reply, buffer);
1058 /* Record 'retval' as the dump status, but don't overwrite an error
1060 ovs_mutex_lock(&dump->mutex);
1061 if (dump->status <= 0) {
1062 dump->status = retval;
1064 ovs_mutex_unlock(&dump->mutex);
1069 ofpbuf_set_data(reply, NULL);
1070 ofpbuf_set_size(reply, 0);
1075 /* Completes Netlink dump operation 'dump', which must have been initialized
1076 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1077 * otherwise a positive errno value describing the problem. */
1079 nl_dump_done(struct nl_dump *dump)
1083 ovs_mutex_lock(&dump->mutex);
1084 status = dump->status;
1085 ovs_mutex_unlock(&dump->mutex);
1087 /* Drain any remaining messages that the client didn't read. Otherwise the
1088 * kernel will continue to queue them up and waste buffer space.
1090 * XXX We could just destroy and discard the socket in this case. */
1092 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1093 struct ofpbuf reply, buf;
1095 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1096 while (nl_dump_next(dump, &reply, &buf)) {
1097 /* Nothing to do. */
1099 ofpbuf_uninit(&buf);
1101 ovs_mutex_lock(&dump->mutex);
1102 status = dump->status;
1103 ovs_mutex_unlock(&dump->mutex);
1107 nl_pool_release(dump->sock);
1108 ovs_mutex_destroy(&dump->mutex);
1110 return status == EOF ? 0 : status;
1114 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1115 * an event or a packet is ready to be read. Once the I/O is completed
1116 * the overlapped structure event associated with the pending I/O will be set
1119 pend_io_request(const struct nl_sock *sock)
1121 struct ofpbuf request;
1122 uint64_t request_stub[128];
1123 struct ovs_header *ovs_header;
1124 struct nlmsghdr *nlmsg;
1129 OVERLAPPED *overlapped = &sock->overlapped;
1131 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1132 sizeof (struct ovs_header);
1134 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1136 seq = nl_sock_allocate_seq(sock, 1);
1137 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1138 OVS_CTRL_CMD_WIN_PEND_REQ, OVS_WIN_CONTROL_VERSION);
1139 nlmsg = nl_msg_nlmsghdr(&request);
1140 nlmsg->nlmsg_seq = seq;
1142 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1143 ovs_header->dp_ifindex = 0;
1145 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1146 ofpbuf_data(&request), ofpbuf_size(&request),
1147 NULL, 0, &bytes, overlapped)) {
1148 error = GetLastError();
1149 /* Check if the I/O got pended */
1150 if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1151 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1156 /* The I/O was completed synchronously */
1157 poll_immediate_wake();
1162 ofpbuf_uninit(&request);
1167 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1168 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
1170 nl_sock_wait(const struct nl_sock *sock, short int events)
1173 if (sock->overlapped.Internal != STATUS_PENDING) {
1174 pend_io_request(sock);
1176 poll_fd_wait(sock->handle, events);
1178 poll_fd_wait(sock->fd, events);
1182 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1183 * that can't use nl_sock_wait().
1185 * It's a little tricky to use the returned fd correctly, because nl_sock does
1186 * "copy on write" to allow a single nl_sock to be used for notifications,
1187 * transactions, and dumps. If 'sock' is used only for notifications and
1188 * transactions (and never for dump) then the usage is safe. */
1190 nl_sock_fd(const struct nl_sock *sock)
1193 return sock->handle;
1199 /* Returns the PID associated with this socket. */
1201 nl_sock_pid(const struct nl_sock *sock)
1206 /* Miscellaneous. */
1208 struct genl_family {
1209 struct hmap_node hmap_node;
1214 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1216 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1217 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1218 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1221 static struct genl_family *
1222 find_genl_family_by_id(uint16_t id)
1224 struct genl_family *family;
1226 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1228 if (family->id == id) {
1236 define_genl_family(uint16_t id, const char *name)
1238 struct genl_family *family = find_genl_family_by_id(id);
1241 if (!strcmp(family->name, name)) {
1246 family = xmalloc(sizeof *family);
1248 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1250 family->name = xstrdup(name);
1254 genl_family_to_name(uint16_t id)
1256 if (id == GENL_ID_CTRL) {
1259 struct genl_family *family = find_genl_family_by_id(id);
1260 return family ? family->name : "unknown";
1266 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1267 struct ofpbuf **replyp)
1269 struct nl_sock *sock;
1270 struct ofpbuf request, *reply;
1274 error = nl_sock_create(NETLINK_GENERIC, &sock);
1279 ofpbuf_init(&request, 0);
1280 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1281 CTRL_CMD_GETFAMILY, 1);
1282 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1283 error = nl_sock_transact(sock, &request, &reply);
1284 ofpbuf_uninit(&request);
1286 nl_sock_destroy(sock);
1290 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1291 family_policy, attrs, ARRAY_SIZE(family_policy))
1292 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1293 nl_sock_destroy(sock);
1294 ofpbuf_delete(reply);
1298 nl_sock_destroy(sock);
1304 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1305 struct ofpbuf **replyp)
1307 struct nlmsghdr *nlmsg;
1308 struct ofpbuf *reply;
1311 const char *family_name;
1312 uint32_t family_version;
1313 uint32_t family_attrmax;
1314 uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1315 const char *mcgrp_name = NULL;
1318 reply = ofpbuf_new(1024);
1320 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1321 if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1322 family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1323 family_name = OVS_WIN_CONTROL_FAMILY;
1324 family_version = OVS_WIN_CONTROL_VERSION;
1325 family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1326 } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1327 family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1328 family_name = OVS_DATAPATH_FAMILY;
1329 family_version = OVS_DATAPATH_VERSION;
1330 family_attrmax = OVS_DP_ATTR_MAX;
1331 } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1332 family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1333 family_name = OVS_PACKET_FAMILY;
1334 family_version = OVS_PACKET_VERSION;
1335 family_attrmax = OVS_PACKET_ATTR_MAX;
1336 } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1337 family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1338 family_name = OVS_VPORT_FAMILY;
1339 family_version = OVS_VPORT_VERSION;
1340 family_attrmax = OVS_VPORT_ATTR_MAX;
1341 mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1342 mcgrp_name = OVS_VPORT_MCGROUP;
1343 } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1344 family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1345 family_name = OVS_FLOW_FAMILY;
1346 family_version = OVS_FLOW_VERSION;
1347 family_attrmax = OVS_FLOW_ATTR_MAX;
1349 ofpbuf_delete(reply);
1353 nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1354 CTRL_CMD_NEWFAMILY, family_version);
1355 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1356 * callers do not seem to need them. */
1357 nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1358 nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1359 nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1360 nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1362 if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1363 size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1364 size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1365 OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1366 nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1367 ovs_assert(mcgrp_name != NULL);
1368 nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1369 nl_msg_end_nested(reply, mcgrp_ofs2);
1370 nl_msg_end_nested(reply, mcgrp_ofs1);
1373 /* Set the total length of the netlink message. */
1374 nlmsg = nl_msg_nlmsghdr(reply);
1375 nlmsg->nlmsg_len = ofpbuf_size(reply);
1377 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1378 family_policy, attrs, ARRAY_SIZE(family_policy))
1379 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1380 ofpbuf_delete(reply);
1389 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1390 * When successful, writes its result to 'multicast_group' and returns 0.
1391 * Otherwise, clears 'multicast_group' and returns a positive error code.
1394 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1395 unsigned int *multicast_group)
1397 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1398 const struct nlattr *mc;
1399 struct ofpbuf *reply;
1403 *multicast_group = 0;
1404 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1409 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1414 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1415 static const struct nl_policy mc_policy[] = {
1416 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1417 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1420 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1421 const char *mc_name;
1423 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1428 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1429 if (!strcmp(group_name, mc_name)) {
1431 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1439 ofpbuf_delete(reply);
1443 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1444 * number and stores it in '*number'. If successful, returns 0 and the caller
1445 * may use '*number' as the family number. On failure, returns a positive
1446 * errno value and '*number' caches the errno value. */
1448 nl_lookup_genl_family(const char *name, int *number)
1451 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1452 struct ofpbuf *reply;
1455 error = do_lookup_genl_family(name, attrs, &reply);
1457 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1458 define_genl_family(*number, name);
1462 ofpbuf_delete(reply);
1464 ovs_assert(*number != 0);
1466 return *number > 0 ? 0 : -*number;
1470 struct nl_sock *socks[16];
1474 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1475 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1478 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1480 struct nl_sock *sock = NULL;
1481 struct nl_pool *pool;
1483 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1485 ovs_mutex_lock(&pool_mutex);
1486 pool = &pools[protocol];
1488 sock = pool->socks[--pool->n];
1490 ovs_mutex_unlock(&pool_mutex);
1496 return nl_sock_create(protocol, sockp);
1501 nl_pool_release(struct nl_sock *sock)
1504 struct nl_pool *pool = &pools[sock->protocol];
1506 ovs_mutex_lock(&pool_mutex);
1507 if (pool->n < ARRAY_SIZE(pool->socks)) {
1508 pool->socks[pool->n++] = sock;
1511 ovs_mutex_unlock(&pool_mutex);
1513 nl_sock_destroy(sock);
1517 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1518 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1519 * successful, returns 0. On failure, returns a positive errno value.
1521 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1522 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1523 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1524 * reply, if any, is discarded.
1526 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1527 * match ofpbuf_size(msg), nlmsg_pid will be set to the pid of the socket used
1528 * for sending the request, and nlmsg_seq will be initialized.
1530 * The caller is responsible for destroying 'request'.
1532 * Bare Netlink is an unreliable transport protocol. This function layers
1533 * reliable delivery and reply semantics on top of bare Netlink.
1535 * In Netlink, sending a request to the kernel is reliable enough, because the
1536 * kernel will tell us if the message cannot be queued (and we will in that
1537 * case put it on the transmit queue and wait until it can be delivered).
1539 * Receiving the reply is the real problem: if the socket buffer is full when
1540 * the kernel tries to send the reply, the reply will be dropped. However, the
1541 * kernel sets a flag that a reply has been dropped. The next call to recv
1542 * then returns ENOBUFS. We can then re-send the request.
1546 * 1. Netlink depends on sequence numbers to match up requests and
1547 * replies. The sender of a request supplies a sequence number, and
1548 * the reply echos back that sequence number.
1550 * This is fine, but (1) some kernel netlink implementations are
1551 * broken, in that they fail to echo sequence numbers and (2) this
1552 * function will drop packets with non-matching sequence numbers, so
1553 * that only a single request can be usefully transacted at a time.
1555 * 2. Resending the request causes it to be re-executed, so the request
1556 * needs to be idempotent.
1559 nl_transact(int protocol, const struct ofpbuf *request,
1560 struct ofpbuf **replyp)
1562 struct nl_sock *sock;
1565 error = nl_pool_alloc(protocol, &sock);
1571 error = nl_sock_transact(sock, request, replyp);
1573 nl_pool_release(sock);
1577 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1578 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1579 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1580 * the 'error' member of each transaction with 0 if it was successful,
1581 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1582 * be filled with the reply if the message receives a detailed reply. In other
1583 * cases, i.e. where the request failed or had no reply beyond an indication of
1584 * success, 'reply' will be cleared if it is nonnull.
1586 * The caller is responsible for destroying each request and reply, and the
1587 * transactions array itself.
1589 * Before sending each message, this function will finalize nlmsg_len in each
1590 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1591 * used for the transaction, and initialize nlmsg_seq.
1593 * Bare Netlink is an unreliable transport protocol. This function layers
1594 * reliable delivery and reply semantics on top of bare Netlink. See
1595 * nl_transact() for some caveats.
1598 nl_transact_multiple(int protocol,
1599 struct nl_transaction **transactions, size_t n)
1601 struct nl_sock *sock;
1604 error = nl_pool_alloc(protocol, &sock);
1606 nl_sock_transact_multiple(sock, transactions, n);
1607 nl_pool_release(sock);
1609 nl_sock_record_errors__(transactions, n, error);
1615 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1617 uint32_t seq = sock->next_seq;
1619 sock->next_seq += n;
1621 /* Make it impossible for the next request for sequence numbers to wrap
1622 * around to 0. Start over with 1 to avoid ever using a sequence number of
1623 * 0, because the kernel uses sequence number 0 for notifications. */
1624 if (sock->next_seq >= UINT32_MAX / 2) {
1632 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1638 static const struct nlmsg_flag flags[] = {
1639 { NLM_F_REQUEST, "REQUEST" },
1640 { NLM_F_MULTI, "MULTI" },
1641 { NLM_F_ACK, "ACK" },
1642 { NLM_F_ECHO, "ECHO" },
1643 { NLM_F_DUMP, "DUMP" },
1644 { NLM_F_ROOT, "ROOT" },
1645 { NLM_F_MATCH, "MATCH" },
1646 { NLM_F_ATOMIC, "ATOMIC" },
1648 const struct nlmsg_flag *flag;
1649 uint16_t flags_left;
1651 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1652 h->nlmsg_len, h->nlmsg_type);
1653 if (h->nlmsg_type == NLMSG_NOOP) {
1654 ds_put_cstr(ds, "(no-op)");
1655 } else if (h->nlmsg_type == NLMSG_ERROR) {
1656 ds_put_cstr(ds, "(error)");
1657 } else if (h->nlmsg_type == NLMSG_DONE) {
1658 ds_put_cstr(ds, "(done)");
1659 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1660 ds_put_cstr(ds, "(overrun)");
1661 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1662 ds_put_cstr(ds, "(reserved)");
1663 } else if (protocol == NETLINK_GENERIC) {
1664 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1666 ds_put_cstr(ds, "(family-defined)");
1668 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1669 flags_left = h->nlmsg_flags;
1670 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1671 if ((flags_left & flag->bits) == flag->bits) {
1672 ds_put_format(ds, "[%s]", flag->name);
1673 flags_left &= ~flag->bits;
1677 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1679 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1680 h->nlmsg_seq, h->nlmsg_pid);
1684 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1686 struct ds ds = DS_EMPTY_INITIALIZER;
1687 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1689 nlmsghdr_to_string(h, protocol, &ds);
1690 if (h->nlmsg_type == NLMSG_ERROR) {
1691 const struct nlmsgerr *e;
1692 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1693 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1695 ds_put_format(&ds, " error(%d", e->error);
1697 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1699 ds_put_cstr(&ds, ", in-reply-to(");
1700 nlmsghdr_to_string(&e->msg, protocol, &ds);
1701 ds_put_cstr(&ds, "))");
1703 ds_put_cstr(&ds, " error(truncated)");
1705 } else if (h->nlmsg_type == NLMSG_DONE) {
1706 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1708 ds_put_format(&ds, " done(%d", *error);
1710 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1712 ds_put_cstr(&ds, ")");
1714 ds_put_cstr(&ds, " done(truncated)");
1716 } else if (protocol == NETLINK_GENERIC) {
1717 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1719 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1720 genl->cmd, genl->version);
1724 ds_put_cstr(&ds, "nl(truncated)");
1730 log_nlmsg(const char *function, int error,
1731 const void *message, size_t size, int protocol)
1733 struct ofpbuf buffer;
1736 if (!VLOG_IS_DBG_ENABLED()) {
1740 ofpbuf_use_const(&buffer, message, size);
1741 nlmsg = nlmsg_to_string(&buffer, protocol);
1742 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);