thread-pool.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * QEMU block layer thread pool
  3. *
  4. * Copyright IBM, Corp. 2008
  5. * Copyright Red Hat, Inc. 2012
  6. *
  7. * Authors:
  8. * Anthony Liguori <aliguori@us.ibm.com>
  9. * Paolo Bonzini <pbonzini@redhat.com>
  10. *
  11. * This work is licensed under the terms of the GNU GPL, version 2. See
  12. * the COPYING file in the top-level directory.
  13. *
  14. * Contributions after 2012-01-13 are licensed under the terms of the
  15. * GNU GPL, version 2 or (at your option) any later version.
  16. */
  17. #include "qemu/osdep.h"
  18. #include "qemu/defer-call.h"
  19. #include "qemu/queue.h"
  20. #include "qemu/thread.h"
  21. #include "qemu/coroutine.h"
  22. #include "trace.h"
  23. #include "block/thread-pool.h"
  24. #include "qemu/main-loop.h"
  25. static void do_spawn_thread(ThreadPool *pool);
  26. typedef struct ThreadPoolElement ThreadPoolElement;
  27. enum ThreadState {
  28. THREAD_QUEUED,
  29. THREAD_ACTIVE,
  30. THREAD_DONE,
  31. };
  32. struct ThreadPoolElement {
  33. BlockAIOCB common;
  34. ThreadPool *pool;
  35. ThreadPoolFunc *func;
  36. void *arg;
  37. /* Moving state out of THREAD_QUEUED is protected by lock. After
  38. * that, only the worker thread can write to it. Reads and writes
  39. * of state and ret are ordered with memory barriers.
  40. */
  41. enum ThreadState state;
  42. int ret;
  43. /* Access to this list is protected by lock. */
  44. QTAILQ_ENTRY(ThreadPoolElement) reqs;
  45. /* This list is only written by the thread pool's mother thread. */
  46. QLIST_ENTRY(ThreadPoolElement) all;
  47. };
  48. struct ThreadPool {
  49. AioContext *ctx;
  50. QEMUBH *completion_bh;
  51. QemuMutex lock;
  52. QemuCond worker_stopped;
  53. QemuCond request_cond;
  54. QEMUBH *new_thread_bh;
  55. /* The following variables are only accessed from one AioContext. */
  56. QLIST_HEAD(, ThreadPoolElement) head;
  57. /* The following variables are protected by lock. */
  58. QTAILQ_HEAD(, ThreadPoolElement) request_list;
  59. int cur_threads;
  60. int idle_threads;
  61. int new_threads; /* backlog of threads we need to create */
  62. int pending_threads; /* threads created but not running yet */
  63. int min_threads;
  64. int max_threads;
  65. };
  66. static void *worker_thread(void *opaque)
  67. {
  68. ThreadPool *pool = opaque;
  69. qemu_mutex_lock(&pool->lock);
  70. pool->pending_threads--;
  71. do_spawn_thread(pool);
  72. while (pool->cur_threads <= pool->max_threads) {
  73. ThreadPoolElement *req;
  74. int ret;
  75. if (QTAILQ_EMPTY(&pool->request_list)) {
  76. pool->idle_threads++;
  77. ret = qemu_cond_timedwait(&pool->request_cond, &pool->lock, 10000);
  78. pool->idle_threads--;
  79. if (ret == 0 &&
  80. QTAILQ_EMPTY(&pool->request_list) &&
  81. pool->cur_threads > pool->min_threads) {
  82. /* Timed out + no work to do + no need for warm threads = exit. */
  83. break;
  84. }
  85. /*
  86. * Even if there was some work to do, check if there aren't
  87. * too many worker threads before picking it up.
  88. */
  89. continue;
  90. }
  91. req = QTAILQ_FIRST(&pool->request_list);
  92. QTAILQ_REMOVE(&pool->request_list, req, reqs);
  93. req->state = THREAD_ACTIVE;
  94. qemu_mutex_unlock(&pool->lock);
  95. ret = req->func(req->arg);
  96. req->ret = ret;
  97. /* Write ret before state. */
  98. smp_wmb();
  99. req->state = THREAD_DONE;
  100. qemu_bh_schedule(pool->completion_bh);
  101. qemu_mutex_lock(&pool->lock);
  102. }
  103. pool->cur_threads--;
  104. qemu_cond_signal(&pool->worker_stopped);
  105. /*
  106. * Wake up another thread, in case we got a wakeup but decided
  107. * to exit due to pool->cur_threads > pool->max_threads.
  108. */
  109. qemu_cond_signal(&pool->request_cond);
  110. qemu_mutex_unlock(&pool->lock);
  111. return NULL;
  112. }
  113. static void do_spawn_thread(ThreadPool *pool)
  114. {
  115. QemuThread t;
  116. /* Runs with lock taken. */
  117. if (!pool->new_threads) {
  118. return;
  119. }
  120. pool->new_threads--;
  121. pool->pending_threads++;
  122. qemu_thread_create(&t, "worker", worker_thread, pool, QEMU_THREAD_DETACHED);
  123. }
  124. static void spawn_thread_bh_fn(void *opaque)
  125. {
  126. ThreadPool *pool = opaque;
  127. qemu_mutex_lock(&pool->lock);
  128. do_spawn_thread(pool);
  129. qemu_mutex_unlock(&pool->lock);
  130. }
  131. static void spawn_thread(ThreadPool *pool)
  132. {
  133. pool->cur_threads++;
  134. pool->new_threads++;
  135. /* If there are threads being created, they will spawn new workers, so
  136. * we don't spend time creating many threads in a loop holding a mutex or
  137. * starving the current vcpu.
  138. *
  139. * If there are no idle threads, ask the main thread to create one, so we
  140. * inherit the correct affinity instead of the vcpu affinity.
  141. */
  142. if (!pool->pending_threads) {
  143. qemu_bh_schedule(pool->new_thread_bh);
  144. }
  145. }
  146. static void thread_pool_completion_bh(void *opaque)
  147. {
  148. ThreadPool *pool = opaque;
  149. ThreadPoolElement *elem, *next;
  150. defer_call_begin(); /* cb() may use defer_call() to coalesce work */
  151. restart:
  152. QLIST_FOREACH_SAFE(elem, &pool->head, all, next) {
  153. if (elem->state != THREAD_DONE) {
  154. continue;
  155. }
  156. trace_thread_pool_complete(pool, elem, elem->common.opaque,
  157. elem->ret);
  158. QLIST_REMOVE(elem, all);
  159. if (elem->common.cb) {
  160. /* Read state before ret. */
  161. smp_rmb();
  162. /* Schedule ourselves in case elem->common.cb() calls aio_poll() to
  163. * wait for another request that completed at the same time.
  164. */
  165. qemu_bh_schedule(pool->completion_bh);
  166. elem->common.cb(elem->common.opaque, elem->ret);
  167. /* We can safely cancel the completion_bh here regardless of someone
  168. * else having scheduled it meanwhile because we reenter the
  169. * completion function anyway (goto restart).
  170. */
  171. qemu_bh_cancel(pool->completion_bh);
  172. qemu_aio_unref(elem);
  173. goto restart;
  174. } else {
  175. qemu_aio_unref(elem);
  176. }
  177. }
  178. defer_call_end();
  179. }
  180. static void thread_pool_cancel(BlockAIOCB *acb)
  181. {
  182. ThreadPoolElement *elem = (ThreadPoolElement *)acb;
  183. ThreadPool *pool = elem->pool;
  184. trace_thread_pool_cancel(elem, elem->common.opaque);
  185. QEMU_LOCK_GUARD(&pool->lock);
  186. if (elem->state == THREAD_QUEUED) {
  187. QTAILQ_REMOVE(&pool->request_list, elem, reqs);
  188. qemu_bh_schedule(pool->completion_bh);
  189. elem->state = THREAD_DONE;
  190. elem->ret = -ECANCELED;
  191. }
  192. }
  193. static const AIOCBInfo thread_pool_aiocb_info = {
  194. .aiocb_size = sizeof(ThreadPoolElement),
  195. .cancel_async = thread_pool_cancel,
  196. };
  197. BlockAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,
  198. BlockCompletionFunc *cb, void *opaque)
  199. {
  200. ThreadPoolElement *req;
  201. AioContext *ctx = qemu_get_current_aio_context();
  202. ThreadPool *pool = aio_get_thread_pool(ctx);
  203. /* Assert that the thread submitting work is the same running the pool */
  204. assert(pool->ctx == qemu_get_current_aio_context());
  205. req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
  206. req->func = func;
  207. req->arg = arg;
  208. req->state = THREAD_QUEUED;
  209. req->pool = pool;
  210. QLIST_INSERT_HEAD(&pool->head, req, all);
  211. trace_thread_pool_submit(pool, req, arg);
  212. qemu_mutex_lock(&pool->lock);
  213. if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
  214. spawn_thread(pool);
  215. }
  216. QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
  217. qemu_mutex_unlock(&pool->lock);
  218. qemu_cond_signal(&pool->request_cond);
  219. return &req->common;
  220. }
  221. typedef struct ThreadPoolCo {
  222. Coroutine *co;
  223. int ret;
  224. } ThreadPoolCo;
  225. static void thread_pool_co_cb(void *opaque, int ret)
  226. {
  227. ThreadPoolCo *co = opaque;
  228. co->ret = ret;
  229. aio_co_wake(co->co);
  230. }
  231. int coroutine_fn thread_pool_submit_co(ThreadPoolFunc *func, void *arg)
  232. {
  233. ThreadPoolCo tpc = { .co = qemu_coroutine_self(), .ret = -EINPROGRESS };
  234. assert(qemu_in_coroutine());
  235. thread_pool_submit_aio(func, arg, thread_pool_co_cb, &tpc);
  236. qemu_coroutine_yield();
  237. return tpc.ret;
  238. }
  239. void thread_pool_submit(ThreadPoolFunc *func, void *arg)
  240. {
  241. thread_pool_submit_aio(func, arg, NULL, NULL);
  242. }
  243. void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
  244. {
  245. qemu_mutex_lock(&pool->lock);
  246. pool->min_threads = ctx->thread_pool_min;
  247. pool->max_threads = ctx->thread_pool_max;
  248. /*
  249. * We either have to:
  250. * - Increase the number available of threads until over the min_threads
  251. * threshold.
  252. * - Bump the worker threads so that they exit, until under the max_threads
  253. * threshold.
  254. * - Do nothing. The current number of threads fall in between the min and
  255. * max thresholds. We'll let the pool manage itself.
  256. */
  257. for (int i = pool->cur_threads; i < pool->min_threads; i++) {
  258. spawn_thread(pool);
  259. }
  260. for (int i = pool->cur_threads; i > pool->max_threads; i--) {
  261. qemu_cond_signal(&pool->request_cond);
  262. }
  263. qemu_mutex_unlock(&pool->lock);
  264. }
  265. static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
  266. {
  267. if (!ctx) {
  268. ctx = qemu_get_aio_context();
  269. }
  270. memset(pool, 0, sizeof(*pool));
  271. pool->ctx = ctx;
  272. pool->completion_bh = aio_bh_new(ctx, thread_pool_completion_bh, pool);
  273. qemu_mutex_init(&pool->lock);
  274. qemu_cond_init(&pool->worker_stopped);
  275. qemu_cond_init(&pool->request_cond);
  276. pool->new_thread_bh = aio_bh_new(ctx, spawn_thread_bh_fn, pool);
  277. QLIST_INIT(&pool->head);
  278. QTAILQ_INIT(&pool->request_list);
  279. thread_pool_update_params(pool, ctx);
  280. }
  281. ThreadPool *thread_pool_new(AioContext *ctx)
  282. {
  283. ThreadPool *pool = g_new(ThreadPool, 1);
  284. thread_pool_init_one(pool, ctx);
  285. return pool;
  286. }
  287. void thread_pool_free(ThreadPool *pool)
  288. {
  289. if (!pool) {
  290. return;
  291. }
  292. assert(QLIST_EMPTY(&pool->head));
  293. qemu_mutex_lock(&pool->lock);
  294. /* Stop new threads from spawning */
  295. qemu_bh_delete(pool->new_thread_bh);
  296. pool->cur_threads -= pool->new_threads;
  297. pool->new_threads = 0;
  298. /* Wait for worker threads to terminate */
  299. pool->max_threads = 0;
  300. qemu_cond_broadcast(&pool->request_cond);
  301. while (pool->cur_threads > 0) {
  302. qemu_cond_wait(&pool->worker_stopped, &pool->lock);
  303. }
  304. qemu_mutex_unlock(&pool->lock);
  305. qemu_bh_delete(pool->completion_bh);
  306. qemu_cond_destroy(&pool->request_cond);
  307. qemu_cond_destroy(&pool->worker_stopped);
  308. qemu_mutex_destroy(&pool->lock);
  309. g_free(pool);
  310. }