thread-pool: replace semaphore with condition variable
[qemu/ar7.git] / util / thread-pool.c
blob6e3d4e4a2f4c74f27baaf18a259642f79e5c108b
1 /*
2 * QEMU block layer thread pool
4 * Copyright IBM, Corp. 2008
5 * Copyright Red Hat, Inc. 2012
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Paolo Bonzini <pbonzini@redhat.com>
11 * This work is licensed under the terms of the GNU GPL, version 2. See
12 * the COPYING file in the top-level directory.
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.
17 #include "qemu/osdep.h"
18 #include "qemu/queue.h"
19 #include "qemu/thread.h"
20 #include "qemu/coroutine.h"
21 #include "trace.h"
22 #include "block/thread-pool.h"
23 #include "qemu/main-loop.h"
25 static void do_spawn_thread(ThreadPool *pool);
27 typedef struct ThreadPoolElement ThreadPoolElement;
29 enum ThreadState {
30 THREAD_QUEUED,
31 THREAD_ACTIVE,
32 THREAD_DONE,
35 struct ThreadPoolElement {
36 BlockAIOCB common;
37 ThreadPool *pool;
38 ThreadPoolFunc *func;
39 void *arg;
41 /* Moving state out of THREAD_QUEUED is protected by lock. After
42 * that, only the worker thread can write to it. Reads and writes
43 * of state and ret are ordered with memory barriers.
45 enum ThreadState state;
46 int ret;
48 /* Access to this list is protected by lock. */
49 QTAILQ_ENTRY(ThreadPoolElement) reqs;
51 /* Access to this list is protected by the global mutex. */
52 QLIST_ENTRY(ThreadPoolElement) all;
55 struct ThreadPool {
56 AioContext *ctx;
57 QEMUBH *completion_bh;
58 QemuMutex lock;
59 QemuCond worker_stopped;
60 QemuCond request_cond;
61 QEMUBH *new_thread_bh;
63 /* The following variables are only accessed from one AioContext. */
64 QLIST_HEAD(, ThreadPoolElement) head;
66 /* The following variables are protected by lock. */
67 QTAILQ_HEAD(, ThreadPoolElement) request_list;
68 int cur_threads;
69 int idle_threads;
70 int new_threads; /* backlog of threads we need to create */
71 int pending_threads; /* threads created but not running yet */
72 bool stopping;
73 int min_threads;
74 int max_threads;
77 static void *worker_thread(void *opaque)
79 ThreadPool *pool = opaque;
81 qemu_mutex_lock(&pool->lock);
82 pool->pending_threads--;
83 do_spawn_thread(pool);
85 while (!pool->stopping && pool->cur_threads <= pool->max_threads) {
86 ThreadPoolElement *req;
87 int ret;
89 if (QTAILQ_EMPTY(&pool->request_list)) {
90 pool->idle_threads++;
91 ret = qemu_cond_timedwait(&pool->request_cond, &pool->lock, 10000);
92 pool->idle_threads--;
93 if (ret == 0 &&
94 QTAILQ_EMPTY(&pool->request_list) &&
95 pool->cur_threads > pool->min_threads) {
96 /* Timed out + no work to do + no need for warm threads = exit. */
97 break;
100 * Even if there was some work to do, check if there aren't
101 * too many worker threads before picking it up.
103 continue;
106 req = QTAILQ_FIRST(&pool->request_list);
107 QTAILQ_REMOVE(&pool->request_list, req, reqs);
108 req->state = THREAD_ACTIVE;
109 qemu_mutex_unlock(&pool->lock);
111 ret = req->func(req->arg);
113 req->ret = ret;
114 /* Write ret before state. */
115 smp_wmb();
116 req->state = THREAD_DONE;
118 qemu_bh_schedule(pool->completion_bh);
119 qemu_mutex_lock(&pool->lock);
122 pool->cur_threads--;
123 qemu_cond_signal(&pool->worker_stopped);
124 qemu_mutex_unlock(&pool->lock);
127 * Wake up another thread, in case we got a wakeup but decided
128 * to exit due to pool->cur_threads > pool->max_threads.
130 qemu_cond_signal(&pool->request_cond);
131 return NULL;
134 static void do_spawn_thread(ThreadPool *pool)
136 QemuThread t;
138 /* Runs with lock taken. */
139 if (!pool->new_threads) {
140 return;
143 pool->new_threads--;
144 pool->pending_threads++;
146 qemu_thread_create(&t, "worker", worker_thread, pool, QEMU_THREAD_DETACHED);
149 static void spawn_thread_bh_fn(void *opaque)
151 ThreadPool *pool = opaque;
153 qemu_mutex_lock(&pool->lock);
154 do_spawn_thread(pool);
155 qemu_mutex_unlock(&pool->lock);
158 static void spawn_thread(ThreadPool *pool)
160 pool->cur_threads++;
161 pool->new_threads++;
162 /* If there are threads being created, they will spawn new workers, so
163 * we don't spend time creating many threads in a loop holding a mutex or
164 * starving the current vcpu.
166 * If there are no idle threads, ask the main thread to create one, so we
167 * inherit the correct affinity instead of the vcpu affinity.
169 if (!pool->pending_threads) {
170 qemu_bh_schedule(pool->new_thread_bh);
174 static void thread_pool_completion_bh(void *opaque)
176 ThreadPool *pool = opaque;
177 ThreadPoolElement *elem, *next;
179 aio_context_acquire(pool->ctx);
180 restart:
181 QLIST_FOREACH_SAFE(elem, &pool->head, all, next) {
182 if (elem->state != THREAD_DONE) {
183 continue;
186 trace_thread_pool_complete(pool, elem, elem->common.opaque,
187 elem->ret);
188 QLIST_REMOVE(elem, all);
190 if (elem->common.cb) {
191 /* Read state before ret. */
192 smp_rmb();
194 /* Schedule ourselves in case elem->common.cb() calls aio_poll() to
195 * wait for another request that completed at the same time.
197 qemu_bh_schedule(pool->completion_bh);
199 aio_context_release(pool->ctx);
200 elem->common.cb(elem->common.opaque, elem->ret);
201 aio_context_acquire(pool->ctx);
203 /* We can safely cancel the completion_bh here regardless of someone
204 * else having scheduled it meanwhile because we reenter the
205 * completion function anyway (goto restart).
207 qemu_bh_cancel(pool->completion_bh);
209 qemu_aio_unref(elem);
210 goto restart;
211 } else {
212 qemu_aio_unref(elem);
215 aio_context_release(pool->ctx);
218 static void thread_pool_cancel(BlockAIOCB *acb)
220 ThreadPoolElement *elem = (ThreadPoolElement *)acb;
221 ThreadPool *pool = elem->pool;
223 trace_thread_pool_cancel(elem, elem->common.opaque);
225 QEMU_LOCK_GUARD(&pool->lock);
226 if (elem->state == THREAD_QUEUED) {
227 QTAILQ_REMOVE(&pool->request_list, elem, reqs);
228 qemu_bh_schedule(pool->completion_bh);
230 elem->state = THREAD_DONE;
231 elem->ret = -ECANCELED;
236 static AioContext *thread_pool_get_aio_context(BlockAIOCB *acb)
238 ThreadPoolElement *elem = (ThreadPoolElement *)acb;
239 ThreadPool *pool = elem->pool;
240 return pool->ctx;
243 static const AIOCBInfo thread_pool_aiocb_info = {
244 .aiocb_size = sizeof(ThreadPoolElement),
245 .cancel_async = thread_pool_cancel,
246 .get_aio_context = thread_pool_get_aio_context,
249 BlockAIOCB *thread_pool_submit_aio(ThreadPool *pool,
250 ThreadPoolFunc *func, void *arg,
251 BlockCompletionFunc *cb, void *opaque)
253 ThreadPoolElement *req;
255 req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);
256 req->func = func;
257 req->arg = arg;
258 req->state = THREAD_QUEUED;
259 req->pool = pool;
261 QLIST_INSERT_HEAD(&pool->head, req, all);
263 trace_thread_pool_submit(pool, req, arg);
265 qemu_mutex_lock(&pool->lock);
266 if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {
267 spawn_thread(pool);
269 QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);
270 qemu_mutex_unlock(&pool->lock);
271 qemu_cond_signal(&pool->request_cond);
272 return &req->common;
275 typedef struct ThreadPoolCo {
276 Coroutine *co;
277 int ret;
278 } ThreadPoolCo;
280 static void thread_pool_co_cb(void *opaque, int ret)
282 ThreadPoolCo *co = opaque;
284 co->ret = ret;
285 aio_co_wake(co->co);
288 int coroutine_fn thread_pool_submit_co(ThreadPool *pool, ThreadPoolFunc *func,
289 void *arg)
291 ThreadPoolCo tpc = { .co = qemu_coroutine_self(), .ret = -EINPROGRESS };
292 assert(qemu_in_coroutine());
293 thread_pool_submit_aio(pool, func, arg, thread_pool_co_cb, &tpc);
294 qemu_coroutine_yield();
295 return tpc.ret;
298 void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)
300 thread_pool_submit_aio(pool, func, arg, NULL, NULL);
303 void thread_pool_update_params(ThreadPool *pool, AioContext *ctx)
305 qemu_mutex_lock(&pool->lock);
307 pool->min_threads = ctx->thread_pool_min;
308 pool->max_threads = ctx->thread_pool_max;
311 * We either have to:
312 * - Increase the number available of threads until over the min_threads
313 * threshold.
314 * - Bump the worker threads so that they exit, until under the max_threads
315 * threshold.
316 * - Do nothing. The current number of threads fall in between the min and
317 * max thresholds. We'll let the pool manage itself.
319 for (int i = pool->cur_threads; i < pool->min_threads; i++) {
320 spawn_thread(pool);
323 for (int i = pool->cur_threads; i > pool->max_threads; i--) {
324 qemu_cond_signal(&pool->request_cond);
327 qemu_mutex_unlock(&pool->lock);
330 static void thread_pool_init_one(ThreadPool *pool, AioContext *ctx)
332 if (!ctx) {
333 ctx = qemu_get_aio_context();
336 memset(pool, 0, sizeof(*pool));
337 pool->ctx = ctx;
338 pool->completion_bh = aio_bh_new(ctx, thread_pool_completion_bh, pool);
339 qemu_mutex_init(&pool->lock);
340 qemu_cond_init(&pool->worker_stopped);
341 qemu_cond_init(&pool->request_cond);
342 pool->new_thread_bh = aio_bh_new(ctx, spawn_thread_bh_fn, pool);
344 QLIST_INIT(&pool->head);
345 QTAILQ_INIT(&pool->request_list);
347 thread_pool_update_params(pool, ctx);
350 ThreadPool *thread_pool_new(AioContext *ctx)
352 ThreadPool *pool = g_new(ThreadPool, 1);
353 thread_pool_init_one(pool, ctx);
354 return pool;
357 void thread_pool_free(ThreadPool *pool)
359 if (!pool) {
360 return;
363 assert(QLIST_EMPTY(&pool->head));
365 qemu_mutex_lock(&pool->lock);
367 /* Stop new threads from spawning */
368 qemu_bh_delete(pool->new_thread_bh);
369 pool->cur_threads -= pool->new_threads;
370 pool->new_threads = 0;
372 /* Wait for worker threads to terminate */
373 pool->stopping = true;
374 qemu_cond_broadcast(&pool->request_cond);
375 while (pool->cur_threads > 0) {
376 qemu_cond_wait(&pool->worker_stopped, &pool->lock);
379 qemu_mutex_unlock(&pool->lock);
381 qemu_bh_delete(pool->completion_bh);
382 qemu_cond_destroy(&pool->request_cond);
383 qemu_cond_destroy(&pool->worker_stopped);
384 qemu_mutex_destroy(&pool->lock);
385 g_free(pool);