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