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