1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <time.h>
17 #include <errno.h>
18 #include <stdint.h>
19 #include "syscall.h"
20 #include "atomic.h"
21 
22 #ifdef VDSO_TIME_SYM
23 
24 static void *volatile vdso_time;
25 
time_init(time_t *t)26 static time_t time_init(time_t *t)
27 {
28 	__get_vdso_info();
29 	void *p = __get_vdso_addr(VDSO_TIME_VER, VDSO_TIME_SYM);
30 	time_t (*f)(time_t *) =
31 		(time_t (*)(time_t *))p;
32 	a_cas_p(&vdso_time, (void *)time_init, p);
33 	return f ? f(t) : -ENOSYS;
34 }
35 
36 static void *volatile vdso_time = (void *)time_init;
37 
38 #endif
39 
time(time_t *t)40 time_t time(time_t *t)
41 {
42 #ifdef VDSO_TIME_SYM
43 	time_t (*f)(time_t *) =
44 	(time_t (*)(time_t *))vdso_time;
45     if (f) {
46 		return f(t);
47 	}
48 #endif
49 
50 	struct timespec ts;
51 	__clock_gettime(CLOCK_REALTIME, &ts);
52 	if (t) *t = ts.tv_sec;
53 	return ts.tv_sec;
54 }
55