]> git.proxmox.com Git - mirror_ovs.git/blame - lib/netlink-socket.c
ovs-lib: Ensure Emacs and vim identify the file type properly.
[mirror_ovs.git] / lib / netlink-socket.c
CommitLineData
2fe27d5a 1/*
0a2869d5 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Nicira, Inc.
2fe27d5a
BP
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include <config.h>
18#include "netlink-socket.h"
2fe27d5a
BP
19#include <errno.h>
20#include <inttypes.h>
21#include <stdlib.h>
a86bd14e 22#include <sys/socket.h>
2fe27d5a 23#include <sys/types.h>
cc75061a 24#include <sys/uio.h>
2fe27d5a
BP
25#include <unistd.h>
26#include "coverage.h"
3e8a2ad1 27#include "openvswitch/dynamic-string.h"
2ad204c8 28#include "hash.h"
ee89ea7b 29#include "openvswitch/hmap.h"
2fe27d5a
BP
30#include "netlink.h"
31#include "netlink-protocol.h"
a86bd14e 32#include "netnsid.h"
886dd35a 33#include "odp-netlink.h"
64c96779 34#include "openvswitch/ofpbuf.h"
0bd01224 35#include "ovs-thread.h"
fd016ae3 36#include "openvswitch/poll-loop.h"
0672776e 37#include "seq.h"
6b7c12fd 38#include "socket-util.h"
cc75061a 39#include "util.h"
e6211adc 40#include "openvswitch/vlog.h"
2fe27d5a
BP
41
42VLOG_DEFINE_THIS_MODULE(netlink_socket);
43
44COVERAGE_DEFINE(netlink_overflow);
45COVERAGE_DEFINE(netlink_received);
fc999dda 46COVERAGE_DEFINE(netlink_recv_jumbo);
2fe27d5a
BP
47COVERAGE_DEFINE(netlink_sent);
48
49/* Linux header file confusion causes this to be undefined. */
50#ifndef SOL_NETLINK
51#define SOL_NETLINK 270
52#endif
53
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. */
57static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
58
7d7447df 59static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
2fe27d5a 60static void log_nlmsg(const char *function, int error,
7041c3a9 61 const void *message, size_t size, int protocol);
886dd35a 62#ifdef _WIN32
ebac7fb7 63static int get_sock_pid_from_kernel(struct nl_sock *sock);
e70f55ed 64static int set_sock_property(struct nl_sock *sock);
74804b21
AS
65static int nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
66 struct ofpbuf **replyp);
d553dd54
AS
67
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. */
74void
75lost_communication(DWORD last_err)
76{
77 if (last_err == ERROR_NOT_FOUND) {
78 ovs_abort(0, "lost communication with the kernel device");
79 }
80}
886dd35a 81#endif
2fe27d5a
BP
82\f
83/* Netlink sockets. */
84
0d121c73 85struct nl_sock {
22326ba6
AS
86#ifdef _WIN32
87 HANDLE handle;
7fa09611 88 OVERLAPPED overlapped;
64513e68 89 DWORD read_ioctl;
22326ba6 90#else
2fe27d5a 91 int fd;
22326ba6 92#endif
7d7447df 93 uint32_t next_seq;
2fe27d5a 94 uint32_t pid;
7041c3a9 95 int protocol;
cc75061a 96 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
2fe27d5a
BP
97};
98
cc75061a
BP
99/* Compile-time limit on iovecs, so that we can allocate a maximum-size array
100 * of iovecs on the stack. */
101#define MAX_IOVS 128
102
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.
105 *
106 * Initialized by nl_sock_create(). */
107static int max_iovs;
108
a88b4e04
BP
109static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
110static void nl_pool_release(struct nl_sock *);
2fe27d5a
BP
111
112/* Creates a new netlink socket for the given netlink 'protocol'
113 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
a88b4e04 114 * new socket if successful, otherwise returns a positive errno value. */
2fe27d5a 115int
cceb11f5 116nl_sock_create(int protocol, struct nl_sock **sockp)
2fe27d5a 117{
0bd01224 118 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2fe27d5a 119 struct nl_sock *sock;
22326ba6 120#ifndef _WIN32
2fe27d5a 121 struct sockaddr_nl local, remote;
22326ba6 122#endif
2c5a6834 123 socklen_t local_size;
d2b9f5b0 124 int rcvbuf;
2fe27d5a
BP
125 int retval = 0;
126
0bd01224 127 if (ovsthread_once_start(&once)) {
cc75061a
BP
128 int save_errno = errno;
129 errno = 0;
130
131 max_iovs = sysconf(_SC_UIO_MAXIOV);
132 if (max_iovs < _XOPEN_IOV_MAX) {
133 if (max_iovs == -1 && errno) {
10a89ef0 134 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
cc75061a
BP
135 }
136 max_iovs = _XOPEN_IOV_MAX;
137 } else if (max_iovs > MAX_IOVS) {
138 max_iovs = MAX_IOVS;
139 }
140
141 errno = save_errno;
0bd01224 142 ovsthread_once_done(&once);
cc75061a
BP
143 }
144
2fe27d5a 145 *sockp = NULL;
488232b7 146 sock = xmalloc(sizeof *sock);
2fe27d5a 147
22326ba6 148#ifdef _WIN32
e6b298ef 149 sock->overlapped.hEvent = NULL;
7fa09611
EE
150 sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
151 GENERIC_READ | GENERIC_WRITE,
152 FILE_SHARE_READ | FILE_SHARE_WRITE,
153 NULL, OPEN_EXISTING,
154 FILE_FLAG_OVERLAPPED, NULL);
22326ba6
AS
155
156 if (sock->handle == INVALID_HANDLE_VALUE) {
52a1540a 157 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
7fa09611
EE
158 goto error;
159 }
160
161 memset(&sock->overlapped, 0, sizeof sock->overlapped);
162 sock->overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
163 if (sock->overlapped.hEvent == NULL) {
52a1540a 164 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
22326ba6
AS
165 goto error;
166 }
64513e68
EE
167 /* Initialize the type/ioctl to Generic */
168 sock->read_ioctl = OVS_IOCTL_READ;
22326ba6 169#else
2fe27d5a
BP
170 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
171 if (sock->fd < 0) {
10a89ef0 172 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
2fe27d5a
BP
173 goto error;
174 }
22326ba6
AS
175#endif
176
7041c3a9 177 sock->protocol = protocol;
7d7447df 178 sock->next_seq = 1;
2fe27d5a 179
d2b9f5b0 180 rcvbuf = 1024 * 1024;
22326ba6
AS
181#ifdef _WIN32
182 sock->rcvbuf = rcvbuf;
ebac7fb7 183 retval = get_sock_pid_from_kernel(sock);
886dd35a
NR
184 if (retval != 0) {
185 goto error;
186 }
e70f55ed
SV
187 retval = set_sock_property(sock);
188 if (retval != 0) {
189 goto error;
190 }
22326ba6 191#else
d2b9f5b0
BP
192 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
193 &rcvbuf, sizeof rcvbuf)) {
80af5ee5
BP
194 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
195 * Warn only if the failure is therefore unexpected. */
f28b6dd3 196 if (errno != EPERM) {
80af5ee5 197 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
10a89ef0 198 "(%s)", rcvbuf, ovs_strerror(errno));
80af5ee5 199 }
d2b9f5b0
BP
200 }
201
cc75061a
BP
202 retval = get_socket_rcvbuf(sock->fd);
203 if (retval < 0) {
204 retval = -retval;
205 goto error;
206 }
207 sock->rcvbuf = retval;
2e467950 208 retval = 0;
cc75061a 209
2c5a6834 210 /* Connect to kernel (pid 0) as remote address. */
2fe27d5a
BP
211 memset(&remote, 0, sizeof remote);
212 remote.nl_family = AF_NETLINK;
213 remote.nl_pid = 0;
214 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
10a89ef0 215 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
2c5a6834
BP
216 goto error;
217 }
218
219 /* Obtain pid assigned by kernel. */
220 local_size = sizeof local;
221 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
10a89ef0 222 VLOG_ERR("getsockname: %s", ovs_strerror(errno));
2c5a6834
BP
223 goto error;
224 }
225 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
226 VLOG_ERR("getsockname returned bad Netlink name");
227 retval = EINVAL;
228 goto error;
2fe27d5a 229 }
2c5a6834 230 sock->pid = local.nl_pid;
22326ba6 231#endif
2fe27d5a 232
2fe27d5a
BP
233 *sockp = sock;
234 return 0;
235
2fe27d5a
BP
236error:
237 if (retval == 0) {
238 retval = errno;
239 if (retval == 0) {
240 retval = EINVAL;
241 }
242 }
22326ba6 243#ifdef _WIN32
7fa09611
EE
244 if (sock->overlapped.hEvent) {
245 CloseHandle(sock->overlapped.hEvent);
246 }
22326ba6
AS
247 if (sock->handle != INVALID_HANDLE_VALUE) {
248 CloseHandle(sock->handle);
249 }
250#else
2fe27d5a
BP
251 if (sock->fd >= 0) {
252 close(sock->fd);
253 }
22326ba6 254#endif
2fe27d5a
BP
255 free(sock);
256 return retval;
257}
258
c6eab56d
BP
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
261 * errno value. */
262int
263nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
264{
265 return nl_sock_create(src->protocol, sockp);
266}
267
2fe27d5a
BP
268/* Destroys netlink socket 'sock'. */
269void
270nl_sock_destroy(struct nl_sock *sock)
271{
272 if (sock) {
22326ba6 273#ifdef _WIN32
7fa09611
EE
274 if (sock->overlapped.hEvent) {
275 CloseHandle(sock->overlapped.hEvent);
276 }
22326ba6
AS
277 CloseHandle(sock->handle);
278#else
a88b4e04 279 close(sock->fd);
22326ba6 280#endif
a88b4e04 281 free(sock);
2fe27d5a
BP
282 }
283}
284
886dd35a
NR
285#ifdef _WIN32
286/* Reads the pid for 'sock' generated in the kernel datapath. The function
190cf533
SV
287 * uses a separate IOCTL instead of a transaction semantic to avoid unnecessary
288 * message overhead. */
886dd35a 289static int
ebac7fb7 290get_sock_pid_from_kernel(struct nl_sock *sock)
886dd35a 291{
190cf533
SV
292 uint32_t pid = 0;
293 int retval = 0;
294 DWORD bytes = 0;
886dd35a 295
190cf533
SV
296 if (!DeviceIoControl(sock->handle, OVS_IOCTL_GET_PID,
297 NULL, 0, &pid, sizeof(pid),
886dd35a 298 &bytes, NULL)) {
d553dd54 299 lost_communication(GetLastError());
886dd35a 300 retval = EINVAL;
886dd35a 301 } else {
190cf533 302 if (bytes < sizeof(pid)) {
886dd35a 303 retval = EINVAL;
190cf533
SV
304 } else {
305 sock->pid = pid;
886dd35a 306 }
886dd35a 307 }
886dd35a 308
886dd35a
NR
309 return retval;
310}
e70f55ed
SV
311
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
318 * is not modified.
319 * Also verify if Protocol and PID in Kernel reflects the values in userspace
320 * */
321static int
322set_sock_property(struct nl_sock *sock)
323{
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 }
327 };
328
329 struct ofpbuf request, *reply;
330 struct ovs_header *ovs_header;
331 struct nlattr *attrs[ARRAY_SIZE(ovs_socket_policy)];
332 int retval = 0;
333 int error;
334
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;
340
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
344 */
345 nl_msg_put_be32(&request, OVS_NL_ATTR_SOCK_PID, sock->pid);
346
347 error = nl_sock_transact(sock, &request, &reply);
348 ofpbuf_uninit(&request);
349 if (error) {
350 retval = EINVAL;
351 }
352
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);
358 retval = EINVAL;
359 }
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);
366 retval = EINVAL;
367 }
368 }
369
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",
374 pid, sock->pid);
375 retval = EINVAL;
376 }
377 }
378
379 return retval;
380}
886dd35a
NR
381#endif /* _WIN32 */
382
b8f958ea
EE
383#ifdef _WIN32
384static int __inline
385nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
386{
387 struct ofpbuf request;
388 uint64_t request_stub[128];
389 struct ovs_header *ovs_header;
390 struct nlmsghdr *nlmsg;
391 int error;
392
393 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
394
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);
398
399 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
400 ovs_header->dp_ifindex = 0;
401
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);
404
405 error = nl_sock_send(sock, &request, true);
406 ofpbuf_uninit(&request);
407 return error;
408}
409#endif
cceb11f5
BP
410/* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
411 * successful, otherwise a positive errno value.
412 *
a838c4fe
BP
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.
416 *
cceb11f5
BP
417 * Multicast group numbers are always positive.
418 *
419 * It is not an error to attempt to join a multicast group to which a socket
420 * already belongs. */
421int
422nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
423{
22326ba6 424#ifdef _WIN32
64513e68
EE
425 /* Set the socket type as a "multicast" socket */
426 sock->read_ioctl = OVS_IOCTL_READ_EVENT;
b8f958ea
EE
427 int error = nl_sock_mcgroup(sock, multicast_group, true);
428 if (error) {
64513e68 429 sock->read_ioctl = OVS_IOCTL_READ;
b8f958ea 430 VLOG_WARN("could not join multicast group %u (%s)",
15fd9052
NR
431 multicast_group, ovs_strerror(error));
432 return error;
b8f958ea 433 }
22326ba6 434#else
cceb11f5
BP
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)",
10a89ef0 438 multicast_group, ovs_strerror(errno));
cceb11f5
BP
439 return errno;
440 }
22326ba6 441#endif
cceb11f5
BP
442 return 0;
443}
444
cf114a7f
FL
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.
451 *
452 * Returns 0 if successful, otherwise a positive errno. */
453int
454nl_sock_listen_all_nsid(struct nl_sock *sock, bool enable)
455{
456 int error;
457 int val = enable ? 1 : 0;
458
459#ifndef _WIN32
460 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, &val,
461 sizeof val) < 0) {
462 error = errno;
463 VLOG_INFO("netlink: could not %s listening to all nsid (%s)",
464 enable ? "enable" : "disable", ovs_strerror(error));
465 return errno;
466 }
467#endif
468
469 return 0;
470}
471
36791e21 472#ifdef _WIN32
74804b21
AS
473int
474nl_sock_subscribe_packet__(struct nl_sock *sock, bool subscribe)
475{
476 struct ofpbuf request;
477 uint64_t request_stub[128];
478 struct ovs_header *ovs_header;
479 struct nlmsghdr *nlmsg;
480 int error;
481
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);
486
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);
491
492 error = nl_sock_send(sock, &request, true);
493 ofpbuf_uninit(&request);
494 return error;
495}
496
36791e21
NR
497int
498nl_sock_subscribe_packets(struct nl_sock *sock)
499{
500 int error;
501
502 if (sock->read_ioctl != OVS_IOCTL_READ) {
503 return EINVAL;
504 }
505
506 error = nl_sock_subscribe_packet__(sock, true);
507 if (error) {
d8d1ef2f
AS
508 VLOG_WARN("could not subscribe packets (%s)",
509 ovs_strerror(error));
36791e21
NR
510 return error;
511 }
512 sock->read_ioctl = OVS_IOCTL_READ_PACKET;
513
514 return 0;
515}
516
517int
518nl_sock_unsubscribe_packets(struct nl_sock *sock)
519{
520 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET);
521
522 int error = nl_sock_subscribe_packet__(sock, false);
523 if (error) {
d8d1ef2f
AS
524 VLOG_WARN("could not unsubscribe to packets (%s)",
525 ovs_strerror(error));
36791e21
NR
526 return error;
527 }
528
529 sock->read_ioctl = OVS_IOCTL_READ;
530 return 0;
531}
36791e21
NR
532#endif
533
cceb11f5
BP
534/* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
535 * successful, otherwise a positive errno value.
536 *
537 * Multicast group numbers are always positive.
538 *
539 * It is not an error to attempt to leave a multicast group to which a socket
540 * does not belong.
541 *
542 * On success, reading from 'sock' will still return any messages that were
543 * received on 'multicast_group' before the group was left. */
544int
545nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
546{
22326ba6 547#ifdef _WIN32
b8f958ea
EE
548 int error = nl_sock_mcgroup(sock, multicast_group, false);
549 if (error) {
550 VLOG_WARN("could not leave multicast group %u (%s)",
15fd9052
NR
551 multicast_group, ovs_strerror(error));
552 return error;
b8f958ea 553 }
64513e68 554 sock->read_ioctl = OVS_IOCTL_READ;
22326ba6 555#else
cceb11f5
BP
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)",
10a89ef0 559 multicast_group, ovs_strerror(errno));
cceb11f5
BP
560 return errno;
561 }
22326ba6 562#endif
cceb11f5
BP
563 return 0;
564}
565
c6eab56d 566static int
ff459dd6
BP
567nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
568 uint32_t nlmsg_seq, bool wait)
2fe27d5a
BP
569{
570 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
571 int error;
572
6fd6ed71 573 nlmsg->nlmsg_len = msg->size;
ff459dd6 574 nlmsg->nlmsg_seq = nlmsg_seq;
2fe27d5a
BP
575 nlmsg->nlmsg_pid = sock->pid;
576 do {
577 int retval;
22326ba6 578#ifdef _WIN32
fd972eb8
NR
579 DWORD bytes;
580
581 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
6fd6ed71 582 msg->data, msg->size, NULL, 0,
0fd22ae2 583 &bytes, NULL)) {
d553dd54 584 lost_communication(GetLastError());
22326ba6 585 retval = -1;
fd972eb8
NR
586 /* XXX: Map to a more appropriate error based on GetLastError(). */
587 errno = EINVAL;
a51a5086 588 VLOG_DBG_RL(&rl, "fatal driver failure in write: %s",
d553dd54 589 ovs_lasterror_to_string());
fd972eb8 590 } else {
6fd6ed71 591 retval = msg->size;
22326ba6
AS
592 }
593#else
6fd6ed71 594 retval = send(sock->fd, msg->data, msg->size,
fd972eb8 595 wait ? 0 : MSG_DONTWAIT);
22326ba6 596#endif
2fe27d5a
BP
597 error = retval < 0 ? errno : 0;
598 } while (error == EINTR);
6fd6ed71 599 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
2fe27d5a
BP
600 if (!error) {
601 COVERAGE_INC(netlink_sent);
602 }
603 return error;
604}
605
c6eab56d 606/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
6fd6ed71 607 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
ff459dd6
BP
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.
c6eab56d
BP
610 *
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. */
614int
615nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
ff459dd6
BP
616{
617 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
618}
619
620/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
6fd6ed71 621 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
ff459dd6
BP
622 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
623 * 'nlmsg_seq', before the message is sent.
624 *
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.
628 *
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. */
631int
632nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
633 uint32_t nlmsg_seq, bool wait)
c6eab56d 634{
ff459dd6 635 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
c6eab56d
BP
636}
637
c6eab56d 638static int
a86bd14e 639nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, int *nsid, bool wait)
2fe27d5a 640{
72d32ac0
BP
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). */
2fe27d5a 646 struct nlmsghdr *nlmsghdr;
72d32ac0 647 uint8_t tail[65536];
fc999dda 648 struct iovec iov[2];
fc999dda 649 struct msghdr msg;
a86bd14e
FL
650 uint8_t msgctrl[64];
651 struct cmsghdr *cmsg;
fc999dda 652 ssize_t retval;
a86bd14e 653 int *ptr;
8f20fd98 654 int error;
fc999dda 655
cb22974d 656 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
72d32ac0 657 ofpbuf_clear(buf);
2fe27d5a 658
6fd6ed71 659 iov[0].iov_base = buf->base;
72d32ac0 660 iov[0].iov_len = buf->allocated;
fc999dda 661 iov[1].iov_base = tail;
72d32ac0 662 iov[1].iov_len = sizeof tail;
fc999dda
BP
663
664 memset(&msg, 0, sizeof msg);
665 msg.msg_iov = iov;
666 msg.msg_iovlen = 2;
a86bd14e
FL
667 msg.msg_control = msgctrl;
668 msg.msg_controllen = sizeof msgctrl;
fc999dda 669
8f20fd98
BP
670 /* Receive a Netlink message from the kernel.
671 *
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. */
6fd6ed71 677 nlmsghdr = buf->base;
2fe27d5a 678 do {
8f20fd98 679 nlmsghdr->nlmsg_len = UINT32_MAX;
22326ba6 680#ifdef _WIN32
fd972eb8 681 DWORD bytes;
64513e68 682 if (!DeviceIoControl(sock->handle, sock->read_ioctl,
fd972eb8 683 NULL, 0, tail, sizeof tail, &bytes, NULL)) {
d553dd54 684 lost_communication(GetLastError());
a51a5086 685 VLOG_DBG_RL(&rl, "fatal driver failure in transact: %s",
d71c423e 686 ovs_lasterror_to_string());
22326ba6 687 retval = -1;
a51a5086 688 /* XXX: Map to a more appropriate error. */
fd972eb8 689 errno = EINVAL;
22326ba6 690 } else {
fd972eb8
NR
691 retval = bytes;
692 if (retval == 0) {
693 retval = -1;
694 errno = EAGAIN;
695 } else {
696 if (retval >= buf->allocated) {
697 ofpbuf_reinit(buf, retval);
6fd6ed71 698 nlmsghdr = buf->base;
15fd9052 699 nlmsghdr->nlmsg_len = UINT32_MAX;
fd972eb8 700 }
6fd6ed71
PS
701 memcpy(buf->data, tail, retval);
702 buf->size = retval;
fd972eb8 703 }
22326ba6
AS
704 }
705#else
fc999dda 706 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
22326ba6 707#endif
8f20fd98
BP
708 error = (retval < 0 ? errno
709 : retval == 0 ? ECONNRESET /* not possible? */
710 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
7f8e2646 711 : retval);
8f20fd98
BP
712 } while (error == EINTR);
713 if (error) {
fc999dda
BP
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);
718 }
fc999dda 719 return error;
2fe27d5a 720 }
fc999dda 721
2fe27d5a 722 if (msg.msg_flags & MSG_TRUNC) {
34582733 723 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
72d32ac0 724 sizeof tail);
fc999dda 725 return E2BIG;
2fe27d5a 726 }
2fe27d5a 727
fc999dda 728 if (retval < sizeof *nlmsghdr
2fe27d5a 729 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
fc999dda 730 || nlmsghdr->nlmsg_len > retval) {
e5e4b47c 731 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
72d32ac0 732 retval, sizeof *nlmsghdr);
2fe27d5a
BP
733 return EPROTO;
734 }
22326ba6 735#ifndef _WIN32
6fd6ed71 736 buf->size = MIN(retval, buf->allocated);
72d32ac0
BP
737 if (retval > buf->allocated) {
738 COVERAGE_INC(netlink_recv_jumbo);
739 ofpbuf_put(buf, tail, retval - buf->allocated);
740 }
22326ba6 741#endif
72d32ac0 742
a86bd14e
FL
743 if (nsid) {
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);
750 cmsg = CMSG_FIRSTHDR(&msg);
751 while (cmsg != NULL) {
752 if (cmsg->cmsg_level == SOL_NETLINK
753 && cmsg->cmsg_type == NETLINK_LISTEN_ALL_NSID) {
754 ptr = ALIGNED_CAST(int *, CMSG_DATA(cmsg));
755 netnsid_set(nsid, *ptr);
756 }
757 if (cmsg->cmsg_level == SOL_SOCKET
758 && cmsg->cmsg_type == SCM_RIGHTS) {
759 /* This is unexpected and unwanted, close all fds */
760 int nfds;
761 int i;
762 nfds = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))
763 / sizeof(int);
764 ptr = ALIGNED_CAST(int *, CMSG_DATA(cmsg));
765 for (i = 0; i < nfds; i++) {
766 VLOG_ERR_RL(&rl, "closing unexpected received fd (%d).",
767 ptr[i]);
768 close(ptr[i]);
769 }
770 }
771
772 cmsg = CMSG_NXTHDR(&msg, cmsg);
773 }
774 }
775
6fd6ed71 776 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
2fe27d5a
BP
777 COVERAGE_INC(netlink_received);
778
779 return 0;
780}
781
72d32ac0
BP
782/* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
783 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
a86bd14e
FL
784 * EAGAIN if the 'sock' receive buffer is empty. If 'nsid' is provided, the
785 * network namespace id from which the message was sent will be provided.
72d32ac0
BP
786 *
787 * The caller must have initialized 'buf' with an allocation of at least
788 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
789 * space for a "typical" message.
790 *
791 * On success, returns 0 and replaces 'buf''s previous content by the received
792 * message. This function expands 'buf''s allocated memory, as necessary, to
793 * hold the actual size of the received message.
c6eab56d 794 *
72d32ac0
BP
795 * On failure, returns a positive errno value and clears 'buf' to zero length.
796 * 'buf' retains its previous memory allocation.
797 *
798 * Regardless of success or failure, this function resets 'buf''s headroom to
799 * 0. */
c6eab56d 800int
a86bd14e 801nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, int *nsid, bool wait)
c6eab56d 802{
a86bd14e 803 return nl_sock_recv__(sock, buf, nsid, wait);
cc75061a
BP
804}
805
806static void
807nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
808 int error)
809{
810 size_t i;
811
812 for (i = 0; i < n; i++) {
72d32ac0
BP
813 struct nl_transaction *txn = transactions[i];
814
815 txn->error = error;
816 if (txn->reply) {
817 ofpbuf_clear(txn->reply);
818 }
cc75061a
BP
819 }
820}
821
822static int
823nl_sock_transact_multiple__(struct nl_sock *sock,
824 struct nl_transaction **transactions, size_t n,
825 size_t *done)
826{
72d32ac0
BP
827 uint64_t tmp_reply_stub[1024 / 8];
828 struct nl_transaction tmp_txn;
829 struct ofpbuf tmp_reply;
830
831 uint32_t base_seq;
cc75061a
BP
832 struct iovec iovs[MAX_IOVS];
833 struct msghdr msg;
834 int error;
835 int i;
836
72d32ac0 837 base_seq = nl_sock_allocate_seq(sock, n);
cc75061a
BP
838 *done = 0;
839 for (i = 0; i < n; i++) {
72d32ac0
BP
840 struct nl_transaction *txn = transactions[i];
841 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
cc75061a 842
6fd6ed71 843 nlmsg->nlmsg_len = txn->request->size;
72d32ac0 844 nlmsg->nlmsg_seq = base_seq + i;
cc75061a 845 nlmsg->nlmsg_pid = sock->pid;
cc75061a 846
6fd6ed71
PS
847 iovs[i].iov_base = txn->request->data;
848 iovs[i].iov_len = txn->request->size;
cc75061a
BP
849 }
850
0fd22ae2 851#ifndef _WIN32
cc75061a
BP
852 memset(&msg, 0, sizeof msg);
853 msg.msg_iov = iovs;
854 msg.msg_iovlen = n;
855 do {
856 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
857 } while (error == EINTR);
858
859 for (i = 0; i < n; i++) {
72d32ac0 860 struct nl_transaction *txn = transactions[i];
cc75061a 861
6fd6ed71
PS
862 log_nlmsg(__func__, error, txn->request->data,
863 txn->request->size, sock->protocol);
cc75061a
BP
864 }
865 if (!error) {
866 COVERAGE_ADD(netlink_sent, n);
867 }
868
869 if (error) {
870 return error;
871 }
872
72d32ac0
BP
873 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
874 tmp_txn.request = NULL;
875 tmp_txn.reply = &tmp_reply;
876 tmp_txn.error = 0;
cc75061a 877 while (n > 0) {
72d32ac0
BP
878 struct nl_transaction *buf_txn, *txn;
879 uint32_t seq;
880
881 /* Find a transaction whose buffer we can use for receiving a reply.
882 * If no such transaction is left, use tmp_txn. */
883 buf_txn = &tmp_txn;
884 for (i = 0; i < n; i++) {
885 if (transactions[i]->reply) {
886 buf_txn = transactions[i];
887 break;
888 }
889 }
cc75061a 890
72d32ac0 891 /* Receive a reply. */
a86bd14e 892 error = nl_sock_recv__(sock, buf_txn->reply, NULL, false);
72d32ac0
BP
893 if (error) {
894 if (error == EAGAIN) {
895 nl_sock_record_errors__(transactions, n, 0);
896 *done += n;
897 error = 0;
898 }
899 break;
cc75061a
BP
900 }
901
72d32ac0
BP
902 /* Match the reply up with a transaction. */
903 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
904 if (seq < base_seq || seq >= base_seq + n) {
905 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
cc75061a
BP
906 continue;
907 }
72d32ac0
BP
908 i = seq - base_seq;
909 txn = transactions[i];
cc75061a 910
72d32ac0
BP
911 /* Fill in the results for 'txn'. */
912 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
913 if (txn->reply) {
914 ofpbuf_clear(txn->reply);
915 }
916 if (txn->error) {
cc75061a 917 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
10a89ef0 918 error, ovs_strerror(txn->error));
cc75061a 919 }
cc75061a 920 } else {
72d32ac0
BP
921 txn->error = 0;
922 if (txn->reply && txn != buf_txn) {
923 /* Swap buffers. */
924 struct ofpbuf *reply = buf_txn->reply;
925 buf_txn->reply = txn->reply;
926 txn->reply = reply;
927 }
cc75061a
BP
928 }
929
72d32ac0
BP
930 /* Fill in the results for transactions before 'txn'. (We have to do
931 * this after the results for 'txn' itself because of the buffer swap
932 * above.) */
933 nl_sock_record_errors__(transactions, i, 0);
934
935 /* Advance. */
cc75061a
BP
936 *done += i + 1;
937 transactions += i + 1;
938 n -= i + 1;
72d32ac0 939 base_seq += i + 1;
cc75061a 940 }
72d32ac0 941 ofpbuf_uninit(&tmp_reply);
0fd22ae2
NR
942#else
943 error = 0;
9189184d 944 uint8_t reply_buf[65536];
0fd22ae2
NR
945 for (i = 0; i < n; i++) {
946 DWORD reply_len;
a51a5086 947 bool ret;
0fd22ae2
NR
948 struct nl_transaction *txn = transactions[i];
949 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
950
a51a5086
NR
951 ret = DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
952 txn->request->data,
953 txn->request->size,
954 reply_buf, sizeof reply_buf,
955 &reply_len, NULL);
956
957 if (ret && reply_len == 0) {
958 /*
959 * The current transaction did not produce any data to read and that
960 * is not an error as such. Continue with the remainder of the
961 * transactions.
962 */
963 txn->error = 0;
964 if (txn->reply) {
965 ofpbuf_clear(txn->reply);
966 }
967 } else if (!ret) {
0fd22ae2 968 /* XXX: Map to a more appropriate error. */
d553dd54 969 lost_communication(GetLastError());
0fd22ae2 970 error = EINVAL;
b937e116
BP
971 VLOG_DBG_RL(&rl, "fatal driver failure: %s",
972 ovs_lasterror_to_string());
0fd22ae2
NR
973 break;
974 }
975
a51a5086 976 if (reply_len != 0) {
7e86fe82
AS
977 request_nlmsg = nl_msg_nlmsghdr(txn->request);
978
a51a5086
NR
979 if (reply_len < sizeof *reply_nlmsg) {
980 nl_sock_record_errors__(transactions, n, 0);
981 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32
982 " for seq: %#"PRIx32, reply_len, request_nlmsg->nlmsg_seq);
983 break;
984 }
0fd22ae2 985
a51a5086 986 /* Validate the sequence number in the reply. */
a51a5086 987 reply_nlmsg = (struct nlmsghdr *)reply_buf;
0fd22ae2 988
a51a5086
NR
989 if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
990 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
991 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
992 ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
993 reply_nlmsg->nlmsg_seq);
994 break;
0fd22ae2 995 }
a51a5086
NR
996
997 /* Handle errors embedded within the netlink message. */
998 ofpbuf_use_stub(&tmp_reply, reply_buf, sizeof reply_buf);
999 tmp_reply.size = sizeof reply_buf;
1000 if (nl_msg_nlmsgerr(&tmp_reply, &txn->error)) {
1001 if (txn->reply) {
1002 ofpbuf_clear(txn->reply);
1003 }
1004 if (txn->error) {
1005 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
1006 error, ovs_strerror(txn->error));
1007 }
1008 } else {
1009 txn->error = 0;
1010 if (txn->reply) {
1011 /* Copy the reply to the buffer specified by the caller. */
1012 if (reply_len > txn->reply->allocated) {
1013 ofpbuf_reinit(txn->reply, reply_len);
1014 }
1015 memcpy(txn->reply->data, reply_buf, reply_len);
1016 txn->reply->size = reply_len;
0fd22ae2 1017 }
0fd22ae2 1018 }
a51a5086 1019 ofpbuf_uninit(&tmp_reply);
0fd22ae2
NR
1020 }
1021
1022 /* Count the number of successful transactions. */
1023 (*done)++;
9189184d 1024
0fd22ae2
NR
1025 }
1026
1027 if (!error) {
1028 COVERAGE_ADD(netlink_sent, n);
1029 }
1030#endif
cc75061a 1031
72d32ac0 1032 return error;
cc75061a
BP
1033}
1034
022ad2b9 1035static void
cc75061a
BP
1036nl_sock_transact_multiple(struct nl_sock *sock,
1037 struct nl_transaction **transactions, size_t n)
1038{
1039 int max_batch_count;
1040 int error;
1041
1042 if (!n) {
1043 return;
1044 }
1045
cc75061a
BP
1046 /* In theory, every request could have a 64 kB reply. But the default and
1047 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
1048 * be a bit below 128 kB, so that would only allow a single message in a
1049 * "batch". So we assume that replies average (at most) 4 kB, which allows
1050 * a good deal of batching.
1051 *
1052 * In practice, most of the requests that we batch either have no reply at
1053 * all or a brief reply. */
1054 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
1055 max_batch_count = MIN(max_batch_count, max_iovs);
1056
1057 while (n > 0) {
1058 size_t count, bytes;
1059 size_t done;
1060
1061 /* Batch up to 'max_batch_count' transactions. But cap it at about a
1062 * page of requests total because big skbuffs are expensive to
1063 * allocate in the kernel. */
1064#if defined(PAGESIZE)
1065 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
1066#else
1067 enum { MAX_BATCH_BYTES = 4096 - 512 };
1068#endif
6fd6ed71 1069 bytes = transactions[0]->request->size;
cc75061a 1070 for (count = 1; count < n && count < max_batch_count; count++) {
6fd6ed71 1071 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
cc75061a
BP
1072 break;
1073 }
6fd6ed71 1074 bytes += transactions[count]->request->size;
cc75061a
BP
1075 }
1076
1077 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
1078 transactions += done;
1079 n -= done;
1080
1081 if (error == ENOBUFS) {
1082 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
1083 } else if (error) {
10a89ef0 1084 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
cc75061a 1085 nl_sock_record_errors__(transactions, n, error);
b937e116
BP
1086 if (error != EAGAIN) {
1087 /* A fatal error has occurred. Abort the rest of
1088 * transactions. */
1089 break;
1090 }
cc75061a
BP
1091 }
1092 }
1093}
1094
022ad2b9 1095static int
cc75061a
BP
1096nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
1097 struct ofpbuf **replyp)
2fe27d5a 1098{
cc75061a
BP
1099 struct nl_transaction *transactionp;
1100 struct nl_transaction transaction;
2fe27d5a 1101
ebc56baa 1102 transaction.request = CONST_CAST(struct ofpbuf *, request);
72d32ac0 1103 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
cc75061a 1104 transactionp = &transaction;
72d32ac0 1105
cc75061a 1106 nl_sock_transact_multiple(sock, &transactionp, 1);
72d32ac0 1107
2fe27d5a 1108 if (replyp) {
72d32ac0
BP
1109 if (transaction.error) {
1110 ofpbuf_delete(transaction.reply);
1111 *replyp = NULL;
1112 } else {
1113 *replyp = transaction.reply;
1114 }
2fe27d5a 1115 }
72d32ac0 1116
cc75061a 1117 return transaction.error;
2fe27d5a
BP
1118}
1119
6b7c12fd
BP
1120/* Drain all the messages currently in 'sock''s receive queue. */
1121int
1122nl_sock_drain(struct nl_sock *sock)
1123{
22326ba6
AS
1124#ifdef _WIN32
1125 return 0;
1126#else
6b7c12fd 1127 return drain_rcvbuf(sock->fd);
22326ba6 1128#endif
6b7c12fd
BP
1129}
1130
a88b4e04
BP
1131/* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
1132 * Netlink socket created with the given 'protocol', and initializes 'dump' to
1133 * reflect the state of the operation.
2fe27d5a 1134 *
db1fc210
JS
1135 * 'request' must contain a Netlink message. Before sending the message,
1136 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
1137 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
1138 * nlmsg_flags.
2fe27d5a 1139 *
a88b4e04 1140 * The design of this Netlink socket library ensures that the dump is reliable.
2fe27d5a 1141 *
db1fc210
JS
1142 * This function provides no status indication. nl_dump_done() provides an
1143 * error status for the entire dump operation.
2fe27d5a 1144 *
db1fc210 1145 * The caller must eventually destroy 'request'.
2fe27d5a
BP
1146 */
1147void
a88b4e04 1148nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
2fe27d5a 1149{
7d7447df 1150 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
93295354
BP
1151
1152 ovs_mutex_init(&dump->mutex);
1153 ovs_mutex_lock(&dump->mutex);
1154 dump->status = nl_pool_alloc(protocol, &dump->sock);
1155 if (!dump->status) {
1156 dump->status = nl_sock_send__(dump->sock, request,
1157 nl_sock_allocate_seq(dump->sock, 1),
1158 true);
b2d1c78a 1159 }
9c8ad495 1160 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
93295354
BP
1161 ovs_mutex_unlock(&dump->mutex);
1162}
1163
1164static int
1165nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
1166 OVS_REQUIRES(dump->mutex)
1167{
1168 struct nlmsghdr *nlmsghdr;
1169 int error;
1170
6fd6ed71 1171 while (!buffer->size) {
a86bd14e 1172 error = nl_sock_recv__(dump->sock, buffer, NULL, false);
93295354 1173 if (error) {
1738803a
AW
1174 /* The kernel never blocks providing the results of a dump, so
1175 * error == EAGAIN means that we've read the whole thing, and
1176 * therefore transform it into EOF. (The kernel always provides
1177 * NLMSG_DONE as a sentinel. Some other thread must have received
1178 * that already but not yet signaled it in 'status'.)
1179 *
1180 * Any other error is just an error. */
93295354
BP
1181 return error == EAGAIN ? EOF : error;
1182 }
1183
1184 nlmsghdr = nl_msg_nlmsghdr(buffer);
1185 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
1186 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
1187 nlmsghdr->nlmsg_seq, dump->nl_seq);
1188 ofpbuf_clear(buffer);
1189 }
1190 }
1191
1192 if (nl_msg_nlmsgerr(buffer, &error) && error) {
1193 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
1194 ovs_strerror(error));
1195 ofpbuf_clear(buffer);
1196 return error;
1197 }
1198
1199 return 0;
1200}
1201
1202static int
1203nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1204{
1205 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1206 if (!nlmsghdr) {
1207 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1208 return EPROTO;
1209 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1210 return EOF;
1211 } else {
1212 return 0;
1213 }
2fe27d5a
BP
1214}
1215
d57695d7
JS
1216/* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1217 * have been initialized with nl_dump_start(), and 'buffer' must have been
1218 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
2fe27d5a 1219 *
19aa20a0 1220 * If successful, returns true and points 'reply->data' and
6fd6ed71 1221 * 'reply->size' to the message that was retrieved. The caller must not
19aa20a0
BP
1222 * modify 'reply' (because it points within 'buffer', which will be used by
1223 * future calls to this function).
1224 *
1225 * On failure, returns false and sets 'reply->data' to NULL and
6fd6ed71 1226 * 'reply->size' to 0. Failure might indicate an actual error or merely
19aa20a0
BP
1227 * the end of replies. An error status for the entire dump operation is
1228 * provided when it is completed by calling nl_dump_done().
0672776e
JS
1229 *
1230 * Multiple threads may call this function, passing the same nl_dump, however
1231 * each must provide independent buffers. This function may cache multiple
1232 * replies in the buffer, and these will be processed before more replies are
1233 * fetched. When this function returns false, other threads may continue to
1234 * process replies in their buffers, but they will not fetch more replies.
2fe27d5a
BP
1235 */
1236bool
d57695d7 1237nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
2fe27d5a 1238{
93295354 1239 int retval = 0;
0672776e 1240
93295354
BP
1241 /* If the buffer is empty, refill it.
1242 *
1243 * If the buffer is not empty, we don't check the dump's status.
1244 * Otherwise, we could end up skipping some of the dump results if thread A
1245 * hits EOF while thread B is in the midst of processing a batch. */
6fd6ed71 1246 if (!buffer->size) {
0791315e 1247 ovs_mutex_lock(&dump->mutex);
93295354
BP
1248 if (!dump->status) {
1249 /* Take the mutex here to avoid an in-kernel race. If two threads
1250 * try to read from a Netlink dump socket at once, then the socket
1251 * error can be set to EINVAL, which will be encountered on the
1252 * next recv on that socket, which could be anywhere due to the way
1253 * that we pool Netlink sockets. Serializing the recv calls avoids
1254 * the issue. */
1255 dump->status = nl_dump_refill(dump, buffer);
1256 }
1257 retval = dump->status;
0791315e 1258 ovs_mutex_unlock(&dump->mutex);
93295354 1259 }
0791315e 1260
93295354
BP
1261 /* Fetch the next message from the buffer. */
1262 if (!retval) {
1263 retval = nl_dump_next__(reply, buffer);
2fe27d5a 1264 if (retval) {
93295354
BP
1265 /* Record 'retval' as the dump status, but don't overwrite an error
1266 * with EOF. */
1267 ovs_mutex_lock(&dump->mutex);
1268 if (dump->status <= 0) {
1269 dump->status = retval;
2fe27d5a 1270 }
93295354 1271 ovs_mutex_unlock(&dump->mutex);
2fe27d5a 1272 }
2fe27d5a
BP
1273 }
1274
93295354 1275 if (retval) {
6fd6ed71
PS
1276 reply->data = NULL;
1277 reply->size = 0;
0672776e 1278 }
93295354 1279 return !retval;
2fe27d5a
BP
1280}
1281
1282/* Completes Netlink dump operation 'dump', which must have been initialized
1283 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1284 * otherwise a positive errno value describing the problem. */
1285int
1286nl_dump_done(struct nl_dump *dump)
1287{
0672776e 1288 int status;
d57695d7 1289
93295354
BP
1290 ovs_mutex_lock(&dump->mutex);
1291 status = dump->status;
1292 ovs_mutex_unlock(&dump->mutex);
1293
2fe27d5a 1294 /* Drain any remaining messages that the client didn't read. Otherwise the
a88b4e04
BP
1295 * kernel will continue to queue them up and waste buffer space.
1296 *
1297 * XXX We could just destroy and discard the socket in this case. */
0672776e
JS
1298 if (!status) {
1299 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1300 struct ofpbuf reply, buf;
1301
1302 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1303 while (nl_dump_next(dump, &reply, &buf)) {
1304 /* Nothing to do. */
2fe27d5a 1305 }
0672776e 1306 ofpbuf_uninit(&buf);
93295354
BP
1307
1308 ovs_mutex_lock(&dump->mutex);
1309 status = dump->status;
1310 ovs_mutex_unlock(&dump->mutex);
1311 ovs_assert(status);
2fe27d5a 1312 }
93295354 1313
a88b4e04 1314 nl_pool_release(dump->sock);
0791315e 1315 ovs_mutex_destroy(&dump->mutex);
93295354
BP
1316
1317 return status == EOF ? 0 : status;
2fe27d5a
BP
1318}
1319
7fa09611
EE
1320#ifdef _WIN32
1321/* Pend an I/O request in the driver. The driver completes the I/O whenever
1322 * an event or a packet is ready to be read. Once the I/O is completed
1323 * the overlapped structure event associated with the pending I/O will be set
1324 */
1325static int
8341662d 1326pend_io_request(struct nl_sock *sock)
7fa09611
EE
1327{
1328 struct ofpbuf request;
1329 uint64_t request_stub[128];
1330 struct ovs_header *ovs_header;
1331 struct nlmsghdr *nlmsg;
1332 uint32_t seq;
b91d3d03 1333 int retval = 0;
7fa09611
EE
1334 int error;
1335 DWORD bytes;
64513e68 1336 OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
b91d3d03
NR
1337 uint16_t cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ;
1338
1339 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET ||
1340 sock->read_ioctl == OVS_IOCTL_READ_EVENT);
1341 if (sock->read_ioctl == OVS_IOCTL_READ_EVENT) {
1342 cmd = OVS_CTRL_CMD_WIN_PEND_REQ;
1343 }
7fa09611
EE
1344
1345 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1346 sizeof (struct ovs_header);
1347
1348 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1349
1350 seq = nl_sock_allocate_seq(sock, 1);
1351 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
b91d3d03 1352 cmd, OVS_WIN_CONTROL_VERSION);
7fa09611
EE
1353 nlmsg = nl_msg_nlmsghdr(&request);
1354 nlmsg->nlmsg_seq = seq;
92a5068f 1355 nlmsg->nlmsg_pid = sock->pid;
7fa09611
EE
1356
1357 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1358 ovs_header->dp_ifindex = 0;
e6b298ef 1359 nlmsg->nlmsg_len = request.size;
7fa09611
EE
1360
1361 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
6fd6ed71 1362 request.data, request.size,
7fa09611
EE
1363 NULL, 0, &bytes, overlapped)) {
1364 error = GetLastError();
1365 /* Check if the I/O got pended */
1366 if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
d553dd54 1367 lost_communication(error);
7fa09611
EE
1368 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1369 retval = EINVAL;
7fa09611
EE
1370 }
1371 } else {
b91d3d03 1372 retval = EAGAIN;
7fa09611 1373 }
7fa09611
EE
1374
1375done:
1376 ofpbuf_uninit(&request);
1377 return retval;
1378}
1379#endif /* _WIN32 */
1380
2fe27d5a 1381/* Causes poll_block() to wake up when any of the specified 'events' (which is
8341662d
NR
1382 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'.
1383 * On Windows, 'sock' is not treated as const, and may be modified. */
2fe27d5a
BP
1384void
1385nl_sock_wait(const struct nl_sock *sock, short int events)
1386{
22326ba6 1387#ifdef _WIN32
7fa09611 1388 if (sock->overlapped.Internal != STATUS_PENDING) {
b91d3d03
NR
1389 int ret = pend_io_request(CONST_CAST(struct nl_sock *, sock));
1390 if (ret == 0) {
1391 poll_wevent_wait(sock->overlapped.hEvent);
1392 } else {
1393 poll_immediate_wake();
1394 }
1395 } else {
1396 poll_wevent_wait(sock->overlapped.hEvent);
7fa09611 1397 }
22326ba6 1398#else
2fe27d5a 1399 poll_fd_wait(sock->fd, events);
22326ba6 1400#endif
2fe27d5a 1401}
50802adb 1402
9667de98 1403#ifndef _WIN32
8522ba09
BP
1404/* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1405 * that can't use nl_sock_wait().
1406 *
1407 * It's a little tricky to use the returned fd correctly, because nl_sock does
1408 * "copy on write" to allow a single nl_sock to be used for notifications,
1409 * transactions, and dumps. If 'sock' is used only for notifications and
1410 * transactions (and never for dump) then the usage is safe. */
1411int
1412nl_sock_fd(const struct nl_sock *sock)
1413{
1414 return sock->fd;
1415}
9667de98 1416#endif
8522ba09 1417
50802adb
JG
1418/* Returns the PID associated with this socket. */
1419uint32_t
1420nl_sock_pid(const struct nl_sock *sock)
1421{
1422 return sock->pid;
1423}
2fe27d5a
BP
1424\f
1425/* Miscellaneous. */
1426
2ad204c8
BP
1427struct genl_family {
1428 struct hmap_node hmap_node;
1429 uint16_t id;
1430 char *name;
1431};
1432
1433static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1434
2fe27d5a
BP
1435static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1436 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
213a13ed 1437 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
2fe27d5a
BP
1438};
1439
2ad204c8
BP
1440static struct genl_family *
1441find_genl_family_by_id(uint16_t id)
1442{
1443 struct genl_family *family;
1444
1445 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1446 &genl_families) {
1447 if (family->id == id) {
1448 return family;
1449 }
1450 }
1451 return NULL;
1452}
1453
1454static void
1455define_genl_family(uint16_t id, const char *name)
1456{
1457 struct genl_family *family = find_genl_family_by_id(id);
1458
1459 if (family) {
1460 if (!strcmp(family->name, name)) {
1461 return;
1462 }
1463 free(family->name);
1464 } else {
1465 family = xmalloc(sizeof *family);
1466 family->id = id;
1467 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1468 }
1469 family->name = xstrdup(name);
1470}
1471
1472static const char *
1473genl_family_to_name(uint16_t id)
1474{
1475 if (id == GENL_ID_CTRL) {
1476 return "control";
1477 } else {
1478 struct genl_family *family = find_genl_family_by_id(id);
1479 return family ? family->name : "unknown";
1480 }
1481}
1482
b3fca8a8 1483#ifndef _WIN32
e408762f 1484static int
2a477244
BP
1485do_lookup_genl_family(const char *name, struct nlattr **attrs,
1486 struct ofpbuf **replyp)
2fe27d5a
BP
1487{
1488 struct nl_sock *sock;
1489 struct ofpbuf request, *reply;
2a477244 1490 int error;
2fe27d5a 1491
2a477244
BP
1492 *replyp = NULL;
1493 error = nl_sock_create(NETLINK_GENERIC, &sock);
1494 if (error) {
1495 return error;
2fe27d5a
BP
1496 }
1497
1498 ofpbuf_init(&request, 0);
1499 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1500 CTRL_CMD_GETFAMILY, 1);
1501 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
2a477244 1502 error = nl_sock_transact(sock, &request, &reply);
2fe27d5a 1503 ofpbuf_uninit(&request);
2a477244 1504 if (error) {
2fe27d5a 1505 nl_sock_destroy(sock);
2a477244 1506 return error;
2fe27d5a
BP
1507 }
1508
1509 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
2a477244
BP
1510 family_policy, attrs, ARRAY_SIZE(family_policy))
1511 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
2fe27d5a
BP
1512 nl_sock_destroy(sock);
1513 ofpbuf_delete(reply);
2a477244 1514 return EPROTO;
2fe27d5a
BP
1515 }
1516
2fe27d5a 1517 nl_sock_destroy(sock);
2a477244
BP
1518 *replyp = reply;
1519 return 0;
2fe27d5a 1520}
b3fca8a8
NR
1521#else
1522static int
1523do_lookup_genl_family(const char *name, struct nlattr **attrs,
1524 struct ofpbuf **replyp)
1525{
4c484aca 1526 struct nlmsghdr *nlmsg;
b3fca8a8
NR
1527 struct ofpbuf *reply;
1528 int error;
1529 uint16_t family_id;
1530 const char *family_name;
1531 uint32_t family_version;
1532 uint32_t family_attrmax;
4c484aca
NR
1533 uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1534 const char *mcgrp_name = NULL;
b3fca8a8
NR
1535
1536 *replyp = NULL;
1537 reply = ofpbuf_new(1024);
1538
4c484aca 1539 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
b3fca8a8
NR
1540 if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1541 family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1542 family_name = OVS_WIN_CONTROL_FAMILY;
1543 family_version = OVS_WIN_CONTROL_VERSION;
1544 family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1545 } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1546 family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1547 family_name = OVS_DATAPATH_FAMILY;
1548 family_version = OVS_DATAPATH_VERSION;
1549 family_attrmax = OVS_DP_ATTR_MAX;
1550 } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1551 family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1552 family_name = OVS_PACKET_FAMILY;
1553 family_version = OVS_PACKET_VERSION;
1554 family_attrmax = OVS_PACKET_ATTR_MAX;
1555 } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1556 family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1557 family_name = OVS_VPORT_FAMILY;
1558 family_version = OVS_VPORT_VERSION;
1559 family_attrmax = OVS_VPORT_ATTR_MAX;
4c484aca
NR
1560 mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1561 mcgrp_name = OVS_VPORT_MCGROUP;
b3fca8a8
NR
1562 } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1563 family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1564 family_name = OVS_FLOW_FAMILY;
1565 family_version = OVS_FLOW_VERSION;
1566 family_attrmax = OVS_FLOW_ATTR_MAX;
83cc9d56
NR
1567 } else if (!strcmp(name, OVS_WIN_NETDEV_FAMILY)) {
1568 family_id = OVS_WIN_NL_NETDEV_FAMILY_ID;
1569 family_name = OVS_WIN_NETDEV_FAMILY;
1570 family_version = OVS_WIN_NETDEV_VERSION;
1571 family_attrmax = OVS_WIN_NETDEV_ATTR_MAX;
b3fca8a8
NR
1572 } else {
1573 ofpbuf_delete(reply);
1574 return EINVAL;
1575 }
1576
1577 nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1578 CTRL_CMD_NEWFAMILY, family_version);
1579 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1580 * callers do not seem to need them. */
1581 nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1582 nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1583 nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1584 nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1585
4c484aca
NR
1586 if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1587 size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1588 size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1589 OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1590 nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1591 ovs_assert(mcgrp_name != NULL);
1592 nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1593 nl_msg_end_nested(reply, mcgrp_ofs2);
1594 nl_msg_end_nested(reply, mcgrp_ofs1);
1595 }
1596
1597 /* Set the total length of the netlink message. */
1598 nlmsg = nl_msg_nlmsghdr(reply);
6fd6ed71 1599 nlmsg->nlmsg_len = reply->size;
4c484aca 1600
b3fca8a8
NR
1601 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1602 family_policy, attrs, ARRAY_SIZE(family_policy))
1603 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
b3fca8a8
NR
1604 ofpbuf_delete(reply);
1605 return EPROTO;
1606 }
1607
1608 *replyp = reply;
1609 return 0;
1610}
1611#endif
2fe27d5a 1612
e408762f
EJ
1613/* Finds the multicast group called 'group_name' in genl family 'family_name'.
1614 * When successful, writes its result to 'multicast_group' and returns 0.
213a13ed 1615 * Otherwise, clears 'multicast_group' and returns a positive error code.
b3dcb73c 1616 */
e408762f
EJ
1617int
1618nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
b3dcb73c 1619 unsigned int *multicast_group)
e408762f
EJ
1620{
1621 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
6d23c6f4 1622 const struct nlattr *mc;
2a477244 1623 struct ofpbuf *reply;
e408762f 1624 unsigned int left;
2a477244 1625 int error;
e408762f
EJ
1626
1627 *multicast_group = 0;
2a477244
BP
1628 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1629 if (error) {
1630 return error;
e408762f
EJ
1631 }
1632
213a13ed 1633 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
b3dcb73c 1634 error = EPROTO;
213a13ed
EJ
1635 goto exit;
1636 }
1637
6d23c6f4 1638 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
e408762f
EJ
1639 static const struct nl_policy mc_policy[] = {
1640 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1641 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1642 };
1643
1644 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1645 const char *mc_name;
1646
1647 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
2a477244
BP
1648 error = EPROTO;
1649 goto exit;
e408762f
EJ
1650 }
1651
1652 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1653 if (!strcmp(group_name, mc_name)) {
1654 *multicast_group =
1655 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
2a477244
BP
1656 error = 0;
1657 goto exit;
e408762f
EJ
1658 }
1659 }
2a477244 1660 error = EPROTO;
e408762f 1661
2a477244
BP
1662exit:
1663 ofpbuf_delete(reply);
1664 return error;
e408762f
EJ
1665}
1666
2fe27d5a
BP
1667/* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1668 * number and stores it in '*number'. If successful, returns 0 and the caller
1669 * may use '*number' as the family number. On failure, returns a positive
1670 * errno value and '*number' caches the errno value. */
1671int
1672nl_lookup_genl_family(const char *name, int *number)
1673{
1674 if (*number == 0) {
2a477244
BP
1675 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1676 struct ofpbuf *reply;
1677 int error;
1678
1679 error = do_lookup_genl_family(name, attrs, &reply);
1680 if (!error) {
1681 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1682 define_genl_family(*number, name);
1683 } else {
1684 *number = -error;
1685 }
1686 ofpbuf_delete(reply);
1687
cb22974d 1688 ovs_assert(*number != 0);
2fe27d5a
BP
1689 }
1690 return *number > 0 ? 0 : -*number;
1691}
a88b4e04
BP
1692\f
1693struct nl_pool {
1694 struct nl_sock *socks[16];
1695 int n;
1696};
1697
834d6caf 1698static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
97be1538 1699static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
a88b4e04
BP
1700
1701static int
1702nl_pool_alloc(int protocol, struct nl_sock **sockp)
1703{
0bd01224 1704 struct nl_sock *sock = NULL;
a88b4e04
BP
1705 struct nl_pool *pool;
1706
1707 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1708
97be1538 1709 ovs_mutex_lock(&pool_mutex);
a88b4e04
BP
1710 pool = &pools[protocol];
1711 if (pool->n > 0) {
0bd01224
BP
1712 sock = pool->socks[--pool->n];
1713 }
97be1538 1714 ovs_mutex_unlock(&pool_mutex);
0bd01224
BP
1715
1716 if (sock) {
1717 *sockp = sock;
a88b4e04
BP
1718 return 0;
1719 } else {
1720 return nl_sock_create(protocol, sockp);
1721 }
1722}
1723
1724static void
1725nl_pool_release(struct nl_sock *sock)
1726{
1727 if (sock) {
1728 struct nl_pool *pool = &pools[sock->protocol];
1729
97be1538 1730 ovs_mutex_lock(&pool_mutex);
a88b4e04
BP
1731 if (pool->n < ARRAY_SIZE(pool->socks)) {
1732 pool->socks[pool->n++] = sock;
0bd01224 1733 sock = NULL;
a88b4e04 1734 }
97be1538 1735 ovs_mutex_unlock(&pool_mutex);
0bd01224
BP
1736
1737 nl_sock_destroy(sock);
a88b4e04
BP
1738 }
1739}
1740
022ad2b9
BP
1741/* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1742 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1743 * successful, returns 0. On failure, returns a positive errno value.
1744 *
1745 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1746 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1747 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1748 * reply, if any, is discarded.
1749 *
1750 * Before the message is sent, nlmsg_len in 'request' will be finalized to
6fd6ed71 1751 * match msg->size, nlmsg_pid will be set to the pid of the socket used
022ad2b9
BP
1752 * for sending the request, and nlmsg_seq will be initialized.
1753 *
1754 * The caller is responsible for destroying 'request'.
1755 *
1756 * Bare Netlink is an unreliable transport protocol. This function layers
1757 * reliable delivery and reply semantics on top of bare Netlink.
1758 *
1759 * In Netlink, sending a request to the kernel is reliable enough, because the
1760 * kernel will tell us if the message cannot be queued (and we will in that
1761 * case put it on the transmit queue and wait until it can be delivered).
1762 *
1763 * Receiving the reply is the real problem: if the socket buffer is full when
1764 * the kernel tries to send the reply, the reply will be dropped. However, the
1765 * kernel sets a flag that a reply has been dropped. The next call to recv
1766 * then returns ENOBUFS. We can then re-send the request.
1767 *
1768 * Caveats:
1769 *
1770 * 1. Netlink depends on sequence numbers to match up requests and
1771 * replies. The sender of a request supplies a sequence number, and
1772 * the reply echos back that sequence number.
1773 *
1774 * This is fine, but (1) some kernel netlink implementations are
1775 * broken, in that they fail to echo sequence numbers and (2) this
1776 * function will drop packets with non-matching sequence numbers, so
1777 * that only a single request can be usefully transacted at a time.
1778 *
1779 * 2. Resending the request causes it to be re-executed, so the request
1780 * needs to be idempotent.
1781 */
a88b4e04
BP
1782int
1783nl_transact(int protocol, const struct ofpbuf *request,
1784 struct ofpbuf **replyp)
1785{
1786 struct nl_sock *sock;
1787 int error;
1788
1789 error = nl_pool_alloc(protocol, &sock);
1790 if (error) {
d9c194a1
RD
1791 if (replyp) {
1792 *replyp = NULL;
1793 }
a88b4e04
BP
1794 return error;
1795 }
1796
1797 error = nl_sock_transact(sock, request, replyp);
1798
1799 nl_pool_release(sock);
1800 return error;
1801}
1802
022ad2b9
BP
1803/* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1804 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1805 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1806 * the 'error' member of each transaction with 0 if it was successful,
1807 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1808 * be filled with the reply if the message receives a detailed reply. In other
1809 * cases, i.e. where the request failed or had no reply beyond an indication of
1810 * success, 'reply' will be cleared if it is nonnull.
1811 *
1812 * The caller is responsible for destroying each request and reply, and the
1813 * transactions array itself.
1814 *
1815 * Before sending each message, this function will finalize nlmsg_len in each
1816 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1817 * used for the transaction, and initialize nlmsg_seq.
1818 *
1819 * Bare Netlink is an unreliable transport protocol. This function layers
1820 * reliable delivery and reply semantics on top of bare Netlink. See
1821 * nl_transact() for some caveats.
1822 */
a88b4e04
BP
1823void
1824nl_transact_multiple(int protocol,
1825 struct nl_transaction **transactions, size_t n)
1826{
1827 struct nl_sock *sock;
1828 int error;
1829
1830 error = nl_pool_alloc(protocol, &sock);
1831 if (!error) {
1832 nl_sock_transact_multiple(sock, transactions, n);
1833 nl_pool_release(sock);
1834 } else {
1835 nl_sock_record_errors__(transactions, n, error);
1836 }
1837}
1838
2fe27d5a 1839\f
7d7447df
BP
1840static uint32_t
1841nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1842{
1843 uint32_t seq = sock->next_seq;
1844
1845 sock->next_seq += n;
1846
1847 /* Make it impossible for the next request for sequence numbers to wrap
1848 * around to 0. Start over with 1 to avoid ever using a sequence number of
1849 * 0, because the kernel uses sequence number 0 for notifications. */
1850 if (sock->next_seq >= UINT32_MAX / 2) {
1851 sock->next_seq = 1;
1852 }
1853
1854 return seq;
1855}
1856
2fe27d5a 1857static void
2ad204c8 1858nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
2fe27d5a
BP
1859{
1860 struct nlmsg_flag {
1861 unsigned int bits;
1862 const char *name;
1863 };
1864 static const struct nlmsg_flag flags[] = {
1865 { NLM_F_REQUEST, "REQUEST" },
1866 { NLM_F_MULTI, "MULTI" },
1867 { NLM_F_ACK, "ACK" },
1868 { NLM_F_ECHO, "ECHO" },
1869 { NLM_F_DUMP, "DUMP" },
1870 { NLM_F_ROOT, "ROOT" },
1871 { NLM_F_MATCH, "MATCH" },
1872 { NLM_F_ATOMIC, "ATOMIC" },
1873 };
1874 const struct nlmsg_flag *flag;
1875 uint16_t flags_left;
1876
1877 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1878 h->nlmsg_len, h->nlmsg_type);
1879 if (h->nlmsg_type == NLMSG_NOOP) {
1880 ds_put_cstr(ds, "(no-op)");
1881 } else if (h->nlmsg_type == NLMSG_ERROR) {
1882 ds_put_cstr(ds, "(error)");
1883 } else if (h->nlmsg_type == NLMSG_DONE) {
1884 ds_put_cstr(ds, "(done)");
1885 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1886 ds_put_cstr(ds, "(overrun)");
1887 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1888 ds_put_cstr(ds, "(reserved)");
2ad204c8
BP
1889 } else if (protocol == NETLINK_GENERIC) {
1890 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
2fe27d5a
BP
1891 } else {
1892 ds_put_cstr(ds, "(family-defined)");
1893 }
1894 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1895 flags_left = h->nlmsg_flags;
1896 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1897 if ((flags_left & flag->bits) == flag->bits) {
1898 ds_put_format(ds, "[%s]", flag->name);
1899 flags_left &= ~flag->bits;
1900 }
1901 }
1902 if (flags_left) {
1903 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1904 }
2c5a6834
BP
1905 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1906 h->nlmsg_seq, h->nlmsg_pid);
2fe27d5a
BP
1907}
1908
1909static char *
7041c3a9 1910nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
2fe27d5a
BP
1911{
1912 struct ds ds = DS_EMPTY_INITIALIZER;
1913 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1914 if (h) {
2ad204c8 1915 nlmsghdr_to_string(h, protocol, &ds);
2fe27d5a
BP
1916 if (h->nlmsg_type == NLMSG_ERROR) {
1917 const struct nlmsgerr *e;
1918 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1919 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1920 if (e) {
1921 ds_put_format(&ds, " error(%d", e->error);
1922 if (e->error < 0) {
10a89ef0 1923 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
2fe27d5a
BP
1924 }
1925 ds_put_cstr(&ds, ", in-reply-to(");
2ad204c8 1926 nlmsghdr_to_string(&e->msg, protocol, &ds);
2fe27d5a
BP
1927 ds_put_cstr(&ds, "))");
1928 } else {
1929 ds_put_cstr(&ds, " error(truncated)");
1930 }
1931 } else if (h->nlmsg_type == NLMSG_DONE) {
1932 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1933 if (error) {
1934 ds_put_format(&ds, " done(%d", *error);
1935 if (*error < 0) {
10a89ef0 1936 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
2fe27d5a
BP
1937 }
1938 ds_put_cstr(&ds, ")");
1939 } else {
1940 ds_put_cstr(&ds, " done(truncated)");
1941 }
7041c3a9
BP
1942 } else if (protocol == NETLINK_GENERIC) {
1943 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1944 if (genl) {
1945 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1946 genl->cmd, genl->version);
1947 }
2fe27d5a
BP
1948 }
1949 } else {
1950 ds_put_cstr(&ds, "nl(truncated)");
1951 }
1952 return ds.string;
1953}
1954
1955static void
1956log_nlmsg(const char *function, int error,
7041c3a9 1957 const void *message, size_t size, int protocol)
2fe27d5a 1958{
2fe27d5a
BP
1959 if (!VLOG_IS_DBG_ENABLED()) {
1960 return;
1961 }
1962
0a2869d5
BP
1963 struct ofpbuf buffer = ofpbuf_const_initializer(message, size);
1964 char *nlmsg = nlmsg_to_string(&buffer, protocol);
10a89ef0 1965 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
2fe27d5a
BP
1966 free(nlmsg);
1967}