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/socket.h>
23 #include <sys/types.h>
27 #include "openvswitch/dynamic-string.h"
29 #include "openvswitch/hmap.h"
31 #include "netlink-protocol.h"
33 #include "odp-netlink.h"
34 #include "openvswitch/ofpbuf.h"
35 #include "ovs-thread.h"
36 #include "openvswitch/poll-loop.h"
38 #include "socket-util.h"
40 #include "openvswitch/vlog.h"
42 VLOG_DEFINE_THIS_MODULE(netlink_socket
);
44 COVERAGE_DEFINE(netlink_overflow
);
45 COVERAGE_DEFINE(netlink_received
);
46 COVERAGE_DEFINE(netlink_recv_jumbo
);
47 COVERAGE_DEFINE(netlink_sent
);
49 /* Linux header file confusion causes this to be undefined. */
51 #define SOL_NETLINK 270
54 /* A single (bad) Netlink message can in theory dump out many, many log
55 * messages, so the burst size is set quite high here to avoid missing useful
56 * information. Also, at high logging levels we log *all* Netlink messages. */
57 static struct vlog_rate_limit rl
= VLOG_RATE_LIMIT_INIT(60, 600);
59 static uint32_t nl_sock_allocate_seq(struct nl_sock
*, unsigned int n
);
60 static void log_nlmsg(const char *function
, int error
,
61 const void *message
, size_t size
, int protocol
);
63 static int get_sock_pid_from_kernel(struct nl_sock
*sock
);
64 static int set_sock_property(struct nl_sock
*sock
);
65 static int nl_sock_transact(struct nl_sock
*sock
, const struct ofpbuf
*request
,
66 struct ofpbuf
**replyp
);
68 /* In the case DeviceIoControl failed and GetLastError returns with
69 * ERROR_NOT_FOUND means we lost communication with the kernel device.
70 * CloseHandle will fail because the handle in 'theory' does not exist.
71 * The only remaining option is to crash and allow the service to be restarted
72 * via service manager. This is the only way to close the handle from both
73 * userspace and kernel. */
75 lost_communication(DWORD last_err
)
77 if (last_err
== ERROR_NOT_FOUND
) {
78 ovs_abort(0, "lost communication with the kernel device");
83 /* Netlink sockets. */
88 OVERLAPPED overlapped
;
96 unsigned int rcvbuf
; /* Receive buffer size (SO_RCVBUF). */
99 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
100 * of iovecs on the stack. */
103 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
104 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
106 * Initialized by nl_sock_create(). */
109 static int nl_pool_alloc(int protocol
, struct nl_sock
**sockp
);
110 static void nl_pool_release(struct nl_sock
*);
112 /* Creates a new netlink socket for the given netlink 'protocol'
113 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
114 * new socket if successful, otherwise returns a positive errno value. */
116 nl_sock_create(int protocol
, struct nl_sock
**sockp
)
118 static struct ovsthread_once once
= OVSTHREAD_ONCE_INITIALIZER
;
119 struct nl_sock
*sock
;
121 struct sockaddr_nl local
, remote
;
123 socklen_t local_size
;
127 if (ovsthread_once_start(&once
)) {
128 int save_errno
= errno
;
131 max_iovs
= sysconf(_SC_UIO_MAXIOV
);
132 if (max_iovs
< _XOPEN_IOV_MAX
) {
133 if (max_iovs
== -1 && errno
) {
134 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno
));
136 max_iovs
= _XOPEN_IOV_MAX
;
137 } else if (max_iovs
> MAX_IOVS
) {
142 ovsthread_once_done(&once
);
146 sock
= xmalloc(sizeof *sock
);
149 sock
->overlapped
.hEvent
= NULL
;
150 sock
->handle
= CreateFile(OVS_DEVICE_NAME_USER
,
151 GENERIC_READ
| GENERIC_WRITE
,
152 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
154 FILE_FLAG_OVERLAPPED
, NULL
);
156 if (sock
->handle
== INVALID_HANDLE_VALUE
) {
157 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
161 memset(&sock
->overlapped
, 0, sizeof sock
->overlapped
);
162 sock
->overlapped
.hEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
163 if (sock
->overlapped
.hEvent
== NULL
) {
164 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
167 /* Initialize the type/ioctl to Generic */
168 sock
->read_ioctl
= OVS_IOCTL_READ
;
170 sock
->fd
= socket(AF_NETLINK
, SOCK_RAW
, protocol
);
172 VLOG_ERR("fcntl: %s", ovs_strerror(errno
));
177 sock
->protocol
= protocol
;
180 rcvbuf
= 1024 * 1024;
182 sock
->rcvbuf
= rcvbuf
;
183 retval
= get_sock_pid_from_kernel(sock
);
187 retval
= set_sock_property(sock
);
192 if (setsockopt(sock
->fd
, SOL_SOCKET
, SO_RCVBUFFORCE
,
193 &rcvbuf
, sizeof rcvbuf
)) {
194 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
195 * Warn only if the failure is therefore unexpected. */
196 if (errno
!= EPERM
) {
197 VLOG_WARN_RL(&rl
, "setting %d-byte socket receive buffer failed "
198 "(%s)", rcvbuf
, ovs_strerror(errno
));
202 retval
= get_socket_rcvbuf(sock
->fd
);
207 sock
->rcvbuf
= retval
;
210 /* Connect to kernel (pid 0) as remote address. */
211 memset(&remote
, 0, sizeof remote
);
212 remote
.nl_family
= AF_NETLINK
;
214 if (connect(sock
->fd
, (struct sockaddr
*) &remote
, sizeof remote
) < 0) {
215 VLOG_ERR("connect(0): %s", ovs_strerror(errno
));
219 /* Obtain pid assigned by kernel. */
220 local_size
= sizeof local
;
221 if (getsockname(sock
->fd
, (struct sockaddr
*) &local
, &local_size
) < 0) {
222 VLOG_ERR("getsockname: %s", ovs_strerror(errno
));
225 if (local_size
< sizeof local
|| local
.nl_family
!= AF_NETLINK
) {
226 VLOG_ERR("getsockname returned bad Netlink name");
230 sock
->pid
= local
.nl_pid
;
244 if (sock
->overlapped
.hEvent
) {
245 CloseHandle(sock
->overlapped
.hEvent
);
247 if (sock
->handle
!= INVALID_HANDLE_VALUE
) {
248 CloseHandle(sock
->handle
);
259 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
260 * sets '*sockp' to the new socket if successful, otherwise returns a positive
263 nl_sock_clone(const struct nl_sock
*src
, struct nl_sock
**sockp
)
265 return nl_sock_create(src
->protocol
, sockp
);
268 /* Destroys netlink socket 'sock'. */
270 nl_sock_destroy(struct nl_sock
*sock
)
274 if (sock
->overlapped
.hEvent
) {
275 CloseHandle(sock
->overlapped
.hEvent
);
277 CloseHandle(sock
->handle
);
286 /* Reads the pid for 'sock' generated in the kernel datapath. The function
287 * uses a separate IOCTL instead of a transaction semantic to avoid unnecessary
288 * message overhead. */
290 get_sock_pid_from_kernel(struct nl_sock
*sock
)
296 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_GET_PID
,
297 NULL
, 0, &pid
, sizeof(pid
),
299 lost_communication(GetLastError());
302 if (bytes
< sizeof(pid
)) {
312 /* Used for setting and managing socket properties in userspace and kernel.
313 * Currently two attributes are tracked - pid and protocol
314 * protocol - supplied by userspace based on the netlink family. Windows uses
315 * this property to set the value in kernel datapath.
316 * eg: (NETLINK_GENERIC/ NETLINK_NETFILTER)
317 * pid - generated by windows kernel and set in userspace. The property
319 * Also verify if Protocol and PID in Kernel reflects the values in userspace
322 set_sock_property(struct nl_sock
*sock
)
324 static const struct nl_policy ovs_socket_policy
[] = {
325 [OVS_NL_ATTR_SOCK_PROTO
] = { .type
= NL_A_BE32
, .optional
= true },
326 [OVS_NL_ATTR_SOCK_PID
] = { .type
= NL_A_BE32
, .optional
= true }
329 struct ofpbuf request
, *reply
;
330 struct ovs_header
*ovs_header
;
331 struct nlattr
*attrs
[ARRAY_SIZE(ovs_socket_policy
)];
335 ofpbuf_init(&request
, 0);
336 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
337 OVS_CTRL_CMD_SOCK_PROP
, OVS_WIN_CONTROL_VERSION
);
338 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
339 ovs_header
->dp_ifindex
= 0;
341 nl_msg_put_be32(&request
, OVS_NL_ATTR_SOCK_PROTO
, sock
->protocol
);
342 /* pid is already set as part of get_sock_pid_from_kernel()
343 * This is added to maintain consistency
345 nl_msg_put_be32(&request
, OVS_NL_ATTR_SOCK_PID
, sock
->pid
);
347 error
= nl_sock_transact(sock
, &request
, &reply
);
348 ofpbuf_uninit(&request
);
353 if (!nl_policy_parse(reply
,
354 NLMSG_HDRLEN
+ GENL_HDRLEN
+ sizeof *ovs_header
,
355 ovs_socket_policy
, attrs
,
356 ARRAY_SIZE(ovs_socket_policy
))) {
357 ofpbuf_delete(reply
);
360 /* Verify if the properties are setup properly */
361 if (attrs
[OVS_NL_ATTR_SOCK_PROTO
]) {
362 int protocol
= nl_attr_get_be32(attrs
[OVS_NL_ATTR_SOCK_PROTO
]);
363 if (protocol
!= sock
->protocol
) {
364 VLOG_ERR("Invalid protocol returned:%d expected:%d",
365 protocol
, sock
->protocol
);
370 if (attrs
[OVS_NL_ATTR_SOCK_PID
]) {
371 int pid
= nl_attr_get_be32(attrs
[OVS_NL_ATTR_SOCK_PID
]);
372 if (pid
!= sock
->pid
) {
373 VLOG_ERR("Invalid pid returned:%d expected:%d",
385 nl_sock_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
, bool join
)
387 struct ofpbuf request
;
388 uint64_t request_stub
[128];
389 struct ovs_header
*ovs_header
;
390 struct nlmsghdr
*nlmsg
;
393 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
395 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
396 OVS_CTRL_CMD_MC_SUBSCRIBE_REQ
,
397 OVS_WIN_CONTROL_VERSION
);
399 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
400 ovs_header
->dp_ifindex
= 0;
402 nl_msg_put_u32(&request
, OVS_NL_ATTR_MCAST_GRP
, multicast_group
);
403 nl_msg_put_u8(&request
, OVS_NL_ATTR_MCAST_JOIN
, join
? 1 : 0);
405 error
= nl_sock_send(sock
, &request
, true);
406 ofpbuf_uninit(&request
);
410 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
411 * successful, otherwise a positive errno value.
413 * A socket that is subscribed to a multicast group that receives asynchronous
414 * notifications must not be used for Netlink transactions or dumps, because
415 * transactions and dumps can cause notifications to be lost.
417 * Multicast group numbers are always positive.
419 * It is not an error to attempt to join a multicast group to which a socket
420 * already belongs. */
422 nl_sock_join_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
)
425 /* Set the socket type as a "multicast" socket */
426 sock
->read_ioctl
= OVS_IOCTL_READ_EVENT
;
427 int error
= nl_sock_mcgroup(sock
, multicast_group
, true);
429 sock
->read_ioctl
= OVS_IOCTL_READ
;
430 VLOG_WARN("could not join multicast group %u (%s)",
431 multicast_group
, ovs_strerror(error
));
435 if (setsockopt(sock
->fd
, SOL_NETLINK
, NETLINK_ADD_MEMBERSHIP
,
436 &multicast_group
, sizeof multicast_group
) < 0) {
437 VLOG_WARN("could not join multicast group %u (%s)",
438 multicast_group
, ovs_strerror(errno
));
445 /* When 'enable' is true, it tries to enable 'sock' to receive netlink
446 * notifications form all network namespaces that have an nsid assigned
447 * into the network namespace where the socket has been opened. The
448 * running kernel needs to provide support for that. When 'enable' is
449 * false, it will receive netlink notifications only from the network
450 * namespace where the socket has been opened.
452 * Returns 0 if successful, otherwise a positive errno. */
454 nl_sock_listen_all_nsid(struct nl_sock
*sock
, bool enable
)
457 int val
= enable
? 1 : 0;
460 if (setsockopt(sock
->fd
, SOL_NETLINK
, NETLINK_LISTEN_ALL_NSID
, &val
,
463 VLOG_INFO("netlink: could not %s listening to all nsid (%s)",
464 enable
? "enable" : "disable", ovs_strerror(error
));
474 nl_sock_subscribe_packet__(struct nl_sock
*sock
, bool subscribe
)
476 struct ofpbuf request
;
477 uint64_t request_stub
[128];
478 struct ovs_header
*ovs_header
;
479 struct nlmsghdr
*nlmsg
;
482 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
483 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
484 OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ
,
485 OVS_WIN_CONTROL_VERSION
);
487 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
488 ovs_header
->dp_ifindex
= 0;
489 nl_msg_put_u8(&request
, OVS_NL_ATTR_PACKET_SUBSCRIBE
, subscribe
? 1 : 0);
490 nl_msg_put_u32(&request
, OVS_NL_ATTR_PACKET_PID
, sock
->pid
);
492 error
= nl_sock_send(sock
, &request
, true);
493 ofpbuf_uninit(&request
);
498 nl_sock_subscribe_packets(struct nl_sock
*sock
)
502 if (sock
->read_ioctl
!= OVS_IOCTL_READ
) {
506 error
= nl_sock_subscribe_packet__(sock
, true);
508 VLOG_WARN("could not subscribe packets (%s)",
509 ovs_strerror(error
));
512 sock
->read_ioctl
= OVS_IOCTL_READ_PACKET
;
518 nl_sock_unsubscribe_packets(struct nl_sock
*sock
)
520 ovs_assert(sock
->read_ioctl
== OVS_IOCTL_READ_PACKET
);
522 int error
= nl_sock_subscribe_packet__(sock
, false);
524 VLOG_WARN("could not unsubscribe to packets (%s)",
525 ovs_strerror(error
));
529 sock
->read_ioctl
= OVS_IOCTL_READ
;
534 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
535 * successful, otherwise a positive errno value.
537 * Multicast group numbers are always positive.
539 * It is not an error to attempt to leave a multicast group to which a socket
542 * On success, reading from 'sock' will still return any messages that were
543 * received on 'multicast_group' before the group was left. */
545 nl_sock_leave_mcgroup(struct nl_sock
*sock
, unsigned int multicast_group
)
548 int error
= nl_sock_mcgroup(sock
, multicast_group
, false);
550 VLOG_WARN("could not leave multicast group %u (%s)",
551 multicast_group
, ovs_strerror(error
));
554 sock
->read_ioctl
= OVS_IOCTL_READ
;
556 if (setsockopt(sock
->fd
, SOL_NETLINK
, NETLINK_DROP_MEMBERSHIP
,
557 &multicast_group
, sizeof multicast_group
) < 0) {
558 VLOG_WARN("could not leave multicast group %u (%s)",
559 multicast_group
, ovs_strerror(errno
));
567 nl_sock_send__(struct nl_sock
*sock
, const struct ofpbuf
*msg
,
568 uint32_t nlmsg_seq
, bool wait
)
570 struct nlmsghdr
*nlmsg
= nl_msg_nlmsghdr(msg
);
573 nlmsg
->nlmsg_len
= msg
->size
;
574 nlmsg
->nlmsg_seq
= nlmsg_seq
;
575 nlmsg
->nlmsg_pid
= sock
->pid
;
581 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_WRITE
,
582 msg
->data
, msg
->size
, NULL
, 0,
584 lost_communication(GetLastError());
586 /* XXX: Map to a more appropriate error based on GetLastError(). */
588 VLOG_DBG_RL(&rl
, "fatal driver failure in write: %s",
589 ovs_lasterror_to_string());
594 retval
= send(sock
->fd
, msg
->data
, msg
->size
,
595 wait
? 0 : MSG_DONTWAIT
);
597 error
= retval
< 0 ? errno
: 0;
598 } while (error
== EINTR
);
599 log_nlmsg(__func__
, error
, msg
->data
, msg
->size
, sock
->protocol
);
601 COVERAGE_INC(netlink_sent
);
606 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
607 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
608 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
609 * sequence number, before the message is sent.
611 * Returns 0 if successful, otherwise a positive errno value. If
612 * 'wait' is true, then the send will wait until buffer space is ready;
613 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
615 nl_sock_send(struct nl_sock
*sock
, const struct ofpbuf
*msg
, bool wait
)
617 return nl_sock_send_seq(sock
, msg
, nl_sock_allocate_seq(sock
, 1), wait
);
620 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
621 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
622 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
623 * 'nlmsg_seq', before the message is sent.
625 * Returns 0 if successful, otherwise a positive errno value. If
626 * 'wait' is true, then the send will wait until buffer space is ready;
627 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
629 * This function is suitable for sending a reply to a request that was received
630 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
632 nl_sock_send_seq(struct nl_sock
*sock
, const struct ofpbuf
*msg
,
633 uint32_t nlmsg_seq
, bool wait
)
635 return nl_sock_send__(sock
, msg
, nlmsg_seq
, wait
);
639 nl_sock_recv__(struct nl_sock
*sock
, struct ofpbuf
*buf
, int *nsid
, bool wait
)
641 /* We can't accurately predict the size of the data to be received. The
642 * caller is supposed to have allocated enough space in 'buf' to handle the
643 * "typical" case. To handle exceptions, we make available enough space in
644 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
645 * figure since that's the maximum length of a Netlink attribute). */
646 struct nlmsghdr
*nlmsghdr
;
651 struct cmsghdr
*cmsg
;
656 ovs_assert(buf
->allocated
>= sizeof *nlmsghdr
);
659 iov
[0].iov_base
= buf
->base
;
660 iov
[0].iov_len
= buf
->allocated
;
661 iov
[1].iov_base
= tail
;
662 iov
[1].iov_len
= sizeof tail
;
664 memset(&msg
, 0, sizeof msg
);
667 msg
.msg_control
= msgctrl
;
668 msg
.msg_controllen
= sizeof msgctrl
;
670 /* Receive a Netlink message from the kernel.
672 * This works around a kernel bug in which the kernel returns an error code
673 * as if it were the number of bytes read. It doesn't actually modify
674 * anything in the receive buffer in that case, so we can initialize the
675 * Netlink header with an impossible message length and then, upon success,
676 * check whether it changed. */
677 nlmsghdr
= buf
->base
;
679 nlmsghdr
->nlmsg_len
= UINT32_MAX
;
682 if (!DeviceIoControl(sock
->handle
, sock
->read_ioctl
,
683 NULL
, 0, tail
, sizeof tail
, &bytes
, NULL
)) {
684 lost_communication(GetLastError());
685 VLOG_DBG_RL(&rl
, "fatal driver failure in transact: %s",
686 ovs_lasterror_to_string());
688 /* XXX: Map to a more appropriate error. */
696 if (retval
>= buf
->allocated
) {
697 ofpbuf_reinit(buf
, retval
);
698 nlmsghdr
= buf
->base
;
699 nlmsghdr
->nlmsg_len
= UINT32_MAX
;
701 memcpy(buf
->data
, tail
, retval
);
706 retval
= recvmsg(sock
->fd
, &msg
, wait
? 0 : MSG_DONTWAIT
);
708 error
= (retval
< 0 ? errno
709 : retval
== 0 ? ECONNRESET
/* not possible? */
710 : nlmsghdr
->nlmsg_len
!= UINT32_MAX
? 0
712 } while (error
== EINTR
);
714 if (error
== ENOBUFS
) {
715 /* Socket receive buffer overflow dropped one or more messages that
716 * the kernel tried to send to us. */
717 COVERAGE_INC(netlink_overflow
);
722 if (msg
.msg_flags
& MSG_TRUNC
) {
723 VLOG_ERR_RL(&rl
, "truncated message (longer than %"PRIuSIZE
" bytes)",
728 if (retval
< sizeof *nlmsghdr
729 || nlmsghdr
->nlmsg_len
< sizeof *nlmsghdr
730 || nlmsghdr
->nlmsg_len
> retval
) {
731 VLOG_ERR_RL(&rl
, "received invalid nlmsg (%"PRIuSIZE
" bytes < %"PRIuSIZE
")",
732 retval
, sizeof *nlmsghdr
);
736 buf
->size
= MIN(retval
, buf
->allocated
);
737 if (retval
> buf
->allocated
) {
738 COVERAGE_INC(netlink_recv_jumbo
);
739 ofpbuf_put(buf
, tail
, retval
- buf
->allocated
);
744 /* The network namespace id from which the message was sent comes
745 * as ancillary data. For older kernels, this data is either not
746 * available or it might be -1, so it falls back to local network
747 * namespace (no id). Latest kernels return a valid ID only if
748 * available or nothing. */
749 netnsid_set_local(nsid
);
751 cmsg
= CMSG_FIRSTHDR(&msg
);
752 while (cmsg
!= NULL
) {
753 if (cmsg
->cmsg_level
== SOL_NETLINK
754 && cmsg
->cmsg_type
== NETLINK_LISTEN_ALL_NSID
) {
755 ptr
= ALIGNED_CAST(int *, CMSG_DATA(cmsg
));
756 netnsid_set(nsid
, *ptr
);
758 if (cmsg
->cmsg_level
== SOL_SOCKET
759 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
760 /* This is unexpected and unwanted, close all fds */
763 nfds
= (cmsg
->cmsg_len
- CMSG_ALIGN(sizeof(struct cmsghdr
)))
765 ptr
= ALIGNED_CAST(int *, CMSG_DATA(cmsg
));
766 for (i
= 0; i
< nfds
; i
++) {
767 VLOG_ERR_RL(&rl
, "closing unexpected received fd (%d).",
773 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
778 log_nlmsg(__func__
, 0, buf
->data
, buf
->size
, sock
->protocol
);
779 COVERAGE_INC(netlink_received
);
784 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
785 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
786 * EAGAIN if the 'sock' receive buffer is empty. If 'nsid' is provided, the
787 * network namespace id from which the message was sent will be provided.
789 * The caller must have initialized 'buf' with an allocation of at least
790 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
791 * space for a "typical" message.
793 * On success, returns 0 and replaces 'buf''s previous content by the received
794 * message. This function expands 'buf''s allocated memory, as necessary, to
795 * hold the actual size of the received message.
797 * On failure, returns a positive errno value and clears 'buf' to zero length.
798 * 'buf' retains its previous memory allocation.
800 * Regardless of success or failure, this function resets 'buf''s headroom to
803 nl_sock_recv(struct nl_sock
*sock
, struct ofpbuf
*buf
, int *nsid
, bool wait
)
805 return nl_sock_recv__(sock
, buf
, nsid
, wait
);
809 nl_sock_record_errors__(struct nl_transaction
**transactions
, size_t n
,
814 for (i
= 0; i
< n
; i
++) {
815 struct nl_transaction
*txn
= transactions
[i
];
819 ofpbuf_clear(txn
->reply
);
825 nl_sock_transact_multiple__(struct nl_sock
*sock
,
826 struct nl_transaction
**transactions
, size_t n
,
829 uint64_t tmp_reply_stub
[1024 / 8];
830 struct nl_transaction tmp_txn
;
831 struct ofpbuf tmp_reply
;
834 struct iovec iovs
[MAX_IOVS
];
839 base_seq
= nl_sock_allocate_seq(sock
, n
);
841 for (i
= 0; i
< n
; i
++) {
842 struct nl_transaction
*txn
= transactions
[i
];
843 struct nlmsghdr
*nlmsg
= nl_msg_nlmsghdr(txn
->request
);
845 nlmsg
->nlmsg_len
= txn
->request
->size
;
846 nlmsg
->nlmsg_seq
= base_seq
+ i
;
847 nlmsg
->nlmsg_pid
= sock
->pid
;
849 iovs
[i
].iov_base
= txn
->request
->data
;
850 iovs
[i
].iov_len
= txn
->request
->size
;
854 memset(&msg
, 0, sizeof msg
);
858 error
= sendmsg(sock
->fd
, &msg
, 0) < 0 ? errno
: 0;
859 } while (error
== EINTR
);
861 for (i
= 0; i
< n
; i
++) {
862 struct nl_transaction
*txn
= transactions
[i
];
864 log_nlmsg(__func__
, error
, txn
->request
->data
,
865 txn
->request
->size
, sock
->protocol
);
868 COVERAGE_ADD(netlink_sent
, n
);
875 ofpbuf_use_stub(&tmp_reply
, tmp_reply_stub
, sizeof tmp_reply_stub
);
876 tmp_txn
.request
= NULL
;
877 tmp_txn
.reply
= &tmp_reply
;
880 struct nl_transaction
*buf_txn
, *txn
;
883 /* Find a transaction whose buffer we can use for receiving a reply.
884 * If no such transaction is left, use tmp_txn. */
886 for (i
= 0; i
< n
; i
++) {
887 if (transactions
[i
]->reply
) {
888 buf_txn
= transactions
[i
];
893 /* Receive a reply. */
894 error
= nl_sock_recv__(sock
, buf_txn
->reply
, NULL
, false);
896 if (error
== EAGAIN
) {
897 nl_sock_record_errors__(transactions
, n
, 0);
904 /* Match the reply up with a transaction. */
905 seq
= nl_msg_nlmsghdr(buf_txn
->reply
)->nlmsg_seq
;
906 if (seq
< base_seq
|| seq
>= base_seq
+ n
) {
907 VLOG_DBG_RL(&rl
, "ignoring unexpected seq %#"PRIx32
, seq
);
911 txn
= transactions
[i
];
913 /* Fill in the results for 'txn'. */
914 if (nl_msg_nlmsgerr(buf_txn
->reply
, &txn
->error
)) {
916 ofpbuf_clear(txn
->reply
);
919 VLOG_DBG_RL(&rl
, "received NAK error=%d (%s)",
920 error
, ovs_strerror(txn
->error
));
924 if (txn
->reply
&& txn
!= buf_txn
) {
926 struct ofpbuf
*reply
= buf_txn
->reply
;
927 buf_txn
->reply
= txn
->reply
;
932 /* Fill in the results for transactions before 'txn'. (We have to do
933 * this after the results for 'txn' itself because of the buffer swap
935 nl_sock_record_errors__(transactions
, i
, 0);
939 transactions
+= i
+ 1;
943 ofpbuf_uninit(&tmp_reply
);
946 uint8_t reply_buf
[65536];
947 for (i
= 0; i
< n
; i
++) {
950 struct nl_transaction
*txn
= transactions
[i
];
951 struct nlmsghdr
*request_nlmsg
, *reply_nlmsg
;
953 ret
= DeviceIoControl(sock
->handle
, OVS_IOCTL_TRANSACT
,
956 reply_buf
, sizeof reply_buf
,
959 if (ret
&& reply_len
== 0) {
961 * The current transaction did not produce any data to read and that
962 * is not an error as such. Continue with the remainder of the
967 ofpbuf_clear(txn
->reply
);
970 /* XXX: Map to a more appropriate error. */
971 lost_communication(GetLastError());
973 VLOG_DBG_RL(&rl
, "fatal driver failure: %s",
974 ovs_lasterror_to_string());
978 if (reply_len
!= 0) {
979 request_nlmsg
= nl_msg_nlmsghdr(txn
->request
);
981 if (reply_len
< sizeof *reply_nlmsg
) {
982 nl_sock_record_errors__(transactions
, n
, 0);
983 VLOG_DBG_RL(&rl
, "insufficient length of reply %#"PRIu32
984 " for seq: %#"PRIx32
, reply_len
, request_nlmsg
->nlmsg_seq
);
988 /* Validate the sequence number in the reply. */
989 reply_nlmsg
= (struct nlmsghdr
*)reply_buf
;
991 if (request_nlmsg
->nlmsg_seq
!= reply_nlmsg
->nlmsg_seq
) {
992 ovs_assert(request_nlmsg
->nlmsg_seq
== reply_nlmsg
->nlmsg_seq
);
993 VLOG_DBG_RL(&rl
, "mismatched seq request %#"PRIx32
994 ", reply %#"PRIx32
, request_nlmsg
->nlmsg_seq
,
995 reply_nlmsg
->nlmsg_seq
);
999 /* Handle errors embedded within the netlink message. */
1000 ofpbuf_use_stub(&tmp_reply
, reply_buf
, sizeof reply_buf
);
1001 tmp_reply
.size
= sizeof reply_buf
;
1002 if (nl_msg_nlmsgerr(&tmp_reply
, &txn
->error
)) {
1004 ofpbuf_clear(txn
->reply
);
1007 VLOG_DBG_RL(&rl
, "received NAK error=%d (%s)",
1008 error
, ovs_strerror(txn
->error
));
1013 /* Copy the reply to the buffer specified by the caller. */
1014 if (reply_len
> txn
->reply
->allocated
) {
1015 ofpbuf_reinit(txn
->reply
, reply_len
);
1017 memcpy(txn
->reply
->data
, reply_buf
, reply_len
);
1018 txn
->reply
->size
= reply_len
;
1021 ofpbuf_uninit(&tmp_reply
);
1024 /* Count the number of successful transactions. */
1030 COVERAGE_ADD(netlink_sent
, n
);
1038 nl_sock_transact_multiple(struct nl_sock
*sock
,
1039 struct nl_transaction
**transactions
, size_t n
)
1041 int max_batch_count
;
1048 /* In theory, every request could have a 64 kB reply. But the default and
1049 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
1050 * be a bit below 128 kB, so that would only allow a single message in a
1051 * "batch". So we assume that replies average (at most) 4 kB, which allows
1052 * a good deal of batching.
1054 * In practice, most of the requests that we batch either have no reply at
1055 * all or a brief reply. */
1056 max_batch_count
= MAX(sock
->rcvbuf
/ 4096, 1);
1057 max_batch_count
= MIN(max_batch_count
, max_iovs
);
1060 size_t count
, bytes
;
1063 /* Batch up to 'max_batch_count' transactions. But cap it at about a
1064 * page of requests total because big skbuffs are expensive to
1065 * allocate in the kernel. */
1066 #if defined(PAGESIZE)
1067 enum { MAX_BATCH_BYTES
= MAX(1, PAGESIZE
- 512) };
1069 enum { MAX_BATCH_BYTES
= 4096 - 512 };
1071 bytes
= transactions
[0]->request
->size
;
1072 for (count
= 1; count
< n
&& count
< max_batch_count
; count
++) {
1073 if (bytes
+ transactions
[count
]->request
->size
> MAX_BATCH_BYTES
) {
1076 bytes
+= transactions
[count
]->request
->size
;
1079 error
= nl_sock_transact_multiple__(sock
, transactions
, count
, &done
);
1080 transactions
+= done
;
1083 if (error
== ENOBUFS
) {
1084 VLOG_DBG_RL(&rl
, "receive buffer overflow, resending request");
1086 VLOG_ERR_RL(&rl
, "transaction error (%s)", ovs_strerror(error
));
1087 nl_sock_record_errors__(transactions
, n
, error
);
1088 if (error
!= EAGAIN
) {
1089 /* A fatal error has occurred. Abort the rest of
1098 nl_sock_transact(struct nl_sock
*sock
, const struct ofpbuf
*request
,
1099 struct ofpbuf
**replyp
)
1101 struct nl_transaction
*transactionp
;
1102 struct nl_transaction transaction
;
1104 transaction
.request
= CONST_CAST(struct ofpbuf
*, request
);
1105 transaction
.reply
= replyp
? ofpbuf_new(1024) : NULL
;
1106 transactionp
= &transaction
;
1108 nl_sock_transact_multiple(sock
, &transactionp
, 1);
1111 if (transaction
.error
) {
1112 ofpbuf_delete(transaction
.reply
);
1115 *replyp
= transaction
.reply
;
1119 return transaction
.error
;
1122 /* Drain all the messages currently in 'sock''s receive queue. */
1124 nl_sock_drain(struct nl_sock
*sock
)
1129 return drain_rcvbuf(sock
->fd
);
1133 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
1134 * Netlink socket created with the given 'protocol', and initializes 'dump' to
1135 * reflect the state of the operation.
1137 * 'request' must contain a Netlink message. Before sending the message,
1138 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
1139 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
1142 * The design of this Netlink socket library ensures that the dump is reliable.
1144 * This function provides no status indication. nl_dump_done() provides an
1145 * error status for the entire dump operation.
1147 * The caller must eventually destroy 'request'.
1150 nl_dump_start(struct nl_dump
*dump
, int protocol
, const struct ofpbuf
*request
)
1152 nl_msg_nlmsghdr(request
)->nlmsg_flags
|= NLM_F_DUMP
| NLM_F_ACK
;
1154 ovs_mutex_init(&dump
->mutex
);
1155 ovs_mutex_lock(&dump
->mutex
);
1156 dump
->status
= nl_pool_alloc(protocol
, &dump
->sock
);
1157 if (!dump
->status
) {
1158 dump
->status
= nl_sock_send__(dump
->sock
, request
,
1159 nl_sock_allocate_seq(dump
->sock
, 1),
1162 dump
->nl_seq
= nl_msg_nlmsghdr(request
)->nlmsg_seq
;
1163 ovs_mutex_unlock(&dump
->mutex
);
1167 nl_dump_refill(struct nl_dump
*dump
, struct ofpbuf
*buffer
)
1168 OVS_REQUIRES(dump
->mutex
)
1170 struct nlmsghdr
*nlmsghdr
;
1173 while (!buffer
->size
) {
1174 error
= nl_sock_recv__(dump
->sock
, buffer
, NULL
, false);
1176 /* The kernel never blocks providing the results of a dump, so
1177 * error == EAGAIN means that we've read the whole thing, and
1178 * therefore transform it into EOF. (The kernel always provides
1179 * NLMSG_DONE as a sentinel. Some other thread must have received
1180 * that already but not yet signaled it in 'status'.)
1182 * Any other error is just an error. */
1183 return error
== EAGAIN
? EOF
: error
;
1186 nlmsghdr
= nl_msg_nlmsghdr(buffer
);
1187 if (dump
->nl_seq
!= nlmsghdr
->nlmsg_seq
) {
1188 VLOG_DBG_RL(&rl
, "ignoring seq %#"PRIx32
" != expected %#"PRIx32
,
1189 nlmsghdr
->nlmsg_seq
, dump
->nl_seq
);
1190 ofpbuf_clear(buffer
);
1194 if (nl_msg_nlmsgerr(buffer
, &error
) && error
) {
1195 VLOG_INFO_RL(&rl
, "netlink dump request error (%s)",
1196 ovs_strerror(error
));
1197 ofpbuf_clear(buffer
);
1205 nl_dump_next__(struct ofpbuf
*reply
, struct ofpbuf
*buffer
)
1207 struct nlmsghdr
*nlmsghdr
= nl_msg_next(buffer
, reply
);
1209 VLOG_WARN_RL(&rl
, "netlink dump contains message fragment");
1211 } else if (nlmsghdr
->nlmsg_type
== NLMSG_DONE
) {
1218 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1219 * have been initialized with nl_dump_start(), and 'buffer' must have been
1220 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1222 * If successful, returns true and points 'reply->data' and
1223 * 'reply->size' to the message that was retrieved. The caller must not
1224 * modify 'reply' (because it points within 'buffer', which will be used by
1225 * future calls to this function).
1227 * On failure, returns false and sets 'reply->data' to NULL and
1228 * 'reply->size' to 0. Failure might indicate an actual error or merely
1229 * the end of replies. An error status for the entire dump operation is
1230 * provided when it is completed by calling nl_dump_done().
1232 * Multiple threads may call this function, passing the same nl_dump, however
1233 * each must provide independent buffers. This function may cache multiple
1234 * replies in the buffer, and these will be processed before more replies are
1235 * fetched. When this function returns false, other threads may continue to
1236 * process replies in their buffers, but they will not fetch more replies.
1239 nl_dump_next(struct nl_dump
*dump
, struct ofpbuf
*reply
, struct ofpbuf
*buffer
)
1243 /* If the buffer is empty, refill it.
1245 * If the buffer is not empty, we don't check the dump's status.
1246 * Otherwise, we could end up skipping some of the dump results if thread A
1247 * hits EOF while thread B is in the midst of processing a batch. */
1248 if (!buffer
->size
) {
1249 ovs_mutex_lock(&dump
->mutex
);
1250 if (!dump
->status
) {
1251 /* Take the mutex here to avoid an in-kernel race. If two threads
1252 * try to read from a Netlink dump socket at once, then the socket
1253 * error can be set to EINVAL, which will be encountered on the
1254 * next recv on that socket, which could be anywhere due to the way
1255 * that we pool Netlink sockets. Serializing the recv calls avoids
1257 dump
->status
= nl_dump_refill(dump
, buffer
);
1259 retval
= dump
->status
;
1260 ovs_mutex_unlock(&dump
->mutex
);
1263 /* Fetch the next message from the buffer. */
1265 retval
= nl_dump_next__(reply
, buffer
);
1267 /* Record 'retval' as the dump status, but don't overwrite an error
1269 ovs_mutex_lock(&dump
->mutex
);
1270 if (dump
->status
<= 0) {
1271 dump
->status
= retval
;
1273 ovs_mutex_unlock(&dump
->mutex
);
1284 /* Completes Netlink dump operation 'dump', which must have been initialized
1285 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1286 * otherwise a positive errno value describing the problem. */
1288 nl_dump_done(struct nl_dump
*dump
)
1292 ovs_mutex_lock(&dump
->mutex
);
1293 status
= dump
->status
;
1294 ovs_mutex_unlock(&dump
->mutex
);
1296 /* Drain any remaining messages that the client didn't read. Otherwise the
1297 * kernel will continue to queue them up and waste buffer space.
1299 * XXX We could just destroy and discard the socket in this case. */
1301 uint64_t tmp_reply_stub
[NL_DUMP_BUFSIZE
/ 8];
1302 struct ofpbuf reply
, buf
;
1304 ofpbuf_use_stub(&buf
, tmp_reply_stub
, sizeof tmp_reply_stub
);
1305 while (nl_dump_next(dump
, &reply
, &buf
)) {
1306 /* Nothing to do. */
1308 ofpbuf_uninit(&buf
);
1310 ovs_mutex_lock(&dump
->mutex
);
1311 status
= dump
->status
;
1312 ovs_mutex_unlock(&dump
->mutex
);
1316 nl_pool_release(dump
->sock
);
1317 ovs_mutex_destroy(&dump
->mutex
);
1319 return status
== EOF
? 0 : status
;
1323 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1324 * an event or a packet is ready to be read. Once the I/O is completed
1325 * the overlapped structure event associated with the pending I/O will be set
1328 pend_io_request(struct nl_sock
*sock
)
1330 struct ofpbuf request
;
1331 uint64_t request_stub
[128];
1332 struct ovs_header
*ovs_header
;
1333 struct nlmsghdr
*nlmsg
;
1338 OVERLAPPED
*overlapped
= CONST_CAST(OVERLAPPED
*, &sock
->overlapped
);
1339 uint16_t cmd
= OVS_CTRL_CMD_WIN_PEND_PACKET_REQ
;
1341 ovs_assert(sock
->read_ioctl
== OVS_IOCTL_READ_PACKET
||
1342 sock
->read_ioctl
== OVS_IOCTL_READ_EVENT
);
1343 if (sock
->read_ioctl
== OVS_IOCTL_READ_EVENT
) {
1344 cmd
= OVS_CTRL_CMD_WIN_PEND_REQ
;
1347 int ovs_msg_size
= sizeof (struct nlmsghdr
) + sizeof (struct genlmsghdr
) +
1348 sizeof (struct ovs_header
);
1350 ofpbuf_use_stub(&request
, request_stub
, sizeof request_stub
);
1352 seq
= nl_sock_allocate_seq(sock
, 1);
1353 nl_msg_put_genlmsghdr(&request
, 0, OVS_WIN_NL_CTRL_FAMILY_ID
, 0,
1354 cmd
, OVS_WIN_CONTROL_VERSION
);
1355 nlmsg
= nl_msg_nlmsghdr(&request
);
1356 nlmsg
->nlmsg_seq
= seq
;
1357 nlmsg
->nlmsg_pid
= sock
->pid
;
1359 ovs_header
= ofpbuf_put_uninit(&request
, sizeof *ovs_header
);
1360 ovs_header
->dp_ifindex
= 0;
1361 nlmsg
->nlmsg_len
= request
.size
;
1363 if (!DeviceIoControl(sock
->handle
, OVS_IOCTL_WRITE
,
1364 request
.data
, request
.size
,
1365 NULL
, 0, &bytes
, overlapped
)) {
1366 error
= GetLastError();
1367 /* Check if the I/O got pended */
1368 if (error
!= ERROR_IO_INCOMPLETE
&& error
!= ERROR_IO_PENDING
) {
1369 lost_communication(error
);
1370 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error
));
1378 ofpbuf_uninit(&request
);
1383 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1384 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'.
1385 * On Windows, 'sock' is not treated as const, and may be modified. */
1387 nl_sock_wait(const struct nl_sock
*sock
, short int events
)
1390 if (sock
->overlapped
.Internal
!= STATUS_PENDING
) {
1391 int ret
= pend_io_request(CONST_CAST(struct nl_sock
*, sock
));
1393 poll_wevent_wait(sock
->overlapped
.hEvent
);
1395 poll_immediate_wake();
1398 poll_wevent_wait(sock
->overlapped
.hEvent
);
1401 poll_fd_wait(sock
->fd
, events
);
1406 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1407 * that can't use nl_sock_wait().
1409 * It's a little tricky to use the returned fd correctly, because nl_sock does
1410 * "copy on write" to allow a single nl_sock to be used for notifications,
1411 * transactions, and dumps. If 'sock' is used only for notifications and
1412 * transactions (and never for dump) then the usage is safe. */
1414 nl_sock_fd(const struct nl_sock
*sock
)
1420 /* Returns the PID associated with this socket. */
1422 nl_sock_pid(const struct nl_sock
*sock
)
1427 /* Miscellaneous. */
1429 struct genl_family
{
1430 struct hmap_node hmap_node
;
1435 static struct hmap genl_families
= HMAP_INITIALIZER(&genl_families
);
1437 static const struct nl_policy family_policy
[CTRL_ATTR_MAX
+ 1] = {
1438 [CTRL_ATTR_FAMILY_ID
] = {.type
= NL_A_U16
},
1439 [CTRL_ATTR_MCAST_GROUPS
] = {.type
= NL_A_NESTED
, .optional
= true},
1442 static struct genl_family
*
1443 find_genl_family_by_id(uint16_t id
)
1445 struct genl_family
*family
;
1447 HMAP_FOR_EACH_IN_BUCKET (family
, hmap_node
, hash_int(id
, 0),
1449 if (family
->id
== id
) {
1457 define_genl_family(uint16_t id
, const char *name
)
1459 struct genl_family
*family
= find_genl_family_by_id(id
);
1462 if (!strcmp(family
->name
, name
)) {
1467 family
= xmalloc(sizeof *family
);
1469 hmap_insert(&genl_families
, &family
->hmap_node
, hash_int(id
, 0));
1471 family
->name
= xstrdup(name
);
1475 genl_family_to_name(uint16_t id
)
1477 if (id
== GENL_ID_CTRL
) {
1480 struct genl_family
*family
= find_genl_family_by_id(id
);
1481 return family
? family
->name
: "unknown";
1487 do_lookup_genl_family(const char *name
, struct nlattr
**attrs
,
1488 struct ofpbuf
**replyp
)
1490 struct nl_sock
*sock
;
1491 struct ofpbuf request
, *reply
;
1495 error
= nl_sock_create(NETLINK_GENERIC
, &sock
);
1500 ofpbuf_init(&request
, 0);
1501 nl_msg_put_genlmsghdr(&request
, 0, GENL_ID_CTRL
, NLM_F_REQUEST
,
1502 CTRL_CMD_GETFAMILY
, 1);
1503 nl_msg_put_string(&request
, CTRL_ATTR_FAMILY_NAME
, name
);
1504 error
= nl_sock_transact(sock
, &request
, &reply
);
1505 ofpbuf_uninit(&request
);
1507 nl_sock_destroy(sock
);
1511 if (!nl_policy_parse(reply
, NLMSG_HDRLEN
+ GENL_HDRLEN
,
1512 family_policy
, attrs
, ARRAY_SIZE(family_policy
))
1513 || nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]) == 0) {
1514 nl_sock_destroy(sock
);
1515 ofpbuf_delete(reply
);
1519 nl_sock_destroy(sock
);
1525 do_lookup_genl_family(const char *name
, struct nlattr
**attrs
,
1526 struct ofpbuf
**replyp
)
1528 struct nlmsghdr
*nlmsg
;
1529 struct ofpbuf
*reply
;
1532 const char *family_name
;
1533 uint32_t family_version
;
1534 uint32_t family_attrmax
;
1535 uint32_t mcgrp_id
= OVS_WIN_NL_INVALID_MCGRP_ID
;
1536 const char *mcgrp_name
= NULL
;
1539 reply
= ofpbuf_new(1024);
1541 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1542 if (!strcmp(name
, OVS_WIN_CONTROL_FAMILY
)) {
1543 family_id
= OVS_WIN_NL_CTRL_FAMILY_ID
;
1544 family_name
= OVS_WIN_CONTROL_FAMILY
;
1545 family_version
= OVS_WIN_CONTROL_VERSION
;
1546 family_attrmax
= OVS_WIN_CONTROL_ATTR_MAX
;
1547 } else if (!strcmp(name
, OVS_DATAPATH_FAMILY
)) {
1548 family_id
= OVS_WIN_NL_DATAPATH_FAMILY_ID
;
1549 family_name
= OVS_DATAPATH_FAMILY
;
1550 family_version
= OVS_DATAPATH_VERSION
;
1551 family_attrmax
= OVS_DP_ATTR_MAX
;
1552 } else if (!strcmp(name
, OVS_PACKET_FAMILY
)) {
1553 family_id
= OVS_WIN_NL_PACKET_FAMILY_ID
;
1554 family_name
= OVS_PACKET_FAMILY
;
1555 family_version
= OVS_PACKET_VERSION
;
1556 family_attrmax
= OVS_PACKET_ATTR_MAX
;
1557 } else if (!strcmp(name
, OVS_VPORT_FAMILY
)) {
1558 family_id
= OVS_WIN_NL_VPORT_FAMILY_ID
;
1559 family_name
= OVS_VPORT_FAMILY
;
1560 family_version
= OVS_VPORT_VERSION
;
1561 family_attrmax
= OVS_VPORT_ATTR_MAX
;
1562 mcgrp_id
= OVS_WIN_NL_VPORT_MCGRP_ID
;
1563 mcgrp_name
= OVS_VPORT_MCGROUP
;
1564 } else if (!strcmp(name
, OVS_FLOW_FAMILY
)) {
1565 family_id
= OVS_WIN_NL_FLOW_FAMILY_ID
;
1566 family_name
= OVS_FLOW_FAMILY
;
1567 family_version
= OVS_FLOW_VERSION
;
1568 family_attrmax
= OVS_FLOW_ATTR_MAX
;
1569 } else if (!strcmp(name
, OVS_WIN_NETDEV_FAMILY
)) {
1570 family_id
= OVS_WIN_NL_NETDEV_FAMILY_ID
;
1571 family_name
= OVS_WIN_NETDEV_FAMILY
;
1572 family_version
= OVS_WIN_NETDEV_VERSION
;
1573 family_attrmax
= OVS_WIN_NETDEV_ATTR_MAX
;
1574 } else if (!strcmp(name
, OVS_CT_LIMIT_FAMILY
)) {
1575 family_id
= OVS_WIN_NL_CTLIMIT_FAMILY_ID
;
1576 family_name
= OVS_CT_LIMIT_FAMILY
;
1577 family_version
= OVS_CT_LIMIT_VERSION
;
1578 family_attrmax
= OVS_CT_LIMIT_ATTR_MAX
;
1580 ofpbuf_delete(reply
);
1584 nl_msg_put_genlmsghdr(reply
, 0, GENL_ID_CTRL
, 0,
1585 CTRL_CMD_NEWFAMILY
, family_version
);
1586 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1587 * callers do not seem to need them. */
1588 nl_msg_put_u16(reply
, CTRL_ATTR_FAMILY_ID
, family_id
);
1589 nl_msg_put_string(reply
, CTRL_ATTR_FAMILY_NAME
, family_name
);
1590 nl_msg_put_u32(reply
, CTRL_ATTR_VERSION
, family_version
);
1591 nl_msg_put_u32(reply
, CTRL_ATTR_MAXATTR
, family_attrmax
);
1593 if (mcgrp_id
!= OVS_WIN_NL_INVALID_MCGRP_ID
) {
1594 size_t mcgrp_ofs1
= nl_msg_start_nested(reply
, CTRL_ATTR_MCAST_GROUPS
);
1595 size_t mcgrp_ofs2
= nl_msg_start_nested(reply
,
1596 OVS_WIN_NL_VPORT_MCGRP_ID
- OVS_WIN_NL_MCGRP_START_ID
);
1597 nl_msg_put_u32(reply
, CTRL_ATTR_MCAST_GRP_ID
, mcgrp_id
);
1598 ovs_assert(mcgrp_name
!= NULL
);
1599 nl_msg_put_string(reply
, CTRL_ATTR_MCAST_GRP_NAME
, mcgrp_name
);
1600 nl_msg_end_nested(reply
, mcgrp_ofs2
);
1601 nl_msg_end_nested(reply
, mcgrp_ofs1
);
1604 /* Set the total length of the netlink message. */
1605 nlmsg
= nl_msg_nlmsghdr(reply
);
1606 nlmsg
->nlmsg_len
= reply
->size
;
1608 if (!nl_policy_parse(reply
, NLMSG_HDRLEN
+ GENL_HDRLEN
,
1609 family_policy
, attrs
, ARRAY_SIZE(family_policy
))
1610 || nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]) == 0) {
1611 ofpbuf_delete(reply
);
1620 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1621 * When successful, writes its result to 'multicast_group' and returns 0.
1622 * Otherwise, clears 'multicast_group' and returns a positive error code.
1625 nl_lookup_genl_mcgroup(const char *family_name
, const char *group_name
,
1626 unsigned int *multicast_group
)
1628 struct nlattr
*family_attrs
[ARRAY_SIZE(family_policy
)];
1629 const struct nlattr
*mc
;
1630 struct ofpbuf
*reply
;
1634 *multicast_group
= 0;
1635 error
= do_lookup_genl_family(family_name
, family_attrs
, &reply
);
1640 if (!family_attrs
[CTRL_ATTR_MCAST_GROUPS
]) {
1645 NL_NESTED_FOR_EACH (mc
, left
, family_attrs
[CTRL_ATTR_MCAST_GROUPS
]) {
1646 static const struct nl_policy mc_policy
[] = {
1647 [CTRL_ATTR_MCAST_GRP_ID
] = {.type
= NL_A_U32
},
1648 [CTRL_ATTR_MCAST_GRP_NAME
] = {.type
= NL_A_STRING
},
1651 struct nlattr
*mc_attrs
[ARRAY_SIZE(mc_policy
)];
1652 const char *mc_name
;
1654 if (!nl_parse_nested(mc
, mc_policy
, mc_attrs
, ARRAY_SIZE(mc_policy
))) {
1659 mc_name
= nl_attr_get_string(mc_attrs
[CTRL_ATTR_MCAST_GRP_NAME
]);
1660 if (!strcmp(group_name
, mc_name
)) {
1662 nl_attr_get_u32(mc_attrs
[CTRL_ATTR_MCAST_GRP_ID
]);
1670 ofpbuf_delete(reply
);
1674 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1675 * number and stores it in '*number'. If successful, returns 0 and the caller
1676 * may use '*number' as the family number. On failure, returns a positive
1677 * errno value and '*number' caches the errno value. */
1679 nl_lookup_genl_family(const char *name
, int *number
)
1682 struct nlattr
*attrs
[ARRAY_SIZE(family_policy
)];
1683 struct ofpbuf
*reply
;
1686 error
= do_lookup_genl_family(name
, attrs
, &reply
);
1688 *number
= nl_attr_get_u16(attrs
[CTRL_ATTR_FAMILY_ID
]);
1689 define_genl_family(*number
, name
);
1693 ofpbuf_delete(reply
);
1695 ovs_assert(*number
!= 0);
1697 return *number
> 0 ? 0 : -*number
;
1701 struct nl_sock
*socks
[16];
1705 static struct ovs_mutex pool_mutex
= OVS_MUTEX_INITIALIZER
;
1706 static struct nl_pool pools
[MAX_LINKS
] OVS_GUARDED_BY(pool_mutex
);
1709 nl_pool_alloc(int protocol
, struct nl_sock
**sockp
)
1711 struct nl_sock
*sock
= NULL
;
1712 struct nl_pool
*pool
;
1714 ovs_assert(protocol
>= 0 && protocol
< ARRAY_SIZE(pools
));
1716 ovs_mutex_lock(&pool_mutex
);
1717 pool
= &pools
[protocol
];
1719 sock
= pool
->socks
[--pool
->n
];
1721 ovs_mutex_unlock(&pool_mutex
);
1727 return nl_sock_create(protocol
, sockp
);
1732 nl_pool_release(struct nl_sock
*sock
)
1735 struct nl_pool
*pool
= &pools
[sock
->protocol
];
1737 ovs_mutex_lock(&pool_mutex
);
1738 if (pool
->n
< ARRAY_SIZE(pool
->socks
)) {
1739 pool
->socks
[pool
->n
++] = sock
;
1742 ovs_mutex_unlock(&pool_mutex
);
1744 nl_sock_destroy(sock
);
1748 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1749 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1750 * successful, returns 0. On failure, returns a positive errno value.
1752 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1753 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1754 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1755 * reply, if any, is discarded.
1757 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1758 * match msg->size, nlmsg_pid will be set to the pid of the socket used
1759 * for sending the request, and nlmsg_seq will be initialized.
1761 * The caller is responsible for destroying 'request'.
1763 * Bare Netlink is an unreliable transport protocol. This function layers
1764 * reliable delivery and reply semantics on top of bare Netlink.
1766 * In Netlink, sending a request to the kernel is reliable enough, because the
1767 * kernel will tell us if the message cannot be queued (and we will in that
1768 * case put it on the transmit queue and wait until it can be delivered).
1770 * Receiving the reply is the real problem: if the socket buffer is full when
1771 * the kernel tries to send the reply, the reply will be dropped. However, the
1772 * kernel sets a flag that a reply has been dropped. The next call to recv
1773 * then returns ENOBUFS. We can then re-send the request.
1777 * 1. Netlink depends on sequence numbers to match up requests and
1778 * replies. The sender of a request supplies a sequence number, and
1779 * the reply echos back that sequence number.
1781 * This is fine, but (1) some kernel netlink implementations are
1782 * broken, in that they fail to echo sequence numbers and (2) this
1783 * function will drop packets with non-matching sequence numbers, so
1784 * that only a single request can be usefully transacted at a time.
1786 * 2. Resending the request causes it to be re-executed, so the request
1787 * needs to be idempotent.
1790 nl_transact(int protocol
, const struct ofpbuf
*request
,
1791 struct ofpbuf
**replyp
)
1793 struct nl_sock
*sock
;
1796 error
= nl_pool_alloc(protocol
, &sock
);
1804 error
= nl_sock_transact(sock
, request
, replyp
);
1806 nl_pool_release(sock
);
1810 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1811 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1812 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1813 * the 'error' member of each transaction with 0 if it was successful,
1814 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1815 * be filled with the reply if the message receives a detailed reply. In other
1816 * cases, i.e. where the request failed or had no reply beyond an indication of
1817 * success, 'reply' will be cleared if it is nonnull.
1819 * The caller is responsible for destroying each request and reply, and the
1820 * transactions array itself.
1822 * Before sending each message, this function will finalize nlmsg_len in each
1823 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1824 * used for the transaction, and initialize nlmsg_seq.
1826 * Bare Netlink is an unreliable transport protocol. This function layers
1827 * reliable delivery and reply semantics on top of bare Netlink. See
1828 * nl_transact() for some caveats.
1831 nl_transact_multiple(int protocol
,
1832 struct nl_transaction
**transactions
, size_t n
)
1834 struct nl_sock
*sock
;
1837 error
= nl_pool_alloc(protocol
, &sock
);
1839 nl_sock_transact_multiple(sock
, transactions
, n
);
1840 nl_pool_release(sock
);
1842 nl_sock_record_errors__(transactions
, n
, error
);
1848 nl_sock_allocate_seq(struct nl_sock
*sock
, unsigned int n
)
1850 uint32_t seq
= sock
->next_seq
;
1852 sock
->next_seq
+= n
;
1854 /* Make it impossible for the next request for sequence numbers to wrap
1855 * around to 0. Start over with 1 to avoid ever using a sequence number of
1856 * 0, because the kernel uses sequence number 0 for notifications. */
1857 if (sock
->next_seq
>= UINT32_MAX
/ 2) {
1865 nlmsghdr_to_string(const struct nlmsghdr
*h
, int protocol
, struct ds
*ds
)
1871 static const struct nlmsg_flag flags
[] = {
1872 { NLM_F_REQUEST
, "REQUEST" },
1873 { NLM_F_MULTI
, "MULTI" },
1874 { NLM_F_ACK
, "ACK" },
1875 { NLM_F_ECHO
, "ECHO" },
1876 { NLM_F_DUMP
, "DUMP" },
1877 { NLM_F_ROOT
, "ROOT" },
1878 { NLM_F_MATCH
, "MATCH" },
1879 { NLM_F_ATOMIC
, "ATOMIC" },
1881 const struct nlmsg_flag
*flag
;
1882 uint16_t flags_left
;
1884 ds_put_format(ds
, "nl(len:%"PRIu32
", type=%"PRIu16
,
1885 h
->nlmsg_len
, h
->nlmsg_type
);
1886 if (h
->nlmsg_type
== NLMSG_NOOP
) {
1887 ds_put_cstr(ds
, "(no-op)");
1888 } else if (h
->nlmsg_type
== NLMSG_ERROR
) {
1889 ds_put_cstr(ds
, "(error)");
1890 } else if (h
->nlmsg_type
== NLMSG_DONE
) {
1891 ds_put_cstr(ds
, "(done)");
1892 } else if (h
->nlmsg_type
== NLMSG_OVERRUN
) {
1893 ds_put_cstr(ds
, "(overrun)");
1894 } else if (h
->nlmsg_type
< NLMSG_MIN_TYPE
) {
1895 ds_put_cstr(ds
, "(reserved)");
1896 } else if (protocol
== NETLINK_GENERIC
) {
1897 ds_put_format(ds
, "(%s)", genl_family_to_name(h
->nlmsg_type
));
1899 ds_put_cstr(ds
, "(family-defined)");
1901 ds_put_format(ds
, ", flags=%"PRIx16
, h
->nlmsg_flags
);
1902 flags_left
= h
->nlmsg_flags
;
1903 for (flag
= flags
; flag
< &flags
[ARRAY_SIZE(flags
)]; flag
++) {
1904 if ((flags_left
& flag
->bits
) == flag
->bits
) {
1905 ds_put_format(ds
, "[%s]", flag
->name
);
1906 flags_left
&= ~flag
->bits
;
1910 ds_put_format(ds
, "[OTHER:%"PRIx16
"]", flags_left
);
1912 ds_put_format(ds
, ", seq=%"PRIx32
", pid=%"PRIu32
,
1913 h
->nlmsg_seq
, h
->nlmsg_pid
);
1917 nlmsg_to_string(const struct ofpbuf
*buffer
, int protocol
)
1919 struct ds ds
= DS_EMPTY_INITIALIZER
;
1920 const struct nlmsghdr
*h
= ofpbuf_at(buffer
, 0, NLMSG_HDRLEN
);
1922 nlmsghdr_to_string(h
, protocol
, &ds
);
1923 if (h
->nlmsg_type
== NLMSG_ERROR
) {
1924 const struct nlmsgerr
*e
;
1925 e
= ofpbuf_at(buffer
, NLMSG_HDRLEN
,
1926 NLMSG_ALIGN(sizeof(struct nlmsgerr
)));
1928 ds_put_format(&ds
, " error(%d", e
->error
);
1930 ds_put_format(&ds
, "(%s)", ovs_strerror(-e
->error
));
1932 ds_put_cstr(&ds
, ", in-reply-to(");
1933 nlmsghdr_to_string(&e
->msg
, protocol
, &ds
);
1934 ds_put_cstr(&ds
, "))");
1936 ds_put_cstr(&ds
, " error(truncated)");
1938 } else if (h
->nlmsg_type
== NLMSG_DONE
) {
1939 int *error
= ofpbuf_at(buffer
, NLMSG_HDRLEN
, sizeof *error
);
1941 ds_put_format(&ds
, " done(%d", *error
);
1943 ds_put_format(&ds
, "(%s)", ovs_strerror(-*error
));
1945 ds_put_cstr(&ds
, ")");
1947 ds_put_cstr(&ds
, " done(truncated)");
1949 } else if (protocol
== NETLINK_GENERIC
) {
1950 struct genlmsghdr
*genl
= nl_msg_genlmsghdr(buffer
);
1952 ds_put_format(&ds
, ",genl(cmd=%"PRIu8
",version=%"PRIu8
")",
1953 genl
->cmd
, genl
->version
);
1957 ds_put_cstr(&ds
, "nl(truncated)");
1963 log_nlmsg(const char *function
, int error
,
1964 const void *message
, size_t size
, int protocol
)
1966 if (!VLOG_IS_DBG_ENABLED()) {
1970 struct ofpbuf buffer
= ofpbuf_const_initializer(message
, size
);
1971 char *nlmsg
= nlmsg_to_string(&buffer
, protocol
);
1972 VLOG_DBG_RL(&rl
, "%s (%s): %s", function
, ovs_strerror(error
), nlmsg
);