4608375924a6c336479c2085c607e2d55ffba0a2
[musl] / src / time / clock_gettime.c
1 #include <time.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include "syscall.h"
5 #include "atomic.h"
6
7 #ifdef VDSO_CGT_SYM
8
9 static void *volatile vdso_func;
10
11 static int cgt_init(clockid_t clk, struct timespec *ts)
12 {
13         void *p = __vdsosym(VDSO_CGT_VER, VDSO_CGT_SYM);
14         int (*f)(clockid_t, struct timespec *) =
15                 (int (*)(clockid_t, struct timespec *))p;
16         a_cas_p(&vdso_func, (void *)cgt_init, p);
17         return f ? f(clk, ts) : -ENOSYS;
18 }
19
20 static void *volatile vdso_func = (void *)cgt_init;
21
22 #endif
23
24 int __clock_gettime(clockid_t clk, struct timespec *ts)
25 {
26         int r;
27
28 #ifdef VDSO_CGT_SYM
29         int (*f)(clockid_t, struct timespec *) =
30                 (int (*)(clockid_t, struct timespec *))vdso_func;
31         if (f) {
32                 r = f(clk, ts);
33                 if (!r) return r;
34                 if (r == -EINVAL) return __syscall_ret(r);
35                 /* Fall through on errors other than EINVAL. Some buggy
36                  * vdso implementations return ENOSYS for clocks they
37                  * can't handle, rather than making the syscall. This
38                  * also handles the case where cgt_init fails to find
39                  * a vdso function to use. */
40         }
41 #endif
42
43 #ifdef SYS_clock_gettime64
44         if (sizeof(time_t) > 4)
45                 r = __syscall(SYS_clock_gettime64, clk, ts);
46         if (SYS_clock_gettime == SYS_clock_gettime64 || r!=-ENOSYS)
47                 return __syscall_ret(r);
48         long ts32[2];
49         r = __syscall(SYS_clock_gettime, clk, ts32);
50         if (r==-ENOSYS && clk==CLOCK_REALTIME) {
51                 r = __syscall(SYS_gettimeofday, ts32, 0);
52                 ts32[1] *= 1000;
53         }
54         if (!r) {
55                 ts->tv_sec = ts32[0];
56                 ts->tv_nsec = ts32[1];
57                 return r;
58         }
59         return __syscall_ret(r);
60 #else
61         r = __syscall(SYS_clock_gettime, clk, ts);
62         if (r == -ENOSYS) {
63                 if (clk == CLOCK_REALTIME) {
64                         __syscall(SYS_gettimeofday, ts, 0);
65                         ts->tv_nsec = (int)ts->tv_nsec * 1000;
66                         return 0;
67                 }
68                 r = -EINVAL;
69         }
70         return __syscall_ret(r);
71 #endif
72 }
73
74 weak_alias(__clock_gettime, clock_gettime);