netlink-socket: Reduce nl_sock_recv() from 2 (or more) system calls to 1.
[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     bool any_groups;
66     struct nl_dump *dump;
67 };
68
69 static int alloc_pid(uint32_t *);
70 static void free_pid(uint32_t);
71 static int nl_sock_cow__(struct nl_sock *);
72
73 /* Creates a new netlink socket for the given netlink 'protocol'
74  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
75  * new socket if successful, otherwise returns a positive errno value.  */
76 int
77 nl_sock_create(int protocol, struct nl_sock **sockp)
78 {
79     struct nl_sock *sock;
80     struct sockaddr_nl local, remote;
81     int retval = 0;
82
83     *sockp = NULL;
84     sock = malloc(sizeof *sock);
85     if (sock == NULL) {
86         return ENOMEM;
87     }
88
89     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
90     if (sock->fd < 0) {
91         VLOG_ERR("fcntl: %s", strerror(errno));
92         goto error;
93     }
94     sock->protocol = protocol;
95     sock->any_groups = false;
96     sock->dump = NULL;
97
98     retval = alloc_pid(&sock->pid);
99     if (retval) {
100         goto error;
101     }
102
103     /* Bind local address as our selected pid. */
104     memset(&local, 0, sizeof local);
105     local.nl_family = AF_NETLINK;
106     local.nl_pid = sock->pid;
107     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
108         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
109         goto error_free_pid;
110     }
111
112     /* Bind remote address as the kernel (pid 0). */
113     memset(&remote, 0, sizeof remote);
114     remote.nl_family = AF_NETLINK;
115     remote.nl_pid = 0;
116     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
117         VLOG_ERR("connect(0): %s", strerror(errno));
118         goto error_free_pid;
119     }
120
121     *sockp = sock;
122     return 0;
123
124 error_free_pid:
125     free_pid(sock->pid);
126 error:
127     if (retval == 0) {
128         retval = errno;
129         if (retval == 0) {
130             retval = EINVAL;
131         }
132     }
133     if (sock->fd >= 0) {
134         close(sock->fd);
135     }
136     free(sock);
137     return retval;
138 }
139
140 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
141  * sets '*sockp' to the new socket if successful, otherwise returns a positive
142  * errno value.  */
143 int
144 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
145 {
146     return nl_sock_create(src->protocol, sockp);
147 }
148
149 /* Destroys netlink socket 'sock'. */
150 void
151 nl_sock_destroy(struct nl_sock *sock)
152 {
153     if (sock) {
154         if (sock->dump) {
155             sock->dump = NULL;
156         } else {
157             close(sock->fd);
158             free_pid(sock->pid);
159             free(sock);
160         }
161     }
162 }
163
164 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
165  * successful, otherwise a positive errno value.
166  *
167  * Multicast group numbers are always positive.
168  *
169  * It is not an error to attempt to join a multicast group to which a socket
170  * already belongs. */
171 int
172 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
173 {
174     int error = nl_sock_cow__(sock);
175     if (error) {
176         return error;
177     }
178     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
179                    &multicast_group, sizeof multicast_group) < 0) {
180         VLOG_WARN("could not join multicast group %u (%s)",
181                   multicast_group, strerror(errno));
182         return errno;
183     }
184     sock->any_groups = true;
185     return 0;
186 }
187
188 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
189  * successful, otherwise a positive errno value.
190  *
191  * Multicast group numbers are always positive.
192  *
193  * It is not an error to attempt to leave a multicast group to which a socket
194  * does not belong.
195  *
196  * On success, reading from 'sock' will still return any messages that were
197  * received on 'multicast_group' before the group was left. */
198 int
199 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
200 {
201     assert(!sock->dump);
202     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
203                    &multicast_group, sizeof multicast_group) < 0) {
204         VLOG_WARN("could not leave multicast group %u (%s)",
205                   multicast_group, strerror(errno));
206         return errno;
207     }
208     return 0;
209 }
210
211 static int
212 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
213 {
214     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
215     int error;
216
217     nlmsg->nlmsg_len = msg->size;
218     nlmsg->nlmsg_pid = sock->pid;
219     do {
220         int retval;
221         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
222         error = retval < 0 ? errno : 0;
223     } while (error == EINTR);
224     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
225     if (!error) {
226         COVERAGE_INC(netlink_sent);
227     }
228     return error;
229 }
230
231 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
232  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
233  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
234  *
235  * Returns 0 if successful, otherwise a positive errno value.  If
236  * 'wait' is true, then the send will wait until buffer space is ready;
237  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
238 int
239 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
240 {
241     int error = nl_sock_cow__(sock);
242     if (error) {
243         return error;
244     }
245     return nl_sock_send__(sock, msg, wait);
246 }
247
248 /* This stress option is useful for testing that OVS properly tolerates
249  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
250  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
251  * reply to a request.  They can also occur if messages arrive on a multicast
252  * channel faster than OVS can process them. */
253 STRESS_OPTION(
254     netlink_overflow, "simulate netlink socket receive buffer overflow",
255     5, 1, -1, 100);
256
257 static int
258 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
259 {
260     /* We can't accurately predict the size of the data to be received.  Most
261      * received data will fit in a 2 kB buffer, so we allocate that much space.
262      * In case the data is actually bigger than that, we make available enough
263      * additional space to allow Netlink messages to be up to 64 kB long (a
264      * reasonable figure since that's the maximum length of a Netlink
265      * attribute). */
266     enum { MAX_SIZE = 65536 };
267     enum { HEAD_SIZE = 2048 };
268     enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
269
270     struct nlmsghdr *nlmsghdr;
271     uint8_t tail[TAIL_SIZE];
272     struct iovec iov[2];
273     struct ofpbuf *buf;
274     struct msghdr msg;
275     ssize_t retval;
276
277     *bufp = NULL;
278
279     buf = ofpbuf_new(HEAD_SIZE);
280     iov[0].iov_base = buf->data;
281     iov[0].iov_len = HEAD_SIZE;
282     iov[1].iov_base = tail;
283     iov[1].iov_len = TAIL_SIZE;
284
285     memset(&msg, 0, sizeof msg);
286     msg.msg_iov = iov;
287     msg.msg_iovlen = 2;
288
289     do {
290         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
291     } while (retval < 0 && errno == EINTR);
292
293     if (retval < 0) {
294         int error = errno;
295         if (error == ENOBUFS) {
296             /* Socket receive buffer overflow dropped one or more messages that
297              * the kernel tried to send to us. */
298             COVERAGE_INC(netlink_overflow);
299         }
300         ofpbuf_delete(buf);
301         return error;
302     }
303
304     if (msg.msg_flags & MSG_TRUNC) {
305         VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
306         ofpbuf_delete(buf);
307         return E2BIG;
308     }
309
310     ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
311     if (retval > HEAD_SIZE) {
312         COVERAGE_INC(netlink_recv_jumbo);
313         ofpbuf_put(buf, tail, retval - HEAD_SIZE);
314     }
315
316     nlmsghdr = buf->data;
317     if (retval < sizeof *nlmsghdr
318         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
319         || nlmsghdr->nlmsg_len > retval) {
320         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
321                     retval, NLMSG_HDRLEN);
322         ofpbuf_delete(buf);
323         return EPROTO;
324     }
325
326     if (STRESS(netlink_overflow)) {
327         ofpbuf_delete(buf);
328         return ENOBUFS;
329     }
330
331     *bufp = buf;
332     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
333     COVERAGE_INC(netlink_received);
334
335     return 0;
336 }
337
338 /* Tries to receive a netlink message from the kernel on 'sock'.  If
339  * successful, stores the received message into '*bufp' and returns 0.  The
340  * caller is responsible for destroying the message with ofpbuf_delete().  On
341  * failure, returns a positive errno value and stores a null pointer into
342  * '*bufp'.
343  *
344  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
345  * returns EAGAIN if the 'sock' receive buffer is empty. */
346 int
347 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
348 {
349     int error = nl_sock_cow__(sock);
350     if (error) {
351         return error;
352     }
353     return nl_sock_recv__(sock, bufp, wait);
354 }
355
356 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
357  * successful, returns 0.  On failure, returns a positive errno value.
358  *
359  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
360  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
361  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
362  * reply, if any, is discarded.
363  *
364  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
365  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
366  * in nlmsg_flags.
367  *
368  * The caller is responsible for destroying 'request'.
369  *
370  * Bare Netlink is an unreliable transport protocol.  This function layers
371  * reliable delivery and reply semantics on top of bare Netlink.
372  *
373  * In Netlink, sending a request to the kernel is reliable enough, because the
374  * kernel will tell us if the message cannot be queued (and we will in that
375  * case put it on the transmit queue and wait until it can be delivered).
376  *
377  * Receiving the reply is the real problem: if the socket buffer is full when
378  * the kernel tries to send the reply, the reply will be dropped.  However, the
379  * kernel sets a flag that a reply has been dropped.  The next call to recv
380  * then returns ENOBUFS.  We can then re-send the request.
381  *
382  * Caveats:
383  *
384  *      1. Netlink depends on sequence numbers to match up requests and
385  *         replies.  The sender of a request supplies a sequence number, and
386  *         the reply echos back that sequence number.
387  *
388  *         This is fine, but (1) some kernel netlink implementations are
389  *         broken, in that they fail to echo sequence numbers and (2) this
390  *         function will drop packets with non-matching sequence numbers, so
391  *         that only a single request can be usefully transacted at a time.
392  *
393  *      2. Resending the request causes it to be re-executed, so the request
394  *         needs to be idempotent.
395  */
396 int
397 nl_sock_transact(struct nl_sock *sock,
398                  const struct ofpbuf *request, struct ofpbuf **replyp)
399 {
400     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
401     struct nlmsghdr *nlmsghdr;
402     struct ofpbuf *reply;
403     int retval;
404
405     if (replyp) {
406         *replyp = NULL;
407     }
408
409     /* Ensure that we get a reply even if this message doesn't ordinarily call
410      * for one. */
411     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
412
413 send:
414     retval = nl_sock_send(sock, request, true);
415     if (retval) {
416         return retval;
417     }
418
419 recv:
420     retval = nl_sock_recv(sock, &reply, true);
421     if (retval) {
422         if (retval == ENOBUFS) {
423             COVERAGE_INC(netlink_overflow);
424             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
425             goto send;
426         } else {
427             return retval;
428         }
429     }
430     nlmsghdr = nl_msg_nlmsghdr(reply);
431     if (seq != nlmsghdr->nlmsg_seq) {
432         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
433                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
434         ofpbuf_delete(reply);
435         goto recv;
436     }
437
438     /* If the reply is an error, discard the reply and return the error code.
439      *
440      * Except: if the reply is just an acknowledgement (error code of 0), and
441      * the caller is interested in the reply (replyp != NULL), pass the reply
442      * up to the caller.  Otherwise the caller will get a return value of 0
443      * and null '*replyp', which makes unwary callers likely to segfault. */
444     if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
445         ofpbuf_delete(reply);
446         if (retval) {
447             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
448                         retval, strerror(retval));
449         }
450         return retval != EAGAIN ? retval : EPROTO;
451     }
452
453     if (replyp) {
454         *replyp = reply;
455     } else {
456         ofpbuf_delete(reply);
457     }
458     return 0;
459 }
460
461 /* Drain all the messages currently in 'sock''s receive queue. */
462 int
463 nl_sock_drain(struct nl_sock *sock)
464 {
465     int error = nl_sock_cow__(sock);
466     if (error) {
467         return error;
468     }
469     return drain_rcvbuf(sock->fd);
470 }
471
472 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
473  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
474  * old fd over to the dump. */
475 static int
476 nl_sock_cow__(struct nl_sock *sock)
477 {
478     struct nl_sock *copy;
479     uint32_t tmp_pid;
480     int tmp_fd;
481     int error;
482
483     if (!sock->dump) {
484         return 0;
485     }
486
487     error = nl_sock_clone(sock, &copy);
488     if (error) {
489         return error;
490     }
491
492     tmp_fd = sock->fd;
493     sock->fd = copy->fd;
494     copy->fd = tmp_fd;
495
496     tmp_pid = sock->pid;
497     sock->pid = copy->pid;
498     copy->pid = tmp_pid;
499
500     sock->dump->sock = copy;
501     sock->dump = NULL;
502
503     return 0;
504 }
505
506 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
507  * 'sock', and initializes 'dump' to reflect the state of the operation.
508  *
509  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
510  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
511  * NLM_F_ACK will be set in nlmsg_flags.
512  *
513  * This Netlink socket library is designed to ensure that the dump is reliable
514  * and that it will not interfere with other operations on 'sock', including
515  * destroying or sending and receiving messages on 'sock'.  One corner case is
516  * not handled:
517  *
518  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
519  *     whose response has not yet been received (e.g. with nl_sock_recv()).
520  *     This is unusual: usually nl_sock_transact() is used to send a message
521  *     and receive its reply all in one go.
522  *
523  * This function provides no status indication.  An error status for the entire
524  * dump operation is provided when it is completed by calling nl_dump_done().
525  *
526  * The caller is responsible for destroying 'request'.
527  *
528  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
529  * in either order.
530  */
531 void
532 nl_dump_start(struct nl_dump *dump,
533               struct nl_sock *sock, const struct ofpbuf *request)
534 {
535     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
536     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
537     dump->seq = nlmsghdr->nlmsg_seq;
538     dump->buffer = NULL;
539     if (sock->any_groups || sock->dump) {
540         /* 'sock' might belong to some multicast group, or it already has an
541          * onoging dump.  Clone the socket to avoid possibly intermixing
542          * multicast messages or previous dump results with our results. */
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 \f
671 /* Miscellaneous.  */
672
673 struct genl_family {
674     struct hmap_node hmap_node;
675     uint16_t id;
676     char *name;
677 };
678
679 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
680
681 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
682     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
683 };
684
685 static struct genl_family *
686 find_genl_family_by_id(uint16_t id)
687 {
688     struct genl_family *family;
689
690     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
691                              &genl_families) {
692         if (family->id == id) {
693             return family;
694         }
695     }
696     return NULL;
697 }
698
699 static void
700 define_genl_family(uint16_t id, const char *name)
701 {
702     struct genl_family *family = find_genl_family_by_id(id);
703
704     if (family) {
705         if (!strcmp(family->name, name)) {
706             return;
707         }
708         free(family->name);
709     } else {
710         family = xmalloc(sizeof *family);
711         family->id = id;
712         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
713     }
714     family->name = xstrdup(name);
715 }
716
717 static const char *
718 genl_family_to_name(uint16_t id)
719 {
720     if (id == GENL_ID_CTRL) {
721         return "control";
722     } else {
723         struct genl_family *family = find_genl_family_by_id(id);
724         return family ? family->name : "unknown";
725     }
726 }
727
728 static int do_lookup_genl_family(const char *name)
729 {
730     struct nl_sock *sock;
731     struct ofpbuf request, *reply;
732     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
733     int retval;
734
735     retval = nl_sock_create(NETLINK_GENERIC, &sock);
736     if (retval) {
737         return -retval;
738     }
739
740     ofpbuf_init(&request, 0);
741     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
742                           CTRL_CMD_GETFAMILY, 1);
743     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
744     retval = nl_sock_transact(sock, &request, &reply);
745     ofpbuf_uninit(&request);
746     if (retval) {
747         nl_sock_destroy(sock);
748         return -retval;
749     }
750
751     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
752                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
753         nl_sock_destroy(sock);
754         ofpbuf_delete(reply);
755         return -EPROTO;
756     }
757
758     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
759     if (retval == 0) {
760         retval = -EPROTO;
761     } else {
762         define_genl_family(retval, name);
763     }
764     nl_sock_destroy(sock);
765     ofpbuf_delete(reply);
766
767     return retval;
768 }
769
770 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
771  * number and stores it in '*number'.  If successful, returns 0 and the caller
772  * may use '*number' as the family number.  On failure, returns a positive
773  * errno value and '*number' caches the errno value. */
774 int
775 nl_lookup_genl_family(const char *name, int *number)
776 {
777     if (*number == 0) {
778         *number = do_lookup_genl_family(name);
779         assert(*number != 0);
780     }
781     return *number > 0 ? 0 : -*number;
782 }
783 \f
784 /* Netlink PID.
785  *
786  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
787  * programs that have a single Netlink socket use their Unix process ID as PID,
788  * and programs with multiple Netlink sockets add a unique per-socket
789  * identifier in the bits above the Unix process ID.
790  *
791  * The kernel has Netlink PID 0.
792  */
793
794 /* Parameters for how many bits in the PID should come from the Unix process ID
795  * and how many unique per-socket. */
796 #define SOCKET_BITS 10
797 #define MAX_SOCKETS (1u << SOCKET_BITS)
798
799 #define PROCESS_BITS (32 - SOCKET_BITS)
800 #define MAX_PROCESSES (1u << PROCESS_BITS)
801 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
802
803 /* Bit vector of unused socket identifiers. */
804 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
805
806 /* Allocates and returns a new Netlink PID. */
807 static int
808 alloc_pid(uint32_t *pid)
809 {
810     int i;
811
812     for (i = 0; i < MAX_SOCKETS; i++) {
813         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
814             avail_sockets[i / 32] |= 1u << (i % 32);
815             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
816             return 0;
817         }
818     }
819     VLOG_ERR("netlink pid space exhausted");
820     return ENOBUFS;
821 }
822
823 /* Makes the specified 'pid' available for reuse. */
824 static void
825 free_pid(uint32_t pid)
826 {
827     int sock = pid >> PROCESS_BITS;
828     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
829     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
830 }
831 \f
832 static void
833 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
834 {
835     struct nlmsg_flag {
836         unsigned int bits;
837         const char *name;
838     };
839     static const struct nlmsg_flag flags[] = {
840         { NLM_F_REQUEST, "REQUEST" },
841         { NLM_F_MULTI, "MULTI" },
842         { NLM_F_ACK, "ACK" },
843         { NLM_F_ECHO, "ECHO" },
844         { NLM_F_DUMP, "DUMP" },
845         { NLM_F_ROOT, "ROOT" },
846         { NLM_F_MATCH, "MATCH" },
847         { NLM_F_ATOMIC, "ATOMIC" },
848     };
849     const struct nlmsg_flag *flag;
850     uint16_t flags_left;
851
852     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
853                   h->nlmsg_len, h->nlmsg_type);
854     if (h->nlmsg_type == NLMSG_NOOP) {
855         ds_put_cstr(ds, "(no-op)");
856     } else if (h->nlmsg_type == NLMSG_ERROR) {
857         ds_put_cstr(ds, "(error)");
858     } else if (h->nlmsg_type == NLMSG_DONE) {
859         ds_put_cstr(ds, "(done)");
860     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
861         ds_put_cstr(ds, "(overrun)");
862     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
863         ds_put_cstr(ds, "(reserved)");
864     } else if (protocol == NETLINK_GENERIC) {
865         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
866     } else {
867         ds_put_cstr(ds, "(family-defined)");
868     }
869     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
870     flags_left = h->nlmsg_flags;
871     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
872         if ((flags_left & flag->bits) == flag->bits) {
873             ds_put_format(ds, "[%s]", flag->name);
874             flags_left &= ~flag->bits;
875         }
876     }
877     if (flags_left) {
878         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
879     }
880     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
881                   h->nlmsg_seq, h->nlmsg_pid,
882                   (int) (h->nlmsg_pid & PROCESS_MASK),
883                   (int) (h->nlmsg_pid >> PROCESS_BITS));
884 }
885
886 static char *
887 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
888 {
889     struct ds ds = DS_EMPTY_INITIALIZER;
890     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
891     if (h) {
892         nlmsghdr_to_string(h, protocol, &ds);
893         if (h->nlmsg_type == NLMSG_ERROR) {
894             const struct nlmsgerr *e;
895             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
896                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
897             if (e) {
898                 ds_put_format(&ds, " error(%d", e->error);
899                 if (e->error < 0) {
900                     ds_put_format(&ds, "(%s)", strerror(-e->error));
901                 }
902                 ds_put_cstr(&ds, ", in-reply-to(");
903                 nlmsghdr_to_string(&e->msg, protocol, &ds);
904                 ds_put_cstr(&ds, "))");
905             } else {
906                 ds_put_cstr(&ds, " error(truncated)");
907             }
908         } else if (h->nlmsg_type == NLMSG_DONE) {
909             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
910             if (error) {
911                 ds_put_format(&ds, " done(%d", *error);
912                 if (*error < 0) {
913                     ds_put_format(&ds, "(%s)", strerror(-*error));
914                 }
915                 ds_put_cstr(&ds, ")");
916             } else {
917                 ds_put_cstr(&ds, " done(truncated)");
918             }
919         } else if (protocol == NETLINK_GENERIC) {
920             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
921             if (genl) {
922                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
923                               genl->cmd, genl->version);
924             }
925         }
926     } else {
927         ds_put_cstr(&ds, "nl(truncated)");
928     }
929     return ds.string;
930 }
931
932 static void
933 log_nlmsg(const char *function, int error,
934           const void *message, size_t size, int protocol)
935 {
936     struct ofpbuf buffer;
937     char *nlmsg;
938
939     if (!VLOG_IS_DBG_ENABLED()) {
940         return;
941     }
942
943     ofpbuf_use_const(&buffer, message, size);
944     nlmsg = nlmsg_to_string(&buffer, protocol);
945     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
946     free(nlmsg);
947 }
948
949