2 * Data plane event loop
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2017 QEMU contributors
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 #include "qemu/osdep.h"
27 #include "qapi/error.h"
28 #include "block/aio.h"
29 #include "block/thread-pool.h"
30 #include "block/graph-lock.h"
31 #include "qemu/main-loop.h"
32 #include "qemu/atomic.h"
33 #include "qemu/rcu_queue.h"
34 #include "block/raw-aio.h"
35 #include "qemu/coroutine_int.h"
36 #include "qemu/coroutine-tls.h"
37 #include "sysemu/cpu-timers.h"
40 /***********************************************************/
41 /* bottom halves (can be seen as timers which expire ASAP) */
43 /* QEMUBH::flags values */
45 /* Already enqueued and waiting for aio_bh_poll() */
46 BH_PENDING
= (1 << 0),
48 /* Invoke the callback */
49 BH_SCHEDULED
= (1 << 1),
51 /* Delete without invoking callback */
52 BH_DELETED
= (1 << 2),
54 /* Delete after invoking callback */
55 BH_ONESHOT
= (1 << 3),
57 /* Schedule periodically when the event loop is idle */
66 QSLIST_ENTRY(QEMUBH
) next
;
70 /* Called concurrently from any thread */
71 static void aio_bh_enqueue(QEMUBH
*bh
, unsigned new_flags
)
73 AioContext
*ctx
= bh
->ctx
;
77 * Synchronizes with atomic_fetch_and() in aio_bh_dequeue(), ensuring that
78 * insertion starts after BH_PENDING is set.
80 old_flags
= qatomic_fetch_or(&bh
->flags
, BH_PENDING
| new_flags
);
82 if (!(old_flags
& BH_PENDING
)) {
84 * At this point the bottom half becomes visible to aio_bh_poll().
85 * This insertion thus synchronizes with QSLIST_MOVE_ATOMIC in
86 * aio_bh_poll(), ensuring that:
87 * 1. any writes needed by the callback are visible from the callback
88 * after aio_bh_dequeue() returns bh.
89 * 2. ctx is loaded before the callback has a chance to execute and bh
92 QSLIST_INSERT_HEAD_ATOMIC(&ctx
->bh_list
, bh
, next
);
97 * Workaround for record/replay.
98 * vCPU execution should be suspended when new BH is set.
99 * This is needed to avoid guest timeouts caused
100 * by the long cycles of the execution.
102 icount_notify_exit();
105 /* Only called from aio_bh_poll() and aio_ctx_finalize() */
106 static QEMUBH
*aio_bh_dequeue(BHList
*head
, unsigned *flags
)
108 QEMUBH
*bh
= QSLIST_FIRST_RCU(head
);
114 QSLIST_REMOVE_HEAD(head
, next
);
117 * Synchronizes with qatomic_fetch_or() in aio_bh_enqueue(), ensuring that
118 * the removal finishes before BH_PENDING is reset.
120 *flags
= qatomic_fetch_and(&bh
->flags
,
121 ~(BH_PENDING
| BH_SCHEDULED
| BH_IDLE
));
125 void aio_bh_schedule_oneshot_full(AioContext
*ctx
, QEMUBHFunc
*cb
,
126 void *opaque
, const char *name
)
129 bh
= g_new(QEMUBH
, 1);
136 aio_bh_enqueue(bh
, BH_SCHEDULED
| BH_ONESHOT
);
139 QEMUBH
*aio_bh_new_full(AioContext
*ctx
, QEMUBHFunc
*cb
, void *opaque
,
143 bh
= g_new(QEMUBH
, 1);
153 void aio_bh_call(QEMUBH
*bh
)
158 /* Multiple occurrences of aio_bh_poll cannot be called concurrently. */
159 int aio_bh_poll(AioContext
*ctx
)
165 /* Synchronizes with QSLIST_INSERT_HEAD_ATOMIC in aio_bh_enqueue(). */
166 QSLIST_MOVE_ATOMIC(&slice
.bh_list
, &ctx
->bh_list
);
167 QSIMPLEQ_INSERT_TAIL(&ctx
->bh_slice_list
, &slice
, next
);
169 while ((s
= QSIMPLEQ_FIRST(&ctx
->bh_slice_list
))) {
173 bh
= aio_bh_dequeue(&s
->bh_list
, &flags
);
175 QSIMPLEQ_REMOVE_HEAD(&ctx
->bh_slice_list
, next
);
179 if ((flags
& (BH_SCHEDULED
| BH_DELETED
)) == BH_SCHEDULED
) {
180 /* Idle BHs don't count as progress */
181 if (!(flags
& BH_IDLE
)) {
186 if (flags
& (BH_DELETED
| BH_ONESHOT
)) {
194 void qemu_bh_schedule_idle(QEMUBH
*bh
)
196 aio_bh_enqueue(bh
, BH_SCHEDULED
| BH_IDLE
);
199 void qemu_bh_schedule(QEMUBH
*bh
)
201 aio_bh_enqueue(bh
, BH_SCHEDULED
);
204 /* This func is async.
206 void qemu_bh_cancel(QEMUBH
*bh
)
208 qatomic_and(&bh
->flags
, ~BH_SCHEDULED
);
211 /* This func is async.The bottom half will do the delete action at the finial
214 void qemu_bh_delete(QEMUBH
*bh
)
216 aio_bh_enqueue(bh
, BH_DELETED
);
219 static int64_t aio_compute_bh_timeout(BHList
*head
, int timeout
)
223 QSLIST_FOREACH_RCU(bh
, head
, next
) {
224 if ((bh
->flags
& (BH_SCHEDULED
| BH_DELETED
)) == BH_SCHEDULED
) {
225 if (bh
->flags
& BH_IDLE
) {
226 /* idle bottom halves will be polled at least
230 /* non-idle bottom halves will be executed
241 aio_compute_timeout(AioContext
*ctx
)
247 timeout
= aio_compute_bh_timeout(&ctx
->bh_list
, timeout
);
252 QSIMPLEQ_FOREACH(s
, &ctx
->bh_slice_list
, next
) {
253 timeout
= aio_compute_bh_timeout(&s
->bh_list
, timeout
);
259 deadline
= timerlistgroup_deadline_ns(&ctx
->tlg
);
263 return qemu_soonest_timeout(timeout
, deadline
);
268 aio_ctx_prepare(GSource
*source
, gint
*timeout
)
270 AioContext
*ctx
= (AioContext
*) source
;
272 qatomic_set(&ctx
->notify_me
, qatomic_read(&ctx
->notify_me
) | 1);
275 * Write ctx->notify_me before computing the timeout
276 * (reading bottom half flags, etc.). Pairs with
277 * smp_mb in aio_notify().
281 /* We assume there is no timeout already supplied */
282 *timeout
= qemu_timeout_ns_to_ms(aio_compute_timeout(ctx
));
284 if (aio_prepare(ctx
)) {
288 return *timeout
== 0;
292 aio_ctx_check(GSource
*source
)
294 AioContext
*ctx
= (AioContext
*) source
;
298 /* Finish computing the timeout before clearing the flag. */
299 qatomic_store_release(&ctx
->notify_me
, qatomic_read(&ctx
->notify_me
) & ~1);
300 aio_notify_accept(ctx
);
302 QSLIST_FOREACH_RCU(bh
, &ctx
->bh_list
, next
) {
303 if ((bh
->flags
& (BH_SCHEDULED
| BH_DELETED
)) == BH_SCHEDULED
) {
308 QSIMPLEQ_FOREACH(s
, &ctx
->bh_slice_list
, next
) {
309 QSLIST_FOREACH_RCU(bh
, &s
->bh_list
, next
) {
310 if ((bh
->flags
& (BH_SCHEDULED
| BH_DELETED
)) == BH_SCHEDULED
) {
315 return aio_pending(ctx
) || (timerlistgroup_deadline_ns(&ctx
->tlg
) == 0);
319 aio_ctx_dispatch(GSource
*source
,
320 GSourceFunc callback
,
323 AioContext
*ctx
= (AioContext
*) source
;
325 assert(callback
== NULL
);
331 aio_ctx_finalize(GSource
*source
)
333 AioContext
*ctx
= (AioContext
*) source
;
337 thread_pool_free(ctx
->thread_pool
);
339 #ifdef CONFIG_LINUX_AIO
340 if (ctx
->linux_aio
) {
341 laio_detach_aio_context(ctx
->linux_aio
, ctx
);
342 laio_cleanup(ctx
->linux_aio
);
343 ctx
->linux_aio
= NULL
;
347 #ifdef CONFIG_LINUX_IO_URING
348 if (ctx
->linux_io_uring
) {
349 luring_detach_aio_context(ctx
->linux_io_uring
, ctx
);
350 luring_cleanup(ctx
->linux_io_uring
);
351 ctx
->linux_io_uring
= NULL
;
355 assert(QSLIST_EMPTY(&ctx
->scheduled_coroutines
));
356 qemu_bh_delete(ctx
->co_schedule_bh
);
358 /* There must be no aio_bh_poll() calls going on */
359 assert(QSIMPLEQ_EMPTY(&ctx
->bh_slice_list
));
361 while ((bh
= aio_bh_dequeue(&ctx
->bh_list
, &flags
))) {
363 * qemu_bh_delete() must have been called on BHs in this AioContext. In
364 * many cases memory leaks, hangs, or inconsistent state occur when a
365 * BH is leaked because something still expects it to run.
367 * If you hit this, fix the lifecycle of the BH so that
368 * qemu_bh_delete() and any associated cleanup is called before the
369 * AioContext is finalized.
371 if (unlikely(!(flags
& BH_DELETED
))) {
372 fprintf(stderr
, "%s: BH '%s' leaked, aborting...\n",
380 aio_set_event_notifier(ctx
, &ctx
->notifier
, false, NULL
, NULL
, NULL
);
381 event_notifier_cleanup(&ctx
->notifier
);
382 qemu_rec_mutex_destroy(&ctx
->lock
);
383 qemu_lockcnt_destroy(&ctx
->list_lock
);
384 timerlistgroup_deinit(&ctx
->tlg
);
385 unregister_aiocontext(ctx
);
386 aio_context_destroy(ctx
);
389 static GSourceFuncs aio_source_funcs
= {
396 GSource
*aio_get_g_source(AioContext
*ctx
)
398 aio_context_use_g_source(ctx
);
399 g_source_ref(&ctx
->source
);
403 ThreadPool
*aio_get_thread_pool(AioContext
*ctx
)
405 if (!ctx
->thread_pool
) {
406 ctx
->thread_pool
= thread_pool_new(ctx
);
408 return ctx
->thread_pool
;
411 #ifdef CONFIG_LINUX_AIO
412 LinuxAioState
*aio_setup_linux_aio(AioContext
*ctx
, Error
**errp
)
414 if (!ctx
->linux_aio
) {
415 ctx
->linux_aio
= laio_init(errp
);
416 if (ctx
->linux_aio
) {
417 laio_attach_aio_context(ctx
->linux_aio
, ctx
);
420 return ctx
->linux_aio
;
423 LinuxAioState
*aio_get_linux_aio(AioContext
*ctx
)
425 assert(ctx
->linux_aio
);
426 return ctx
->linux_aio
;
430 #ifdef CONFIG_LINUX_IO_URING
431 LuringState
*aio_setup_linux_io_uring(AioContext
*ctx
, Error
**errp
)
433 if (ctx
->linux_io_uring
) {
434 return ctx
->linux_io_uring
;
437 ctx
->linux_io_uring
= luring_init(errp
);
438 if (!ctx
->linux_io_uring
) {
442 luring_attach_aio_context(ctx
->linux_io_uring
, ctx
);
443 return ctx
->linux_io_uring
;
446 LuringState
*aio_get_linux_io_uring(AioContext
*ctx
)
448 assert(ctx
->linux_io_uring
);
449 return ctx
->linux_io_uring
;
453 void aio_notify(AioContext
*ctx
)
456 * Write e.g. ctx->bh_list before writing ctx->notified. Pairs with
457 * smp_mb() in aio_notify_accept().
460 qatomic_set(&ctx
->notified
, true);
463 * Write ctx->notified (and also ctx->bh_list) before reading ctx->notify_me.
464 * Pairs with smp_mb() in aio_ctx_prepare or aio_poll.
467 if (qatomic_read(&ctx
->notify_me
)) {
468 event_notifier_set(&ctx
->notifier
);
472 void aio_notify_accept(AioContext
*ctx
)
474 qatomic_set(&ctx
->notified
, false);
477 * Order reads of ctx->notified (in aio_context_notifier_poll()) and the
478 * above clearing of ctx->notified before reads of e.g. bh->flags. Pairs
479 * with smp_wmb() in aio_notify.
484 static void aio_timerlist_notify(void *opaque
, QEMUClockType type
)
489 static void aio_context_notifier_cb(EventNotifier
*e
)
491 AioContext
*ctx
= container_of(e
, AioContext
, notifier
);
493 event_notifier_test_and_clear(&ctx
->notifier
);
496 /* Returns true if aio_notify() was called (e.g. a BH was scheduled) */
497 static bool aio_context_notifier_poll(void *opaque
)
499 EventNotifier
*e
= opaque
;
500 AioContext
*ctx
= container_of(e
, AioContext
, notifier
);
503 * No need for load-acquire because we just want to kick the
504 * event loop. aio_notify_accept() takes care of synchronizing
505 * the event loop with the producers.
507 return qatomic_read(&ctx
->notified
);
510 static void aio_context_notifier_poll_ready(EventNotifier
*e
)
512 /* Do nothing, we just wanted to kick the event loop */
515 static void co_schedule_bh_cb(void *opaque
)
517 AioContext
*ctx
= opaque
;
518 QSLIST_HEAD(, Coroutine
) straight
, reversed
;
520 QSLIST_MOVE_ATOMIC(&reversed
, &ctx
->scheduled_coroutines
);
521 QSLIST_INIT(&straight
);
523 while (!QSLIST_EMPTY(&reversed
)) {
524 Coroutine
*co
= QSLIST_FIRST(&reversed
);
525 QSLIST_REMOVE_HEAD(&reversed
, co_scheduled_next
);
526 QSLIST_INSERT_HEAD(&straight
, co
, co_scheduled_next
);
529 while (!QSLIST_EMPTY(&straight
)) {
530 Coroutine
*co
= QSLIST_FIRST(&straight
);
531 QSLIST_REMOVE_HEAD(&straight
, co_scheduled_next
);
532 trace_aio_co_schedule_bh_cb(ctx
, co
);
533 aio_context_acquire(ctx
);
535 /* Protected by write barrier in qemu_aio_coroutine_enter */
536 qatomic_set(&co
->scheduled
, NULL
);
537 qemu_aio_coroutine_enter(ctx
, co
);
538 aio_context_release(ctx
);
542 AioContext
*aio_context_new(Error
**errp
)
547 ctx
= (AioContext
*) g_source_new(&aio_source_funcs
, sizeof(AioContext
));
548 QSLIST_INIT(&ctx
->bh_list
);
549 QSIMPLEQ_INIT(&ctx
->bh_slice_list
);
550 aio_context_setup(ctx
);
552 ret
= event_notifier_init(&ctx
->notifier
, false);
554 error_setg_errno(errp
, -ret
, "Failed to initialize event notifier");
557 g_source_set_can_recurse(&ctx
->source
, true);
558 qemu_lockcnt_init(&ctx
->list_lock
);
560 ctx
->co_schedule_bh
= aio_bh_new(ctx
, co_schedule_bh_cb
, ctx
);
561 QSLIST_INIT(&ctx
->scheduled_coroutines
);
563 aio_set_event_notifier(ctx
, &ctx
->notifier
,
565 aio_context_notifier_cb
,
566 aio_context_notifier_poll
,
567 aio_context_notifier_poll_ready
);
568 #ifdef CONFIG_LINUX_AIO
569 ctx
->linux_aio
= NULL
;
572 #ifdef CONFIG_LINUX_IO_URING
573 ctx
->linux_io_uring
= NULL
;
576 ctx
->thread_pool
= NULL
;
577 qemu_rec_mutex_init(&ctx
->lock
);
578 timerlistgroup_init(&ctx
->tlg
, aio_timerlist_notify
, ctx
);
581 ctx
->poll_max_ns
= 0;
583 ctx
->poll_shrink
= 0;
585 ctx
->aio_max_batch
= 0;
587 ctx
->thread_pool_min
= 0;
588 ctx
->thread_pool_max
= THREAD_POOL_MAX_THREADS_DEFAULT
;
590 register_aiocontext(ctx
);
594 g_source_destroy(&ctx
->source
);
598 void aio_co_schedule(AioContext
*ctx
, Coroutine
*co
)
600 trace_aio_co_schedule(ctx
, co
);
601 const char *scheduled
= qatomic_cmpxchg(&co
->scheduled
, NULL
,
606 "%s: Co-routine was already scheduled in '%s'\n",
607 __func__
, scheduled
);
611 /* The coroutine might run and release the last ctx reference before we
612 * invoke qemu_bh_schedule(). Take a reference to keep ctx alive until
615 aio_context_ref(ctx
);
617 QSLIST_INSERT_HEAD_ATOMIC(&ctx
->scheduled_coroutines
,
618 co
, co_scheduled_next
);
619 qemu_bh_schedule(ctx
->co_schedule_bh
);
621 aio_context_unref(ctx
);
624 typedef struct AioCoRescheduleSelf
{
627 } AioCoRescheduleSelf
;
629 static void aio_co_reschedule_self_bh(void *opaque
)
631 AioCoRescheduleSelf
*data
= opaque
;
632 aio_co_schedule(data
->new_ctx
, data
->co
);
635 void coroutine_fn
aio_co_reschedule_self(AioContext
*new_ctx
)
637 AioContext
*old_ctx
= qemu_get_current_aio_context();
639 if (old_ctx
!= new_ctx
) {
640 AioCoRescheduleSelf data
= {
641 .co
= qemu_coroutine_self(),
645 * We can't directly schedule the coroutine in the target context
646 * because this would be racy: The other thread could try to enter the
647 * coroutine before it has yielded in this one.
649 aio_bh_schedule_oneshot(old_ctx
, aio_co_reschedule_self_bh
, &data
);
650 qemu_coroutine_yield();
654 void aio_co_wake(Coroutine
*co
)
658 /* Read coroutine before co->ctx. Matches smp_wmb in
659 * qemu_coroutine_enter.
661 smp_read_barrier_depends();
662 ctx
= qatomic_read(&co
->ctx
);
664 aio_co_enter(ctx
, co
);
667 void aio_co_enter(AioContext
*ctx
, Coroutine
*co
)
669 if (ctx
!= qemu_get_current_aio_context()) {
670 aio_co_schedule(ctx
, co
);
674 if (qemu_in_coroutine()) {
675 Coroutine
*self
= qemu_coroutine_self();
677 QSIMPLEQ_INSERT_TAIL(&self
->co_queue_wakeup
, co
, co_queue_next
);
679 aio_context_acquire(ctx
);
680 qemu_aio_coroutine_enter(ctx
, co
);
681 aio_context_release(ctx
);
685 void aio_context_ref(AioContext
*ctx
)
687 g_source_ref(&ctx
->source
);
690 void aio_context_unref(AioContext
*ctx
)
692 g_source_unref(&ctx
->source
);
695 void aio_context_acquire(AioContext
*ctx
)
697 qemu_rec_mutex_lock(&ctx
->lock
);
700 void aio_context_release(AioContext
*ctx
)
702 qemu_rec_mutex_unlock(&ctx
->lock
);
705 QEMU_DEFINE_STATIC_CO_TLS(AioContext
*, my_aiocontext
)
707 AioContext
*qemu_get_current_aio_context(void)
709 AioContext
*ctx
= get_my_aiocontext();
713 if (qemu_mutex_iothread_locked()) {
714 /* Possibly in a vCPU thread. */
715 return qemu_get_aio_context();
720 void qemu_set_current_aio_context(AioContext
*ctx
)
722 assert(!get_my_aiocontext());
723 set_my_aiocontext(ctx
);
726 void aio_context_set_thread_pool_params(AioContext
*ctx
, int64_t min
,
727 int64_t max
, Error
**errp
)
730 if (min
> max
|| !max
|| min
> INT_MAX
|| max
> INT_MAX
) {
731 error_setg(errp
, "bad thread-pool-min/thread-pool-max values");
735 ctx
->thread_pool_min
= min
;
736 ctx
->thread_pool_max
= max
;
738 if (ctx
->thread_pool
) {
739 thread_pool_update_params(ctx
->thread_pool
, ctx
);