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