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"
32 #include "ovs-thread.h"
33 #include "poll-loop.h"
35 #include "socket-util.h"
39 VLOG_DEFINE_THIS_MODULE(netlink_socket);
41 COVERAGE_DEFINE(netlink_overflow);
42 COVERAGE_DEFINE(netlink_received);
43 COVERAGE_DEFINE(netlink_recv_jumbo);
44 COVERAGE_DEFINE(netlink_sent);
46 /* Linux header file confusion causes this to be undefined. */
48 #define SOL_NETLINK 270
51 /* A single (bad) Netlink message can in theory dump out many, many log
52 * messages, so the burst size is set quite high here to avoid missing useful
53 * information. Also, at high logging levels we log *all* Netlink messages. */
54 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
56 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
57 static void log_nlmsg(const char *function, int error,
58 const void *message, size_t size, int protocol);
60 /* Netlink sockets. */
67 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
70 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
71 * of iovecs on the stack. */
74 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
75 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
77 * Initialized by nl_sock_create(). */
80 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
81 static void nl_pool_release(struct nl_sock *);
83 /* Creates a new netlink socket for the given netlink 'protocol'
84 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
85 * new socket if successful, otherwise returns a positive errno value. */
87 nl_sock_create(int protocol, struct nl_sock **sockp)
89 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
91 struct sockaddr_nl local, remote;
96 if (ovsthread_once_start(&once)) {
97 int save_errno = errno;
100 max_iovs = sysconf(_SC_UIO_MAXIOV);
101 if (max_iovs < _XOPEN_IOV_MAX) {
102 if (max_iovs == -1 && errno) {
103 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
105 max_iovs = _XOPEN_IOV_MAX;
106 } else if (max_iovs > MAX_IOVS) {
111 ovsthread_once_done(&once);
115 sock = xmalloc(sizeof *sock);
117 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
119 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
122 sock->protocol = protocol;
125 rcvbuf = 1024 * 1024;
126 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
127 &rcvbuf, sizeof rcvbuf)) {
128 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
129 * Warn only if the failure is therefore unexpected. */
130 if (errno != EPERM) {
131 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
132 "(%s)", rcvbuf, ovs_strerror(errno));
136 retval = get_socket_rcvbuf(sock->fd);
141 sock->rcvbuf = retval;
143 /* Connect to kernel (pid 0) as remote address. */
144 memset(&remote, 0, sizeof remote);
145 remote.nl_family = AF_NETLINK;
147 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
148 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
152 /* Obtain pid assigned by kernel. */
153 local_size = sizeof local;
154 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
155 VLOG_ERR("getsockname: %s", ovs_strerror(errno));
158 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
159 VLOG_ERR("getsockname returned bad Netlink name");
163 sock->pid = local.nl_pid;
182 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
183 * sets '*sockp' to the new socket if successful, otherwise returns a positive
186 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
188 return nl_sock_create(src->protocol, sockp);
191 /* Destroys netlink socket 'sock'. */
193 nl_sock_destroy(struct nl_sock *sock)
201 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
202 * successful, otherwise a positive errno value.
204 * A socket that is subscribed to a multicast group that receives asynchronous
205 * notifications must not be used for Netlink transactions or dumps, because
206 * transactions and dumps can cause notifications to be lost.
208 * Multicast group numbers are always positive.
210 * It is not an error to attempt to join a multicast group to which a socket
211 * already belongs. */
213 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
215 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
216 &multicast_group, sizeof multicast_group) < 0) {
217 VLOG_WARN("could not join multicast group %u (%s)",
218 multicast_group, ovs_strerror(errno));
224 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
225 * successful, otherwise a positive errno value.
227 * Multicast group numbers are always positive.
229 * It is not an error to attempt to leave a multicast group to which a socket
232 * On success, reading from 'sock' will still return any messages that were
233 * received on 'multicast_group' before the group was left. */
235 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
237 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
238 &multicast_group, sizeof multicast_group) < 0) {
239 VLOG_WARN("could not leave multicast group %u (%s)",
240 multicast_group, ovs_strerror(errno));
247 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
248 uint32_t nlmsg_seq, bool wait)
250 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
253 nlmsg->nlmsg_len = ofpbuf_size(msg);
254 nlmsg->nlmsg_seq = nlmsg_seq;
255 nlmsg->nlmsg_pid = sock->pid;
258 retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg), wait ? 0 : MSG_DONTWAIT);
259 error = retval < 0 ? errno : 0;
260 } while (error == EINTR);
261 log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
263 COVERAGE_INC(netlink_sent);
268 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
269 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
270 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
271 * sequence number, before the message is sent.
273 * Returns 0 if successful, otherwise a positive errno value. If
274 * 'wait' is true, then the send will wait until buffer space is ready;
275 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
277 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
279 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
282 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
283 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
284 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
285 * 'nlmsg_seq', before the message is sent.
287 * Returns 0 if successful, otherwise a positive errno value. If
288 * 'wait' is true, then the send will wait until buffer space is ready;
289 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
291 * This function is suitable for sending a reply to a request that was received
292 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
294 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
295 uint32_t nlmsg_seq, bool wait)
297 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
301 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
303 /* We can't accurately predict the size of the data to be received. The
304 * caller is supposed to have allocated enough space in 'buf' to handle the
305 * "typical" case. To handle exceptions, we make available enough space in
306 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
307 * figure since that's the maximum length of a Netlink attribute). */
308 struct nlmsghdr *nlmsghdr;
315 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
318 iov[0].iov_base = ofpbuf_base(buf);
319 iov[0].iov_len = buf->allocated;
320 iov[1].iov_base = tail;
321 iov[1].iov_len = sizeof tail;
323 memset(&msg, 0, sizeof msg);
327 /* Receive a Netlink message from the kernel.
329 * This works around a kernel bug in which the kernel returns an error code
330 * as if it were the number of bytes read. It doesn't actually modify
331 * anything in the receive buffer in that case, so we can initialize the
332 * Netlink header with an impossible message length and then, upon success,
333 * check whether it changed. */
334 nlmsghdr = ofpbuf_base(buf);
336 nlmsghdr->nlmsg_len = UINT32_MAX;
337 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
338 error = (retval < 0 ? errno
339 : retval == 0 ? ECONNRESET /* not possible? */
340 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
342 } while (error == EINTR);
344 if (error == ENOBUFS) {
345 /* Socket receive buffer overflow dropped one or more messages that
346 * the kernel tried to send to us. */
347 COVERAGE_INC(netlink_overflow);
352 if (msg.msg_flags & MSG_TRUNC) {
353 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
358 if (retval < sizeof *nlmsghdr
359 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
360 || nlmsghdr->nlmsg_len > retval) {
361 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
362 retval, sizeof *nlmsghdr);
366 ofpbuf_set_size(buf, MIN(retval, buf->allocated));
367 if (retval > buf->allocated) {
368 COVERAGE_INC(netlink_recv_jumbo);
369 ofpbuf_put(buf, tail, retval - buf->allocated);
372 log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
373 COVERAGE_INC(netlink_received);
378 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
379 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
380 * EAGAIN if the 'sock' receive buffer is empty.
382 * The caller must have initialized 'buf' with an allocation of at least
383 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
384 * space for a "typical" message.
386 * On success, returns 0 and replaces 'buf''s previous content by the received
387 * message. This function expands 'buf''s allocated memory, as necessary, to
388 * hold the actual size of the received message.
390 * On failure, returns a positive errno value and clears 'buf' to zero length.
391 * 'buf' retains its previous memory allocation.
393 * Regardless of success or failure, this function resets 'buf''s headroom to
396 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
398 return nl_sock_recv__(sock, buf, wait);
402 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
407 for (i = 0; i < n; i++) {
408 struct nl_transaction *txn = transactions[i];
412 ofpbuf_clear(txn->reply);
418 nl_sock_transact_multiple__(struct nl_sock *sock,
419 struct nl_transaction **transactions, size_t n,
422 uint64_t tmp_reply_stub[1024 / 8];
423 struct nl_transaction tmp_txn;
424 struct ofpbuf tmp_reply;
427 struct iovec iovs[MAX_IOVS];
432 base_seq = nl_sock_allocate_seq(sock, n);
434 for (i = 0; i < n; i++) {
435 struct nl_transaction *txn = transactions[i];
436 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
438 nlmsg->nlmsg_len = ofpbuf_size(txn->request);
439 nlmsg->nlmsg_seq = base_seq + i;
440 nlmsg->nlmsg_pid = sock->pid;
442 iovs[i].iov_base = ofpbuf_data(txn->request);
443 iovs[i].iov_len = ofpbuf_size(txn->request);
446 memset(&msg, 0, sizeof msg);
450 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
451 } while (error == EINTR);
453 for (i = 0; i < n; i++) {
454 struct nl_transaction *txn = transactions[i];
456 log_nlmsg(__func__, error, ofpbuf_data(txn->request), ofpbuf_size(txn->request),
460 COVERAGE_ADD(netlink_sent, n);
467 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
468 tmp_txn.request = NULL;
469 tmp_txn.reply = &tmp_reply;
472 struct nl_transaction *buf_txn, *txn;
475 /* Find a transaction whose buffer we can use for receiving a reply.
476 * If no such transaction is left, use tmp_txn. */
478 for (i = 0; i < n; i++) {
479 if (transactions[i]->reply) {
480 buf_txn = transactions[i];
485 /* Receive a reply. */
486 error = nl_sock_recv__(sock, buf_txn->reply, false);
488 if (error == EAGAIN) {
489 nl_sock_record_errors__(transactions, n, 0);
496 /* Match the reply up with a transaction. */
497 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
498 if (seq < base_seq || seq >= base_seq + n) {
499 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
503 txn = transactions[i];
505 /* Fill in the results for 'txn'. */
506 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
508 ofpbuf_clear(txn->reply);
511 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
512 error, ovs_strerror(txn->error));
516 if (txn->reply && txn != buf_txn) {
518 struct ofpbuf *reply = buf_txn->reply;
519 buf_txn->reply = txn->reply;
524 /* Fill in the results for transactions before 'txn'. (We have to do
525 * this after the results for 'txn' itself because of the buffer swap
527 nl_sock_record_errors__(transactions, i, 0);
531 transactions += i + 1;
535 ofpbuf_uninit(&tmp_reply);
540 /* Sends the 'request' member of the 'n' transactions in 'transactions' on
541 * 'sock', in order, and receives responses to all of them. Fills in the
542 * 'error' member of each transaction with 0 if it was successful, otherwise
543 * with a positive errno value. If 'reply' is nonnull, then it will be filled
544 * with the reply if the message receives a detailed reply. In other cases,
545 * i.e. where the request failed or had no reply beyond an indication of
546 * success, 'reply' will be cleared if it is nonnull.
548 * The caller is responsible for destroying each request and reply, and the
549 * transactions array itself.
551 * Before sending each message, this function will finalize nlmsg_len in each
552 * 'request' to match the ofpbuf's size, set nlmsg_pid to 'sock''s pid, and
553 * initialize nlmsg_seq.
555 * Bare Netlink is an unreliable transport protocol. This function layers
556 * reliable delivery and reply semantics on top of bare Netlink. See
557 * nl_sock_transact() for some caveats.
560 nl_sock_transact_multiple(struct nl_sock *sock,
561 struct nl_transaction **transactions, size_t n)
570 /* In theory, every request could have a 64 kB reply. But the default and
571 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
572 * be a bit below 128 kB, so that would only allow a single message in a
573 * "batch". So we assume that replies average (at most) 4 kB, which allows
574 * a good deal of batching.
576 * In practice, most of the requests that we batch either have no reply at
577 * all or a brief reply. */
578 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
579 max_batch_count = MIN(max_batch_count, max_iovs);
585 /* Batch up to 'max_batch_count' transactions. But cap it at about a
586 * page of requests total because big skbuffs are expensive to
587 * allocate in the kernel. */
588 #if defined(PAGESIZE)
589 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
591 enum { MAX_BATCH_BYTES = 4096 - 512 };
593 bytes = ofpbuf_size(transactions[0]->request);
594 for (count = 1; count < n && count < max_batch_count; count++) {
595 if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
598 bytes += ofpbuf_size(transactions[count]->request);
601 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
602 transactions += done;
605 if (error == ENOBUFS) {
606 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
608 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
609 nl_sock_record_errors__(transactions, n, error);
614 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
615 * successful, returns 0. On failure, returns a positive errno value.
617 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
618 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
619 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
620 * reply, if any, is discarded.
622 * Before the message is sent, nlmsg_len in 'request' will be finalized to
623 * match ofpbuf_size(msg), nlmsg_pid will be set to 'sock''s pid, and nlmsg_seq will
624 * be initialized, NLM_F_ACK will be set in nlmsg_flags.
626 * The caller is responsible for destroying 'request'.
628 * Bare Netlink is an unreliable transport protocol. This function layers
629 * reliable delivery and reply semantics on top of bare Netlink.
631 * In Netlink, sending a request to the kernel is reliable enough, because the
632 * kernel will tell us if the message cannot be queued (and we will in that
633 * case put it on the transmit queue and wait until it can be delivered).
635 * Receiving the reply is the real problem: if the socket buffer is full when
636 * the kernel tries to send the reply, the reply will be dropped. However, the
637 * kernel sets a flag that a reply has been dropped. The next call to recv
638 * then returns ENOBUFS. We can then re-send the request.
642 * 1. Netlink depends on sequence numbers to match up requests and
643 * replies. The sender of a request supplies a sequence number, and
644 * the reply echos back that sequence number.
646 * This is fine, but (1) some kernel netlink implementations are
647 * broken, in that they fail to echo sequence numbers and (2) this
648 * function will drop packets with non-matching sequence numbers, so
649 * that only a single request can be usefully transacted at a time.
651 * 2. Resending the request causes it to be re-executed, so the request
652 * needs to be idempotent.
655 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
656 struct ofpbuf **replyp)
658 struct nl_transaction *transactionp;
659 struct nl_transaction transaction;
661 transaction.request = CONST_CAST(struct ofpbuf *, request);
662 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
663 transactionp = &transaction;
665 nl_sock_transact_multiple(sock, &transactionp, 1);
668 if (transaction.error) {
669 ofpbuf_delete(transaction.reply);
672 *replyp = transaction.reply;
676 return transaction.error;
679 /* Drain all the messages currently in 'sock''s receive queue. */
681 nl_sock_drain(struct nl_sock *sock)
683 return drain_rcvbuf(sock->fd);
686 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
687 * Netlink socket created with the given 'protocol', and initializes 'dump' to
688 * reflect the state of the operation.
690 * 'request' must contain a Netlink message. Before sending the message,
691 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
692 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
695 * The design of this Netlink socket library ensures that the dump is reliable.
697 * This function provides no status indication. nl_dump_done() provides an
698 * error status for the entire dump operation.
700 * The caller must eventually destroy 'request'.
703 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
705 int status = nl_pool_alloc(protocol, &dump->sock);
711 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
712 status = nl_sock_send__(dump->sock, request,
713 nl_sock_allocate_seq(dump->sock, 1), true);
714 atomic_init(&dump->status, status << 1);
715 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
716 dump->status_seq = seq_create();
719 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
720 * have been initialized with nl_dump_start(), and 'buffer' must have been
721 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
723 * If successful, returns true and points 'reply->data' and 'ofpbuf_size(reply)' to
724 * the message that was retrieved. The caller must not modify 'reply' (because
725 * it points within 'buffer', which will be used by future calls to this
728 * On failure, returns false and sets 'reply->data' to NULL and 'ofpbuf_size(reply)'
729 * to 0. Failure might indicate an actual error or merely the end of replies.
730 * An error status for the entire dump operation is provided when it is
731 * completed by calling nl_dump_done().
733 * Multiple threads may call this function, passing the same nl_dump, however
734 * each must provide independent buffers. This function may cache multiple
735 * replies in the buffer, and these will be processed before more replies are
736 * fetched. When this function returns false, other threads may continue to
737 * process replies in their buffers, but they will not fetch more replies.
740 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
742 struct nlmsghdr *nlmsghdr;
745 ofpbuf_set_data(reply, NULL);
746 ofpbuf_set_size(reply, 0);
748 /* If 'buffer' is empty, fetch another batch of nlmsgs. */
749 while (!ofpbuf_size(buffer)) {
753 seq = seq_read(dump->status_seq);
754 atomic_read(&dump->status, &status);
759 retval = nl_sock_recv__(dump->sock, buffer, false);
761 ofpbuf_clear(buffer);
762 if (retval == EAGAIN) {
763 nl_sock_wait(dump->sock, POLLIN);
764 seq_wait(dump->status_seq, seq);
773 nlmsghdr = nl_msg_nlmsghdr(buffer);
774 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
775 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
776 nlmsghdr->nlmsg_seq, dump->nl_seq);
777 ofpbuf_clear(buffer);
781 if (nl_msg_nlmsgerr(buffer, &retval) && retval) {
782 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
783 ovs_strerror(retval));
784 error = retval == EAGAIN ? EPROTO : retval;
785 ofpbuf_clear(buffer);
790 /* Fetch the next nlmsg in the current batch. */
791 nlmsghdr = nl_msg_next(buffer, reply);
793 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
795 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
802 atomic_or(&dump->status, 1, &old);
803 seq_change(dump->status_seq);
805 atomic_store(&dump->status, error << 1);
806 seq_change(dump->status_seq);
811 /* Completes Netlink dump operation 'dump', which must have been initialized
812 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
813 * otherwise a positive errno value describing the problem. */
815 nl_dump_done(struct nl_dump *dump)
819 /* Drain any remaining messages that the client didn't read. Otherwise the
820 * kernel will continue to queue them up and waste buffer space.
822 * XXX We could just destroy and discard the socket in this case. */
823 atomic_read(&dump->status, &status);
825 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
826 struct ofpbuf reply, buf;
828 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
829 while (nl_dump_next(dump, &reply, &buf)) {
832 atomic_read(&dump->status, &status);
836 nl_pool_release(dump->sock);
837 seq_destroy(dump->status_seq);
841 /* Causes poll_block() to wake up when any of the specified 'events' (which is
842 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
844 nl_sock_wait(const struct nl_sock *sock, short int events)
846 poll_fd_wait(sock->fd, events);
849 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
850 * that can't use nl_sock_wait().
852 * It's a little tricky to use the returned fd correctly, because nl_sock does
853 * "copy on write" to allow a single nl_sock to be used for notifications,
854 * transactions, and dumps. If 'sock' is used only for notifications and
855 * transactions (and never for dump) then the usage is safe. */
857 nl_sock_fd(const struct nl_sock *sock)
862 /* Returns the PID associated with this socket. */
864 nl_sock_pid(const struct nl_sock *sock)
872 struct hmap_node hmap_node;
877 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
879 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
880 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
881 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
884 static struct genl_family *
885 find_genl_family_by_id(uint16_t id)
887 struct genl_family *family;
889 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
891 if (family->id == id) {
899 define_genl_family(uint16_t id, const char *name)
901 struct genl_family *family = find_genl_family_by_id(id);
904 if (!strcmp(family->name, name)) {
909 family = xmalloc(sizeof *family);
911 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
913 family->name = xstrdup(name);
917 genl_family_to_name(uint16_t id)
919 if (id == GENL_ID_CTRL) {
922 struct genl_family *family = find_genl_family_by_id(id);
923 return family ? family->name : "unknown";
928 do_lookup_genl_family(const char *name, struct nlattr **attrs,
929 struct ofpbuf **replyp)
931 struct nl_sock *sock;
932 struct ofpbuf request, *reply;
936 error = nl_sock_create(NETLINK_GENERIC, &sock);
941 ofpbuf_init(&request, 0);
942 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
943 CTRL_CMD_GETFAMILY, 1);
944 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
945 error = nl_sock_transact(sock, &request, &reply);
946 ofpbuf_uninit(&request);
948 nl_sock_destroy(sock);
952 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
953 family_policy, attrs, ARRAY_SIZE(family_policy))
954 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
955 nl_sock_destroy(sock);
956 ofpbuf_delete(reply);
960 nl_sock_destroy(sock);
965 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
966 * When successful, writes its result to 'multicast_group' and returns 0.
967 * Otherwise, clears 'multicast_group' and returns a positive error code.
970 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
971 unsigned int *multicast_group)
973 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
974 const struct nlattr *mc;
975 struct ofpbuf *reply;
979 *multicast_group = 0;
980 error = do_lookup_genl_family(family_name, family_attrs, &reply);
985 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
990 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
991 static const struct nl_policy mc_policy[] = {
992 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
993 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
996 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
999 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1004 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1005 if (!strcmp(group_name, mc_name)) {
1007 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1015 ofpbuf_delete(reply);
1019 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1020 * number and stores it in '*number'. If successful, returns 0 and the caller
1021 * may use '*number' as the family number. On failure, returns a positive
1022 * errno value and '*number' caches the errno value. */
1024 nl_lookup_genl_family(const char *name, int *number)
1027 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1028 struct ofpbuf *reply;
1031 error = do_lookup_genl_family(name, attrs, &reply);
1033 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1034 define_genl_family(*number, name);
1038 ofpbuf_delete(reply);
1040 ovs_assert(*number != 0);
1042 return *number > 0 ? 0 : -*number;
1046 struct nl_sock *socks[16];
1050 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1051 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1054 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1056 struct nl_sock *sock = NULL;
1057 struct nl_pool *pool;
1059 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1061 ovs_mutex_lock(&pool_mutex);
1062 pool = &pools[protocol];
1064 sock = pool->socks[--pool->n];
1066 ovs_mutex_unlock(&pool_mutex);
1072 return nl_sock_create(protocol, sockp);
1077 nl_pool_release(struct nl_sock *sock)
1080 struct nl_pool *pool = &pools[sock->protocol];
1082 ovs_mutex_lock(&pool_mutex);
1083 if (pool->n < ARRAY_SIZE(pool->socks)) {
1084 pool->socks[pool->n++] = sock;
1087 ovs_mutex_unlock(&pool_mutex);
1089 nl_sock_destroy(sock);
1094 nl_transact(int protocol, const struct ofpbuf *request,
1095 struct ofpbuf **replyp)
1097 struct nl_sock *sock;
1100 error = nl_pool_alloc(protocol, &sock);
1106 error = nl_sock_transact(sock, request, replyp);
1108 nl_pool_release(sock);
1113 nl_transact_multiple(int protocol,
1114 struct nl_transaction **transactions, size_t n)
1116 struct nl_sock *sock;
1119 error = nl_pool_alloc(protocol, &sock);
1121 nl_sock_transact_multiple(sock, transactions, n);
1122 nl_pool_release(sock);
1124 nl_sock_record_errors__(transactions, n, error);
1130 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1132 uint32_t seq = sock->next_seq;
1134 sock->next_seq += n;
1136 /* Make it impossible for the next request for sequence numbers to wrap
1137 * around to 0. Start over with 1 to avoid ever using a sequence number of
1138 * 0, because the kernel uses sequence number 0 for notifications. */
1139 if (sock->next_seq >= UINT32_MAX / 2) {
1147 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1153 static const struct nlmsg_flag flags[] = {
1154 { NLM_F_REQUEST, "REQUEST" },
1155 { NLM_F_MULTI, "MULTI" },
1156 { NLM_F_ACK, "ACK" },
1157 { NLM_F_ECHO, "ECHO" },
1158 { NLM_F_DUMP, "DUMP" },
1159 { NLM_F_ROOT, "ROOT" },
1160 { NLM_F_MATCH, "MATCH" },
1161 { NLM_F_ATOMIC, "ATOMIC" },
1163 const struct nlmsg_flag *flag;
1164 uint16_t flags_left;
1166 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1167 h->nlmsg_len, h->nlmsg_type);
1168 if (h->nlmsg_type == NLMSG_NOOP) {
1169 ds_put_cstr(ds, "(no-op)");
1170 } else if (h->nlmsg_type == NLMSG_ERROR) {
1171 ds_put_cstr(ds, "(error)");
1172 } else if (h->nlmsg_type == NLMSG_DONE) {
1173 ds_put_cstr(ds, "(done)");
1174 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1175 ds_put_cstr(ds, "(overrun)");
1176 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1177 ds_put_cstr(ds, "(reserved)");
1178 } else if (protocol == NETLINK_GENERIC) {
1179 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1181 ds_put_cstr(ds, "(family-defined)");
1183 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1184 flags_left = h->nlmsg_flags;
1185 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1186 if ((flags_left & flag->bits) == flag->bits) {
1187 ds_put_format(ds, "[%s]", flag->name);
1188 flags_left &= ~flag->bits;
1192 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1194 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1195 h->nlmsg_seq, h->nlmsg_pid);
1199 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1201 struct ds ds = DS_EMPTY_INITIALIZER;
1202 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1204 nlmsghdr_to_string(h, protocol, &ds);
1205 if (h->nlmsg_type == NLMSG_ERROR) {
1206 const struct nlmsgerr *e;
1207 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1208 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1210 ds_put_format(&ds, " error(%d", e->error);
1212 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1214 ds_put_cstr(&ds, ", in-reply-to(");
1215 nlmsghdr_to_string(&e->msg, protocol, &ds);
1216 ds_put_cstr(&ds, "))");
1218 ds_put_cstr(&ds, " error(truncated)");
1220 } else if (h->nlmsg_type == NLMSG_DONE) {
1221 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1223 ds_put_format(&ds, " done(%d", *error);
1225 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1227 ds_put_cstr(&ds, ")");
1229 ds_put_cstr(&ds, " done(truncated)");
1231 } else if (protocol == NETLINK_GENERIC) {
1232 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1234 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1235 genl->cmd, genl->version);
1239 ds_put_cstr(&ds, "nl(truncated)");
1245 log_nlmsg(const char *function, int error,
1246 const void *message, size_t size, int protocol)
1248 struct ofpbuf buffer;
1251 if (!VLOG_IS_DBG_ENABLED()) {
1255 ofpbuf_use_const(&buffer, message, size);
1256 nlmsg = nlmsg_to_string(&buffer, protocol);
1257 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);