2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "netlink-socket.h"
22 #include <sys/types.h>
26 #include "dynamic-string.h"
30 #include "netlink-protocol.h"
32 #include "poll-loop.h"
33 #include "socket-util.h"
37 VLOG_DEFINE_THIS_MODULE(netlink_socket);
39 COVERAGE_DEFINE(netlink_overflow);
40 COVERAGE_DEFINE(netlink_received);
41 COVERAGE_DEFINE(netlink_recv_jumbo);
42 COVERAGE_DEFINE(netlink_send);
43 COVERAGE_DEFINE(netlink_sent);
45 /* Linux header file confusion causes this to be undefined. */
47 #define SOL_NETLINK 270
50 /* A single (bad) Netlink message can in theory dump out many, many log
51 * messages, so the burst size is set quite high here to avoid missing useful
52 * information. Also, at high logging levels we log *all* Netlink messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
55 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
56 static void log_nlmsg(const char *function, int error,
57 const void *message, size_t size, int protocol);
59 /* Netlink sockets. */
66 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
69 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
70 * of iovecs on the stack. */
73 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
74 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
76 * Initialized by nl_sock_create(). */
79 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
80 static void nl_pool_release(struct nl_sock *);
82 /* Creates a new netlink socket for the given netlink 'protocol'
83 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
84 * new socket if successful, otherwise returns a positive errno value. */
86 nl_sock_create(int protocol, struct nl_sock **sockp)
89 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", ovs_strerror(errno));
103 max_iovs = _XOPEN_IOV_MAX;
104 } else if (max_iovs > MAX_IOVS) {
112 sock = xmalloc(sizeof *sock);
114 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
116 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
119 sock->protocol = protocol;
122 rcvbuf = 1024 * 1024;
123 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
124 &rcvbuf, sizeof rcvbuf)) {
125 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
126 * Warn only if the failure is therefore unexpected. */
127 if (errno != EPERM) {
128 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
129 "(%s)", rcvbuf, ovs_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", ovs_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", ovs_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)
198 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
199 * successful, otherwise a positive errno value.
201 * A socket that is subscribed to a multicast group that receives asynchronous
202 * notifications must not be used for Netlink transactions or dumps, because
203 * transactions and dumps can cause notifications to be lost.
205 * Multicast group numbers are always positive.
207 * It is not an error to attempt to join a multicast group to which a socket
208 * already belongs. */
210 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
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, ovs_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)
234 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
235 &multicast_group, sizeof multicast_group) < 0) {
236 VLOG_WARN("could not leave multicast group %u (%s)",
237 multicast_group, ovs_strerror(errno));
244 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
245 uint32_t nlmsg_seq, bool wait)
247 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
250 nlmsg->nlmsg_len = msg->size;
251 nlmsg->nlmsg_seq = nlmsg_seq;
252 nlmsg->nlmsg_pid = sock->pid;
255 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
256 error = retval < 0 ? errno : 0;
257 } while (error == EINTR);
258 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
260 COVERAGE_INC(netlink_sent);
265 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
266 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
267 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
268 * sequence number, before the message is sent.
270 * Returns 0 if successful, otherwise a positive errno value. If
271 * 'wait' is true, then the send will wait until buffer space is ready;
272 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
274 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
276 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
279 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
280 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
281 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
282 * 'nlmsg_seq', before the message is sent.
284 * Returns 0 if successful, otherwise a positive errno value. If
285 * 'wait' is true, then the send will wait until buffer space is ready;
286 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
288 * This function is suitable for sending a reply to a request that was received
289 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
291 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
292 uint32_t nlmsg_seq, bool wait)
294 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
298 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
300 /* We can't accurately predict the size of the data to be received. The
301 * caller is supposed to have allocated enough space in 'buf' to handle the
302 * "typical" case. To handle exceptions, we make available enough space in
303 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
304 * figure since that's the maximum length of a Netlink attribute). */
305 struct nlmsghdr *nlmsghdr;
311 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
314 iov[0].iov_base = buf->base;
315 iov[0].iov_len = buf->allocated;
316 iov[1].iov_base = tail;
317 iov[1].iov_len = sizeof tail;
319 memset(&msg, 0, sizeof msg);
324 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
325 } while (retval < 0 && errno == EINTR);
329 if (error == ENOBUFS) {
330 /* Socket receive buffer overflow dropped one or more messages that
331 * the kernel tried to send to us. */
332 COVERAGE_INC(netlink_overflow);
337 if (msg.msg_flags & MSG_TRUNC) {
338 VLOG_ERR_RL(&rl, "truncated message (longer than %zu bytes)",
343 nlmsghdr = buf->data;
344 if (retval < sizeof *nlmsghdr
345 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
346 || nlmsghdr->nlmsg_len > retval) {
347 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %zu)",
348 retval, sizeof *nlmsghdr);
352 buf->size = MIN(retval, buf->allocated);
353 if (retval > buf->allocated) {
354 COVERAGE_INC(netlink_recv_jumbo);
355 ofpbuf_put(buf, tail, retval - buf->allocated);
358 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
359 COVERAGE_INC(netlink_received);
364 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
365 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
366 * EAGAIN if the 'sock' receive buffer is empty.
368 * The caller must have initialized 'buf' with an allocation of at least
369 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
370 * space for a "typical" message.
372 * On success, returns 0 and replaces 'buf''s previous content by the received
373 * message. This function expands 'buf''s allocated memory, as necessary, to
374 * hold the actual size of the received message.
376 * On failure, returns a positive errno value and clears 'buf' to zero length.
377 * 'buf' retains its previous memory allocation.
379 * Regardless of success or failure, this function resets 'buf''s headroom to
382 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
384 return nl_sock_recv__(sock, buf, wait);
388 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
393 for (i = 0; i < n; i++) {
394 struct nl_transaction *txn = transactions[i];
398 ofpbuf_clear(txn->reply);
404 nl_sock_transact_multiple__(struct nl_sock *sock,
405 struct nl_transaction **transactions, size_t n,
408 uint64_t tmp_reply_stub[1024 / 8];
409 struct nl_transaction tmp_txn;
410 struct ofpbuf tmp_reply;
413 struct iovec iovs[MAX_IOVS];
418 base_seq = nl_sock_allocate_seq(sock, n);
420 for (i = 0; i < n; i++) {
421 struct nl_transaction *txn = transactions[i];
422 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
424 nlmsg->nlmsg_len = txn->request->size;
425 nlmsg->nlmsg_seq = base_seq + i;
426 nlmsg->nlmsg_pid = sock->pid;
428 iovs[i].iov_base = txn->request->data;
429 iovs[i].iov_len = txn->request->size;
432 memset(&msg, 0, sizeof msg);
436 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
437 } while (error == EINTR);
439 for (i = 0; i < n; i++) {
440 struct nl_transaction *txn = transactions[i];
442 log_nlmsg(__func__, error, txn->request->data, txn->request->size,
446 COVERAGE_ADD(netlink_sent, n);
453 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
454 tmp_txn.request = NULL;
455 tmp_txn.reply = &tmp_reply;
458 struct nl_transaction *buf_txn, *txn;
461 /* Find a transaction whose buffer we can use for receiving a reply.
462 * If no such transaction is left, use tmp_txn. */
464 for (i = 0; i < n; i++) {
465 if (transactions[i]->reply) {
466 buf_txn = transactions[i];
471 /* Receive a reply. */
472 error = nl_sock_recv__(sock, buf_txn->reply, false);
474 if (error == EAGAIN) {
475 nl_sock_record_errors__(transactions, n, 0);
482 /* Match the reply up with a transaction. */
483 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
484 if (seq < base_seq || seq >= base_seq + n) {
485 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
489 txn = transactions[i];
491 /* Fill in the results for 'txn'. */
492 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
494 ofpbuf_clear(txn->reply);
497 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
498 error, ovs_strerror(txn->error));
502 if (txn->reply && txn != buf_txn) {
504 struct ofpbuf *reply = buf_txn->reply;
505 buf_txn->reply = txn->reply;
510 /* Fill in the results for transactions before 'txn'. (We have to do
511 * this after the results for 'txn' itself because of the buffer swap
513 nl_sock_record_errors__(transactions, i, 0);
517 transactions += i + 1;
521 ofpbuf_uninit(&tmp_reply);
526 /* Sends the 'request' member of the 'n' transactions in 'transactions' on
527 * 'sock', in order, and receives responses to all of them. Fills in the
528 * 'error' member of each transaction with 0 if it was successful, otherwise
529 * with a positive errno value. If 'reply' is nonnull, then it will be filled
530 * with the reply if the message receives a detailed reply. In other cases,
531 * i.e. where the request failed or had no reply beyond an indication of
532 * success, 'reply' will be cleared if it is nonnull.
534 * The caller is responsible for destroying each request and reply, and the
535 * transactions array itself.
537 * Before sending each message, this function will finalize nlmsg_len in each
538 * 'request' to match the ofpbuf's size, set nlmsg_pid to 'sock''s pid, and
539 * initialize nlmsg_seq.
541 * Bare Netlink is an unreliable transport protocol. This function layers
542 * reliable delivery and reply semantics on top of bare Netlink. See
543 * nl_sock_transact() for some caveats.
546 nl_sock_transact_multiple(struct nl_sock *sock,
547 struct nl_transaction **transactions, size_t n)
556 /* In theory, every request could have a 64 kB reply. But the default and
557 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
558 * be a bit below 128 kB, so that would only allow a single message in a
559 * "batch". So we assume that replies average (at most) 4 kB, which allows
560 * a good deal of batching.
562 * In practice, most of the requests that we batch either have no reply at
563 * all or a brief reply. */
564 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
565 max_batch_count = MIN(max_batch_count, max_iovs);
571 /* Batch up to 'max_batch_count' transactions. But cap it at about a
572 * page of requests total because big skbuffs are expensive to
573 * allocate in the kernel. */
574 #if defined(PAGESIZE)
575 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
577 enum { MAX_BATCH_BYTES = 4096 - 512 };
579 bytes = transactions[0]->request->size;
580 for (count = 1; count < n && count < max_batch_count; count++) {
581 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
584 bytes += transactions[count]->request->size;
587 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
588 transactions += done;
591 if (error == ENOBUFS) {
592 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
594 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
595 nl_sock_record_errors__(transactions, n, error);
600 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
601 * successful, returns 0. On failure, returns a positive errno value.
603 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
604 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
605 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
606 * reply, if any, is discarded.
608 * Before the message is sent, nlmsg_len in 'request' will be finalized to
609 * match msg->size, nlmsg_pid will be set to 'sock''s pid, and nlmsg_seq will
610 * be initialized, NLM_F_ACK will be set in nlmsg_flags.
612 * The caller is responsible for destroying 'request'.
614 * Bare Netlink is an unreliable transport protocol. This function layers
615 * reliable delivery and reply semantics on top of bare Netlink.
617 * In Netlink, sending a request to the kernel is reliable enough, because the
618 * kernel will tell us if the message cannot be queued (and we will in that
619 * case put it on the transmit queue and wait until it can be delivered).
621 * Receiving the reply is the real problem: if the socket buffer is full when
622 * the kernel tries to send the reply, the reply will be dropped. However, the
623 * kernel sets a flag that a reply has been dropped. The next call to recv
624 * then returns ENOBUFS. We can then re-send the request.
628 * 1. Netlink depends on sequence numbers to match up requests and
629 * replies. The sender of a request supplies a sequence number, and
630 * the reply echos back that sequence number.
632 * This is fine, but (1) some kernel netlink implementations are
633 * broken, in that they fail to echo sequence numbers and (2) this
634 * function will drop packets with non-matching sequence numbers, so
635 * that only a single request can be usefully transacted at a time.
637 * 2. Resending the request causes it to be re-executed, so the request
638 * needs to be idempotent.
641 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
642 struct ofpbuf **replyp)
644 struct nl_transaction *transactionp;
645 struct nl_transaction transaction;
647 transaction.request = CONST_CAST(struct ofpbuf *, request);
648 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
649 transactionp = &transaction;
651 nl_sock_transact_multiple(sock, &transactionp, 1);
654 if (transaction.error) {
655 ofpbuf_delete(transaction.reply);
658 *replyp = transaction.reply;
662 return transaction.error;
665 /* Drain all the messages currently in 'sock''s receive queue. */
667 nl_sock_drain(struct nl_sock *sock)
669 return drain_rcvbuf(sock->fd);
672 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
673 * Netlink socket created with the given 'protocol', and initializes 'dump' to
674 * reflect the state of the operation.
676 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
677 * be set to the Netlink socket's pid, before the message is sent. NLM_F_DUMP
678 * and NLM_F_ACK will be set in nlmsg_flags.
680 * The design of this Netlink socket library ensures that the dump is reliable.
682 * This function provides no status indication. An error status for the entire
683 * dump operation is provided when it is completed by calling nl_dump_done().
685 * The caller is responsible for destroying 'request'.
688 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
690 ofpbuf_init(&dump->buffer, 4096);
691 dump->status = nl_pool_alloc(protocol, &dump->sock);
696 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
697 dump->status = nl_sock_send__(dump->sock, request,
698 nl_sock_allocate_seq(dump->sock, 1), true);
699 dump->seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
702 /* Helper function for nl_dump_next(). */
704 nl_dump_recv(struct nl_dump *dump)
706 struct nlmsghdr *nlmsghdr;
709 retval = nl_sock_recv__(dump->sock, &dump->buffer, true);
711 return retval == EINTR ? EAGAIN : retval;
714 nlmsghdr = nl_msg_nlmsghdr(&dump->buffer);
715 if (dump->seq != nlmsghdr->nlmsg_seq) {
716 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
717 nlmsghdr->nlmsg_seq, dump->seq);
721 if (nl_msg_nlmsgerr(&dump->buffer, &retval)) {
722 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
723 ovs_strerror(retval));
724 return retval && retval != EAGAIN ? retval : EPROTO;
730 /* Attempts to retrieve another reply from 'dump', which must have been
731 * initialized with nl_dump_start().
733 * If successful, returns true and points 'reply->data' and 'reply->size' to
734 * the message that was retrieved. The caller must not modify 'reply' (because
735 * it points into the middle of a larger buffer).
737 * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
738 * to 0. Failure might indicate an actual error or merely the end of replies.
739 * An error status for the entire dump operation is provided when it is
740 * completed by calling nl_dump_done().
743 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
745 struct nlmsghdr *nlmsghdr;
753 while (!dump->buffer.size) {
754 int retval = nl_dump_recv(dump);
756 ofpbuf_clear(&dump->buffer);
757 if (retval != EAGAIN) {
758 dump->status = retval;
764 nlmsghdr = nl_msg_next(&dump->buffer, reply);
766 VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
767 dump->status = EPROTO;
769 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
777 /* Completes Netlink dump operation 'dump', which must have been initialized
778 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
779 * otherwise a positive errno value describing the problem. */
781 nl_dump_done(struct nl_dump *dump)
783 /* Drain any remaining messages that the client didn't read. Otherwise the
784 * kernel will continue to queue them up and waste buffer space.
786 * XXX We could just destroy and discard the socket in this case. */
787 while (!dump->status) {
789 if (!nl_dump_next(dump, &reply)) {
790 ovs_assert(dump->status);
793 nl_pool_release(dump->sock);
794 ofpbuf_uninit(&dump->buffer);
795 return dump->status == EOF ? 0 : dump->status;
798 /* Causes poll_block() to wake up when any of the specified 'events' (which is
799 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
801 nl_sock_wait(const struct nl_sock *sock, short int events)
803 poll_fd_wait(sock->fd, events);
806 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
807 * that can't use nl_sock_wait().
809 * It's a little tricky to use the returned fd correctly, because nl_sock does
810 * "copy on write" to allow a single nl_sock to be used for notifications,
811 * transactions, and dumps. If 'sock' is used only for notifications and
812 * transactions (and never for dump) then the usage is safe. */
814 nl_sock_fd(const struct nl_sock *sock)
819 /* Returns the PID associated with this socket. */
821 nl_sock_pid(const struct nl_sock *sock)
829 struct hmap_node hmap_node;
834 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
836 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
837 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
838 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
841 static struct genl_family *
842 find_genl_family_by_id(uint16_t id)
844 struct genl_family *family;
846 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
848 if (family->id == id) {
856 define_genl_family(uint16_t id, const char *name)
858 struct genl_family *family = find_genl_family_by_id(id);
861 if (!strcmp(family->name, name)) {
866 family = xmalloc(sizeof *family);
868 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
870 family->name = xstrdup(name);
874 genl_family_to_name(uint16_t id)
876 if (id == GENL_ID_CTRL) {
879 struct genl_family *family = find_genl_family_by_id(id);
880 return family ? family->name : "unknown";
885 do_lookup_genl_family(const char *name, struct nlattr **attrs,
886 struct ofpbuf **replyp)
888 struct nl_sock *sock;
889 struct ofpbuf request, *reply;
893 error = nl_sock_create(NETLINK_GENERIC, &sock);
898 ofpbuf_init(&request, 0);
899 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
900 CTRL_CMD_GETFAMILY, 1);
901 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
902 error = nl_sock_transact(sock, &request, &reply);
903 ofpbuf_uninit(&request);
905 nl_sock_destroy(sock);
909 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
910 family_policy, attrs, ARRAY_SIZE(family_policy))
911 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
912 nl_sock_destroy(sock);
913 ofpbuf_delete(reply);
917 nl_sock_destroy(sock);
922 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
923 * When successful, writes its result to 'multicast_group' and returns 0.
924 * Otherwise, clears 'multicast_group' and returns a positive error code.
926 * Some kernels do not support looking up a multicast group with this function.
927 * In this case, 'multicast_group' will be populated with 'fallback'. */
929 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
930 unsigned int *multicast_group, unsigned int fallback)
932 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
933 const struct nlattr *mc;
934 struct ofpbuf *reply;
938 *multicast_group = 0;
939 error = do_lookup_genl_family(family_name, family_attrs, &reply);
944 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
945 *multicast_group = fallback;
946 VLOG_WARN("%s-%s: has no multicast group, using fallback %d",
947 family_name, group_name, *multicast_group);
952 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
953 static const struct nl_policy mc_policy[] = {
954 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
955 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
958 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
961 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
966 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
967 if (!strcmp(group_name, mc_name)) {
969 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
977 ofpbuf_delete(reply);
981 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
982 * number and stores it in '*number'. If successful, returns 0 and the caller
983 * may use '*number' as the family number. On failure, returns a positive
984 * errno value and '*number' caches the errno value. */
986 nl_lookup_genl_family(const char *name, int *number)
989 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
990 struct ofpbuf *reply;
993 error = do_lookup_genl_family(name, attrs, &reply);
995 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
996 define_genl_family(*number, name);
1000 ofpbuf_delete(reply);
1002 ovs_assert(*number != 0);
1004 return *number > 0 ? 0 : -*number;
1008 struct nl_sock *socks[16];
1012 static struct nl_pool pools[MAX_LINKS];
1015 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1017 struct nl_pool *pool;
1019 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1021 pool = &pools[protocol];
1023 *sockp = pool->socks[--pool->n];
1026 return nl_sock_create(protocol, sockp);
1031 nl_pool_release(struct nl_sock *sock)
1034 struct nl_pool *pool = &pools[sock->protocol];
1036 if (pool->n < ARRAY_SIZE(pool->socks)) {
1037 pool->socks[pool->n++] = sock;
1039 nl_sock_destroy(sock);
1045 nl_transact(int protocol, const struct ofpbuf *request,
1046 struct ofpbuf **replyp)
1048 struct nl_sock *sock;
1051 error = nl_pool_alloc(protocol, &sock);
1057 error = nl_sock_transact(sock, request, replyp);
1059 nl_pool_release(sock);
1064 nl_transact_multiple(int protocol,
1065 struct nl_transaction **transactions, size_t n)
1067 struct nl_sock *sock;
1070 error = nl_pool_alloc(protocol, &sock);
1072 nl_sock_transact_multiple(sock, transactions, n);
1073 nl_pool_release(sock);
1075 nl_sock_record_errors__(transactions, n, error);
1081 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1083 uint32_t seq = sock->next_seq;
1085 sock->next_seq += n;
1087 /* Make it impossible for the next request for sequence numbers to wrap
1088 * around to 0. Start over with 1 to avoid ever using a sequence number of
1089 * 0, because the kernel uses sequence number 0 for notifications. */
1090 if (sock->next_seq >= UINT32_MAX / 2) {
1098 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1104 static const struct nlmsg_flag flags[] = {
1105 { NLM_F_REQUEST, "REQUEST" },
1106 { NLM_F_MULTI, "MULTI" },
1107 { NLM_F_ACK, "ACK" },
1108 { NLM_F_ECHO, "ECHO" },
1109 { NLM_F_DUMP, "DUMP" },
1110 { NLM_F_ROOT, "ROOT" },
1111 { NLM_F_MATCH, "MATCH" },
1112 { NLM_F_ATOMIC, "ATOMIC" },
1114 const struct nlmsg_flag *flag;
1115 uint16_t flags_left;
1117 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1118 h->nlmsg_len, h->nlmsg_type);
1119 if (h->nlmsg_type == NLMSG_NOOP) {
1120 ds_put_cstr(ds, "(no-op)");
1121 } else if (h->nlmsg_type == NLMSG_ERROR) {
1122 ds_put_cstr(ds, "(error)");
1123 } else if (h->nlmsg_type == NLMSG_DONE) {
1124 ds_put_cstr(ds, "(done)");
1125 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1126 ds_put_cstr(ds, "(overrun)");
1127 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1128 ds_put_cstr(ds, "(reserved)");
1129 } else if (protocol == NETLINK_GENERIC) {
1130 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1132 ds_put_cstr(ds, "(family-defined)");
1134 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1135 flags_left = h->nlmsg_flags;
1136 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1137 if ((flags_left & flag->bits) == flag->bits) {
1138 ds_put_format(ds, "[%s]", flag->name);
1139 flags_left &= ~flag->bits;
1143 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1145 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1146 h->nlmsg_seq, h->nlmsg_pid);
1150 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1152 struct ds ds = DS_EMPTY_INITIALIZER;
1153 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1155 nlmsghdr_to_string(h, protocol, &ds);
1156 if (h->nlmsg_type == NLMSG_ERROR) {
1157 const struct nlmsgerr *e;
1158 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1159 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1161 ds_put_format(&ds, " error(%d", e->error);
1163 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1165 ds_put_cstr(&ds, ", in-reply-to(");
1166 nlmsghdr_to_string(&e->msg, protocol, &ds);
1167 ds_put_cstr(&ds, "))");
1169 ds_put_cstr(&ds, " error(truncated)");
1171 } else if (h->nlmsg_type == NLMSG_DONE) {
1172 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1174 ds_put_format(&ds, " done(%d", *error);
1176 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1178 ds_put_cstr(&ds, ")");
1180 ds_put_cstr(&ds, " done(truncated)");
1182 } else if (protocol == NETLINK_GENERIC) {
1183 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1185 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1186 genl->cmd, genl->version);
1190 ds_put_cstr(&ds, "nl(truncated)");
1196 log_nlmsg(const char *function, int error,
1197 const void *message, size_t size, int protocol)
1199 struct ofpbuf buffer;
1202 if (!VLOG_IS_DBG_ENABLED()) {
1206 ofpbuf_use_const(&buffer, message, size);
1207 nlmsg = nlmsg_to_string(&buffer, protocol);
1208 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);