qemu-coroutine-sleep.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #include "qemu/osdep.h"
  14. #include "qemu/coroutine.h"
  15. #include "qemu/coroutine_int.h"
  16. #include "qemu/timer.h"
  17. #include "block/aio.h"
  18. static const char *qemu_co_sleep_ns__scheduled = "qemu_co_sleep_ns";
  19. struct QemuCoSleepState {
  20. Coroutine *co;
  21. QEMUTimer *ts;
  22. QemuCoSleepState **user_state_pointer;
  23. };
  24. void qemu_co_sleep_wake(QemuCoSleepState *sleep_state)
  25. {
  26. /* Write of schedule protected by barrier write in aio_co_schedule */
  27. const char *scheduled = atomic_cmpxchg(&sleep_state->co->scheduled,
  28. qemu_co_sleep_ns__scheduled, NULL);
  29. assert(scheduled == qemu_co_sleep_ns__scheduled);
  30. if (sleep_state->user_state_pointer) {
  31. *sleep_state->user_state_pointer = NULL;
  32. }
  33. timer_del(sleep_state->ts);
  34. aio_co_wake(sleep_state->co);
  35. }
  36. static void co_sleep_cb(void *opaque)
  37. {
  38. qemu_co_sleep_wake(opaque);
  39. }
  40. void coroutine_fn qemu_co_sleep_ns_wakeable(QEMUClockType type, int64_t ns,
  41. QemuCoSleepState **sleep_state)
  42. {
  43. AioContext *ctx = qemu_get_current_aio_context();
  44. QemuCoSleepState state = {
  45. .co = qemu_coroutine_self(),
  46. .ts = aio_timer_new(ctx, type, SCALE_NS, co_sleep_cb, &state),
  47. .user_state_pointer = sleep_state,
  48. };
  49. const char *scheduled = atomic_cmpxchg(&state.co->scheduled, NULL,
  50. qemu_co_sleep_ns__scheduled);
  51. if (scheduled) {
  52. fprintf(stderr,
  53. "%s: Co-routine was already scheduled in '%s'\n",
  54. __func__, scheduled);
  55. abort();
  56. }
  57. if (sleep_state) {
  58. *sleep_state = &state;
  59. }
  60. timer_mod(state.ts, qemu_clock_get_ns(type) + ns);
  61. qemu_coroutine_yield();
  62. if (sleep_state) {
  63. /*
  64. * Note that *sleep_state is cleared during qemu_co_sleep_wake
  65. * before resuming this coroutine.
  66. */
  67. assert(*sleep_state == NULL);
  68. }
  69. timer_free(state.ts);
  70. }