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