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