2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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"
23 #include <sys/types.h>
26 #include "dynamic-string.h"
28 #include "netlink-protocol.h"
30 #include "poll-loop.h"
34 VLOG_DEFINE_THIS_MODULE(netlink_socket);
36 COVERAGE_DEFINE(netlink_overflow);
37 COVERAGE_DEFINE(netlink_received);
38 COVERAGE_DEFINE(netlink_recv_retry);
39 COVERAGE_DEFINE(netlink_send);
40 COVERAGE_DEFINE(netlink_sent);
42 /* Linux header file confusion causes this to be undefined. */
44 #define SOL_NETLINK 270
47 /* A single (bad) Netlink message can in theory dump out many, many log
48 * messages, so the burst size is set quite high here to avoid missing useful
49 * information. Also, at high logging levels we log *all* Netlink messages. */
50 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
52 static void log_nlmsg(const char *function, int error,
53 const void *message, size_t size);
55 /* Netlink sockets. */
63 static int alloc_pid(uint32_t *);
64 static void free_pid(uint32_t);
66 /* Creates a new netlink socket for the given netlink 'protocol'
67 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
68 * new socket if successful, otherwise returns a positive errno value. */
70 nl_sock_create(int protocol, struct nl_sock **sockp)
73 struct sockaddr_nl local, remote;
77 sock = malloc(sizeof *sock);
82 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
84 VLOG_ERR("fcntl: %s", strerror(errno));
88 retval = alloc_pid(&sock->pid);
93 /* Bind local address as our selected pid. */
94 memset(&local, 0, sizeof local);
95 local.nl_family = AF_NETLINK;
96 local.nl_pid = sock->pid;
97 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
98 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
102 /* Bind remote address as the kernel (pid 0). */
103 memset(&remote, 0, sizeof remote);
104 remote.nl_family = AF_NETLINK;
106 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
107 VLOG_ERR("connect(0): %s", strerror(errno));
130 /* Destroys netlink socket 'sock'. */
132 nl_sock_destroy(struct nl_sock *sock)
141 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
142 * successful, otherwise a positive errno value.
144 * Multicast group numbers are always positive.
146 * It is not an error to attempt to join a multicast group to which a socket
147 * already belongs. */
149 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
151 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
152 &multicast_group, sizeof multicast_group) < 0) {
153 VLOG_WARN("could not join multicast group %u (%s)",
154 multicast_group, strerror(errno));
160 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
161 * successful, otherwise a positive errno value.
163 * Multicast group numbers are always positive.
165 * It is not an error to attempt to leave a multicast group to which a socket
168 * On success, reading from 'sock' will still return any messages that were
169 * received on 'multicast_group' before the group was left. */
171 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
173 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
174 &multicast_group, sizeof multicast_group) < 0) {
175 VLOG_WARN("could not leave multicast group %u (%s)",
176 multicast_group, strerror(errno));
182 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
183 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, and
184 * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
186 * Returns 0 if successful, otherwise a positive errno value. If
187 * 'wait' is true, then the send will wait until buffer space is ready;
188 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
190 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
192 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
195 nlmsg->nlmsg_len = msg->size;
196 nlmsg->nlmsg_pid = sock->pid;
199 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
200 error = retval < 0 ? errno : 0;
201 } while (error == EINTR);
202 log_nlmsg(__func__, error, msg->data, msg->size);
204 COVERAGE_INC(netlink_sent);
209 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
210 * a single Netlink message. (The message must be fully formed and not require
211 * finalization of its nlmsg_len or nlmsg_pid fields.)
213 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
214 * true, then the send will wait until buffer space is ready; otherwise,
215 * returns EAGAIN if the 'sock' send buffer is full. */
217 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
223 COVERAGE_INC(netlink_send);
224 memset(&msg, 0, sizeof msg);
225 msg.msg_iov = (struct iovec *) iov;
226 msg.msg_iovlen = n_iov;
229 retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
230 error = retval < 0 ? errno : 0;
231 } while (error == EINTR);
232 if (error != EAGAIN) {
233 log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len);
235 COVERAGE_INC(netlink_sent);
241 /* This stress option is useful for testing that OVS properly tolerates
242 * -ENOBUFS on NetLink sockets. Such errors are unavoidable because they can
243 * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
244 * reply to a request. They can also occur if messages arrive on a multicast
245 * channel faster than OVS can process them. */
247 netlink_overflow, "simulate netlink socket receive buffer overflow",
250 /* Tries to receive a netlink message from the kernel on 'sock'. If
251 * successful, stores the received message into '*bufp' and returns 0. The
252 * caller is responsible for destroying the message with ofpbuf_delete(). On
253 * failure, returns a positive errno value and stores a null pointer into
256 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
257 * returns EAGAIN if the 'sock' receive buffer is empty. */
259 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
262 ssize_t bufsize = 2048;
263 ssize_t nbytes, nbytes2;
265 struct nlmsghdr *nlmsghdr;
267 struct msghdr msg = {
277 buf = ofpbuf_new(bufsize);
281 /* Attempt to read the message. We don't know the size of the data
282 * yet, so we take a guess at 2048. If we're wrong, we keep trying
283 * and doubling the buffer size each time.
285 nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
286 iov.iov_base = nlmsghdr;
287 iov.iov_len = bufsize;
289 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
290 } while (nbytes < 0 && errno == EINTR);
295 if (msg.msg_flags & MSG_TRUNC) {
296 COVERAGE_INC(netlink_recv_retry);
298 ofpbuf_reinit(buf, bufsize);
303 /* We successfully read the message, so recv again to clear the queue */
307 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
308 } while (nbytes2 < 0 && errno == EINTR);
310 if (errno == ENOBUFS) {
311 /* The kernel is notifying us that a message it tried to send to us
312 * was dropped. We have to pass this along to the caller in case
313 * it wants to retry a request. So kill the buffer, which we can
314 * re-read next time. */
315 COVERAGE_INC(netlink_overflow);
319 VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
323 if (nbytes < sizeof *nlmsghdr
324 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
325 || nlmsghdr->nlmsg_len > nbytes) {
326 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
327 bufsize, NLMSG_HDRLEN);
332 if (STRESS(netlink_overflow)) {
338 log_nlmsg(__func__, 0, buf->data, buf->size);
339 COVERAGE_INC(netlink_received);
344 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
345 * successful, returns 0. On failure, returns a positive errno value.
347 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
348 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
349 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
350 * reply, if any, is discarded.
352 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
353 * be set to 'sock''s pid, before the message is sent. NLM_F_ACK will be set
356 * The caller is responsible for destroying 'request'.
358 * Bare Netlink is an unreliable transport protocol. This function layers
359 * reliable delivery and reply semantics on top of bare Netlink.
361 * In Netlink, sending a request to the kernel is reliable enough, because the
362 * kernel will tell us if the message cannot be queued (and we will in that
363 * case put it on the transmit queue and wait until it can be delivered).
365 * Receiving the reply is the real problem: if the socket buffer is full when
366 * the kernel tries to send the reply, the reply will be dropped. However, the
367 * kernel sets a flag that a reply has been dropped. The next call to recv
368 * then returns ENOBUFS. We can then re-send the request.
372 * 1. Netlink depends on sequence numbers to match up requests and
373 * replies. The sender of a request supplies a sequence number, and
374 * the reply echos back that sequence number.
376 * This is fine, but (1) some kernel netlink implementations are
377 * broken, in that they fail to echo sequence numbers and (2) this
378 * function will drop packets with non-matching sequence numbers, so
379 * that only a single request can be usefully transacted at a time.
381 * 2. Resending the request causes it to be re-executed, so the request
382 * needs to be idempotent.
385 nl_sock_transact(struct nl_sock *sock,
386 const struct ofpbuf *request, struct ofpbuf **replyp)
388 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
389 struct nlmsghdr *nlmsghdr;
390 struct ofpbuf *reply;
397 /* Ensure that we get a reply even if this message doesn't ordinarily call
399 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
402 retval = nl_sock_send(sock, request, true);
408 retval = nl_sock_recv(sock, &reply, true);
410 if (retval == ENOBUFS) {
411 COVERAGE_INC(netlink_overflow);
412 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
418 nlmsghdr = nl_msg_nlmsghdr(reply);
419 if (seq != nlmsghdr->nlmsg_seq) {
420 VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
421 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
422 ofpbuf_delete(reply);
426 /* If the reply is an error, discard the reply and return the error code.
428 * Except: if the reply is just an acknowledgement (error code of 0), and
429 * the caller is interested in the reply (replyp != NULL), pass the reply
430 * up to the caller. Otherwise the caller will get a return value of 0
431 * and null '*replyp', which makes unwary callers likely to segfault. */
432 if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
433 ofpbuf_delete(reply);
435 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
436 retval, strerror(retval));
438 return retval != EAGAIN ? retval : EPROTO;
444 ofpbuf_delete(reply);
449 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
450 * 'sock', and initializes 'dump' to reflect the state of the operation.
452 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
453 * be set to 'sock''s pid, before the message is sent. NLM_F_DUMP and
454 * NLM_F_ACK will be set in nlmsg_flags.
456 * The properties of Netlink make dump operations reliable as long as all of
457 * the following are true:
459 * - At most a single dump is in progress at a time on a given nl_sock.
461 * - The nl_sock is not subscribed to any multicast groups.
463 * - The nl_sock is not used to send any other messages before the dump
464 * operation is complete.
466 * This function provides no status indication. An error status for the entire
467 * dump operation is provided when it is completed by calling nl_dump_done().
469 * The caller is responsible for destroying 'request'. The caller must not
470 * close 'sock' before it completes the dump operation (by calling
474 nl_dump_start(struct nl_dump *dump,
475 struct nl_sock *sock, const struct ofpbuf *request)
477 struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
478 nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
479 dump->seq = nlmsghdr->nlmsg_seq;
481 dump->status = nl_sock_send(sock, request, true);
485 /* Helper function for nl_dump_next(). */
487 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
489 struct nlmsghdr *nlmsghdr;
490 struct ofpbuf *buffer;
493 retval = nl_sock_recv(dump->sock, bufferp, true);
495 return retval == EINTR ? EAGAIN : retval;
499 nlmsghdr = nl_msg_nlmsghdr(buffer);
500 if (dump->seq != nlmsghdr->nlmsg_seq) {
501 VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
502 nlmsghdr->nlmsg_seq, dump->seq);
506 if (nl_msg_nlmsgerr(buffer, &retval)) {
507 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
509 return retval && retval != EAGAIN ? retval : EPROTO;
515 /* Attempts to retrieve another reply from 'dump', which must have been
516 * initialized with nl_dump_start().
518 * If successful, returns true and points 'reply->data' and 'reply->size' to
519 * the message that was retrieved. The caller must not modify 'reply' (because
520 * it points into the middle of a larger buffer).
522 * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
523 * to 0. Failure might indicate an actual error or merely the end of replies.
524 * An error status for the entire dump operation is provided when it is
525 * completed by calling nl_dump_done().
528 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
530 struct nlmsghdr *nlmsghdr;
538 if (dump->buffer && !dump->buffer->size) {
539 ofpbuf_delete(dump->buffer);
542 while (!dump->buffer) {
543 int retval = nl_dump_recv(dump, &dump->buffer);
545 ofpbuf_delete(dump->buffer);
547 if (retval != EAGAIN) {
548 dump->status = retval;
554 nlmsghdr = nl_msg_next(dump->buffer, reply);
556 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
557 dump->status = EPROTO;
559 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
567 /* Completes Netlink dump operation 'dump', which must have been initialized
568 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
569 * otherwise a positive errno value describing the problem. */
571 nl_dump_done(struct nl_dump *dump)
573 /* Drain any remaining messages that the client didn't read. Otherwise the
574 * kernel will continue to queue them up and waste buffer space. */
575 while (!dump->status) {
577 if (!nl_dump_next(dump, &reply)) {
578 assert(dump->status);
582 ofpbuf_delete(dump->buffer);
583 return dump->status == EOF ? 0 : dump->status;
586 /* Causes poll_block() to wake up when any of the specified 'events' (which is
587 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
589 nl_sock_wait(const struct nl_sock *sock, short int events)
591 poll_fd_wait(sock->fd, events);
596 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
597 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
600 static int do_lookup_genl_family(const char *name)
602 struct nl_sock *sock;
603 struct ofpbuf request, *reply;
604 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
607 retval = nl_sock_create(NETLINK_GENERIC, &sock);
612 ofpbuf_init(&request, 0);
613 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
614 CTRL_CMD_GETFAMILY, 1);
615 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
616 retval = nl_sock_transact(sock, &request, &reply);
617 ofpbuf_uninit(&request);
619 nl_sock_destroy(sock);
623 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
624 family_policy, attrs, ARRAY_SIZE(family_policy))) {
625 nl_sock_destroy(sock);
626 ofpbuf_delete(reply);
630 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
634 nl_sock_destroy(sock);
635 ofpbuf_delete(reply);
639 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
640 * number and stores it in '*number'. If successful, returns 0 and the caller
641 * may use '*number' as the family number. On failure, returns a positive
642 * errno value and '*number' caches the errno value. */
644 nl_lookup_genl_family(const char *name, int *number)
647 *number = do_lookup_genl_family(name);
648 assert(*number != 0);
650 return *number > 0 ? 0 : -*number;
655 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
656 * programs that have a single Netlink socket use their Unix process ID as PID,
657 * and programs with multiple Netlink sockets add a unique per-socket
658 * identifier in the bits above the Unix process ID.
660 * The kernel has Netlink PID 0.
663 /* Parameters for how many bits in the PID should come from the Unix process ID
664 * and how many unique per-socket. */
665 #define SOCKET_BITS 10
666 #define MAX_SOCKETS (1u << SOCKET_BITS)
668 #define PROCESS_BITS (32 - SOCKET_BITS)
669 #define MAX_PROCESSES (1u << PROCESS_BITS)
670 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
672 /* Bit vector of unused socket identifiers. */
673 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
675 /* Allocates and returns a new Netlink PID. */
677 alloc_pid(uint32_t *pid)
681 for (i = 0; i < MAX_SOCKETS; i++) {
682 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
683 avail_sockets[i / 32] |= 1u << (i % 32);
684 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
688 VLOG_ERR("netlink pid space exhausted");
692 /* Makes the specified 'pid' available for reuse. */
694 free_pid(uint32_t pid)
696 int sock = pid >> PROCESS_BITS;
697 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
698 avail_sockets[sock / 32] &= ~(1u << (sock % 32));
702 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
708 static const struct nlmsg_flag flags[] = {
709 { NLM_F_REQUEST, "REQUEST" },
710 { NLM_F_MULTI, "MULTI" },
711 { NLM_F_ACK, "ACK" },
712 { NLM_F_ECHO, "ECHO" },
713 { NLM_F_DUMP, "DUMP" },
714 { NLM_F_ROOT, "ROOT" },
715 { NLM_F_MATCH, "MATCH" },
716 { NLM_F_ATOMIC, "ATOMIC" },
718 const struct nlmsg_flag *flag;
721 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
722 h->nlmsg_len, h->nlmsg_type);
723 if (h->nlmsg_type == NLMSG_NOOP) {
724 ds_put_cstr(ds, "(no-op)");
725 } else if (h->nlmsg_type == NLMSG_ERROR) {
726 ds_put_cstr(ds, "(error)");
727 } else if (h->nlmsg_type == NLMSG_DONE) {
728 ds_put_cstr(ds, "(done)");
729 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
730 ds_put_cstr(ds, "(overrun)");
731 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
732 ds_put_cstr(ds, "(reserved)");
734 ds_put_cstr(ds, "(family-defined)");
736 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
737 flags_left = h->nlmsg_flags;
738 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
739 if ((flags_left & flag->bits) == flag->bits) {
740 ds_put_format(ds, "[%s]", flag->name);
741 flags_left &= ~flag->bits;
745 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
747 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
748 h->nlmsg_seq, h->nlmsg_pid,
749 (int) (h->nlmsg_pid & PROCESS_MASK),
750 (int) (h->nlmsg_pid >> PROCESS_BITS));
754 nlmsg_to_string(const struct ofpbuf *buffer)
756 struct ds ds = DS_EMPTY_INITIALIZER;
757 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
759 nlmsghdr_to_string(h, &ds);
760 if (h->nlmsg_type == NLMSG_ERROR) {
761 const struct nlmsgerr *e;
762 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
763 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
765 ds_put_format(&ds, " error(%d", e->error);
767 ds_put_format(&ds, "(%s)", strerror(-e->error));
769 ds_put_cstr(&ds, ", in-reply-to(");
770 nlmsghdr_to_string(&e->msg, &ds);
771 ds_put_cstr(&ds, "))");
773 ds_put_cstr(&ds, " error(truncated)");
775 } else if (h->nlmsg_type == NLMSG_DONE) {
776 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
778 ds_put_format(&ds, " done(%d", *error);
780 ds_put_format(&ds, "(%s)", strerror(-*error));
782 ds_put_cstr(&ds, ")");
784 ds_put_cstr(&ds, " done(truncated)");
788 ds_put_cstr(&ds, "nl(truncated)");
794 log_nlmsg(const char *function, int error,
795 const void *message, size_t size)
797 struct ofpbuf buffer;
800 if (!VLOG_IS_DBG_ENABLED()) {
804 ofpbuf_use_const(&buffer, message, size);
805 nlmsg = nlmsg_to_string(&buffer);
806 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);