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