xref: /qemu/include/qemu/futex.h (revision 96215036f47403438c7c7869b7cd419bd7a11f82)
1 /*
2  * Wrappers around Linux futex syscall and similar
3  *
4  * Copyright Red Hat, Inc. 2017
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 
14 /*
15  * Note that a wake-up can also be caused by common futex usage patterns in
16  * unrelated code that happened to have previously used the futex word's
17  * memory location (e.g., typical futex-based implementations of Pthreads
18  * mutexes can cause this under some conditions).  Therefore, qemu_futex_wait()
19  * callers should always conservatively assume that it is a spurious wake-up,
20  * and use the futex word's value (i.e., the user-space synchronization scheme)
21  * to decide whether to continue to block or not.
22  */
23 
24 #ifndef QEMU_FUTEX_H
25 #define QEMU_FUTEX_H
26 
27 #define HAVE_FUTEX
28 
29 #ifdef CONFIG_LINUX
30 #include <sys/syscall.h>
31 #include <linux/futex.h>
32 
33 #define qemu_futex(...)              syscall(__NR_futex, __VA_ARGS__)
34 
qemu_futex_wake_all(void * f)35 static inline void qemu_futex_wake_all(void *f)
36 {
37     qemu_futex(f, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
38 }
39 
qemu_futex_wake_single(void * f)40 static inline void qemu_futex_wake_single(void *f)
41 {
42     qemu_futex(f, FUTEX_WAKE, 1, NULL, NULL, 0);
43 }
44 
qemu_futex_wait(void * f,unsigned val)45 static inline void qemu_futex_wait(void *f, unsigned val)
46 {
47     while (qemu_futex(f, FUTEX_WAIT, (int) val, NULL, NULL, 0)) {
48         switch (errno) {
49         case EWOULDBLOCK:
50             return;
51         case EINTR:
52             break; /* get out of switch and retry */
53         default:
54             abort();
55         }
56     }
57 }
58 #elif defined(CONFIG_WIN32)
59 #include <synchapi.h>
60 
qemu_futex_wake_all(void * f)61 static inline void qemu_futex_wake_all(void *f)
62 {
63     WakeByAddressAll(f);
64 }
65 
qemu_futex_wake_single(void * f)66 static inline void qemu_futex_wake_single(void *f)
67 {
68     WakeByAddressSingle(f);
69 }
70 
qemu_futex_wait(void * f,unsigned val)71 static inline void qemu_futex_wait(void *f, unsigned val)
72 {
73     WaitOnAddress(f, &val, sizeof(val), INFINITE);
74 }
75 #else
76 #undef HAVE_FUTEX
77 #endif
78 
79 #endif /* QEMU_FUTEX_H */
80