xref: /openbmc/qemu/util/async.c (revision 1bbbe7cf2df11a1bc334489a3b87ee23e13c3c29)
1 /*
2  * Data plane event loop
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2009-2017 QEMU contributors
6  *
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:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
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.
24  */
25 
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 "exec/icount.h"
39 #include "trace.h"
40 
41 /***********************************************************/
42 /* bottom halves (can be seen as timers which expire ASAP) */
43 
44 /* QEMUBH::flags values */
45 enum {
46     /* Already enqueued and waiting for aio_bh_poll() */
47     BH_PENDING   = (1 << 0),
48 
49     /* Invoke the callback */
50     BH_SCHEDULED = (1 << 1),
51 
52     /* Delete without invoking callback */
53     BH_DELETED   = (1 << 2),
54 
55     /* Delete after invoking callback */
56     BH_ONESHOT   = (1 << 3),
57 
58     /* Schedule periodically when the event loop is idle */
59     BH_IDLE      = (1 << 4),
60 };
61 
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;
70 };
71 
72 /* Called concurrently from any thread */
73 static void aio_bh_enqueue(QEMUBH *bh, unsigned new_flags)
74 {
75     AioContext *ctx = bh->ctx;
76     unsigned old_flags;
77 
78     /*
79      * Synchronizes with atomic_fetch_and() in aio_bh_dequeue(), ensuring that
80      * insertion starts after BH_PENDING is set.
81      */
82     old_flags = qatomic_fetch_or(&bh->flags, BH_PENDING | new_flags);
83 
84     if (!(old_flags & BH_PENDING)) {
85         /*
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.
93          */
94         QSLIST_INSERT_HEAD_ATOMIC(&ctx->bh_list, bh, next);
95     }
96 
97     aio_notify(ctx);
98     if (unlikely(icount_enabled())) {
99         /*
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.
104          */
105         icount_notify_exit();
106     }
107 }
108 
109 /* Only called from aio_bh_poll() and aio_ctx_finalize() */
110 static QEMUBH *aio_bh_dequeue(BHList *head, unsigned *flags)
111 {
112     QEMUBH *bh = QSLIST_FIRST_RCU(head);
113 
114     if (!bh) {
115         return NULL;
116     }
117 
118     QSLIST_REMOVE_HEAD(head, next);
119 
120     /*
121      * Synchronizes with qatomic_fetch_or() in aio_bh_enqueue(), ensuring that
122      * the removal finishes before BH_PENDING is reset.
123      */
124     *flags = qatomic_fetch_and(&bh->flags,
125                               ~(BH_PENDING | BH_SCHEDULED | BH_IDLE));
126     return bh;
127 }
128 
129 void aio_bh_schedule_oneshot_full(AioContext *ctx, QEMUBHFunc *cb,
130                                   void *opaque, const char *name)
131 {
132     QEMUBH *bh;
133     bh = g_new(QEMUBH, 1);
134     *bh = (QEMUBH){
135         .ctx = ctx,
136         .cb = cb,
137         .opaque = opaque,
138         .name = name,
139     };
140     aio_bh_enqueue(bh, BH_SCHEDULED | BH_ONESHOT);
141 }
142 
143 QEMUBH *aio_bh_new_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
144                         const char *name, MemReentrancyGuard *reentrancy_guard)
145 {
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,
154     };
155     return bh;
156 }
157 
158 void aio_bh_call(QEMUBH *bh)
159 {
160     bool last_engaged_in_io = false;
161 
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);
168         }
169         reentrancy_guard->engaged_in_io = true;
170     }
171 
172     bh->cb(bh->opaque);
173 
174     if (reentrancy_guard) {
175         reentrancy_guard->engaged_in_io = last_engaged_in_io;
176     }
177 }
178 
179 /* Multiple occurrences of aio_bh_poll cannot be called concurrently. */
180 int aio_bh_poll(AioContext *ctx)
181 {
182     BHListSlice slice;
183     BHListSlice *s;
184     int ret = 0;
185 
186     /* Synchronizes with QSLIST_INSERT_HEAD_ATOMIC in aio_bh_enqueue().  */
187     QSLIST_MOVE_ATOMIC(&slice.bh_list, &ctx->bh_list);
188 
189     /*
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.
193      */
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
203 
204     while ((s = QSIMPLEQ_FIRST(&ctx->bh_slice_list))) {
205         QEMUBH *bh;
206         unsigned flags;
207 
208         bh = aio_bh_dequeue(&s->bh_list, &flags);
209         if (!bh) {
210             QSIMPLEQ_REMOVE_HEAD(&ctx->bh_slice_list, next);
211             continue;
212         }
213 
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;
218             }
219             aio_bh_call(bh);
220         }
221         if (flags & (BH_DELETED | BH_ONESHOT)) {
222             g_free(bh);
223         }
224     }
225 
226     return ret;
227 }
228 
229 void qemu_bh_schedule_idle(QEMUBH *bh)
230 {
231     aio_bh_enqueue(bh, BH_SCHEDULED | BH_IDLE);
232 }
233 
234 void qemu_bh_schedule(QEMUBH *bh)
235 {
236     aio_bh_enqueue(bh, BH_SCHEDULED);
237 }
238 
239 /* This func is async.
240  */
241 void qemu_bh_cancel(QEMUBH *bh)
242 {
243     qatomic_and(&bh->flags, ~BH_SCHEDULED);
244 }
245 
246 /* This func is async.The bottom half will do the delete action at the finial
247  * end.
248  */
249 void qemu_bh_delete(QEMUBH *bh)
250 {
251     aio_bh_enqueue(bh, BH_DELETED);
252 }
253 
254 static int64_t aio_compute_bh_timeout(BHList *head, int timeout)
255 {
256     QEMUBH *bh;
257 
258     QSLIST_FOREACH_RCU(bh, head, next) {
259         int flags = qatomic_load_acquire(&bh->flags);
260         if ((flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
261             if (flags & BH_IDLE) {
262                 /* idle bottom halves will be polled at least
263                  * every 10ms */
264                 timeout = 10000000;
265             } else {
266                 /* non-idle bottom halves will be executed
267                  * immediately */
268                 return 0;
269             }
270         }
271     }
272 
273     return timeout;
274 }
275 
276 int64_t
277 aio_compute_timeout(AioContext *ctx)
278 {
279     BHListSlice *s;
280     int64_t deadline;
281     int timeout = -1;
282 
283     timeout = aio_compute_bh_timeout(&ctx->bh_list, timeout);
284     if (timeout == 0) {
285         return 0;
286     }
287 
288     QSIMPLEQ_FOREACH(s, &ctx->bh_slice_list, next) {
289         timeout = aio_compute_bh_timeout(&s->bh_list, timeout);
290         if (timeout == 0) {
291             return 0;
292         }
293     }
294 
295     deadline = timerlistgroup_deadline_ns(&ctx->tlg);
296     if (deadline == 0) {
297         return 0;
298     } else {
299         return qemu_soonest_timeout(timeout, deadline);
300     }
301 }
302 
303 static gboolean
304 aio_ctx_prepare(GSource *source, gint    *timeout)
305 {
306     AioContext *ctx = (AioContext *) source;
307 
308     qatomic_set(&ctx->notify_me, qatomic_read(&ctx->notify_me) | 1);
309 
310     /*
311      * Write ctx->notify_me before computing the timeout
312      * (reading bottom half flags, etc.).  Pairs with
313      * smp_mb in aio_notify().
314      */
315     smp_mb();
316 
317     /* We assume there is no timeout already supplied */
318     *timeout = qemu_timeout_ns_to_ms(aio_compute_timeout(ctx));
319 
320     if (aio_prepare(ctx)) {
321         *timeout = 0;
322     }
323 
324     return *timeout == 0;
325 }
326 
327 static gboolean
328 aio_ctx_check(GSource *source)
329 {
330     AioContext *ctx = (AioContext *) source;
331     QEMUBH *bh;
332     BHListSlice *s;
333 
334     /* Finish computing the timeout before clearing the flag.  */
335     qatomic_store_release(&ctx->notify_me, qatomic_read(&ctx->notify_me) & ~1);
336     aio_notify_accept(ctx);
337 
338     QSLIST_FOREACH_RCU(bh, &ctx->bh_list, next) {
339         int flags = qatomic_load_acquire(&bh->flags);
340         if ((flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
341             return true;
342         }
343     }
344 
345     QSIMPLEQ_FOREACH(s, &ctx->bh_slice_list, next) {
346         QSLIST_FOREACH_RCU(bh, &s->bh_list, next) {
347             int flags = qatomic_load_acquire(&bh->flags);
348             if ((flags & (BH_SCHEDULED | BH_DELETED)) == BH_SCHEDULED) {
349                 return true;
350             }
351         }
352     }
353     return aio_pending(ctx) || (timerlistgroup_deadline_ns(&ctx->tlg) == 0);
354 }
355 
356 static gboolean
357 aio_ctx_dispatch(GSource     *source,
358                  GSourceFunc  callback,
359                  gpointer     user_data)
360 {
361     AioContext *ctx = (AioContext *) source;
362 
363     assert(callback == NULL);
364     aio_dispatch(ctx);
365     return true;
366 }
367 
368 static void
369 aio_ctx_finalize(GSource     *source)
370 {
371     AioContext *ctx = (AioContext *) source;
372     QEMUBH *bh;
373     unsigned flags;
374 
375     thread_pool_free_aio(ctx->thread_pool);
376 
377 #ifdef CONFIG_LINUX_AIO
378     if (ctx->linux_aio) {
379         laio_detach_aio_context(ctx->linux_aio, ctx);
380         laio_cleanup(ctx->linux_aio);
381         ctx->linux_aio = NULL;
382     }
383 #endif
384 
385 #ifdef CONFIG_LINUX_IO_URING
386     if (ctx->linux_io_uring) {
387         luring_detach_aio_context(ctx->linux_io_uring, ctx);
388         luring_cleanup(ctx->linux_io_uring);
389         ctx->linux_io_uring = NULL;
390     }
391 #endif
392 
393     assert(QSLIST_EMPTY(&ctx->scheduled_coroutines));
394     qemu_bh_delete(ctx->co_schedule_bh);
395 
396     /* There must be no aio_bh_poll() calls going on */
397     assert(QSIMPLEQ_EMPTY(&ctx->bh_slice_list));
398 
399     while ((bh = aio_bh_dequeue(&ctx->bh_list, &flags))) {
400         /*
401          * qemu_bh_delete() must have been called on BHs in this AioContext. In
402          * many cases memory leaks, hangs, or inconsistent state occur when a
403          * BH is leaked because something still expects it to run.
404          *
405          * If you hit this, fix the lifecycle of the BH so that
406          * qemu_bh_delete() and any associated cleanup is called before the
407          * AioContext is finalized.
408          */
409         if (unlikely(!(flags & BH_DELETED))) {
410             fprintf(stderr, "%s: BH '%s' leaked, aborting...\n",
411                     __func__, bh->name);
412             abort();
413         }
414 
415         g_free(bh);
416     }
417 
418     aio_set_event_notifier(ctx, &ctx->notifier, NULL, NULL, NULL);
419     event_notifier_cleanup(&ctx->notifier);
420     qemu_rec_mutex_destroy(&ctx->lock);
421     qemu_lockcnt_destroy(&ctx->list_lock);
422     timerlistgroup_deinit(&ctx->tlg);
423     unregister_aiocontext(ctx);
424     aio_context_destroy(ctx);
425 }
426 
427 static GSourceFuncs aio_source_funcs = {
428     aio_ctx_prepare,
429     aio_ctx_check,
430     aio_ctx_dispatch,
431     aio_ctx_finalize
432 };
433 
434 GSource *aio_get_g_source(AioContext *ctx)
435 {
436     aio_context_use_g_source(ctx);
437     g_source_ref(&ctx->source);
438     return &ctx->source;
439 }
440 
441 ThreadPoolAio *aio_get_thread_pool(AioContext *ctx)
442 {
443     if (!ctx->thread_pool) {
444         ctx->thread_pool = thread_pool_new_aio(ctx);
445     }
446     return ctx->thread_pool;
447 }
448 
449 #ifdef CONFIG_LINUX_AIO
450 LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp)
451 {
452     if (!ctx->linux_aio) {
453         ctx->linux_aio = laio_init(errp);
454         if (ctx->linux_aio) {
455             laio_attach_aio_context(ctx->linux_aio, ctx);
456         }
457     }
458     return ctx->linux_aio;
459 }
460 
461 LinuxAioState *aio_get_linux_aio(AioContext *ctx)
462 {
463     assert(ctx->linux_aio);
464     return ctx->linux_aio;
465 }
466 #endif
467 
468 #ifdef CONFIG_LINUX_IO_URING
469 LuringState *aio_setup_linux_io_uring(AioContext *ctx, Error **errp)
470 {
471     if (ctx->linux_io_uring) {
472         return ctx->linux_io_uring;
473     }
474 
475     ctx->linux_io_uring = luring_init(errp);
476     if (!ctx->linux_io_uring) {
477         return NULL;
478     }
479 
480     luring_attach_aio_context(ctx->linux_io_uring, ctx);
481     return ctx->linux_io_uring;
482 }
483 
484 LuringState *aio_get_linux_io_uring(AioContext *ctx)
485 {
486     assert(ctx->linux_io_uring);
487     return ctx->linux_io_uring;
488 }
489 #endif
490 
491 void aio_notify(AioContext *ctx)
492 {
493     /*
494      * Write e.g. ctx->bh_list before writing ctx->notified.  Pairs with
495      * smp_mb() in aio_notify_accept().
496      */
497     smp_wmb();
498     qatomic_set(&ctx->notified, true);
499 
500     /*
501      * Write ctx->notified (and also ctx->bh_list) before reading ctx->notify_me.
502      * Pairs with smp_mb() in aio_ctx_prepare or aio_poll.
503      */
504     smp_mb();
505     if (qatomic_read(&ctx->notify_me)) {
506         event_notifier_set(&ctx->notifier);
507     }
508 }
509 
510 void aio_notify_accept(AioContext *ctx)
511 {
512     qatomic_set(&ctx->notified, false);
513 
514     /*
515      * Order reads of ctx->notified (in aio_context_notifier_poll()) and the
516      * above clearing of ctx->notified before reads of e.g. bh->flags.  Pairs
517      * with smp_wmb() in aio_notify.
518      */
519     smp_mb();
520 }
521 
522 static void aio_timerlist_notify(void *opaque, QEMUClockType type)
523 {
524     aio_notify(opaque);
525 }
526 
527 static void aio_context_notifier_cb(EventNotifier *e)
528 {
529     AioContext *ctx = container_of(e, AioContext, notifier);
530 
531     event_notifier_test_and_clear(&ctx->notifier);
532 }
533 
534 /* Returns true if aio_notify() was called (e.g. a BH was scheduled) */
535 static bool aio_context_notifier_poll(void *opaque)
536 {
537     EventNotifier *e = opaque;
538     AioContext *ctx = container_of(e, AioContext, notifier);
539 
540     /*
541      * No need for load-acquire because we just want to kick the
542      * event loop.  aio_notify_accept() takes care of synchronizing
543      * the event loop with the producers.
544      */
545     return qatomic_read(&ctx->notified);
546 }
547 
548 static void aio_context_notifier_poll_ready(EventNotifier *e)
549 {
550     /* Do nothing, we just wanted to kick the event loop */
551 }
552 
553 static void co_schedule_bh_cb(void *opaque)
554 {
555     AioContext *ctx = opaque;
556     QSLIST_HEAD(, Coroutine) straight, reversed;
557 
558     QSLIST_MOVE_ATOMIC(&reversed, &ctx->scheduled_coroutines);
559     QSLIST_INIT(&straight);
560 
561     while (!QSLIST_EMPTY(&reversed)) {
562         Coroutine *co = QSLIST_FIRST(&reversed);
563         QSLIST_REMOVE_HEAD(&reversed, co_scheduled_next);
564         QSLIST_INSERT_HEAD(&straight, co, co_scheduled_next);
565     }
566 
567     while (!QSLIST_EMPTY(&straight)) {
568         Coroutine *co = QSLIST_FIRST(&straight);
569         QSLIST_REMOVE_HEAD(&straight, co_scheduled_next);
570         trace_aio_co_schedule_bh_cb(ctx, co);
571 
572         /* Protected by write barrier in qemu_aio_coroutine_enter */
573         qatomic_set(&co->scheduled, NULL);
574         qemu_aio_coroutine_enter(ctx, co);
575     }
576 }
577 
578 AioContext *aio_context_new(Error **errp)
579 {
580     int ret;
581     AioContext *ctx;
582 
583     ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));
584     QSLIST_INIT(&ctx->bh_list);
585     QSIMPLEQ_INIT(&ctx->bh_slice_list);
586     aio_context_setup(ctx);
587 
588     ret = event_notifier_init(&ctx->notifier, false);
589     if (ret < 0) {
590         error_setg_errno(errp, -ret, "Failed to initialize event notifier");
591         goto fail;
592     }
593     g_source_set_can_recurse(&ctx->source, true);
594     qemu_lockcnt_init(&ctx->list_lock);
595 
596     ctx->co_schedule_bh = aio_bh_new(ctx, co_schedule_bh_cb, ctx);
597     QSLIST_INIT(&ctx->scheduled_coroutines);
598 
599     aio_set_event_notifier(ctx, &ctx->notifier,
600                            aio_context_notifier_cb,
601                            aio_context_notifier_poll,
602                            aio_context_notifier_poll_ready);
603 #ifdef CONFIG_LINUX_AIO
604     ctx->linux_aio = NULL;
605 #endif
606 
607 #ifdef CONFIG_LINUX_IO_URING
608     ctx->linux_io_uring = NULL;
609 #endif
610 
611     ctx->thread_pool = NULL;
612     qemu_rec_mutex_init(&ctx->lock);
613     timerlistgroup_init(&ctx->tlg, aio_timerlist_notify, ctx);
614 
615     ctx->poll_max_ns = 0;
616     ctx->poll_grow = 0;
617     ctx->poll_shrink = 0;
618 
619     ctx->aio_max_batch = 0;
620 
621     ctx->thread_pool_min = 0;
622     ctx->thread_pool_max = THREAD_POOL_MAX_THREADS_DEFAULT;
623 
624     register_aiocontext(ctx);
625 
626     return ctx;
627 fail:
628     g_source_destroy(&ctx->source);
629     return NULL;
630 }
631 
632 void aio_co_schedule(AioContext *ctx, Coroutine *co)
633 {
634     trace_aio_co_schedule(ctx, co);
635     const char *scheduled = qatomic_cmpxchg(&co->scheduled, NULL,
636                                            __func__);
637 
638     if (scheduled) {
639         fprintf(stderr,
640                 "%s: Co-routine was already scheduled in '%s'\n",
641                 __func__, scheduled);
642         abort();
643     }
644 
645     /* The coroutine might run and release the last ctx reference before we
646      * invoke qemu_bh_schedule().  Take a reference to keep ctx alive until
647      * we're done.
648      */
649     aio_context_ref(ctx);
650 
651     QSLIST_INSERT_HEAD_ATOMIC(&ctx->scheduled_coroutines,
652                               co, co_scheduled_next);
653     qemu_bh_schedule(ctx->co_schedule_bh);
654 
655     aio_context_unref(ctx);
656 }
657 
658 typedef struct AioCoRescheduleSelf {
659     Coroutine *co;
660     AioContext *new_ctx;
661 } AioCoRescheduleSelf;
662 
663 static void aio_co_reschedule_self_bh(void *opaque)
664 {
665     AioCoRescheduleSelf *data = opaque;
666     aio_co_schedule(data->new_ctx, data->co);
667 }
668 
669 void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx)
670 {
671     AioContext *old_ctx = qemu_get_current_aio_context();
672 
673     if (old_ctx != new_ctx) {
674         AioCoRescheduleSelf data = {
675             .co = qemu_coroutine_self(),
676             .new_ctx = new_ctx,
677         };
678         /*
679          * We can't directly schedule the coroutine in the target context
680          * because this would be racy: The other thread could try to enter the
681          * coroutine before it has yielded in this one.
682          */
683         aio_bh_schedule_oneshot(old_ctx, aio_co_reschedule_self_bh, &data);
684         qemu_coroutine_yield();
685     }
686 }
687 
688 void aio_co_wake(Coroutine *co)
689 {
690     AioContext *ctx;
691 
692     /* Read coroutine before co->ctx.  Matches smp_wmb in
693      * qemu_coroutine_enter.
694      */
695     smp_read_barrier_depends();
696     ctx = qatomic_read(&co->ctx);
697 
698     aio_co_enter(ctx, co);
699 }
700 
701 void aio_co_enter(AioContext *ctx, Coroutine *co)
702 {
703     if (ctx != qemu_get_current_aio_context()) {
704         aio_co_schedule(ctx, co);
705         return;
706     }
707 
708     if (qemu_in_coroutine()) {
709         Coroutine *self = qemu_coroutine_self();
710         assert(self != co);
711         QSIMPLEQ_INSERT_TAIL(&self->co_queue_wakeup, co, co_queue_next);
712     } else {
713         qemu_aio_coroutine_enter(ctx, co);
714     }
715 }
716 
717 void aio_context_ref(AioContext *ctx)
718 {
719     g_source_ref(&ctx->source);
720 }
721 
722 void aio_context_unref(AioContext *ctx)
723 {
724     g_source_unref(&ctx->source);
725 }
726 
727 QEMU_DEFINE_STATIC_CO_TLS(AioContext *, my_aiocontext)
728 
729 AioContext *qemu_get_current_aio_context(void)
730 {
731     AioContext *ctx = get_my_aiocontext();
732     if (ctx) {
733         return ctx;
734     }
735     if (bql_locked()) {
736         /* Possibly in a vCPU thread.  */
737         return qemu_get_aio_context();
738     }
739     return NULL;
740 }
741 
742 void qemu_set_current_aio_context(AioContext *ctx)
743 {
744     assert(!get_my_aiocontext());
745     set_my_aiocontext(ctx);
746 }
747 
748 void aio_context_set_thread_pool_params(AioContext *ctx, int64_t min,
749                                         int64_t max, Error **errp)
750 {
751 
752     if (min > max || max <= 0 || min < 0 || min > INT_MAX || max > INT_MAX) {
753         error_setg(errp, "bad thread-pool-min/thread-pool-max values");
754         return;
755     }
756 
757     ctx->thread_pool_min = min;
758     ctx->thread_pool_max = max;
759 
760     if (ctx->thread_pool) {
761         thread_pool_update_params(ctx->thread_pool, ctx);
762     }
763 }
764