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 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;
95 int save_errno = errno;
98 max_iovs = sysconf(_SC_UIO_MAXIOV);
99 if (max_iovs < _XOPEN_IOV_MAX) {
100 if (max_iovs == -1 && errno) {
101 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", strerror(errno));
103 max_iovs = _XOPEN_IOV_MAX;
104 } else if (max_iovs > MAX_IOVS) {
112 sock = malloc(sizeof *sock);
117 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
119 VLOG_ERR("fcntl: %s", strerror(errno));
122 sock->protocol = protocol;
125 retval = get_socket_rcvbuf(sock->fd);
130 sock->rcvbuf = retval;
132 /* Connect to kernel (pid 0) as remote address. */
133 memset(&remote, 0, sizeof remote);
134 remote.nl_family = AF_NETLINK;
136 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
137 VLOG_ERR("connect(0): %s", strerror(errno));
141 /* Obtain pid assigned by kernel. */
142 local_size = sizeof local;
143 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
144 VLOG_ERR("getsockname: %s", strerror(errno));
147 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
148 VLOG_ERR("getsockname returned bad Netlink name");
152 sock->pid = local.nl_pid;
171 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
172 * sets '*sockp' to the new socket if successful, otherwise returns a positive
175 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
177 return nl_sock_create(src->protocol, sockp);
180 /* Destroys netlink socket 'sock'. */
182 nl_sock_destroy(struct nl_sock *sock)
194 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
195 * successful, otherwise a positive errno value.
197 * A socket that is subscribed to a multicast group that receives asynchronous
198 * notifications must not be used for Netlink transactions or dumps, because
199 * transactions and dumps can cause notifications to be lost.
201 * Multicast group numbers are always positive.
203 * It is not an error to attempt to join a multicast group to which a socket
204 * already belongs. */
206 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
208 int error = nl_sock_cow__(sock);
212 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
213 &multicast_group, sizeof multicast_group) < 0) {
214 VLOG_WARN("could not join multicast group %u (%s)",
215 multicast_group, strerror(errno));
221 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
222 * successful, otherwise a positive errno value.
224 * Multicast group numbers are always positive.
226 * It is not an error to attempt to leave a multicast group to which a socket
229 * On success, reading from 'sock' will still return any messages that were
230 * received on 'multicast_group' before the group was left. */
232 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
235 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
236 &multicast_group, sizeof multicast_group) < 0) {
237 VLOG_WARN("could not leave multicast group %u (%s)",
238 multicast_group, strerror(errno));
245 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
247 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
250 nlmsg->nlmsg_len = msg->size;
251 nlmsg->nlmsg_pid = sock->pid;
254 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
255 error = retval < 0 ? errno : 0;
256 } while (error == EINTR);
257 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
259 COVERAGE_INC(netlink_sent);
264 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
265 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, and
266 * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
268 * Returns 0 if successful, otherwise a positive errno value. If
269 * 'wait' is true, then the send will wait until buffer space is ready;
270 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
272 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
274 int error = nl_sock_cow__(sock);
278 return nl_sock_send__(sock, msg, wait);
281 /* This stress option is useful for testing that OVS properly tolerates
282 * -ENOBUFS on NetLink sockets. Such errors are unavoidable because they can
283 * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
284 * reply to a request. They can also occur if messages arrive on a multicast
285 * channel faster than OVS can process them. */
287 netlink_overflow, "simulate netlink socket receive buffer overflow",
291 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
293 /* We can't accurately predict the size of the data to be received. Most
294 * received data will fit in a 2 kB buffer, so we allocate that much space.
295 * In case the data is actually bigger than that, we make available enough
296 * additional space to allow Netlink messages to be up to 64 kB long (a
297 * reasonable figure since that's the maximum length of a Netlink
299 enum { MAX_SIZE = 65536 };
300 enum { HEAD_SIZE = 2048 };
301 enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
303 struct nlmsghdr *nlmsghdr;
304 uint8_t tail[TAIL_SIZE];
312 buf = ofpbuf_new(HEAD_SIZE);
313 iov[0].iov_base = buf->data;
314 iov[0].iov_len = HEAD_SIZE;
315 iov[1].iov_base = tail;
316 iov[1].iov_len = TAIL_SIZE;
318 memset(&msg, 0, sizeof msg);
323 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
324 } while (retval < 0 && errno == EINTR);
328 if (error == ENOBUFS) {
329 /* Socket receive buffer overflow dropped one or more messages that
330 * the kernel tried to send to us. */
331 COVERAGE_INC(netlink_overflow);
337 if (msg.msg_flags & MSG_TRUNC) {
338 VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
343 ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
344 if (retval > HEAD_SIZE) {
345 COVERAGE_INC(netlink_recv_jumbo);
346 ofpbuf_put(buf, tail, retval - HEAD_SIZE);
349 nlmsghdr = buf->data;
350 if (retval < sizeof *nlmsghdr
351 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
352 || nlmsghdr->nlmsg_len > retval) {
353 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
354 retval, NLMSG_HDRLEN);
359 if (STRESS(netlink_overflow)) {
365 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
366 COVERAGE_INC(netlink_received);
371 /* Tries to receive a netlink message from the kernel on 'sock'. If
372 * successful, stores the received message into '*bufp' and returns 0. The
373 * caller is responsible for destroying the message with ofpbuf_delete(). On
374 * failure, returns a positive errno value and stores a null pointer into
377 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
378 * returns EAGAIN if the 'sock' receive buffer is empty. */
380 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
382 int error = nl_sock_cow__(sock);
386 return nl_sock_recv__(sock, bufp, wait);
390 find_nl_transaction_by_seq(struct nl_transaction **transactions, size_t n,
395 for (i = 0; i < n; i++) {
396 struct nl_transaction *t = transactions[i];
398 if (seq == nl_msg_nlmsghdr(t->request)->nlmsg_seq) {
407 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
412 for (i = 0; i < n; i++) {
413 transactions[i]->error = error;
414 transactions[i]->reply = NULL;
419 nl_sock_transact_multiple__(struct nl_sock *sock,
420 struct nl_transaction **transactions, size_t n,
423 struct iovec iovs[MAX_IOVS];
429 for (i = 0; i < n; i++) {
430 struct ofpbuf *request = transactions[i]->request;
431 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(request);
433 nlmsg->nlmsg_len = request->size;
434 nlmsg->nlmsg_pid = sock->pid;
436 /* Ensure that we get a reply even if the final request doesn't
437 * ordinarily call for one. */
438 nlmsg->nlmsg_flags |= NLM_F_ACK;
441 iovs[i].iov_base = request->data;
442 iovs[i].iov_len = request->size;
445 memset(&msg, 0, sizeof msg);
449 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
450 } while (error == EINTR);
452 for (i = 0; i < n; i++) {
453 struct ofpbuf *request = transactions[i]->request;
455 log_nlmsg(__func__, error, request->data, request->size,
459 COVERAGE_ADD(netlink_sent, n);
467 struct ofpbuf *reply;
469 error = nl_sock_recv__(sock, &reply, true);
474 i = find_nl_transaction_by_seq(transactions, n,
475 nl_msg_nlmsghdr(reply)->nlmsg_seq);
477 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32,
478 nl_msg_nlmsghdr(reply)->nlmsg_seq);
479 ofpbuf_delete(reply);
483 nl_sock_record_errors__(transactions, i, 0);
484 if (nl_msg_nlmsgerr(reply, &error)) {
485 transactions[i]->reply = NULL;
486 transactions[i]->error = error;
488 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
489 error, strerror(error));
491 ofpbuf_delete(reply);
493 transactions[i]->reply = reply;
494 transactions[i]->error = 0;
498 transactions += i + 1;
505 /* Sends the 'request' member of the 'n' transactions in 'transactions' to the
506 * kernel, in order, and waits for responses to all of them. Fills in the
507 * 'error' member of each transaction with 0 if it was successful, otherwise
508 * with a positive errno value. 'reply' will be NULL on error or if the
509 * transaction was successful but had no reply beyond an indication of success.
510 * For a successful transaction that did have a more detailed reply, 'reply'
511 * will be set to the reply message.
513 * The caller is responsible for destroying each request and reply, and the
514 * transactions array itself.
516 * Before sending each message, this function will finalize nlmsg_len in each
517 * 'request' to match the ofpbuf's size, and set nlmsg_pid to 'sock''s pid.
518 * NLM_F_ACK will be added to some requests' nlmsg_flags.
520 * Bare Netlink is an unreliable transport protocol. This function layers
521 * reliable delivery and reply semantics on top of bare Netlink. See
522 * nl_sock_transact() for some caveats.
525 nl_sock_transact_multiple(struct nl_sock *sock,
526 struct nl_transaction **transactions, size_t n)
535 error = nl_sock_cow__(sock);
537 nl_sock_record_errors__(transactions, n, error);
541 /* In theory, every request could have a 64 kB reply. But the default and
542 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
543 * be a bit below 128 kB, so that would only allow a single message in a
544 * "batch". So we assume that replies average (at most) 4 kB, which allows
545 * a good deal of batching.
547 * In practice, most of the requests that we batch either have no reply at
548 * all or a brief reply. */
549 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
550 max_batch_count = MIN(max_batch_count, max_iovs);
556 /* Batch up to 'max_batch_count' transactions. But cap it at about a
557 * page of requests total because big skbuffs are expensive to
558 * allocate in the kernel. */
559 #if defined(PAGESIZE)
560 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
562 enum { MAX_BATCH_BYTES = 4096 - 512 };
564 bytes = transactions[0]->request->size;
565 for (count = 1; count < n && count < max_batch_count; count++) {
566 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
569 bytes += transactions[count]->request->size;
572 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
573 transactions += done;
576 if (error == ENOBUFS) {
577 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
579 VLOG_ERR_RL(&rl, "transaction error (%s)", strerror(error));
580 nl_sock_record_errors__(transactions, n, error);
585 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
586 * successful, returns 0. On failure, returns a positive errno value.
588 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
589 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
590 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
591 * reply, if any, is discarded.
593 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
594 * be set to 'sock''s pid, before the message is sent. NLM_F_ACK will be set
597 * The caller is responsible for destroying 'request'.
599 * Bare Netlink is an unreliable transport protocol. This function layers
600 * reliable delivery and reply semantics on top of bare Netlink.
602 * In Netlink, sending a request to the kernel is reliable enough, because the
603 * kernel will tell us if the message cannot be queued (and we will in that
604 * case put it on the transmit queue and wait until it can be delivered).
606 * Receiving the reply is the real problem: if the socket buffer is full when
607 * the kernel tries to send the reply, the reply will be dropped. However, the
608 * kernel sets a flag that a reply has been dropped. The next call to recv
609 * then returns ENOBUFS. We can then re-send the request.
613 * 1. Netlink depends on sequence numbers to match up requests and
614 * replies. The sender of a request supplies a sequence number, and
615 * the reply echos back that sequence number.
617 * This is fine, but (1) some kernel netlink implementations are
618 * broken, in that they fail to echo sequence numbers and (2) this
619 * function will drop packets with non-matching sequence numbers, so
620 * that only a single request can be usefully transacted at a time.
622 * 2. Resending the request causes it to be re-executed, so the request
623 * needs to be idempotent.
626 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
627 struct ofpbuf **replyp)
629 struct nl_transaction *transactionp;
630 struct nl_transaction transaction;
632 transaction.request = (struct ofpbuf *) request;
633 transactionp = &transaction;
634 nl_sock_transact_multiple(sock, &transactionp, 1);
636 *replyp = transaction.reply;
638 ofpbuf_delete(transaction.reply);
640 return transaction.error;
643 /* Drain all the messages currently in 'sock''s receive queue. */
645 nl_sock_drain(struct nl_sock *sock)
647 int error = nl_sock_cow__(sock);
651 return drain_rcvbuf(sock->fd);
654 /* The client is attempting some operation on 'sock'. If 'sock' has an ongoing
655 * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
656 * old fd over to the dump. */
658 nl_sock_cow__(struct nl_sock *sock)
660 struct nl_sock *copy;
669 error = nl_sock_clone(sock, ©);
679 sock->pid = copy->pid;
682 sock->dump->sock = copy;
688 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
689 * 'sock', and initializes 'dump' to reflect the state of the operation.
691 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
692 * be set to 'sock''s pid, before the message is sent. NLM_F_DUMP and
693 * NLM_F_ACK will be set in nlmsg_flags.
695 * This Netlink socket library is designed to ensure that the dump is reliable
696 * and that it will not interfere with other operations on 'sock', including
697 * destroying or sending and receiving messages on 'sock'. One corner case is
700 * - If 'sock' has been used to send a request (e.g. with nl_sock_send())
701 * whose response has not yet been received (e.g. with nl_sock_recv()).
702 * This is unusual: usually nl_sock_transact() is used to send a message
703 * and receive its reply all in one go.
705 * This function provides no status indication. An error status for the entire
706 * dump operation is provided when it is completed by calling nl_dump_done().
708 * The caller is responsible for destroying 'request'.
710 * The new 'dump' is independent of 'sock'. 'sock' and 'dump' may be destroyed
714 nl_dump_start(struct nl_dump *dump,
715 struct nl_sock *sock, const struct ofpbuf *request)
717 struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
718 nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
719 dump->seq = nlmsghdr->nlmsg_seq;
722 /* 'sock' already has an ongoing dump. Clone the socket because
723 * Netlink only allows one dump at a time. */
724 dump->status = nl_sock_clone(sock, &dump->sock);
733 dump->status = nl_sock_send__(sock, request, true);
736 /* Helper function for nl_dump_next(). */
738 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
740 struct nlmsghdr *nlmsghdr;
741 struct ofpbuf *buffer;
744 retval = nl_sock_recv__(dump->sock, bufferp, true);
746 return retval == EINTR ? EAGAIN : retval;
750 nlmsghdr = nl_msg_nlmsghdr(buffer);
751 if (dump->seq != nlmsghdr->nlmsg_seq) {
752 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
753 nlmsghdr->nlmsg_seq, dump->seq);
757 if (nl_msg_nlmsgerr(buffer, &retval)) {
758 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
760 return retval && retval != EAGAIN ? retval : EPROTO;
766 /* Attempts to retrieve another reply from 'dump', which must have been
767 * initialized with nl_dump_start().
769 * If successful, returns true and points 'reply->data' and 'reply->size' to
770 * the message that was retrieved. The caller must not modify 'reply' (because
771 * it points into the middle of a larger buffer).
773 * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
774 * to 0. Failure might indicate an actual error or merely the end of replies.
775 * An error status for the entire dump operation is provided when it is
776 * completed by calling nl_dump_done().
779 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
781 struct nlmsghdr *nlmsghdr;
789 if (dump->buffer && !dump->buffer->size) {
790 ofpbuf_delete(dump->buffer);
793 while (!dump->buffer) {
794 int retval = nl_dump_recv(dump, &dump->buffer);
796 ofpbuf_delete(dump->buffer);
798 if (retval != EAGAIN) {
799 dump->status = retval;
805 nlmsghdr = nl_msg_next(dump->buffer, reply);
807 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
808 dump->status = EPROTO;
810 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
818 /* Completes Netlink dump operation 'dump', which must have been initialized
819 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
820 * otherwise a positive errno value describing the problem. */
822 nl_dump_done(struct nl_dump *dump)
824 /* Drain any remaining messages that the client didn't read. Otherwise the
825 * kernel will continue to queue them up and waste buffer space. */
826 while (!dump->status) {
828 if (!nl_dump_next(dump, &reply)) {
829 assert(dump->status);
834 if (dump->sock->dump) {
835 dump->sock->dump = NULL;
837 nl_sock_destroy(dump->sock);
840 ofpbuf_delete(dump->buffer);
841 return dump->status == EOF ? 0 : dump->status;
844 /* Causes poll_block() to wake up when any of the specified 'events' (which is
845 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
847 nl_sock_wait(const struct nl_sock *sock, short int events)
849 poll_fd_wait(sock->fd, events);
852 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
853 * that can't use nl_sock_wait().
855 * It's a little tricky to use the returned fd correctly, because nl_sock does
856 * "copy on write" to allow a single nl_sock to be used for notifications,
857 * transactions, and dumps. If 'sock' is used only for notifications and
858 * transactions (and never for dump) then the usage is safe. */
860 nl_sock_fd(const struct nl_sock *sock)
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;
1054 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1060 static const struct nlmsg_flag flags[] = {
1061 { NLM_F_REQUEST, "REQUEST" },
1062 { NLM_F_MULTI, "MULTI" },
1063 { NLM_F_ACK, "ACK" },
1064 { NLM_F_ECHO, "ECHO" },
1065 { NLM_F_DUMP, "DUMP" },
1066 { NLM_F_ROOT, "ROOT" },
1067 { NLM_F_MATCH, "MATCH" },
1068 { NLM_F_ATOMIC, "ATOMIC" },
1070 const struct nlmsg_flag *flag;
1071 uint16_t flags_left;
1073 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1074 h->nlmsg_len, h->nlmsg_type);
1075 if (h->nlmsg_type == NLMSG_NOOP) {
1076 ds_put_cstr(ds, "(no-op)");
1077 } else if (h->nlmsg_type == NLMSG_ERROR) {
1078 ds_put_cstr(ds, "(error)");
1079 } else if (h->nlmsg_type == NLMSG_DONE) {
1080 ds_put_cstr(ds, "(done)");
1081 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1082 ds_put_cstr(ds, "(overrun)");
1083 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1084 ds_put_cstr(ds, "(reserved)");
1085 } else if (protocol == NETLINK_GENERIC) {
1086 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1088 ds_put_cstr(ds, "(family-defined)");
1090 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1091 flags_left = h->nlmsg_flags;
1092 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1093 if ((flags_left & flag->bits) == flag->bits) {
1094 ds_put_format(ds, "[%s]", flag->name);
1095 flags_left &= ~flag->bits;
1099 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1101 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1102 h->nlmsg_seq, h->nlmsg_pid);
1106 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1108 struct ds ds = DS_EMPTY_INITIALIZER;
1109 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1111 nlmsghdr_to_string(h, protocol, &ds);
1112 if (h->nlmsg_type == NLMSG_ERROR) {
1113 const struct nlmsgerr *e;
1114 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1115 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1117 ds_put_format(&ds, " error(%d", e->error);
1119 ds_put_format(&ds, "(%s)", strerror(-e->error));
1121 ds_put_cstr(&ds, ", in-reply-to(");
1122 nlmsghdr_to_string(&e->msg, protocol, &ds);
1123 ds_put_cstr(&ds, "))");
1125 ds_put_cstr(&ds, " error(truncated)");
1127 } else if (h->nlmsg_type == NLMSG_DONE) {
1128 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1130 ds_put_format(&ds, " done(%d", *error);
1132 ds_put_format(&ds, "(%s)", strerror(-*error));
1134 ds_put_cstr(&ds, ")");
1136 ds_put_cstr(&ds, " done(truncated)");
1138 } else if (protocol == NETLINK_GENERIC) {
1139 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1141 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1142 genl->cmd, genl->version);
1146 ds_put_cstr(&ds, "nl(truncated)");
1152 log_nlmsg(const char *function, int error,
1153 const void *message, size_t size, int protocol)
1155 struct ofpbuf buffer;
1158 if (!VLOG_IS_DBG_ENABLED()) {
1162 ofpbuf_use_const(&buffer, message, size);
1163 nlmsg = nlmsg_to_string(&buffer, protocol);
1164 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);