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