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 #define IS32BIT(x) !((x)+0x80000000ULL>>32)
9 #define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
10
__futex4_cp(volatile void * addr,int op,int val,const struct timespec * to)11 static int __futex4_cp(volatile void *addr, int op, int val, const struct timespec *to)
12 {
13 int r;
14 unsigned int useconds = 0xffffffffU;
15 #if 0
16 #ifdef SYS_futex_time64
17 time_t s = to ? to->tv_sec : 0;
18 long ns = to ? to->tv_nsec : 0;
19 r = -ENOSYS;
20 if (SYS_futex == SYS_futex_time64 || !IS32BIT(s))
21 r = __syscall_cp(SYS_futex_time64, addr, op, val,
22 to ? ((long long[]){s, ns}) : 0);
23 if (SYS_futex == SYS_futex_time64 || r!=-ENOSYS) return r;
24 to = to ? (void *)(long[]){CLAMP(s), ns} : 0;
25 #endif
26 #endif
27
28 if (to) {
29 useconds = (to->tv_sec * 1000000 + to->tv_nsec / 1000);
30 if ((useconds == 0) && (to->tv_nsec != 0)) {
31 useconds = 1;
32 }
33 }
34
35 r = __syscall_cp(SYS_futex, addr, op, val, useconds);
36 if (r != -ENOSYS) return r;
37 return __syscall_cp(SYS_futex, addr, op & ~FUTEX_PRIVATE, val, useconds);
38 }
39
40 static volatile int dummy = 0;
41 weak_alias(dummy, __eintr_valid_flag);
42
__timedwait_cp(volatile int * addr,int val,clockid_t clk,const struct timespec * at,int priv)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 /* Mitigate bug in old kernels wrongly reporting EINTR for non-
66 * interrupting (SA_RESTART) signal handlers. This is only practical
67 * when NO interrupting signal handlers have been installed, and
68 * works by sigaction tracking whether that's the case. */
69 if (r == EINTR && !__eintr_valid_flag) r = 0;
70
71 return r;
72 }
73
__timedwait(volatile int * addr,int val,clockid_t clk,const struct timespec * at,int priv)74 int __timedwait(volatile int *addr, int val,
75 clockid_t clk, const struct timespec *at, int priv)
76 {
77 int cs, r;
78 __pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
79 r = __timedwait_cp(addr, val, clk, at, priv);
80 __pthread_setcancelstate(cs, 0);
81 return r;
82 }
83