netlink-socket: Simplify multithreaded dumping to match Linux reality.
[cascardo/ovs.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
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"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include <sys/uio.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "hash.h"
28 #include "hmap.h"
29 #include "netlink.h"
30 #include "netlink-protocol.h"
31 #include "ofpbuf.h"
32 #include "ovs-thread.h"
33 #include "poll-loop.h"
34 #include "seq.h"
35 #include "socket-util.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(netlink_socket);
40
41 COVERAGE_DEFINE(netlink_overflow);
42 COVERAGE_DEFINE(netlink_received);
43 COVERAGE_DEFINE(netlink_recv_jumbo);
44 COVERAGE_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. */
54 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
55
56 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
57 static void log_nlmsg(const char *function, int error,
58                       const void *message, size_t size, int protocol);
59 \f
60 /* Netlink sockets. */
61
62 struct nl_sock {
63     int fd;
64     uint32_t next_seq;
65     uint32_t pid;
66     int protocol;
67     unsigned int rcvbuf;        /* Receive buffer size (SO_RCVBUF). */
68 };
69
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(). */
78 static int max_iovs;
79
80 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
81 static void nl_pool_release(struct nl_sock *);
82
83 /* Creates a new netlink socket for the given netlink 'protocol'
84  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
85  * new socket if successful, otherwise returns a positive errno value. */
86 int
87 nl_sock_create(int protocol, struct nl_sock **sockp)
88 {
89     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
90     struct nl_sock *sock;
91     struct sockaddr_nl local, remote;
92     socklen_t local_size;
93     int rcvbuf;
94     int retval = 0;
95
96     if (ovsthread_once_start(&once)) {
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) {
103                 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
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;
111         ovsthread_once_done(&once);
112     }
113
114     *sockp = NULL;
115     sock = xmalloc(sizeof *sock);
116
117     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
118     if (sock->fd < 0) {
119         VLOG_ERR("fcntl: %s", ovs_strerror(errno));
120         goto error;
121     }
122     sock->protocol = protocol;
123     sock->next_seq = 1;
124
125     rcvbuf = 1024 * 1024;
126     if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
127                    &rcvbuf, sizeof rcvbuf)) {
128         /* Only root can use SO_RCVBUFFORCE.  Everyone else gets EPERM.
129          * Warn only if the failure is therefore unexpected. */
130         if (errno != EPERM) {
131             VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
132                          "(%s)", rcvbuf, ovs_strerror(errno));
133         }
134     }
135
136     retval = get_socket_rcvbuf(sock->fd);
137     if (retval < 0) {
138         retval = -retval;
139         goto error;
140     }
141     sock->rcvbuf = retval;
142
143     /* Connect to kernel (pid 0) as remote address. */
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) {
148         VLOG_ERR("connect(0): %s", ovs_strerror(errno));
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) {
155         VLOG_ERR("getsockname: %s", ovs_strerror(errno));
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;
162     }
163     sock->pid = local.nl_pid;
164
165     *sockp = sock;
166     return 0;
167
168 error:
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
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.  */
185 int
186 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
187 {
188     return nl_sock_create(src->protocol, sockp);
189 }
190
191 /* Destroys netlink socket 'sock'. */
192 void
193 nl_sock_destroy(struct nl_sock *sock)
194 {
195     if (sock) {
196         close(sock->fd);
197         free(sock);
198     }
199 }
200
201 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
202  * successful, otherwise a positive errno value.
203  *
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  *
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. */
212 int
213 nl_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)",
218                   multicast_group, ovs_strerror(errno));
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. */
234 int
235 nl_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)",
240                   multicast_group, ovs_strerror(errno));
241         return errno;
242     }
243     return 0;
244 }
245
246 static int
247 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
248                uint32_t nlmsg_seq, bool wait)
249 {
250     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
251     int error;
252
253     nlmsg->nlmsg_len = ofpbuf_size(msg);
254     nlmsg->nlmsg_seq = nlmsg_seq;
255     nlmsg->nlmsg_pid = sock->pid;
256     do {
257         int retval;
258         retval = send(sock->fd, ofpbuf_data(msg), ofpbuf_size(msg), wait ? 0 : MSG_DONTWAIT);
259         error = retval < 0 ? errno : 0;
260     } while (error == EINTR);
261     log_nlmsg(__func__, error, ofpbuf_data(msg), ofpbuf_size(msg), sock->protocol);
262     if (!error) {
263         COVERAGE_INC(netlink_sent);
264     }
265     return error;
266 }
267
268 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
269  * 'sock'.  nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
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.
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. */
276 int
277 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
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
283  * 'sock'.  nlmsg_len in 'msg' will be finalized to match ofpbuf_size(msg), nlmsg_pid
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. */
293 int
294 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
295                  uint32_t nlmsg_seq, bool wait)
296 {
297     return nl_sock_send__(sock, msg, nlmsg_seq, wait);
298 }
299
300 static int
301 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
302 {
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). */
308     struct nlmsghdr *nlmsghdr;
309     uint8_t tail[65536];
310     struct iovec iov[2];
311     struct msghdr msg;
312     ssize_t retval;
313     int error;
314
315     ovs_assert(buf->allocated >= sizeof *nlmsghdr);
316     ofpbuf_clear(buf);
317
318     iov[0].iov_base = ofpbuf_base(buf);
319     iov[0].iov_len = buf->allocated;
320     iov[1].iov_base = tail;
321     iov[1].iov_len = sizeof tail;
322
323     memset(&msg, 0, sizeof msg);
324     msg.msg_iov = iov;
325     msg.msg_iovlen = 2;
326
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);
335     do {
336         nlmsghdr->nlmsg_len = UINT32_MAX;
337         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
338         error = (retval < 0 ? errno
339                  : retval == 0 ? ECONNRESET /* not possible? */
340                  : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
341                  : retval);
342     } while (error == EINTR);
343     if (error) {
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         }
349         return error;
350     }
351
352     if (msg.msg_flags & MSG_TRUNC) {
353         VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
354                     sizeof tail);
355         return E2BIG;
356     }
357
358     if (retval < sizeof *nlmsghdr
359         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
360         || nlmsghdr->nlmsg_len > retval) {
361         VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
362                     retval, sizeof *nlmsghdr);
363         return EPROTO;
364     }
365
366     ofpbuf_set_size(buf, MIN(retval, buf->allocated));
367     if (retval > buf->allocated) {
368         COVERAGE_INC(netlink_recv_jumbo);
369         ofpbuf_put(buf, tail, retval - buf->allocated);
370     }
371
372     log_nlmsg(__func__, 0, ofpbuf_data(buf), ofpbuf_size(buf), sock->protocol);
373     COVERAGE_INC(netlink_received);
374
375     return 0;
376 }
377
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.
389  *
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. */
395 int
396 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
397 {
398     return nl_sock_recv__(sock, buf, wait);
399 }
400
401 static void
402 nl_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++) {
408         struct nl_transaction *txn = transactions[i];
409
410         txn->error = error;
411         if (txn->reply) {
412             ofpbuf_clear(txn->reply);
413         }
414     }
415 }
416
417 static int
418 nl_sock_transact_multiple__(struct nl_sock *sock,
419                             struct nl_transaction **transactions, size_t n,
420                             size_t *done)
421 {
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;
427     struct iovec iovs[MAX_IOVS];
428     struct msghdr msg;
429     int error;
430     int i;
431
432     base_seq = nl_sock_allocate_seq(sock, n);
433     *done = 0;
434     for (i = 0; i < n; i++) {
435         struct nl_transaction *txn = transactions[i];
436         struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
437
438         nlmsg->nlmsg_len = ofpbuf_size(txn->request);
439         nlmsg->nlmsg_seq = base_seq + i;
440         nlmsg->nlmsg_pid = sock->pid;
441
442         iovs[i].iov_base = ofpbuf_data(txn->request);
443         iovs[i].iov_len = ofpbuf_size(txn->request);
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++) {
454         struct nl_transaction *txn = transactions[i];
455
456         log_nlmsg(__func__, error, ofpbuf_data(txn->request), ofpbuf_size(txn->request),
457                   sock->protocol);
458     }
459     if (!error) {
460         COVERAGE_ADD(netlink_sent, n);
461     }
462
463     if (error) {
464         return error;
465     }
466
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;
471     while (n > 0) {
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         }
484
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;
494         }
495
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);
500             continue;
501         }
502         i = seq - base_seq;
503         txn = transactions[i];
504
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) {
511                 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
512                             error, ovs_strerror(txn->error));
513             }
514         } else {
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             }
522         }
523
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. */
530         *done += i + 1;
531         transactions += i + 1;
532         n -= i + 1;
533         base_seq += i + 1;
534     }
535     ofpbuf_uninit(&tmp_reply);
536
537     return error;
538 }
539
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
542  * 'error' member of each transaction with 0 if it was successful, otherwise
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.
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
552  * 'request' to match the ofpbuf's size,  set nlmsg_pid to 'sock''s pid, and
553  * initialize nlmsg_seq.
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  */
559 void
560 nl_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
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
593         bytes = ofpbuf_size(transactions[0]->request);
594         for (count = 1; count < n && count < max_batch_count; count++) {
595             if (bytes + ofpbuf_size(transactions[count]->request) > MAX_BATCH_BYTES) {
596                 break;
597             }
598             bytes += ofpbuf_size(transactions[count]->request);
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) {
608             VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
609             nl_sock_record_errors__(transactions, n, error);
610         }
611     }
612 }
613
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  *
622  * Before the message is sent, nlmsg_len in 'request' will be finalized to
623  * match ofpbuf_size(msg), nlmsg_pid will be set to 'sock''s pid, and nlmsg_seq will
624  * be initialized, NLM_F_ACK will be set in nlmsg_flags.
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  */
654 int
655 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
656                  struct ofpbuf **replyp)
657 {
658     struct nl_transaction *transactionp;
659     struct nl_transaction transaction;
660
661     transaction.request = CONST_CAST(struct ofpbuf *, request);
662     transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
663     transactionp = &transaction;
664
665     nl_sock_transact_multiple(sock, &transactionp, 1);
666
667     if (replyp) {
668         if (transaction.error) {
669             ofpbuf_delete(transaction.reply);
670             *replyp = NULL;
671         } else {
672             *replyp = transaction.reply;
673         }
674     }
675
676     return transaction.error;
677 }
678
679 /* Drain all the messages currently in 'sock''s receive queue. */
680 int
681 nl_sock_drain(struct nl_sock *sock)
682 {
683     return drain_rcvbuf(sock->fd);
684 }
685
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.
689  *
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.
694  *
695  * The design of this Netlink socket library ensures that the dump is reliable.
696  *
697  * This function provides no status indication.  nl_dump_done() provides an
698  * error status for the entire dump operation.
699  *
700  * The caller must eventually destroy 'request'.
701  */
702 void
703 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
704 {
705     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
706
707     ovs_mutex_init(&dump->mutex);
708     ovs_mutex_lock(&dump->mutex);
709     dump->status = nl_pool_alloc(protocol, &dump->sock);
710     if (!dump->status) {
711         dump->status = nl_sock_send__(dump->sock, request,
712                                       nl_sock_allocate_seq(dump->sock, 1),
713                                       true);
714     }
715     dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
716     ovs_mutex_unlock(&dump->mutex);
717 }
718
719 static int
720 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
721     OVS_REQUIRES(dump->mutex)
722 {
723     struct nlmsghdr *nlmsghdr;
724     int error;
725
726     while (!ofpbuf_size(buffer)) {
727         error = nl_sock_recv__(dump->sock, buffer, true);
728         if (error) {
729             /* The kernel shouldn't return EAGAIN while there's data left. */
730             return error == EAGAIN ? EOF : error;
731         }
732
733         nlmsghdr = nl_msg_nlmsghdr(buffer);
734         if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
735             VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
736                         nlmsghdr->nlmsg_seq, dump->nl_seq);
737             ofpbuf_clear(buffer);
738         }
739     }
740
741     if (nl_msg_nlmsgerr(buffer, &error) && error) {
742         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
743                      ovs_strerror(error));
744         ofpbuf_clear(buffer);
745         return error;
746     }
747
748     return 0;
749 }
750
751 static int
752 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
753 {
754     struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
755     if (!nlmsghdr) {
756         VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
757         return EPROTO;
758     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
759         return EOF;
760     } else {
761         return 0;
762     }
763 }
764
765 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
766  * have been initialized with nl_dump_start(), and 'buffer' must have been
767  * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
768  *
769  * If successful, returns true and points 'reply->data' and
770  * 'ofpbuf_size(reply)' to the message that was retrieved. The caller must not
771  * modify 'reply' (because it points within 'buffer', which will be used by
772  * future calls to this function).
773  *
774  * On failure, returns false and sets 'reply->data' to NULL and
775  * 'ofpbuf_size(reply)' to 0.  Failure might indicate an actual error or merely
776  * the end of replies.  An error status for the entire dump operation is
777  * provided when it is completed by calling nl_dump_done().
778  *
779  * Multiple threads may call this function, passing the same nl_dump, however
780  * each must provide independent buffers. This function may cache multiple
781  * replies in the buffer, and these will be processed before more replies are
782  * fetched. When this function returns false, other threads may continue to
783  * process replies in their buffers, but they will not fetch more replies.
784  */
785 bool
786 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
787 {
788     int retval = 0;
789
790     /* If the buffer is empty, refill it.
791      *
792      * If the buffer is not empty, we don't check the dump's status.
793      * Otherwise, we could end up skipping some of the dump results if thread A
794      * hits EOF while thread B is in the midst of processing a batch. */
795     if (!ofpbuf_size(buffer)) {
796         ovs_mutex_lock(&dump->mutex);
797         if (!dump->status) {
798             /* Take the mutex here to avoid an in-kernel race.  If two threads
799              * try to read from a Netlink dump socket at once, then the socket
800              * error can be set to EINVAL, which will be encountered on the
801              * next recv on that socket, which could be anywhere due to the way
802              * that we pool Netlink sockets.  Serializing the recv calls avoids
803              * the issue. */
804             dump->status = nl_dump_refill(dump, buffer);
805         }
806         retval = dump->status;
807         ovs_mutex_unlock(&dump->mutex);
808     }
809
810     /* Fetch the next message from the buffer. */
811     if (!retval) {
812         retval = nl_dump_next__(reply, buffer);
813         if (retval) {
814             /* Record 'retval' as the dump status, but don't overwrite an error
815              * with EOF.  */
816             ovs_mutex_lock(&dump->mutex);
817             if (dump->status <= 0) {
818                 dump->status = retval;
819             }
820             ovs_mutex_unlock(&dump->mutex);
821         }
822     }
823
824     if (retval) {
825         ofpbuf_set_data(reply, NULL);
826         ofpbuf_set_size(reply, 0);
827     }
828     return !retval;
829 }
830
831 /* Completes Netlink dump operation 'dump', which must have been initialized
832  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
833  * otherwise a positive errno value describing the problem. */
834 int
835 nl_dump_done(struct nl_dump *dump)
836 {
837     int status;
838
839     ovs_mutex_lock(&dump->mutex);
840     status = dump->status;
841     ovs_mutex_unlock(&dump->mutex);
842
843     /* Drain any remaining messages that the client didn't read.  Otherwise the
844      * kernel will continue to queue them up and waste buffer space.
845      *
846      * XXX We could just destroy and discard the socket in this case. */
847     if (!status) {
848         uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
849         struct ofpbuf reply, buf;
850
851         ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
852         while (nl_dump_next(dump, &reply, &buf)) {
853             /* Nothing to do. */
854         }
855         ofpbuf_uninit(&buf);
856
857         ovs_mutex_lock(&dump->mutex);
858         status = dump->status;
859         ovs_mutex_unlock(&dump->mutex);
860         ovs_assert(status);
861     }
862
863     nl_pool_release(dump->sock);
864     ovs_mutex_destroy(&dump->mutex);
865
866     return status == EOF ? 0 : status;
867 }
868
869 /* Causes poll_block() to wake up when any of the specified 'events' (which is
870  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
871 void
872 nl_sock_wait(const struct nl_sock *sock, short int events)
873 {
874     poll_fd_wait(sock->fd, events);
875 }
876
877 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
878  * that can't use nl_sock_wait().
879  *
880  * It's a little tricky to use the returned fd correctly, because nl_sock does
881  * "copy on write" to allow a single nl_sock to be used for notifications,
882  * transactions, and dumps.  If 'sock' is used only for notifications and
883  * transactions (and never for dump) then the usage is safe. */
884 int
885 nl_sock_fd(const struct nl_sock *sock)
886 {
887     return sock->fd;
888 }
889
890 /* Returns the PID associated with this socket. */
891 uint32_t
892 nl_sock_pid(const struct nl_sock *sock)
893 {
894     return sock->pid;
895 }
896 \f
897 /* Miscellaneous.  */
898
899 struct genl_family {
900     struct hmap_node hmap_node;
901     uint16_t id;
902     char *name;
903 };
904
905 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
906
907 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
908     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
909     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
910 };
911
912 static struct genl_family *
913 find_genl_family_by_id(uint16_t id)
914 {
915     struct genl_family *family;
916
917     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
918                              &genl_families) {
919         if (family->id == id) {
920             return family;
921         }
922     }
923     return NULL;
924 }
925
926 static void
927 define_genl_family(uint16_t id, const char *name)
928 {
929     struct genl_family *family = find_genl_family_by_id(id);
930
931     if (family) {
932         if (!strcmp(family->name, name)) {
933             return;
934         }
935         free(family->name);
936     } else {
937         family = xmalloc(sizeof *family);
938         family->id = id;
939         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
940     }
941     family->name = xstrdup(name);
942 }
943
944 static const char *
945 genl_family_to_name(uint16_t id)
946 {
947     if (id == GENL_ID_CTRL) {
948         return "control";
949     } else {
950         struct genl_family *family = find_genl_family_by_id(id);
951         return family ? family->name : "unknown";
952     }
953 }
954
955 static int
956 do_lookup_genl_family(const char *name, struct nlattr **attrs,
957                       struct ofpbuf **replyp)
958 {
959     struct nl_sock *sock;
960     struct ofpbuf request, *reply;
961     int error;
962
963     *replyp = NULL;
964     error = nl_sock_create(NETLINK_GENERIC, &sock);
965     if (error) {
966         return error;
967     }
968
969     ofpbuf_init(&request, 0);
970     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
971                           CTRL_CMD_GETFAMILY, 1);
972     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
973     error = nl_sock_transact(sock, &request, &reply);
974     ofpbuf_uninit(&request);
975     if (error) {
976         nl_sock_destroy(sock);
977         return error;
978     }
979
980     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
981                          family_policy, attrs, ARRAY_SIZE(family_policy))
982         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
983         nl_sock_destroy(sock);
984         ofpbuf_delete(reply);
985         return EPROTO;
986     }
987
988     nl_sock_destroy(sock);
989     *replyp = reply;
990     return 0;
991 }
992
993 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
994  * When successful, writes its result to 'multicast_group' and returns 0.
995  * Otherwise, clears 'multicast_group' and returns a positive error code.
996  */
997 int
998 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
999                        unsigned int *multicast_group)
1000 {
1001     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1002     const struct nlattr *mc;
1003     struct ofpbuf *reply;
1004     unsigned int left;
1005     int error;
1006
1007     *multicast_group = 0;
1008     error = do_lookup_genl_family(family_name, family_attrs, &reply);
1009     if (error) {
1010         return error;
1011     }
1012
1013     if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1014         error = EPROTO;
1015         goto exit;
1016     }
1017
1018     NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1019         static const struct nl_policy mc_policy[] = {
1020             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1021             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1022         };
1023
1024         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1025         const char *mc_name;
1026
1027         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1028             error = EPROTO;
1029             goto exit;
1030         }
1031
1032         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1033         if (!strcmp(group_name, mc_name)) {
1034             *multicast_group =
1035                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1036             error = 0;
1037             goto exit;
1038         }
1039     }
1040     error = EPROTO;
1041
1042 exit:
1043     ofpbuf_delete(reply);
1044     return error;
1045 }
1046
1047 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1048  * number and stores it in '*number'.  If successful, returns 0 and the caller
1049  * may use '*number' as the family number.  On failure, returns a positive
1050  * errno value and '*number' caches the errno value. */
1051 int
1052 nl_lookup_genl_family(const char *name, int *number)
1053 {
1054     if (*number == 0) {
1055         struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1056         struct ofpbuf *reply;
1057         int error;
1058
1059         error = do_lookup_genl_family(name, attrs, &reply);
1060         if (!error) {
1061             *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1062             define_genl_family(*number, name);
1063         } else {
1064             *number = -error;
1065         }
1066         ofpbuf_delete(reply);
1067
1068         ovs_assert(*number != 0);
1069     }
1070     return *number > 0 ? 0 : -*number;
1071 }
1072 \f
1073 struct nl_pool {
1074     struct nl_sock *socks[16];
1075     int n;
1076 };
1077
1078 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1079 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1080
1081 static int
1082 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1083 {
1084     struct nl_sock *sock = NULL;
1085     struct nl_pool *pool;
1086
1087     ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1088
1089     ovs_mutex_lock(&pool_mutex);
1090     pool = &pools[protocol];
1091     if (pool->n > 0) {
1092         sock = pool->socks[--pool->n];
1093     }
1094     ovs_mutex_unlock(&pool_mutex);
1095
1096     if (sock) {
1097         *sockp = sock;
1098         return 0;
1099     } else {
1100         return nl_sock_create(protocol, sockp);
1101     }
1102 }
1103
1104 static void
1105 nl_pool_release(struct nl_sock *sock)
1106 {
1107     if (sock) {
1108         struct nl_pool *pool = &pools[sock->protocol];
1109
1110         ovs_mutex_lock(&pool_mutex);
1111         if (pool->n < ARRAY_SIZE(pool->socks)) {
1112             pool->socks[pool->n++] = sock;
1113             sock = NULL;
1114         }
1115         ovs_mutex_unlock(&pool_mutex);
1116
1117         nl_sock_destroy(sock);
1118     }
1119 }
1120
1121 int
1122 nl_transact(int protocol, const struct ofpbuf *request,
1123             struct ofpbuf **replyp)
1124 {
1125     struct nl_sock *sock;
1126     int error;
1127
1128     error = nl_pool_alloc(protocol, &sock);
1129     if (error) {
1130         *replyp = NULL;
1131         return error;
1132     }
1133
1134     error = nl_sock_transact(sock, request, replyp);
1135
1136     nl_pool_release(sock);
1137     return error;
1138 }
1139
1140 void
1141 nl_transact_multiple(int protocol,
1142                      struct nl_transaction **transactions, size_t n)
1143 {
1144     struct nl_sock *sock;
1145     int error;
1146
1147     error = nl_pool_alloc(protocol, &sock);
1148     if (!error) {
1149         nl_sock_transact_multiple(sock, transactions, n);
1150         nl_pool_release(sock);
1151     } else {
1152         nl_sock_record_errors__(transactions, n, error);
1153     }
1154 }
1155
1156 \f
1157 static uint32_t
1158 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1159 {
1160     uint32_t seq = sock->next_seq;
1161
1162     sock->next_seq += n;
1163
1164     /* Make it impossible for the next request for sequence numbers to wrap
1165      * around to 0.  Start over with 1 to avoid ever using a sequence number of
1166      * 0, because the kernel uses sequence number 0 for notifications. */
1167     if (sock->next_seq >= UINT32_MAX / 2) {
1168         sock->next_seq = 1;
1169     }
1170
1171     return seq;
1172 }
1173
1174 static void
1175 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1176 {
1177     struct nlmsg_flag {
1178         unsigned int bits;
1179         const char *name;
1180     };
1181     static const struct nlmsg_flag flags[] = {
1182         { NLM_F_REQUEST, "REQUEST" },
1183         { NLM_F_MULTI, "MULTI" },
1184         { NLM_F_ACK, "ACK" },
1185         { NLM_F_ECHO, "ECHO" },
1186         { NLM_F_DUMP, "DUMP" },
1187         { NLM_F_ROOT, "ROOT" },
1188         { NLM_F_MATCH, "MATCH" },
1189         { NLM_F_ATOMIC, "ATOMIC" },
1190     };
1191     const struct nlmsg_flag *flag;
1192     uint16_t flags_left;
1193
1194     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1195                   h->nlmsg_len, h->nlmsg_type);
1196     if (h->nlmsg_type == NLMSG_NOOP) {
1197         ds_put_cstr(ds, "(no-op)");
1198     } else if (h->nlmsg_type == NLMSG_ERROR) {
1199         ds_put_cstr(ds, "(error)");
1200     } else if (h->nlmsg_type == NLMSG_DONE) {
1201         ds_put_cstr(ds, "(done)");
1202     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1203         ds_put_cstr(ds, "(overrun)");
1204     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1205         ds_put_cstr(ds, "(reserved)");
1206     } else if (protocol == NETLINK_GENERIC) {
1207         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1208     } else {
1209         ds_put_cstr(ds, "(family-defined)");
1210     }
1211     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1212     flags_left = h->nlmsg_flags;
1213     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1214         if ((flags_left & flag->bits) == flag->bits) {
1215             ds_put_format(ds, "[%s]", flag->name);
1216             flags_left &= ~flag->bits;
1217         }
1218     }
1219     if (flags_left) {
1220         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1221     }
1222     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1223                   h->nlmsg_seq, h->nlmsg_pid);
1224 }
1225
1226 static char *
1227 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1228 {
1229     struct ds ds = DS_EMPTY_INITIALIZER;
1230     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1231     if (h) {
1232         nlmsghdr_to_string(h, protocol, &ds);
1233         if (h->nlmsg_type == NLMSG_ERROR) {
1234             const struct nlmsgerr *e;
1235             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1236                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1237             if (e) {
1238                 ds_put_format(&ds, " error(%d", e->error);
1239                 if (e->error < 0) {
1240                     ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1241                 }
1242                 ds_put_cstr(&ds, ", in-reply-to(");
1243                 nlmsghdr_to_string(&e->msg, protocol, &ds);
1244                 ds_put_cstr(&ds, "))");
1245             } else {
1246                 ds_put_cstr(&ds, " error(truncated)");
1247             }
1248         } else if (h->nlmsg_type == NLMSG_DONE) {
1249             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1250             if (error) {
1251                 ds_put_format(&ds, " done(%d", *error);
1252                 if (*error < 0) {
1253                     ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1254                 }
1255                 ds_put_cstr(&ds, ")");
1256             } else {
1257                 ds_put_cstr(&ds, " done(truncated)");
1258             }
1259         } else if (protocol == NETLINK_GENERIC) {
1260             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1261             if (genl) {
1262                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1263                               genl->cmd, genl->version);
1264             }
1265         }
1266     } else {
1267         ds_put_cstr(&ds, "nl(truncated)");
1268     }
1269     return ds.string;
1270 }
1271
1272 static void
1273 log_nlmsg(const char *function, int error,
1274           const void *message, size_t size, int protocol)
1275 {
1276     struct ofpbuf buffer;
1277     char *nlmsg;
1278
1279     if (!VLOG_IS_DBG_ENABLED()) {
1280         return;
1281     }
1282
1283     ofpbuf_use_const(&buffer, message, size);
1284     nlmsg = nlmsg_to_string(&buffer, protocol);
1285     VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
1286     free(nlmsg);
1287 }