]> git.proxmox.com Git - mirror_ovs.git/blame - lib/netlink-socket.c
netlink-socket: Adapt to Windows and MSVC.
[mirror_ovs.git] / lib / netlink-socket.c
CommitLineData
2fe27d5a 1/*
db1fc210 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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>
22#include <sys/types.h>
cc75061a 23#include <sys/uio.h>
2fe27d5a
BP
24#include <unistd.h>
25#include "coverage.h"
26#include "dynamic-string.h"
2ad204c8
BP
27#include "hash.h"
28#include "hmap.h"
2fe27d5a
BP
29#include "netlink.h"
30#include "netlink-protocol.h"
31#include "ofpbuf.h"
0bd01224 32#include "ovs-thread.h"
2fe27d5a 33#include "poll-loop.h"
0672776e 34#include "seq.h"
6b7c12fd 35#include "socket-util.h"
cc75061a 36#include "util.h"
2fe27d5a
BP
37#include "vlog.h"
38
39VLOG_DEFINE_THIS_MODULE(netlink_socket);
40
41COVERAGE_DEFINE(netlink_overflow);
42COVERAGE_DEFINE(netlink_received);
fc999dda 43COVERAGE_DEFINE(netlink_recv_jumbo);
2fe27d5a
BP
44COVERAGE_DEFINE(netlink_sent);
45
46/* Linux header file confusion causes this to be undefined. */
47#ifndef SOL_NETLINK
48#define SOL_NETLINK 270
49#endif
50
22326ba6
AS
51#ifdef _WIN32
52static struct ovs_mutex portid_mutex = OVS_MUTEX_INITIALIZER;
53static uint32_t g_last_portid = 0;
54
55/* Port IDs must be unique! */
56static uint32_t
57portid_next(void)
58 OVS_GUARDED_BY(portid_mutex)
59{
60 g_last_portid++;
61 return g_last_portid;
62}
63
64static void
65set_sock_pid_in_kernel(HANDLE handle, uint32_t pid)
66 OVS_GUARDED_BY(portid_mutex)
67{
68 struct nlmsghdr msg = { 0 };
69
70 msg.nlmsg_len = sizeof(struct nlmsghdr);
71 msg.nlmsg_type = 80; /* target = set file pid */
72 msg.nlmsg_flags = 0;
73 msg.nlmsg_seq = 0;
74 msg.nlmsg_pid = pid;
75
76 WriteFile(handle, &msg, sizeof(struct nlmsghdr), NULL, NULL);
77}
78#endif /* _WIN32 */
79
2fe27d5a
BP
80/* A single (bad) Netlink message can in theory dump out many, many log
81 * messages, so the burst size is set quite high here to avoid missing useful
82 * information. Also, at high logging levels we log *all* Netlink messages. */
83static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
84
7d7447df 85static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
2fe27d5a 86static void log_nlmsg(const char *function, int error,
7041c3a9 87 const void *message, size_t size, int protocol);
2fe27d5a
BP
88\f
89/* Netlink sockets. */
90
0d121c73 91struct nl_sock {
22326ba6
AS
92#ifdef _WIN32
93 HANDLE handle;
94#else
2fe27d5a 95 int fd;
22326ba6 96#endif
7d7447df 97 uint32_t next_seq;
2fe27d5a 98 uint32_t pid;
7041c3a9 99 int protocol;
cc75061a 100 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
2fe27d5a
BP
101};
102
cc75061a
BP
103/* Compile-time limit on iovecs, so that we can allocate a maximum-size array
104 * of iovecs on the stack. */
105#define MAX_IOVS 128
106
107/* Maximum number of iovecs that may be passed to sendmsg, capped at a
108 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
109 *
110 * Initialized by nl_sock_create(). */
111static int max_iovs;
112
a88b4e04
BP
113static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
114static void nl_pool_release(struct nl_sock *);
2fe27d5a
BP
115
116/* Creates a new netlink socket for the given netlink 'protocol'
117 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
a88b4e04 118 * new socket if successful, otherwise returns a positive errno value. */
2fe27d5a 119int
cceb11f5 120nl_sock_create(int protocol, struct nl_sock **sockp)
2fe27d5a 121{
0bd01224 122 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2fe27d5a 123 struct nl_sock *sock;
22326ba6 124#ifndef _WIN32
2fe27d5a 125 struct sockaddr_nl local, remote;
22326ba6 126#endif
2c5a6834 127 socklen_t local_size;
d2b9f5b0 128 int rcvbuf;
2fe27d5a
BP
129 int retval = 0;
130
0bd01224 131 if (ovsthread_once_start(&once)) {
cc75061a
BP
132 int save_errno = errno;
133 errno = 0;
134
135 max_iovs = sysconf(_SC_UIO_MAXIOV);
136 if (max_iovs < _XOPEN_IOV_MAX) {
137 if (max_iovs == -1 && errno) {
10a89ef0 138 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
cc75061a
BP
139 }
140 max_iovs = _XOPEN_IOV_MAX;
141 } else if (max_iovs > MAX_IOVS) {
142 max_iovs = MAX_IOVS;
143 }
144
145 errno = save_errno;
0bd01224 146 ovsthread_once_done(&once);
cc75061a
BP
147 }
148
2fe27d5a 149 *sockp = NULL;
488232b7 150 sock = xmalloc(sizeof *sock);
2fe27d5a 151
22326ba6
AS
152#ifdef _WIN32
153 sock->handle = CreateFileA("\\\\.\\OpenVSwitchDevice",
154 GENERIC_READ | GENERIC_WRITE,
155 FILE_SHARE_READ | FILE_SHARE_WRITE,
156 NULL, OPEN_EXISTING,
157 FILE_ATTRIBUTE_NORMAL, NULL);
158
159 int last_error = GetLastError();
160
161 if (sock->handle == INVALID_HANDLE_VALUE) {
162 VLOG_ERR("fcntl: %s", ovs_strerror(last_error));
163 goto error;
164 }
165#else
2fe27d5a
BP
166 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
167 if (sock->fd < 0) {
10a89ef0 168 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
2fe27d5a
BP
169 goto error;
170 }
22326ba6
AS
171#endif
172
7041c3a9 173 sock->protocol = protocol;
7d7447df 174 sock->next_seq = 1;
2fe27d5a 175
d2b9f5b0 176 rcvbuf = 1024 * 1024;
22326ba6
AS
177#ifdef _WIN32
178 sock->rcvbuf = rcvbuf;
179 ovs_mutex_lock(&portid_mutex);
180 sock->pid = portid_next();
181 set_sock_pid_in_kernel(sock->handle, sock->pid);
182 ovs_mutex_unlock(&portid_mutex);
183#else
d2b9f5b0
BP
184 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
185 &rcvbuf, sizeof rcvbuf)) {
80af5ee5
BP
186 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
187 * Warn only if the failure is therefore unexpected. */
f28b6dd3 188 if (errno != EPERM) {
80af5ee5 189 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
10a89ef0 190 "(%s)", rcvbuf, ovs_strerror(errno));
80af5ee5 191 }
d2b9f5b0
BP
192 }
193
cc75061a
BP
194 retval = get_socket_rcvbuf(sock->fd);
195 if (retval < 0) {
196 retval = -retval;
197 goto error;
198 }
199 sock->rcvbuf = retval;
200
2c5a6834 201 /* Connect to kernel (pid 0) as remote address. */
2fe27d5a
BP
202 memset(&remote, 0, sizeof remote);
203 remote.nl_family = AF_NETLINK;
204 remote.nl_pid = 0;
205 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
10a89ef0 206 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
2c5a6834
BP
207 goto error;
208 }
209
210 /* Obtain pid assigned by kernel. */
211 local_size = sizeof local;
212 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
10a89ef0 213 VLOG_ERR("getsockname: %s", ovs_strerror(errno));
2c5a6834
BP
214 goto error;
215 }
216 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
217 VLOG_ERR("getsockname returned bad Netlink name");
218 retval = EINVAL;
219 goto error;
2fe27d5a 220 }
2c5a6834 221 sock->pid = local.nl_pid;
22326ba6 222#endif
2fe27d5a 223
2fe27d5a
BP
224 *sockp = sock;
225 return 0;
226
2fe27d5a
BP
227error:
228 if (retval == 0) {
229 retval = errno;
230 if (retval == 0) {
231 retval = EINVAL;
232 }
233 }
22326ba6
AS
234#ifdef _WIN32
235 if (sock->handle != INVALID_HANDLE_VALUE) {
236 CloseHandle(sock->handle);
237 }
238#else
2fe27d5a
BP
239 if (sock->fd >= 0) {
240 close(sock->fd);
241 }
22326ba6 242#endif
2fe27d5a
BP
243 free(sock);
244 return retval;
245}
246
c6eab56d
BP
247/* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
248 * sets '*sockp' to the new socket if successful, otherwise returns a positive
249 * errno value. */
250int
251nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
252{
253 return nl_sock_create(src->protocol, sockp);
254}
255
2fe27d5a
BP
256/* Destroys netlink socket 'sock'. */
257void
258nl_sock_destroy(struct nl_sock *sock)
259{
260 if (sock) {
22326ba6
AS
261#ifdef _WIN32
262 CloseHandle(sock->handle);
263#else
a88b4e04 264 close(sock->fd);
22326ba6 265#endif
a88b4e04 266 free(sock);
2fe27d5a
BP
267 }
268}
269
cceb11f5
BP
270/* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
271 * successful, otherwise a positive errno value.
272 *
a838c4fe
BP
273 * A socket that is subscribed to a multicast group that receives asynchronous
274 * notifications must not be used for Netlink transactions or dumps, because
275 * transactions and dumps can cause notifications to be lost.
276 *
cceb11f5
BP
277 * Multicast group numbers are always positive.
278 *
279 * It is not an error to attempt to join a multicast group to which a socket
280 * already belongs. */
281int
282nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
283{
22326ba6
AS
284#ifdef _WIN32
285#define OVS_VPORT_MCGROUP_FALLBACK_ID 33
286 struct ofpbuf msg_buf;
287 struct message_multicast
288 {
289 struct nlmsghdr;
290 /* if true, join; if else, leave */
291 unsigned char join;
292 unsigned int groupId;
293 };
294
295 struct message_multicast msg = { 0 };
296
297 msg.nlmsg_len = sizeof(struct message_multicast);
298 msg.nlmsg_type = OVS_VPORT_MCGROUP_FALLBACK_ID;
299 msg.nlmsg_flags = 0;
300 msg.nlmsg_seq = 0;
301 msg.nlmsg_pid = sock->pid;
302
303 msg.join = 1;
304 msg.groupId = multicast_group;
305 msg_buf.base_ = &msg;
306 msg_buf.data_ = &msg;
307 msg_buf.size_ = msg.nlmsg_len;
308
309 nl_sock_send__(sock, &msg_buf, msg.nlmsg_seq, 0);
310#else
cceb11f5
BP
311 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
312 &multicast_group, sizeof multicast_group) < 0) {
313 VLOG_WARN("could not join multicast group %u (%s)",
10a89ef0 314 multicast_group, ovs_strerror(errno));
cceb11f5
BP
315 return errno;
316 }
22326ba6 317#endif
cceb11f5
BP
318 return 0;
319}
320
321/* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
322 * successful, otherwise a positive errno value.
323 *
324 * Multicast group numbers are always positive.
325 *
326 * It is not an error to attempt to leave a multicast group to which a socket
327 * does not belong.
328 *
329 * On success, reading from 'sock' will still return any messages that were
330 * received on 'multicast_group' before the group was left. */
331int
332nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
333{
22326ba6
AS
334#ifdef _WIN32
335 struct ofpbuf msg_buf;
336 struct message_multicast
337 {
338 struct nlmsghdr;
339 /* if true, join; if else, leave*/
340 unsigned char join;
341 };
342
343 struct message_multicast msg = { 0 };
344 nl_msg_put_nlmsghdr(&msg, sizeof(struct message_multicast),
345 multicast_group, 0);
346 msg.join = 0;
347
348 msg_buf.base_ = &msg;
349 msg_buf.data_ = &msg;
350 msg_buf.size_ = msg.nlmsg_len;
351
352 nl_sock_send__(sock, &msg_buf, msg.nlmsg_seq, 0);
353#else
cceb11f5
BP
354 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
355 &multicast_group, sizeof multicast_group) < 0) {
356 VLOG_WARN("could not leave multicast group %u (%s)",
10a89ef0 357 multicast_group, ovs_strerror(errno));
cceb11f5
BP
358 return errno;
359 }
22326ba6 360#endif
cceb11f5
BP
361 return 0;
362}
363
c6eab56d 364static int
ff459dd6
BP
365nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
366 uint32_t nlmsg_seq, bool wait)
2fe27d5a
BP
367{
368 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
369 int error;
370
1f317cb5 371 nlmsg->nlmsg_len = ofpbuf_size(msg);
ff459dd6 372 nlmsg->nlmsg_seq = nlmsg_seq;
2fe27d5a
BP
373 nlmsg->nlmsg_pid = sock->pid;
374 do {
375 int retval;
22326ba6
AS
376#ifdef _WIN32
377 bool result;
378 DWORD last_error = 0;
379 result = WriteFile(sock->handle, ofpbuf_data(msg), ofpbuf_size(msg),
380 &retval, NULL);
381 last_error = GetLastError();
382 if (last_error != ERROR_SUCCESS && !result) {
383 retval = -1;
384 errno = EAGAIN;
385 }
386#else
1f317cb5 387 retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg), wait ? 0 : MSG_DONTWAIT);
22326ba6 388#endif
2fe27d5a
BP
389 error = retval < 0 ? errno : 0;
390 } while (error == EINTR);
1f317cb5 391 log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
2fe27d5a
BP
392 if (!error) {
393 COVERAGE_INC(netlink_sent);
394 }
395 return error;
396}
397
c6eab56d 398/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
1f317cb5 399 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
ff459dd6
BP
400 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
401 * sequence number, before the message is sent.
c6eab56d
BP
402 *
403 * Returns 0 if successful, otherwise a positive errno value. If
404 * 'wait' is true, then the send will wait until buffer space is ready;
405 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
406int
407nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
ff459dd6
BP
408{
409 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
410}
411
412/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
1f317cb5 413 * 'sock'. nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
ff459dd6
BP
414 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
415 * 'nlmsg_seq', before the message is sent.
416 *
417 * Returns 0 if successful, otherwise a positive errno value. If
418 * 'wait' is true, then the send will wait until buffer space is ready;
419 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
420 *
421 * This function is suitable for sending a reply to a request that was received
422 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
423int
424nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
425 uint32_t nlmsg_seq, bool wait)
c6eab56d 426{
ff459dd6 427 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
c6eab56d
BP
428}
429
c6eab56d 430static int
72d32ac0 431nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
2fe27d5a 432{
72d32ac0
BP
433 /* We can't accurately predict the size of the data to be received. The
434 * caller is supposed to have allocated enough space in 'buf' to handle the
435 * "typical" case. To handle exceptions, we make available enough space in
436 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
437 * figure since that's the maximum length of a Netlink attribute). */
2fe27d5a 438 struct nlmsghdr *nlmsghdr;
22326ba6
AS
439#ifdef _WIN32
440#define MAX_STACK_LENGTH 81920
441 uint8_t tail[MAX_STACK_LENGTH];
442#else
72d32ac0 443 uint8_t tail[65536];
22326ba6 444#endif
fc999dda 445 struct iovec iov[2];
fc999dda
BP
446 struct msghdr msg;
447 ssize_t retval;
8f20fd98 448 int error;
fc999dda 449
cb22974d 450 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
72d32ac0 451 ofpbuf_clear(buf);
2fe27d5a 452
1f317cb5 453 iov[0].iov_base = ofpbuf_base(buf);
72d32ac0 454 iov[0].iov_len = buf->allocated;
fc999dda 455 iov[1].iov_base = tail;
72d32ac0 456 iov[1].iov_len = sizeof tail;
fc999dda
BP
457
458 memset(&msg, 0, sizeof msg);
459 msg.msg_iov = iov;
460 msg.msg_iovlen = 2;
461
8f20fd98
BP
462 /* Receive a Netlink message from the kernel.
463 *
464 * This works around a kernel bug in which the kernel returns an error code
465 * as if it were the number of bytes read. It doesn't actually modify
466 * anything in the receive buffer in that case, so we can initialize the
467 * Netlink header with an impossible message length and then, upon success,
468 * check whether it changed. */
469 nlmsghdr = ofpbuf_base(buf);
2fe27d5a 470 do {
8f20fd98 471 nlmsghdr->nlmsg_len = UINT32_MAX;
22326ba6
AS
472#ifdef _WIN32
473 boolean result = false;
474 DWORD last_error = 0;
475 result = ReadFile(sock->handle, tail, MAX_STACK_LENGTH, &retval, NULL);
476 last_error = GetLastError();
477 if (last_error != ERROR_SUCCESS && !result) {
478 retval = -1;
479 errno = EAGAIN;
480 } else {
481 ofpbuf_put(buf, tail, retval);
482 }
483#else
fc999dda 484 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
22326ba6 485#endif
8f20fd98
BP
486 error = (retval < 0 ? errno
487 : retval == 0 ? ECONNRESET /* not possible? */
488 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
7f8e2646 489 : retval);
8f20fd98
BP
490 } while (error == EINTR);
491 if (error) {
fc999dda
BP
492 if (error == ENOBUFS) {
493 /* Socket receive buffer overflow dropped one or more messages that
494 * the kernel tried to send to us. */
495 COVERAGE_INC(netlink_overflow);
496 }
fc999dda 497 return error;
2fe27d5a 498 }
fc999dda 499
2fe27d5a 500 if (msg.msg_flags & MSG_TRUNC) {
34582733 501 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
72d32ac0 502 sizeof tail);
fc999dda 503 return E2BIG;
2fe27d5a 504 }
2fe27d5a 505
fc999dda 506 if (retval < sizeof *nlmsghdr
2fe27d5a 507 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
fc999dda 508 || nlmsghdr->nlmsg_len > retval) {
e5e4b47c 509 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
72d32ac0 510 retval, sizeof *nlmsghdr);
2fe27d5a
BP
511 return EPROTO;
512 }
22326ba6 513#ifndef _WIN32
1f317cb5 514 ofpbuf_set_size(buf, MIN(retval, buf->allocated));
72d32ac0
BP
515 if (retval > buf->allocated) {
516 COVERAGE_INC(netlink_recv_jumbo);
517 ofpbuf_put(buf, tail, retval - buf->allocated);
518 }
22326ba6 519#endif
72d32ac0 520
1f317cb5 521 log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
2fe27d5a
BP
522 COVERAGE_INC(netlink_received);
523
524 return 0;
525}
526
72d32ac0
BP
527/* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
528 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
529 * EAGAIN if the 'sock' receive buffer is empty.
530 *
531 * The caller must have initialized 'buf' with an allocation of at least
532 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
533 * space for a "typical" message.
534 *
535 * On success, returns 0 and replaces 'buf''s previous content by the received
536 * message. This function expands 'buf''s allocated memory, as necessary, to
537 * hold the actual size of the received message.
c6eab56d 538 *
72d32ac0
BP
539 * On failure, returns a positive errno value and clears 'buf' to zero length.
540 * 'buf' retains its previous memory allocation.
541 *
542 * Regardless of success or failure, this function resets 'buf''s headroom to
543 * 0. */
c6eab56d 544int
72d32ac0 545nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
c6eab56d 546{
72d32ac0 547 return nl_sock_recv__(sock, buf, wait);
cc75061a
BP
548}
549
550static void
551nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
552 int error)
553{
554 size_t i;
555
556 for (i = 0; i < n; i++) {
72d32ac0
BP
557 struct nl_transaction *txn = transactions[i];
558
559 txn->error = error;
560 if (txn->reply) {
561 ofpbuf_clear(txn->reply);
562 }
cc75061a
BP
563 }
564}
565
566static int
567nl_sock_transact_multiple__(struct nl_sock *sock,
568 struct nl_transaction **transactions, size_t n,
569 size_t *done)
570{
72d32ac0
BP
571 uint64_t tmp_reply_stub[1024 / 8];
572 struct nl_transaction tmp_txn;
573 struct ofpbuf tmp_reply;
574
575 uint32_t base_seq;
cc75061a
BP
576 struct iovec iovs[MAX_IOVS];
577 struct msghdr msg;
578 int error;
579 int i;
580
72d32ac0 581 base_seq = nl_sock_allocate_seq(sock, n);
cc75061a
BP
582 *done = 0;
583 for (i = 0; i < n; i++) {
72d32ac0
BP
584 struct nl_transaction *txn = transactions[i];
585 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
cc75061a 586
1f317cb5 587 nlmsg->nlmsg_len = ofpbuf_size(txn->request);
72d32ac0 588 nlmsg->nlmsg_seq = base_seq + i;
cc75061a 589 nlmsg->nlmsg_pid = sock->pid;
cc75061a 590
1f317cb5
PS
591 iovs[i].iov_base = ofpbuf_data(txn->request);
592 iovs[i].iov_len = ofpbuf_size(txn->request);
cc75061a
BP
593 }
594
595 memset(&msg, 0, sizeof msg);
596 msg.msg_iov = iovs;
597 msg.msg_iovlen = n;
598 do {
22326ba6
AS
599#ifdef _WIN32
600 DWORD last_error = 0;
601 bool result = FALSE;
602 for (i = 0; i < n; i++) {
603 result = WriteFile((HANDLE)sock->handle, iovs[i].iov_base, iovs[i].iov_len,
604 &error, NULL);
605 last_error = GetLastError();
606 if (last_error != ERROR_SUCCESS && !result) {
607 error = EAGAIN;
608 errno = EAGAIN;
609 } else {
610 error = 0;
611 }
612 }
613#else
cc75061a 614 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
22326ba6 615#endif
cc75061a
BP
616 } while (error == EINTR);
617
618 for (i = 0; i < n; i++) {
72d32ac0 619 struct nl_transaction *txn = transactions[i];
cc75061a 620
1f317cb5 621 log_nlmsg(__func__, error, ofpbuf_data(txn->request), ofpbuf_size(txn->request),
cc75061a
BP
622 sock->protocol);
623 }
624 if (!error) {
625 COVERAGE_ADD(netlink_sent, n);
626 }
627
628 if (error) {
629 return error;
630 }
631
72d32ac0
BP
632 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
633 tmp_txn.request = NULL;
634 tmp_txn.reply = &tmp_reply;
635 tmp_txn.error = 0;
cc75061a 636 while (n > 0) {
72d32ac0
BP
637 struct nl_transaction *buf_txn, *txn;
638 uint32_t seq;
639
640 /* Find a transaction whose buffer we can use for receiving a reply.
641 * If no such transaction is left, use tmp_txn. */
642 buf_txn = &tmp_txn;
643 for (i = 0; i < n; i++) {
644 if (transactions[i]->reply) {
645 buf_txn = transactions[i];
646 break;
647 }
648 }
cc75061a 649
72d32ac0
BP
650 /* Receive a reply. */
651 error = nl_sock_recv__(sock, buf_txn->reply, false);
652 if (error) {
653 if (error == EAGAIN) {
654 nl_sock_record_errors__(transactions, n, 0);
655 *done += n;
656 error = 0;
657 }
658 break;
cc75061a
BP
659 }
660
72d32ac0
BP
661 /* Match the reply up with a transaction. */
662 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
663 if (seq < base_seq || seq >= base_seq + n) {
664 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
cc75061a
BP
665 continue;
666 }
72d32ac0
BP
667 i = seq - base_seq;
668 txn = transactions[i];
cc75061a 669
72d32ac0
BP
670 /* Fill in the results for 'txn'. */
671 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
672 if (txn->reply) {
673 ofpbuf_clear(txn->reply);
674 }
675 if (txn->error) {
cc75061a 676 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
10a89ef0 677 error, ovs_strerror(txn->error));
cc75061a 678 }
cc75061a 679 } else {
72d32ac0
BP
680 txn->error = 0;
681 if (txn->reply && txn != buf_txn) {
682 /* Swap buffers. */
683 struct ofpbuf *reply = buf_txn->reply;
684 buf_txn->reply = txn->reply;
685 txn->reply = reply;
686 }
cc75061a
BP
687 }
688
72d32ac0
BP
689 /* Fill in the results for transactions before 'txn'. (We have to do
690 * this after the results for 'txn' itself because of the buffer swap
691 * above.) */
692 nl_sock_record_errors__(transactions, i, 0);
693
694 /* Advance. */
cc75061a
BP
695 *done += i + 1;
696 transactions += i + 1;
697 n -= i + 1;
72d32ac0 698 base_seq += i + 1;
cc75061a 699 }
72d32ac0 700 ofpbuf_uninit(&tmp_reply);
cc75061a 701
72d32ac0 702 return error;
cc75061a
BP
703}
704
022ad2b9 705static void
cc75061a
BP
706nl_sock_transact_multiple(struct nl_sock *sock,
707 struct nl_transaction **transactions, size_t n)
708{
709 int max_batch_count;
710 int error;
711
712 if (!n) {
713 return;
714 }
715
cc75061a
BP
716 /* In theory, every request could have a 64 kB reply. But the default and
717 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
718 * be a bit below 128 kB, so that would only allow a single message in a
719 * "batch". So we assume that replies average (at most) 4 kB, which allows
720 * a good deal of batching.
721 *
722 * In practice, most of the requests that we batch either have no reply at
723 * all or a brief reply. */
724 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
725 max_batch_count = MIN(max_batch_count, max_iovs);
726
727 while (n > 0) {
728 size_t count, bytes;
729 size_t done;
730
731 /* Batch up to 'max_batch_count' transactions. But cap it at about a
732 * page of requests total because big skbuffs are expensive to
733 * allocate in the kernel. */
734#if defined(PAGESIZE)
735 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
736#else
737 enum { MAX_BATCH_BYTES = 4096 - 512 };
738#endif
1f317cb5 739 bytes = ofpbuf_size(transactions[0]->request);
cc75061a 740 for (count = 1; count < n && count < max_batch_count; count++) {
1f317cb5 741 if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
cc75061a
BP
742 break;
743 }
1f317cb5 744 bytes += ofpbuf_size(transactions[count]->request);
cc75061a
BP
745 }
746
747 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
748 transactions += done;
749 n -= done;
750
751 if (error == ENOBUFS) {
752 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
753 } else if (error) {
10a89ef0 754 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
cc75061a
BP
755 nl_sock_record_errors__(transactions, n, error);
756 }
757 }
758}
759
022ad2b9 760static int
cc75061a
BP
761nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
762 struct ofpbuf **replyp)
2fe27d5a 763{
cc75061a
BP
764 struct nl_transaction *transactionp;
765 struct nl_transaction transaction;
2fe27d5a 766
ebc56baa 767 transaction.request = CONST_CAST(struct ofpbuf *, request);
72d32ac0 768 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
cc75061a 769 transactionp = &transaction;
72d32ac0 770
cc75061a 771 nl_sock_transact_multiple(sock, &transactionp, 1);
72d32ac0 772
2fe27d5a 773 if (replyp) {
72d32ac0
BP
774 if (transaction.error) {
775 ofpbuf_delete(transaction.reply);
776 *replyp = NULL;
777 } else {
778 *replyp = transaction.reply;
779 }
2fe27d5a 780 }
72d32ac0 781
cc75061a 782 return transaction.error;
2fe27d5a
BP
783}
784
6b7c12fd
BP
785/* Drain all the messages currently in 'sock''s receive queue. */
786int
787nl_sock_drain(struct nl_sock *sock)
788{
22326ba6
AS
789#ifdef _WIN32
790 return 0;
791#else
6b7c12fd 792 return drain_rcvbuf(sock->fd);
22326ba6 793#endif
6b7c12fd
BP
794}
795
a88b4e04
BP
796/* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
797 * Netlink socket created with the given 'protocol', and initializes 'dump' to
798 * reflect the state of the operation.
2fe27d5a 799 *
db1fc210
JS
800 * 'request' must contain a Netlink message. Before sending the message,
801 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
802 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
803 * nlmsg_flags.
2fe27d5a 804 *
a88b4e04 805 * The design of this Netlink socket library ensures that the dump is reliable.
2fe27d5a 806 *
db1fc210
JS
807 * This function provides no status indication. nl_dump_done() provides an
808 * error status for the entire dump operation.
2fe27d5a 809 *
db1fc210 810 * The caller must eventually destroy 'request'.
2fe27d5a
BP
811 */
812void
a88b4e04 813nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
2fe27d5a 814{
7d7447df 815 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
93295354
BP
816
817 ovs_mutex_init(&dump->mutex);
818 ovs_mutex_lock(&dump->mutex);
819 dump->status = nl_pool_alloc(protocol, &dump->sock);
820 if (!dump->status) {
821 dump->status = nl_sock_send__(dump->sock, request,
822 nl_sock_allocate_seq(dump->sock, 1),
823 true);
b2d1c78a 824 }
9c8ad495 825 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
93295354
BP
826 ovs_mutex_unlock(&dump->mutex);
827}
828
829static int
830nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
831 OVS_REQUIRES(dump->mutex)
832{
833 struct nlmsghdr *nlmsghdr;
834 int error;
835
836 while (!ofpbuf_size(buffer)) {
1738803a 837 error = nl_sock_recv__(dump->sock, buffer, false);
93295354 838 if (error) {
1738803a
AW
839 /* The kernel never blocks providing the results of a dump, so
840 * error == EAGAIN means that we've read the whole thing, and
841 * therefore transform it into EOF. (The kernel always provides
842 * NLMSG_DONE as a sentinel. Some other thread must have received
843 * that already but not yet signaled it in 'status'.)
844 *
845 * Any other error is just an error. */
93295354
BP
846 return error == EAGAIN ? EOF : error;
847 }
848
849 nlmsghdr = nl_msg_nlmsghdr(buffer);
850 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
851 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
852 nlmsghdr->nlmsg_seq, dump->nl_seq);
853 ofpbuf_clear(buffer);
854 }
855 }
856
857 if (nl_msg_nlmsgerr(buffer, &error) && error) {
858 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
859 ovs_strerror(error));
860 ofpbuf_clear(buffer);
861 return error;
862 }
863
864 return 0;
865}
866
867static int
868nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
869{
870 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
871 if (!nlmsghdr) {
872 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
873 return EPROTO;
874 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
875 return EOF;
876 } else {
877 return 0;
878 }
2fe27d5a
BP
879}
880
d57695d7
JS
881/* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
882 * have been initialized with nl_dump_start(), and 'buffer' must have been
883 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
2fe27d5a 884 *
19aa20a0
BP
885 * If successful, returns true and points 'reply->data' and
886 * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
887 * modify 'reply' (because it points within 'buffer', which will be used by
888 * future calls to this function).
889 *
890 * On failure, returns false and sets 'reply->data' to NULL and
891 * 'ofpbuf_size(reply)' to 0. Failure might indicate an actual error or merely
892 * the end of replies. An error status for the entire dump operation is
893 * provided when it is completed by calling nl_dump_done().
0672776e
JS
894 *
895 * Multiple threads may call this function, passing the same nl_dump, however
896 * each must provide independent buffers. This function may cache multiple
897 * replies in the buffer, and these will be processed before more replies are
898 * fetched. When this function returns false, other threads may continue to
899 * process replies in their buffers, but they will not fetch more replies.
2fe27d5a
BP
900 */
901bool
d57695d7 902nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
2fe27d5a 903{
93295354 904 int retval = 0;
0672776e 905
93295354
BP
906 /* If the buffer is empty, refill it.
907 *
908 * If the buffer is not empty, we don't check the dump's status.
909 * Otherwise, we could end up skipping some of the dump results if thread A
910 * hits EOF while thread B is in the midst of processing a batch. */
911 if (!ofpbuf_size(buffer)) {
0791315e 912 ovs_mutex_lock(&dump->mutex);
93295354
BP
913 if (!dump->status) {
914 /* Take the mutex here to avoid an in-kernel race. If two threads
915 * try to read from a Netlink dump socket at once, then the socket
916 * error can be set to EINVAL, which will be encountered on the
917 * next recv on that socket, which could be anywhere due to the way
918 * that we pool Netlink sockets. Serializing the recv calls avoids
919 * the issue. */
920 dump->status = nl_dump_refill(dump, buffer);
921 }
922 retval = dump->status;
0791315e 923 ovs_mutex_unlock(&dump->mutex);
93295354 924 }
0791315e 925
93295354
BP
926 /* Fetch the next message from the buffer. */
927 if (!retval) {
928 retval = nl_dump_next__(reply, buffer);
2fe27d5a 929 if (retval) {
93295354
BP
930 /* Record 'retval' as the dump status, but don't overwrite an error
931 * with EOF. */
932 ovs_mutex_lock(&dump->mutex);
933 if (dump->status <= 0) {
934 dump->status = retval;
2fe27d5a 935 }
93295354 936 ovs_mutex_unlock(&dump->mutex);
2fe27d5a 937 }
2fe27d5a
BP
938 }
939
93295354
BP
940 if (retval) {
941 ofpbuf_set_data(reply, NULL);
942 ofpbuf_set_size(reply, 0);
0672776e 943 }
93295354 944 return !retval;
2fe27d5a
BP
945}
946
947/* Completes Netlink dump operation 'dump', which must have been initialized
948 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
949 * otherwise a positive errno value describing the problem. */
950int
951nl_dump_done(struct nl_dump *dump)
952{
0672776e 953 int status;
d57695d7 954
93295354
BP
955 ovs_mutex_lock(&dump->mutex);
956 status = dump->status;
957 ovs_mutex_unlock(&dump->mutex);
958
2fe27d5a 959 /* Drain any remaining messages that the client didn't read. Otherwise the
a88b4e04
BP
960 * kernel will continue to queue them up and waste buffer space.
961 *
962 * XXX We could just destroy and discard the socket in this case. */
0672776e
JS
963 if (!status) {
964 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
965 struct ofpbuf reply, buf;
966
967 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
968 while (nl_dump_next(dump, &reply, &buf)) {
969 /* Nothing to do. */
2fe27d5a 970 }
0672776e 971 ofpbuf_uninit(&buf);
93295354
BP
972
973 ovs_mutex_lock(&dump->mutex);
974 status = dump->status;
975 ovs_mutex_unlock(&dump->mutex);
976 ovs_assert(status);
2fe27d5a 977 }
93295354 978
a88b4e04 979 nl_pool_release(dump->sock);
0791315e 980 ovs_mutex_destroy(&dump->mutex);
93295354
BP
981
982 return status == EOF ? 0 : status;
2fe27d5a
BP
983}
984
985/* Causes poll_block() to wake up when any of the specified 'events' (which is
986 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
987void
988nl_sock_wait(const struct nl_sock *sock, short int events)
989{
22326ba6
AS
990#ifdef _WIN32
991 poll_fd_wait(sock->handle, events);
992#else
2fe27d5a 993 poll_fd_wait(sock->fd, events);
22326ba6 994#endif
2fe27d5a 995}
50802adb 996
8522ba09
BP
997/* Returns the underlying fd for 'sock', for use in "poll()"-like operations
998 * that can't use nl_sock_wait().
999 *
1000 * It's a little tricky to use the returned fd correctly, because nl_sock does
1001 * "copy on write" to allow a single nl_sock to be used for notifications,
1002 * transactions, and dumps. If 'sock' is used only for notifications and
1003 * transactions (and never for dump) then the usage is safe. */
1004int
1005nl_sock_fd(const struct nl_sock *sock)
1006{
22326ba6
AS
1007#ifdef _WIN32
1008 return sock->handle;
1009#else
8522ba09 1010 return sock->fd;
22326ba6 1011#endif
8522ba09
BP
1012}
1013
50802adb
JG
1014/* Returns the PID associated with this socket. */
1015uint32_t
1016nl_sock_pid(const struct nl_sock *sock)
1017{
1018 return sock->pid;
1019}
2fe27d5a
BP
1020\f
1021/* Miscellaneous. */
1022
2ad204c8
BP
1023struct genl_family {
1024 struct hmap_node hmap_node;
1025 uint16_t id;
1026 char *name;
1027};
1028
1029static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1030
2fe27d5a
BP
1031static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1032 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
213a13ed 1033 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
2fe27d5a
BP
1034};
1035
2ad204c8
BP
1036static struct genl_family *
1037find_genl_family_by_id(uint16_t id)
1038{
1039 struct genl_family *family;
1040
1041 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1042 &genl_families) {
1043 if (family->id == id) {
1044 return family;
1045 }
1046 }
1047 return NULL;
1048}
1049
1050static void
1051define_genl_family(uint16_t id, const char *name)
1052{
1053 struct genl_family *family = find_genl_family_by_id(id);
1054
1055 if (family) {
1056 if (!strcmp(family->name, name)) {
1057 return;
1058 }
1059 free(family->name);
1060 } else {
1061 family = xmalloc(sizeof *family);
1062 family->id = id;
1063 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1064 }
1065 family->name = xstrdup(name);
1066}
1067
1068static const char *
1069genl_family_to_name(uint16_t id)
1070{
1071 if (id == GENL_ID_CTRL) {
1072 return "control";
1073 } else {
1074 struct genl_family *family = find_genl_family_by_id(id);
1075 return family ? family->name : "unknown";
1076 }
1077}
1078
e408762f 1079static int
2a477244
BP
1080do_lookup_genl_family(const char *name, struct nlattr **attrs,
1081 struct ofpbuf **replyp)
2fe27d5a
BP
1082{
1083 struct nl_sock *sock;
1084 struct ofpbuf request, *reply;
2a477244 1085 int error;
2fe27d5a 1086
2a477244
BP
1087 *replyp = NULL;
1088 error = nl_sock_create(NETLINK_GENERIC, &sock);
1089 if (error) {
1090 return error;
2fe27d5a
BP
1091 }
1092
1093 ofpbuf_init(&request, 0);
1094 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1095 CTRL_CMD_GETFAMILY, 1);
1096 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
2a477244 1097 error = nl_sock_transact(sock, &request, &reply);
2fe27d5a 1098 ofpbuf_uninit(&request);
2a477244 1099 if (error) {
2fe27d5a 1100 nl_sock_destroy(sock);
2a477244 1101 return error;
2fe27d5a
BP
1102 }
1103
1104 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
2a477244
BP
1105 family_policy, attrs, ARRAY_SIZE(family_policy))
1106 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
2fe27d5a
BP
1107 nl_sock_destroy(sock);
1108 ofpbuf_delete(reply);
2a477244 1109 return EPROTO;
2fe27d5a
BP
1110 }
1111
2fe27d5a 1112 nl_sock_destroy(sock);
2a477244
BP
1113 *replyp = reply;
1114 return 0;
2fe27d5a
BP
1115}
1116
e408762f
EJ
1117/* Finds the multicast group called 'group_name' in genl family 'family_name'.
1118 * When successful, writes its result to 'multicast_group' and returns 0.
213a13ed 1119 * Otherwise, clears 'multicast_group' and returns a positive error code.
b3dcb73c 1120 */
e408762f
EJ
1121int
1122nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
b3dcb73c 1123 unsigned int *multicast_group)
e408762f
EJ
1124{
1125 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
6d23c6f4 1126 const struct nlattr *mc;
2a477244 1127 struct ofpbuf *reply;
e408762f 1128 unsigned int left;
2a477244 1129 int error;
e408762f
EJ
1130
1131 *multicast_group = 0;
2a477244
BP
1132 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1133 if (error) {
1134 return error;
e408762f
EJ
1135 }
1136
213a13ed 1137 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
b3dcb73c 1138 error = EPROTO;
213a13ed
EJ
1139 goto exit;
1140 }
1141
6d23c6f4 1142 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
e408762f
EJ
1143 static const struct nl_policy mc_policy[] = {
1144 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1145 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1146 };
1147
1148 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1149 const char *mc_name;
1150
1151 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
2a477244
BP
1152 error = EPROTO;
1153 goto exit;
e408762f
EJ
1154 }
1155
1156 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1157 if (!strcmp(group_name, mc_name)) {
1158 *multicast_group =
1159 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
2a477244
BP
1160 error = 0;
1161 goto exit;
e408762f
EJ
1162 }
1163 }
2a477244 1164 error = EPROTO;
e408762f 1165
2a477244
BP
1166exit:
1167 ofpbuf_delete(reply);
1168 return error;
e408762f
EJ
1169}
1170
2fe27d5a
BP
1171/* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1172 * number and stores it in '*number'. If successful, returns 0 and the caller
1173 * may use '*number' as the family number. On failure, returns a positive
1174 * errno value and '*number' caches the errno value. */
1175int
1176nl_lookup_genl_family(const char *name, int *number)
1177{
1178 if (*number == 0) {
2a477244
BP
1179 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1180 struct ofpbuf *reply;
1181 int error;
1182
1183 error = do_lookup_genl_family(name, attrs, &reply);
1184 if (!error) {
1185 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1186 define_genl_family(*number, name);
1187 } else {
1188 *number = -error;
1189 }
1190 ofpbuf_delete(reply);
1191
cb22974d 1192 ovs_assert(*number != 0);
2fe27d5a
BP
1193 }
1194 return *number > 0 ? 0 : -*number;
1195}
a88b4e04
BP
1196\f
1197struct nl_pool {
1198 struct nl_sock *socks[16];
1199 int n;
1200};
1201
834d6caf 1202static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
97be1538 1203static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
a88b4e04
BP
1204
1205static int
1206nl_pool_alloc(int protocol, struct nl_sock **sockp)
1207{
0bd01224 1208 struct nl_sock *sock = NULL;
a88b4e04
BP
1209 struct nl_pool *pool;
1210
1211 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1212
97be1538 1213 ovs_mutex_lock(&pool_mutex);
a88b4e04
BP
1214 pool = &pools[protocol];
1215 if (pool->n > 0) {
0bd01224
BP
1216 sock = pool->socks[--pool->n];
1217 }
97be1538 1218 ovs_mutex_unlock(&pool_mutex);
0bd01224
BP
1219
1220 if (sock) {
1221 *sockp = sock;
a88b4e04
BP
1222 return 0;
1223 } else {
1224 return nl_sock_create(protocol, sockp);
1225 }
1226}
1227
1228static void
1229nl_pool_release(struct nl_sock *sock)
1230{
1231 if (sock) {
1232 struct nl_pool *pool = &pools[sock->protocol];
1233
97be1538 1234 ovs_mutex_lock(&pool_mutex);
a88b4e04
BP
1235 if (pool->n < ARRAY_SIZE(pool->socks)) {
1236 pool->socks[pool->n++] = sock;
0bd01224 1237 sock = NULL;
a88b4e04 1238 }
97be1538 1239 ovs_mutex_unlock(&pool_mutex);
0bd01224
BP
1240
1241 nl_sock_destroy(sock);
a88b4e04
BP
1242 }
1243}
1244
022ad2b9
BP
1245/* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1246 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1247 * successful, returns 0. On failure, returns a positive errno value.
1248 *
1249 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1250 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1251 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1252 * reply, if any, is discarded.
1253 *
1254 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1255 * match ofpbuf_size(msg), nlmsg_pid will be set to the pid of the socket used
1256 * for sending the request, and nlmsg_seq will be initialized.
1257 *
1258 * The caller is responsible for destroying 'request'.
1259 *
1260 * Bare Netlink is an unreliable transport protocol. This function layers
1261 * reliable delivery and reply semantics on top of bare Netlink.
1262 *
1263 * In Netlink, sending a request to the kernel is reliable enough, because the
1264 * kernel will tell us if the message cannot be queued (and we will in that
1265 * case put it on the transmit queue and wait until it can be delivered).
1266 *
1267 * Receiving the reply is the real problem: if the socket buffer is full when
1268 * the kernel tries to send the reply, the reply will be dropped. However, the
1269 * kernel sets a flag that a reply has been dropped. The next call to recv
1270 * then returns ENOBUFS. We can then re-send the request.
1271 *
1272 * Caveats:
1273 *
1274 * 1. Netlink depends on sequence numbers to match up requests and
1275 * replies. The sender of a request supplies a sequence number, and
1276 * the reply echos back that sequence number.
1277 *
1278 * This is fine, but (1) some kernel netlink implementations are
1279 * broken, in that they fail to echo sequence numbers and (2) this
1280 * function will drop packets with non-matching sequence numbers, so
1281 * that only a single request can be usefully transacted at a time.
1282 *
1283 * 2. Resending the request causes it to be re-executed, so the request
1284 * needs to be idempotent.
1285 */
a88b4e04
BP
1286int
1287nl_transact(int protocol, const struct ofpbuf *request,
1288 struct ofpbuf **replyp)
1289{
1290 struct nl_sock *sock;
1291 int error;
1292
1293 error = nl_pool_alloc(protocol, &sock);
1294 if (error) {
1295 *replyp = NULL;
1296 return error;
1297 }
1298
1299 error = nl_sock_transact(sock, request, replyp);
1300
1301 nl_pool_release(sock);
1302 return error;
1303}
1304
022ad2b9
BP
1305/* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1306 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1307 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1308 * the 'error' member of each transaction with 0 if it was successful,
1309 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1310 * be filled with the reply if the message receives a detailed reply. In other
1311 * cases, i.e. where the request failed or had no reply beyond an indication of
1312 * success, 'reply' will be cleared if it is nonnull.
1313 *
1314 * The caller is responsible for destroying each request and reply, and the
1315 * transactions array itself.
1316 *
1317 * Before sending each message, this function will finalize nlmsg_len in each
1318 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1319 * used for the transaction, and initialize nlmsg_seq.
1320 *
1321 * Bare Netlink is an unreliable transport protocol. This function layers
1322 * reliable delivery and reply semantics on top of bare Netlink. See
1323 * nl_transact() for some caveats.
1324 */
a88b4e04
BP
1325void
1326nl_transact_multiple(int protocol,
1327 struct nl_transaction **transactions, size_t n)
1328{
1329 struct nl_sock *sock;
1330 int error;
1331
1332 error = nl_pool_alloc(protocol, &sock);
1333 if (!error) {
1334 nl_sock_transact_multiple(sock, transactions, n);
1335 nl_pool_release(sock);
1336 } else {
1337 nl_sock_record_errors__(transactions, n, error);
1338 }
1339}
1340
2fe27d5a 1341\f
7d7447df
BP
1342static uint32_t
1343nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1344{
1345 uint32_t seq = sock->next_seq;
1346
1347 sock->next_seq += n;
1348
1349 /* Make it impossible for the next request for sequence numbers to wrap
1350 * around to 0. Start over with 1 to avoid ever using a sequence number of
1351 * 0, because the kernel uses sequence number 0 for notifications. */
1352 if (sock->next_seq >= UINT32_MAX / 2) {
1353 sock->next_seq = 1;
1354 }
1355
1356 return seq;
1357}
1358
2fe27d5a 1359static void
2ad204c8 1360nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
2fe27d5a
BP
1361{
1362 struct nlmsg_flag {
1363 unsigned int bits;
1364 const char *name;
1365 };
1366 static const struct nlmsg_flag flags[] = {
1367 { NLM_F_REQUEST, "REQUEST" },
1368 { NLM_F_MULTI, "MULTI" },
1369 { NLM_F_ACK, "ACK" },
1370 { NLM_F_ECHO, "ECHO" },
1371 { NLM_F_DUMP, "DUMP" },
1372 { NLM_F_ROOT, "ROOT" },
1373 { NLM_F_MATCH, "MATCH" },
1374 { NLM_F_ATOMIC, "ATOMIC" },
1375 };
1376 const struct nlmsg_flag *flag;
1377 uint16_t flags_left;
1378
1379 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1380 h->nlmsg_len, h->nlmsg_type);
1381 if (h->nlmsg_type == NLMSG_NOOP) {
1382 ds_put_cstr(ds, "(no-op)");
1383 } else if (h->nlmsg_type == NLMSG_ERROR) {
1384 ds_put_cstr(ds, "(error)");
1385 } else if (h->nlmsg_type == NLMSG_DONE) {
1386 ds_put_cstr(ds, "(done)");
1387 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1388 ds_put_cstr(ds, "(overrun)");
1389 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1390 ds_put_cstr(ds, "(reserved)");
2ad204c8
BP
1391 } else if (protocol == NETLINK_GENERIC) {
1392 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
2fe27d5a
BP
1393 } else {
1394 ds_put_cstr(ds, "(family-defined)");
1395 }
1396 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1397 flags_left = h->nlmsg_flags;
1398 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1399 if ((flags_left & flag->bits) == flag->bits) {
1400 ds_put_format(ds, "[%s]", flag->name);
1401 flags_left &= ~flag->bits;
1402 }
1403 }
1404 if (flags_left) {
1405 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1406 }
2c5a6834
BP
1407 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1408 h->nlmsg_seq, h->nlmsg_pid);
2fe27d5a
BP
1409}
1410
1411static char *
7041c3a9 1412nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
2fe27d5a
BP
1413{
1414 struct ds ds = DS_EMPTY_INITIALIZER;
1415 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1416 if (h) {
2ad204c8 1417 nlmsghdr_to_string(h, protocol, &ds);
2fe27d5a
BP
1418 if (h->nlmsg_type == NLMSG_ERROR) {
1419 const struct nlmsgerr *e;
1420 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1421 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1422 if (e) {
1423 ds_put_format(&ds, " error(%d", e->error);
1424 if (e->error < 0) {
10a89ef0 1425 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
2fe27d5a
BP
1426 }
1427 ds_put_cstr(&ds, ", in-reply-to(");
2ad204c8 1428 nlmsghdr_to_string(&e->msg, protocol, &ds);
2fe27d5a
BP
1429 ds_put_cstr(&ds, "))");
1430 } else {
1431 ds_put_cstr(&ds, " error(truncated)");
1432 }
1433 } else if (h->nlmsg_type == NLMSG_DONE) {
1434 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1435 if (error) {
1436 ds_put_format(&ds, " done(%d", *error);
1437 if (*error < 0) {
10a89ef0 1438 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
2fe27d5a
BP
1439 }
1440 ds_put_cstr(&ds, ")");
1441 } else {
1442 ds_put_cstr(&ds, " done(truncated)");
1443 }
7041c3a9
BP
1444 } else if (protocol == NETLINK_GENERIC) {
1445 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1446 if (genl) {
1447 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1448 genl->cmd, genl->version);
1449 }
2fe27d5a
BP
1450 }
1451 } else {
1452 ds_put_cstr(&ds, "nl(truncated)");
1453 }
1454 return ds.string;
1455}
1456
1457static void
1458log_nlmsg(const char *function, int error,
7041c3a9 1459 const void *message, size_t size, int protocol)
2fe27d5a
BP
1460{
1461 struct ofpbuf buffer;
1462 char *nlmsg;
1463
1464 if (!VLOG_IS_DBG_ENABLED()) {
1465 return;
1466 }
1467
1468 ofpbuf_use_const(&buffer, message, size);
7041c3a9 1469 nlmsg = nlmsg_to_string(&buffer, protocol);
10a89ef0 1470 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
2fe27d5a
BP
1471 free(nlmsg);
1472}