Debian Codegraph @

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

raw
1 #include <pthread.h>
2 #include <time.h>
3 #include <errno.h>
4 #include "futex.h"
5 #include "syscall.h"
6 #include "pthread_impl.h"
7
8 #ifdef __wasilibc_unmodified_upstream
9 #define IS32BIT(x) !((x)+0x80000000ULL>>32)
10 #define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
11
12 static int __futex4_cp(volatile void *addr, int op, int val, const struct timespec *to)
13 {
14 int r;
15 #ifdef SYS_futex_time64
16 time_t s = to ? to->tv_sec : 0;
17 long ns = to ? to->tv_nsec : 0;
18 r = -ENOSYS;
19 if (SYS_futex == SYS_futex_time64 || !IS32BIT(s))
20 r = __syscall_cp(SYS_futex_time64, addr, op, val,
21 to ? ((long long[]){s, ns}) : 0);
22 if (SYS_futex == SYS_futex_time64 || r!=-ENOSYS) return r;
23 to = to ? (void *)(long[]){CLAMP(s), ns} : 0;
24 #endif
25 r = __syscall_cp(SYS_futex, addr, op, val, to);
26 if (r != -ENOSYS) return r;
27 return __syscall_cp(SYS_futex, addr, op & ~FUTEX_PRIVATE, val, to);
28 }
29
30 static volatile int dummy = 0;
31 weak_alias(dummy, __eintr_valid_flag);
32 #else
33 static int __futex4_cp(volatile void *addr, int op, int val, const struct timespec *to)
34 {
35 int64_t max_wait_ns = -1;
36 if (to) {
37 max_wait_ns = (int64_t)(to->tv_sec * 1000000000 + to->tv_nsec);
38 }
39 return __wasilibc_futex_wait(addr, op, val, max_wait_ns);
40 }
41 #endif
42
43 int __timedwait_cp(volatile int *addr, int val,
44 clockid_t clk, const struct timespec *at, int priv)
45 {
46 int r;
47 struct timespec to, *top=0;
48
49 if (priv) priv = FUTEX_PRIVATE;
50
51 if (at) {
52 if (at->tv_nsec >= 1000000000UL) return EINVAL;
53 if (__clock_gettime(clk, &to)) return EINVAL;
54 to.tv_sec = at->tv_sec - to.tv_sec;
55 if ((to.tv_nsec = at->tv_nsec - to.tv_nsec) < 0) {
56 to.tv_sec--;
57 to.tv_nsec += 1000000000;
58 }
59 if (to.tv_sec < 0) return ETIMEDOUT;
60 top = &to;
61 }
62
63 r = -__futex4_cp(addr, FUTEX_WAIT|priv, val, top);
64 if (r != EINTR && r != ETIMEDOUT && r != ECANCELED) r = 0;
65 #ifdef __wasilibc_unmodified_upstream
66 /* Mitigate bug in old kernels wrongly reporting EINTR for non-
67 * interrupting (SA_RESTART) signal handlers. This is only practical
68 * when NO interrupting signal handlers have been installed, and
69 * works by sigaction tracking whether that's the case. */
70 if (r == EINTR && !__eintr_valid_flag) r = 0;
71 #endif
72
73 return r;
74 }
75
76 int __timedwait(volatile int *addr, int val,
77 clockid_t clk, const struct timespec *at, int priv)
78 {
79 int cs, r;
80 __pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
81 r = __timedwait_cp(addr, val, clk, at, priv);
82 __pthread_setcancelstate(cs, 0);
83 return r;
84 }