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