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