qemu-coroutine-sleep.c (2133B)
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 14#include "qemu/osdep.h" 15#include "qemu/coroutine.h" 16#include "qemu/coroutine_int.h" 17#include "qemu/timer.h" 18#include "block/aio.h" 19 20static const char *qemu_co_sleep_ns__scheduled = "qemu_co_sleep_ns"; 21 22void qemu_co_sleep_wake(QemuCoSleep *w) 23{ 24 Coroutine *co; 25 26 co = w->to_wake; 27 w->to_wake = NULL; 28 if (co) { 29 /* Write of schedule protected by barrier write in aio_co_schedule */ 30 const char *scheduled = qatomic_cmpxchg(&co->scheduled, 31 qemu_co_sleep_ns__scheduled, NULL); 32 33 assert(scheduled == qemu_co_sleep_ns__scheduled); 34 aio_co_wake(co); 35 } 36} 37 38static void co_sleep_cb(void *opaque) 39{ 40 QemuCoSleep *w = opaque; 41 qemu_co_sleep_wake(w); 42} 43 44void coroutine_fn qemu_co_sleep(QemuCoSleep *w) 45{ 46 Coroutine *co = qemu_coroutine_self(); 47 48 const char *scheduled = qatomic_cmpxchg(&co->scheduled, NULL, 49 qemu_co_sleep_ns__scheduled); 50 if (scheduled) { 51 fprintf(stderr, 52 "%s: Co-routine was already scheduled in '%s'\n", 53 __func__, scheduled); 54 abort(); 55 } 56 57 w->to_wake = co; 58 qemu_coroutine_yield(); 59 60 /* w->to_wake is cleared before resuming this coroutine. */ 61 assert(w->to_wake == NULL); 62} 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}