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