5ab27a7ac6e00c29272f462e23449761775cadf3
[cascardo/ovs.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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 <sys/uio.h>
25 #include <unistd.h>
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "hash.h"
29 #include "hmap.h"
30 #include "netlink.h"
31 #include "netlink-protocol.h"
32 #include "ofpbuf.h"
33 #include "poll-loop.h"
34 #include "socket-util.h"
35 #include "stress.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(netlink_socket);
40
41 COVERAGE_DEFINE(netlink_overflow);
42 COVERAGE_DEFINE(netlink_received);
43 COVERAGE_DEFINE(netlink_recv_jumbo);
44 COVERAGE_DEFINE(netlink_send);
45 COVERAGE_DEFINE(netlink_sent);
46
47 /* Linux header file confusion causes this to be undefined. */
48 #ifndef SOL_NETLINK
49 #define SOL_NETLINK 270
50 #endif
51
52 /* A single (bad) Netlink message can in theory dump out many, many log
53  * messages, so the burst size is set quite high here to avoid missing useful
54  * information.  Also, at high logging levels we log *all* Netlink messages. */
55 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
56
57 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
58 static void log_nlmsg(const char *function, int error,
59                       const void *message, size_t size, int protocol);
60 \f
61 /* Netlink sockets. */
62
63 struct nl_sock
64 {
65     int fd;
66     uint32_t next_seq;
67     uint32_t pid;
68     int protocol;
69     struct nl_dump *dump;
70     unsigned int rcvbuf;        /* Receive buffer size (SO_RCVBUF). */
71 };
72
73 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
74  * of iovecs on the stack. */
75 #define MAX_IOVS 128
76
77 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
78  * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
79  *
80  * Initialized by nl_sock_create(). */
81 static int max_iovs;
82
83 static int nl_sock_cow__(struct nl_sock *);
84
85 /* Creates a new netlink socket for the given netlink 'protocol'
86  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
87  * new socket if successful, otherwise returns a positive errno value.  */
88 int
89 nl_sock_create(int protocol, struct nl_sock **sockp)
90 {
91     struct nl_sock *sock;
92     struct sockaddr_nl local, remote;
93     socklen_t local_size;
94     int rcvbuf;
95     int retval = 0;
96
97     if (!max_iovs) {
98         int save_errno = errno;
99         errno = 0;
100
101         max_iovs = sysconf(_SC_UIO_MAXIOV);
102         if (max_iovs < _XOPEN_IOV_MAX) {
103             if (max_iovs == -1 && errno) {
104                 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", strerror(errno));
105             }
106             max_iovs = _XOPEN_IOV_MAX;
107         } else if (max_iovs > MAX_IOVS) {
108             max_iovs = MAX_IOVS;
109         }
110
111         errno = save_errno;
112     }
113
114     *sockp = NULL;
115     sock = malloc(sizeof *sock);
116     if (sock == NULL) {
117         return ENOMEM;
118     }
119
120     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
121     if (sock->fd < 0) {
122         VLOG_ERR("fcntl: %s", strerror(errno));
123         goto error;
124     }
125     sock->protocol = protocol;
126     sock->dump = NULL;
127     sock->next_seq = 1;
128
129     rcvbuf = 1024 * 1024;
130     if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
131                    &rcvbuf, sizeof rcvbuf)) {
132         /* Only root can use SO_RCVBUFFORCE.  Everyone else gets EPERM.
133          * Warn only if the failure is therefore unexpected. */
134         if (errno != EPERM || !getuid()) {
135             VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
136                          "(%s)", rcvbuf, strerror(errno));
137         }
138     }
139
140     retval = get_socket_rcvbuf(sock->fd);
141     if (retval < 0) {
142         retval = -retval;
143         goto error;
144     }
145     sock->rcvbuf = retval;
146
147     /* Connect to kernel (pid 0) as remote address. */
148     memset(&remote, 0, sizeof remote);
149     remote.nl_family = AF_NETLINK;
150     remote.nl_pid = 0;
151     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
152         VLOG_ERR("connect(0): %s", strerror(errno));
153         goto error;
154     }
155
156     /* Obtain pid assigned by kernel. */
157     local_size = sizeof local;
158     if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
159         VLOG_ERR("getsockname: %s", strerror(errno));
160         goto error;
161     }
162     if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
163         VLOG_ERR("getsockname returned bad Netlink name");
164         retval = EINVAL;
165         goto error;
166     }
167     sock->pid = local.nl_pid;
168
169     *sockp = sock;
170     return 0;
171
172 error:
173     if (retval == 0) {
174         retval = errno;
175         if (retval == 0) {
176             retval = EINVAL;
177         }
178     }
179     if (sock->fd >= 0) {
180         close(sock->fd);
181     }
182     free(sock);
183     return retval;
184 }
185
186 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
187  * sets '*sockp' to the new socket if successful, otherwise returns a positive
188  * errno value.  */
189 int
190 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
191 {
192     return nl_sock_create(src->protocol, sockp);
193 }
194
195 /* Destroys netlink socket 'sock'. */
196 void
197 nl_sock_destroy(struct nl_sock *sock)
198 {
199     if (sock) {
200         if (sock->dump) {
201             sock->dump = NULL;
202         } else {
203             close(sock->fd);
204             free(sock);
205         }
206     }
207 }
208
209 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
210  * successful, otherwise a positive errno value.
211  *
212  * A socket that is subscribed to a multicast group that receives asynchronous
213  * notifications must not be used for Netlink transactions or dumps, because
214  * transactions and dumps can cause notifications to be lost.
215  *
216  * Multicast group numbers are always positive.
217  *
218  * It is not an error to attempt to join a multicast group to which a socket
219  * already belongs. */
220 int
221 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
222 {
223     int error = nl_sock_cow__(sock);
224     if (error) {
225         return error;
226     }
227     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
228                    &multicast_group, sizeof multicast_group) < 0) {
229         VLOG_WARN("could not join multicast group %u (%s)",
230                   multicast_group, strerror(errno));
231         return errno;
232     }
233     return 0;
234 }
235
236 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
237  * successful, otherwise a positive errno value.
238  *
239  * Multicast group numbers are always positive.
240  *
241  * It is not an error to attempt to leave a multicast group to which a socket
242  * does not belong.
243  *
244  * On success, reading from 'sock' will still return any messages that were
245  * received on 'multicast_group' before the group was left. */
246 int
247 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
248 {
249     assert(!sock->dump);
250     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
251                    &multicast_group, sizeof multicast_group) < 0) {
252         VLOG_WARN("could not leave multicast group %u (%s)",
253                   multicast_group, strerror(errno));
254         return errno;
255     }
256     return 0;
257 }
258
259 static int
260 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
261                uint32_t nlmsg_seq, bool wait)
262 {
263     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
264     int error;
265
266     nlmsg->nlmsg_len = msg->size;
267     nlmsg->nlmsg_seq = nlmsg_seq;
268     nlmsg->nlmsg_pid = sock->pid;
269     do {
270         int retval;
271         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
272         error = retval < 0 ? errno : 0;
273     } while (error == EINTR);
274     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
275     if (!error) {
276         COVERAGE_INC(netlink_sent);
277     }
278     return error;
279 }
280
281 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
282  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
283  * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
284  * sequence number, before the message is sent.
285  *
286  * Returns 0 if successful, otherwise a positive errno value.  If
287  * 'wait' is true, then the send will wait until buffer space is ready;
288  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
289 int
290 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
291 {
292     return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
293 }
294
295 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
296  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
297  * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
298  * 'nlmsg_seq', before the message is sent.
299  *
300  * Returns 0 if successful, otherwise a positive errno value.  If
301  * 'wait' is true, then the send will wait until buffer space is ready;
302  * otherwise, returns EAGAIN if the 'sock' send buffer is full.
303  *
304  * This function is suitable for sending a reply to a request that was received
305  * with sequence number 'nlmsg_seq'.  Otherwise, use nl_sock_send() instead. */
306 int
307 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
308                  uint32_t nlmsg_seq, bool wait)
309 {
310     int error = nl_sock_cow__(sock);
311     if (error) {
312         return error;
313     }
314     return nl_sock_send__(sock, msg, nlmsg_seq, wait);
315 }
316
317 /* This stress option is useful for testing that OVS properly tolerates
318  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
319  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
320  * reply to a request.  They can also occur if messages arrive on a multicast
321  * channel faster than OVS can process them. */
322 STRESS_OPTION(
323     netlink_overflow, "simulate netlink socket receive buffer overflow",
324     5, 1, -1, 100);
325
326 static int
327 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
328 {
329     /* We can't accurately predict the size of the data to be received.  The
330      * caller is supposed to have allocated enough space in 'buf' to handle the
331      * "typical" case.  To handle exceptions, we make available enough space in
332      * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
333      * figure since that's the maximum length of a Netlink attribute). */
334     struct nlmsghdr *nlmsghdr;
335     uint8_t tail[65536];
336     struct iovec iov[2];
337     struct msghdr msg;
338     ssize_t retval;
339
340     assert(buf->allocated >= sizeof *nlmsghdr);
341     ofpbuf_clear(buf);
342
343     iov[0].iov_base = buf->base;
344     iov[0].iov_len = buf->allocated;
345     iov[1].iov_base = tail;
346     iov[1].iov_len = sizeof tail;
347
348     memset(&msg, 0, sizeof msg);
349     msg.msg_iov = iov;
350     msg.msg_iovlen = 2;
351
352     do {
353         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
354     } while (retval < 0 && errno == EINTR);
355
356     if (retval < 0) {
357         int error = errno;
358         if (error == ENOBUFS) {
359             /* Socket receive buffer overflow dropped one or more messages that
360              * the kernel tried to send to us. */
361             COVERAGE_INC(netlink_overflow);
362         }
363         return error;
364     }
365
366     if (msg.msg_flags & MSG_TRUNC) {
367         VLOG_ERR_RL(&rl, "truncated message (longer than %zu bytes)",
368                     sizeof tail);
369         return E2BIG;
370     }
371
372     nlmsghdr = buf->data;
373     if (retval < sizeof *nlmsghdr
374         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
375         || nlmsghdr->nlmsg_len > retval) {
376         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %zu)",
377                     retval, sizeof *nlmsghdr);
378         return EPROTO;
379     }
380
381     if (STRESS(netlink_overflow)) {
382         return ENOBUFS;
383     }
384
385     buf->size = MIN(retval, buf->allocated);
386     if (retval > buf->allocated) {
387         COVERAGE_INC(netlink_recv_jumbo);
388         ofpbuf_put(buf, tail, retval - buf->allocated);
389     }
390
391     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
392     COVERAGE_INC(netlink_received);
393
394     return 0;
395 }
396
397 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'.  If
398  * 'wait' is true, waits for a message to be ready.  Otherwise, fails with
399  * EAGAIN if the 'sock' receive buffer is empty.
400  *
401  * The caller must have initialized 'buf' with an allocation of at least
402  * NLMSG_HDRLEN bytes.  For best performance, the caller should allocate enough
403  * space for a "typical" message.
404  *
405  * On success, returns 0 and replaces 'buf''s previous content by the received
406  * message.  This function expands 'buf''s allocated memory, as necessary, to
407  * hold the actual size of the received message.
408  *
409  * On failure, returns a positive errno value and clears 'buf' to zero length.
410  * 'buf' retains its previous memory allocation.
411  *
412  * Regardless of success or failure, this function resets 'buf''s headroom to
413  * 0. */
414 int
415 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
416 {
417     int error = nl_sock_cow__(sock);
418     if (error) {
419         return error;
420     }
421     return nl_sock_recv__(sock, buf, wait);
422 }
423
424 static void
425 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
426                         int error)
427 {
428     size_t i;
429
430     for (i = 0; i < n; i++) {
431         struct nl_transaction *txn = transactions[i];
432
433         txn->error = error;
434         if (txn->reply) {
435             ofpbuf_clear(txn->reply);
436         }
437     }
438 }
439
440 static int
441 nl_sock_transact_multiple__(struct nl_sock *sock,
442                             struct nl_transaction **transactions, size_t n,
443                             size_t *done)
444 {
445     uint64_t tmp_reply_stub[1024 / 8];
446     struct nl_transaction tmp_txn;
447     struct ofpbuf tmp_reply;
448
449     uint32_t base_seq;
450     struct iovec iovs[MAX_IOVS];
451     struct msghdr msg;
452     int error;
453     int i;
454
455     base_seq = nl_sock_allocate_seq(sock, n);
456     *done = 0;
457     for (i = 0; i < n; i++) {
458         struct nl_transaction *txn = transactions[i];
459         struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
460
461         nlmsg->nlmsg_len = txn->request->size;
462         nlmsg->nlmsg_seq = base_seq + i;
463         nlmsg->nlmsg_pid = sock->pid;
464
465         iovs[i].iov_base = txn->request->data;
466         iovs[i].iov_len = txn->request->size;
467     }
468
469     memset(&msg, 0, sizeof msg);
470     msg.msg_iov = iovs;
471     msg.msg_iovlen = n;
472     do {
473         error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
474     } while (error == EINTR);
475
476     for (i = 0; i < n; i++) {
477         struct nl_transaction *txn = transactions[i];
478
479         log_nlmsg(__func__, error, txn->request->data, txn->request->size,
480                   sock->protocol);
481     }
482     if (!error) {
483         COVERAGE_ADD(netlink_sent, n);
484     }
485
486     if (error) {
487         return error;
488     }
489
490     ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
491     tmp_txn.request = NULL;
492     tmp_txn.reply = &tmp_reply;
493     tmp_txn.error = 0;
494     while (n > 0) {
495         struct nl_transaction *buf_txn, *txn;
496         uint32_t seq;
497
498         /* Find a transaction whose buffer we can use for receiving a reply.
499          * If no such transaction is left, use tmp_txn. */
500         buf_txn = &tmp_txn;
501         for (i = 0; i < n; i++) {
502             if (transactions[i]->reply) {
503                 buf_txn = transactions[i];
504                 break;
505             }
506         }
507
508         /* Receive a reply. */
509         error = nl_sock_recv__(sock, buf_txn->reply, false);
510         if (error) {
511             if (error == EAGAIN) {
512                 nl_sock_record_errors__(transactions, n, 0);
513                 *done += n;
514                 error = 0;
515             }
516             break;
517         }
518
519         /* Match the reply up with a transaction. */
520         seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
521         if (seq < base_seq || seq >= base_seq + n) {
522             VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
523             continue;
524         }
525         i = seq - base_seq;
526         txn = transactions[i];
527
528         /* Fill in the results for 'txn'. */
529         if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
530             if (txn->reply) {
531                 ofpbuf_clear(txn->reply);
532             }
533             if (txn->error) {
534                 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
535                             error, strerror(txn->error));
536             }
537         } else {
538             txn->error = 0;
539             if (txn->reply && txn != buf_txn) {
540                 /* Swap buffers. */
541                 struct ofpbuf *reply = buf_txn->reply;
542                 buf_txn->reply = txn->reply;
543                 txn->reply = reply;
544             }
545         }
546
547         /* Fill in the results for transactions before 'txn'.  (We have to do
548          * this after the results for 'txn' itself because of the buffer swap
549          * above.) */
550         nl_sock_record_errors__(transactions, i, 0);
551
552         /* Advance. */
553         *done += i + 1;
554         transactions += i + 1;
555         n -= i + 1;
556         base_seq += i + 1;
557     }
558     ofpbuf_uninit(&tmp_reply);
559
560     return error;
561 }
562
563 /* Sends the 'request' member of the 'n' transactions in 'transactions' on
564  * 'sock', in order, and receives responses to all of them.  Fills in the
565  * 'error' member of each transaction with 0 if it was successful, otherwise
566  * with a positive errno value.  If 'reply' is nonnull, then it will be filled
567  * with the reply if the message receives a detailed reply.  In other cases,
568  * i.e. where the request failed or had no reply beyond an indication of
569  * success, 'reply' will be cleared if it is nonnull.
570  *
571  * The caller is responsible for destroying each request and reply, and the
572  * transactions array itself.
573  *
574  * Before sending each message, this function will finalize nlmsg_len in each
575  * 'request' to match the ofpbuf's size,  set nlmsg_pid to 'sock''s pid, and
576  * initialize nlmsg_seq.
577  *
578  * Bare Netlink is an unreliable transport protocol.  This function layers
579  * reliable delivery and reply semantics on top of bare Netlink.  See
580  * nl_sock_transact() for some caveats.
581  */
582 void
583 nl_sock_transact_multiple(struct nl_sock *sock,
584                           struct nl_transaction **transactions, size_t n)
585 {
586     int max_batch_count;
587     int error;
588
589     if (!n) {
590         return;
591     }
592
593     error = nl_sock_cow__(sock);
594     if (error) {
595         nl_sock_record_errors__(transactions, n, error);
596         return;
597     }
598
599     /* In theory, every request could have a 64 kB reply.  But the default and
600      * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
601      * be a bit below 128 kB, so that would only allow a single message in a
602      * "batch".  So we assume that replies average (at most) 4 kB, which allows
603      * a good deal of batching.
604      *
605      * In practice, most of the requests that we batch either have no reply at
606      * all or a brief reply. */
607     max_batch_count = MAX(sock->rcvbuf / 4096, 1);
608     max_batch_count = MIN(max_batch_count, max_iovs);
609
610     while (n > 0) {
611         size_t count, bytes;
612         size_t done;
613
614         /* Batch up to 'max_batch_count' transactions.  But cap it at about a
615          * page of requests total because big skbuffs are expensive to
616          * allocate in the kernel.  */
617 #if defined(PAGESIZE)
618         enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
619 #else
620         enum { MAX_BATCH_BYTES = 4096 - 512 };
621 #endif
622         bytes = transactions[0]->request->size;
623         for (count = 1; count < n && count < max_batch_count; count++) {
624             if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
625                 break;
626             }
627             bytes += transactions[count]->request->size;
628         }
629
630         error = nl_sock_transact_multiple__(sock, transactions, count, &done);
631         transactions += done;
632         n -= done;
633
634         if (error == ENOBUFS) {
635             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
636         } else if (error) {
637             VLOG_ERR_RL(&rl, "transaction error (%s)", strerror(error));
638             nl_sock_record_errors__(transactions, n, error);
639         }
640     }
641 }
642
643 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
644  * successful, returns 0.  On failure, returns a positive errno value.
645  *
646  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
647  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
648  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
649  * reply, if any, is discarded.
650  *
651  * Before the message is sent, nlmsg_len in 'request' will be finalized to
652  * match msg->size, nlmsg_pid will be set to 'sock''s pid, and nlmsg_seq will
653  * be initialized, NLM_F_ACK will be set in nlmsg_flags.
654  *
655  * The caller is responsible for destroying 'request'.
656  *
657  * Bare Netlink is an unreliable transport protocol.  This function layers
658  * reliable delivery and reply semantics on top of bare Netlink.
659  *
660  * In Netlink, sending a request to the kernel is reliable enough, because the
661  * kernel will tell us if the message cannot be queued (and we will in that
662  * case put it on the transmit queue and wait until it can be delivered).
663  *
664  * Receiving the reply is the real problem: if the socket buffer is full when
665  * the kernel tries to send the reply, the reply will be dropped.  However, the
666  * kernel sets a flag that a reply has been dropped.  The next call to recv
667  * then returns ENOBUFS.  We can then re-send the request.
668  *
669  * Caveats:
670  *
671  *      1. Netlink depends on sequence numbers to match up requests and
672  *         replies.  The sender of a request supplies a sequence number, and
673  *         the reply echos back that sequence number.
674  *
675  *         This is fine, but (1) some kernel netlink implementations are
676  *         broken, in that they fail to echo sequence numbers and (2) this
677  *         function will drop packets with non-matching sequence numbers, so
678  *         that only a single request can be usefully transacted at a time.
679  *
680  *      2. Resending the request causes it to be re-executed, so the request
681  *         needs to be idempotent.
682  */
683 int
684 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
685                  struct ofpbuf **replyp)
686 {
687     struct nl_transaction *transactionp;
688     struct nl_transaction transaction;
689
690     transaction.request = CONST_CAST(struct ofpbuf *, request);
691     transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
692     transactionp = &transaction;
693
694     nl_sock_transact_multiple(sock, &transactionp, 1);
695
696     if (replyp) {
697         if (transaction.error) {
698             ofpbuf_delete(transaction.reply);
699             *replyp = NULL;
700         } else {
701             *replyp = transaction.reply;
702         }
703     }
704
705     return transaction.error;
706 }
707
708 /* Drain all the messages currently in 'sock''s receive queue. */
709 int
710 nl_sock_drain(struct nl_sock *sock)
711 {
712     int error = nl_sock_cow__(sock);
713     if (error) {
714         return error;
715     }
716     return drain_rcvbuf(sock->fd);
717 }
718
719 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
720  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
721  * old fd over to the dump. */
722 static int
723 nl_sock_cow__(struct nl_sock *sock)
724 {
725     struct nl_sock *copy;
726     uint32_t tmp_pid;
727     int tmp_fd;
728     int error;
729
730     if (!sock->dump) {
731         return 0;
732     }
733
734     error = nl_sock_clone(sock, &copy);
735     if (error) {
736         return error;
737     }
738
739     tmp_fd = sock->fd;
740     sock->fd = copy->fd;
741     copy->fd = tmp_fd;
742
743     tmp_pid = sock->pid;
744     sock->pid = copy->pid;
745     copy->pid = tmp_pid;
746
747     sock->dump->sock = copy;
748     sock->dump = NULL;
749
750     return 0;
751 }
752
753 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
754  * 'sock', and initializes 'dump' to reflect the state of the operation.
755  *
756  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
757  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
758  * NLM_F_ACK will be set in nlmsg_flags.
759  *
760  * This Netlink socket library is designed to ensure that the dump is reliable
761  * and that it will not interfere with other operations on 'sock', including
762  * destroying or sending and receiving messages on 'sock'.  One corner case is
763  * not handled:
764  *
765  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
766  *     whose response has not yet been received (e.g. with nl_sock_recv()).
767  *     This is unusual: usually nl_sock_transact() is used to send a message
768  *     and receive its reply all in one go.
769  *
770  * This function provides no status indication.  An error status for the entire
771  * dump operation is provided when it is completed by calling nl_dump_done().
772  *
773  * The caller is responsible for destroying 'request'.
774  *
775  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
776  * in either order.
777  */
778 void
779 nl_dump_start(struct nl_dump *dump,
780               struct nl_sock *sock, const struct ofpbuf *request)
781 {
782     ofpbuf_init(&dump->buffer, 4096);
783     if (sock->dump) {
784         /* 'sock' already has an ongoing dump.  Clone the socket because
785          * Netlink only allows one dump at a time. */
786         dump->status = nl_sock_clone(sock, &dump->sock);
787         if (dump->status) {
788             return;
789         }
790     } else {
791         sock->dump = dump;
792         dump->sock = sock;
793         dump->status = 0;
794     }
795
796     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
797     dump->status = nl_sock_send__(sock, request, nl_sock_allocate_seq(sock, 1),
798                                   true);
799     dump->seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
800 }
801
802 /* Helper function for nl_dump_next(). */
803 static int
804 nl_dump_recv(struct nl_dump *dump)
805 {
806     struct nlmsghdr *nlmsghdr;
807     int retval;
808
809     retval = nl_sock_recv__(dump->sock, &dump->buffer, true);
810     if (retval) {
811         return retval == EINTR ? EAGAIN : retval;
812     }
813
814     nlmsghdr = nl_msg_nlmsghdr(&dump->buffer);
815     if (dump->seq != nlmsghdr->nlmsg_seq) {
816         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
817                     nlmsghdr->nlmsg_seq, dump->seq);
818         return EAGAIN;
819     }
820
821     if (nl_msg_nlmsgerr(&dump->buffer, &retval)) {
822         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
823                      strerror(retval));
824         return retval && retval != EAGAIN ? retval : EPROTO;
825     }
826
827     return 0;
828 }
829
830 /* Attempts to retrieve another reply from 'dump', which must have been
831  * initialized with nl_dump_start().
832  *
833  * If successful, returns true and points 'reply->data' and 'reply->size' to
834  * the message that was retrieved.  The caller must not modify 'reply' (because
835  * it points into the middle of a larger buffer).
836  *
837  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
838  * to 0.  Failure might indicate an actual error or merely the end of replies.
839  * An error status for the entire dump operation is provided when it is
840  * completed by calling nl_dump_done().
841  */
842 bool
843 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
844 {
845     struct nlmsghdr *nlmsghdr;
846
847     reply->data = NULL;
848     reply->size = 0;
849     if (dump->status) {
850         return false;
851     }
852
853     while (!dump->buffer.size) {
854         int retval = nl_dump_recv(dump);
855         if (retval) {
856             ofpbuf_clear(&dump->buffer);
857             if (retval != EAGAIN) {
858                 dump->status = retval;
859                 return false;
860             }
861         }
862     }
863
864     nlmsghdr = nl_msg_next(&dump->buffer, reply);
865     if (!nlmsghdr) {
866         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
867         dump->status = EPROTO;
868         return false;
869     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
870         dump->status = EOF;
871         return false;
872     }
873
874     return true;
875 }
876
877 /* Completes Netlink dump operation 'dump', which must have been initialized
878  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
879  * otherwise a positive errno value describing the problem. */
880 int
881 nl_dump_done(struct nl_dump *dump)
882 {
883     /* Drain any remaining messages that the client didn't read.  Otherwise the
884      * kernel will continue to queue them up and waste buffer space. */
885     while (!dump->status) {
886         struct ofpbuf reply;
887         if (!nl_dump_next(dump, &reply)) {
888             assert(dump->status);
889         }
890     }
891
892     if (dump->sock) {
893         if (dump->sock->dump) {
894             dump->sock->dump = NULL;
895         } else {
896             nl_sock_destroy(dump->sock);
897         }
898     }
899     ofpbuf_uninit(&dump->buffer);
900     return dump->status == EOF ? 0 : dump->status;
901 }
902
903 /* Causes poll_block() to wake up when any of the specified 'events' (which is
904  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
905 void
906 nl_sock_wait(const struct nl_sock *sock, short int events)
907 {
908     poll_fd_wait(sock->fd, events);
909 }
910
911 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
912  * that can't use nl_sock_wait().
913  *
914  * It's a little tricky to use the returned fd correctly, because nl_sock does
915  * "copy on write" to allow a single nl_sock to be used for notifications,
916  * transactions, and dumps.  If 'sock' is used only for notifications and
917  * transactions (and never for dump) then the usage is safe. */
918 int
919 nl_sock_fd(const struct nl_sock *sock)
920 {
921     return sock->fd;
922 }
923
924 /* Returns the PID associated with this socket. */
925 uint32_t
926 nl_sock_pid(const struct nl_sock *sock)
927 {
928     return sock->pid;
929 }
930 \f
931 /* Miscellaneous.  */
932
933 struct genl_family {
934     struct hmap_node hmap_node;
935     uint16_t id;
936     char *name;
937 };
938
939 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
940
941 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
942     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
943     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
944 };
945
946 static struct genl_family *
947 find_genl_family_by_id(uint16_t id)
948 {
949     struct genl_family *family;
950
951     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
952                              &genl_families) {
953         if (family->id == id) {
954             return family;
955         }
956     }
957     return NULL;
958 }
959
960 static void
961 define_genl_family(uint16_t id, const char *name)
962 {
963     struct genl_family *family = find_genl_family_by_id(id);
964
965     if (family) {
966         if (!strcmp(family->name, name)) {
967             return;
968         }
969         free(family->name);
970     } else {
971         family = xmalloc(sizeof *family);
972         family->id = id;
973         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
974     }
975     family->name = xstrdup(name);
976 }
977
978 static const char *
979 genl_family_to_name(uint16_t id)
980 {
981     if (id == GENL_ID_CTRL) {
982         return "control";
983     } else {
984         struct genl_family *family = find_genl_family_by_id(id);
985         return family ? family->name : "unknown";
986     }
987 }
988
989 static int
990 do_lookup_genl_family(const char *name, struct nlattr **attrs,
991                       struct ofpbuf **replyp)
992 {
993     struct nl_sock *sock;
994     struct ofpbuf request, *reply;
995     int error;
996
997     *replyp = NULL;
998     error = nl_sock_create(NETLINK_GENERIC, &sock);
999     if (error) {
1000         return error;
1001     }
1002
1003     ofpbuf_init(&request, 0);
1004     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1005                           CTRL_CMD_GETFAMILY, 1);
1006     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1007     error = nl_sock_transact(sock, &request, &reply);
1008     ofpbuf_uninit(&request);
1009     if (error) {
1010         nl_sock_destroy(sock);
1011         return error;
1012     }
1013
1014     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1015                          family_policy, attrs, ARRAY_SIZE(family_policy))
1016         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1017         nl_sock_destroy(sock);
1018         ofpbuf_delete(reply);
1019         return EPROTO;
1020     }
1021
1022     nl_sock_destroy(sock);
1023     *replyp = reply;
1024     return 0;
1025 }
1026
1027 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1028  * When successful, writes its result to 'multicast_group' and returns 0.
1029  * Otherwise, clears 'multicast_group' and returns a positive error code.
1030  *
1031  * Some kernels do not support looking up a multicast group with this function.
1032  * In this case, 'multicast_group' will be populated with 'fallback'. */
1033 int
1034 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1035                        unsigned int *multicast_group, unsigned int fallback)
1036 {
1037     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1038     const struct nlattr *mc;
1039     struct ofpbuf *reply;
1040     unsigned int left;
1041     int error;
1042
1043     *multicast_group = 0;
1044     error = do_lookup_genl_family(family_name, family_attrs, &reply);
1045     if (error) {
1046         return error;
1047     }
1048
1049     if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1050         *multicast_group = fallback;
1051         VLOG_WARN("%s-%s: has no multicast group, using fallback %d",
1052                   family_name, group_name, *multicast_group);
1053         error = 0;
1054         goto exit;
1055     }
1056
1057     NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1058         static const struct nl_policy mc_policy[] = {
1059             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1060             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1061         };
1062
1063         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1064         const char *mc_name;
1065
1066         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1067             error = EPROTO;
1068             goto exit;
1069         }
1070
1071         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1072         if (!strcmp(group_name, mc_name)) {
1073             *multicast_group =
1074                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1075             error = 0;
1076             goto exit;
1077         }
1078     }
1079     error = EPROTO;
1080
1081 exit:
1082     ofpbuf_delete(reply);
1083     return error;
1084 }
1085
1086 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1087  * number and stores it in '*number'.  If successful, returns 0 and the caller
1088  * may use '*number' as the family number.  On failure, returns a positive
1089  * errno value and '*number' caches the errno value. */
1090 int
1091 nl_lookup_genl_family(const char *name, int *number)
1092 {
1093     if (*number == 0) {
1094         struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1095         struct ofpbuf *reply;
1096         int error;
1097
1098         error = do_lookup_genl_family(name, attrs, &reply);
1099         if (!error) {
1100             *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1101             define_genl_family(*number, name);
1102         } else {
1103             *number = -error;
1104         }
1105         ofpbuf_delete(reply);
1106
1107         assert(*number != 0);
1108     }
1109     return *number > 0 ? 0 : -*number;
1110 }
1111 \f
1112 static uint32_t
1113 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1114 {
1115     uint32_t seq = sock->next_seq;
1116
1117     sock->next_seq += n;
1118
1119     /* Make it impossible for the next request for sequence numbers to wrap
1120      * around to 0.  Start over with 1 to avoid ever using a sequence number of
1121      * 0, because the kernel uses sequence number 0 for notifications. */
1122     if (sock->next_seq >= UINT32_MAX / 2) {
1123         sock->next_seq = 1;
1124     }
1125
1126     return seq;
1127 }
1128
1129 static void
1130 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1131 {
1132     struct nlmsg_flag {
1133         unsigned int bits;
1134         const char *name;
1135     };
1136     static const struct nlmsg_flag flags[] = {
1137         { NLM_F_REQUEST, "REQUEST" },
1138         { NLM_F_MULTI, "MULTI" },
1139         { NLM_F_ACK, "ACK" },
1140         { NLM_F_ECHO, "ECHO" },
1141         { NLM_F_DUMP, "DUMP" },
1142         { NLM_F_ROOT, "ROOT" },
1143         { NLM_F_MATCH, "MATCH" },
1144         { NLM_F_ATOMIC, "ATOMIC" },
1145     };
1146     const struct nlmsg_flag *flag;
1147     uint16_t flags_left;
1148
1149     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1150                   h->nlmsg_len, h->nlmsg_type);
1151     if (h->nlmsg_type == NLMSG_NOOP) {
1152         ds_put_cstr(ds, "(no-op)");
1153     } else if (h->nlmsg_type == NLMSG_ERROR) {
1154         ds_put_cstr(ds, "(error)");
1155     } else if (h->nlmsg_type == NLMSG_DONE) {
1156         ds_put_cstr(ds, "(done)");
1157     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1158         ds_put_cstr(ds, "(overrun)");
1159     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1160         ds_put_cstr(ds, "(reserved)");
1161     } else if (protocol == NETLINK_GENERIC) {
1162         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1163     } else {
1164         ds_put_cstr(ds, "(family-defined)");
1165     }
1166     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1167     flags_left = h->nlmsg_flags;
1168     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1169         if ((flags_left & flag->bits) == flag->bits) {
1170             ds_put_format(ds, "[%s]", flag->name);
1171             flags_left &= ~flag->bits;
1172         }
1173     }
1174     if (flags_left) {
1175         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1176     }
1177     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1178                   h->nlmsg_seq, h->nlmsg_pid);
1179 }
1180
1181 static char *
1182 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1183 {
1184     struct ds ds = DS_EMPTY_INITIALIZER;
1185     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1186     if (h) {
1187         nlmsghdr_to_string(h, protocol, &ds);
1188         if (h->nlmsg_type == NLMSG_ERROR) {
1189             const struct nlmsgerr *e;
1190             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1191                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1192             if (e) {
1193                 ds_put_format(&ds, " error(%d", e->error);
1194                 if (e->error < 0) {
1195                     ds_put_format(&ds, "(%s)", strerror(-e->error));
1196                 }
1197                 ds_put_cstr(&ds, ", in-reply-to(");
1198                 nlmsghdr_to_string(&e->msg, protocol, &ds);
1199                 ds_put_cstr(&ds, "))");
1200             } else {
1201                 ds_put_cstr(&ds, " error(truncated)");
1202             }
1203         } else if (h->nlmsg_type == NLMSG_DONE) {
1204             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1205             if (error) {
1206                 ds_put_format(&ds, " done(%d", *error);
1207                 if (*error < 0) {
1208                     ds_put_format(&ds, "(%s)", strerror(-*error));
1209                 }
1210                 ds_put_cstr(&ds, ")");
1211             } else {
1212                 ds_put_cstr(&ds, " done(truncated)");
1213             }
1214         } else if (protocol == NETLINK_GENERIC) {
1215             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1216             if (genl) {
1217                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1218                               genl->cmd, genl->version);
1219             }
1220         }
1221     } else {
1222         ds_put_cstr(&ds, "nl(truncated)");
1223     }
1224     return ds.string;
1225 }
1226
1227 static void
1228 log_nlmsg(const char *function, int error,
1229           const void *message, size_t size, int protocol)
1230 {
1231     struct ofpbuf buffer;
1232     char *nlmsg;
1233
1234     if (!VLOG_IS_DBG_ENABLED()) {
1235         return;
1236     }
1237
1238     ofpbuf_use_const(&buffer, message, size);
1239     nlmsg = nlmsg_to_string(&buffer, protocol);
1240     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1241     free(nlmsg);
1242 }