]> git.proxmox.com Git - mirror_qemu.git/blame - util/qemu-coroutine-sleep.c
Merge tag 'for-upstream' of https://gitlab.com/bonzini/qemu into staging
[mirror_qemu.git] / util / qemu-coroutine-sleep.c
CommitLineData
7e624667
SH
1/*
2 * QEMU coroutine sleep
3 *
4 * Copyright IBM, Corp. 2011
5 *
6 * Authors:
7 * Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10 * See the COPYING.LIB file in the top-level directory.
11 *
12 */
13
aafd7584 14#include "qemu/osdep.h"
10817bf0 15#include "qemu/coroutine.h"
6133b39f 16#include "qemu/coroutine_int.h"
1de7afc9 17#include "qemu/timer.h"
3ab7bd19 18#include "block/aio.h"
7e624667 19
3d692649
VSO
20static const char *qemu_co_sleep_ns__scheduled = "qemu_co_sleep_ns";
21
29a6ea24
PB
22void qemu_co_sleep_wake(QemuCoSleep *w)
23{
3d692649 24 Coroutine *co;
7e624667 25
29a6ea24
PB
26 co = w->to_wake;
27 w->to_wake = NULL;
28 if (co) {
eaee0720 29 /* Write of schedule protected by barrier write in aio_co_schedule */
29a6ea24 30 const char *scheduled = qatomic_cmpxchg(&co->scheduled,
eaee0720 31 qemu_co_sleep_ns__scheduled, NULL);
3d692649 32
eaee0720 33 assert(scheduled == qemu_co_sleep_ns__scheduled);
29a6ea24 34 aio_co_wake(co);
eaee0720 35 }
7e624667
SH
36}
37
3d692649
VSO
38static void co_sleep_cb(void *opaque)
39{
29a6ea24
PB
40 QemuCoSleep *w = opaque;
41 qemu_co_sleep_wake(w);
3d692649
VSO
42}
43
0a6f0c76 44void coroutine_fn qemu_co_sleep(QemuCoSleep *w)
3ab7bd19 45{
29a6ea24 46 Coroutine *co = qemu_coroutine_self();
6133b39f 47
29a6ea24
PB
48 const char *scheduled = qatomic_cmpxchg(&co->scheduled, NULL,
49 qemu_co_sleep_ns__scheduled);
6133b39f
JC
50 if (scheduled) {
51 fprintf(stderr,
52 "%s: Co-routine was already scheduled in '%s'\n",
53 __func__, scheduled);
54 abort();
55 }
3d692649 56
29a6ea24 57 w->to_wake = co;
3ab7bd19 58 qemu_coroutine_yield();
fb74a286 59
29a6ea24
PB
60 /* w->to_wake is cleared before resuming this coroutine. */
61 assert(w->to_wake == NULL);
3ab7bd19 62}
0a6f0c76
PB
63
64void coroutine_fn qemu_co_sleep_ns_wakeable(QemuCoSleep *w,
65 QEMUClockType type, int64_t ns)
66{
67 AioContext *ctx = qemu_get_current_aio_context();
68 QEMUTimer ts;
69
70 aio_timer_init(ctx, &ts, type, SCALE_NS, co_sleep_cb, w);
71 timer_mod(&ts, qemu_clock_get_ns(type) + ns);
72
73 /*
74 * The timer will fire in the current AiOContext, so the callback
75 * must happen after qemu_co_sleep yields and there is no race
76 * between timer_mod and qemu_co_sleep.
77 */
78 qemu_co_sleep(w);
79 timer_del(&ts);
80}