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;
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 * follows a transaction semantic. Eventually this function should call into
279 get_sock_pid_from_kernel(struct nl_sock *sock)
281 struct nl_transaction txn;
282 struct ofpbuf request;
283 uint64_t request_stub[128];
285 uint64_t reply_stub[128];
286 struct ovs_header *ovs_header;
287 struct nlmsghdr *nlmsg;
291 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
292 sizeof (struct ovs_header);
294 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
295 txn.request = &request;
296 ofpbuf_use_stub(&reply, reply_stub, sizeof reply_stub);
299 seq = nl_sock_allocate_seq(sock, 1);
300 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
301 OVS_CTRL_CMD_WIN_GET_PID, OVS_WIN_CONTROL_VERSION);
302 nlmsg = nl_msg_nlmsghdr(txn.request);
303 nlmsg->nlmsg_seq = seq;
305 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
306 ovs_header->dp_ifindex = 0;
307 ovs_header = ofpbuf_put_uninit(&reply, ovs_msg_size);
309 if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
310 ofpbuf_data(txn.request), ofpbuf_size(txn.request),
311 ofpbuf_data(txn.reply), ofpbuf_size(txn.reply),
316 if (bytes < ovs_msg_size) {
321 nlmsg = nl_msg_nlmsghdr(txn.reply);
322 if (nlmsg->nlmsg_seq != seq) {
326 sock->pid = nlmsg->nlmsg_pid;
331 ofpbuf_uninit(&request);
332 ofpbuf_uninit(&reply);
339 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
341 struct ofpbuf request;
342 uint64_t request_stub[128];
343 struct ovs_header *ovs_header;
344 struct nlmsghdr *nlmsg;
347 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
349 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
350 OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
351 OVS_WIN_CONTROL_VERSION);
353 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
354 ovs_header->dp_ifindex = 0;
356 nl_msg_put_u32(&request, OVS_NL_ATTR_MCAST_GRP, multicast_group);
357 nl_msg_put_u8(&request, OVS_NL_ATTR_MCAST_JOIN, join ? 1 : 0);
359 error = nl_sock_send(sock, &request, true);
360 ofpbuf_uninit(&request);
364 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
365 * successful, otherwise a positive errno value.
367 * A socket that is subscribed to a multicast group that receives asynchronous
368 * notifications must not be used for Netlink transactions or dumps, because
369 * transactions and dumps can cause notifications to be lost.
371 * Multicast group numbers are always positive.
373 * It is not an error to attempt to join a multicast group to which a socket
374 * already belongs. */
376 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
379 /* Set the socket type as a "multicast" socket */
380 sock->read_ioctl = OVS_IOCTL_READ_EVENT;
381 int error = nl_sock_mcgroup(sock, multicast_group, true);
383 sock->read_ioctl = OVS_IOCTL_READ;
384 VLOG_WARN("could not join multicast group %u (%s)",
385 multicast_group, ovs_strerror(error));
389 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
390 &multicast_group, sizeof multicast_group) < 0) {
391 VLOG_WARN("could not join multicast group %u (%s)",
392 multicast_group, ovs_strerror(errno));
399 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
400 * successful, otherwise a positive errno value.
402 * Multicast group numbers are always positive.
404 * It is not an error to attempt to leave a multicast group to which a socket
407 * On success, reading from 'sock' will still return any messages that were
408 * received on 'multicast_group' before the group was left. */
410 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
413 int error = nl_sock_mcgroup(sock, multicast_group, false);
415 VLOG_WARN("could not leave multicast group %u (%s)",
416 multicast_group, ovs_strerror(error));
419 sock->read_ioctl = OVS_IOCTL_READ;
421 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
422 &multicast_group, sizeof multicast_group) < 0) {
423 VLOG_WARN("could not leave multicast group %u (%s)",
424 multicast_group, ovs_strerror(errno));
432 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
433 uint32_t nlmsg_seq, bool wait)
435 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
438 nlmsg->nlmsg_len = ofpbuf_size(msg);
439 nlmsg->nlmsg_seq = nlmsg_seq;
440 nlmsg->nlmsg_pid = sock->pid;
446 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
447 ofpbuf_data(msg), ofpbuf_size(msg), NULL, 0,
450 /* XXX: Map to a more appropriate error based on GetLastError(). */
453 retval = ofpbuf_size(msg);
456 retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg),
457 wait ? 0 : MSG_DONTWAIT);
459 error = retval < 0 ? errno : 0;
460 } while (error == EINTR);
461 log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
463 COVERAGE_INC(netlink_sent);
468 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
469 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
470 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
471 * sequence number, before the message is sent.
473 * Returns 0 if successful, otherwise a positive errno value. If
474 * 'wait' is true, then the send will wait until buffer space is ready;
475 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
477 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
479 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
482 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
483 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
484 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
485 * 'nlmsg_seq', before the message is sent.
487 * Returns 0 if successful, otherwise a positive errno value. If
488 * 'wait' is true, then the send will wait until buffer space is ready;
489 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
491 * This function is suitable for sending a reply to a request that was received
492 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
494 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
495 uint32_t nlmsg_seq, bool wait)
497 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
501 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
503 /* We can't accurately predict the size of the data to be received. The
504 * caller is supposed to have allocated enough space in 'buf' to handle the
505 * "typical" case. To handle exceptions, we make available enough space in
506 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
507 * figure since that's the maximum length of a Netlink attribute). */
508 struct nlmsghdr *nlmsghdr;
515 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
518 iov[0].iov_base = ofpbuf_base(buf);
519 iov[0].iov_len = buf->allocated;
520 iov[1].iov_base = tail;
521 iov[1].iov_len = sizeof tail;
523 memset(&msg, 0, sizeof msg);
527 /* Receive a Netlink message from the kernel.
529 * This works around a kernel bug in which the kernel returns an error code
530 * as if it were the number of bytes read. It doesn't actually modify
531 * anything in the receive buffer in that case, so we can initialize the
532 * Netlink header with an impossible message length and then, upon success,
533 * check whether it changed. */
534 nlmsghdr = ofpbuf_base(buf);
536 nlmsghdr->nlmsg_len = UINT32_MAX;
539 if (!DeviceIoControl(sock->handle, sock->read_ioctl,
540 NULL, 0, tail, sizeof tail, &bytes, NULL)) {
549 if (retval >= buf->allocated) {
550 ofpbuf_reinit(buf, retval);
551 nlmsghdr = ofpbuf_base(buf);
552 nlmsghdr->nlmsg_len = UINT32_MAX;
554 memcpy(ofpbuf_data(buf), tail, retval);
555 ofpbuf_set_size(buf, retval);
559 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
561 error = (retval < 0 ? errno
562 : retval == 0 ? ECONNRESET /* not possible? */
563 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
565 } while (error == EINTR);
567 if (error == ENOBUFS) {
568 /* Socket receive buffer overflow dropped one or more messages that
569 * the kernel tried to send to us. */
570 COVERAGE_INC(netlink_overflow);
575 if (msg.msg_flags & MSG_TRUNC) {
576 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
581 if (retval < sizeof *nlmsghdr
582 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
583 || nlmsghdr->nlmsg_len > retval) {
584 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
585 retval, sizeof *nlmsghdr);
589 ofpbuf_set_size(buf, MIN(retval, buf->allocated));
590 if (retval > buf->allocated) {
591 COVERAGE_INC(netlink_recv_jumbo);
592 ofpbuf_put(buf, tail, retval - buf->allocated);
596 log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
597 COVERAGE_INC(netlink_received);
602 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
603 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
604 * EAGAIN if the 'sock' receive buffer is empty.
606 * The caller must have initialized 'buf' with an allocation of at least
607 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
608 * space for a "typical" message.
610 * On success, returns 0 and replaces 'buf''s previous content by the received
611 * message. This function expands 'buf''s allocated memory, as necessary, to
612 * hold the actual size of the received message.
614 * On failure, returns a positive errno value and clears 'buf' to zero length.
615 * 'buf' retains its previous memory allocation.
617 * Regardless of success or failure, this function resets 'buf''s headroom to
620 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
622 return nl_sock_recv__(sock, buf, wait);
626 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
631 for (i = 0; i < n; i++) {
632 struct nl_transaction *txn = transactions[i];
636 ofpbuf_clear(txn->reply);
642 nl_sock_transact_multiple__(struct nl_sock *sock,
643 struct nl_transaction **transactions, size_t n,
646 uint64_t tmp_reply_stub[1024 / 8];
647 struct nl_transaction tmp_txn;
648 struct ofpbuf tmp_reply;
651 struct iovec iovs[MAX_IOVS];
656 base_seq = nl_sock_allocate_seq(sock, n);
658 for (i = 0; i < n; i++) {
659 struct nl_transaction *txn = transactions[i];
660 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
662 nlmsg->nlmsg_len = ofpbuf_size(txn->request);
663 nlmsg->nlmsg_seq = base_seq + i;
664 nlmsg->nlmsg_pid = sock->pid;
666 iovs[i].iov_base = ofpbuf_data(txn->request);
667 iovs[i].iov_len = ofpbuf_size(txn->request);
671 memset(&msg, 0, sizeof msg);
675 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
676 } while (error == EINTR);
678 for (i = 0; i < n; i++) {
679 struct nl_transaction *txn = transactions[i];
681 log_nlmsg(__func__, error, ofpbuf_data(txn->request),
682 ofpbuf_size(txn->request), sock->protocol);
685 COVERAGE_ADD(netlink_sent, n);
692 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
693 tmp_txn.request = NULL;
694 tmp_txn.reply = &tmp_reply;
697 struct nl_transaction *buf_txn, *txn;
700 /* Find a transaction whose buffer we can use for receiving a reply.
701 * If no such transaction is left, use tmp_txn. */
703 for (i = 0; i < n; i++) {
704 if (transactions[i]->reply) {
705 buf_txn = transactions[i];
710 /* Receive a reply. */
711 error = nl_sock_recv__(sock, buf_txn->reply, false);
713 if (error == EAGAIN) {
714 nl_sock_record_errors__(transactions, n, 0);
721 /* Match the reply up with a transaction. */
722 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
723 if (seq < base_seq || seq >= base_seq + n) {
724 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
728 txn = transactions[i];
730 /* Fill in the results for 'txn'. */
731 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
733 ofpbuf_clear(txn->reply);
736 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
737 error, ovs_strerror(txn->error));
741 if (txn->reply && txn != buf_txn) {
743 struct ofpbuf *reply = buf_txn->reply;
744 buf_txn->reply = txn->reply;
749 /* Fill in the results for transactions before 'txn'. (We have to do
750 * this after the results for 'txn' itself because of the buffer swap
752 nl_sock_record_errors__(transactions, i, 0);
756 transactions += i + 1;
760 ofpbuf_uninit(&tmp_reply);
763 uint8_t reply_buf[65536];
764 for (i = 0; i < n; i++) {
766 struct nl_transaction *txn = transactions[i];
767 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
769 if (!DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
770 ofpbuf_data(txn->request),
771 ofpbuf_size(txn->request),
772 reply_buf, sizeof reply_buf,
774 /* XXX: Map to a more appropriate error. */
779 if (reply_len < sizeof *reply_nlmsg) {
780 nl_sock_record_errors__(transactions, n, 0);
781 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32
782 " for seq: %#"PRIx32, reply_len, request_nlmsg->nlmsg_seq);
786 /* Validate the sequence number in the reply. */
787 request_nlmsg = nl_msg_nlmsghdr(txn->request);
788 reply_nlmsg = (struct nlmsghdr *)reply_buf;
790 if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
791 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
792 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
793 ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
794 reply_nlmsg->nlmsg_seq);
798 /* Handle errors embedded within the netlink message. */
799 ofpbuf_use_stub(&tmp_reply, reply_buf, sizeof reply_buf);
800 ofpbuf_set_size(&tmp_reply, sizeof reply_buf);
801 if (nl_msg_nlmsgerr(&tmp_reply, &txn->error)) {
803 ofpbuf_clear(txn->reply);
806 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
807 error, ovs_strerror(txn->error));
812 /* Copy the reply to the buffer specified by the caller. */
813 if (reply_len > txn->reply->allocated) {
814 ofpbuf_reinit(txn->reply, reply_len);
816 memcpy(ofpbuf_data(txn->reply), reply_buf, reply_len);
817 ofpbuf_set_size(txn->reply, reply_len);
820 ofpbuf_uninit(&tmp_reply);
822 /* Count the number of successful transactions. */
828 COVERAGE_ADD(netlink_sent, n);
836 nl_sock_transact_multiple(struct nl_sock *sock,
837 struct nl_transaction **transactions, size_t n)
846 /* In theory, every request could have a 64 kB reply. But the default and
847 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
848 * be a bit below 128 kB, so that would only allow a single message in a
849 * "batch". So we assume that replies average (at most) 4 kB, which allows
850 * a good deal of batching.
852 * In practice, most of the requests that we batch either have no reply at
853 * all or a brief reply. */
854 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
855 max_batch_count = MIN(max_batch_count, max_iovs);
861 /* Batch up to 'max_batch_count' transactions. But cap it at about a
862 * page of requests total because big skbuffs are expensive to
863 * allocate in the kernel. */
864 #if defined(PAGESIZE)
865 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
867 enum { MAX_BATCH_BYTES = 4096 - 512 };
869 bytes = ofpbuf_size(transactions[0]->request);
870 for (count = 1; count < n && count < max_batch_count; count++) {
871 if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
874 bytes += ofpbuf_size(transactions[count]->request);
877 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
878 transactions += done;
881 if (error == ENOBUFS) {
882 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
884 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
885 nl_sock_record_errors__(transactions, n, error);
891 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
892 struct ofpbuf **replyp)
894 struct nl_transaction *transactionp;
895 struct nl_transaction transaction;
897 transaction.request = CONST_CAST(struct ofpbuf *, request);
898 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
899 transactionp = &transaction;
901 nl_sock_transact_multiple(sock, &transactionp, 1);
904 if (transaction.error) {
905 ofpbuf_delete(transaction.reply);
908 *replyp = transaction.reply;
912 return transaction.error;
915 /* Drain all the messages currently in 'sock''s receive queue. */
917 nl_sock_drain(struct nl_sock *sock)
922 return drain_rcvbuf(sock->fd);
926 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
927 * Netlink socket created with the given 'protocol', and initializes 'dump' to
928 * reflect the state of the operation.
930 * 'request' must contain a Netlink message. Before sending the message,
931 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
932 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
935 * The design of this Netlink socket library ensures that the dump is reliable.
937 * This function provides no status indication. nl_dump_done() provides an
938 * error status for the entire dump operation.
940 * The caller must eventually destroy 'request'.
943 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
945 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
947 ovs_mutex_init(&dump->mutex);
948 ovs_mutex_lock(&dump->mutex);
949 dump->status = nl_pool_alloc(protocol, &dump->sock);
951 dump->status = nl_sock_send__(dump->sock, request,
952 nl_sock_allocate_seq(dump->sock, 1),
955 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
956 ovs_mutex_unlock(&dump->mutex);
960 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
961 OVS_REQUIRES(dump->mutex)
963 struct nlmsghdr *nlmsghdr;
966 while (!ofpbuf_size(buffer)) {
967 error = nl_sock_recv__(dump->sock, buffer, false);
969 /* The kernel never blocks providing the results of a dump, so
970 * error == EAGAIN means that we've read the whole thing, and
971 * therefore transform it into EOF. (The kernel always provides
972 * NLMSG_DONE as a sentinel. Some other thread must have received
973 * that already but not yet signaled it in 'status'.)
975 * Any other error is just an error. */
976 return error == EAGAIN ? EOF : error;
979 nlmsghdr = nl_msg_nlmsghdr(buffer);
980 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
981 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
982 nlmsghdr->nlmsg_seq, dump->nl_seq);
983 ofpbuf_clear(buffer);
987 if (nl_msg_nlmsgerr(buffer, &error) && error) {
988 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
989 ovs_strerror(error));
990 ofpbuf_clear(buffer);
998 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1000 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1002 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1004 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1011 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1012 * have been initialized with nl_dump_start(), and 'buffer' must have been
1013 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1015 * If successful, returns true and points 'reply->data' and
1016 * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
1017 * modify 'reply' (because it points within 'buffer', which will be used by
1018 * future calls to this function).
1020 * On failure, returns false and sets 'reply->data' to NULL and
1021 * 'ofpbuf_size(reply)' to 0. Failure might indicate an actual error or merely
1022 * the end of replies. An error status for the entire dump operation is
1023 * provided when it is completed by calling nl_dump_done().
1025 * Multiple threads may call this function, passing the same nl_dump, however
1026 * each must provide independent buffers. This function may cache multiple
1027 * replies in the buffer, and these will be processed before more replies are
1028 * fetched. When this function returns false, other threads may continue to
1029 * process replies in their buffers, but they will not fetch more replies.
1032 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1036 /* If the buffer is empty, refill it.
1038 * If the buffer is not empty, we don't check the dump's status.
1039 * Otherwise, we could end up skipping some of the dump results if thread A
1040 * hits EOF while thread B is in the midst of processing a batch. */
1041 if (!ofpbuf_size(buffer)) {
1042 ovs_mutex_lock(&dump->mutex);
1043 if (!dump->status) {
1044 /* Take the mutex here to avoid an in-kernel race. If two threads
1045 * try to read from a Netlink dump socket at once, then the socket
1046 * error can be set to EINVAL, which will be encountered on the
1047 * next recv on that socket, which could be anywhere due to the way
1048 * that we pool Netlink sockets. Serializing the recv calls avoids
1050 dump->status = nl_dump_refill(dump, buffer);
1052 retval = dump->status;
1053 ovs_mutex_unlock(&dump->mutex);
1056 /* Fetch the next message from the buffer. */
1058 retval = nl_dump_next__(reply, buffer);
1060 /* Record 'retval' as the dump status, but don't overwrite an error
1062 ovs_mutex_lock(&dump->mutex);
1063 if (dump->status <= 0) {
1064 dump->status = retval;
1066 ovs_mutex_unlock(&dump->mutex);
1071 ofpbuf_set_data(reply, NULL);
1072 ofpbuf_set_size(reply, 0);
1077 /* Completes Netlink dump operation 'dump', which must have been initialized
1078 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1079 * otherwise a positive errno value describing the problem. */
1081 nl_dump_done(struct nl_dump *dump)
1085 ovs_mutex_lock(&dump->mutex);
1086 status = dump->status;
1087 ovs_mutex_unlock(&dump->mutex);
1089 /* Drain any remaining messages that the client didn't read. Otherwise the
1090 * kernel will continue to queue them up and waste buffer space.
1092 * XXX We could just destroy and discard the socket in this case. */
1094 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1095 struct ofpbuf reply, buf;
1097 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1098 while (nl_dump_next(dump, &reply, &buf)) {
1099 /* Nothing to do. */
1101 ofpbuf_uninit(&buf);
1103 ovs_mutex_lock(&dump->mutex);
1104 status = dump->status;
1105 ovs_mutex_unlock(&dump->mutex);
1109 nl_pool_release(dump->sock);
1110 ovs_mutex_destroy(&dump->mutex);
1112 return status == EOF ? 0 : status;
1116 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1117 * an event or a packet is ready to be read. Once the I/O is completed
1118 * the overlapped structure event associated with the pending I/O will be set
1121 pend_io_request(const struct nl_sock *sock)
1123 struct ofpbuf request;
1124 uint64_t request_stub[128];
1125 struct ovs_header *ovs_header;
1126 struct nlmsghdr *nlmsg;
1131 OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
1133 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1134 sizeof (struct ovs_header);
1136 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1138 seq = nl_sock_allocate_seq(sock, 1);
1139 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1140 OVS_CTRL_CMD_WIN_PEND_REQ, OVS_WIN_CONTROL_VERSION);
1141 nlmsg = nl_msg_nlmsghdr(&request);
1142 nlmsg->nlmsg_seq = seq;
1144 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1145 ovs_header->dp_ifindex = 0;
1147 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1148 ofpbuf_data(&request), ofpbuf_size(&request),
1149 NULL, 0, &bytes, overlapped)) {
1150 error = GetLastError();
1151 /* Check if the I/O got pended */
1152 if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1153 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1158 /* The I/O was completed synchronously */
1159 poll_immediate_wake();
1164 ofpbuf_uninit(&request);
1169 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1170 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
1172 nl_sock_wait(const struct nl_sock *sock, short int events)
1175 if (sock->overlapped.Internal != STATUS_PENDING) {
1176 pend_io_request(sock);
1178 poll_fd_wait(sock->handle, events);
1180 poll_fd_wait(sock->fd, events);
1184 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1185 * that can't use nl_sock_wait().
1187 * It's a little tricky to use the returned fd correctly, because nl_sock does
1188 * "copy on write" to allow a single nl_sock to be used for notifications,
1189 * transactions, and dumps. If 'sock' is used only for notifications and
1190 * transactions (and never for dump) then the usage is safe. */
1192 nl_sock_fd(const struct nl_sock *sock)
1195 return sock->handle;
1201 /* Returns the PID associated with this socket. */
1203 nl_sock_pid(const struct nl_sock *sock)
1208 /* Miscellaneous. */
1210 struct genl_family {
1211 struct hmap_node hmap_node;
1216 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1218 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1219 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1220 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1223 static struct genl_family *
1224 find_genl_family_by_id(uint16_t id)
1226 struct genl_family *family;
1228 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1230 if (family->id == id) {
1238 define_genl_family(uint16_t id, const char *name)
1240 struct genl_family *family = find_genl_family_by_id(id);
1243 if (!strcmp(family->name, name)) {
1248 family = xmalloc(sizeof *family);
1250 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1252 family->name = xstrdup(name);
1256 genl_family_to_name(uint16_t id)
1258 if (id == GENL_ID_CTRL) {
1261 struct genl_family *family = find_genl_family_by_id(id);
1262 return family ? family->name : "unknown";
1268 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1269 struct ofpbuf **replyp)
1271 struct nl_sock *sock;
1272 struct ofpbuf request, *reply;
1276 error = nl_sock_create(NETLINK_GENERIC, &sock);
1281 ofpbuf_init(&request, 0);
1282 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1283 CTRL_CMD_GETFAMILY, 1);
1284 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1285 error = nl_sock_transact(sock, &request, &reply);
1286 ofpbuf_uninit(&request);
1288 nl_sock_destroy(sock);
1292 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1293 family_policy, attrs, ARRAY_SIZE(family_policy))
1294 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1295 nl_sock_destroy(sock);
1296 ofpbuf_delete(reply);
1300 nl_sock_destroy(sock);
1306 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1307 struct ofpbuf **replyp)
1309 struct nlmsghdr *nlmsg;
1310 struct ofpbuf *reply;
1313 const char *family_name;
1314 uint32_t family_version;
1315 uint32_t family_attrmax;
1316 uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1317 const char *mcgrp_name = NULL;
1320 reply = ofpbuf_new(1024);
1322 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1323 if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1324 family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1325 family_name = OVS_WIN_CONTROL_FAMILY;
1326 family_version = OVS_WIN_CONTROL_VERSION;
1327 family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1328 } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1329 family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1330 family_name = OVS_DATAPATH_FAMILY;
1331 family_version = OVS_DATAPATH_VERSION;
1332 family_attrmax = OVS_DP_ATTR_MAX;
1333 } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1334 family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1335 family_name = OVS_PACKET_FAMILY;
1336 family_version = OVS_PACKET_VERSION;
1337 family_attrmax = OVS_PACKET_ATTR_MAX;
1338 } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1339 family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1340 family_name = OVS_VPORT_FAMILY;
1341 family_version = OVS_VPORT_VERSION;
1342 family_attrmax = OVS_VPORT_ATTR_MAX;
1343 mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1344 mcgrp_name = OVS_VPORT_MCGROUP;
1345 } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1346 family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1347 family_name = OVS_FLOW_FAMILY;
1348 family_version = OVS_FLOW_VERSION;
1349 family_attrmax = OVS_FLOW_ATTR_MAX;
1350 } else if (!strcmp(name, OVS_WIN_NETDEV_FAMILY)) {
1351 family_id = OVS_WIN_NL_NETDEV_FAMILY_ID;
1352 family_name = OVS_WIN_NETDEV_FAMILY;
1353 family_version = OVS_WIN_NETDEV_VERSION;
1354 family_attrmax = OVS_WIN_NETDEV_ATTR_MAX;
1356 ofpbuf_delete(reply);
1360 nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1361 CTRL_CMD_NEWFAMILY, family_version);
1362 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1363 * callers do not seem to need them. */
1364 nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1365 nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1366 nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1367 nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1369 if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1370 size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1371 size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1372 OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1373 nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1374 ovs_assert(mcgrp_name != NULL);
1375 nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1376 nl_msg_end_nested(reply, mcgrp_ofs2);
1377 nl_msg_end_nested(reply, mcgrp_ofs1);
1380 /* Set the total length of the netlink message. */
1381 nlmsg = nl_msg_nlmsghdr(reply);
1382 nlmsg->nlmsg_len = ofpbuf_size(reply);
1384 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1385 family_policy, attrs, ARRAY_SIZE(family_policy))
1386 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1387 ofpbuf_delete(reply);
1396 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1397 * When successful, writes its result to 'multicast_group' and returns 0.
1398 * Otherwise, clears 'multicast_group' and returns a positive error code.
1401 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1402 unsigned int *multicast_group)
1404 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1405 const struct nlattr *mc;
1406 struct ofpbuf *reply;
1410 *multicast_group = 0;
1411 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1416 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1421 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1422 static const struct nl_policy mc_policy[] = {
1423 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1424 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1427 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1428 const char *mc_name;
1430 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1435 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1436 if (!strcmp(group_name, mc_name)) {
1438 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1446 ofpbuf_delete(reply);
1450 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1451 * number and stores it in '*number'. If successful, returns 0 and the caller
1452 * may use '*number' as the family number. On failure, returns a positive
1453 * errno value and '*number' caches the errno value. */
1455 nl_lookup_genl_family(const char *name, int *number)
1458 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1459 struct ofpbuf *reply;
1462 error = do_lookup_genl_family(name, attrs, &reply);
1464 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1465 define_genl_family(*number, name);
1469 ofpbuf_delete(reply);
1471 ovs_assert(*number != 0);
1473 return *number > 0 ? 0 : -*number;
1477 struct nl_sock *socks[16];
1481 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1482 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1485 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1487 struct nl_sock *sock = NULL;
1488 struct nl_pool *pool;
1490 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1492 ovs_mutex_lock(&pool_mutex);
1493 pool = &pools[protocol];
1495 sock = pool->socks[--pool->n];
1497 ovs_mutex_unlock(&pool_mutex);
1503 return nl_sock_create(protocol, sockp);
1508 nl_pool_release(struct nl_sock *sock)
1511 struct nl_pool *pool = &pools[sock->protocol];
1513 ovs_mutex_lock(&pool_mutex);
1514 if (pool->n < ARRAY_SIZE(pool->socks)) {
1515 pool->socks[pool->n++] = sock;
1518 ovs_mutex_unlock(&pool_mutex);
1520 nl_sock_destroy(sock);
1524 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1525 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1526 * successful, returns 0. On failure, returns a positive errno value.
1528 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1529 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1530 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1531 * reply, if any, is discarded.
1533 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1534 * match ofpbuf_size(msg), nlmsg_pid will be set to the pid of the socket used
1535 * for sending the request, and nlmsg_seq will be initialized.
1537 * The caller is responsible for destroying 'request'.
1539 * Bare Netlink is an unreliable transport protocol. This function layers
1540 * reliable delivery and reply semantics on top of bare Netlink.
1542 * In Netlink, sending a request to the kernel is reliable enough, because the
1543 * kernel will tell us if the message cannot be queued (and we will in that
1544 * case put it on the transmit queue and wait until it can be delivered).
1546 * Receiving the reply is the real problem: if the socket buffer is full when
1547 * the kernel tries to send the reply, the reply will be dropped. However, the
1548 * kernel sets a flag that a reply has been dropped. The next call to recv
1549 * then returns ENOBUFS. We can then re-send the request.
1553 * 1. Netlink depends on sequence numbers to match up requests and
1554 * replies. The sender of a request supplies a sequence number, and
1555 * the reply echos back that sequence number.
1557 * This is fine, but (1) some kernel netlink implementations are
1558 * broken, in that they fail to echo sequence numbers and (2) this
1559 * function will drop packets with non-matching sequence numbers, so
1560 * that only a single request can be usefully transacted at a time.
1562 * 2. Resending the request causes it to be re-executed, so the request
1563 * needs to be idempotent.
1566 nl_transact(int protocol, const struct ofpbuf *request,
1567 struct ofpbuf **replyp)
1569 struct nl_sock *sock;
1572 error = nl_pool_alloc(protocol, &sock);
1578 error = nl_sock_transact(sock, request, replyp);
1580 nl_pool_release(sock);
1584 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1585 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1586 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1587 * the 'error' member of each transaction with 0 if it was successful,
1588 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1589 * be filled with the reply if the message receives a detailed reply. In other
1590 * cases, i.e. where the request failed or had no reply beyond an indication of
1591 * success, 'reply' will be cleared if it is nonnull.
1593 * The caller is responsible for destroying each request and reply, and the
1594 * transactions array itself.
1596 * Before sending each message, this function will finalize nlmsg_len in each
1597 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1598 * used for the transaction, and initialize nlmsg_seq.
1600 * Bare Netlink is an unreliable transport protocol. This function layers
1601 * reliable delivery and reply semantics on top of bare Netlink. See
1602 * nl_transact() for some caveats.
1605 nl_transact_multiple(int protocol,
1606 struct nl_transaction **transactions, size_t n)
1608 struct nl_sock *sock;
1611 error = nl_pool_alloc(protocol, &sock);
1613 nl_sock_transact_multiple(sock, transactions, n);
1614 nl_pool_release(sock);
1616 nl_sock_record_errors__(transactions, n, error);
1622 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1624 uint32_t seq = sock->next_seq;
1626 sock->next_seq += n;
1628 /* Make it impossible for the next request for sequence numbers to wrap
1629 * around to 0. Start over with 1 to avoid ever using a sequence number of
1630 * 0, because the kernel uses sequence number 0 for notifications. */
1631 if (sock->next_seq >= UINT32_MAX / 2) {
1639 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1645 static const struct nlmsg_flag flags[] = {
1646 { NLM_F_REQUEST, "REQUEST" },
1647 { NLM_F_MULTI, "MULTI" },
1648 { NLM_F_ACK, "ACK" },
1649 { NLM_F_ECHO, "ECHO" },
1650 { NLM_F_DUMP, "DUMP" },
1651 { NLM_F_ROOT, "ROOT" },
1652 { NLM_F_MATCH, "MATCH" },
1653 { NLM_F_ATOMIC, "ATOMIC" },
1655 const struct nlmsg_flag *flag;
1656 uint16_t flags_left;
1658 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1659 h->nlmsg_len, h->nlmsg_type);
1660 if (h->nlmsg_type == NLMSG_NOOP) {
1661 ds_put_cstr(ds, "(no-op)");
1662 } else if (h->nlmsg_type == NLMSG_ERROR) {
1663 ds_put_cstr(ds, "(error)");
1664 } else if (h->nlmsg_type == NLMSG_DONE) {
1665 ds_put_cstr(ds, "(done)");
1666 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1667 ds_put_cstr(ds, "(overrun)");
1668 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1669 ds_put_cstr(ds, "(reserved)");
1670 } else if (protocol == NETLINK_GENERIC) {
1671 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1673 ds_put_cstr(ds, "(family-defined)");
1675 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1676 flags_left = h->nlmsg_flags;
1677 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1678 if ((flags_left & flag->bits) == flag->bits) {
1679 ds_put_format(ds, "[%s]", flag->name);
1680 flags_left &= ~flag->bits;
1684 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1686 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1687 h->nlmsg_seq, h->nlmsg_pid);
1691 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1693 struct ds ds = DS_EMPTY_INITIALIZER;
1694 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1696 nlmsghdr_to_string(h, protocol, &ds);
1697 if (h->nlmsg_type == NLMSG_ERROR) {
1698 const struct nlmsgerr *e;
1699 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1700 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1702 ds_put_format(&ds, " error(%d", e->error);
1704 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1706 ds_put_cstr(&ds, ", in-reply-to(");
1707 nlmsghdr_to_string(&e->msg, protocol, &ds);
1708 ds_put_cstr(&ds, "))");
1710 ds_put_cstr(&ds, " error(truncated)");
1712 } else if (h->nlmsg_type == NLMSG_DONE) {
1713 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1715 ds_put_format(&ds, " done(%d", *error);
1717 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1719 ds_put_cstr(&ds, ")");
1721 ds_put_cstr(&ds, " done(truncated)");
1723 } else if (protocol == NETLINK_GENERIC) {
1724 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1726 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1727 genl->cmd, genl->version);
1731 ds_put_cstr(&ds, "nl(truncated)");
1737 log_nlmsg(const char *function, int error,
1738 const void *message, size_t size, int protocol)
1740 struct ofpbuf buffer;
1743 if (!VLOG_IS_DBG_ENABLED()) {
1747 ofpbuf_use_const(&buffer, message, size);
1748 nlmsg = nlmsg_to_string(&buffer, protocol);
1749 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);