Debian Codegraph @

libc-top-half/musl/src/thread/__wait.c

raw
1 #include "pthread_impl.h"
2 #ifndef __wasilibc_unmodified_upstream
3 #include "assert.h"
4 #endif
5
6 #ifndef __wasilibc_unmodified_upstream
7
8 weak int __wasilibc_futex_wait_maybe_busy(volatile void *addr, int op, int val, int64_t max_wait_ns);
9
10 // Use WebAssembly's `wait` instruction to implement a futex. Note that `op` is
11 // unused but retained as a parameter to match the original signature of the
12 // syscall and that, for `max_wait_ns`, -1 (or any negative number) means wait
13 // indefinitely.
14 //
15 // Adapted from Emscripten: see
16 // https://github.com/emscripten-core/emscripten/blob/058a9fff/system/lib/pthread/emscripten_futex_wait.c#L111-L150.
17 int __wasilibc_futex_wait_atomic_wait(volatile void *addr, int op, int val, int64_t max_wait_ns)
18 {
19 int ret = __builtin_wasm_memory_atomic_wait32((int *)addr, val, max_wait_ns);
20
21 // memory.atomic.wait32 returns:
22 // 0 => "ok", woken by another agent.
23 // 1 => "not-equal", loaded value != expected value
24 // 2 => "timed-out", the timeout expired
25 if (ret == 1) {
26 return -EWOULDBLOCK;
27 }
28 if (ret == 2) {
29 return -ETIMEDOUT;
30 }
31 assert(ret == 0);
32 return 0;
33 }
34
35 int __wasilibc_futex_wait(volatile void *addr, int op, int val, int64_t max_wait_ns)
36 {
37 if ((((intptr_t)addr) & 3) != 0) {
38 return -EINVAL;
39 }
40
41 if (__wasilibc_futex_wait_maybe_busy) {
42 return __wasilibc_futex_wait_maybe_busy(addr, op, val, max_wait_ns);
43 }
44 return __wasilibc_futex_wait_atomic_wait(addr, op, val, max_wait_ns);
45 }
46 #endif
47
48 void __wait(volatile int *addr, volatile int *waiters, int val, int priv)
49 {
50 int spins=100;
51 if (priv) priv = FUTEX_PRIVATE;
52 while (spins-- && (!waiters || !*waiters)) {
53 if (*addr==val) a_spin();
54 else return;
55 }
56 if (waiters) a_inc(waiters);
57 while (*addr==val) {
58 #ifdef __wasilibc_unmodified_upstream
59 __syscall(SYS_futex, addr, FUTEX_WAIT|priv, val, 0) != -ENOSYS
60 || __syscall(SYS_futex, addr, FUTEX_WAIT, val, 0);
61 #else
62 __wasilibc_futex_wait(addr, FUTEX_WAIT, val, -1);
63 #endif
64 }
65 if (waiters) a_dec(waiters);
66 }