xref: /openbmc/qemu/block/linux-aio.c (revision 89aafcf2)
1 /*
2  * Linux native AIO support.
3  *
4  * Copyright (C) 2009 IBM, Corp.
5  * Copyright (C) 2009 Red Hat, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 #include "qemu/osdep.h"
11 #include "block/aio.h"
12 #include "qemu/queue.h"
13 #include "block/block.h"
14 #include "block/raw-aio.h"
15 #include "qemu/event_notifier.h"
16 #include "qemu/coroutine.h"
17 #include "qapi/error.h"
18 
19 /* Only used for assertions.  */
20 #include "qemu/coroutine_int.h"
21 
22 #include <libaio.h>
23 
24 /*
25  * Queue size (per-device).
26  *
27  * XXX: eventually we need to communicate this to the guest and/or make it
28  *      tunable by the guest.  If we get more outstanding requests at a time
29  *      than this we will get EAGAIN from io_submit which is communicated to
30  *      the guest as an I/O error.
31  */
32 #define MAX_EVENTS 1024
33 
34 /* Maximum number of requests in a batch. (default value) */
35 #define DEFAULT_MAX_BATCH 32
36 
37 struct qemu_laiocb {
38     Coroutine *co;
39     LinuxAioState *ctx;
40     struct iocb iocb;
41     ssize_t ret;
42     size_t nbytes;
43     QEMUIOVector *qiov;
44     bool is_read;
45     QSIMPLEQ_ENTRY(qemu_laiocb) next;
46 };
47 
48 typedef struct {
49     int plugged;
50     unsigned int in_queue;
51     unsigned int in_flight;
52     bool blocked;
53     QSIMPLEQ_HEAD(, qemu_laiocb) pending;
54 } LaioQueue;
55 
56 struct LinuxAioState {
57     AioContext *aio_context;
58 
59     io_context_t ctx;
60     EventNotifier e;
61 
62     /* No locking required, only accessed from AioContext home thread */
63     LaioQueue io_q;
64     QEMUBH *completion_bh;
65     int event_idx;
66     int event_max;
67 };
68 
69 static void ioq_submit(LinuxAioState *s);
70 
71 static inline ssize_t io_event_ret(struct io_event *ev)
72 {
73     return (ssize_t)(((uint64_t)ev->res2 << 32) | ev->res);
74 }
75 
76 /*
77  * Completes an AIO request.
78  */
79 static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)
80 {
81     int ret;
82 
83     ret = laiocb->ret;
84     if (ret != -ECANCELED) {
85         if (ret == laiocb->nbytes) {
86             ret = 0;
87         } else if (ret >= 0) {
88             /* Short reads mean EOF, pad with zeros. */
89             if (laiocb->is_read) {
90                 qemu_iovec_memset(laiocb->qiov, ret, 0,
91                     laiocb->qiov->size - ret);
92             } else {
93                 ret = -ENOSPC;
94             }
95         }
96     }
97 
98     laiocb->ret = ret;
99 
100     /*
101      * If the coroutine is already entered it must be in ioq_submit() and
102      * will notice laio->ret has been filled in when it eventually runs
103      * later.  Coroutines cannot be entered recursively so avoid doing
104      * that!
105      */
106     assert(laiocb->co->ctx == laiocb->ctx->aio_context);
107     if (!qemu_coroutine_entered(laiocb->co)) {
108         aio_co_wake(laiocb->co);
109     }
110 }
111 
112 /**
113  * aio_ring buffer which is shared between userspace and kernel.
114  *
115  * This copied from linux/fs/aio.c, common header does not exist
116  * but AIO exists for ages so we assume ABI is stable.
117  */
118 struct aio_ring {
119     unsigned    id;    /* kernel internal index number */
120     unsigned    nr;    /* number of io_events */
121     unsigned    head;  /* Written to by userland or by kernel. */
122     unsigned    tail;
123 
124     unsigned    magic;
125     unsigned    compat_features;
126     unsigned    incompat_features;
127     unsigned    header_length;  /* size of aio_ring */
128 
129     struct io_event io_events[];
130 };
131 
132 /**
133  * io_getevents_peek:
134  * @ctx: AIO context
135  * @events: pointer on events array, output value
136 
137  * Returns the number of completed events and sets a pointer
138  * on events array.  This function does not update the internal
139  * ring buffer, only reads head and tail.  When @events has been
140  * processed io_getevents_commit() must be called.
141  */
142 static inline unsigned int io_getevents_peek(io_context_t ctx,
143                                              struct io_event **events)
144 {
145     struct aio_ring *ring = (struct aio_ring *)ctx;
146     unsigned int head = ring->head, tail = ring->tail;
147     unsigned int nr;
148 
149     nr = tail >= head ? tail - head : ring->nr - head;
150     *events = ring->io_events + head;
151     /* To avoid speculative loads of s->events[i] before observing tail.
152        Paired with smp_wmb() inside linux/fs/aio.c: aio_complete(). */
153     smp_rmb();
154 
155     return nr;
156 }
157 
158 /**
159  * io_getevents_commit:
160  * @ctx: AIO context
161  * @nr: the number of events on which head should be advanced
162  *
163  * Advances head of a ring buffer.
164  */
165 static inline void io_getevents_commit(io_context_t ctx, unsigned int nr)
166 {
167     struct aio_ring *ring = (struct aio_ring *)ctx;
168 
169     if (nr) {
170         ring->head = (ring->head + nr) % ring->nr;
171     }
172 }
173 
174 /**
175  * io_getevents_advance_and_peek:
176  * @ctx: AIO context
177  * @events: pointer on events array, output value
178  * @nr: the number of events on which head should be advanced
179  *
180  * Advances head of a ring buffer and returns number of elements left.
181  */
182 static inline unsigned int
183 io_getevents_advance_and_peek(io_context_t ctx,
184                               struct io_event **events,
185                               unsigned int nr)
186 {
187     io_getevents_commit(ctx, nr);
188     return io_getevents_peek(ctx, events);
189 }
190 
191 /**
192  * qemu_laio_process_completions:
193  * @s: AIO state
194  *
195  * Fetches completed I/O requests and invokes their callbacks.
196  *
197  * The function is somewhat tricky because it supports nested event loops, for
198  * example when a request callback invokes aio_poll().  In order to do this,
199  * indices are kept in LinuxAioState.  Function schedules BH completion so it
200  * can be called again in a nested event loop.  When there are no events left
201  * to complete the BH is being canceled.
202  */
203 static void qemu_laio_process_completions(LinuxAioState *s)
204 {
205     struct io_event *events;
206 
207     /* Reschedule so nested event loops see currently pending completions */
208     qemu_bh_schedule(s->completion_bh);
209 
210     while ((s->event_max = io_getevents_advance_and_peek(s->ctx, &events,
211                                                          s->event_idx))) {
212         for (s->event_idx = 0; s->event_idx < s->event_max; ) {
213             struct iocb *iocb = events[s->event_idx].obj;
214             struct qemu_laiocb *laiocb =
215                 container_of(iocb, struct qemu_laiocb, iocb);
216 
217             laiocb->ret = io_event_ret(&events[s->event_idx]);
218 
219             /* Change counters one-by-one because we can be nested. */
220             s->io_q.in_flight--;
221             s->event_idx++;
222             qemu_laio_process_completion(laiocb);
223         }
224     }
225 
226     qemu_bh_cancel(s->completion_bh);
227 
228     /* If we are nested we have to notify the level above that we are done
229      * by setting event_max to zero, upper level will then jump out of it's
230      * own `for` loop.  If we are the last all counters droped to zero. */
231     s->event_max = 0;
232     s->event_idx = 0;
233 }
234 
235 static void qemu_laio_process_completions_and_submit(LinuxAioState *s)
236 {
237     qemu_laio_process_completions(s);
238 
239     if (!s->io_q.plugged && !QSIMPLEQ_EMPTY(&s->io_q.pending)) {
240         ioq_submit(s);
241     }
242 }
243 
244 static void qemu_laio_completion_bh(void *opaque)
245 {
246     LinuxAioState *s = opaque;
247 
248     qemu_laio_process_completions_and_submit(s);
249 }
250 
251 static void qemu_laio_completion_cb(EventNotifier *e)
252 {
253     LinuxAioState *s = container_of(e, LinuxAioState, e);
254 
255     if (event_notifier_test_and_clear(&s->e)) {
256         qemu_laio_process_completions_and_submit(s);
257     }
258 }
259 
260 static bool qemu_laio_poll_cb(void *opaque)
261 {
262     EventNotifier *e = opaque;
263     LinuxAioState *s = container_of(e, LinuxAioState, e);
264     struct io_event *events;
265 
266     return io_getevents_peek(s->ctx, &events);
267 }
268 
269 static void qemu_laio_poll_ready(EventNotifier *opaque)
270 {
271     EventNotifier *e = opaque;
272     LinuxAioState *s = container_of(e, LinuxAioState, e);
273 
274     qemu_laio_process_completions_and_submit(s);
275 }
276 
277 static void ioq_init(LaioQueue *io_q)
278 {
279     QSIMPLEQ_INIT(&io_q->pending);
280     io_q->plugged = 0;
281     io_q->in_queue = 0;
282     io_q->in_flight = 0;
283     io_q->blocked = false;
284 }
285 
286 static void ioq_submit(LinuxAioState *s)
287 {
288     int ret, len;
289     struct qemu_laiocb *aiocb;
290     struct iocb *iocbs[MAX_EVENTS];
291     QSIMPLEQ_HEAD(, qemu_laiocb) completed;
292 
293     do {
294         if (s->io_q.in_flight >= MAX_EVENTS) {
295             break;
296         }
297         len = 0;
298         QSIMPLEQ_FOREACH(aiocb, &s->io_q.pending, next) {
299             iocbs[len++] = &aiocb->iocb;
300             if (s->io_q.in_flight + len >= MAX_EVENTS) {
301                 break;
302             }
303         }
304 
305         ret = io_submit(s->ctx, len, iocbs);
306         if (ret == -EAGAIN) {
307             break;
308         }
309         if (ret < 0) {
310             /* Fail the first request, retry the rest */
311             aiocb = QSIMPLEQ_FIRST(&s->io_q.pending);
312             QSIMPLEQ_REMOVE_HEAD(&s->io_q.pending, next);
313             s->io_q.in_queue--;
314             aiocb->ret = ret;
315             qemu_laio_process_completion(aiocb);
316             continue;
317         }
318 
319         s->io_q.in_flight += ret;
320         s->io_q.in_queue  -= ret;
321         aiocb = container_of(iocbs[ret - 1], struct qemu_laiocb, iocb);
322         QSIMPLEQ_SPLIT_AFTER(&s->io_q.pending, aiocb, next, &completed);
323     } while (ret == len && !QSIMPLEQ_EMPTY(&s->io_q.pending));
324     s->io_q.blocked = (s->io_q.in_queue > 0);
325 
326     if (s->io_q.in_flight) {
327         /* We can try to complete something just right away if there are
328          * still requests in-flight. */
329         qemu_laio_process_completions(s);
330         /*
331          * Even we have completed everything (in_flight == 0), the queue can
332          * have still pended requests (in_queue > 0).  We do not attempt to
333          * repeat submission to avoid IO hang.  The reason is simple: s->e is
334          * still set and completion callback will be called shortly and all
335          * pended requests will be submitted from there.
336          */
337     }
338 }
339 
340 static uint64_t laio_max_batch(LinuxAioState *s, uint64_t dev_max_batch)
341 {
342     uint64_t max_batch = s->aio_context->aio_max_batch ?: DEFAULT_MAX_BATCH;
343 
344     /*
345      * AIO context can be shared between multiple block devices, so
346      * `dev_max_batch` allows reducing the batch size for latency-sensitive
347      * devices.
348      */
349     max_batch = MIN_NON_ZERO(dev_max_batch, max_batch);
350 
351     /* limit the batch with the number of available events */
352     max_batch = MIN_NON_ZERO(MAX_EVENTS - s->io_q.in_flight, max_batch);
353 
354     return max_batch;
355 }
356 
357 void laio_io_plug(void)
358 {
359     AioContext *ctx = qemu_get_current_aio_context();
360     LinuxAioState *s = aio_get_linux_aio(ctx);
361 
362     s->io_q.plugged++;
363 }
364 
365 void laio_io_unplug(uint64_t dev_max_batch)
366 {
367     AioContext *ctx = qemu_get_current_aio_context();
368     LinuxAioState *s = aio_get_linux_aio(ctx);
369 
370     assert(s->io_q.plugged);
371     s->io_q.plugged--;
372 
373     /*
374      * Why max batch checking is performed here:
375      * Another BDS may have queued requests with a higher dev_max_batch and
376      * therefore in_queue could now exceed our dev_max_batch. Re-check the max
377      * batch so we can honor our device's dev_max_batch.
378      */
379     if (s->io_q.in_queue >= laio_max_batch(s, dev_max_batch) ||
380         (!s->io_q.plugged &&
381          !s->io_q.blocked && !QSIMPLEQ_EMPTY(&s->io_q.pending))) {
382         ioq_submit(s);
383     }
384 }
385 
386 static int laio_do_submit(int fd, struct qemu_laiocb *laiocb, off_t offset,
387                           int type, uint64_t dev_max_batch)
388 {
389     LinuxAioState *s = laiocb->ctx;
390     struct iocb *iocbs = &laiocb->iocb;
391     QEMUIOVector *qiov = laiocb->qiov;
392 
393     switch (type) {
394     case QEMU_AIO_WRITE:
395         io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);
396         break;
397     case QEMU_AIO_ZONE_APPEND:
398         io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);
399         break;
400     case QEMU_AIO_READ:
401         io_prep_preadv(iocbs, fd, qiov->iov, qiov->niov, offset);
402         break;
403     /* Currently Linux kernel does not support other operations */
404     default:
405         fprintf(stderr, "%s: invalid AIO request type 0x%x.\n",
406                         __func__, type);
407         return -EIO;
408     }
409     io_set_eventfd(&laiocb->iocb, event_notifier_get_fd(&s->e));
410 
411     QSIMPLEQ_INSERT_TAIL(&s->io_q.pending, laiocb, next);
412     s->io_q.in_queue++;
413     if (!s->io_q.blocked &&
414         (!s->io_q.plugged ||
415          s->io_q.in_queue >= laio_max_batch(s, dev_max_batch))) {
416         ioq_submit(s);
417     }
418 
419     return 0;
420 }
421 
422 int coroutine_fn laio_co_submit(int fd, uint64_t offset, QEMUIOVector *qiov,
423                                 int type, uint64_t dev_max_batch)
424 {
425     int ret;
426     AioContext *ctx = qemu_get_current_aio_context();
427     struct qemu_laiocb laiocb = {
428         .co         = qemu_coroutine_self(),
429         .nbytes     = qiov->size,
430         .ctx        = aio_get_linux_aio(ctx),
431         .ret        = -EINPROGRESS,
432         .is_read    = (type == QEMU_AIO_READ),
433         .qiov       = qiov,
434     };
435 
436     ret = laio_do_submit(fd, &laiocb, offset, type, dev_max_batch);
437     if (ret < 0) {
438         return ret;
439     }
440 
441     if (laiocb.ret == -EINPROGRESS) {
442         qemu_coroutine_yield();
443     }
444     return laiocb.ret;
445 }
446 
447 void laio_detach_aio_context(LinuxAioState *s, AioContext *old_context)
448 {
449     aio_set_event_notifier(old_context, &s->e, NULL, NULL, NULL);
450     qemu_bh_delete(s->completion_bh);
451     s->aio_context = NULL;
452 }
453 
454 void laio_attach_aio_context(LinuxAioState *s, AioContext *new_context)
455 {
456     s->aio_context = new_context;
457     s->completion_bh = aio_bh_new(new_context, qemu_laio_completion_bh, s);
458     aio_set_event_notifier(new_context, &s->e,
459                            qemu_laio_completion_cb,
460                            qemu_laio_poll_cb,
461                            qemu_laio_poll_ready);
462 }
463 
464 LinuxAioState *laio_init(Error **errp)
465 {
466     int rc;
467     LinuxAioState *s;
468 
469     s = g_malloc0(sizeof(*s));
470     rc = event_notifier_init(&s->e, false);
471     if (rc < 0) {
472         error_setg_errno(errp, -rc, "failed to initialize event notifier");
473         goto out_free_state;
474     }
475 
476     rc = io_setup(MAX_EVENTS, &s->ctx);
477     if (rc < 0) {
478         error_setg_errno(errp, -rc, "failed to create linux AIO context");
479         goto out_close_efd;
480     }
481 
482     ioq_init(&s->io_q);
483 
484     return s;
485 
486 out_close_efd:
487     event_notifier_cleanup(&s->e);
488 out_free_state:
489     g_free(s);
490     return NULL;
491 }
492 
493 void laio_cleanup(LinuxAioState *s)
494 {
495     event_notifier_cleanup(&s->e);
496 
497     if (io_destroy(s->ctx) != 0) {
498         fprintf(stderr, "%s: destroy AIO context %p failed\n",
499                         __func__, &s->ctx);
500     }
501     g_free(s);
502 }
503