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