2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 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"
31 #include "odp-netlink.h"
33 #include "ovs-thread.h"
34 #include "poll-loop.h"
36 #include "socket-util.h"
38 #include "openvswitch/vlog.h"
40 VLOG_DEFINE_THIS_MODULE(netlink_socket
);
42 COVERAGE_DEFINE(netlink_overflow
);
43 COVERAGE_DEFINE(netlink_received
);
44 COVERAGE_DEFINE(netlink_recv_jumbo
);
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 uint32_t nl_sock_allocate_seq(struct nl_sock
*, unsigned int n
);
58 static void log_nlmsg(const char *function
, int error
,
59 const void *message
, size_t size
, int protocol
);
61 static int get_sock_pid_from_kernel(struct nl_sock
*sock
);
64 /* Netlink sockets. */
69 OVERLAPPED overlapped
;
77 unsigned int rcvbuf
; /* Receive buffer size (SO_RCVBUF). */
80 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
81 * of iovecs on the stack. */
84 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
85 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
87 * Initialized by nl_sock_create(). */
90 static int nl_pool_alloc(int protocol
, struct nl_sock
**sockp
);
91 static void nl_pool_release(struct nl_sock
*);
93 /* Creates a new netlink socket for the given netlink 'protocol'
94 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
95 * new socket if successful, otherwise returns a positive errno value. */
97 nl_sock_create(int protocol
, struct nl_sock
**sockp
)
99 static struct ovsthread_once once
= OVSTHREAD_ONCE_INITIALIZER
;
100 struct nl_sock
*sock
;
102 struct sockaddr_nl local
, remote
;
104 socklen_t local_size
;
108 if (ovsthread_once_start(&once
)) {
109 int save_errno
= errno
;
112 max_iovs
= sysconf(_SC_UIO_MAXIOV
);
113 if (max_iovs
< _XOPEN_IOV_MAX
) {
114 if (max_iovs
== -1 && errno
) {
115 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno
));
117 max_iovs
= _XOPEN_IOV_MAX
;
118 } else if (max_iovs
> MAX_IOVS
) {
123 ovsthread_once_done(&once
);
127 sock
= xmalloc(sizeof *sock
);
130 sock
->handle
= CreateFile(OVS_DEVICE_NAME_USER
,
131 GENERIC_READ
| GENERIC_WRITE
,
132 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
134 FILE_FLAG_OVERLAPPED
, NULL
);
136 if (sock
->handle
== INVALID_HANDLE_VALUE
) {
137 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
141 memset(&sock
->overlapped
, 0, sizeof sock
->overlapped
);
142 sock
->overlapped
.hEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
143 if (sock
->overlapped
.hEvent
== NULL
) {
144 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
147 /* Initialize the type/ioctl to Generic */
148 sock
->read_ioctl
= OVS_IOCTL_READ
;
150 sock
->fd
= socket(AF_NETLINK
, SOCK_RAW
, protocol
);
152 VLOG_ERR("fcntl: %s", ovs_strerror(errno
));
157 sock
->protocol
= protocol
;
160 rcvbuf
= 1024 * 1024;
162 sock
->rcvbuf
= rcvbuf
;
163 retval
= get_sock_pid_from_kernel(sock
);
168 if (setsockopt(sock
->fd
, SOL_SOCKET
, SO_RCVBUFFORCE
,
169 &rcvbuf
, sizeof rcvbuf
)) {
170 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
171 * Warn only if the failure is therefore unexpected. */
172 if (errno
!= EPERM
) {
173 VLOG_WARN_RL(&rl
, "setting %d-byte socket receive buffer failed "
174 "(%s)", rcvbuf
, ovs_strerror(errno
));
178 retval
= get_socket_rcvbuf(sock
->fd
);
183 sock
->rcvbuf
= retval
;
186 /* Connect to kernel (pid 0) as remote address. */
187 memset(&remote
, 0, sizeof remote
);
188 remote
.nl_family
= AF_NETLINK
;
190 if (connect(sock
->fd
, (struct sockaddr
*) &remote
, sizeof remote
) < 0) {
191 VLOG_ERR("connect(0): %s", ovs_strerror(errno
));
195 /* Obtain pid assigned by kernel. */
196 local_size
= sizeof local
;
197 if (getsockname(sock
->fd
, (struct sockaddr
*) &local
, &local_size
) < 0) {
198 VLOG_ERR("getsockname: %s", ovs_strerror(errno
));
201 if (local_size
< sizeof local
|| local
.nl_family
!= AF_NETLINK
) {
202 VLOG_ERR("getsockname returned bad Netlink name");
206 sock
->pid
= local
.nl_pid
;
220 if (sock
->overlapped
.hEvent
) {
221 CloseHandle(sock
->overlapped
.hEvent
);
223 if (sock
->handle
!= INVALID_HANDLE_VALUE
) {
224 CloseHandle(sock
->handle
);
235 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
236 * sets '*sockp' to the new socket if successful, otherwise returns a positive
239 nl_sock_clone(const struct nl_sock
*src
, struct nl_sock
**sockp
)
241 return nl_sock_create(src
->protocol
, sockp
);
244 /* Destroys netlink socket 'sock'. */
246 nl_sock_destroy(struct nl_sock
*sock
)
250 if (sock
->overlapped
.hEvent
) {
251 CloseHandle(sock
->overlapped
.hEvent
);
253 CloseHandle(sock
->handle
);
262 /* Reads the pid for 'sock' generated in the kernel datapath. The function
263 * uses a separate IOCTL instead of a transaction semantic to avoid unnecessary
264 * message overhead. */
266 get_sock_pid_from_kernel(struct nl_sock
*sock
)
272 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_GET_PID
,
273 NULL
, 0, &pid
, sizeof(pid
),
277 if (bytes
< sizeof(pid
)) {
290 nl_sock_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
, bool join
)
292 struct ofpbuf request
;
293 uint64_t request_stub
[128];
294 struct ovs_header
*ovs_header
;
295 struct nlmsghdr
*nlmsg
;
298 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
300 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
301 OVS_CTRL_CMD_MC_SUBSCRIBE_REQ
,
302 OVS_WIN_CONTROL_VERSION
);
304 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
305 ovs_header
->dp_ifindex
= 0;
307 nl_msg_put_u32(&request
, OVS_NL_ATTR_MCAST_GRP
, multicast_group
);
308 nl_msg_put_u8(&request
, OVS_NL_ATTR_MCAST_JOIN
, join
? 1 : 0);
310 error
= nl_sock_send(sock
, &request
, true);
311 ofpbuf_uninit(&request
);
315 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
316 * successful, otherwise a positive errno value.
318 * A socket that is subscribed to a multicast group that receives asynchronous
319 * notifications must not be used for Netlink transactions or dumps, because
320 * transactions and dumps can cause notifications to be lost.
322 * Multicast group numbers are always positive.
324 * It is not an error to attempt to join a multicast group to which a socket
325 * already belongs. */
327 nl_sock_join_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
)
330 /* Set the socket type as a "multicast" socket */
331 sock
->read_ioctl
= OVS_IOCTL_READ_EVENT
;
332 int error
= nl_sock_mcgroup(sock
, multicast_group
, true);
334 sock
->read_ioctl
= OVS_IOCTL_READ
;
335 VLOG_WARN("could not join multicast group %u (%s)",
336 multicast_group
, ovs_strerror(error
));
340 if (setsockopt(sock
->fd
, SOL_NETLINK
, NETLINK_ADD_MEMBERSHIP
,
341 &multicast_group
, sizeof multicast_group
) < 0) {
342 VLOG_WARN("could not join multicast group %u (%s)",
343 multicast_group
, ovs_strerror(errno
));
352 nl_sock_subscribe_packets(struct nl_sock
*sock
)
356 if (sock
->read_ioctl
!= OVS_IOCTL_READ
) {
360 error
= nl_sock_subscribe_packet__(sock
, true);
362 VLOG_WARN("could not subscribe packets (%s)",
363 ovs_strerror(error
));
366 sock
->read_ioctl
= OVS_IOCTL_READ_PACKET
;
372 nl_sock_unsubscribe_packets(struct nl_sock
*sock
)
374 ovs_assert(sock
->read_ioctl
== OVS_IOCTL_READ_PACKET
);
376 int error
= nl_sock_subscribe_packet__(sock
, false);
378 VLOG_WARN("could not unsubscribe to packets (%s)",
379 ovs_strerror(error
));
383 sock
->read_ioctl
= OVS_IOCTL_READ
;
388 nl_sock_subscribe_packet__(struct nl_sock
*sock
, bool subscribe
)
390 struct ofpbuf request
;
391 uint64_t request_stub
[128];
392 struct ovs_header
*ovs_header
;
393 struct nlmsghdr
*nlmsg
;
396 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
397 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
398 OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ
,
399 OVS_WIN_CONTROL_VERSION
);
401 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
402 ovs_header
->dp_ifindex
= 0;
403 nl_msg_put_u8(&request
, OVS_NL_ATTR_PACKET_SUBSCRIBE
, subscribe
? 1 : 0);
404 nl_msg_put_u32(&request
, OVS_NL_ATTR_PACKET_PID
, sock
->pid
);
406 error
= nl_sock_send(sock
, &request
, true);
407 ofpbuf_uninit(&request
);
412 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
413 * successful, otherwise a positive errno value.
415 * Multicast group numbers are always positive.
417 * It is not an error to attempt to leave a multicast group to which a socket
420 * On success, reading from 'sock' will still return any messages that were
421 * received on 'multicast_group' before the group was left. */
423 nl_sock_leave_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
)
426 int error
= nl_sock_mcgroup(sock
, multicast_group
, false);
428 VLOG_WARN("could not leave multicast group %u (%s)",
429 multicast_group
, ovs_strerror(error
));
432 sock
->read_ioctl
= OVS_IOCTL_READ
;
434 if (setsockopt(sock
->fd
, SOL_NETLINK
, NETLINK_DROP_MEMBERSHIP
,
435 &multicast_group
, sizeof multicast_group
) < 0) {
436 VLOG_WARN("could not leave multicast group %u (%s)",
437 multicast_group
, ovs_strerror(errno
));
445 nl_sock_send__(struct nl_sock
*sock
, const struct ofpbuf
*msg
,
446 uint32_t nlmsg_seq
, bool wait
)
448 struct nlmsghdr
*nlmsg
= nl_msg_nlmsghdr(msg
);
451 nlmsg
->nlmsg_len
= msg
->size
;
452 nlmsg
->nlmsg_seq
= nlmsg_seq
;
453 nlmsg
->nlmsg_pid
= sock
->pid
;
459 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_WRITE
,
460 msg
->data
, msg
->size
, NULL
, 0,
463 /* XXX: Map to a more appropriate error based on GetLastError(). */
465 VLOG_DBG_RL(&rl
, "fatal driver failure in write: %s",
466 ovs_lasterror_to_string());
471 retval
= send(sock
->fd
, msg
->data
, msg
->size
,
472 wait
? 0 : MSG_DONTWAIT
);
474 error
= retval
< 0 ? errno
: 0;
475 } while (error
== EINTR
);
476 log_nlmsg(__func__
, error
, msg
->data
, msg
->size
, sock
->protocol
);
478 COVERAGE_INC(netlink_sent
);
483 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
484 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
485 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
486 * sequence number, before the message is sent.
488 * Returns 0 if successful, otherwise a positive errno value. If
489 * 'wait' is true, then the send will wait until buffer space is ready;
490 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
492 nl_sock_send(struct nl_sock
*sock
, const struct ofpbuf
*msg
, bool wait
)
494 return nl_sock_send_seq(sock
, msg
, nl_sock_allocate_seq(sock
, 1), wait
);
497 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
498 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
499 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
500 * 'nlmsg_seq', before the message is sent.
502 * Returns 0 if successful, otherwise a positive errno value. If
503 * 'wait' is true, then the send will wait until buffer space is ready;
504 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
506 * This function is suitable for sending a reply to a request that was received
507 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
509 nl_sock_send_seq(struct nl_sock
*sock
, const struct ofpbuf
*msg
,
510 uint32_t nlmsg_seq
, bool wait
)
512 return nl_sock_send__(sock
, msg
, nlmsg_seq
, wait
);
516 nl_sock_recv__(struct nl_sock
*sock
, struct ofpbuf
*buf
, bool wait
)
518 /* We can't accurately predict the size of the data to be received. The
519 * caller is supposed to have allocated enough space in 'buf' to handle the
520 * "typical" case. To handle exceptions, we make available enough space in
521 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
522 * figure since that's the maximum length of a Netlink attribute). */
523 struct nlmsghdr
*nlmsghdr
;
530 ovs_assert(buf
->allocated
>= sizeof *nlmsghdr
);
533 iov
[0].iov_base
= buf
->base
;
534 iov
[0].iov_len
= buf
->allocated
;
535 iov
[1].iov_base
= tail
;
536 iov
[1].iov_len
= sizeof tail
;
538 memset(&msg
, 0, sizeof msg
);
542 /* Receive a Netlink message from the kernel.
544 * This works around a kernel bug in which the kernel returns an error code
545 * as if it were the number of bytes read. It doesn't actually modify
546 * anything in the receive buffer in that case, so we can initialize the
547 * Netlink header with an impossible message length and then, upon success,
548 * check whether it changed. */
549 nlmsghdr
= buf
->base
;
551 nlmsghdr
->nlmsg_len
= UINT32_MAX
;
554 if (!DeviceIoControl(sock
->handle
, sock
->read_ioctl
,
555 NULL
, 0, tail
, sizeof tail
, &bytes
, NULL
)) {
556 VLOG_DBG_RL(&rl
, "fatal driver failure in transact: %s",
557 ovs_lasterror_to_string());
559 /* XXX: Map to a more appropriate error. */
567 if (retval
>= buf
->allocated
) {
568 ofpbuf_reinit(buf
, retval
);
569 nlmsghdr
= buf
->base
;
570 nlmsghdr
->nlmsg_len
= UINT32_MAX
;
572 memcpy(buf
->data
, tail
, retval
);
577 retval
= recvmsg(sock
->fd
, &msg
, wait
? 0 : MSG_DONTWAIT
);
579 error
= (retval
< 0 ? errno
580 : retval
== 0 ? ECONNRESET
/* not possible? */
581 : nlmsghdr
->nlmsg_len
!= UINT32_MAX
? 0
583 } while (error
== EINTR
);
585 if (error
== ENOBUFS
) {
586 /* Socket receive buffer overflow dropped one or more messages that
587 * the kernel tried to send to us. */
588 COVERAGE_INC(netlink_overflow
);
593 if (msg
.msg_flags
& MSG_TRUNC
) {
594 VLOG_ERR_RL(&rl
, "truncated message (longer than %"PRIuSIZE
" bytes)",
599 if (retval
< sizeof *nlmsghdr
600 || nlmsghdr
->nlmsg_len
< sizeof *nlmsghdr
601 || nlmsghdr
->nlmsg_len
> retval
) {
602 VLOG_ERR_RL(&rl
, "received invalid nlmsg (%"PRIuSIZE
" bytes < %"PRIuSIZE
")",
603 retval
, sizeof *nlmsghdr
);
607 buf
->size
= MIN(retval
, buf
->allocated
);
608 if (retval
> buf
->allocated
) {
609 COVERAGE_INC(netlink_recv_jumbo
);
610 ofpbuf_put(buf
, tail
, retval
- buf
->allocated
);
614 log_nlmsg(__func__
, 0, buf
->data
, buf
->size
, sock
->protocol
);
615 COVERAGE_INC(netlink_received
);
620 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
621 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
622 * EAGAIN if the 'sock' receive buffer is empty.
624 * The caller must have initialized 'buf' with an allocation of at least
625 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
626 * space for a "typical" message.
628 * On success, returns 0 and replaces 'buf''s previous content by the received
629 * message. This function expands 'buf''s allocated memory, as necessary, to
630 * hold the actual size of the received message.
632 * On failure, returns a positive errno value and clears 'buf' to zero length.
633 * 'buf' retains its previous memory allocation.
635 * Regardless of success or failure, this function resets 'buf''s headroom to
638 nl_sock_recv(struct nl_sock
*sock
, struct ofpbuf
*buf
, bool wait
)
640 return nl_sock_recv__(sock
, buf
, wait
);
644 nl_sock_record_errors__(struct nl_transaction
**transactions
, size_t n
,
649 for (i
= 0; i
< n
; i
++) {
650 struct nl_transaction
*txn
= transactions
[i
];
654 ofpbuf_clear(txn
->reply
);
660 nl_sock_transact_multiple__(struct nl_sock
*sock
,
661 struct nl_transaction
**transactions
, size_t n
,
664 uint64_t tmp_reply_stub
[1024 / 8];
665 struct nl_transaction tmp_txn
;
666 struct ofpbuf tmp_reply
;
669 struct iovec iovs
[MAX_IOVS
];
674 base_seq
= nl_sock_allocate_seq(sock
, n
);
676 for (i
= 0; i
< n
; i
++) {
677 struct nl_transaction
*txn
= transactions
[i
];
678 struct nlmsghdr
*nlmsg
= nl_msg_nlmsghdr(txn
->request
);
680 nlmsg
->nlmsg_len
= txn
->request
->size
;
681 nlmsg
->nlmsg_seq
= base_seq
+ i
;
682 nlmsg
->nlmsg_pid
= sock
->pid
;
684 iovs
[i
].iov_base
= txn
->request
->data
;
685 iovs
[i
].iov_len
= txn
->request
->size
;
689 memset(&msg
, 0, sizeof msg
);
693 error
= sendmsg(sock
->fd
, &msg
, 0) < 0 ? errno
: 0;
694 } while (error
== EINTR
);
696 for (i
= 0; i
< n
; i
++) {
697 struct nl_transaction
*txn
= transactions
[i
];
699 log_nlmsg(__func__
, error
, txn
->request
->data
,
700 txn
->request
->size
, sock
->protocol
);
703 COVERAGE_ADD(netlink_sent
, n
);
710 ofpbuf_use_stub(&tmp_reply
, tmp_reply_stub
, sizeof tmp_reply_stub
);
711 tmp_txn
.request
= NULL
;
712 tmp_txn
.reply
= &tmp_reply
;
715 struct nl_transaction
*buf_txn
, *txn
;
718 /* Find a transaction whose buffer we can use for receiving a reply.
719 * If no such transaction is left, use tmp_txn. */
721 for (i
= 0; i
< n
; i
++) {
722 if (transactions
[i
]->reply
) {
723 buf_txn
= transactions
[i
];
728 /* Receive a reply. */
729 error
= nl_sock_recv__(sock
, buf_txn
->reply
, false);
731 if (error
== EAGAIN
) {
732 nl_sock_record_errors__(transactions
, n
, 0);
739 /* Match the reply up with a transaction. */
740 seq
= nl_msg_nlmsghdr(buf_txn
->reply
)->nlmsg_seq
;
741 if (seq
< base_seq
|| seq
>= base_seq
+ n
) {
742 VLOG_DBG_RL(&rl
, "ignoring unexpected seq %#"PRIx32
, seq
);
746 txn
= transactions
[i
];
748 /* Fill in the results for 'txn'. */
749 if (nl_msg_nlmsgerr(buf_txn
->reply
, &txn
->error
)) {
751 ofpbuf_clear(txn
->reply
);
754 VLOG_DBG_RL(&rl
, "received NAK error=%d (%s)",
755 error
, ovs_strerror(txn
->error
));
759 if (txn
->reply
&& txn
!= buf_txn
) {
761 struct ofpbuf
*reply
= buf_txn
->reply
;
762 buf_txn
->reply
= txn
->reply
;
767 /* Fill in the results for transactions before 'txn'. (We have to do
768 * this after the results for 'txn' itself because of the buffer swap
770 nl_sock_record_errors__(transactions
, i
, 0);
774 transactions
+= i
+ 1;
778 ofpbuf_uninit(&tmp_reply
);
781 uint8_t reply_buf
[65536];
782 for (i
= 0; i
< n
; i
++) {
785 struct nl_transaction
*txn
= transactions
[i
];
786 struct nlmsghdr
*request_nlmsg
, *reply_nlmsg
;
788 ret
= DeviceIoControl(sock
->handle
, OVS_IOCTL_TRANSACT
,
791 reply_buf
, sizeof reply_buf
,
794 if (ret
&& reply_len
== 0) {
796 * The current transaction did not produce any data to read and that
797 * is not an error as such. Continue with the remainder of the
802 ofpbuf_clear(txn
->reply
);
805 /* XXX: Map to a more appropriate error. */
807 VLOG_DBG_RL(&rl
, "fatal driver failure: %s",
808 ovs_lasterror_to_string());
812 if (reply_len
!= 0) {
813 if (reply_len
< sizeof *reply_nlmsg
) {
814 nl_sock_record_errors__(transactions
, n
, 0);
815 VLOG_DBG_RL(&rl
, "insufficient length of reply %#"PRIu32
816 " for seq: %#"PRIx32
, reply_len
, request_nlmsg
->nlmsg_seq
);
820 /* Validate the sequence number in the reply. */
821 request_nlmsg
= nl_msg_nlmsghdr(txn
->request
);
822 reply_nlmsg
= (struct nlmsghdr
*)reply_buf
;
824 if (request_nlmsg
->nlmsg_seq
!= reply_nlmsg
->nlmsg_seq
) {
825 ovs_assert(request_nlmsg
->nlmsg_seq
== reply_nlmsg
->nlmsg_seq
);
826 VLOG_DBG_RL(&rl
, "mismatched seq request %#"PRIx32
827 ", reply %#"PRIx32
, request_nlmsg
->nlmsg_seq
,
828 reply_nlmsg
->nlmsg_seq
);
832 /* Handle errors embedded within the netlink message. */
833 ofpbuf_use_stub(&tmp_reply
, reply_buf
, sizeof reply_buf
);
834 tmp_reply
.size
= sizeof reply_buf
;
835 if (nl_msg_nlmsgerr(&tmp_reply
, &txn
->error
)) {
837 ofpbuf_clear(txn
->reply
);
840 VLOG_DBG_RL(&rl
, "received NAK error=%d (%s)",
841 error
, ovs_strerror(txn
->error
));
846 /* Copy the reply to the buffer specified by the caller. */
847 if (reply_len
> txn
->reply
->allocated
) {
848 ofpbuf_reinit(txn
->reply
, reply_len
);
850 memcpy(txn
->reply
->data
, reply_buf
, reply_len
);
851 txn
->reply
->size
= reply_len
;
854 ofpbuf_uninit(&tmp_reply
);
857 /* Count the number of successful transactions. */
863 COVERAGE_ADD(netlink_sent
, n
);
871 nl_sock_transact_multiple(struct nl_sock
*sock
,
872 struct nl_transaction
**transactions
, size_t n
)
881 /* In theory, every request could have a 64 kB reply. But the default and
882 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
883 * be a bit below 128 kB, so that would only allow a single message in a
884 * "batch". So we assume that replies average (at most) 4 kB, which allows
885 * a good deal of batching.
887 * In practice, most of the requests that we batch either have no reply at
888 * all or a brief reply. */
889 max_batch_count
= MAX(sock
->rcvbuf
/ 4096, 1);
890 max_batch_count
= MIN(max_batch_count
, max_iovs
);
896 /* Batch up to 'max_batch_count' transactions. But cap it at about a
897 * page of requests total because big skbuffs are expensive to
898 * allocate in the kernel. */
899 #if defined(PAGESIZE)
900 enum { MAX_BATCH_BYTES
= MAX(1, PAGESIZE
- 512) };
902 enum { MAX_BATCH_BYTES
= 4096 - 512 };
904 bytes
= transactions
[0]->request
->size
;
905 for (count
= 1; count
< n
&& count
< max_batch_count
; count
++) {
906 if (bytes
+ transactions
[count
]->request
->size
> MAX_BATCH_BYTES
) {
909 bytes
+= transactions
[count
]->request
->size
;
912 error
= nl_sock_transact_multiple__(sock
, transactions
, count
, &done
);
913 transactions
+= done
;
916 if (error
== ENOBUFS
) {
917 VLOG_DBG_RL(&rl
, "receive buffer overflow, resending request");
919 VLOG_ERR_RL(&rl
, "transaction error (%s)", ovs_strerror(error
));
920 nl_sock_record_errors__(transactions
, n
, error
);
921 if (error
!= EAGAIN
) {
922 /* A fatal error has occurred. Abort the rest of
931 nl_sock_transact(struct nl_sock
*sock
, const struct ofpbuf
*request
,
932 struct ofpbuf
**replyp
)
934 struct nl_transaction
*transactionp
;
935 struct nl_transaction transaction
;
937 transaction
.request
= CONST_CAST(struct ofpbuf
*, request
);
938 transaction
.reply
= replyp
? ofpbuf_new(1024) : NULL
;
939 transactionp
= &transaction
;
941 nl_sock_transact_multiple(sock
, &transactionp
, 1);
944 if (transaction
.error
) {
945 ofpbuf_delete(transaction
.reply
);
948 *replyp
= transaction
.reply
;
952 return transaction
.error
;
955 /* Drain all the messages currently in 'sock''s receive queue. */
957 nl_sock_drain(struct nl_sock
*sock
)
962 return drain_rcvbuf(sock
->fd
);
966 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
967 * Netlink socket created with the given 'protocol', and initializes 'dump' to
968 * reflect the state of the operation.
970 * 'request' must contain a Netlink message. Before sending the message,
971 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
972 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
975 * The design of this Netlink socket library ensures that the dump is reliable.
977 * This function provides no status indication. nl_dump_done() provides an
978 * error status for the entire dump operation.
980 * The caller must eventually destroy 'request'.
983 nl_dump_start(struct nl_dump
*dump
, int protocol
, const struct ofpbuf
*request
)
985 nl_msg_nlmsghdr(request
)->nlmsg_flags
|= NLM_F_DUMP
| NLM_F_ACK
;
987 ovs_mutex_init(&dump
->mutex
);
988 ovs_mutex_lock(&dump
->mutex
);
989 dump
->status
= nl_pool_alloc(protocol
, &dump
->sock
);
991 dump
->status
= nl_sock_send__(dump
->sock
, request
,
992 nl_sock_allocate_seq(dump
->sock
, 1),
995 dump
->nl_seq
= nl_msg_nlmsghdr(request
)->nlmsg_seq
;
996 ovs_mutex_unlock(&dump
->mutex
);
1000 nl_dump_refill(struct nl_dump
*dump
, struct ofpbuf
*buffer
)
1001 OVS_REQUIRES(dump
->mutex
)
1003 struct nlmsghdr
*nlmsghdr
;
1006 while (!buffer
->size
) {
1007 error
= nl_sock_recv__(dump
->sock
, buffer
, false);
1009 /* The kernel never blocks providing the results of a dump, so
1010 * error == EAGAIN means that we've read the whole thing, and
1011 * therefore transform it into EOF. (The kernel always provides
1012 * NLMSG_DONE as a sentinel. Some other thread must have received
1013 * that already but not yet signaled it in 'status'.)
1015 * Any other error is just an error. */
1016 return error
== EAGAIN
? EOF
: error
;
1019 nlmsghdr
= nl_msg_nlmsghdr(buffer
);
1020 if (dump
->nl_seq
!= nlmsghdr
->nlmsg_seq
) {
1021 VLOG_DBG_RL(&rl
, "ignoring seq %#"PRIx32
" != expected %#"PRIx32
,
1022 nlmsghdr
->nlmsg_seq
, dump
->nl_seq
);
1023 ofpbuf_clear(buffer
);
1027 if (nl_msg_nlmsgerr(buffer
, &error
) && error
) {
1028 VLOG_INFO_RL(&rl
, "netlink dump request error (%s)",
1029 ovs_strerror(error
));
1030 ofpbuf_clear(buffer
);
1038 nl_dump_next__(struct ofpbuf
*reply
, struct ofpbuf
*buffer
)
1040 struct nlmsghdr
*nlmsghdr
= nl_msg_next(buffer
, reply
);
1042 VLOG_WARN_RL(&rl
, "netlink dump contains message fragment");
1044 } else if (nlmsghdr
->nlmsg_type
== NLMSG_DONE
) {
1051 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1052 * have been initialized with nl_dump_start(), and 'buffer' must have been
1053 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1055 * If successful, returns true and points 'reply->data' and
1056 * 'reply->size' to the message that was retrieved. The caller must not
1057 * modify 'reply' (because it points within 'buffer', which will be used by
1058 * future calls to this function).
1060 * On failure, returns false and sets 'reply->data' to NULL and
1061 * 'reply->size' to 0. Failure might indicate an actual error or merely
1062 * the end of replies. An error status for the entire dump operation is
1063 * provided when it is completed by calling nl_dump_done().
1065 * Multiple threads may call this function, passing the same nl_dump, however
1066 * each must provide independent buffers. This function may cache multiple
1067 * replies in the buffer, and these will be processed before more replies are
1068 * fetched. When this function returns false, other threads may continue to
1069 * process replies in their buffers, but they will not fetch more replies.
1072 nl_dump_next(struct nl_dump
*dump
, struct ofpbuf
*reply
, struct ofpbuf
*buffer
)
1076 /* If the buffer is empty, refill it.
1078 * If the buffer is not empty, we don't check the dump's status.
1079 * Otherwise, we could end up skipping some of the dump results if thread A
1080 * hits EOF while thread B is in the midst of processing a batch. */
1081 if (!buffer
->size
) {
1082 ovs_mutex_lock(&dump
->mutex
);
1083 if (!dump
->status
) {
1084 /* Take the mutex here to avoid an in-kernel race. If two threads
1085 * try to read from a Netlink dump socket at once, then the socket
1086 * error can be set to EINVAL, which will be encountered on the
1087 * next recv on that socket, which could be anywhere due to the way
1088 * that we pool Netlink sockets. Serializing the recv calls avoids
1090 dump
->status
= nl_dump_refill(dump
, buffer
);
1092 retval
= dump
->status
;
1093 ovs_mutex_unlock(&dump
->mutex
);
1096 /* Fetch the next message from the buffer. */
1098 retval
= nl_dump_next__(reply
, buffer
);
1100 /* Record 'retval' as the dump status, but don't overwrite an error
1102 ovs_mutex_lock(&dump
->mutex
);
1103 if (dump
->status
<= 0) {
1104 dump
->status
= retval
;
1106 ovs_mutex_unlock(&dump
->mutex
);
1117 /* Completes Netlink dump operation 'dump', which must have been initialized
1118 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1119 * otherwise a positive errno value describing the problem. */
1121 nl_dump_done(struct nl_dump
*dump
)
1125 ovs_mutex_lock(&dump
->mutex
);
1126 status
= dump
->status
;
1127 ovs_mutex_unlock(&dump
->mutex
);
1129 /* Drain any remaining messages that the client didn't read. Otherwise the
1130 * kernel will continue to queue them up and waste buffer space.
1132 * XXX We could just destroy and discard the socket in this case. */
1134 uint64_t tmp_reply_stub
[NL_DUMP_BUFSIZE
/ 8];
1135 struct ofpbuf reply
, buf
;
1137 ofpbuf_use_stub(&buf
, tmp_reply_stub
, sizeof tmp_reply_stub
);
1138 while (nl_dump_next(dump
, &reply
, &buf
)) {
1139 /* Nothing to do. */
1141 ofpbuf_uninit(&buf
);
1143 ovs_mutex_lock(&dump
->mutex
);
1144 status
= dump
->status
;
1145 ovs_mutex_unlock(&dump
->mutex
);
1149 nl_pool_release(dump
->sock
);
1150 ovs_mutex_destroy(&dump
->mutex
);
1152 return status
== EOF
? 0 : status
;
1156 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1157 * an event or a packet is ready to be read. Once the I/O is completed
1158 * the overlapped structure event associated with the pending I/O will be set
1161 pend_io_request(struct nl_sock
*sock
)
1163 struct ofpbuf request
;
1164 uint64_t request_stub
[128];
1165 struct ovs_header
*ovs_header
;
1166 struct nlmsghdr
*nlmsg
;
1171 OVERLAPPED
*overlapped
= CONST_CAST(OVERLAPPED
*, &sock
->overlapped
);
1172 uint16_t cmd
= OVS_CTRL_CMD_WIN_PEND_PACKET_REQ
;
1174 ovs_assert(sock
->read_ioctl
== OVS_IOCTL_READ_PACKET
||
1175 sock
->read_ioctl
== OVS_IOCTL_READ_EVENT
);
1176 if (sock
->read_ioctl
== OVS_IOCTL_READ_EVENT
) {
1177 cmd
= OVS_CTRL_CMD_WIN_PEND_REQ
;
1180 int ovs_msg_size
= sizeof (struct nlmsghdr
) + sizeof (struct genlmsghdr
) +
1181 sizeof (struct ovs_header
);
1183 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
1185 seq
= nl_sock_allocate_seq(sock
, 1);
1186 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
1187 cmd
, OVS_WIN_CONTROL_VERSION
);
1188 nlmsg
= nl_msg_nlmsghdr(&request
);
1189 nlmsg
->nlmsg_seq
= seq
;
1190 nlmsg
->nlmsg_pid
= sock
->pid
;
1192 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
1193 ovs_header
->dp_ifindex
= 0;
1195 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_WRITE
,
1196 request
.data
, request
.size
,
1197 NULL
, 0, &bytes
, overlapped
)) {
1198 error
= GetLastError();
1199 /* Check if the I/O got pended */
1200 if (error
!= ERROR_IO_INCOMPLETE
&& error
!= ERROR_IO_PENDING
) {
1201 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error
));
1209 ofpbuf_uninit(&request
);
1214 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1215 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'.
1216 * On Windows, 'sock' is not treated as const, and may be modified. */
1218 nl_sock_wait(const struct nl_sock
*sock
, short int events
)
1221 if (sock
->overlapped
.Internal
!= STATUS_PENDING
) {
1222 int ret
= pend_io_request(CONST_CAST(struct nl_sock
*, sock
));
1224 poll_wevent_wait(sock
->overlapped
.hEvent
);
1226 poll_immediate_wake();
1229 poll_wevent_wait(sock
->overlapped
.hEvent
);
1232 poll_fd_wait(sock
->fd
, events
);
1237 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1238 * that can't use nl_sock_wait().
1240 * It's a little tricky to use the returned fd correctly, because nl_sock does
1241 * "copy on write" to allow a single nl_sock to be used for notifications,
1242 * transactions, and dumps. If 'sock' is used only for notifications and
1243 * transactions (and never for dump) then the usage is safe. */
1245 nl_sock_fd(const struct nl_sock
*sock
)
1251 /* Returns the PID associated with this socket. */
1253 nl_sock_pid(const struct nl_sock
*sock
)
1258 /* Miscellaneous. */
1260 struct genl_family
{
1261 struct hmap_node hmap_node
;
1266 static struct hmap genl_families
= HMAP_INITIALIZER(&genl_families
);
1268 static const struct nl_policy family_policy
[CTRL_ATTR_MAX
+ 1] = {
1269 [CTRL_ATTR_FAMILY_ID
] = {.type
= NL_A_U16
},
1270 [CTRL_ATTR_MCAST_GROUPS
] = {.type
= NL_A_NESTED
, .optional
= true},
1273 static struct genl_family
*
1274 find_genl_family_by_id(uint16_t id
)
1276 struct genl_family
*family
;
1278 HMAP_FOR_EACH_IN_BUCKET (family
, hmap_node
, hash_int(id
, 0),
1280 if (family
->id
== id
) {
1288 define_genl_family(uint16_t id
, const char *name
)
1290 struct genl_family
*family
= find_genl_family_by_id(id
);
1293 if (!strcmp(family
->name
, name
)) {
1298 family
= xmalloc(sizeof *family
);
1300 hmap_insert(&genl_families
, &family
->hmap_node
, hash_int(id
, 0));
1302 family
->name
= xstrdup(name
);
1306 genl_family_to_name(uint16_t id
)
1308 if (id
== GENL_ID_CTRL
) {
1311 struct genl_family
*family
= find_genl_family_by_id(id
);
1312 return family
? family
->name
: "unknown";
1318 do_lookup_genl_family(const char *name
, struct nlattr
**attrs
,
1319 struct ofpbuf
**replyp
)
1321 struct nl_sock
*sock
;
1322 struct ofpbuf request
, *reply
;
1326 error
= nl_sock_create(NETLINK_GENERIC
, &sock
);
1331 ofpbuf_init(&request
, 0);
1332 nl_msg_put_genlmsghdr(&request
, 0, GENL_ID_CTRL
, NLM_F_REQUEST
,
1333 CTRL_CMD_GETFAMILY
, 1);
1334 nl_msg_put_string(&request
, CTRL_ATTR_FAMILY_NAME
, name
);
1335 error
= nl_sock_transact(sock
, &request
, &reply
);
1336 ofpbuf_uninit(&request
);
1338 nl_sock_destroy(sock
);
1342 if (!nl_policy_parse(reply
, NLMSG_HDRLEN
+ GENL_HDRLEN
,
1343 family_policy
, attrs
, ARRAY_SIZE(family_policy
))
1344 || nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]) == 0) {
1345 nl_sock_destroy(sock
);
1346 ofpbuf_delete(reply
);
1350 nl_sock_destroy(sock
);
1356 do_lookup_genl_family(const char *name
, struct nlattr
**attrs
,
1357 struct ofpbuf
**replyp
)
1359 struct nlmsghdr
*nlmsg
;
1360 struct ofpbuf
*reply
;
1363 const char *family_name
;
1364 uint32_t family_version
;
1365 uint32_t family_attrmax
;
1366 uint32_t mcgrp_id
= OVS_WIN_NL_INVALID_MCGRP_ID
;
1367 const char *mcgrp_name
= NULL
;
1370 reply
= ofpbuf_new(1024);
1372 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1373 if (!strcmp(name
, OVS_WIN_CONTROL_FAMILY
)) {
1374 family_id
= OVS_WIN_NL_CTRL_FAMILY_ID
;
1375 family_name
= OVS_WIN_CONTROL_FAMILY
;
1376 family_version
= OVS_WIN_CONTROL_VERSION
;
1377 family_attrmax
= OVS_WIN_CONTROL_ATTR_MAX
;
1378 } else if (!strcmp(name
, OVS_DATAPATH_FAMILY
)) {
1379 family_id
= OVS_WIN_NL_DATAPATH_FAMILY_ID
;
1380 family_name
= OVS_DATAPATH_FAMILY
;
1381 family_version
= OVS_DATAPATH_VERSION
;
1382 family_attrmax
= OVS_DP_ATTR_MAX
;
1383 } else if (!strcmp(name
, OVS_PACKET_FAMILY
)) {
1384 family_id
= OVS_WIN_NL_PACKET_FAMILY_ID
;
1385 family_name
= OVS_PACKET_FAMILY
;
1386 family_version
= OVS_PACKET_VERSION
;
1387 family_attrmax
= OVS_PACKET_ATTR_MAX
;
1388 } else if (!strcmp(name
, OVS_VPORT_FAMILY
)) {
1389 family_id
= OVS_WIN_NL_VPORT_FAMILY_ID
;
1390 family_name
= OVS_VPORT_FAMILY
;
1391 family_version
= OVS_VPORT_VERSION
;
1392 family_attrmax
= OVS_VPORT_ATTR_MAX
;
1393 mcgrp_id
= OVS_WIN_NL_VPORT_MCGRP_ID
;
1394 mcgrp_name
= OVS_VPORT_MCGROUP
;
1395 } else if (!strcmp(name
, OVS_FLOW_FAMILY
)) {
1396 family_id
= OVS_WIN_NL_FLOW_FAMILY_ID
;
1397 family_name
= OVS_FLOW_FAMILY
;
1398 family_version
= OVS_FLOW_VERSION
;
1399 family_attrmax
= OVS_FLOW_ATTR_MAX
;
1400 } else if (!strcmp(name
, OVS_WIN_NETDEV_FAMILY
)) {
1401 family_id
= OVS_WIN_NL_NETDEV_FAMILY_ID
;
1402 family_name
= OVS_WIN_NETDEV_FAMILY
;
1403 family_version
= OVS_WIN_NETDEV_VERSION
;
1404 family_attrmax
= OVS_WIN_NETDEV_ATTR_MAX
;
1406 ofpbuf_delete(reply
);
1410 nl_msg_put_genlmsghdr(reply
, 0, GENL_ID_CTRL
, 0,
1411 CTRL_CMD_NEWFAMILY
, family_version
);
1412 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1413 * callers do not seem to need them. */
1414 nl_msg_put_u16(reply
, CTRL_ATTR_FAMILY_ID
, family_id
);
1415 nl_msg_put_string(reply
, CTRL_ATTR_FAMILY_NAME
, family_name
);
1416 nl_msg_put_u32(reply
, CTRL_ATTR_VERSION
, family_version
);
1417 nl_msg_put_u32(reply
, CTRL_ATTR_MAXATTR
, family_attrmax
);
1419 if (mcgrp_id
!= OVS_WIN_NL_INVALID_MCGRP_ID
) {
1420 size_t mcgrp_ofs1
= nl_msg_start_nested(reply
, CTRL_ATTR_MCAST_GROUPS
);
1421 size_t mcgrp_ofs2
= nl_msg_start_nested(reply
,
1422 OVS_WIN_NL_VPORT_MCGRP_ID
- OVS_WIN_NL_MCGRP_START_ID
);
1423 nl_msg_put_u32(reply
, CTRL_ATTR_MCAST_GRP_ID
, mcgrp_id
);
1424 ovs_assert(mcgrp_name
!= NULL
);
1425 nl_msg_put_string(reply
, CTRL_ATTR_MCAST_GRP_NAME
, mcgrp_name
);
1426 nl_msg_end_nested(reply
, mcgrp_ofs2
);
1427 nl_msg_end_nested(reply
, mcgrp_ofs1
);
1430 /* Set the total length of the netlink message. */
1431 nlmsg
= nl_msg_nlmsghdr(reply
);
1432 nlmsg
->nlmsg_len
= reply
->size
;
1434 if (!nl_policy_parse(reply
, NLMSG_HDRLEN
+ GENL_HDRLEN
,
1435 family_policy
, attrs
, ARRAY_SIZE(family_policy
))
1436 || nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]) == 0) {
1437 ofpbuf_delete(reply
);
1446 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1447 * When successful, writes its result to 'multicast_group' and returns 0.
1448 * Otherwise, clears 'multicast_group' and returns a positive error code.
1451 nl_lookup_genl_mcgroup(const char *family_name
, const char *group_name
,
1452 unsigned int *multicast_group
)
1454 struct nlattr
*family_attrs
[ARRAY_SIZE(family_policy
)];
1455 const struct nlattr
*mc
;
1456 struct ofpbuf
*reply
;
1460 *multicast_group
= 0;
1461 error
= do_lookup_genl_family(family_name
, family_attrs
, &reply
);
1466 if (!family_attrs
[CTRL_ATTR_MCAST_GROUPS
]) {
1471 NL_NESTED_FOR_EACH (mc
, left
, family_attrs
[CTRL_ATTR_MCAST_GROUPS
]) {
1472 static const struct nl_policy mc_policy
[] = {
1473 [CTRL_ATTR_MCAST_GRP_ID
] = {.type
= NL_A_U32
},
1474 [CTRL_ATTR_MCAST_GRP_NAME
] = {.type
= NL_A_STRING
},
1477 struct nlattr
*mc_attrs
[ARRAY_SIZE(mc_policy
)];
1478 const char *mc_name
;
1480 if (!nl_parse_nested(mc
, mc_policy
, mc_attrs
, ARRAY_SIZE(mc_policy
))) {
1485 mc_name
= nl_attr_get_string(mc_attrs
[CTRL_ATTR_MCAST_GRP_NAME
]);
1486 if (!strcmp(group_name
, mc_name
)) {
1488 nl_attr_get_u32(mc_attrs
[CTRL_ATTR_MCAST_GRP_ID
]);
1496 ofpbuf_delete(reply
);
1500 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1501 * number and stores it in '*number'. If successful, returns 0 and the caller
1502 * may use '*number' as the family number. On failure, returns a positive
1503 * errno value and '*number' caches the errno value. */
1505 nl_lookup_genl_family(const char *name
, int *number
)
1508 struct nlattr
*attrs
[ARRAY_SIZE(family_policy
)];
1509 struct ofpbuf
*reply
;
1512 error
= do_lookup_genl_family(name
, attrs
, &reply
);
1514 *number
= nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]);
1515 define_genl_family(*number
, name
);
1519 ofpbuf_delete(reply
);
1521 ovs_assert(*number
!= 0);
1523 return *number
> 0 ? 0 : -*number
;
1527 struct nl_sock
*socks
[16];
1531 static struct ovs_mutex pool_mutex
= OVS_MUTEX_INITIALIZER
;
1532 static struct nl_pool pools
[MAX_LINKS
] OVS_GUARDED_BY(pool_mutex
);
1535 nl_pool_alloc(int protocol
, struct nl_sock
**sockp
)
1537 struct nl_sock
*sock
= NULL
;
1538 struct nl_pool
*pool
;
1540 ovs_assert(protocol
>= 0 && protocol
< ARRAY_SIZE(pools
));
1542 ovs_mutex_lock(&pool_mutex
);
1543 pool
= &pools
[protocol
];
1545 sock
= pool
->socks
[--pool
->n
];
1547 ovs_mutex_unlock(&pool_mutex
);
1553 return nl_sock_create(protocol
, sockp
);
1558 nl_pool_release(struct nl_sock
*sock
)
1561 struct nl_pool
*pool
= &pools
[sock
->protocol
];
1563 ovs_mutex_lock(&pool_mutex
);
1564 if (pool
->n
< ARRAY_SIZE(pool
->socks
)) {
1565 pool
->socks
[pool
->n
++] = sock
;
1568 ovs_mutex_unlock(&pool_mutex
);
1570 nl_sock_destroy(sock
);
1574 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1575 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1576 * successful, returns 0. On failure, returns a positive errno value.
1578 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1579 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1580 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1581 * reply, if any, is discarded.
1583 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1584 * match msg->size, nlmsg_pid will be set to the pid of the socket used
1585 * for sending the request, and nlmsg_seq will be initialized.
1587 * The caller is responsible for destroying 'request'.
1589 * Bare Netlink is an unreliable transport protocol. This function layers
1590 * reliable delivery and reply semantics on top of bare Netlink.
1592 * In Netlink, sending a request to the kernel is reliable enough, because the
1593 * kernel will tell us if the message cannot be queued (and we will in that
1594 * case put it on the transmit queue and wait until it can be delivered).
1596 * Receiving the reply is the real problem: if the socket buffer is full when
1597 * the kernel tries to send the reply, the reply will be dropped. However, the
1598 * kernel sets a flag that a reply has been dropped. The next call to recv
1599 * then returns ENOBUFS. We can then re-send the request.
1603 * 1. Netlink depends on sequence numbers to match up requests and
1604 * replies. The sender of a request supplies a sequence number, and
1605 * the reply echos back that sequence number.
1607 * This is fine, but (1) some kernel netlink implementations are
1608 * broken, in that they fail to echo sequence numbers and (2) this
1609 * function will drop packets with non-matching sequence numbers, so
1610 * that only a single request can be usefully transacted at a time.
1612 * 2. Resending the request causes it to be re-executed, so the request
1613 * needs to be idempotent.
1616 nl_transact(int protocol
, const struct ofpbuf
*request
,
1617 struct ofpbuf
**replyp
)
1619 struct nl_sock
*sock
;
1622 error
= nl_pool_alloc(protocol
, &sock
);
1628 error
= nl_sock_transact(sock
, request
, replyp
);
1630 nl_pool_release(sock
);
1634 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1635 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1636 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1637 * the 'error' member of each transaction with 0 if it was successful,
1638 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1639 * be filled with the reply if the message receives a detailed reply. In other
1640 * cases, i.e. where the request failed or had no reply beyond an indication of
1641 * success, 'reply' will be cleared if it is nonnull.
1643 * The caller is responsible for destroying each request and reply, and the
1644 * transactions array itself.
1646 * Before sending each message, this function will finalize nlmsg_len in each
1647 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1648 * used for the transaction, and initialize nlmsg_seq.
1650 * Bare Netlink is an unreliable transport protocol. This function layers
1651 * reliable delivery and reply semantics on top of bare Netlink. See
1652 * nl_transact() for some caveats.
1655 nl_transact_multiple(int protocol
,
1656 struct nl_transaction
**transactions
, size_t n
)
1658 struct nl_sock
*sock
;
1661 error
= nl_pool_alloc(protocol
, &sock
);
1663 nl_sock_transact_multiple(sock
, transactions
, n
);
1664 nl_pool_release(sock
);
1666 nl_sock_record_errors__(transactions
, n
, error
);
1672 nl_sock_allocate_seq(struct nl_sock
*sock
, unsigned int n
)
1674 uint32_t seq
= sock
->next_seq
;
1676 sock
->next_seq
+= n
;
1678 /* Make it impossible for the next request for sequence numbers to wrap
1679 * around to 0. Start over with 1 to avoid ever using a sequence number of
1680 * 0, because the kernel uses sequence number 0 for notifications. */
1681 if (sock
->next_seq
>= UINT32_MAX
/ 2) {
1689 nlmsghdr_to_string(const struct nlmsghdr
*h
, int protocol
, struct ds
*ds
)
1695 static const struct nlmsg_flag flags
[] = {
1696 { NLM_F_REQUEST
, "REQUEST" },
1697 { NLM_F_MULTI
, "MULTI" },
1698 { NLM_F_ACK
, "ACK" },
1699 { NLM_F_ECHO
, "ECHO" },
1700 { NLM_F_DUMP
, "DUMP" },
1701 { NLM_F_ROOT
, "ROOT" },
1702 { NLM_F_MATCH
, "MATCH" },
1703 { NLM_F_ATOMIC
, "ATOMIC" },
1705 const struct nlmsg_flag
*flag
;
1706 uint16_t flags_left
;
1708 ds_put_format(ds
, "nl(len:%"PRIu32
", type=%"PRIu16
,
1709 h
->nlmsg_len
, h
->nlmsg_type
);
1710 if (h
->nlmsg_type
== NLMSG_NOOP
) {
1711 ds_put_cstr(ds
, "(no-op)");
1712 } else if (h
->nlmsg_type
== NLMSG_ERROR
) {
1713 ds_put_cstr(ds
, "(error)");
1714 } else if (h
->nlmsg_type
== NLMSG_DONE
) {
1715 ds_put_cstr(ds
, "(done)");
1716 } else if (h
->nlmsg_type
== NLMSG_OVERRUN
) {
1717 ds_put_cstr(ds
, "(overrun)");
1718 } else if (h
->nlmsg_type
< NLMSG_MIN_TYPE
) {
1719 ds_put_cstr(ds
, "(reserved)");
1720 } else if (protocol
== NETLINK_GENERIC
) {
1721 ds_put_format(ds
, "(%s)", genl_family_to_name(h
->nlmsg_type
));
1723 ds_put_cstr(ds
, "(family-defined)");
1725 ds_put_format(ds
, ", flags=%"PRIx16
, h
->nlmsg_flags
);
1726 flags_left
= h
->nlmsg_flags
;
1727 for (flag
= flags
; flag
< &flags
[ARRAY_SIZE(flags
)]; flag
++) {
1728 if ((flags_left
& flag
->bits
) == flag
->bits
) {
1729 ds_put_format(ds
, "[%s]", flag
->name
);
1730 flags_left
&= ~flag
->bits
;
1734 ds_put_format(ds
, "[OTHER:%"PRIx16
"]", flags_left
);
1736 ds_put_format(ds
, ", seq=%"PRIx32
", pid=%"PRIu32
,
1737 h
->nlmsg_seq
, h
->nlmsg_pid
);
1741 nlmsg_to_string(const struct ofpbuf
*buffer
, int protocol
)
1743 struct ds ds
= DS_EMPTY_INITIALIZER
;
1744 const struct nlmsghdr
*h
= ofpbuf_at(buffer
, 0, NLMSG_HDRLEN
);
1746 nlmsghdr_to_string(h
, protocol
, &ds
);
1747 if (h
->nlmsg_type
== NLMSG_ERROR
) {
1748 const struct nlmsgerr
*e
;
1749 e
= ofpbuf_at(buffer
, NLMSG_HDRLEN
,
1750 NLMSG_ALIGN(sizeof(struct nlmsgerr
)));
1752 ds_put_format(&ds
, " error(%d", e
->error
);
1754 ds_put_format(&ds
, "(%s)", ovs_strerror(-e
->error
));
1756 ds_put_cstr(&ds
, ", in-reply-to(");
1757 nlmsghdr_to_string(&e
->msg
, protocol
, &ds
);
1758 ds_put_cstr(&ds
, "))");
1760 ds_put_cstr(&ds
, " error(truncated)");
1762 } else if (h
->nlmsg_type
== NLMSG_DONE
) {
1763 int *error
= ofpbuf_at(buffer
, NLMSG_HDRLEN
, sizeof *error
);
1765 ds_put_format(&ds
, " done(%d", *error
);
1767 ds_put_format(&ds
, "(%s)", ovs_strerror(-*error
));
1769 ds_put_cstr(&ds
, ")");
1771 ds_put_cstr(&ds
, " done(truncated)");
1773 } else if (protocol
== NETLINK_GENERIC
) {
1774 struct genlmsghdr
*genl
= nl_msg_genlmsghdr(buffer
);
1776 ds_put_format(&ds
, ",genl(cmd=%"PRIu8
",version=%"PRIu8
")",
1777 genl
->cmd
, genl
->version
);
1781 ds_put_cstr(&ds
, "nl(truncated)");
1787 log_nlmsg(const char *function
, int error
,
1788 const void *message
, size_t size
, int protocol
)
1790 if (!VLOG_IS_DBG_ENABLED()) {
1794 struct ofpbuf buffer
= ofpbuf_const_initializer(message
, size
);
1795 char *nlmsg
= nlmsg_to_string(&buffer
, protocol
);
1796 VLOG_DBG_RL(&rl
, "%s (%s): %s", function
, ovs_strerror(error
), nlmsg
);