2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 nl_sock_cow__(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)
90 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 rcvbuf = 1024 * 1024;
127 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
128 &rcvbuf, sizeof rcvbuf)) {
129 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed (%s)",
130 rcvbuf, strerror(errno));
133 retval = get_socket_rcvbuf(sock->fd);
138 sock->rcvbuf = retval;
140 /* Connect to kernel (pid 0) as remote address. */
141 memset(&remote, 0, sizeof remote);
142 remote.nl_family = AF_NETLINK;
144 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
145 VLOG_ERR("connect(0): %s", strerror(errno));
149 /* Obtain pid assigned by kernel. */
150 local_size = sizeof local;
151 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
152 VLOG_ERR("getsockname: %s", strerror(errno));
155 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
156 VLOG_ERR("getsockname returned bad Netlink name");
160 sock->pid = local.nl_pid;
179 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
180 * sets '*sockp' to the new socket if successful, otherwise returns a positive
183 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
185 return nl_sock_create(src->protocol, sockp);
188 /* Destroys netlink socket 'sock'. */
190 nl_sock_destroy(struct nl_sock *sock)
202 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
203 * successful, otherwise a positive errno value.
205 * A socket that is subscribed to a multicast group that receives asynchronous
206 * notifications must not be used for Netlink transactions or dumps, because
207 * transactions and dumps can cause notifications to be lost.
209 * Multicast group numbers are always positive.
211 * It is not an error to attempt to join a multicast group to which a socket
212 * already belongs. */
214 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
216 int error = nl_sock_cow__(sock);
220 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
221 &multicast_group, sizeof multicast_group) < 0) {
222 VLOG_WARN("could not join multicast group %u (%s)",
223 multicast_group, strerror(errno));
229 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
230 * successful, otherwise a positive errno value.
232 * Multicast group numbers are always positive.
234 * It is not an error to attempt to leave a multicast group to which a socket
237 * On success, reading from 'sock' will still return any messages that were
238 * received on 'multicast_group' before the group was left. */
240 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
243 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
244 &multicast_group, sizeof multicast_group) < 0) {
245 VLOG_WARN("could not leave multicast group %u (%s)",
246 multicast_group, strerror(errno));
253 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
255 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
258 nlmsg->nlmsg_len = msg->size;
259 nlmsg->nlmsg_pid = sock->pid;
262 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
263 error = retval < 0 ? errno : 0;
264 } while (error == EINTR);
265 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
267 COVERAGE_INC(netlink_sent);
272 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
273 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, and
274 * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
276 * Returns 0 if successful, otherwise a positive errno value. If
277 * 'wait' is true, then the send will wait until buffer space is ready;
278 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
280 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
282 int error = nl_sock_cow__(sock);
286 return nl_sock_send__(sock, msg, wait);
289 /* This stress option is useful for testing that OVS properly tolerates
290 * -ENOBUFS on NetLink sockets. Such errors are unavoidable because they can
291 * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
292 * reply to a request. They can also occur if messages arrive on a multicast
293 * channel faster than OVS can process them. */
295 netlink_overflow, "simulate netlink socket receive buffer overflow",
299 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
301 /* We can't accurately predict the size of the data to be received. Most
302 * received data will fit in a 2 kB buffer, so we allocate that much space.
303 * In case the data is actually bigger than that, we make available enough
304 * additional space to allow Netlink messages to be up to 64 kB long (a
305 * reasonable figure since that's the maximum length of a Netlink
307 enum { MAX_SIZE = 65536 };
308 enum { HEAD_SIZE = 2048 };
309 enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
311 struct nlmsghdr *nlmsghdr;
312 uint8_t tail[TAIL_SIZE];
320 buf = ofpbuf_new(HEAD_SIZE);
321 iov[0].iov_base = buf->data;
322 iov[0].iov_len = HEAD_SIZE;
323 iov[1].iov_base = tail;
324 iov[1].iov_len = TAIL_SIZE;
326 memset(&msg, 0, sizeof msg);
331 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
332 } while (retval < 0 && errno == EINTR);
336 if (error == ENOBUFS) {
337 /* Socket receive buffer overflow dropped one or more messages that
338 * the kernel tried to send to us. */
339 COVERAGE_INC(netlink_overflow);
345 if (msg.msg_flags & MSG_TRUNC) {
346 VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
351 ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
352 if (retval > HEAD_SIZE) {
353 COVERAGE_INC(netlink_recv_jumbo);
354 ofpbuf_put(buf, tail, retval - HEAD_SIZE);
357 nlmsghdr = buf->data;
358 if (retval < sizeof *nlmsghdr
359 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
360 || nlmsghdr->nlmsg_len > retval) {
361 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
362 retval, NLMSG_HDRLEN);
367 if (STRESS(netlink_overflow)) {
373 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
374 COVERAGE_INC(netlink_received);
379 /* Tries to receive a netlink message from the kernel on 'sock'. If
380 * successful, stores the received message into '*bufp' and returns 0. The
381 * caller is responsible for destroying the message with ofpbuf_delete(). On
382 * failure, returns a positive errno value and stores a null pointer into
385 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
386 * returns EAGAIN if the 'sock' receive buffer is empty. */
388 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
390 int error = nl_sock_cow__(sock);
394 return nl_sock_recv__(sock, bufp, wait);
398 find_nl_transaction_by_seq(struct nl_transaction **transactions, size_t n,
403 for (i = 0; i < n; i++) {
404 struct nl_transaction *t = transactions[i];
406 if (seq == nl_msg_nlmsghdr(t->request)->nlmsg_seq) {
415 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
420 for (i = 0; i < n; i++) {
421 transactions[i]->error = error;
422 transactions[i]->reply = NULL;
427 nl_sock_transact_multiple__(struct nl_sock *sock,
428 struct nl_transaction **transactions, size_t n,
431 struct iovec iovs[MAX_IOVS];
437 for (i = 0; i < n; i++) {
438 struct ofpbuf *request = transactions[i]->request;
439 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(request);
441 nlmsg->nlmsg_len = request->size;
442 nlmsg->nlmsg_pid = sock->pid;
444 iovs[i].iov_base = request->data;
445 iovs[i].iov_len = request->size;
448 memset(&msg, 0, sizeof msg);
452 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
453 } while (error == EINTR);
455 for (i = 0; i < n; i++) {
456 struct ofpbuf *request = transactions[i]->request;
458 log_nlmsg(__func__, error, request->data, request->size,
462 COVERAGE_ADD(netlink_sent, n);
470 struct ofpbuf *reply;
472 error = nl_sock_recv__(sock, &reply, false);
473 if (error == EAGAIN) {
474 nl_sock_record_errors__(transactions, n, 0);
481 i = find_nl_transaction_by_seq(transactions, n,
482 nl_msg_nlmsghdr(reply)->nlmsg_seq);
484 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32,
485 nl_msg_nlmsghdr(reply)->nlmsg_seq);
486 ofpbuf_delete(reply);
490 nl_sock_record_errors__(transactions, i, 0);
491 if (nl_msg_nlmsgerr(reply, &error)) {
492 transactions[i]->reply = NULL;
493 transactions[i]->error = error;
495 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
496 error, strerror(error));
498 ofpbuf_delete(reply);
500 transactions[i]->reply = reply;
501 transactions[i]->error = 0;
505 transactions += i + 1;
512 /* Sends the 'request' member of the 'n' transactions in 'transactions' to the
513 * kernel, in order, and waits for responses to all of them. Fills in the
514 * 'error' member of each transaction with 0 if it was successful, otherwise
515 * with a positive errno value. 'reply' will be NULL on error or if the
516 * transaction was successful but had no reply beyond an indication of success.
517 * For a successful transaction that did have a more detailed reply, 'reply'
518 * will be set to the reply message.
520 * The caller is responsible for destroying each request and reply, and the
521 * transactions array itself.
523 * Before sending each message, this function will finalize nlmsg_len in each
524 * 'request' to match the ofpbuf's size, and set nlmsg_pid to 'sock''s pid.
525 * NLM_F_ACK will be added to some requests' nlmsg_flags.
527 * Bare Netlink is an unreliable transport protocol. This function layers
528 * reliable delivery and reply semantics on top of bare Netlink. See
529 * nl_sock_transact() for some caveats.
532 nl_sock_transact_multiple(struct nl_sock *sock,
533 struct nl_transaction **transactions, size_t n)
542 error = nl_sock_cow__(sock);
544 nl_sock_record_errors__(transactions, n, error);
548 /* In theory, every request could have a 64 kB reply. But the default and
549 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
550 * be a bit below 128 kB, so that would only allow a single message in a
551 * "batch". So we assume that replies average (at most) 4 kB, which allows
552 * a good deal of batching.
554 * In practice, most of the requests that we batch either have no reply at
555 * all or a brief reply. */
556 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
557 max_batch_count = MIN(max_batch_count, max_iovs);
563 /* Batch up to 'max_batch_count' transactions. But cap it at about a
564 * page of requests total because big skbuffs are expensive to
565 * allocate in the kernel. */
566 #if defined(PAGESIZE)
567 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
569 enum { MAX_BATCH_BYTES = 4096 - 512 };
571 bytes = transactions[0]->request->size;
572 for (count = 1; count < n && count < max_batch_count; count++) {
573 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
576 bytes += transactions[count]->request->size;
579 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
580 transactions += done;
583 if (error == ENOBUFS) {
584 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
586 VLOG_ERR_RL(&rl, "transaction error (%s)", strerror(error));
587 nl_sock_record_errors__(transactions, n, error);
592 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
593 * successful, returns 0. On failure, returns a positive errno value.
595 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
596 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
597 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
598 * reply, if any, is discarded.
600 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
601 * be set to 'sock''s pid, before the message is sent. NLM_F_ACK will be set
604 * The caller is responsible for destroying 'request'.
606 * Bare Netlink is an unreliable transport protocol. This function layers
607 * reliable delivery and reply semantics on top of bare Netlink.
609 * In Netlink, sending a request to the kernel is reliable enough, because the
610 * kernel will tell us if the message cannot be queued (and we will in that
611 * case put it on the transmit queue and wait until it can be delivered).
613 * Receiving the reply is the real problem: if the socket buffer is full when
614 * the kernel tries to send the reply, the reply will be dropped. However, the
615 * kernel sets a flag that a reply has been dropped. The next call to recv
616 * then returns ENOBUFS. We can then re-send the request.
620 * 1. Netlink depends on sequence numbers to match up requests and
621 * replies. The sender of a request supplies a sequence number, and
622 * the reply echos back that sequence number.
624 * This is fine, but (1) some kernel netlink implementations are
625 * broken, in that they fail to echo sequence numbers and (2) this
626 * function will drop packets with non-matching sequence numbers, so
627 * that only a single request can be usefully transacted at a time.
629 * 2. Resending the request causes it to be re-executed, so the request
630 * needs to be idempotent.
633 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
634 struct ofpbuf **replyp)
636 struct nl_transaction *transactionp;
637 struct nl_transaction transaction;
639 transaction.request = (struct ofpbuf *) request;
640 transactionp = &transaction;
641 nl_sock_transact_multiple(sock, &transactionp, 1);
643 *replyp = transaction.reply;
645 ofpbuf_delete(transaction.reply);
647 return transaction.error;
650 /* Drain all the messages currently in 'sock''s receive queue. */
652 nl_sock_drain(struct nl_sock *sock)
654 int error = nl_sock_cow__(sock);
658 return drain_rcvbuf(sock->fd);
661 /* The client is attempting some operation on 'sock'. If 'sock' has an ongoing
662 * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
663 * old fd over to the dump. */
665 nl_sock_cow__(struct nl_sock *sock)
667 struct nl_sock *copy;
676 error = nl_sock_clone(sock, ©);
686 sock->pid = copy->pid;
689 sock->dump->sock = copy;
695 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
696 * 'sock', and initializes 'dump' to reflect the state of the operation.
698 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
699 * be set to 'sock''s pid, before the message is sent. NLM_F_DUMP and
700 * NLM_F_ACK will be set in nlmsg_flags.
702 * This Netlink socket library is designed to ensure that the dump is reliable
703 * and that it will not interfere with other operations on 'sock', including
704 * destroying or sending and receiving messages on 'sock'. One corner case is
707 * - If 'sock' has been used to send a request (e.g. with nl_sock_send())
708 * whose response has not yet been received (e.g. with nl_sock_recv()).
709 * This is unusual: usually nl_sock_transact() is used to send a message
710 * and receive its reply all in one go.
712 * This function provides no status indication. An error status for the entire
713 * dump operation is provided when it is completed by calling nl_dump_done().
715 * The caller is responsible for destroying 'request'.
717 * The new 'dump' is independent of 'sock'. 'sock' and 'dump' may be destroyed
721 nl_dump_start(struct nl_dump *dump,
722 struct nl_sock *sock, const struct ofpbuf *request)
724 struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
725 nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
726 dump->seq = nlmsghdr->nlmsg_seq;
729 /* 'sock' already has an ongoing dump. Clone the socket because
730 * Netlink only allows one dump at a time. */
731 dump->status = nl_sock_clone(sock, &dump->sock);
740 dump->status = nl_sock_send__(sock, request, true);
743 /* Helper function for nl_dump_next(). */
745 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
747 struct nlmsghdr *nlmsghdr;
748 struct ofpbuf *buffer;
751 retval = nl_sock_recv__(dump->sock, bufferp, true);
753 return retval == EINTR ? EAGAIN : retval;
757 nlmsghdr = nl_msg_nlmsghdr(buffer);
758 if (dump->seq != nlmsghdr->nlmsg_seq) {
759 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
760 nlmsghdr->nlmsg_seq, dump->seq);
764 if (nl_msg_nlmsgerr(buffer, &retval)) {
765 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
767 return retval && retval != EAGAIN ? retval : EPROTO;
773 /* Attempts to retrieve another reply from 'dump', which must have been
774 * initialized with nl_dump_start().
776 * If successful, returns true and points 'reply->data' and 'reply->size' to
777 * the message that was retrieved. The caller must not modify 'reply' (because
778 * it points into the middle of a larger buffer).
780 * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
781 * to 0. Failure might indicate an actual error or merely the end of replies.
782 * An error status for the entire dump operation is provided when it is
783 * completed by calling nl_dump_done().
786 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
788 struct nlmsghdr *nlmsghdr;
796 if (dump->buffer && !dump->buffer->size) {
797 ofpbuf_delete(dump->buffer);
800 while (!dump->buffer) {
801 int retval = nl_dump_recv(dump, &dump->buffer);
803 ofpbuf_delete(dump->buffer);
805 if (retval != EAGAIN) {
806 dump->status = retval;
812 nlmsghdr = nl_msg_next(dump->buffer, reply);
814 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
815 dump->status = EPROTO;
817 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
825 /* Completes Netlink dump operation 'dump', which must have been initialized
826 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
827 * otherwise a positive errno value describing the problem. */
829 nl_dump_done(struct nl_dump *dump)
831 /* Drain any remaining messages that the client didn't read. Otherwise the
832 * kernel will continue to queue them up and waste buffer space. */
833 while (!dump->status) {
835 if (!nl_dump_next(dump, &reply)) {
836 assert(dump->status);
841 if (dump->sock->dump) {
842 dump->sock->dump = NULL;
844 nl_sock_destroy(dump->sock);
847 ofpbuf_delete(dump->buffer);
848 return dump->status == EOF ? 0 : dump->status;
851 /* Causes poll_block() to wake up when any of the specified 'events' (which is
852 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
854 nl_sock_wait(const struct nl_sock *sock, short int events)
856 poll_fd_wait(sock->fd, events);
859 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
860 * that can't use nl_sock_wait().
862 * It's a little tricky to use the returned fd correctly, because nl_sock does
863 * "copy on write" to allow a single nl_sock to be used for notifications,
864 * transactions, and dumps. If 'sock' is used only for notifications and
865 * transactions (and never for dump) then the usage is safe. */
867 nl_sock_fd(const struct nl_sock *sock)
872 /* Returns the PID associated with this socket. */
874 nl_sock_pid(const struct nl_sock *sock)
882 struct hmap_node hmap_node;
887 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
889 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
890 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
891 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
894 static struct genl_family *
895 find_genl_family_by_id(uint16_t id)
897 struct genl_family *family;
899 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
901 if (family->id == id) {
909 define_genl_family(uint16_t id, const char *name)
911 struct genl_family *family = find_genl_family_by_id(id);
914 if (!strcmp(family->name, name)) {
919 family = xmalloc(sizeof *family);
921 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
923 family->name = xstrdup(name);
927 genl_family_to_name(uint16_t id)
929 if (id == GENL_ID_CTRL) {
932 struct genl_family *family = find_genl_family_by_id(id);
933 return family ? family->name : "unknown";
938 do_lookup_genl_family(const char *name, struct nlattr **attrs,
939 struct ofpbuf **replyp)
941 struct nl_sock *sock;
942 struct ofpbuf request, *reply;
946 error = nl_sock_create(NETLINK_GENERIC, &sock);
951 ofpbuf_init(&request, 0);
952 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
953 CTRL_CMD_GETFAMILY, 1);
954 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
955 error = nl_sock_transact(sock, &request, &reply);
956 ofpbuf_uninit(&request);
958 nl_sock_destroy(sock);
962 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
963 family_policy, attrs, ARRAY_SIZE(family_policy))
964 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
965 nl_sock_destroy(sock);
966 ofpbuf_delete(reply);
970 nl_sock_destroy(sock);
975 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
976 * When successful, writes its result to 'multicast_group' and returns 0.
977 * Otherwise, clears 'multicast_group' and returns a positive error code.
979 * Some kernels do not support looking up a multicast group with this function.
980 * In this case, 'multicast_group' will be populated with 'fallback'. */
982 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
983 unsigned int *multicast_group, unsigned int fallback)
985 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
986 const struct nlattr *mc;
987 struct ofpbuf *reply;
991 *multicast_group = 0;
992 error = do_lookup_genl_family(family_name, family_attrs, &reply);
997 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
998 *multicast_group = fallback;
999 VLOG_WARN("%s-%s: has no multicast group, using fallback %d",
1000 family_name, group_name, *multicast_group);
1005 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1006 static const struct nl_policy mc_policy[] = {
1007 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1008 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1011 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1012 const char *mc_name;
1014 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1019 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1020 if (!strcmp(group_name, mc_name)) {
1022 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1030 ofpbuf_delete(reply);
1034 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1035 * number and stores it in '*number'. If successful, returns 0 and the caller
1036 * may use '*number' as the family number. On failure, returns a positive
1037 * errno value and '*number' caches the errno value. */
1039 nl_lookup_genl_family(const char *name, int *number)
1042 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1043 struct ofpbuf *reply;
1046 error = do_lookup_genl_family(name, attrs, &reply);
1048 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1049 define_genl_family(*number, name);
1053 ofpbuf_delete(reply);
1055 assert(*number != 0);
1057 return *number > 0 ? 0 : -*number;
1061 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1067 static const struct nlmsg_flag flags[] = {
1068 { NLM_F_REQUEST, "REQUEST" },
1069 { NLM_F_MULTI, "MULTI" },
1070 { NLM_F_ACK, "ACK" },
1071 { NLM_F_ECHO, "ECHO" },
1072 { NLM_F_DUMP, "DUMP" },
1073 { NLM_F_ROOT, "ROOT" },
1074 { NLM_F_MATCH, "MATCH" },
1075 { NLM_F_ATOMIC, "ATOMIC" },
1077 const struct nlmsg_flag *flag;
1078 uint16_t flags_left;
1080 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1081 h->nlmsg_len, h->nlmsg_type);
1082 if (h->nlmsg_type == NLMSG_NOOP) {
1083 ds_put_cstr(ds, "(no-op)");
1084 } else if (h->nlmsg_type == NLMSG_ERROR) {
1085 ds_put_cstr(ds, "(error)");
1086 } else if (h->nlmsg_type == NLMSG_DONE) {
1087 ds_put_cstr(ds, "(done)");
1088 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1089 ds_put_cstr(ds, "(overrun)");
1090 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1091 ds_put_cstr(ds, "(reserved)");
1092 } else if (protocol == NETLINK_GENERIC) {
1093 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1095 ds_put_cstr(ds, "(family-defined)");
1097 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1098 flags_left = h->nlmsg_flags;
1099 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1100 if ((flags_left & flag->bits) == flag->bits) {
1101 ds_put_format(ds, "[%s]", flag->name);
1102 flags_left &= ~flag->bits;
1106 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1108 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1109 h->nlmsg_seq, h->nlmsg_pid);
1113 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1115 struct ds ds = DS_EMPTY_INITIALIZER;
1116 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1118 nlmsghdr_to_string(h, protocol, &ds);
1119 if (h->nlmsg_type == NLMSG_ERROR) {
1120 const struct nlmsgerr *e;
1121 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1122 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1124 ds_put_format(&ds, " error(%d", e->error);
1126 ds_put_format(&ds, "(%s)", strerror(-e->error));
1128 ds_put_cstr(&ds, ", in-reply-to(");
1129 nlmsghdr_to_string(&e->msg, protocol, &ds);
1130 ds_put_cstr(&ds, "))");
1132 ds_put_cstr(&ds, " error(truncated)");
1134 } else if (h->nlmsg_type == NLMSG_DONE) {
1135 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1137 ds_put_format(&ds, " done(%d", *error);
1139 ds_put_format(&ds, "(%s)", strerror(-*error));
1141 ds_put_cstr(&ds, ")");
1143 ds_put_cstr(&ds, " done(truncated)");
1145 } else if (protocol == NETLINK_GENERIC) {
1146 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1148 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1149 genl->cmd, genl->version);
1153 ds_put_cstr(&ds, "nl(truncated)");
1159 log_nlmsg(const char *function, int error,
1160 const void *message, size_t size, int protocol)
1162 struct ofpbuf buffer;
1165 if (!VLOG_IS_DBG_ENABLED()) {
1169 ofpbuf_use_const(&buffer, message, size);
1170 nlmsg = nlmsg_to_string(&buffer, protocol);
1171 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);