xref: /openbmc/qemu/util/async.c (revision 9febfa94b69b7146582c48a868bd2330ac45037f)
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     if (!ctx->initialized) {
376         return;
377     }
378 
379     thread_pool_free_aio(ctx->thread_pool);
380 
381 #ifdef CONFIG_LINUX_AIO
382     if (ctx->linux_aio) {
383         laio_detach_aio_context(ctx->linux_aio, ctx);
384         laio_cleanup(ctx->linux_aio);
385         ctx->linux_aio = NULL;
386     }
387 #endif
388 
389     assert(QSLIST_EMPTY(&ctx->scheduled_coroutines));
390     qemu_bh_delete(ctx->co_schedule_bh);
391 
392     /* There must be no aio_bh_poll() calls going on */
393     assert(QSIMPLEQ_EMPTY(&ctx->bh_slice_list));
394 
395     while ((bh = aio_bh_dequeue(&ctx->bh_list, &flags))) {
396         /*
397          * qemu_bh_delete() must have been called on BHs in this AioContext. In
398          * many cases memory leaks, hangs, or inconsistent state occur when a
399          * BH is leaked because something still expects it to run.
400          *
401          * If you hit this, fix the lifecycle of the BH so that
402          * qemu_bh_delete() and any associated cleanup is called before the
403          * AioContext is finalized.
404          */
405         if (unlikely(!(flags & BH_DELETED))) {
406             fprintf(stderr, "%s: BH '%s' leaked, aborting...\n",
407                     __func__, bh->name);
408             abort();
409         }
410 
411         g_free(bh);
412     }
413 
414     aio_set_event_notifier(ctx, &ctx->notifier, NULL, NULL, NULL);
415     event_notifier_cleanup(&ctx->notifier);
416     qemu_rec_mutex_destroy(&ctx->lock);
417     timerlistgroup_deinit(&ctx->tlg);
418     unregister_aiocontext(ctx);
419     aio_context_destroy(ctx);
420     /* aio_context_destroy() still needs the lock */
421     qemu_lockcnt_destroy(&ctx->list_lock);
422 }
423 
424 static GSourceFuncs aio_source_funcs = {
425     aio_ctx_prepare,
426     aio_ctx_check,
427     aio_ctx_dispatch,
428     aio_ctx_finalize
429 };
430 
431 GSource *aio_get_g_source(AioContext *ctx)
432 {
433     g_source_ref(&ctx->source);
434     return &ctx->source;
435 }
436 
437 ThreadPoolAio *aio_get_thread_pool(AioContext *ctx)
438 {
439     if (!ctx->thread_pool) {
440         ctx->thread_pool = thread_pool_new_aio(ctx);
441     }
442     return ctx->thread_pool;
443 }
444 
445 #ifdef CONFIG_LINUX_AIO
446 LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp)
447 {
448     if (!ctx->linux_aio) {
449         ctx->linux_aio = laio_init(errp);
450         if (ctx->linux_aio) {
451             laio_attach_aio_context(ctx->linux_aio, ctx);
452         }
453     }
454     return ctx->linux_aio;
455 }
456 
457 LinuxAioState *aio_get_linux_aio(AioContext *ctx)
458 {
459     assert(ctx->linux_aio);
460     return ctx->linux_aio;
461 }
462 #endif
463 
464 void aio_notify(AioContext *ctx)
465 {
466     /*
467      * Write e.g. ctx->bh_list before writing ctx->notified.  Pairs with
468      * smp_mb() in aio_notify_accept().
469      */
470     smp_wmb();
471     qatomic_set(&ctx->notified, true);
472 
473     /*
474      * Write ctx->notified (and also ctx->bh_list) before reading ctx->notify_me.
475      * Pairs with smp_mb() in aio_ctx_prepare or aio_poll.
476      */
477     smp_mb();
478     if (qatomic_read(&ctx->notify_me)) {
479         event_notifier_set(&ctx->notifier);
480     }
481 }
482 
483 void aio_notify_accept(AioContext *ctx)
484 {
485     qatomic_set(&ctx->notified, false);
486 
487     /*
488      * Order reads of ctx->notified (in aio_context_notifier_poll()) and the
489      * above clearing of ctx->notified before reads of e.g. bh->flags.  Pairs
490      * with smp_wmb() in aio_notify.
491      */
492     smp_mb();
493 }
494 
495 static void aio_timerlist_notify(void *opaque, QEMUClockType type)
496 {
497     aio_notify(opaque);
498 }
499 
500 static void aio_context_notifier_cb(EventNotifier *e)
501 {
502     AioContext *ctx = container_of(e, AioContext, notifier);
503 
504     event_notifier_test_and_clear(&ctx->notifier);
505 }
506 
507 /* Returns true if aio_notify() was called (e.g. a BH was scheduled) */
508 static bool aio_context_notifier_poll(void *opaque)
509 {
510     EventNotifier *e = opaque;
511     AioContext *ctx = container_of(e, AioContext, notifier);
512 
513     /*
514      * No need for load-acquire because we just want to kick the
515      * event loop.  aio_notify_accept() takes care of synchronizing
516      * the event loop with the producers.
517      */
518     return qatomic_read(&ctx->notified);
519 }
520 
521 static void aio_context_notifier_poll_ready(EventNotifier *e)
522 {
523     /* Do nothing, we just wanted to kick the event loop */
524 }
525 
526 static void co_schedule_bh_cb(void *opaque)
527 {
528     AioContext *ctx = opaque;
529     QSLIST_HEAD(, Coroutine) straight, reversed;
530 
531     QSLIST_MOVE_ATOMIC(&reversed, &ctx->scheduled_coroutines);
532     QSLIST_INIT(&straight);
533 
534     while (!QSLIST_EMPTY(&reversed)) {
535         Coroutine *co = QSLIST_FIRST(&reversed);
536         QSLIST_REMOVE_HEAD(&reversed, co_scheduled_next);
537         QSLIST_INSERT_HEAD(&straight, co, co_scheduled_next);
538     }
539 
540     while (!QSLIST_EMPTY(&straight)) {
541         Coroutine *co = QSLIST_FIRST(&straight);
542         QSLIST_REMOVE_HEAD(&straight, co_scheduled_next);
543         trace_aio_co_schedule_bh_cb(ctx, co);
544 
545         /* Protected by write barrier in qemu_aio_coroutine_enter */
546         qatomic_set(&co->scheduled, NULL);
547         qemu_aio_coroutine_enter(ctx, co);
548     }
549 }
550 
551 AioContext *aio_context_new(Error **errp)
552 {
553     ERRP_GUARD();
554     int ret;
555     AioContext *ctx;
556 
557     /*
558      * ctx is freed by g_source_unref() (e.g. aio_context_unref()). ctx's
559      * resources are freed as follows:
560      *
561      * 1. By aio_ctx_finalize() after aio_context_new() has returned and set
562      *    ->initialized = true.
563      *
564      * 2. By manual cleanup code in this function's error paths before goto
565      *    fail.
566      *
567      * Be careful to free resources in both cases!
568      */
569     ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));
570     QSLIST_INIT(&ctx->bh_list);
571     QSIMPLEQ_INIT(&ctx->bh_slice_list);
572 
573     ret = event_notifier_init(&ctx->notifier, false);
574     if (ret < 0) {
575         error_setg_errno(errp, -ret, "Failed to initialize event notifier");
576         goto fail;
577     }
578 
579     /*
580      * Resources cannot easily be freed manually after aio_context_setup(). If
581      * you add any new resources to AioContext, it's probably best to acquire
582      * them before aio_context_setup().
583      */
584     if (!aio_context_setup(ctx, errp)) {
585         event_notifier_cleanup(&ctx->notifier);
586         goto fail;
587     }
588 
589     g_source_set_can_recurse(&ctx->source, true);
590     qemu_lockcnt_init(&ctx->list_lock);
591 
592     ctx->co_schedule_bh = aio_bh_new(ctx, co_schedule_bh_cb, ctx);
593     QSLIST_INIT(&ctx->scheduled_coroutines);
594 
595     aio_set_event_notifier(ctx, &ctx->notifier,
596                            aio_context_notifier_cb,
597                            aio_context_notifier_poll,
598                            aio_context_notifier_poll_ready);
599 #ifdef CONFIG_LINUX_AIO
600     ctx->linux_aio = NULL;
601 #endif
602 
603     ctx->thread_pool = NULL;
604     qemu_rec_mutex_init(&ctx->lock);
605     timerlistgroup_init(&ctx->tlg, aio_timerlist_notify, ctx);
606 
607     ctx->poll_max_ns = 0;
608     ctx->poll_grow = 0;
609     ctx->poll_shrink = 0;
610 
611     ctx->aio_max_batch = 0;
612 
613     ctx->thread_pool_min = 0;
614     ctx->thread_pool_max = THREAD_POOL_MAX_THREADS_DEFAULT;
615 
616     register_aiocontext(ctx);
617 
618     ctx->initialized = true;
619 
620     return ctx;
621 fail:
622     g_source_unref(&ctx->source);
623     return NULL;
624 }
625 
626 void aio_co_schedule(AioContext *ctx, Coroutine *co)
627 {
628     trace_aio_co_schedule(ctx, co);
629     const char *scheduled = qatomic_cmpxchg(&co->scheduled, NULL,
630                                            __func__);
631 
632     if (scheduled) {
633         fprintf(stderr,
634                 "%s: Co-routine was already scheduled in '%s'\n",
635                 __func__, scheduled);
636         abort();
637     }
638 
639     /* The coroutine might run and release the last ctx reference before we
640      * invoke qemu_bh_schedule().  Take a reference to keep ctx alive until
641      * we're done.
642      */
643     aio_context_ref(ctx);
644 
645     QSLIST_INSERT_HEAD_ATOMIC(&ctx->scheduled_coroutines,
646                               co, co_scheduled_next);
647     qemu_bh_schedule(ctx->co_schedule_bh);
648 
649     aio_context_unref(ctx);
650 }
651 
652 typedef struct AioCoRescheduleSelf {
653     Coroutine *co;
654     AioContext *new_ctx;
655 } AioCoRescheduleSelf;
656 
657 static void aio_co_reschedule_self_bh(void *opaque)
658 {
659     AioCoRescheduleSelf *data = opaque;
660     aio_co_schedule(data->new_ctx, data->co);
661 }
662 
663 void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx)
664 {
665     AioContext *old_ctx = qemu_get_current_aio_context();
666 
667     if (old_ctx != new_ctx) {
668         AioCoRescheduleSelf data = {
669             .co = qemu_coroutine_self(),
670             .new_ctx = new_ctx,
671         };
672         /*
673          * We can't directly schedule the coroutine in the target context
674          * because this would be racy: The other thread could try to enter the
675          * coroutine before it has yielded in this one.
676          */
677         aio_bh_schedule_oneshot(old_ctx, aio_co_reschedule_self_bh, &data);
678         qemu_coroutine_yield();
679     }
680 }
681 
682 void aio_co_wake(Coroutine *co)
683 {
684     AioContext *ctx;
685 
686     /* Read coroutine before co->ctx.  Matches smp_wmb in
687      * qemu_coroutine_enter.
688      */
689     smp_read_barrier_depends();
690     ctx = qatomic_read(&co->ctx);
691 
692     aio_co_enter(ctx, co);
693 }
694 
695 void aio_co_enter(AioContext *ctx, Coroutine *co)
696 {
697     if (ctx != qemu_get_current_aio_context()) {
698         aio_co_schedule(ctx, co);
699         return;
700     }
701 
702     if (qemu_in_coroutine()) {
703         Coroutine *self = qemu_coroutine_self();
704         assert(self != co);
705         QSIMPLEQ_INSERT_TAIL(&self->co_queue_wakeup, co, co_queue_next);
706     } else {
707         qemu_aio_coroutine_enter(ctx, co);
708     }
709 }
710 
711 void aio_context_ref(AioContext *ctx)
712 {
713     g_source_ref(&ctx->source);
714 }
715 
716 void aio_context_unref(AioContext *ctx)
717 {
718     g_source_unref(&ctx->source);
719 }
720 
721 QEMU_DEFINE_STATIC_CO_TLS(AioContext *, my_aiocontext)
722 
723 AioContext *qemu_get_current_aio_context(void)
724 {
725     AioContext *ctx = get_my_aiocontext();
726     if (ctx) {
727         return ctx;
728     }
729     if (bql_locked()) {
730         /* Possibly in a vCPU thread.  */
731         return qemu_get_aio_context();
732     }
733     return NULL;
734 }
735 
736 void qemu_set_current_aio_context(AioContext *ctx)
737 {
738     assert(!get_my_aiocontext());
739     set_my_aiocontext(ctx);
740 }
741 
742 void aio_context_set_thread_pool_params(AioContext *ctx, int64_t min,
743                                         int64_t max, Error **errp)
744 {
745 
746     if (min > max || max <= 0 || min < 0 || min > INT_MAX || max > INT_MAX) {
747         error_setg(errp, "bad thread-pool-min/thread-pool-max values");
748         return;
749     }
750 
751     ctx->thread_pool_min = min;
752     ctx->thread_pool_max = max;
753 
754     if (ctx->thread_pool) {
755         thread_pool_update_params(ctx->thread_pool, ctx);
756     }
757 }
758