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