netlink-socket: Consistently log sequence numbers in hexadecimal.
[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 <unistd.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "netlink.h"
28 #include "netlink-protocol.h"
29 #include "ofpbuf.h"
30 #include "poll-loop.h"
31 #include "socket-util.h"
32 #include "stress.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(netlink_socket);
36
37 COVERAGE_DEFINE(netlink_overflow);
38 COVERAGE_DEFINE(netlink_received);
39 COVERAGE_DEFINE(netlink_recv_retry);
40 COVERAGE_DEFINE(netlink_send);
41 COVERAGE_DEFINE(netlink_sent);
42
43 /* Linux header file confusion causes this to be undefined. */
44 #ifndef SOL_NETLINK
45 #define SOL_NETLINK 270
46 #endif
47
48 /* A single (bad) Netlink message can in theory dump out many, many log
49  * messages, so the burst size is set quite high here to avoid missing useful
50  * information.  Also, at high logging levels we log *all* Netlink messages. */
51 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
52
53 static void log_nlmsg(const char *function, int error,
54                       const void *message, size_t size, int protocol);
55 \f
56 /* Netlink sockets. */
57
58 struct nl_sock
59 {
60     int fd;
61     uint32_t pid;
62     int protocol;
63     bool any_groups;
64     struct nl_dump *dump;
65 };
66
67 static int alloc_pid(uint32_t *);
68 static void free_pid(uint32_t);
69 static int nl_sock_cow__(struct nl_sock *);
70
71 /* Creates a new netlink socket for the given netlink 'protocol'
72  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
73  * new socket if successful, otherwise returns a positive errno value.  */
74 int
75 nl_sock_create(int protocol, struct nl_sock **sockp)
76 {
77     struct nl_sock *sock;
78     struct sockaddr_nl local, remote;
79     int retval = 0;
80
81     *sockp = NULL;
82     sock = malloc(sizeof *sock);
83     if (sock == NULL) {
84         return ENOMEM;
85     }
86
87     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
88     if (sock->fd < 0) {
89         VLOG_ERR("fcntl: %s", strerror(errno));
90         goto error;
91     }
92     sock->protocol = protocol;
93     sock->any_groups = false;
94
95     retval = alloc_pid(&sock->pid);
96     if (retval) {
97         goto error;
98     }
99
100     /* Bind local address as our selected pid. */
101     memset(&local, 0, sizeof local);
102     local.nl_family = AF_NETLINK;
103     local.nl_pid = sock->pid;
104     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
105         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
106         goto error_free_pid;
107     }
108
109     /* Bind remote address as the kernel (pid 0). */
110     memset(&remote, 0, sizeof remote);
111     remote.nl_family = AF_NETLINK;
112     remote.nl_pid = 0;
113     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
114         VLOG_ERR("connect(0): %s", strerror(errno));
115         goto error_free_pid;
116     }
117
118     *sockp = sock;
119     return 0;
120
121 error_free_pid:
122     free_pid(sock->pid);
123 error:
124     if (retval == 0) {
125         retval = errno;
126         if (retval == 0) {
127             retval = EINVAL;
128         }
129     }
130     if (sock->fd >= 0) {
131         close(sock->fd);
132     }
133     free(sock);
134     return retval;
135 }
136
137 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
138  * sets '*sockp' to the new socket if successful, otherwise returns a positive
139  * errno value.  */
140 int
141 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
142 {
143     return nl_sock_create(src->protocol, sockp);
144 }
145
146 /* Destroys netlink socket 'sock'. */
147 void
148 nl_sock_destroy(struct nl_sock *sock)
149 {
150     if (sock) {
151         if (sock->dump) {
152             sock->dump = NULL;
153         } else {
154             close(sock->fd);
155             free_pid(sock->pid);
156             free(sock);
157         }
158     }
159 }
160
161 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
162  * successful, otherwise a positive errno value.
163  *
164  * Multicast group numbers are always positive.
165  *
166  * It is not an error to attempt to join a multicast group to which a socket
167  * already belongs. */
168 int
169 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
170 {
171     int error = nl_sock_cow__(sock);
172     if (error) {
173         return error;
174     }
175     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
176                    &multicast_group, sizeof multicast_group) < 0) {
177         VLOG_WARN("could not join multicast group %u (%s)",
178                   multicast_group, strerror(errno));
179         return errno;
180     }
181     sock->any_groups = true;
182     return 0;
183 }
184
185 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
186  * successful, otherwise a positive errno value.
187  *
188  * Multicast group numbers are always positive.
189  *
190  * It is not an error to attempt to leave a multicast group to which a socket
191  * does not belong.
192  *
193  * On success, reading from 'sock' will still return any messages that were
194  * received on 'multicast_group' before the group was left. */
195 int
196 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
197 {
198     assert(!sock->dump);
199     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
200                    &multicast_group, sizeof multicast_group) < 0) {
201         VLOG_WARN("could not leave multicast group %u (%s)",
202                   multicast_group, strerror(errno));
203         return errno;
204     }
205     return 0;
206 }
207
208 static int
209 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
210 {
211     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
212     int error;
213
214     nlmsg->nlmsg_len = msg->size;
215     nlmsg->nlmsg_pid = sock->pid;
216     do {
217         int retval;
218         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
219         error = retval < 0 ? errno : 0;
220     } while (error == EINTR);
221     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
222     if (!error) {
223         COVERAGE_INC(netlink_sent);
224     }
225     return error;
226 }
227
228 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
229  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
230  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
231  *
232  * Returns 0 if successful, otherwise a positive errno value.  If
233  * 'wait' is true, then the send will wait until buffer space is ready;
234  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
235 int
236 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
237 {
238     int error = nl_sock_cow__(sock);
239     if (error) {
240         return error;
241     }
242     return nl_sock_send__(sock, msg, wait);
243 }
244
245 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
246  * a single Netlink message.  (The message must be fully formed and not require
247  * finalization of its nlmsg_len or nlmsg_pid fields.)
248  *
249  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
250  * true, then the send will wait until buffer space is ready; otherwise,
251  * returns EAGAIN if the 'sock' send buffer is full. */
252 int
253 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
254               bool wait)
255 {
256     struct msghdr msg;
257     int error;
258
259     COVERAGE_INC(netlink_send);
260     memset(&msg, 0, sizeof msg);
261     msg.msg_iov = (struct iovec *) iov;
262     msg.msg_iovlen = n_iov;
263     do {
264         int retval;
265         retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
266         error = retval < 0 ? errno : 0;
267     } while (error == EINTR);
268     if (error != EAGAIN) {
269         log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len,
270                   sock->protocol);
271         if (!error) {
272             COVERAGE_INC(netlink_sent);
273         }
274     }
275     return error;
276 }
277
278 /* This stress option is useful for testing that OVS properly tolerates
279  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
280  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
281  * reply to a request.  They can also occur if messages arrive on a multicast
282  * channel faster than OVS can process them. */
283 STRESS_OPTION(
284     netlink_overflow, "simulate netlink socket receive buffer overflow",
285     5, 1, -1, 100);
286
287 static int
288 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
289 {
290     uint8_t tmp;
291     ssize_t bufsize = 2048;
292     ssize_t nbytes, nbytes2;
293     struct ofpbuf *buf;
294     struct nlmsghdr *nlmsghdr;
295     struct iovec iov;
296     struct msghdr msg = {
297         .msg_name = NULL,
298         .msg_namelen = 0,
299         .msg_iov = &iov,
300         .msg_iovlen = 1,
301         .msg_control = NULL,
302         .msg_controllen = 0,
303         .msg_flags = 0
304     };
305
306     buf = ofpbuf_new(bufsize);
307     *bufp = NULL;
308
309 try_again:
310     /* Attempt to read the message.  We don't know the size of the data
311      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
312      * and doubling the buffer size each time.
313      */
314     nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
315     iov.iov_base = nlmsghdr;
316     iov.iov_len = bufsize;
317     do {
318         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
319     } while (nbytes < 0 && errno == EINTR);
320     if (nbytes < 0) {
321         ofpbuf_delete(buf);
322         return errno;
323     }
324     if (msg.msg_flags & MSG_TRUNC) {
325         COVERAGE_INC(netlink_recv_retry);
326         bufsize *= 2;
327         ofpbuf_reinit(buf, bufsize);
328         goto try_again;
329     }
330     buf->size = nbytes;
331
332     /* We successfully read the message, so recv again to clear the queue */
333     iov.iov_base = &tmp;
334     iov.iov_len = 1;
335     do {
336         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
337     } while (nbytes2 < 0 && errno == EINTR);
338     if (nbytes2 < 0) {
339         if (errno == ENOBUFS) {
340             /* The kernel is notifying us that a message it tried to send to us
341              * was dropped.  We have to pass this along to the caller in case
342              * it wants to retry a request.  So kill the buffer, which we can
343              * re-read next time. */
344             COVERAGE_INC(netlink_overflow);
345             ofpbuf_delete(buf);
346             return ENOBUFS;
347         } else {
348             VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
349                         strerror(errno));
350         }
351     }
352     if (nbytes < sizeof *nlmsghdr
353         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
354         || nlmsghdr->nlmsg_len > nbytes) {
355         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
356                     bufsize, NLMSG_HDRLEN);
357         ofpbuf_delete(buf);
358         return EPROTO;
359     }
360
361     if (STRESS(netlink_overflow)) {
362         ofpbuf_delete(buf);
363         return ENOBUFS;
364     }
365
366     *bufp = buf;
367     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
368     COVERAGE_INC(netlink_received);
369
370     return 0;
371 }
372
373 /* Tries to receive a netlink message from the kernel on 'sock'.  If
374  * successful, stores the received message into '*bufp' and returns 0.  The
375  * caller is responsible for destroying the message with ofpbuf_delete().  On
376  * failure, returns a positive errno value and stores a null pointer into
377  * '*bufp'.
378  *
379  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
380  * returns EAGAIN if the 'sock' receive buffer is empty. */
381 int
382 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
383 {
384     int error = nl_sock_cow__(sock);
385     if (error) {
386         return error;
387     }
388     return nl_sock_recv__(sock, bufp, wait);
389 }
390
391 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
392  * successful, returns 0.  On failure, returns a positive errno value.
393  *
394  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
395  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
396  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
397  * reply, if any, is discarded.
398  *
399  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
400  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
401  * in nlmsg_flags.
402  *
403  * The caller is responsible for destroying 'request'.
404  *
405  * Bare Netlink is an unreliable transport protocol.  This function layers
406  * reliable delivery and reply semantics on top of bare Netlink.
407  *
408  * In Netlink, sending a request to the kernel is reliable enough, because the
409  * kernel will tell us if the message cannot be queued (and we will in that
410  * case put it on the transmit queue and wait until it can be delivered).
411  *
412  * Receiving the reply is the real problem: if the socket buffer is full when
413  * the kernel tries to send the reply, the reply will be dropped.  However, the
414  * kernel sets a flag that a reply has been dropped.  The next call to recv
415  * then returns ENOBUFS.  We can then re-send the request.
416  *
417  * Caveats:
418  *
419  *      1. Netlink depends on sequence numbers to match up requests and
420  *         replies.  The sender of a request supplies a sequence number, and
421  *         the reply echos back that sequence number.
422  *
423  *         This is fine, but (1) some kernel netlink implementations are
424  *         broken, in that they fail to echo sequence numbers and (2) this
425  *         function will drop packets with non-matching sequence numbers, so
426  *         that only a single request can be usefully transacted at a time.
427  *
428  *      2. Resending the request causes it to be re-executed, so the request
429  *         needs to be idempotent.
430  */
431 int
432 nl_sock_transact(struct nl_sock *sock,
433                  const struct ofpbuf *request, struct ofpbuf **replyp)
434 {
435     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
436     struct nlmsghdr *nlmsghdr;
437     struct ofpbuf *reply;
438     int retval;
439
440     if (replyp) {
441         *replyp = NULL;
442     }
443
444     /* Ensure that we get a reply even if this message doesn't ordinarily call
445      * for one. */
446     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
447
448 send:
449     retval = nl_sock_send(sock, request, true);
450     if (retval) {
451         return retval;
452     }
453
454 recv:
455     retval = nl_sock_recv(sock, &reply, true);
456     if (retval) {
457         if (retval == ENOBUFS) {
458             COVERAGE_INC(netlink_overflow);
459             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
460             goto send;
461         } else {
462             return retval;
463         }
464     }
465     nlmsghdr = nl_msg_nlmsghdr(reply);
466     if (seq != nlmsghdr->nlmsg_seq) {
467         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
468                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
469         ofpbuf_delete(reply);
470         goto recv;
471     }
472
473     /* If the reply is an error, discard the reply and return the error code.
474      *
475      * Except: if the reply is just an acknowledgement (error code of 0), and
476      * the caller is interested in the reply (replyp != NULL), pass the reply
477      * up to the caller.  Otherwise the caller will get a return value of 0
478      * and null '*replyp', which makes unwary callers likely to segfault. */
479     if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
480         ofpbuf_delete(reply);
481         if (retval) {
482             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
483                         retval, strerror(retval));
484         }
485         return retval != EAGAIN ? retval : EPROTO;
486     }
487
488     if (replyp) {
489         *replyp = reply;
490     } else {
491         ofpbuf_delete(reply);
492     }
493     return 0;
494 }
495
496 /* Drain all the messages currently in 'sock''s receive queue. */
497 int
498 nl_sock_drain(struct nl_sock *sock)
499 {
500     int error = nl_sock_cow__(sock);
501     if (error) {
502         return error;
503     }
504     return drain_rcvbuf(sock->fd);
505 }
506
507 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
508  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
509  * old fd over to the dump. */
510 static int
511 nl_sock_cow__(struct nl_sock *sock)
512 {
513     struct nl_sock *copy;
514     uint32_t tmp_pid;
515     int tmp_fd;
516     int error;
517
518     if (!sock->dump) {
519         return 0;
520     }
521
522     error = nl_sock_clone(sock, &copy);
523     if (error) {
524         return error;
525     }
526
527     tmp_fd = sock->fd;
528     sock->fd = copy->fd;
529     copy->fd = tmp_fd;
530
531     tmp_pid = sock->pid;
532     sock->pid = copy->pid;
533     copy->pid = tmp_pid;
534
535     sock->dump->sock = copy;
536     sock->dump = NULL;
537
538     return 0;
539 }
540
541 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
542  * 'sock', and initializes 'dump' to reflect the state of the operation.
543  *
544  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
545  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
546  * NLM_F_ACK will be set in nlmsg_flags.
547  *
548  * This Netlink socket library is designed to ensure that the dump is reliable
549  * and that it will not interfere with other operations on 'sock', including
550  * destroying or sending and receiving messages on 'sock'.  One corner case is
551  * not handled:
552  *
553  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
554  *     whose response has not yet been received (e.g. with nl_sock_recv()).
555  *     This is unusual: usually nl_sock_transact() is used to send a message
556  *     and receive its reply all in one go.
557  *
558  * This function provides no status indication.  An error status for the entire
559  * dump operation is provided when it is completed by calling nl_dump_done().
560  *
561  * The caller is responsible for destroying 'request'.
562  *
563  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
564  * in either order.
565  */
566 void
567 nl_dump_start(struct nl_dump *dump,
568               struct nl_sock *sock, const struct ofpbuf *request)
569 {
570     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
571     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
572     dump->seq = nlmsghdr->nlmsg_seq;
573     dump->buffer = NULL;
574     if (sock->any_groups || sock->dump) {
575         /* 'sock' might belong to some multicast group, or it already has an
576          * onoging dump.  Clone the socket to avoid possibly intermixing
577          * multicast messages or previous dump results with our results. */
578         dump->status = nl_sock_clone(sock, &dump->sock);
579         if (dump->status) {
580             return;
581         }
582     } else {
583         sock->dump = dump;
584         dump->sock = sock;
585         dump->status = 0;
586     }
587     dump->status = nl_sock_send__(sock, request, true);
588 }
589
590 /* Helper function for nl_dump_next(). */
591 static int
592 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
593 {
594     struct nlmsghdr *nlmsghdr;
595     struct ofpbuf *buffer;
596     int retval;
597
598     retval = nl_sock_recv__(dump->sock, bufferp, true);
599     if (retval) {
600         return retval == EINTR ? EAGAIN : retval;
601     }
602     buffer = *bufferp;
603
604     nlmsghdr = nl_msg_nlmsghdr(buffer);
605     if (dump->seq != nlmsghdr->nlmsg_seq) {
606         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
607                     nlmsghdr->nlmsg_seq, dump->seq);
608         return EAGAIN;
609     }
610
611     if (nl_msg_nlmsgerr(buffer, &retval)) {
612         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
613                      strerror(retval));
614         return retval && retval != EAGAIN ? retval : EPROTO;
615     }
616
617     return 0;
618 }
619
620 /* Attempts to retrieve another reply from 'dump', which must have been
621  * initialized with nl_dump_start().
622  *
623  * If successful, returns true and points 'reply->data' and 'reply->size' to
624  * the message that was retrieved.  The caller must not modify 'reply' (because
625  * it points into the middle of a larger buffer).
626  *
627  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
628  * to 0.  Failure might indicate an actual error or merely the end of replies.
629  * An error status for the entire dump operation is provided when it is
630  * completed by calling nl_dump_done().
631  */
632 bool
633 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
634 {
635     struct nlmsghdr *nlmsghdr;
636
637     reply->data = NULL;
638     reply->size = 0;
639     if (dump->status) {
640         return false;
641     }
642
643     if (dump->buffer && !dump->buffer->size) {
644         ofpbuf_delete(dump->buffer);
645         dump->buffer = NULL;
646     }
647     while (!dump->buffer) {
648         int retval = nl_dump_recv(dump, &dump->buffer);
649         if (retval) {
650             ofpbuf_delete(dump->buffer);
651             dump->buffer = NULL;
652             if (retval != EAGAIN) {
653                 dump->status = retval;
654                 return false;
655             }
656         }
657     }
658
659     nlmsghdr = nl_msg_next(dump->buffer, reply);
660     if (!nlmsghdr) {
661         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
662         dump->status = EPROTO;
663         return false;
664     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
665         dump->status = EOF;
666         return false;
667     }
668
669     return true;
670 }
671
672 /* Completes Netlink dump operation 'dump', which must have been initialized
673  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
674  * otherwise a positive errno value describing the problem. */
675 int
676 nl_dump_done(struct nl_dump *dump)
677 {
678     /* Drain any remaining messages that the client didn't read.  Otherwise the
679      * kernel will continue to queue them up and waste buffer space. */
680     while (!dump->status) {
681         struct ofpbuf reply;
682         if (!nl_dump_next(dump, &reply)) {
683             assert(dump->status);
684         }
685     }
686
687     if (dump->sock) {
688         if (dump->sock->dump) {
689             dump->sock->dump = NULL;
690         } else {
691             nl_sock_destroy(dump->sock);
692         }
693     }
694     ofpbuf_delete(dump->buffer);
695     return dump->status == EOF ? 0 : dump->status;
696 }
697
698 /* Causes poll_block() to wake up when any of the specified 'events' (which is
699  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
700 void
701 nl_sock_wait(const struct nl_sock *sock, short int events)
702 {
703     poll_fd_wait(sock->fd, events);
704 }
705 \f
706 /* Miscellaneous.  */
707
708 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
709     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
710 };
711
712 static int do_lookup_genl_family(const char *name)
713 {
714     struct nl_sock *sock;
715     struct ofpbuf request, *reply;
716     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
717     int retval;
718
719     retval = nl_sock_create(NETLINK_GENERIC, &sock);
720     if (retval) {
721         return -retval;
722     }
723
724     ofpbuf_init(&request, 0);
725     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
726                           CTRL_CMD_GETFAMILY, 1);
727     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
728     retval = nl_sock_transact(sock, &request, &reply);
729     ofpbuf_uninit(&request);
730     if (retval) {
731         nl_sock_destroy(sock);
732         return -retval;
733     }
734
735     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
736                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
737         nl_sock_destroy(sock);
738         ofpbuf_delete(reply);
739         return -EPROTO;
740     }
741
742     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
743     if (retval == 0) {
744         retval = -EPROTO;
745     }
746     nl_sock_destroy(sock);
747     ofpbuf_delete(reply);
748     return retval;
749 }
750
751 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
752  * number and stores it in '*number'.  If successful, returns 0 and the caller
753  * may use '*number' as the family number.  On failure, returns a positive
754  * errno value and '*number' caches the errno value. */
755 int
756 nl_lookup_genl_family(const char *name, int *number)
757 {
758     if (*number == 0) {
759         *number = do_lookup_genl_family(name);
760         assert(*number != 0);
761     }
762     return *number > 0 ? 0 : -*number;
763 }
764 \f
765 /* Netlink PID.
766  *
767  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
768  * programs that have a single Netlink socket use their Unix process ID as PID,
769  * and programs with multiple Netlink sockets add a unique per-socket
770  * identifier in the bits above the Unix process ID.
771  *
772  * The kernel has Netlink PID 0.
773  */
774
775 /* Parameters for how many bits in the PID should come from the Unix process ID
776  * and how many unique per-socket. */
777 #define SOCKET_BITS 10
778 #define MAX_SOCKETS (1u << SOCKET_BITS)
779
780 #define PROCESS_BITS (32 - SOCKET_BITS)
781 #define MAX_PROCESSES (1u << PROCESS_BITS)
782 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
783
784 /* Bit vector of unused socket identifiers. */
785 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
786
787 /* Allocates and returns a new Netlink PID. */
788 static int
789 alloc_pid(uint32_t *pid)
790 {
791     int i;
792
793     for (i = 0; i < MAX_SOCKETS; i++) {
794         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
795             avail_sockets[i / 32] |= 1u << (i % 32);
796             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
797             return 0;
798         }
799     }
800     VLOG_ERR("netlink pid space exhausted");
801     return ENOBUFS;
802 }
803
804 /* Makes the specified 'pid' available for reuse. */
805 static void
806 free_pid(uint32_t pid)
807 {
808     int sock = pid >> PROCESS_BITS;
809     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
810     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
811 }
812 \f
813 static void
814 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
815 {
816     struct nlmsg_flag {
817         unsigned int bits;
818         const char *name;
819     };
820     static const struct nlmsg_flag flags[] = {
821         { NLM_F_REQUEST, "REQUEST" },
822         { NLM_F_MULTI, "MULTI" },
823         { NLM_F_ACK, "ACK" },
824         { NLM_F_ECHO, "ECHO" },
825         { NLM_F_DUMP, "DUMP" },
826         { NLM_F_ROOT, "ROOT" },
827         { NLM_F_MATCH, "MATCH" },
828         { NLM_F_ATOMIC, "ATOMIC" },
829     };
830     const struct nlmsg_flag *flag;
831     uint16_t flags_left;
832
833     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
834                   h->nlmsg_len, h->nlmsg_type);
835     if (h->nlmsg_type == NLMSG_NOOP) {
836         ds_put_cstr(ds, "(no-op)");
837     } else if (h->nlmsg_type == NLMSG_ERROR) {
838         ds_put_cstr(ds, "(error)");
839     } else if (h->nlmsg_type == NLMSG_DONE) {
840         ds_put_cstr(ds, "(done)");
841     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
842         ds_put_cstr(ds, "(overrun)");
843     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
844         ds_put_cstr(ds, "(reserved)");
845     } else {
846         ds_put_cstr(ds, "(family-defined)");
847     }
848     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
849     flags_left = h->nlmsg_flags;
850     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
851         if ((flags_left & flag->bits) == flag->bits) {
852             ds_put_format(ds, "[%s]", flag->name);
853             flags_left &= ~flag->bits;
854         }
855     }
856     if (flags_left) {
857         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
858     }
859     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
860                   h->nlmsg_seq, h->nlmsg_pid,
861                   (int) (h->nlmsg_pid & PROCESS_MASK),
862                   (int) (h->nlmsg_pid >> PROCESS_BITS));
863 }
864
865 static char *
866 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
867 {
868     struct ds ds = DS_EMPTY_INITIALIZER;
869     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
870     if (h) {
871         nlmsghdr_to_string(h, &ds);
872         if (h->nlmsg_type == NLMSG_ERROR) {
873             const struct nlmsgerr *e;
874             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
875                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
876             if (e) {
877                 ds_put_format(&ds, " error(%d", e->error);
878                 if (e->error < 0) {
879                     ds_put_format(&ds, "(%s)", strerror(-e->error));
880                 }
881                 ds_put_cstr(&ds, ", in-reply-to(");
882                 nlmsghdr_to_string(&e->msg, &ds);
883                 ds_put_cstr(&ds, "))");
884             } else {
885                 ds_put_cstr(&ds, " error(truncated)");
886             }
887         } else if (h->nlmsg_type == NLMSG_DONE) {
888             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
889             if (error) {
890                 ds_put_format(&ds, " done(%d", *error);
891                 if (*error < 0) {
892                     ds_put_format(&ds, "(%s)", strerror(-*error));
893                 }
894                 ds_put_cstr(&ds, ")");
895             } else {
896                 ds_put_cstr(&ds, " done(truncated)");
897             }
898         } else if (protocol == NETLINK_GENERIC) {
899             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
900             if (genl) {
901                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
902                               genl->cmd, genl->version);
903             }
904         }
905     } else {
906         ds_put_cstr(&ds, "nl(truncated)");
907     }
908     return ds.string;
909 }
910
911 static void
912 log_nlmsg(const char *function, int error,
913           const void *message, size_t size, int protocol)
914 {
915     struct ofpbuf buffer;
916     char *nlmsg;
917
918     if (!VLOG_IS_DBG_ENABLED()) {
919         return;
920     }
921
922     ofpbuf_use_const(&buffer, message, size);
923     nlmsg = nlmsg_to_string(&buffer, protocol);
924     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
925     free(nlmsg);
926 }
927
928