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