coroutine-sigaltstack.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * sigaltstack coroutine initialization code
  3. *
  4. * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
  5. * Copyright (C) 2011 Kevin Wolf <kwolf@redhat.com>
  6. * Copyright (C) 2012 Alex Barcelo <abarcelo@ac.upc.edu>
  7. ** This file is partly based on pth_mctx.c, from the GNU Portable Threads
  8. ** Copyright (c) 1999-2006 Ralf S. Engelschall <rse@engelschall.com>
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  22. */
  23. /* XXX Is there a nicer way to disable glibc's stack check for longjmp? */
  24. #ifdef _FORTIFY_SOURCE
  25. #undef _FORTIFY_SOURCE
  26. #endif
  27. #include <stdlib.h>
  28. #include <setjmp.h>
  29. #include <stdint.h>
  30. #include <pthread.h>
  31. #include <signal.h>
  32. #include "qemu-common.h"
  33. #include "block/coroutine_int.h"
  34. enum {
  35. /* Maximum free pool size prevents holding too many freed coroutines */
  36. POOL_MAX_SIZE = 64,
  37. };
  38. /** Free list to speed up creation */
  39. static QSLIST_HEAD(, Coroutine) pool = QSLIST_HEAD_INITIALIZER(pool);
  40. static unsigned int pool_size;
  41. typedef struct {
  42. Coroutine base;
  43. void *stack;
  44. jmp_buf env;
  45. } CoroutineUContext;
  46. /**
  47. * Per-thread coroutine bookkeeping
  48. */
  49. typedef struct {
  50. /** Currently executing coroutine */
  51. Coroutine *current;
  52. /** The default coroutine */
  53. CoroutineUContext leader;
  54. /** Information for the signal handler (trampoline) */
  55. jmp_buf tr_reenter;
  56. volatile sig_atomic_t tr_called;
  57. void *tr_handler;
  58. } CoroutineThreadState;
  59. static pthread_key_t thread_state_key;
  60. static CoroutineThreadState *coroutine_get_thread_state(void)
  61. {
  62. CoroutineThreadState *s = pthread_getspecific(thread_state_key);
  63. if (!s) {
  64. s = g_malloc0(sizeof(*s));
  65. s->current = &s->leader.base;
  66. pthread_setspecific(thread_state_key, s);
  67. }
  68. return s;
  69. }
  70. static void qemu_coroutine_thread_cleanup(void *opaque)
  71. {
  72. CoroutineThreadState *s = opaque;
  73. g_free(s);
  74. }
  75. static void __attribute__((destructor)) coroutine_cleanup(void)
  76. {
  77. Coroutine *co;
  78. Coroutine *tmp;
  79. QSLIST_FOREACH_SAFE(co, &pool, pool_next, tmp) {
  80. g_free(DO_UPCAST(CoroutineUContext, base, co)->stack);
  81. g_free(co);
  82. }
  83. }
  84. static void __attribute__((constructor)) coroutine_init(void)
  85. {
  86. int ret;
  87. ret = pthread_key_create(&thread_state_key, qemu_coroutine_thread_cleanup);
  88. if (ret != 0) {
  89. fprintf(stderr, "unable to create leader key: %s\n", strerror(errno));
  90. abort();
  91. }
  92. }
  93. /* "boot" function
  94. * This is what starts the coroutine, is called from the trampoline
  95. * (from the signal handler when it is not signal handling, read ahead
  96. * for more information).
  97. */
  98. static void coroutine_bootstrap(CoroutineUContext *self, Coroutine *co)
  99. {
  100. /* Initialize longjmp environment and switch back the caller */
  101. if (!setjmp(self->env)) {
  102. longjmp(*(jmp_buf *)co->entry_arg, 1);
  103. }
  104. while (true) {
  105. co->entry(co->entry_arg);
  106. qemu_coroutine_switch(co, co->caller, COROUTINE_TERMINATE);
  107. }
  108. }
  109. /*
  110. * This is used as the signal handler. This is called with the brand new stack
  111. * (thanks to sigaltstack). We have to return, given that this is a signal
  112. * handler and the sigmask and some other things are changed.
  113. */
  114. static void coroutine_trampoline(int signal)
  115. {
  116. CoroutineUContext *self;
  117. Coroutine *co;
  118. CoroutineThreadState *coTS;
  119. /* Get the thread specific information */
  120. coTS = coroutine_get_thread_state();
  121. self = coTS->tr_handler;
  122. coTS->tr_called = 1;
  123. co = &self->base;
  124. /*
  125. * Here we have to do a bit of a ping pong between the caller, given that
  126. * this is a signal handler and we have to do a return "soon". Then the
  127. * caller can reestablish everything and do a longjmp here again.
  128. */
  129. if (!setjmp(coTS->tr_reenter)) {
  130. return;
  131. }
  132. /*
  133. * Ok, the caller has longjmp'ed back to us, so now prepare
  134. * us for the real machine state switching. We have to jump
  135. * into another function here to get a new stack context for
  136. * the auto variables (which have to be auto-variables
  137. * because the start of the thread happens later). Else with
  138. * PIC (i.e. Position Independent Code which is used when PTH
  139. * is built as a shared library) most platforms would
  140. * horrible core dump as experience showed.
  141. */
  142. coroutine_bootstrap(self, co);
  143. }
  144. static Coroutine *coroutine_new(void)
  145. {
  146. const size_t stack_size = 1 << 20;
  147. CoroutineUContext *co;
  148. CoroutineThreadState *coTS;
  149. struct sigaction sa;
  150. struct sigaction osa;
  151. stack_t ss;
  152. stack_t oss;
  153. sigset_t sigs;
  154. sigset_t osigs;
  155. jmp_buf old_env;
  156. /* The way to manipulate stack is with the sigaltstack function. We
  157. * prepare a stack, with it delivering a signal to ourselves and then
  158. * put setjmp/longjmp where needed.
  159. * This has been done keeping coroutine-ucontext as a model and with the
  160. * pth ideas (GNU Portable Threads). See coroutine-ucontext for the basics
  161. * of the coroutines and see pth_mctx.c (from the pth project) for the
  162. * sigaltstack way of manipulating stacks.
  163. */
  164. co = g_malloc0(sizeof(*co));
  165. co->stack = g_malloc(stack_size);
  166. co->base.entry_arg = &old_env; /* stash away our jmp_buf */
  167. coTS = coroutine_get_thread_state();
  168. coTS->tr_handler = co;
  169. /*
  170. * Preserve the SIGUSR2 signal state, block SIGUSR2,
  171. * and establish our signal handler. The signal will
  172. * later transfer control onto the signal stack.
  173. */
  174. sigemptyset(&sigs);
  175. sigaddset(&sigs, SIGUSR2);
  176. pthread_sigmask(SIG_BLOCK, &sigs, &osigs);
  177. sa.sa_handler = coroutine_trampoline;
  178. sigfillset(&sa.sa_mask);
  179. sa.sa_flags = SA_ONSTACK;
  180. if (sigaction(SIGUSR2, &sa, &osa) != 0) {
  181. abort();
  182. }
  183. /*
  184. * Set the new stack.
  185. */
  186. ss.ss_sp = co->stack;
  187. ss.ss_size = stack_size;
  188. ss.ss_flags = 0;
  189. if (sigaltstack(&ss, &oss) < 0) {
  190. abort();
  191. }
  192. /*
  193. * Now transfer control onto the signal stack and set it up.
  194. * It will return immediately via "return" after the setjmp()
  195. * was performed. Be careful here with race conditions. The
  196. * signal can be delivered the first time sigsuspend() is
  197. * called.
  198. */
  199. coTS->tr_called = 0;
  200. pthread_kill(pthread_self(), SIGUSR2);
  201. sigfillset(&sigs);
  202. sigdelset(&sigs, SIGUSR2);
  203. while (!coTS->tr_called) {
  204. sigsuspend(&sigs);
  205. }
  206. /*
  207. * Inform the system that we are back off the signal stack by
  208. * removing the alternative signal stack. Be careful here: It
  209. * first has to be disabled, before it can be removed.
  210. */
  211. sigaltstack(NULL, &ss);
  212. ss.ss_flags = SS_DISABLE;
  213. if (sigaltstack(&ss, NULL) < 0) {
  214. abort();
  215. }
  216. sigaltstack(NULL, &ss);
  217. if (!(oss.ss_flags & SS_DISABLE)) {
  218. sigaltstack(&oss, NULL);
  219. }
  220. /*
  221. * Restore the old SIGUSR2 signal handler and mask
  222. */
  223. sigaction(SIGUSR2, &osa, NULL);
  224. pthread_sigmask(SIG_SETMASK, &osigs, NULL);
  225. /*
  226. * Now enter the trampoline again, but this time not as a signal
  227. * handler. Instead we jump into it directly. The functionally
  228. * redundant ping-pong pointer arithmetic is necessary to avoid
  229. * type-conversion warnings related to the `volatile' qualifier and
  230. * the fact that `jmp_buf' usually is an array type.
  231. */
  232. if (!setjmp(old_env)) {
  233. longjmp(coTS->tr_reenter, 1);
  234. }
  235. /*
  236. * Ok, we returned again, so now we're finished
  237. */
  238. return &co->base;
  239. }
  240. Coroutine *qemu_coroutine_new(void)
  241. {
  242. Coroutine *co;
  243. co = QSLIST_FIRST(&pool);
  244. if (co) {
  245. QSLIST_REMOVE_HEAD(&pool, pool_next);
  246. pool_size--;
  247. } else {
  248. co = coroutine_new();
  249. }
  250. return co;
  251. }
  252. void qemu_coroutine_delete(Coroutine *co_)
  253. {
  254. CoroutineUContext *co = DO_UPCAST(CoroutineUContext, base, co_);
  255. if (pool_size < POOL_MAX_SIZE) {
  256. QSLIST_INSERT_HEAD(&pool, &co->base, pool_next);
  257. co->base.caller = NULL;
  258. pool_size++;
  259. return;
  260. }
  261. g_free(co->stack);
  262. g_free(co);
  263. }
  264. CoroutineAction qemu_coroutine_switch(Coroutine *from_, Coroutine *to_,
  265. CoroutineAction action)
  266. {
  267. CoroutineUContext *from = DO_UPCAST(CoroutineUContext, base, from_);
  268. CoroutineUContext *to = DO_UPCAST(CoroutineUContext, base, to_);
  269. CoroutineThreadState *s = coroutine_get_thread_state();
  270. int ret;
  271. s->current = to_;
  272. ret = setjmp(from->env);
  273. if (ret == 0) {
  274. longjmp(to->env, action);
  275. }
  276. return ret;
  277. }
  278. Coroutine *qemu_coroutine_self(void)
  279. {
  280. CoroutineThreadState *s = coroutine_get_thread_state();
  281. return s->current;
  282. }
  283. bool qemu_in_coroutine(void)
  284. {
  285. CoroutineThreadState *s = pthread_getspecific(thread_state_key);
  286. return s && s->current->caller;
  287. }