add fast path for normal mutexes back to pthread_mutex_lock
[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 static int do_wait(volatile int *addr, int val, clockid_t clk, const struct timespec *at, int cp, int priv)
8 {
9         int r, flag = 0;
10         struct timespec to, *top=0;
11
12         if (!at) goto notimeout;
13         if (at->tv_nsec >= 1000000000UL)
14                 return EINVAL;
15         if (clk == CLOCK_REALTIME || clk == CLOCK_MONOTONIC) {
16                 if (clk == CLOCK_REALTIME) flag = FUTEX_CLOCK_REALTIME;
17                 if (cp) r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT_BITSET|flag, val, at, 0, -1);
18                 else r = -__syscall(SYS_futex, addr, FUTEX_WAIT_BITSET|flag, val, at, 0, -1);
19                 if (r != EINVAL && r != ENOSYS) goto done;
20         }
21         if (clock_gettime(clk, &to)) return EINVAL;
22         to.tv_sec = at->tv_sec - to.tv_sec;
23         if ((to.tv_nsec = at->tv_nsec - to.tv_nsec) < 0) {
24                 to.tv_sec--;
25                 to.tv_nsec += 1000000000;
26         }
27         if (to.tv_sec < 0) return ETIMEDOUT;
28         top = &to;
29 notimeout:
30         if (cp) r = -__syscall_cp(SYS_futex, addr, FUTEX_WAIT, val, top);
31         else r = -__syscall(SYS_futex, addr, FUTEX_WAIT, val, top);
32 done:
33         if (r == EINTR || r == EINVAL || r == ETIMEDOUT) return r;
34         return 0;
35 }
36
37 int __timedwait(volatile int *addr, int val, clockid_t clk, const struct timespec *at, void (*cleanup)(void *), void *arg, int priv)
38 {
39         int r;
40         if (cleanup) {
41                 pthread_cleanup_push(cleanup, arg);
42                 r = do_wait(addr, val, clk, at, 1, priv);
43                 pthread_cleanup_pop(0);
44         } else {
45                 r = do_wait(addr, val, clk, at, 0, priv);
46         }
47         return r;
48 }