make futex operations use private-futex mode when possible
[musl] / src / thread / __timedwait.c
1 #include <pthread.h>
2 #include <time.h>
3 #include <errno.h>
4 #include "futex.h"
5 #include "syscall.h"
6
7 int __timedwait(volatile int *addr, int val,
8         clockid_t clk, const struct timespec *at,
9         void (*cleanup)(void *), void *arg, int priv)
10 {
11         int r, cs;
12         struct timespec to, *top=0;
13
14         if (priv) priv = 128;
15
16         if (at) {
17                 if (at->tv_nsec >= 1000000000UL) return EINVAL;
18                 if (clock_gettime(clk, &to)) return EINVAL;
19                 to.tv_sec = at->tv_sec - to.tv_sec;
20                 if ((to.tv_nsec = at->tv_nsec - to.tv_nsec) < 0) {
21                         to.tv_sec--;
22                         to.tv_nsec += 1000000000;
23                 }
24                 if (to.tv_sec < 0) return ETIMEDOUT;
25                 top = &to;
26         }
27
28         if (!cleanup) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
29         pthread_cleanup_push(cleanup, arg);
30
31         r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT|priv, val, top);
32         if (r == EINVAL) r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT, val, top);
33         if (r != EINTR && r != ETIMEDOUT) r = 0;
34
35         pthread_cleanup_pop(0);
36         if (!cleanup) pthread_setcancelstate(cs, 0);
37
38         return r;
39 }