qemu-thread-win32.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. * Win32 implementation for mutex/cond/thread functions
  3. *
  4. * Copyright Red Hat, Inc. 2010
  5. *
  6. * Author:
  7. * Paolo Bonzini <pbonzini@redhat.com>
  8. *
  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.
  11. *
  12. */
  13. #include "qemu/osdep.h"
  14. #include "qemu/thread.h"
  15. #include "qemu/notify.h"
  16. #include "qemu-thread-common.h"
  17. #include <process.h>
  18. static bool name_threads;
  19. typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
  20. PCWSTR lpThreadDescription);
  21. static pSetThreadDescription SetThreadDescriptionFunc;
  22. static HMODULE kernel32_module;
  23. static bool load_set_thread_description(void)
  24. {
  25. static gsize _init_once = 0;
  26. if (g_once_init_enter(&_init_once)) {
  27. kernel32_module = LoadLibrary("kernel32.dll");
  28. if (kernel32_module) {
  29. SetThreadDescriptionFunc =
  30. (pSetThreadDescription)GetProcAddress(kernel32_module,
  31. "SetThreadDescription");
  32. if (!SetThreadDescriptionFunc) {
  33. FreeLibrary(kernel32_module);
  34. }
  35. }
  36. g_once_init_leave(&_init_once, 1);
  37. }
  38. return !!SetThreadDescriptionFunc;
  39. }
  40. void qemu_thread_naming(bool enable)
  41. {
  42. name_threads = enable;
  43. if (enable && !load_set_thread_description()) {
  44. fprintf(stderr, "qemu: thread naming not supported on this host\n");
  45. name_threads = false;
  46. }
  47. }
  48. static void error_exit(int err, const char *msg)
  49. {
  50. char *pstr;
  51. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
  52. NULL, err, 0, (LPTSTR)&pstr, 2, NULL);
  53. fprintf(stderr, "qemu: %s: %s\n", msg, pstr);
  54. LocalFree(pstr);
  55. abort();
  56. }
  57. void qemu_mutex_init(QemuMutex *mutex)
  58. {
  59. InitializeSRWLock(&mutex->lock);
  60. qemu_mutex_post_init(mutex);
  61. }
  62. void qemu_mutex_destroy(QemuMutex *mutex)
  63. {
  64. assert(mutex->initialized);
  65. mutex->initialized = false;
  66. InitializeSRWLock(&mutex->lock);
  67. }
  68. void qemu_mutex_lock_impl(QemuMutex *mutex, const char *file, const int line)
  69. {
  70. assert(mutex->initialized);
  71. qemu_mutex_pre_lock(mutex, file, line);
  72. AcquireSRWLockExclusive(&mutex->lock);
  73. qemu_mutex_post_lock(mutex, file, line);
  74. }
  75. int qemu_mutex_trylock_impl(QemuMutex *mutex, const char *file, const int line)
  76. {
  77. int owned;
  78. assert(mutex->initialized);
  79. owned = TryAcquireSRWLockExclusive(&mutex->lock);
  80. if (owned) {
  81. qemu_mutex_post_lock(mutex, file, line);
  82. return 0;
  83. }
  84. return -EBUSY;
  85. }
  86. void qemu_mutex_unlock_impl(QemuMutex *mutex, const char *file, const int line)
  87. {
  88. assert(mutex->initialized);
  89. qemu_mutex_pre_unlock(mutex, file, line);
  90. ReleaseSRWLockExclusive(&mutex->lock);
  91. }
  92. void qemu_rec_mutex_init(QemuRecMutex *mutex)
  93. {
  94. InitializeCriticalSection(&mutex->lock);
  95. mutex->initialized = true;
  96. }
  97. void qemu_rec_mutex_destroy(QemuRecMutex *mutex)
  98. {
  99. assert(mutex->initialized);
  100. mutex->initialized = false;
  101. DeleteCriticalSection(&mutex->lock);
  102. }
  103. void qemu_rec_mutex_lock_impl(QemuRecMutex *mutex, const char *file, int line)
  104. {
  105. assert(mutex->initialized);
  106. EnterCriticalSection(&mutex->lock);
  107. }
  108. int qemu_rec_mutex_trylock_impl(QemuRecMutex *mutex, const char *file, int line)
  109. {
  110. assert(mutex->initialized);
  111. return !TryEnterCriticalSection(&mutex->lock);
  112. }
  113. void qemu_rec_mutex_unlock_impl(QemuRecMutex *mutex, const char *file, int line)
  114. {
  115. assert(mutex->initialized);
  116. LeaveCriticalSection(&mutex->lock);
  117. }
  118. void qemu_cond_init(QemuCond *cond)
  119. {
  120. memset(cond, 0, sizeof(*cond));
  121. InitializeConditionVariable(&cond->var);
  122. cond->initialized = true;
  123. }
  124. void qemu_cond_destroy(QemuCond *cond)
  125. {
  126. assert(cond->initialized);
  127. cond->initialized = false;
  128. InitializeConditionVariable(&cond->var);
  129. }
  130. void qemu_cond_signal(QemuCond *cond)
  131. {
  132. assert(cond->initialized);
  133. WakeConditionVariable(&cond->var);
  134. }
  135. void qemu_cond_broadcast(QemuCond *cond)
  136. {
  137. assert(cond->initialized);
  138. WakeAllConditionVariable(&cond->var);
  139. }
  140. void qemu_cond_wait_impl(QemuCond *cond, QemuMutex *mutex, const char *file, const int line)
  141. {
  142. assert(cond->initialized);
  143. qemu_mutex_pre_unlock(mutex, file, line);
  144. SleepConditionVariableSRW(&cond->var, &mutex->lock, INFINITE, 0);
  145. qemu_mutex_post_lock(mutex, file, line);
  146. }
  147. bool qemu_cond_timedwait_impl(QemuCond *cond, QemuMutex *mutex, int ms,
  148. const char *file, const int line)
  149. {
  150. int rc = 0;
  151. assert(cond->initialized);
  152. trace_qemu_mutex_unlock(mutex, file, line);
  153. if (!SleepConditionVariableSRW(&cond->var, &mutex->lock, ms, 0)) {
  154. rc = GetLastError();
  155. }
  156. trace_qemu_mutex_locked(mutex, file, line);
  157. if (rc && rc != ERROR_TIMEOUT) {
  158. error_exit(rc, __func__);
  159. }
  160. return rc != ERROR_TIMEOUT;
  161. }
  162. void qemu_sem_init(QemuSemaphore *sem, int init)
  163. {
  164. /* Manual reset. */
  165. sem->sema = CreateSemaphore(NULL, init, LONG_MAX, NULL);
  166. sem->initialized = true;
  167. }
  168. void qemu_sem_destroy(QemuSemaphore *sem)
  169. {
  170. assert(sem->initialized);
  171. sem->initialized = false;
  172. CloseHandle(sem->sema);
  173. }
  174. void qemu_sem_post(QemuSemaphore *sem)
  175. {
  176. assert(sem->initialized);
  177. ReleaseSemaphore(sem->sema, 1, NULL);
  178. }
  179. int qemu_sem_timedwait(QemuSemaphore *sem, int ms)
  180. {
  181. int rc;
  182. assert(sem->initialized);
  183. rc = WaitForSingleObject(sem->sema, ms);
  184. if (rc == WAIT_OBJECT_0) {
  185. return 0;
  186. }
  187. if (rc != WAIT_TIMEOUT) {
  188. error_exit(GetLastError(), __func__);
  189. }
  190. return -1;
  191. }
  192. void qemu_sem_wait(QemuSemaphore *sem)
  193. {
  194. assert(sem->initialized);
  195. if (WaitForSingleObject(sem->sema, INFINITE) != WAIT_OBJECT_0) {
  196. error_exit(GetLastError(), __func__);
  197. }
  198. }
  199. /* Wrap a Win32 manual-reset event with a fast userspace path. The idea
  200. * is to reset the Win32 event lazily, as part of a test-reset-test-wait
  201. * sequence. Such a sequence is, indeed, how QemuEvents are used by
  202. * RCU and other subsystems!
  203. *
  204. * Valid transitions:
  205. * - free->set, when setting the event
  206. * - busy->set, when setting the event, followed by SetEvent
  207. * - set->free, when resetting the event
  208. * - free->busy, when waiting
  209. *
  210. * set->busy does not happen (it can be observed from the outside but
  211. * it really is set->free->busy).
  212. *
  213. * busy->free provably cannot happen; to enforce it, the set->free transition
  214. * is done with an OR, which becomes a no-op if the event has concurrently
  215. * transitioned to free or busy (and is faster than cmpxchg).
  216. */
  217. #define EV_SET 0
  218. #define EV_FREE 1
  219. #define EV_BUSY -1
  220. void qemu_event_init(QemuEvent *ev, bool init)
  221. {
  222. /* Manual reset. */
  223. ev->event = CreateEvent(NULL, TRUE, TRUE, NULL);
  224. ev->value = (init ? EV_SET : EV_FREE);
  225. ev->initialized = true;
  226. }
  227. void qemu_event_destroy(QemuEvent *ev)
  228. {
  229. assert(ev->initialized);
  230. ev->initialized = false;
  231. CloseHandle(ev->event);
  232. }
  233. void qemu_event_set(QemuEvent *ev)
  234. {
  235. assert(ev->initialized);
  236. /*
  237. * Pairs with both qemu_event_reset() and qemu_event_wait().
  238. *
  239. * qemu_event_set has release semantics, but because it *loads*
  240. * ev->value we need a full memory barrier here.
  241. */
  242. smp_mb();
  243. if (qatomic_read(&ev->value) != EV_SET) {
  244. int old = qatomic_xchg(&ev->value, EV_SET);
  245. /* Pairs with memory barrier after ResetEvent. */
  246. smp_mb__after_rmw();
  247. if (old == EV_BUSY) {
  248. /* There were waiters, wake them up. */
  249. SetEvent(ev->event);
  250. }
  251. }
  252. }
  253. void qemu_event_reset(QemuEvent *ev)
  254. {
  255. assert(ev->initialized);
  256. /*
  257. * If there was a concurrent reset (or even reset+wait),
  258. * do nothing. Otherwise change EV_SET->EV_FREE.
  259. */
  260. qatomic_or(&ev->value, EV_FREE);
  261. /*
  262. * Order reset before checking the condition in the caller.
  263. * Pairs with the first memory barrier in qemu_event_set().
  264. */
  265. smp_mb__after_rmw();
  266. }
  267. void qemu_event_wait(QemuEvent *ev)
  268. {
  269. unsigned value;
  270. assert(ev->initialized);
  271. /*
  272. * qemu_event_wait must synchronize with qemu_event_set even if it does
  273. * not go down the slow path, so this load-acquire is needed that
  274. * synchronizes with the first memory barrier in qemu_event_set().
  275. *
  276. * If we do go down the slow path, there is no requirement at all: we
  277. * might miss a qemu_event_set() here but ultimately the memory barrier in
  278. * qemu_futex_wait() will ensure the check is done correctly.
  279. */
  280. value = qatomic_load_acquire(&ev->value);
  281. if (value != EV_SET) {
  282. if (value == EV_FREE) {
  283. /*
  284. * Here the underlying kernel event is reset, but qemu_event_set is
  285. * not yet going to call SetEvent. However, there will be another
  286. * check for EV_SET below when setting EV_BUSY. At that point it
  287. * is safe to call WaitForSingleObject.
  288. */
  289. ResetEvent(ev->event);
  290. /*
  291. * It is not clear whether ResetEvent provides this barrier; kernel
  292. * APIs (KeResetEvent/KeClearEvent) do not. Better safe than sorry!
  293. */
  294. smp_mb();
  295. /*
  296. * Leave the event reset and tell qemu_event_set that there are
  297. * waiters. No need to retry, because there cannot be a concurrent
  298. * busy->free transition. After the CAS, the event will be either
  299. * set or busy.
  300. */
  301. if (qatomic_cmpxchg(&ev->value, EV_FREE, EV_BUSY) == EV_SET) {
  302. return;
  303. }
  304. }
  305. /*
  306. * ev->value is now EV_BUSY. Since we didn't observe EV_SET,
  307. * qemu_event_set() must observe EV_BUSY and call SetEvent().
  308. */
  309. WaitForSingleObject(ev->event, INFINITE);
  310. }
  311. }
  312. struct QemuThreadData {
  313. /* Passed to win32_start_routine. */
  314. void *(*start_routine)(void *);
  315. void *arg;
  316. short mode;
  317. NotifierList exit;
  318. /* Only used for joinable threads. */
  319. bool exited;
  320. void *ret;
  321. CRITICAL_SECTION cs;
  322. };
  323. static bool atexit_registered;
  324. static NotifierList main_thread_exit;
  325. static __thread QemuThreadData *qemu_thread_data;
  326. static void run_main_thread_exit(void)
  327. {
  328. notifier_list_notify(&main_thread_exit, NULL);
  329. }
  330. void qemu_thread_atexit_add(Notifier *notifier)
  331. {
  332. if (!qemu_thread_data) {
  333. if (!atexit_registered) {
  334. atexit_registered = true;
  335. atexit(run_main_thread_exit);
  336. }
  337. notifier_list_add(&main_thread_exit, notifier);
  338. } else {
  339. notifier_list_add(&qemu_thread_data->exit, notifier);
  340. }
  341. }
  342. void qemu_thread_atexit_remove(Notifier *notifier)
  343. {
  344. notifier_remove(notifier);
  345. }
  346. static unsigned __stdcall win32_start_routine(void *arg)
  347. {
  348. QemuThreadData *data = (QemuThreadData *) arg;
  349. void *(*start_routine)(void *) = data->start_routine;
  350. void *thread_arg = data->arg;
  351. qemu_thread_data = data;
  352. qemu_thread_exit(start_routine(thread_arg));
  353. abort();
  354. }
  355. void qemu_thread_exit(void *arg)
  356. {
  357. QemuThreadData *data = qemu_thread_data;
  358. notifier_list_notify(&data->exit, NULL);
  359. if (data->mode == QEMU_THREAD_JOINABLE) {
  360. data->ret = arg;
  361. EnterCriticalSection(&data->cs);
  362. data->exited = true;
  363. LeaveCriticalSection(&data->cs);
  364. } else {
  365. g_free(data);
  366. }
  367. _endthreadex(0);
  368. }
  369. void *qemu_thread_join(QemuThread *thread)
  370. {
  371. QemuThreadData *data;
  372. void *ret;
  373. HANDLE handle;
  374. data = thread->data;
  375. if (data->mode == QEMU_THREAD_DETACHED) {
  376. return NULL;
  377. }
  378. /*
  379. * Because multiple copies of the QemuThread can exist via
  380. * qemu_thread_get_self, we need to store a value that cannot
  381. * leak there. The simplest, non racy way is to store the TID,
  382. * discard the handle that _beginthreadex gives back, and
  383. * get another copy of the handle here.
  384. */
  385. handle = qemu_thread_get_handle(thread);
  386. if (handle) {
  387. WaitForSingleObject(handle, INFINITE);
  388. CloseHandle(handle);
  389. }
  390. ret = data->ret;
  391. DeleteCriticalSection(&data->cs);
  392. g_free(data);
  393. return ret;
  394. }
  395. static bool set_thread_description(HANDLE h, const char *name)
  396. {
  397. HRESULT hr;
  398. g_autofree wchar_t *namew = NULL;
  399. if (!load_set_thread_description()) {
  400. return false;
  401. }
  402. namew = g_utf8_to_utf16(name, -1, NULL, NULL, NULL);
  403. if (!namew) {
  404. return false;
  405. }
  406. hr = SetThreadDescriptionFunc(h, namew);
  407. return SUCCEEDED(hr);
  408. }
  409. void qemu_thread_create(QemuThread *thread, const char *name,
  410. void *(*start_routine)(void *),
  411. void *arg, int mode)
  412. {
  413. HANDLE hThread;
  414. struct QemuThreadData *data;
  415. data = g_malloc(sizeof *data);
  416. data->start_routine = start_routine;
  417. data->arg = arg;
  418. data->mode = mode;
  419. data->exited = false;
  420. notifier_list_init(&data->exit);
  421. if (data->mode != QEMU_THREAD_DETACHED) {
  422. InitializeCriticalSection(&data->cs);
  423. }
  424. hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine,
  425. data, 0, &thread->tid);
  426. if (!hThread) {
  427. error_exit(GetLastError(), __func__);
  428. }
  429. if (name_threads && name && !set_thread_description(hThread, name)) {
  430. fprintf(stderr, "qemu: failed to set thread description: %s\n", name);
  431. }
  432. CloseHandle(hThread);
  433. thread->data = data;
  434. }
  435. int qemu_thread_set_affinity(QemuThread *thread, unsigned long *host_cpus,
  436. unsigned long nbits)
  437. {
  438. return -ENOSYS;
  439. }
  440. int qemu_thread_get_affinity(QemuThread *thread, unsigned long **host_cpus,
  441. unsigned long *nbits)
  442. {
  443. return -ENOSYS;
  444. }
  445. void qemu_thread_get_self(QemuThread *thread)
  446. {
  447. thread->data = qemu_thread_data;
  448. thread->tid = GetCurrentThreadId();
  449. }
  450. HANDLE qemu_thread_get_handle(QemuThread *thread)
  451. {
  452. QemuThreadData *data;
  453. HANDLE handle;
  454. data = thread->data;
  455. if (data->mode == QEMU_THREAD_DETACHED) {
  456. return NULL;
  457. }
  458. EnterCriticalSection(&data->cs);
  459. if (!data->exited) {
  460. handle = OpenThread(SYNCHRONIZE | THREAD_SUSPEND_RESUME |
  461. THREAD_SET_CONTEXT, FALSE, thread->tid);
  462. } else {
  463. handle = NULL;
  464. }
  465. LeaveCriticalSection(&data->cs);
  466. return handle;
  467. }
  468. bool qemu_thread_is_self(QemuThread *thread)
  469. {
  470. return GetCurrentThreadId() == thread->tid;
  471. }