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