2 * Win32 implementation for mutex/cond/thread functions
4 * Copyright Red Hat, Inc. 2010
7 * Paolo Bonzini <pbonzini@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qemu/thread.h"
16 #include "qemu/notify.h"
17 #include "qemu-thread-common.h"
20 static bool name_threads
;
22 typedef HRESULT (WINAPI
*pSetThreadDescription
) (HANDLE hThread
,
23 PCWSTR lpThreadDescription
);
24 static pSetThreadDescription SetThreadDescriptionFunc
;
25 static HMODULE kernel32_module
;
27 static bool load_set_thread_description(void)
29 static gsize _init_once
= 0;
31 if (g_once_init_enter(&_init_once
)) {
32 kernel32_module
= LoadLibrary("kernel32.dll");
33 if (kernel32_module
) {
34 SetThreadDescriptionFunc
=
35 (pSetThreadDescription
)GetProcAddress(kernel32_module
,
36 "SetThreadDescription");
37 if (!SetThreadDescriptionFunc
) {
38 FreeLibrary(kernel32_module
);
41 g_once_init_leave(&_init_once
, 1);
44 return !!SetThreadDescriptionFunc
;
47 void qemu_thread_naming(bool enable
)
49 name_threads
= enable
;
51 if (enable
&& !load_set_thread_description()) {
52 fprintf(stderr
, "qemu: thread naming not supported on this host\n");
57 static void error_exit(int err
, const char *msg
)
61 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
,
62 NULL
, err
, 0, (LPTSTR
)&pstr
, 2, NULL
);
63 fprintf(stderr
, "qemu: %s: %s\n", msg
, pstr
);
68 void qemu_mutex_init(QemuMutex
*mutex
)
70 InitializeSRWLock(&mutex
->lock
);
71 qemu_mutex_post_init(mutex
);
74 void qemu_mutex_destroy(QemuMutex
*mutex
)
76 assert(mutex
->initialized
);
77 mutex
->initialized
= false;
78 InitializeSRWLock(&mutex
->lock
);
81 void qemu_mutex_lock_impl(QemuMutex
*mutex
, const char *file
, const int line
)
83 assert(mutex
->initialized
);
84 qemu_mutex_pre_lock(mutex
, file
, line
);
85 AcquireSRWLockExclusive(&mutex
->lock
);
86 qemu_mutex_post_lock(mutex
, file
, line
);
89 int qemu_mutex_trylock_impl(QemuMutex
*mutex
, const char *file
, const int line
)
93 assert(mutex
->initialized
);
94 owned
= TryAcquireSRWLockExclusive(&mutex
->lock
);
96 qemu_mutex_post_lock(mutex
, file
, line
);
102 void qemu_mutex_unlock_impl(QemuMutex
*mutex
, const char *file
, const int line
)
104 assert(mutex
->initialized
);
105 qemu_mutex_pre_unlock(mutex
, file
, line
);
106 ReleaseSRWLockExclusive(&mutex
->lock
);
109 void qemu_rec_mutex_init(QemuRecMutex
*mutex
)
111 InitializeCriticalSection(&mutex
->lock
);
112 mutex
->initialized
= true;
115 void qemu_rec_mutex_destroy(QemuRecMutex
*mutex
)
117 assert(mutex
->initialized
);
118 mutex
->initialized
= false;
119 DeleteCriticalSection(&mutex
->lock
);
122 void qemu_rec_mutex_lock_impl(QemuRecMutex
*mutex
, const char *file
, int line
)
124 assert(mutex
->initialized
);
125 EnterCriticalSection(&mutex
->lock
);
128 int qemu_rec_mutex_trylock_impl(QemuRecMutex
*mutex
, const char *file
, int line
)
130 assert(mutex
->initialized
);
131 return !TryEnterCriticalSection(&mutex
->lock
);
134 void qemu_rec_mutex_unlock_impl(QemuRecMutex
*mutex
, const char *file
, int line
)
136 assert(mutex
->initialized
);
137 LeaveCriticalSection(&mutex
->lock
);
140 void qemu_cond_init(QemuCond
*cond
)
142 memset(cond
, 0, sizeof(*cond
));
143 InitializeConditionVariable(&cond
->var
);
144 cond
->initialized
= true;
147 void qemu_cond_destroy(QemuCond
*cond
)
149 assert(cond
->initialized
);
150 cond
->initialized
= false;
151 InitializeConditionVariable(&cond
->var
);
154 void qemu_cond_signal(QemuCond
*cond
)
156 assert(cond
->initialized
);
157 WakeConditionVariable(&cond
->var
);
160 void qemu_cond_broadcast(QemuCond
*cond
)
162 assert(cond
->initialized
);
163 WakeAllConditionVariable(&cond
->var
);
166 void qemu_cond_wait_impl(QemuCond
*cond
, QemuMutex
*mutex
, const char *file
, const int line
)
168 assert(cond
->initialized
);
169 qemu_mutex_pre_unlock(mutex
, file
, line
);
170 SleepConditionVariableSRW(&cond
->var
, &mutex
->lock
, INFINITE
, 0);
171 qemu_mutex_post_lock(mutex
, file
, line
);
174 bool qemu_cond_timedwait_impl(QemuCond
*cond
, QemuMutex
*mutex
, int ms
,
175 const char *file
, const int line
)
179 assert(cond
->initialized
);
180 trace_qemu_mutex_unlock(mutex
, file
, line
);
181 if (!SleepConditionVariableSRW(&cond
->var
, &mutex
->lock
, ms
, 0)) {
184 trace_qemu_mutex_locked(mutex
, file
, line
);
185 if (rc
&& rc
!= ERROR_TIMEOUT
) {
186 error_exit(rc
, __func__
);
188 return rc
!= ERROR_TIMEOUT
;
191 void qemu_sem_init(QemuSemaphore
*sem
, int init
)
194 sem
->sema
= CreateSemaphore(NULL
, init
, LONG_MAX
, NULL
);
195 sem
->initialized
= true;
198 void qemu_sem_destroy(QemuSemaphore
*sem
)
200 assert(sem
->initialized
);
201 sem
->initialized
= false;
202 CloseHandle(sem
->sema
);
205 void qemu_sem_post(QemuSemaphore
*sem
)
207 assert(sem
->initialized
);
208 ReleaseSemaphore(sem
->sema
, 1, NULL
);
211 int qemu_sem_timedwait(QemuSemaphore
*sem
, int ms
)
215 assert(sem
->initialized
);
216 rc
= WaitForSingleObject(sem
->sema
, ms
);
217 if (rc
== WAIT_OBJECT_0
) {
220 if (rc
!= WAIT_TIMEOUT
) {
221 error_exit(GetLastError(), __func__
);
226 void qemu_sem_wait(QemuSemaphore
*sem
)
228 assert(sem
->initialized
);
229 if (WaitForSingleObject(sem
->sema
, INFINITE
) != WAIT_OBJECT_0
) {
230 error_exit(GetLastError(), __func__
);
234 /* Wrap a Win32 manual-reset event with a fast userspace path. The idea
235 * is to reset the Win32 event lazily, as part of a test-reset-test-wait
236 * sequence. Such a sequence is, indeed, how QemuEvents are used by
237 * RCU and other subsystems!
240 * - free->set, when setting the event
241 * - busy->set, when setting the event, followed by SetEvent
242 * - set->free, when resetting the event
243 * - free->busy, when waiting
245 * set->busy does not happen (it can be observed from the outside but
246 * it really is set->free->busy).
248 * busy->free provably cannot happen; to enforce it, the set->free transition
249 * is done with an OR, which becomes a no-op if the event has concurrently
250 * transitioned to free or busy (and is faster than cmpxchg).
257 void qemu_event_init(QemuEvent
*ev
, bool init
)
260 ev
->event
= CreateEvent(NULL
, TRUE
, TRUE
, NULL
);
261 ev
->value
= (init
? EV_SET
: EV_FREE
);
262 ev
->initialized
= true;
265 void qemu_event_destroy(QemuEvent
*ev
)
267 assert(ev
->initialized
);
268 ev
->initialized
= false;
269 CloseHandle(ev
->event
);
272 void qemu_event_set(QemuEvent
*ev
)
274 assert(ev
->initialized
);
277 * Pairs with both qemu_event_reset() and qemu_event_wait().
279 * qemu_event_set has release semantics, but because it *loads*
280 * ev->value we need a full memory barrier here.
283 if (qatomic_read(&ev
->value
) != EV_SET
) {
284 int old
= qatomic_xchg(&ev
->value
, EV_SET
);
286 /* Pairs with memory barrier after ResetEvent. */
288 if (old
== EV_BUSY
) {
289 /* There were waiters, wake them up. */
295 void qemu_event_reset(QemuEvent
*ev
)
297 assert(ev
->initialized
);
300 * If there was a concurrent reset (or even reset+wait),
301 * do nothing. Otherwise change EV_SET->EV_FREE.
303 qatomic_or(&ev
->value
, EV_FREE
);
306 * Order reset before checking the condition in the caller.
307 * Pairs with the first memory barrier in qemu_event_set().
312 void qemu_event_wait(QemuEvent
*ev
)
316 assert(ev
->initialized
);
319 * qemu_event_wait must synchronize with qemu_event_set even if it does
320 * not go down the slow path, so this load-acquire is needed that
321 * synchronizes with the first memory barrier in qemu_event_set().
323 * If we do go down the slow path, there is no requirement at all: we
324 * might miss a qemu_event_set() here but ultimately the memory barrier in
325 * qemu_futex_wait() will ensure the check is done correctly.
327 value
= qatomic_load_acquire(&ev
->value
);
328 if (value
!= EV_SET
) {
329 if (value
== EV_FREE
) {
331 * Here the underlying kernel event is reset, but qemu_event_set is
332 * not yet going to call SetEvent. However, there will be another
333 * check for EV_SET below when setting EV_BUSY. At that point it
334 * is safe to call WaitForSingleObject.
336 ResetEvent(ev
->event
);
339 * It is not clear whether ResetEvent provides this barrier; kernel
340 * APIs (KeResetEvent/KeClearEvent) do not. Better safe than sorry!
345 * Leave the event reset and tell qemu_event_set that there are
346 * waiters. No need to retry, because there cannot be a concurrent
347 * busy->free transition. After the CAS, the event will be either
350 if (qatomic_cmpxchg(&ev
->value
, EV_FREE
, EV_BUSY
) == EV_SET
) {
356 * ev->value is now EV_BUSY. Since we didn't observe EV_SET,
357 * qemu_event_set() must observe EV_BUSY and call SetEvent().
359 WaitForSingleObject(ev
->event
, INFINITE
);
363 struct QemuThreadData
{
364 /* Passed to win32_start_routine. */
365 void *(*start_routine
)(void *);
370 /* Only used for joinable threads. */
376 static bool atexit_registered
;
377 static NotifierList main_thread_exit
;
379 static __thread QemuThreadData
*qemu_thread_data
;
381 static void run_main_thread_exit(void)
383 notifier_list_notify(&main_thread_exit
, NULL
);
386 void qemu_thread_atexit_add(Notifier
*notifier
)
388 if (!qemu_thread_data
) {
389 if (!atexit_registered
) {
390 atexit_registered
= true;
391 atexit(run_main_thread_exit
);
393 notifier_list_add(&main_thread_exit
, notifier
);
395 notifier_list_add(&qemu_thread_data
->exit
, notifier
);
399 void qemu_thread_atexit_remove(Notifier
*notifier
)
401 notifier_remove(notifier
);
404 static unsigned __stdcall
win32_start_routine(void *arg
)
406 QemuThreadData
*data
= (QemuThreadData
*) arg
;
407 void *(*start_routine
)(void *) = data
->start_routine
;
408 void *thread_arg
= data
->arg
;
410 qemu_thread_data
= data
;
411 qemu_thread_exit(start_routine(thread_arg
));
415 void qemu_thread_exit(void *arg
)
417 QemuThreadData
*data
= qemu_thread_data
;
419 notifier_list_notify(&data
->exit
, NULL
);
420 if (data
->mode
== QEMU_THREAD_JOINABLE
) {
422 EnterCriticalSection(&data
->cs
);
424 LeaveCriticalSection(&data
->cs
);
431 void *qemu_thread_join(QemuThread
*thread
)
433 QemuThreadData
*data
;
438 if (data
->mode
== QEMU_THREAD_DETACHED
) {
443 * Because multiple copies of the QemuThread can exist via
444 * qemu_thread_get_self, we need to store a value that cannot
445 * leak there. The simplest, non racy way is to store the TID,
446 * discard the handle that _beginthreadex gives back, and
447 * get another copy of the handle here.
449 handle
= qemu_thread_get_handle(thread
);
451 WaitForSingleObject(handle
, INFINITE
);
455 DeleteCriticalSection(&data
->cs
);
460 static bool set_thread_description(HANDLE h
, const char *name
)
463 g_autofree
wchar_t *namew
= NULL
;
465 if (!load_set_thread_description()) {
469 namew
= g_utf8_to_utf16(name
, -1, NULL
, NULL
, NULL
);
474 hr
= SetThreadDescriptionFunc(h
, namew
);
476 return SUCCEEDED(hr
);
479 void qemu_thread_create(QemuThread
*thread
, const char *name
,
480 void *(*start_routine
)(void *),
484 struct QemuThreadData
*data
;
486 data
= g_malloc(sizeof *data
);
487 data
->start_routine
= start_routine
;
490 data
->exited
= false;
491 notifier_list_init(&data
->exit
);
493 if (data
->mode
!= QEMU_THREAD_DETACHED
) {
494 InitializeCriticalSection(&data
->cs
);
497 hThread
= (HANDLE
) _beginthreadex(NULL
, 0, win32_start_routine
,
498 data
, 0, &thread
->tid
);
500 error_exit(GetLastError(), __func__
);
502 if (name_threads
&& name
&& !set_thread_description(hThread
, name
)) {
503 fprintf(stderr
, "qemu: failed to set thread description: %s\n", name
);
505 CloseHandle(hThread
);
510 int qemu_thread_set_affinity(QemuThread
*thread
, unsigned long *host_cpus
,
516 int qemu_thread_get_affinity(QemuThread
*thread
, unsigned long **host_cpus
,
517 unsigned long *nbits
)
522 void qemu_thread_get_self(QemuThread
*thread
)
524 thread
->data
= qemu_thread_data
;
525 thread
->tid
= GetCurrentThreadId();
528 HANDLE
qemu_thread_get_handle(QemuThread
*thread
)
530 QemuThreadData
*data
;
534 if (data
->mode
== QEMU_THREAD_DETACHED
) {
538 EnterCriticalSection(&data
->cs
);
540 handle
= OpenThread(SYNCHRONIZE
| THREAD_SUSPEND_RESUME
|
541 THREAD_SET_CONTEXT
, FALSE
, thread
->tid
);
545 LeaveCriticalSection(&data
->cs
);
549 bool qemu_thread_is_self(QemuThread
*thread
)
551 return GetCurrentThreadId() == thread
->tid
;