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>
27 #include "dynamic-string.h"
31 #include "netlink-protocol.h"
33 #include "poll-loop.h"
34 #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_send);
45 COVERAGE_DEFINE(netlink_sent);
47 /* Linux header file confusion causes this to be undefined. */
49 #define SOL_NETLINK 270
52 /* A single (bad) Netlink message can in theory dump out many, many log
53 * messages, so the burst size is set quite high here to avoid missing useful
54 * information. Also, at high logging levels we log *all* Netlink messages. */
55 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
57 static void log_nlmsg(const char *function, int error,
58 const void *message, size_t size, int protocol);
60 /* Netlink sockets. */
68 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
71 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
72 * of iovecs on the stack. */
75 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
76 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
78 * Initialized by nl_sock_create(). */
81 static int alloc_pid(uint32_t *);
82 static void free_pid(uint32_t);
83 static int nl_sock_cow__(struct nl_sock *);
85 /* Creates a new netlink socket for the given netlink 'protocol'
86 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
87 * new socket if successful, otherwise returns a positive errno value. */
89 nl_sock_create(int protocol, struct nl_sock **sockp)
92 struct sockaddr_nl local, remote;
96 int save_errno = errno;
99 max_iovs = sysconf(_SC_UIO_MAXIOV);
100 if (max_iovs < _XOPEN_IOV_MAX) {
101 if (max_iovs == -1 && errno) {
102 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", strerror(errno));
104 max_iovs = _XOPEN_IOV_MAX;
105 } else if (max_iovs > MAX_IOVS) {
113 sock = malloc(sizeof *sock);
118 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
120 VLOG_ERR("fcntl: %s", strerror(errno));
123 sock->protocol = protocol;
126 retval = get_socket_rcvbuf(sock->fd);
131 sock->rcvbuf = retval;
133 retval = alloc_pid(&sock->pid);
138 /* Bind local address as our selected pid. */
139 memset(&local, 0, sizeof local);
140 local.nl_family = AF_NETLINK;
141 local.nl_pid = sock->pid;
142 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
143 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
147 /* Bind remote address as the kernel (pid 0). */
148 memset(&remote, 0, sizeof remote);
149 remote.nl_family = AF_NETLINK;
151 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
152 VLOG_ERR("connect(0): %s", strerror(errno));
175 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
176 * sets '*sockp' to the new socket if successful, otherwise returns a positive
179 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
181 return nl_sock_create(src->protocol, sockp);
184 /* Destroys netlink socket 'sock'. */
186 nl_sock_destroy(struct nl_sock *sock)
199 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
200 * successful, otherwise a positive errno value.
202 * A socket that is subscribed to a multicast group that receives asynchronous
203 * notifications must not be used for Netlink transactions or dumps, because
204 * transactions and dumps can cause notifications to be lost.
206 * Multicast group numbers are always positive.
208 * It is not an error to attempt to join a multicast group to which a socket
209 * already belongs. */
211 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
213 int error = nl_sock_cow__(sock);
217 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
218 &multicast_group, sizeof multicast_group) < 0) {
219 VLOG_WARN("could not join multicast group %u (%s)",
220 multicast_group, strerror(errno));
226 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
227 * successful, otherwise a positive errno value.
229 * Multicast group numbers are always positive.
231 * It is not an error to attempt to leave a multicast group to which a socket
234 * On success, reading from 'sock' will still return any messages that were
235 * received on 'multicast_group' before the group was left. */
237 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
240 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
241 &multicast_group, sizeof multicast_group) < 0) {
242 VLOG_WARN("could not leave multicast group %u (%s)",
243 multicast_group, strerror(errno));
250 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
252 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
255 nlmsg->nlmsg_len = msg->size;
256 nlmsg->nlmsg_pid = sock->pid;
259 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
260 error = retval < 0 ? errno : 0;
261 } while (error == EINTR);
262 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
264 COVERAGE_INC(netlink_sent);
269 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
270 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, and
271 * nlmsg_pid will be set to 'sock''s pid, 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 int error = nl_sock_cow__(sock);
283 return nl_sock_send__(sock, msg, wait);
286 /* This stress option is useful for testing that OVS properly tolerates
287 * -ENOBUFS on NetLink sockets. Such errors are unavoidable because they can
288 * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
289 * reply to a request. They can also occur if messages arrive on a multicast
290 * channel faster than OVS can process them. */
292 netlink_overflow, "simulate netlink socket receive buffer overflow",
296 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
298 /* We can't accurately predict the size of the data to be received. Most
299 * received data will fit in a 2 kB buffer, so we allocate that much space.
300 * In case the data is actually bigger than that, we make available enough
301 * additional space to allow Netlink messages to be up to 64 kB long (a
302 * reasonable figure since that's the maximum length of a Netlink
304 enum { MAX_SIZE = 65536 };
305 enum { HEAD_SIZE = 2048 };
306 enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
308 struct nlmsghdr *nlmsghdr;
309 uint8_t tail[TAIL_SIZE];
317 buf = ofpbuf_new(HEAD_SIZE);
318 iov[0].iov_base = buf->data;
319 iov[0].iov_len = HEAD_SIZE;
320 iov[1].iov_base = tail;
321 iov[1].iov_len = TAIL_SIZE;
323 memset(&msg, 0, sizeof msg);
328 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
329 } while (retval < 0 && errno == EINTR);
333 if (error == ENOBUFS) {
334 /* Socket receive buffer overflow dropped one or more messages that
335 * the kernel tried to send to us. */
336 COVERAGE_INC(netlink_overflow);
342 if (msg.msg_flags & MSG_TRUNC) {
343 VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
348 ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
349 if (retval > HEAD_SIZE) {
350 COVERAGE_INC(netlink_recv_jumbo);
351 ofpbuf_put(buf, tail, retval - HEAD_SIZE);
354 nlmsghdr = buf->data;
355 if (retval < sizeof *nlmsghdr
356 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
357 || nlmsghdr->nlmsg_len > retval) {
358 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
359 retval, NLMSG_HDRLEN);
364 if (STRESS(netlink_overflow)) {
370 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
371 COVERAGE_INC(netlink_received);
376 /* Tries to receive a netlink message from the kernel on 'sock'. If
377 * successful, stores the received message into '*bufp' and returns 0. The
378 * caller is responsible for destroying the message with ofpbuf_delete(). On
379 * failure, returns a positive errno value and stores a null pointer into
382 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
383 * returns EAGAIN if the 'sock' receive buffer is empty. */
385 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
387 int error = nl_sock_cow__(sock);
391 return nl_sock_recv__(sock, bufp, wait);
395 find_nl_transaction_by_seq(struct nl_transaction **transactions, size_t n,
400 for (i = 0; i < n; i++) {
401 struct nl_transaction *t = transactions[i];
403 if (seq == nl_msg_nlmsghdr(t->request)->nlmsg_seq) {
412 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
417 for (i = 0; i < n; i++) {
418 transactions[i]->error = error;
419 transactions[i]->reply = NULL;
424 nl_sock_transact_multiple__(struct nl_sock *sock,
425 struct nl_transaction **transactions, size_t n,
428 struct iovec iovs[MAX_IOVS];
434 for (i = 0; i < n; i++) {
435 struct ofpbuf *request = transactions[i]->request;
436 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(request);
438 nlmsg->nlmsg_len = request->size;
439 nlmsg->nlmsg_pid = sock->pid;
441 /* Ensure that we get a reply even if the final request doesn't
442 * ordinarily call for one. */
443 nlmsg->nlmsg_flags |= NLM_F_ACK;
446 iovs[i].iov_base = request->data;
447 iovs[i].iov_len = request->size;
450 memset(&msg, 0, sizeof msg);
454 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
455 } while (error == EINTR);
457 for (i = 0; i < n; i++) {
458 struct ofpbuf *request = transactions[i]->request;
460 log_nlmsg(__func__, error, request->data, request->size,
464 COVERAGE_ADD(netlink_sent, n);
472 struct ofpbuf *reply;
474 error = nl_sock_recv__(sock, &reply, true);
479 i = find_nl_transaction_by_seq(transactions, n,
480 nl_msg_nlmsghdr(reply)->nlmsg_seq);
482 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32,
483 nl_msg_nlmsghdr(reply)->nlmsg_seq);
484 ofpbuf_delete(reply);
488 nl_sock_record_errors__(transactions, i, 0);
489 if (nl_msg_nlmsgerr(reply, &error)) {
490 transactions[i]->reply = NULL;
491 transactions[i]->error = error;
493 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
494 error, strerror(error));
496 ofpbuf_delete(reply);
498 transactions[i]->reply = reply;
499 transactions[i]->error = 0;
503 transactions += i + 1;
510 /* Sends the 'request' member of the 'n' transactions in 'transactions' to the
511 * kernel, in order, and waits for responses to all of them. Fills in the
512 * 'error' member of each transaction with 0 if it was successful, otherwise
513 * with a positive errno value. 'reply' will be NULL on error or if the
514 * transaction was successful but had no reply beyond an indication of success.
515 * For a successful transaction that did have a more detailed reply, 'reply'
516 * will be set to the reply message.
518 * The caller is responsible for destroying each request and reply, and the
519 * transactions array itself.
521 * Before sending each message, this function will finalize nlmsg_len in each
522 * 'request' to match the ofpbuf's size, and set nlmsg_pid to 'sock''s pid.
523 * NLM_F_ACK will be added to some requests' nlmsg_flags.
525 * Bare Netlink is an unreliable transport protocol. This function layers
526 * reliable delivery and reply semantics on top of bare Netlink. See
527 * nl_sock_transact() for some caveats.
530 nl_sock_transact_multiple(struct nl_sock *sock,
531 struct nl_transaction **transactions, size_t n)
540 error = nl_sock_cow__(sock);
542 nl_sock_record_errors__(transactions, n, error);
546 /* In theory, every request could have a 64 kB reply. But the default and
547 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
548 * be a bit below 128 kB, so that would only allow a single message in a
549 * "batch". So we assume that replies average (at most) 4 kB, which allows
550 * a good deal of batching.
552 * In practice, most of the requests that we batch either have no reply at
553 * all or a brief reply. */
554 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
555 max_batch_count = MIN(max_batch_count, max_iovs);
561 /* Batch up to 'max_batch_count' transactions. But cap it at about a
562 * page of requests total because big skbuffs are expensive to
563 * allocate in the kernel. */
564 #if defined(PAGESIZE)
565 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
567 enum { MAX_BATCH_BYTES = 4096 - 512 };
569 bytes = transactions[0]->request->size;
570 for (count = 1; count < n && count < max_batch_count; count++) {
571 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
574 bytes += transactions[count]->request->size;
577 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
578 transactions += done;
581 if (error == ENOBUFS) {
582 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
584 VLOG_ERR_RL(&rl, "transaction error (%s)", strerror(error));
585 nl_sock_record_errors__(transactions, n, error);
590 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
591 * successful, returns 0. On failure, returns a positive errno value.
593 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
594 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
595 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
596 * reply, if any, is discarded.
598 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
599 * be set to 'sock''s pid, before the message is sent. NLM_F_ACK will be set
602 * The caller is responsible for destroying 'request'.
604 * Bare Netlink is an unreliable transport protocol. This function layers
605 * reliable delivery and reply semantics on top of bare Netlink.
607 * In Netlink, sending a request to the kernel is reliable enough, because the
608 * kernel will tell us if the message cannot be queued (and we will in that
609 * case put it on the transmit queue and wait until it can be delivered).
611 * Receiving the reply is the real problem: if the socket buffer is full when
612 * the kernel tries to send the reply, the reply will be dropped. However, the
613 * kernel sets a flag that a reply has been dropped. The next call to recv
614 * then returns ENOBUFS. We can then re-send the request.
618 * 1. Netlink depends on sequence numbers to match up requests and
619 * replies. The sender of a request supplies a sequence number, and
620 * the reply echos back that sequence number.
622 * This is fine, but (1) some kernel netlink implementations are
623 * broken, in that they fail to echo sequence numbers and (2) this
624 * function will drop packets with non-matching sequence numbers, so
625 * that only a single request can be usefully transacted at a time.
627 * 2. Resending the request causes it to be re-executed, so the request
628 * needs to be idempotent.
631 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
632 struct ofpbuf **replyp)
634 struct nl_transaction *transactionp;
635 struct nl_transaction transaction;
637 transaction.request = (struct ofpbuf *) request;
638 transactionp = &transaction;
639 nl_sock_transact_multiple(sock, &transactionp, 1);
641 *replyp = transaction.reply;
643 ofpbuf_delete(transaction.reply);
645 return transaction.error;
648 /* Drain all the messages currently in 'sock''s receive queue. */
650 nl_sock_drain(struct nl_sock *sock)
652 int error = nl_sock_cow__(sock);
656 return drain_rcvbuf(sock->fd);
659 /* The client is attempting some operation on 'sock'. If 'sock' has an ongoing
660 * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
661 * old fd over to the dump. */
663 nl_sock_cow__(struct nl_sock *sock)
665 struct nl_sock *copy;
674 error = nl_sock_clone(sock, ©);
684 sock->pid = copy->pid;
687 sock->dump->sock = copy;
693 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
694 * 'sock', and initializes 'dump' to reflect the state of the operation.
696 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
697 * be set to 'sock''s pid, before the message is sent. NLM_F_DUMP and
698 * NLM_F_ACK will be set in nlmsg_flags.
700 * This Netlink socket library is designed to ensure that the dump is reliable
701 * and that it will not interfere with other operations on 'sock', including
702 * destroying or sending and receiving messages on 'sock'. One corner case is
705 * - If 'sock' has been used to send a request (e.g. with nl_sock_send())
706 * whose response has not yet been received (e.g. with nl_sock_recv()).
707 * This is unusual: usually nl_sock_transact() is used to send a message
708 * and receive its reply all in one go.
710 * This function provides no status indication. An error status for the entire
711 * dump operation is provided when it is completed by calling nl_dump_done().
713 * The caller is responsible for destroying 'request'.
715 * The new 'dump' is independent of 'sock'. 'sock' and 'dump' may be destroyed
719 nl_dump_start(struct nl_dump *dump,
720 struct nl_sock *sock, const struct ofpbuf *request)
722 struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
723 nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
724 dump->seq = nlmsghdr->nlmsg_seq;
727 /* 'sock' already has an ongoing dump. Clone the socket because
728 * Netlink only allows one dump at a time. */
729 dump->status = nl_sock_clone(sock, &dump->sock);
738 dump->status = nl_sock_send__(sock, request, true);
741 /* Helper function for nl_dump_next(). */
743 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
745 struct nlmsghdr *nlmsghdr;
746 struct ofpbuf *buffer;
749 retval = nl_sock_recv__(dump->sock, bufferp, true);
751 return retval == EINTR ? EAGAIN : retval;
755 nlmsghdr = nl_msg_nlmsghdr(buffer);
756 if (dump->seq != nlmsghdr->nlmsg_seq) {
757 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
758 nlmsghdr->nlmsg_seq, dump->seq);
762 if (nl_msg_nlmsgerr(buffer, &retval)) {
763 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
765 return retval && retval != EAGAIN ? retval : EPROTO;
771 /* Attempts to retrieve another reply from 'dump', which must have been
772 * initialized with nl_dump_start().
774 * If successful, returns true and points 'reply->data' and 'reply->size' to
775 * the message that was retrieved. The caller must not modify 'reply' (because
776 * it points into the middle of a larger buffer).
778 * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
779 * to 0. Failure might indicate an actual error or merely the end of replies.
780 * An error status for the entire dump operation is provided when it is
781 * completed by calling nl_dump_done().
784 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
786 struct nlmsghdr *nlmsghdr;
794 if (dump->buffer && !dump->buffer->size) {
795 ofpbuf_delete(dump->buffer);
798 while (!dump->buffer) {
799 int retval = nl_dump_recv(dump, &dump->buffer);
801 ofpbuf_delete(dump->buffer);
803 if (retval != EAGAIN) {
804 dump->status = retval;
810 nlmsghdr = nl_msg_next(dump->buffer, reply);
812 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
813 dump->status = EPROTO;
815 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
823 /* Completes Netlink dump operation 'dump', which must have been initialized
824 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
825 * otherwise a positive errno value describing the problem. */
827 nl_dump_done(struct nl_dump *dump)
829 /* Drain any remaining messages that the client didn't read. Otherwise the
830 * kernel will continue to queue them up and waste buffer space. */
831 while (!dump->status) {
833 if (!nl_dump_next(dump, &reply)) {
834 assert(dump->status);
839 if (dump->sock->dump) {
840 dump->sock->dump = NULL;
842 nl_sock_destroy(dump->sock);
845 ofpbuf_delete(dump->buffer);
846 return dump->status == EOF ? 0 : dump->status;
849 /* Causes poll_block() to wake up when any of the specified 'events' (which is
850 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
852 nl_sock_wait(const struct nl_sock *sock, short int events)
854 poll_fd_wait(sock->fd, events);
857 /* Checks whether this socket caused a wakeup in the previous run of the poll
860 nl_sock_woke(const struct nl_sock *sock)
862 return poll_fd_woke(sock->fd);
865 /* Returns the PID associated with this socket. */
867 nl_sock_pid(const struct nl_sock *sock)
875 struct hmap_node hmap_node;
880 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
882 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
883 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
884 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
887 static struct genl_family *
888 find_genl_family_by_id(uint16_t id)
890 struct genl_family *family;
892 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
894 if (family->id == id) {
902 define_genl_family(uint16_t id, const char *name)
904 struct genl_family *family = find_genl_family_by_id(id);
907 if (!strcmp(family->name, name)) {
912 family = xmalloc(sizeof *family);
914 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
916 family->name = xstrdup(name);
920 genl_family_to_name(uint16_t id)
922 if (id == GENL_ID_CTRL) {
925 struct genl_family *family = find_genl_family_by_id(id);
926 return family ? family->name : "unknown";
931 do_lookup_genl_family(const char *name, struct nlattr **attrs,
932 struct ofpbuf **replyp)
934 struct nl_sock *sock;
935 struct ofpbuf request, *reply;
939 error = nl_sock_create(NETLINK_GENERIC, &sock);
944 ofpbuf_init(&request, 0);
945 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
946 CTRL_CMD_GETFAMILY, 1);
947 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
948 error = nl_sock_transact(sock, &request, &reply);
949 ofpbuf_uninit(&request);
951 nl_sock_destroy(sock);
955 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
956 family_policy, attrs, ARRAY_SIZE(family_policy))
957 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
958 nl_sock_destroy(sock);
959 ofpbuf_delete(reply);
963 nl_sock_destroy(sock);
968 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
969 * When successful, writes its result to 'multicast_group' and returns 0.
970 * Otherwise, clears 'multicast_group' and returns a positive error code.
972 * Some kernels do not support looking up a multicast group with this function.
973 * In this case, 'multicast_group' will be populated with 'fallback'. */
975 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
976 unsigned int *multicast_group, unsigned int fallback)
978 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
979 const struct nlattr *mc;
980 struct ofpbuf *reply;
984 *multicast_group = 0;
985 error = do_lookup_genl_family(family_name, family_attrs, &reply);
990 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
991 *multicast_group = fallback;
992 VLOG_WARN("%s-%s: has no multicast group, using fallback %d",
993 family_name, group_name, *multicast_group);
998 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
999 static const struct nl_policy mc_policy[] = {
1000 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1001 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1004 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1005 const char *mc_name;
1007 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1012 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1013 if (!strcmp(group_name, mc_name)) {
1015 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1023 ofpbuf_delete(reply);
1027 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1028 * number and stores it in '*number'. If successful, returns 0 and the caller
1029 * may use '*number' as the family number. On failure, returns a positive
1030 * errno value and '*number' caches the errno value. */
1032 nl_lookup_genl_family(const char *name, int *number)
1035 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1036 struct ofpbuf *reply;
1039 error = do_lookup_genl_family(name, attrs, &reply);
1041 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1042 define_genl_family(*number, name);
1046 ofpbuf_delete(reply);
1048 assert(*number != 0);
1050 return *number > 0 ? 0 : -*number;
1055 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
1056 * programs that have a single Netlink socket use their Unix process ID as PID,
1057 * and programs with multiple Netlink sockets add a unique per-socket
1058 * identifier in the bits above the Unix process ID.
1060 * The kernel has Netlink PID 0.
1063 /* Parameters for how many bits in the PID should come from the Unix process ID
1064 * and how many unique per-socket. */
1065 #define SOCKET_BITS 10
1066 #define MAX_SOCKETS (1u << SOCKET_BITS)
1068 #define PROCESS_BITS (32 - SOCKET_BITS)
1069 #define MAX_PROCESSES (1u << PROCESS_BITS)
1070 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
1072 /* Bit vector of unused socket identifiers. */
1073 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
1075 /* Allocates and returns a new Netlink PID. */
1077 alloc_pid(uint32_t *pid)
1081 for (i = 0; i < MAX_SOCKETS; i++) {
1082 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
1083 avail_sockets[i / 32] |= 1u << (i % 32);
1084 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
1088 VLOG_ERR("netlink pid space exhausted");
1092 /* Makes the specified 'pid' available for reuse. */
1094 free_pid(uint32_t pid)
1096 int sock = pid >> PROCESS_BITS;
1097 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
1098 avail_sockets[sock / 32] &= ~(1u << (sock % 32));
1102 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1108 static const struct nlmsg_flag flags[] = {
1109 { NLM_F_REQUEST, "REQUEST" },
1110 { NLM_F_MULTI, "MULTI" },
1111 { NLM_F_ACK, "ACK" },
1112 { NLM_F_ECHO, "ECHO" },
1113 { NLM_F_DUMP, "DUMP" },
1114 { NLM_F_ROOT, "ROOT" },
1115 { NLM_F_MATCH, "MATCH" },
1116 { NLM_F_ATOMIC, "ATOMIC" },
1118 const struct nlmsg_flag *flag;
1119 uint16_t flags_left;
1121 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1122 h->nlmsg_len, h->nlmsg_type);
1123 if (h->nlmsg_type == NLMSG_NOOP) {
1124 ds_put_cstr(ds, "(no-op)");
1125 } else if (h->nlmsg_type == NLMSG_ERROR) {
1126 ds_put_cstr(ds, "(error)");
1127 } else if (h->nlmsg_type == NLMSG_DONE) {
1128 ds_put_cstr(ds, "(done)");
1129 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1130 ds_put_cstr(ds, "(overrun)");
1131 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1132 ds_put_cstr(ds, "(reserved)");
1133 } else if (protocol == NETLINK_GENERIC) {
1134 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1136 ds_put_cstr(ds, "(family-defined)");
1138 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1139 flags_left = h->nlmsg_flags;
1140 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1141 if ((flags_left & flag->bits) == flag->bits) {
1142 ds_put_format(ds, "[%s]", flag->name);
1143 flags_left &= ~flag->bits;
1147 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1149 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1150 h->nlmsg_seq, h->nlmsg_pid,
1151 (int) (h->nlmsg_pid & PROCESS_MASK),
1152 (int) (h->nlmsg_pid >> PROCESS_BITS));
1156 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1158 struct ds ds = DS_EMPTY_INITIALIZER;
1159 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1161 nlmsghdr_to_string(h, protocol, &ds);
1162 if (h->nlmsg_type == NLMSG_ERROR) {
1163 const struct nlmsgerr *e;
1164 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1165 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1167 ds_put_format(&ds, " error(%d", e->error);
1169 ds_put_format(&ds, "(%s)", strerror(-e->error));
1171 ds_put_cstr(&ds, ", in-reply-to(");
1172 nlmsghdr_to_string(&e->msg, protocol, &ds);
1173 ds_put_cstr(&ds, "))");
1175 ds_put_cstr(&ds, " error(truncated)");
1177 } else if (h->nlmsg_type == NLMSG_DONE) {
1178 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1180 ds_put_format(&ds, " done(%d", *error);
1182 ds_put_format(&ds, "(%s)", strerror(-*error));
1184 ds_put_cstr(&ds, ")");
1186 ds_put_cstr(&ds, " done(truncated)");
1188 } else if (protocol == NETLINK_GENERIC) {
1189 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1191 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1192 genl->cmd, genl->version);
1196 ds_put_cstr(&ds, "nl(truncated)");
1202 log_nlmsg(const char *function, int error,
1203 const void *message, size_t size, int protocol)
1205 struct ofpbuf buffer;
1208 if (!VLOG_IS_DBG_ENABLED()) {
1212 ofpbuf_use_const(&buffer, message, size);
1213 nlmsg = nlmsg_to_string(&buffer, protocol);
1214 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);