Merge tag 'pull-loongarch-20241016' of https://gitlab.com/gaosong/qemu into staging
[qemu/armbru.git] / util / async.c
blob99db28389f66059f5691e2fb91ea1995d4b9a85b
1 /*
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
23 * THE SOFTWARE.
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/lockcnt.h"
34 #include "qemu/rcu_queue.h"
35 #include "block/raw-aio.h"
36 #include "qemu/coroutine_int.h"
37 #include "qemu/coroutine-tls.h"
38 #include "sysemu/cpu-timers.h"
39 #include "trace.h"
41 /***********************************************************/
42 /* bottom halves (can be seen as timers which expire ASAP) */
44 /* QEMUBH::flags values */
45 enum {
46 /* Already enqueued and waiting for aio_bh_poll() */
47 BH_PENDING = (1 << 0),
49 /* Invoke the callback */
50 BH_SCHEDULED = (1 << 1),
52 /* Delete without invoking callback */
53 BH_DELETED = (1 << 2),
55 /* Delete after invoking callback */
56 BH_ONESHOT = (1 << 3),
58 /* Schedule periodically when the event loop is idle */
59 BH_IDLE = (1 << 4),
62 struct QEMUBH {
63 AioContext *ctx;
64 const char *name;
65 QEMUBHFunc *cb;
66 void *opaque;
67 QSLIST_ENTRY(QEMUBH) next;
68 unsigned flags;
69 MemReentrancyGuard *reentrancy_guard;
72 /* Called concurrently from any thread */
73 static void aio_bh_enqueue(QEMUBH *bh, unsigned new_flags)
75 AioContext *ctx = bh->ctx;
76 unsigned old_flags;
79 * Synchronizes with atomic_fetch_and() in aio_bh_dequeue(), ensuring that
80 * insertion starts after BH_PENDING is set.
82 old_flags = qatomic_fetch_or(&bh->flags, BH_PENDING | new_flags);
84 if (!(old_flags & BH_PENDING)) {
86 * At this point the bottom half becomes visible to aio_bh_poll().
87 * This insertion thus synchronizes with QSLIST_MOVE_ATOMIC in
88 * aio_bh_poll(), ensuring that:
89 * 1. any writes needed by the callback are visible from the callback
90 * after aio_bh_dequeue() returns bh.
91 * 2. ctx is loaded before the callback has a chance to execute and bh
92 * could be freed.
94 QSLIST_INSERT_HEAD_ATOMIC(&ctx->bh_list, bh, next);
97 aio_notify(ctx);
98 if (unlikely(icount_enabled())) {
100 * Workaround for record/replay.
101 * vCPU execution should be suspended when new BH is set.
102 * This is needed to avoid guest timeouts caused
103 * by the long cycles of the execution.
105 icount_notify_exit();
109 /* Only called from aio_bh_poll() and aio_ctx_finalize() */
110 static QEMUBH *aio_bh_dequeue(BHList *head, unsigned *flags)
112 QEMUBH *bh = QSLIST_FIRST_RCU(head);
114 if (!bh) {
115 return NULL;
118 QSLIST_REMOVE_HEAD(head, next);
121 * Synchronizes with qatomic_fetch_or() in aio_bh_enqueue(), ensuring that
122 * the removal finishes before BH_PENDING is reset.
124 *flags = qatomic_fetch_and(&bh->flags,
125 ~(BH_PENDING | BH_SCHEDULED | BH_IDLE));
126 return bh;
129 void aio_bh_schedule_oneshot_full(AioContext *ctx, QEMUBHFunc *cb,
130 void *opaque, const char *name)
132 QEMUBH *bh;
133 bh = g_new(QEMUBH, 1);
134 *bh = (QEMUBH){
135 .ctx = ctx,
136 .cb = cb,
137 .opaque = opaque,
138 .name = name,
140 aio_bh_enqueue(bh, BH_SCHEDULED | BH_ONESHOT);
143 QEMUBH *aio_bh_new_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
144 const char *name, MemReentrancyGuard *reentrancy_guard)
146 QEMUBH *bh;
147 bh = g_new(QEMUBH, 1);
148 *bh = (QEMUBH){
149 .ctx = ctx,
150 .cb = cb,
151 .opaque = opaque,
152 .name = name,
153 .reentrancy_guard = reentrancy_guard,
155 return bh;
158 void aio_bh_call(QEMUBH *bh)
160 bool last_engaged_in_io = false;
162 /* Make a copy of the guard-pointer as cb may free the bh */
163 MemReentrancyGuard *reentrancy_guard = bh->reentrancy_guard;
164 if (reentrancy_guard) {
165 last_engaged_in_io = reentrancy_guard->engaged_in_io;
166 if (reentrancy_guard->engaged_in_io) {
167 trace_reentrant_aio(bh->ctx, bh->name);
169 reentrancy_guard->engaged_in_io = true;
172 bh->cb(bh->opaque);
174 if (reentrancy_guard) {
175 reentrancy_guard->engaged_in_io = last_engaged_in_io;
179 /* Multiple occurrences of aio_bh_poll cannot be called concurrently. */
180 int aio_bh_poll(AioContext *ctx)
182 BHListSlice slice;
183 BHListSlice *s;
184 int ret = 0;
186 /* Synchronizes with QSLIST_INSERT_HEAD_ATOMIC in aio_bh_enqueue(). */
187 QSLIST_MOVE_ATOMIC(&slice.bh_list, &ctx->bh_list);
190 * GCC13 [-Werror=dangling-pointer=] complains that the local variable
191 * 'slice' is being stored in the global 'ctx->bh_slice_list' but the
192 * list is emptied before this function returns.
194 #if !defined(__clang__)
195 #pragma GCC diagnostic push
196 #pragma GCC diagnostic ignored "-Wpragmas"
197 #pragma GCC diagnostic ignored "-Wdangling-pointer="
198 #endif
199 QSIMPLEQ_INSERT_TAIL(&ctx->bh_slice_list, &slice, next);
200 #if !defined(__clang__)
201 #pragma GCC diagnostic pop
202 #endif
204 while ((s = QSIMPLEQ_FIRST(&ctx->bh_slice_list))) {
205 QEMUBH *bh;
206 unsigned flags;
208 bh = aio_bh_dequeue(&s->bh_list, &flags);
209 if (!bh) {
210 QSIMPLEQ_REMOVE_HEAD(&ctx->bh_slice_list, next);
211 continue;
214 if ((flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
215 /* Idle BHs don't count as progress */
216 if (!(flags & BH_IDLE)) {
217 ret = 1;
219 aio_bh_call(bh);
221 if (flags & (BH_DELETED | BH_ONESHOT)) {
222 g_free(bh);
226 return ret;
229 void qemu_bh_schedule_idle(QEMUBH *bh)
231 aio_bh_enqueue(bh, BH_SCHEDULED | BH_IDLE);
234 void qemu_bh_schedule(QEMUBH *bh)
236 aio_bh_enqueue(bh, BH_SCHEDULED);
239 /* This func is async.
241 void qemu_bh_cancel(QEMUBH *bh)
243 qatomic_and(&bh->flags, ~BH_SCHEDULED);
246 /* This func is async.The bottom half will do the delete action at the finial
247 * end.
249 void qemu_bh_delete(QEMUBH *bh)
251 aio_bh_enqueue(bh, BH_DELETED);
254 static int64_t aio_compute_bh_timeout(BHList *head, int timeout)
256 QEMUBH *bh;
258 QSLIST_FOREACH_RCU(bh, head, next) {
259 if ((bh->flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
260 if (bh->flags & BH_IDLE) {
261 /* idle bottom halves will be polled at least
262 * every 10ms */
263 timeout = 10000000;
264 } else {
265 /* non-idle bottom halves will be executed
266 * immediately */
267 return 0;
272 return timeout;
275 int64_t
276 aio_compute_timeout(AioContext *ctx)
278 BHListSlice *s;
279 int64_t deadline;
280 int timeout = -1;
282 timeout = aio_compute_bh_timeout(&ctx->bh_list, timeout);
283 if (timeout == 0) {
284 return 0;
287 QSIMPLEQ_FOREACH(s, &ctx->bh_slice_list, next) {
288 timeout = aio_compute_bh_timeout(&s->bh_list, timeout);
289 if (timeout == 0) {
290 return 0;
294 deadline = timerlistgroup_deadline_ns(&ctx->tlg);
295 if (deadline == 0) {
296 return 0;
297 } else {
298 return qemu_soonest_timeout(timeout, deadline);
302 static gboolean
303 aio_ctx_prepare(GSource *source, gint *timeout)
305 AioContext *ctx = (AioContext *) source;
307 qatomic_set(&ctx->notify_me, qatomic_read(&ctx->notify_me) | 1);
310 * Write ctx->notify_me before computing the timeout
311 * (reading bottom half flags, etc.). Pairs with
312 * smp_mb in aio_notify().
314 smp_mb();
316 /* We assume there is no timeout already supplied */
317 *timeout = qemu_timeout_ns_to_ms(aio_compute_timeout(ctx));
319 if (aio_prepare(ctx)) {
320 *timeout = 0;
323 return *timeout == 0;
326 static gboolean
327 aio_ctx_check(GSource *source)
329 AioContext *ctx = (AioContext *) source;
330 QEMUBH *bh;
331 BHListSlice *s;
333 /* Finish computing the timeout before clearing the flag. */
334 qatomic_store_release(&ctx->notify_me, qatomic_read(&ctx->notify_me) & ~1);
335 aio_notify_accept(ctx);
337 QSLIST_FOREACH_RCU(bh, &ctx->bh_list, next) {
338 if ((bh->flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
339 return true;
343 QSIMPLEQ_FOREACH(s, &ctx->bh_slice_list, next) {
344 QSLIST_FOREACH_RCU(bh, &s->bh_list, next) {
345 if ((bh->flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
346 return true;
350 return aio_pending(ctx) || (timerlistgroup_deadline_ns(&ctx->tlg) == 0);
353 static gboolean
354 aio_ctx_dispatch(GSource *source,
355 GSourceFunc callback,
356 gpointer user_data)
358 AioContext *ctx = (AioContext *) source;
360 assert(callback == NULL);
361 aio_dispatch(ctx);
362 return true;
365 static void
366 aio_ctx_finalize(GSource *source)
368 AioContext *ctx = (AioContext *) source;
369 QEMUBH *bh;
370 unsigned flags;
372 thread_pool_free(ctx->thread_pool);
374 #ifdef CONFIG_LINUX_AIO
375 if (ctx->linux_aio) {
376 laio_detach_aio_context(ctx->linux_aio, ctx);
377 laio_cleanup(ctx->linux_aio);
378 ctx->linux_aio = NULL;
380 #endif
382 #ifdef CONFIG_LINUX_IO_URING
383 if (ctx->linux_io_uring) {
384 luring_detach_aio_context(ctx->linux_io_uring, ctx);
385 luring_cleanup(ctx->linux_io_uring);
386 ctx->linux_io_uring = NULL;
388 #endif
390 assert(QSLIST_EMPTY(&ctx->scheduled_coroutines));
391 qemu_bh_delete(ctx->co_schedule_bh);
393 /* There must be no aio_bh_poll() calls going on */
394 assert(QSIMPLEQ_EMPTY(&ctx->bh_slice_list));
396 while ((bh = aio_bh_dequeue(&ctx->bh_list, &flags))) {
398 * qemu_bh_delete() must have been called on BHs in this AioContext. In
399 * many cases memory leaks, hangs, or inconsistent state occur when a
400 * BH is leaked because something still expects it to run.
402 * If you hit this, fix the lifecycle of the BH so that
403 * qemu_bh_delete() and any associated cleanup is called before the
404 * AioContext is finalized.
406 if (unlikely(!(flags & BH_DELETED))) {
407 fprintf(stderr, "%s: BH '%s' leaked, aborting...\n",
408 __func__, bh->name);
409 abort();
412 g_free(bh);
415 aio_set_event_notifier(ctx, &ctx->notifier, NULL, NULL, NULL);
416 event_notifier_cleanup(&ctx->notifier);
417 qemu_rec_mutex_destroy(&ctx->lock);
418 qemu_lockcnt_destroy(&ctx->list_lock);
419 timerlistgroup_deinit(&ctx->tlg);
420 unregister_aiocontext(ctx);
421 aio_context_destroy(ctx);
424 static GSourceFuncs aio_source_funcs = {
425 aio_ctx_prepare,
426 aio_ctx_check,
427 aio_ctx_dispatch,
428 aio_ctx_finalize
431 GSource *aio_get_g_source(AioContext *ctx)
433 aio_context_use_g_source(ctx);
434 g_source_ref(&ctx->source);
435 return &ctx->source;
438 ThreadPool *aio_get_thread_pool(AioContext *ctx)
440 if (!ctx->thread_pool) {
441 ctx->thread_pool = thread_pool_new(ctx);
443 return ctx->thread_pool;
446 #ifdef CONFIG_LINUX_AIO
447 LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp)
449 if (!ctx->linux_aio) {
450 ctx->linux_aio = laio_init(errp);
451 if (ctx->linux_aio) {
452 laio_attach_aio_context(ctx->linux_aio, ctx);
455 return ctx->linux_aio;
458 LinuxAioState *aio_get_linux_aio(AioContext *ctx)
460 assert(ctx->linux_aio);
461 return ctx->linux_aio;
463 #endif
465 #ifdef CONFIG_LINUX_IO_URING
466 LuringState *aio_setup_linux_io_uring(AioContext *ctx, Error **errp)
468 if (ctx->linux_io_uring) {
469 return ctx->linux_io_uring;
472 ctx->linux_io_uring = luring_init(errp);
473 if (!ctx->linux_io_uring) {
474 return NULL;
477 luring_attach_aio_context(ctx->linux_io_uring, ctx);
478 return ctx->linux_io_uring;
481 LuringState *aio_get_linux_io_uring(AioContext *ctx)
483 assert(ctx->linux_io_uring);
484 return ctx->linux_io_uring;
486 #endif
488 void aio_notify(AioContext *ctx)
491 * Write e.g. ctx->bh_list before writing ctx->notified. Pairs with
492 * smp_mb() in aio_notify_accept().
494 smp_wmb();
495 qatomic_set(&ctx->notified, true);
498 * Write ctx->notified (and also ctx->bh_list) before reading ctx->notify_me.
499 * Pairs with smp_mb() in aio_ctx_prepare or aio_poll.
501 smp_mb();
502 if (qatomic_read(&ctx->notify_me)) {
503 event_notifier_set(&ctx->notifier);
507 void aio_notify_accept(AioContext *ctx)
509 qatomic_set(&ctx->notified, false);
512 * Order reads of ctx->notified (in aio_context_notifier_poll()) and the
513 * above clearing of ctx->notified before reads of e.g. bh->flags. Pairs
514 * with smp_wmb() in aio_notify.
516 smp_mb();
519 static void aio_timerlist_notify(void *opaque, QEMUClockType type)
521 aio_notify(opaque);
524 static void aio_context_notifier_cb(EventNotifier *e)
526 AioContext *ctx = container_of(e, AioContext, notifier);
528 event_notifier_test_and_clear(&ctx->notifier);
531 /* Returns true if aio_notify() was called (e.g. a BH was scheduled) */
532 static bool aio_context_notifier_poll(void *opaque)
534 EventNotifier *e = opaque;
535 AioContext *ctx = container_of(e, AioContext, notifier);
538 * No need for load-acquire because we just want to kick the
539 * event loop. aio_notify_accept() takes care of synchronizing
540 * the event loop with the producers.
542 return qatomic_read(&ctx->notified);
545 static void aio_context_notifier_poll_ready(EventNotifier *e)
547 /* Do nothing, we just wanted to kick the event loop */
550 static void co_schedule_bh_cb(void *opaque)
552 AioContext *ctx = opaque;
553 QSLIST_HEAD(, Coroutine) straight, reversed;
555 QSLIST_MOVE_ATOMIC(&reversed, &ctx->scheduled_coroutines);
556 QSLIST_INIT(&straight);
558 while (!QSLIST_EMPTY(&reversed)) {
559 Coroutine *co = QSLIST_FIRST(&reversed);
560 QSLIST_REMOVE_HEAD(&reversed, co_scheduled_next);
561 QSLIST_INSERT_HEAD(&straight, co, co_scheduled_next);
564 while (!QSLIST_EMPTY(&straight)) {
565 Coroutine *co = QSLIST_FIRST(&straight);
566 QSLIST_REMOVE_HEAD(&straight, co_scheduled_next);
567 trace_aio_co_schedule_bh_cb(ctx, co);
569 /* Protected by write barrier in qemu_aio_coroutine_enter */
570 qatomic_set(&co->scheduled, NULL);
571 qemu_aio_coroutine_enter(ctx, co);
575 AioContext *aio_context_new(Error **errp)
577 int ret;
578 AioContext *ctx;
580 ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));
581 QSLIST_INIT(&ctx->bh_list);
582 QSIMPLEQ_INIT(&ctx->bh_slice_list);
583 aio_context_setup(ctx);
585 ret = event_notifier_init(&ctx->notifier, false);
586 if (ret < 0) {
587 error_setg_errno(errp, -ret, "Failed to initialize event notifier");
588 goto fail;
590 g_source_set_can_recurse(&ctx->source, true);
591 qemu_lockcnt_init(&ctx->list_lock);
593 ctx->co_schedule_bh = aio_bh_new(ctx, co_schedule_bh_cb, ctx);
594 QSLIST_INIT(&ctx->scheduled_coroutines);
596 aio_set_event_notifier(ctx, &ctx->notifier,
597 aio_context_notifier_cb,
598 aio_context_notifier_poll,
599 aio_context_notifier_poll_ready);
600 #ifdef CONFIG_LINUX_AIO
601 ctx->linux_aio = NULL;
602 #endif
604 #ifdef CONFIG_LINUX_IO_URING
605 ctx->linux_io_uring = NULL;
606 #endif
608 ctx->thread_pool = NULL;
609 qemu_rec_mutex_init(&ctx->lock);
610 timerlistgroup_init(&ctx->tlg, aio_timerlist_notify, ctx);
612 ctx->poll_ns = 0;
613 ctx->poll_max_ns = 0;
614 ctx->poll_grow = 0;
615 ctx->poll_shrink = 0;
617 ctx->aio_max_batch = 0;
619 ctx->thread_pool_min = 0;
620 ctx->thread_pool_max = THREAD_POOL_MAX_THREADS_DEFAULT;
622 register_aiocontext(ctx);
624 return ctx;
625 fail:
626 g_source_destroy(&ctx->source);
627 return NULL;
630 void aio_co_schedule(AioContext *ctx, Coroutine *co)
632 trace_aio_co_schedule(ctx, co);
633 const char *scheduled = qatomic_cmpxchg(&co->scheduled, NULL,
634 __func__);
636 if (scheduled) {
637 fprintf(stderr,
638 "%s: Co-routine was already scheduled in '%s'\n",
639 __func__, scheduled);
640 abort();
643 /* The coroutine might run and release the last ctx reference before we
644 * invoke qemu_bh_schedule(). Take a reference to keep ctx alive until
645 * we're done.
647 aio_context_ref(ctx);
649 QSLIST_INSERT_HEAD_ATOMIC(&ctx->scheduled_coroutines,
650 co, co_scheduled_next);
651 qemu_bh_schedule(ctx->co_schedule_bh);
653 aio_context_unref(ctx);
656 typedef struct AioCoRescheduleSelf {
657 Coroutine *co;
658 AioContext *new_ctx;
659 } AioCoRescheduleSelf;
661 static void aio_co_reschedule_self_bh(void *opaque)
663 AioCoRescheduleSelf *data = opaque;
664 aio_co_schedule(data->new_ctx, data->co);
667 void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx)
669 AioContext *old_ctx = qemu_get_current_aio_context();
671 if (old_ctx != new_ctx) {
672 AioCoRescheduleSelf data = {
673 .co = qemu_coroutine_self(),
674 .new_ctx = new_ctx,
677 * We can't directly schedule the coroutine in the target context
678 * because this would be racy: The other thread could try to enter the
679 * coroutine before it has yielded in this one.
681 aio_bh_schedule_oneshot(old_ctx, aio_co_reschedule_self_bh, &data);
682 qemu_coroutine_yield();
686 void aio_co_wake(Coroutine *co)
688 AioContext *ctx;
690 /* Read coroutine before co->ctx. Matches smp_wmb in
691 * qemu_coroutine_enter.
693 smp_read_barrier_depends();
694 ctx = qatomic_read(&co->ctx);
696 aio_co_enter(ctx, co);
699 void aio_co_enter(AioContext *ctx, Coroutine *co)
701 if (ctx != qemu_get_current_aio_context()) {
702 aio_co_schedule(ctx, co);
703 return;
706 if (qemu_in_coroutine()) {
707 Coroutine *self = qemu_coroutine_self();
708 assert(self != co);
709 QSIMPLEQ_INSERT_TAIL(&self->co_queue_wakeup, co, co_queue_next);
710 } else {
711 qemu_aio_coroutine_enter(ctx, co);
715 void aio_context_ref(AioContext *ctx)
717 g_source_ref(&ctx->source);
720 void aio_context_unref(AioContext *ctx)
722 g_source_unref(&ctx->source);
725 QEMU_DEFINE_STATIC_CO_TLS(AioContext *, my_aiocontext)
727 AioContext *qemu_get_current_aio_context(void)
729 AioContext *ctx = get_my_aiocontext();
730 if (ctx) {
731 return ctx;
733 if (bql_locked()) {
734 /* Possibly in a vCPU thread. */
735 return qemu_get_aio_context();
737 return NULL;
740 void qemu_set_current_aio_context(AioContext *ctx)
742 assert(!get_my_aiocontext());
743 set_my_aiocontext(ctx);
746 void aio_context_set_thread_pool_params(AioContext *ctx, int64_t min,
747 int64_t max, Error **errp)
750 if (min > max || max <= 0 || min < 0 || min > INT_MAX || max > INT_MAX) {
751 error_setg(errp, "bad thread-pool-min/thread-pool-max values");
752 return;
755 ctx->thread_pool_min = min;
756 ctx->thread_pool_max = max;
758 if (ctx->thread_pool) {
759 thread_pool_update_params(ctx->thread_pool, ctx);