• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
3  * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without modification,
6  * are permitted provided that the following conditions are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright notice, this list of
9  *    conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright notice, this list
12  *    of conditions and the following disclaimer in the documentation and/or other materials
13  *    provided with the distribution.
14  *
15  * 3. Neither the name of the copyright holder nor the names of its contributors may be used
16  *    to endorse or promote products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
26  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
28  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include "time.h"
33 #include "stdint.h"
34 #include "stdio.h"
35 #include "sys/times.h"
36 #include "time_posix.h"
37 #include "unistd.h"
38 #ifdef LOSCFG_SECURITY_CAPABILITY
39 #include "capability_api.h"
40 #endif
41 #include "los_signal.h"
42 #ifdef LOSCFG_KERNEL_VDSO
43 #include "los_vdso.h"
44 #endif
45 #ifdef LOSCFG_SECURITY_VID
46 #include "vid_api.h"
47 #endif
48 #include "user_copy.h"
49 #include "los_process_pri.h"
50 #include "los_swtmr_pri.h"
51 #include "los_sys_pri.h"
52 
53 #define CPUCLOCK_PERTHREAD_MASK 4
54 #define CPUCLOCK_ID_OFFSET 3
55 
56 /*
57  * Do a time package defined return. This requires the error code
58  * to be placed in errno, and if it is non-zero, -1 returned as the
59  * result of the function. This also gives us a place to put any
60  * generic tidyup handling needed for things like signal delivery and
61  * cancellation.
62  */
63 #define TIME_RETURN(err) do { \
64     INT32 retVal = 0;         \
65     if ((err) != 0) {         \
66         retVal = -1;          \
67         errno = (err);        \
68     }                         \
69     return retVal;            \
70 } while (0)
71 
72 #ifdef LOSCFG_AARCH64
73 /*
74  * This two structures originally did't exit,
75  * they added by liteos to support 64bit interfaces on 32bit platform,
76  * in 64bit platform, timeval64 define to timeval which is platform adaptive.
77  */
78 #define timeval64 timeval
79 #define timespec64 timespec
80 #endif
81 
ValidTimeval(const struct timeval * tv)82 STATIC INLINE BOOL ValidTimeval(const struct timeval *tv)
83 {
84     /* Fail a NULL pointer */
85     if (tv == NULL) {
86         return FALSE;
87     }
88 
89     /* Fail illegal microseconds values */
90     if ((tv->tv_usec < 0) || (tv->tv_usec >= OS_SYS_US_PER_SECOND) || (tv->tv_sec < 0)) {
91         return FALSE;
92     }
93 
94     return TRUE;
95 }
96 
ValidTimeval64(const struct timeval64 * tv)97 STATIC INLINE BOOL ValidTimeval64(const struct timeval64 *tv)
98 {
99     /* Fail a NULL pointer */
100     if (tv == NULL) {
101         return FALSE;
102     }
103 
104     /* Fail illegal microseconds values */
105     if ((tv->tv_usec < 0) || (tv->tv_usec >= OS_SYS_US_PER_SECOND) || (tv->tv_sec < 0)) {
106         return FALSE;
107     }
108 
109     return TRUE;
110 }
111 
ValidTimerID(UINT16 swtmrID)112 STATIC INLINE BOOL ValidTimerID(UINT16 swtmrID)
113 {
114     /* check timer id */
115     if (swtmrID >= OS_SWTMR_MAX_TIMERID) {
116         return FALSE;
117     }
118 
119     /* check owner of this timer */
120     if (OS_SWT_FROM_SID(swtmrID)->uwOwnerPid != LOS_GetCurrProcessID()) {
121         return FALSE;
122     }
123 
124     return TRUE;
125 }
126 
127 STATIC SPIN_LOCK_INIT(g_timeSpin);
128 STATIC long long g_adjTimeLeft; /* absolute value of adjtime */
129 STATIC INT32 g_adjDirection;    /* 1, speed up; 0, slow down; */
130 
131 /* Adjust pacement, nanoseconds per SCHED_CLOCK_INTETRVAL_TICKS ticks */
132 STATIC const long long g_adjPacement = (((LOSCFG_BASE_CORE_ADJ_PER_SECOND * SCHED_CLOCK_INTETRVAL_TICKS) /
133                                         LOSCFG_BASE_CORE_TICK_PER_SECOND) * OS_SYS_NS_PER_US);
134 
135 /* accumulative time delta from continuous modify, such as adjtime */
136 STATIC struct timespec64 g_accDeltaFromAdj;
137 /* accumulative time delta from discontinuous modify, such as settimeofday */
138 STATIC struct timespec64 g_accDeltaFromSet;
139 
OsAdjTime(VOID)140 VOID OsAdjTime(VOID)
141 {
142     UINT32 intSave;
143 
144     LOS_SpinLockSave(&g_timeSpin, &intSave);
145     if (!g_adjTimeLeft) {
146         LOS_SpinUnlockRestore(&g_timeSpin, intSave);
147         return;
148     }
149 
150     if (g_adjTimeLeft > g_adjPacement) {
151         if (g_adjDirection) {
152             if ((g_accDeltaFromAdj.tv_nsec + g_adjPacement) >= OS_SYS_NS_PER_SECOND) {
153                 g_accDeltaFromAdj.tv_sec++;
154                 g_accDeltaFromAdj.tv_nsec  = (g_accDeltaFromAdj.tv_nsec + g_adjPacement) % OS_SYS_NS_PER_SECOND;
155             } else {
156                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec + g_adjPacement;
157             }
158         } else {
159             if ((g_accDeltaFromAdj.tv_nsec - g_adjPacement) < 0) {
160                 g_accDeltaFromAdj.tv_sec--;
161                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec - g_adjPacement + OS_SYS_NS_PER_SECOND;
162             } else {
163                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec - g_adjPacement;
164             }
165         }
166 
167         g_adjTimeLeft -= g_adjPacement;
168     } else {
169         if (g_adjDirection) {
170             if ((g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft) >= OS_SYS_NS_PER_SECOND) {
171                 g_accDeltaFromAdj.tv_sec++;
172                 g_accDeltaFromAdj.tv_nsec  = (g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft) % OS_SYS_NS_PER_SECOND;
173             } else {
174                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft;
175             }
176         } else {
177             if ((g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft) < 0) {
178                 g_accDeltaFromAdj.tv_sec--;
179                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft + OS_SYS_NS_PER_SECOND;
180             } else {
181                 g_accDeltaFromAdj.tv_nsec  = g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft;
182             }
183         }
184 
185         g_adjTimeLeft = 0;
186     }
187     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
188     return;
189 }
190 
191 /*
192  * Function: adjtime
193  * Description:  correct the time to synchronize the system clock.
194  * Input:     delta - The amount of time by which the clock is to be adjusted.
195  * Output: oldDelta - the amount of time remaining from any previous adjustment that has not yet been completed.
196  * Return: On success, returns 0.  On failure, -1 is returned, and errno is set to indicate the error.
197  */
adjtime(const struct timeval * delta,struct timeval * oldDelta)198 int adjtime(const struct timeval *delta, struct timeval *oldDelta)
199 {
200     UINT32 intSave;
201     LOS_SpinLockSave(&g_timeSpin, &intSave);
202     /* return the amount of time remaining from any previous adjustment that has not yet been completed. */
203     if (oldDelta != NULL) {
204         if (g_adjDirection == 1) {
205             oldDelta->tv_sec = g_adjTimeLeft / OS_SYS_NS_PER_SECOND;
206             oldDelta->tv_usec = (g_adjTimeLeft % OS_SYS_NS_PER_SECOND) / OS_SYS_NS_PER_US;
207         } else {
208             oldDelta->tv_sec = -(g_adjTimeLeft / OS_SYS_NS_PER_SECOND);
209             oldDelta->tv_usec = -((g_adjTimeLeft % OS_SYS_NS_PER_SECOND) / OS_SYS_NS_PER_US);
210         }
211     }
212 
213     if ((delta == NULL) || ((delta->tv_sec == 0) && (delta->tv_usec == 0))) {
214         LOS_SpinUnlockRestore(&g_timeSpin, intSave);
215         return 0;
216     }
217 
218     if ((delta->tv_usec > OS_SYS_US_PER_SECOND) || (delta->tv_usec < -OS_SYS_US_PER_SECOND)) {
219         LOS_SpinUnlockRestore(&g_timeSpin, intSave);
220         TIME_RETURN(EINVAL);
221     }
222 
223     /*
224      * 2: in the glibc implementation, delta must be less than or equal to (INT_MAX / 1000000 - 2) and
225      * greater than or equal to (INT_MIN / 1000000 + 2)
226      */
227     if ((delta->tv_sec < (INT_MIN / OS_SYS_US_PER_SECOND + 2)) ||
228         (delta->tv_sec > (INT_MAX / OS_SYS_US_PER_SECOND + 2))) {
229         LOS_SpinUnlockRestore(&g_timeSpin, intSave);
230         TIME_RETURN(EINVAL);
231     }
232 
233     g_adjTimeLeft = (INT64)delta->tv_sec * OS_SYS_NS_PER_SECOND + delta->tv_usec * OS_SYS_NS_PER_US;
234     if (g_adjTimeLeft > 0) {
235         g_adjDirection = 1;
236     } else {
237         g_adjDirection = 0;
238         g_adjTimeLeft = -g_adjTimeLeft;
239     }
240 
241     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
242     return 0;
243 }
244 
OsTimeSpecAdd(const struct timespec64 t1,const struct timespec64 t2)245 STATIC INLINE struct timespec64 OsTimeSpecAdd(const struct timespec64 t1, const struct timespec64 t2)
246 {
247     struct timespec64 ret = {0};
248 
249     ret.tv_sec = t1.tv_sec + t2.tv_sec;
250     ret.tv_nsec = t1.tv_nsec + t2.tv_nsec;
251     if (ret.tv_nsec >= OS_SYS_NS_PER_SECOND) {
252         ret.tv_sec += 1;
253         ret.tv_nsec -= OS_SYS_NS_PER_SECOND;
254     } else if (ret.tv_nsec < 0L) {
255         ret.tv_sec -= 1;
256         ret.tv_nsec += OS_SYS_NS_PER_SECOND;
257     }
258 
259     return ret;
260 }
261 
OsTimeSpecSub(const struct timespec64 t1,const struct timespec64 t2)262 STATIC INLINE struct timespec64 OsTimeSpecSub(const struct timespec64 t1, const struct timespec64 t2)
263 {
264     struct timespec64 ret = {0};
265 
266     ret.tv_sec = t1.tv_sec - t2.tv_sec;
267     ret.tv_nsec = t1.tv_nsec - t2.tv_nsec;
268     if (ret.tv_nsec < 0) {
269         ret.tv_sec -= 1;
270         ret.tv_nsec += OS_SYS_NS_PER_SECOND;
271     }
272 
273     return ret;
274 }
275 
OsGetHwTime(struct timespec64 * hwTime)276 STATIC VOID OsGetHwTime(struct timespec64 *hwTime)
277 {
278     UINT64 nowNsec;
279 
280     nowNsec = LOS_CurrNanosec();
281     hwTime->tv_sec = nowNsec / OS_SYS_NS_PER_SECOND;
282     hwTime->tv_nsec = nowNsec - hwTime->tv_sec * OS_SYS_NS_PER_SECOND;
283 }
284 
OsSetTimeOfDay(const struct timeval64 * tv,const struct timezone * tz)285 STATIC INT32 OsSetTimeOfDay(const struct timeval64 *tv, const struct timezone *tz)
286 {
287     UINT32 intSave;
288     struct timespec64 setTime = {0};
289     struct timespec64 hwTime = {0};
290     struct timespec64 realTime = {0};
291     struct timespec64 tmp = {0};
292 
293 #ifdef LOSCFG_SECURITY_CAPABILITY
294     if (!IsCapPermit(CAP_SET_TIMEOFDAY)) {
295         TIME_RETURN(EPERM);
296     }
297 #endif
298 
299     (VOID)tz;
300     OsGetHwTime(&hwTime);
301     setTime.tv_sec = tv->tv_sec;
302     setTime.tv_nsec = tv->tv_usec * OS_SYS_NS_PER_US;
303 
304     LOS_SpinLockSave(&g_timeSpin, &intSave);
305     /* stop on-going continuous adjusement */
306     if (g_adjTimeLeft) {
307         g_adjTimeLeft = 0;
308     }
309     realTime = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
310     realTime = OsTimeSpecAdd(realTime, g_accDeltaFromSet);
311 
312     tmp = OsTimeSpecSub(setTime, realTime);
313     g_accDeltaFromSet = OsTimeSpecAdd(g_accDeltaFromSet, tmp);
314 
315     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
316 
317     return 0;
318 }
319 
settimeofday(const struct timeval * tv,const struct timezone * tz)320 int settimeofday(const struct timeval *tv, const struct timezone *tz)
321 {
322     struct timeval64 stTimeVal64 = {0};
323 
324     if (!ValidTimeval(tv)) {
325         TIME_RETURN(EINVAL);
326     }
327 
328     stTimeVal64.tv_sec = tv->tv_sec;
329     stTimeVal64.tv_usec = tv->tv_usec;
330 
331     return OsSetTimeOfDay(&stTimeVal64, tz);
332 }
333 
334 #ifndef LOSCFG_AARCH64
settimeofday64(const struct timeval64 * tv,const struct timezone * tz)335 int settimeofday64(const struct timeval64 *tv, const struct timezone *tz)
336 {
337     if (!ValidTimeval64(tv)) {
338         TIME_RETURN(EINVAL);
339     }
340 
341     return OsSetTimeOfDay(tv, tz);
342 }
343 #endif
344 
setlocalseconds(int seconds)345 int setlocalseconds(int seconds)
346 {
347     struct timeval tv = {0};
348 
349     tv.tv_sec = seconds;
350     tv.tv_usec = 0;
351 
352     return settimeofday(&tv, NULL);
353 }
354 
OsGetTimeOfDay(struct timeval64 * tv,struct timezone * tz)355 STATIC INT32 OsGetTimeOfDay(struct timeval64 *tv, struct timezone *tz)
356 {
357     UINT32 intSave;
358 
359     (VOID)tz;
360     struct timespec64 hwTime = {0};
361     struct timespec64 realTime = {0};
362 
363     OsGetHwTime(&hwTime);
364 
365     LOS_SpinLockSave(&g_timeSpin, &intSave);
366     realTime = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
367     realTime = OsTimeSpecAdd(realTime, g_accDeltaFromSet);
368     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
369 
370     tv->tv_sec = realTime.tv_sec;
371     tv->tv_usec = realTime.tv_nsec / OS_SYS_NS_PER_US;
372 
373     if (tv->tv_sec < 0) {
374         TIME_RETURN(EINVAL);
375     }
376     return 0;
377 }
378 
379 #ifndef LOSCFG_AARCH64
gettimeofday64(struct timeval64 * tv,struct timezone * tz)380 int gettimeofday64(struct timeval64 *tv, struct timezone *tz)
381 {
382     if (tv == NULL) {
383         TIME_RETURN(EINVAL);
384     }
385 
386     return OsGetTimeOfDay(tv, tz);
387 }
388 #endif
389 
gettimeofday(struct timeval * tv,struct timezone * tz)390 int gettimeofday(struct timeval *tv, struct timezone *tz)
391 {
392     struct timeval64 stTimeVal64 = {0};
393 
394     if (tv == NULL) {
395         TIME_RETURN(EINVAL);
396     }
397 
398     if (OsGetTimeOfDay(&stTimeVal64, tz) == -1) {
399         return -1;
400     }
401 
402 #ifdef LOSCFG_AARCH64
403     tv->tv_sec = stTimeVal64.tv_sec;
404     tv->tv_usec = stTimeVal64.tv_usec;
405 #else
406     if (stTimeVal64.tv_sec > (long long)LONG_MAX) {
407         return -1;
408     }
409     tv->tv_sec = (time_t)stTimeVal64.tv_sec;
410     tv->tv_usec = (suseconds_t)stTimeVal64.tv_usec;
411 #endif
412 
413     return 0;
414 }
415 
clock_settime(clockid_t clockID,const struct timespec * tp)416 int clock_settime(clockid_t clockID, const struct timespec *tp)
417 {
418     struct timeval tv = {0};
419 
420     switch (clockID) {
421         case CLOCK_REALTIME:
422             /* we only support the realtime clock currently */
423             break;
424         case CLOCK_MONOTONIC_COARSE:
425         case CLOCK_REALTIME_COARSE:
426         case CLOCK_MONOTONIC_RAW:
427         case CLOCK_PROCESS_CPUTIME_ID:
428         case CLOCK_BOOTTIME:
429         case CLOCK_REALTIME_ALARM:
430         case CLOCK_BOOTTIME_ALARM:
431         case CLOCK_TAI:
432         case CLOCK_THREAD_CPUTIME_ID:
433             TIME_RETURN(ENOTSUP);
434         case CLOCK_MONOTONIC:
435         default:
436             TIME_RETURN(EINVAL);
437     }
438 
439     if (!ValidTimeSpec(tp)) {
440         TIME_RETURN(EINVAL);
441     }
442 
443 #ifdef LOSCFG_SECURITY_CAPABILITY
444     if (!IsCapPermit(CAP_CLOCK_SETTIME)) {
445         TIME_RETURN(EPERM);
446     }
447 #endif
448 
449     tv.tv_sec = tp->tv_sec;
450     tv.tv_usec = tp->tv_nsec / OS_SYS_NS_PER_US;
451     return settimeofday(&tv, NULL);
452 }
453 
454 #ifdef LOSCFG_KERNEL_CPUP
GetTidFromClockID(clockid_t clockID)455 inline UINT32 GetTidFromClockID(clockid_t clockID)
456 {
457     // In musl/src/thread/pthread_getcpuclockid.c, we know 'clockid = (-tid - 1) * 8 + 6'
458     UINT32 tid = -(clockID - 6) / 8 - 1; // 6 8 1 inverse operation from clockID to tid
459     return tid;
460 }
461 
GetPidFromClockID(clockid_t clockID)462 inline const pid_t GetPidFromClockID(clockid_t clockID)
463 {
464     // In musl/src/time/clock_getcpuclockid.c, we know 'clockid = (-pid - 1) * 8 + 2'
465     const pid_t pid = -(clockID - 2) / 8 - 1; // 2 8 1 inverse operation from clockID to pid
466     return pid;
467 }
468 
PthreadGetCputime(clockid_t clockID,struct timespec * ats)469 static int PthreadGetCputime(clockid_t clockID, struct timespec *ats)
470 {
471     uint64_t runtime;
472     UINT32 intSave;
473     UINT32 tid = GetTidFromClockID(clockID);
474 
475     if (OS_TID_CHECK_INVALID(tid)) {
476         return -EINVAL;
477     }
478 
479     LosTaskCB *task = OsGetTaskCB(tid);
480 
481     if (OsCurrTaskGet()->processID != task->processID) {
482         return -EINVAL;
483     }
484 
485     SCHEDULER_LOCK(intSave);
486     runtime = task->taskCpup.allTime;
487     SCHEDULER_UNLOCK(intSave);
488 
489     ats->tv_sec = runtime / OS_SYS_NS_PER_SECOND;
490     ats->tv_nsec = runtime % OS_SYS_NS_PER_SECOND;
491 
492     return 0;
493 }
494 
ProcessGetCputime(clockid_t clockID,struct timespec * ats)495 static int ProcessGetCputime(clockid_t clockID, struct timespec *ats)
496 {
497     UINT64 runtime;
498     UINT32 intSave;
499     const pid_t pid = GetPidFromClockID(clockID);
500     LosProcessCB *spcb = NULL;
501 
502     if (OsProcessIDUserCheckInvalid(pid) || pid < 0) {
503         return -EINVAL;
504     }
505 
506     spcb = OS_PCB_FROM_PID(pid);
507     if (OsProcessIsUnused(spcb)) {
508         return -EINVAL;
509     }
510 
511     SCHEDULER_LOCK(intSave);
512     if (spcb->processCpup == NULL) {
513         SCHEDULER_UNLOCK(intSave);
514         return -EINVAL;
515     }
516     runtime = spcb->processCpup->allTime;
517     SCHEDULER_UNLOCK(intSave);
518 
519     ats->tv_sec = runtime / OS_SYS_NS_PER_SECOND;
520     ats->tv_nsec = runtime % OS_SYS_NS_PER_SECOND;
521 
522     return 0;
523 }
524 
GetCputime(clockid_t clockID,struct timespec * tp)525 static int GetCputime(clockid_t clockID, struct timespec *tp)
526 {
527     int ret;
528 
529     if (clockID >= 0) {
530         return -EINVAL;
531     }
532 
533     if ((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK) {
534         ret = PthreadGetCputime(clockID, tp);
535     } else {
536         ret = ProcessGetCputime(clockID, tp);
537     }
538 
539     return ret;
540 }
541 
CheckClock(const clockid_t clockID)542 static int CheckClock(const clockid_t clockID)
543 {
544     int error = 0;
545     const pid_t pid = GetPidFromClockID(clockID);
546 
547     if (!((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK)) {
548         LosProcessCB *spcb = NULL;
549         if (OsProcessIDUserCheckInvalid(pid) || pid < 0) {
550             return -EINVAL;
551         }
552         spcb = OS_PCB_FROM_PID(pid);
553         if (OsProcessIsUnused(spcb)) {
554             error = -EINVAL;
555         }
556     } else {
557         error = -EINVAL;
558     }
559 
560     return error;
561 }
562 
CpuClockGetres(const clockid_t clockID,struct timespec * tp)563 static int CpuClockGetres(const clockid_t clockID, struct timespec *tp)
564 {
565     if (clockID > 0) {
566         return -EINVAL;
567     }
568 
569     int error = CheckClock(clockID);
570     if (!error) {
571         error = ProcessGetCputime(clockID, tp);
572     }
573 
574     return error;
575 }
576 #endif
577 
clock_gettime(clockid_t clockID,struct timespec * tp)578 int clock_gettime(clockid_t clockID, struct timespec *tp)
579 {
580     UINT32 intSave;
581     struct timespec64 tmp = {0};
582     struct timespec64 hwTime = {0};
583 
584     if (clockID > MAX_CLOCKS) {
585         goto ERROUT;
586     }
587 
588     if (tp == NULL) {
589         goto ERROUT;
590     }
591 
592     OsGetHwTime(&hwTime);
593 
594     switch (clockID) {
595         case CLOCK_MONOTONIC_RAW:
596             tp->tv_sec = hwTime.tv_sec;
597             tp->tv_nsec = hwTime.tv_nsec;
598             break;
599         case CLOCK_MONOTONIC:
600             LOS_SpinLockSave(&g_timeSpin, &intSave);
601             tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
602             LOS_SpinUnlockRestore(&g_timeSpin, intSave);
603             tp->tv_sec = tmp.tv_sec;
604             tp->tv_nsec = tmp.tv_nsec;
605             break;
606         case CLOCK_REALTIME:
607             LOS_SpinLockSave(&g_timeSpin, &intSave);
608             tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
609             tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
610             LOS_SpinUnlockRestore(&g_timeSpin, intSave);
611             tp->tv_sec = tmp.tv_sec;
612             tp->tv_nsec = tmp.tv_nsec;
613             break;
614         case CLOCK_MONOTONIC_COARSE:
615         case CLOCK_REALTIME_COARSE:
616         case CLOCK_THREAD_CPUTIME_ID:
617         case CLOCK_PROCESS_CPUTIME_ID:
618         case CLOCK_BOOTTIME:
619         case CLOCK_REALTIME_ALARM:
620         case CLOCK_BOOTTIME_ALARM:
621         case CLOCK_TAI:
622             TIME_RETURN(ENOTSUP);
623         default:
624         {
625 #ifdef LOSCFG_KERNEL_CPUP
626             int ret = GetCputime(clockID, tp);
627                 TIME_RETURN(-ret);
628 #else
629             TIME_RETURN(EINVAL);
630 #endif
631         }
632     }
633 
634     return 0;
635 
636     ERROUT:
637     TIME_RETURN(EINVAL);
638 }
639 
clock_getres(clockid_t clockID,struct timespec * tp)640 int clock_getres(clockid_t clockID, struct timespec *tp)
641 {
642     if (tp == NULL) {
643         TIME_RETURN(EINVAL);
644     }
645 
646     switch (clockID) {
647         case CLOCK_MONOTONIC_RAW:
648         case CLOCK_MONOTONIC:
649         case CLOCK_REALTIME:
650             /* the accessible rtc resolution */
651             tp->tv_nsec = OS_SYS_NS_PER_US; /* the precision of clock_gettime is 1us */
652             tp->tv_sec = 0;
653             break;
654         case CLOCK_MONOTONIC_COARSE:
655         case CLOCK_REALTIME_COARSE:
656             /* the clock coarse resolution, supported by vdso.
657              * the precision of clock_gettime is 1tick */
658             tp->tv_nsec = OS_SYS_NS_PER_SECOND / LOSCFG_BASE_CORE_TICK_PER_SECOND;
659             tp->tv_sec = 0;
660             break;
661         case CLOCK_THREAD_CPUTIME_ID:
662         case CLOCK_PROCESS_CPUTIME_ID:
663         case CLOCK_BOOTTIME:
664         case CLOCK_REALTIME_ALARM:
665         case CLOCK_BOOTTIME_ALARM:
666         case CLOCK_TAI:
667             TIME_RETURN(ENOTSUP);
668         default:
669 #ifdef LOSCFG_KERNEL_CPUP
670             {
671                 int ret = CpuClockGetres(clockID, tp);
672                 TIME_RETURN(-ret);
673             }
674 #else
675             TIME_RETURN(EINVAL);
676 #endif
677     }
678 
679     TIME_RETURN(0);
680 }
681 
clock_nanosleep(clockid_t clk,int flags,const struct timespec * req,struct timespec * rem)682 int clock_nanosleep(clockid_t clk, int flags, const struct timespec *req, struct timespec *rem)
683 {
684     switch (clk) {
685         case CLOCK_REALTIME:
686             if (flags == 0) {
687                 /* we only support the realtime clock currently */
688                 return nanosleep(req, rem);
689             }
690             /* fallthrough */
691         case CLOCK_MONOTONIC_COARSE:
692         case CLOCK_REALTIME_COARSE:
693         case CLOCK_MONOTONIC_RAW:
694         case CLOCK_MONOTONIC:
695         case CLOCK_PROCESS_CPUTIME_ID:
696         case CLOCK_BOOTTIME:
697         case CLOCK_REALTIME_ALARM:
698         case CLOCK_BOOTTIME_ALARM:
699         case CLOCK_TAI:
700             if (flags == 0 || flags == TIMER_ABSTIME) {
701                 TIME_RETURN(ENOTSUP);
702             }
703             /* fallthrough */
704         case CLOCK_THREAD_CPUTIME_ID:
705         default:
706             TIME_RETURN(EINVAL);
707     }
708 
709     TIME_RETURN(0);
710 }
711 
712 typedef struct {
713     int sigev_signo;
714     pid_t pid;
715     unsigned int tid;
716     union sigval sigev_value;
717 } swtmr_proc_arg;
718 
SwtmrProc(UINTPTR tmrArg)719 static VOID SwtmrProc(UINTPTR tmrArg)
720 {
721     INT32 sig, ret;
722     UINT32 intSave;
723     pid_t pid;
724     siginfo_t info;
725     LosTaskCB *stcb = NULL;
726 
727     swtmr_proc_arg *arg = (swtmr_proc_arg *)tmrArg;
728     OS_GOTO_EXIT_IF(arg == NULL, EINVAL);
729 
730     sig = arg->sigev_signo;
731     pid = arg->pid;
732     OS_GOTO_EXIT_IF(!GOOD_SIGNO(sig), EINVAL);
733 
734     /* Create the siginfo structure */
735     info.si_signo = sig;
736     info.si_code = SI_TIMER;
737     info.si_value.sival_ptr = arg->sigev_value.sival_ptr;
738 
739     /* Send signals to threads or processes */
740     if (arg->tid > 0) {
741         /* Make sure that the para is valid */
742         OS_GOTO_EXIT_IF(OS_TID_CHECK_INVALID(arg->tid), EINVAL);
743         stcb = OsGetTaskCB(arg->tid);
744         ret = OsUserProcessOperatePermissionsCheck(stcb, stcb->processID);
745         OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
746 
747         /* Dispatch the signal to thread, bypassing normal task group thread
748          * dispatch rules. */
749         SCHEDULER_LOCK(intSave);
750         ret = OsTcbDispatch(stcb, &info);
751         SCHEDULER_UNLOCK(intSave);
752         OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
753     } else {
754         /* Make sure that the para is valid */
755         OS_GOTO_EXIT_IF(pid <= 0 || OS_PID_CHECK_INVALID(pid), EINVAL);
756         /* Dispatch the signal to process */
757         SCHEDULER_LOCK(intSave);
758         OsDispatch(pid, &info, OS_USER_KILL_PERMISSION);
759         SCHEDULER_UNLOCK(intSave);
760     }
761     return;
762 EXIT:
763     PRINT_ERR("Dispatch signals failed!, ret: %d\r\n", ret);
764     return;
765 }
766 
OsTimerCreate(clockid_t clockID,struct ksigevent * evp,timer_t * timerID)767 int OsTimerCreate(clockid_t clockID, struct ksigevent *evp, timer_t *timerID)
768 {
769     UINT32 ret;
770     UINT16 swtmrID;
771     swtmr_proc_arg *arg = NULL;
772     int signo;
773 #ifdef LOSCFG_SECURITY_VID
774     UINT16 vid;
775 #endif
776 
777     if ((clockID != CLOCK_REALTIME) || (timerID == NULL)) {
778         errno = EINVAL;
779         return -1;
780     }
781 
782     signo = evp ? evp->sigev_signo : SIGALRM;
783     if (signo > SIGRTMAX || signo < 1) {
784         errno = EINVAL;
785         return -1;
786     }
787     if (evp && (evp->sigev_notify != SIGEV_SIGNAL && evp->sigev_notify != SIGEV_THREAD_ID)) {
788         errno = ENOTSUP;
789         return -1;
790     }
791 
792     arg = (swtmr_proc_arg *)malloc(sizeof(swtmr_proc_arg));
793     if (arg == NULL) {
794         errno = ENOMEM;
795         return -1;
796     }
797 
798     arg->tid = evp ? evp->sigev_tid : 0;
799     arg->sigev_signo = signo;
800     arg->pid = LOS_GetCurrProcessID();
801     arg->sigev_value.sival_ptr = evp ? evp->sigev_value.sival_ptr : NULL;
802     ret = LOS_SwtmrCreate(1, LOS_SWTMR_MODE_ONCE, SwtmrProc, &swtmrID, (UINTPTR)arg);
803     if (ret != LOS_OK) {
804         errno = (ret == LOS_ERRNO_SWTMR_MAXSIZE) ? EAGAIN : EINVAL;
805         free(arg);
806         return -1;
807     }
808 
809 #ifdef LOSCFG_SECURITY_VID
810     vid = AddNodeByRid(swtmrID);
811     if (vid == MAX_INVALID_TIMER_VID) {
812         free(arg);
813         (VOID)LOS_SwtmrDelete(swtmrID);
814         return -1;
815     }
816     swtmrID = vid;
817 #endif
818     *timerID = (timer_t)(UINTPTR)swtmrID;
819     return 0;
820 }
821 
timer_delete(timer_t timerID)822 int timer_delete(timer_t timerID)
823 {
824     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
825     VOID *arg = NULL;
826 
827 #ifdef LOSCFG_SECURITY_VID
828     swtmrID = GetRidByVid(swtmrID);
829 #endif
830     if (OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
831         goto ERROUT;
832     }
833 
834     arg = (VOID *)OS_SWT_FROM_SID(swtmrID)->uwArg;
835     if (LOS_SwtmrDelete(swtmrID)) {
836         goto ERROUT;
837     }
838     if (arg != NULL) {
839         free(arg);
840     }
841 
842 #ifdef LOSCFG_SECURITY_VID
843     RemoveNodeByVid((UINT16)(UINTPTR)timerID);
844 #endif
845     return 0;
846 
847 ERROUT:
848     errno = EINVAL;
849     return -1;
850 }
851 
timer_settime(timer_t timerID,int flags,const struct itimerspec * value,struct itimerspec * oldValue)852 int timer_settime(timer_t timerID, int flags,
853                   const struct itimerspec *value,   /* new value */
854                   struct itimerspec *oldValue)      /* old value to return, always 0 */
855 {
856     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
857     SWTMR_CTRL_S *swtmr = NULL;
858     UINT32 interval, expiry, ret;
859     UINT32 intSave;
860 
861     if (flags != 0) {
862         /* flags not supported currently */
863         errno = ENOSYS;
864         return -1;
865     }
866 
867 #ifdef LOSCFG_SECURITY_VID
868     swtmrID = GetRidByVid(swtmrID);
869 #endif
870     if ((value == NULL) || OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
871         errno = EINVAL;
872         return -1;
873     }
874 
875     if (!ValidTimeSpec(&value->it_value) || !ValidTimeSpec(&value->it_interval)) {
876         errno = EINVAL;
877         return -1;
878     }
879 
880     if (oldValue) {
881         (VOID)timer_gettime(timerID, oldValue);
882     }
883 
884     swtmr = OS_SWT_FROM_SID(swtmrID);
885     ret = LOS_SwtmrStop(swtmr->usTimerID);
886     if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) {
887         errno = EINVAL;
888         return -1;
889     }
890 
891     expiry = OsTimeSpec2Tick(&value->it_value);
892     interval = OsTimeSpec2Tick(&value->it_interval);
893 
894     LOS_SpinLockSave(&g_swtmrSpin, &intSave);
895     swtmr->ucMode = interval ? LOS_SWTMR_MODE_OPP : LOS_SWTMR_MODE_NO_SELFDELETE;
896     swtmr->uwExpiry = expiry + !!expiry; // PS: skip the first tick because it is NOT a full tick.
897     swtmr->uwInterval = interval;
898     swtmr->uwOverrun = 0;
899     LOS_SpinUnlockRestore(&g_swtmrSpin, intSave);
900 
901     if ((value->it_value.tv_sec == 0) && (value->it_value.tv_nsec == 0)) {
902         /*
903          * 1) when expiry is 0, means timer should be stopped.
904          * 2) If timer is ticking, stopping timer is already done before.
905          * 3) If timer is created but not ticking, return 0 as well.
906          */
907         return 0;
908     }
909 
910     if (LOS_SwtmrStart(swtmr->usTimerID)) {
911         errno = EINVAL;
912         return -1;
913     }
914 
915     return 0;
916 }
917 
timer_gettime(timer_t timerID,struct itimerspec * value)918 int timer_gettime(timer_t timerID, struct itimerspec *value)
919 {
920     UINT32 tick = 0;
921     SWTMR_CTRL_S *swtmr = NULL;
922     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
923     UINT32 ret;
924 
925 #ifdef LOSCFG_SECURITY_VID
926     swtmrID = GetRidByVid(swtmrID);
927 #endif
928     if ((value == NULL) || !ValidTimerID(swtmrID)) {
929         errno = EINVAL;
930         return -1;
931     }
932 
933     swtmr = OS_SWT_FROM_SID(swtmrID);
934 
935     /* get expire time */
936     ret = LOS_SwtmrTimeGet(swtmr->usTimerID, &tick);
937     if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) {
938         errno = EINVAL;
939         return -1;
940     }
941 
942     OsTick2TimeSpec(&value->it_value, tick);
943     OsTick2TimeSpec(&value->it_interval, (swtmr->ucMode == LOS_SWTMR_MODE_ONCE) ? 0 : swtmr->uwInterval);
944     return 0;
945 }
946 
timer_getoverrun(timer_t timerID)947 int timer_getoverrun(timer_t timerID)
948 {
949     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
950     SWTMR_CTRL_S *swtmr = NULL;
951     INT32 overRun;
952 
953 #ifdef LOSCFG_SECURITY_VID
954     swtmrID = GetRidByVid(swtmrID);
955 #endif
956     if (!ValidTimerID(swtmrID)) {
957         errno = EINVAL;
958         return -1;
959     }
960 
961     swtmr = OS_SWT_FROM_SID(swtmrID);
962     if (swtmr->usTimerID >= OS_SWTMR_MAX_TIMERID) {
963         errno = EINVAL;
964         return -1;
965     }
966 
967     overRun = (INT32)(swtmr->uwOverrun);
968     return (overRun > DELAYTIMER_MAX) ? DELAYTIMER_MAX : overRun;
969 }
970 
DoNanoSleep(UINT64 nanoseconds)971 STATIC INT32 DoNanoSleep(UINT64 nanoseconds)
972 {
973     UINT32 ret;
974 
975     ret = LOS_TaskDelay(OsNS2Tick(nanoseconds));
976     if (ret == LOS_OK || ret == LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK) {
977         return 0;
978     }
979     return -1;
980 }
981 
usleep(unsigned useconds)982 int usleep(unsigned useconds)
983 {
984     return DoNanoSleep((UINT64)useconds * OS_SYS_NS_PER_US);
985 }
986 
nanosleep(const struct timespec * rqtp,struct timespec * rmtp)987 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
988 {
989     UINT64 nanoseconds;
990     INT32 ret = -1;
991 
992     (VOID)rmtp;
993     /* expire time */
994 
995     if (!ValidTimeSpec(rqtp)) {
996         errno = EINVAL;
997         return ret;
998     }
999 
1000     nanoseconds = (UINT64)rqtp->tv_sec * OS_SYS_NS_PER_SECOND + rqtp->tv_nsec;
1001 
1002     return DoNanoSleep(nanoseconds);
1003 }
1004 
sleep(unsigned int seconds)1005 unsigned int sleep(unsigned int seconds)
1006 {
1007     return DoNanoSleep((UINT64)seconds * OS_SYS_NS_PER_SECOND);
1008 }
1009 
difftime(time_t time2,time_t time1)1010 double difftime(time_t time2, time_t time1)
1011 {
1012     return (double)(time2 - time1);
1013 }
1014 
clock(VOID)1015 clock_t clock(VOID)
1016 {
1017     clock_t clockMsec;
1018     UINT64 nowNsec;
1019 
1020     nowNsec = LOS_CurrNanosec();
1021     clockMsec = (clock_t)(nowNsec / (OS_SYS_NS_PER_SECOND / CLOCKS_PER_SEC));
1022 
1023     return clockMsec;
1024 }
1025 
times(struct tms * buf)1026 clock_t times(struct tms *buf)
1027 {
1028     clock_t clockTick = -1;
1029 
1030     (void)buf;
1031     set_errno(ENOSYS);
1032 
1033     return clockTick;
1034 }
1035 
setitimer(int which,const struct itimerval * value,struct itimerval * ovalue)1036 int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
1037 {
1038     UINT32 intSave;
1039     LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
1040     LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
1041     timer_t timerID = 0;
1042     struct itimerspec spec;
1043     struct itimerspec ospec;
1044     int ret = LOS_OK;
1045 
1046     /* we only support the realtime clock timer currently */
1047     if (which != ITIMER_REAL || !value) {
1048         set_errno(EINVAL);
1049         return -1;
1050     }
1051 
1052     /* To avoid creating an invalid timer after the timer has already been create */
1053     if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1054         ret = OsTimerCreate(CLOCK_REALTIME, NULL, &timerID);
1055         if (ret != LOS_OK) {
1056             return ret;
1057         }
1058     }
1059 
1060     /* The initialization of this global timer must be in spinlock
1061      * OsTimerCreate cannot be located in spinlock.
1062      */
1063     SCHEDULER_LOCK(intSave);
1064     if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1065         processCB->timerID = timerID;
1066         SCHEDULER_UNLOCK(intSave);
1067     } else {
1068         SCHEDULER_UNLOCK(intSave);
1069         if (timerID) {
1070             timer_delete(timerID);
1071         }
1072     }
1073 
1074     if (!ValidTimeval(&value->it_value) || !ValidTimeval(&value->it_interval)) {
1075         set_errno(EINVAL);
1076         return -1;
1077     }
1078 
1079     TIMEVAL_TO_TIMESPEC(&value->it_value, &spec.it_value);
1080     TIMEVAL_TO_TIMESPEC(&value->it_interval, &spec.it_interval);
1081 
1082     ret = timer_settime(processCB->timerID, 0, &spec, ovalue ? &ospec : NULL);
1083     if (ret == LOS_OK && ovalue) {
1084         TIMESPEC_TO_TIMEVAL(&ovalue->it_value, &ospec.it_value);
1085         TIMESPEC_TO_TIMEVAL(&ovalue->it_interval, &ospec.it_interval);
1086     }
1087 
1088     return ret;
1089 }
1090 
getitimer(int which,struct itimerval * value)1091 int getitimer(int which, struct itimerval *value)
1092 {
1093     LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
1094     LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
1095     struct itimerspec spec = {};
1096 
1097     int ret = LOS_OK;
1098 
1099     /* we only support the realtime clock timer currently */
1100     if (which != ITIMER_REAL || !value) {
1101         set_errno(EINVAL);
1102         return -1;
1103     }
1104 
1105     if (processCB->timerID != (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1106         ret = timer_gettime(processCB->timerID, &spec);
1107     }
1108 
1109     if (ret == LOS_OK) {
1110         TIMESPEC_TO_TIMEVAL(&value->it_value, &spec.it_value);
1111         TIMESPEC_TO_TIMEVAL(&value->it_interval, &spec.it_interval);
1112     }
1113 
1114     return ret;
1115 }
1116 
1117 #ifdef LOSCFG_KERNEL_VDSO
OsVdsoTimeGet(VdsoDataPage * vdsoDataPage)1118 VOID OsVdsoTimeGet(VdsoDataPage *vdsoDataPage)
1119 {
1120     UINT32 intSave;
1121     struct timespec64 tmp = {0};
1122     struct timespec64 hwTime = {0};
1123 
1124     if (vdsoDataPage == NULL) {
1125         return;
1126     }
1127 
1128     OsGetHwTime(&hwTime);
1129 
1130     LOS_SpinLockSave(&g_timeSpin, &intSave);
1131     tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
1132     vdsoDataPage->monoTimeSec = tmp.tv_sec;
1133     vdsoDataPage->monoTimeNsec = tmp.tv_nsec;
1134 
1135     tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
1136     vdsoDataPage->realTimeSec = tmp.tv_sec;
1137     vdsoDataPage->realTimeNsec = tmp.tv_nsec;
1138     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
1139 }
1140 #endif
1141 
time(time_t * t)1142 time_t time(time_t *t)
1143 {
1144     struct timeval tp;
1145     int ret;
1146 
1147     /* Get the current time from the system */
1148     ret = gettimeofday(&tp, (struct timezone *)NULL);
1149     if (ret == LOS_OK) {
1150         /* Return the seconds since the epoch */
1151         if (t) {
1152             *t = tp.tv_sec;
1153         }
1154         return tp.tv_sec;
1155     }
1156     return (time_t)OS_ERROR;
1157 }
1158