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