• 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     runtime = spcb->processCpup.allTime;
513     SCHEDULER_UNLOCK(intSave);
514 
515     ats->tv_sec = runtime / OS_SYS_NS_PER_SECOND;
516     ats->tv_nsec = runtime % OS_SYS_NS_PER_SECOND;
517 
518     return 0;
519 }
520 
GetCputime(clockid_t clockID,struct timespec * tp)521 static int GetCputime(clockid_t clockID, struct timespec *tp)
522 {
523     int ret;
524 
525     if (clockID >= 0) {
526         return -EINVAL;
527     }
528 
529     if ((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK) {
530         ret = PthreadGetCputime(clockID, tp);
531     } else {
532         ret = ProcessGetCputime(clockID, tp);
533     }
534 
535     return ret;
536 }
537 
CheckClock(const clockid_t clockID)538 static int CheckClock(const clockid_t clockID)
539 {
540     int error = 0;
541     const pid_t pid = GetPidFromClockID(clockID);
542 
543     if (!((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK)) {
544         LosProcessCB *spcb = NULL;
545         if (OsProcessIDUserCheckInvalid(pid) || pid < 0) {
546             return -EINVAL;
547         }
548         spcb = OS_PCB_FROM_PID(pid);
549         if (OsProcessIsUnused(spcb)) {
550             error = -EINVAL;
551         }
552     } else {
553         error = -EINVAL;
554     }
555 
556     return error;
557 }
558 
CpuClockGetres(const clockid_t clockID,struct timespec * tp)559 static int CpuClockGetres(const clockid_t clockID, struct timespec *tp)
560 {
561     if (clockID > 0) {
562         return -EINVAL;
563     }
564 
565     int error = CheckClock(clockID);
566     if (!error) {
567         error = ProcessGetCputime(clockID, tp);
568     }
569 
570     return error;
571 }
572 #endif
573 
clock_gettime(clockid_t clockID,struct timespec * tp)574 int clock_gettime(clockid_t clockID, struct timespec *tp)
575 {
576     UINT32 intSave;
577     struct timespec64 tmp = {0};
578     struct timespec64 hwTime = {0};
579 
580     if (clockID > MAX_CLOCKS) {
581         goto ERROUT;
582     }
583 
584     if (tp == NULL) {
585         goto ERROUT;
586     }
587 
588     OsGetHwTime(&hwTime);
589 
590     switch (clockID) {
591         case CLOCK_MONOTONIC_RAW:
592             tp->tv_sec = hwTime.tv_sec;
593             tp->tv_nsec = hwTime.tv_nsec;
594             break;
595         case CLOCK_MONOTONIC:
596             LOS_SpinLockSave(&g_timeSpin, &intSave);
597             tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
598             LOS_SpinUnlockRestore(&g_timeSpin, intSave);
599             tp->tv_sec = tmp.tv_sec;
600             tp->tv_nsec = tmp.tv_nsec;
601             break;
602         case CLOCK_REALTIME:
603             LOS_SpinLockSave(&g_timeSpin, &intSave);
604             tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
605             tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
606             LOS_SpinUnlockRestore(&g_timeSpin, intSave);
607             tp->tv_sec = tmp.tv_sec;
608             tp->tv_nsec = tmp.tv_nsec;
609             break;
610         case CLOCK_MONOTONIC_COARSE:
611         case CLOCK_REALTIME_COARSE:
612         case CLOCK_THREAD_CPUTIME_ID:
613         case CLOCK_PROCESS_CPUTIME_ID:
614         case CLOCK_BOOTTIME:
615         case CLOCK_REALTIME_ALARM:
616         case CLOCK_BOOTTIME_ALARM:
617         case CLOCK_TAI:
618             TIME_RETURN(ENOTSUP);
619         default:
620         {
621 #ifdef LOSCFG_KERNEL_CPUP
622             int ret = GetCputime(clockID, tp);
623                 TIME_RETURN(-ret);
624 #else
625             TIME_RETURN(EINVAL);
626 #endif
627         }
628     }
629 
630     return 0;
631 
632     ERROUT:
633     TIME_RETURN(EINVAL);
634 }
635 
clock_getres(clockid_t clockID,struct timespec * tp)636 int clock_getres(clockid_t clockID, struct timespec *tp)
637 {
638     if (tp == NULL) {
639         TIME_RETURN(EINVAL);
640     }
641 
642     switch (clockID) {
643         case CLOCK_MONOTONIC_RAW:
644         case CLOCK_MONOTONIC:
645         case CLOCK_REALTIME:
646             /* the accessable rtc resolution */
647             tp->tv_nsec = OS_SYS_NS_PER_US; /* the precision of clock_gettime is 1us */
648             tp->tv_sec = 0;
649             break;
650         case CLOCK_MONOTONIC_COARSE:
651         case CLOCK_REALTIME_COARSE:
652             /* the clock coarse resolution, supported by vdso.
653              * the precision of clock_gettime is 1tick */
654             tp->tv_nsec = OS_SYS_NS_PER_SECOND / LOSCFG_BASE_CORE_TICK_PER_SECOND;
655             tp->tv_sec = 0;
656             break;
657         case CLOCK_THREAD_CPUTIME_ID:
658         case CLOCK_PROCESS_CPUTIME_ID:
659         case CLOCK_BOOTTIME:
660         case CLOCK_REALTIME_ALARM:
661         case CLOCK_BOOTTIME_ALARM:
662         case CLOCK_TAI:
663             TIME_RETURN(ENOTSUP);
664         default:
665 #ifdef LOSCFG_KERNEL_CPUP
666             {
667                 int ret = CpuClockGetres(clockID, tp);
668                 TIME_RETURN(-ret);
669             }
670 #else
671             TIME_RETURN(EINVAL);
672 #endif
673     }
674 
675     TIME_RETURN(0);
676 }
677 
clock_nanosleep(clockid_t clk,int flags,const struct timespec * req,struct timespec * rem)678 int clock_nanosleep(clockid_t clk, int flags, const struct timespec *req, struct timespec *rem)
679 {
680     switch (clk) {
681         case CLOCK_REALTIME:
682             if (flags == 0) {
683                 /* we only support the realtime clock currently */
684                 return nanosleep(req, rem);
685             }
686             /* fallthrough */
687         case CLOCK_MONOTONIC_COARSE:
688         case CLOCK_REALTIME_COARSE:
689         case CLOCK_MONOTONIC_RAW:
690         case CLOCK_MONOTONIC:
691         case CLOCK_PROCESS_CPUTIME_ID:
692         case CLOCK_BOOTTIME:
693         case CLOCK_REALTIME_ALARM:
694         case CLOCK_BOOTTIME_ALARM:
695         case CLOCK_TAI:
696             if (flags == 0 || flags == TIMER_ABSTIME) {
697                 TIME_RETURN(ENOTSUP);
698             }
699             /* fallthrough */
700         case CLOCK_THREAD_CPUTIME_ID:
701         default:
702             TIME_RETURN(EINVAL);
703     }
704 
705     TIME_RETURN(0);
706 }
707 
708 typedef struct {
709     int sigev_signo;
710     pid_t pid;
711     unsigned int tid;
712     union sigval sigev_value;
713 } swtmr_proc_arg;
714 
SwtmrProc(UINTPTR tmrArg)715 static VOID SwtmrProc(UINTPTR tmrArg)
716 {
717     INT32 sig, ret;
718     UINT32 intSave;
719     pid_t pid;
720     siginfo_t info;
721     LosTaskCB *stcb = NULL;
722 
723     swtmr_proc_arg *arg = (swtmr_proc_arg *)tmrArg;
724     OS_GOTO_EXIT_IF(arg == NULL, EINVAL);
725 
726     sig = arg->sigev_signo;
727     pid = arg->pid;
728     OS_GOTO_EXIT_IF(!GOOD_SIGNO(sig), EINVAL);
729 
730     /* Create the siginfo structure */
731     info.si_signo = sig;
732     info.si_code = SI_TIMER;
733     info.si_value.sival_ptr = arg->sigev_value.sival_ptr;
734 
735     /* Send signals to threads or processes */
736     if (arg->tid > 0) {
737         /* Make sure that the para is valid */
738         OS_GOTO_EXIT_IF(OS_TID_CHECK_INVALID(arg->tid), EINVAL);
739         stcb = OsGetTaskCB(arg->tid);
740         ret = OsUserProcessOperatePermissionsCheck(stcb, stcb->processID);
741         OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
742 
743         /* Dispatch the signal to thread, bypassing normal task group thread
744          * dispatch rules. */
745         SCHEDULER_LOCK(intSave);
746         ret = OsTcbDispatch(stcb, &info);
747         SCHEDULER_UNLOCK(intSave);
748         OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
749     } else {
750         /* Make sure that the para is valid */
751         OS_GOTO_EXIT_IF(pid <= 0 || OS_PID_CHECK_INVALID(pid), EINVAL);
752         /* Dispatch the signal to process */
753         SCHEDULER_LOCK(intSave);
754         OsDispatch(pid, &info, OS_USER_KILL_PERMISSION);
755         SCHEDULER_UNLOCK(intSave);
756     }
757     return;
758 EXIT:
759     PRINT_ERR("Dsipatch signals failed!, ret: %d\r\n", ret);
760     return;
761 }
762 
OsTimerCreate(clockid_t clockID,struct ksigevent * evp,timer_t * timerID)763 int OsTimerCreate(clockid_t clockID, struct ksigevent *evp, timer_t *timerID)
764 {
765     UINT32 ret;
766     UINT16 swtmrID;
767     swtmr_proc_arg *arg = NULL;
768     int signo;
769 #ifdef LOSCFG_SECURITY_VID
770     UINT16 vid;
771 #endif
772 
773     if ((clockID != CLOCK_REALTIME) || (timerID == NULL)) {
774         errno = EINVAL;
775         return -1;
776     }
777 
778     signo = evp ? evp->sigev_signo : SIGALRM;
779     if (signo > SIGRTMAX || signo < 1) {
780         errno = EINVAL;
781         return -1;
782     }
783     if (evp && (evp->sigev_notify != SIGEV_SIGNAL && evp->sigev_notify != SIGEV_THREAD_ID)) {
784         errno = ENOTSUP;
785         return -1;
786     }
787 
788     arg = (swtmr_proc_arg *)malloc(sizeof(swtmr_proc_arg));
789     if (arg == NULL) {
790         errno = ENOMEM;
791         return -1;
792     }
793 
794     arg->tid = evp ? evp->sigev_tid : 0;
795     arg->sigev_signo = signo;
796     arg->pid = LOS_GetCurrProcessID();
797     arg->sigev_value.sival_ptr = evp ? evp->sigev_value.sival_ptr : NULL;
798     ret = LOS_SwtmrCreate(1, LOS_SWTMR_MODE_ONCE, SwtmrProc, &swtmrID, (UINTPTR)arg);
799     if (ret != LOS_OK) {
800         errno = (ret == LOS_ERRNO_SWTMR_MAXSIZE) ? EAGAIN : EINVAL;
801         free(arg);
802         return -1;
803     }
804 
805 #ifdef LOSCFG_SECURITY_VID
806     vid = AddNodeByRid(swtmrID);
807     if (vid == MAX_INVALID_TIMER_VID) {
808         free(arg);
809         (VOID)LOS_SwtmrDelete(swtmrID);
810         return -1;
811     }
812     swtmrID = vid;
813 #endif
814     *timerID = (timer_t)(UINTPTR)swtmrID;
815     return 0;
816 }
817 
timer_delete(timer_t timerID)818 int timer_delete(timer_t timerID)
819 {
820     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
821     VOID *arg = NULL;
822 
823 #ifdef LOSCFG_SECURITY_VID
824     swtmrID = GetRidByVid(swtmrID);
825 #endif
826     if (OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
827         goto ERROUT;
828     }
829 
830     arg = (VOID *)OS_SWT_FROM_SID(swtmrID)->uwArg;
831     if (LOS_SwtmrDelete(swtmrID)) {
832         goto ERROUT;
833     }
834     if (arg != NULL) {
835         free(arg);
836     }
837 
838 #ifdef LOSCFG_SECURITY_VID
839     RemoveNodeByVid((UINT16)(UINTPTR)timerID);
840 #endif
841     return 0;
842 
843 ERROUT:
844     errno = EINVAL;
845     return -1;
846 }
847 
timer_settime(timer_t timerID,int flags,const struct itimerspec * value,struct itimerspec * oldValue)848 int timer_settime(timer_t timerID, int flags,
849                   const struct itimerspec *value,   /* new value */
850                   struct itimerspec *oldValue)      /* old value to return, always 0 */
851 {
852     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
853     SWTMR_CTRL_S *swtmr = NULL;
854     UINT32 interval, expiry, ret;
855     UINT32 intSave;
856 
857     if (flags != 0) {
858         /* flags not supported currently */
859         errno = ENOSYS;
860         return -1;
861     }
862 
863 #ifdef LOSCFG_SECURITY_VID
864     swtmrID = GetRidByVid(swtmrID);
865 #endif
866     if ((value == NULL) || OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
867         errno = EINVAL;
868         return -1;
869     }
870 
871     if (!ValidTimeSpec(&value->it_value) || !ValidTimeSpec(&value->it_interval)) {
872         errno = EINVAL;
873         return -1;
874     }
875 
876     if (oldValue) {
877         (VOID)timer_gettime(timerID, oldValue);
878     }
879 
880     swtmr = OS_SWT_FROM_SID(swtmrID);
881     ret = LOS_SwtmrStop(swtmr->usTimerID);
882     if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) {
883         errno = EINVAL;
884         return -1;
885     }
886 
887     expiry = OsTimeSpec2Tick(&value->it_value);
888     interval = OsTimeSpec2Tick(&value->it_interval);
889 
890     LOS_SpinLockSave(&g_swtmrSpin, &intSave);
891     swtmr->ucMode = interval ? LOS_SWTMR_MODE_OPP : LOS_SWTMR_MODE_NO_SELFDELETE;
892     swtmr->uwExpiry = expiry + !!expiry; // PS: skip the first tick because it is NOT a full tick.
893     swtmr->uwInterval = interval;
894     swtmr->uwOverrun = 0;
895     LOS_SpinUnlockRestore(&g_swtmrSpin, intSave);
896 
897     if ((value->it_value.tv_sec == 0) && (value->it_value.tv_nsec == 0)) {
898         /*
899          * 1) when expiry is 0, means timer should be stopped.
900          * 2) If timer is ticking, stopping timer is already done before.
901          * 3) If timer is created but not ticking, return 0 as well.
902          */
903         return 0;
904     }
905 
906     if (LOS_SwtmrStart(swtmr->usTimerID)) {
907         errno = EINVAL;
908         return -1;
909     }
910 
911     return 0;
912 }
913 
timer_gettime(timer_t timerID,struct itimerspec * value)914 int timer_gettime(timer_t timerID, struct itimerspec *value)
915 {
916     UINT32 tick = 0;
917     SWTMR_CTRL_S *swtmr = NULL;
918     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
919     UINT32 ret;
920 
921 #ifdef LOSCFG_SECURITY_VID
922     swtmrID = GetRidByVid(swtmrID);
923 #endif
924     if ((value == NULL) || !ValidTimerID(swtmrID)) {
925         errno = EINVAL;
926         return -1;
927     }
928 
929     swtmr = OS_SWT_FROM_SID(swtmrID);
930 
931     /* get expire time */
932     ret = LOS_SwtmrTimeGet(swtmr->usTimerID, &tick);
933     if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) {
934         errno = EINVAL;
935         return -1;
936     }
937 
938     OsTick2TimeSpec(&value->it_value, tick);
939     OsTick2TimeSpec(&value->it_interval, (swtmr->ucMode == LOS_SWTMR_MODE_ONCE) ? 0 : swtmr->uwInterval);
940     return 0;
941 }
942 
timer_getoverrun(timer_t timerID)943 int timer_getoverrun(timer_t timerID)
944 {
945     UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
946     SWTMR_CTRL_S *swtmr = NULL;
947     INT32 overRun;
948 
949 #ifdef LOSCFG_SECURITY_VID
950     swtmrID = GetRidByVid(swtmrID);
951 #endif
952     if (!ValidTimerID(swtmrID)) {
953         errno = EINVAL;
954         return -1;
955     }
956 
957     swtmr = OS_SWT_FROM_SID(swtmrID);
958     if (swtmr->usTimerID >= OS_SWTMR_MAX_TIMERID) {
959         errno = EINVAL;
960         return -1;
961     }
962 
963     overRun = (INT32)(swtmr->uwOverrun);
964     return (overRun > DELAYTIMER_MAX) ? DELAYTIMER_MAX : overRun;
965 }
966 
DoNanoSleep(UINT64 nanoseconds)967 STATIC INT32 DoNanoSleep(UINT64 nanoseconds)
968 {
969     UINT32 ret;
970 
971     ret = LOS_TaskDelay(OsNS2Tick(nanoseconds));
972     if (ret == LOS_OK || ret == LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK) {
973         return 0;
974     }
975     return -1;
976 }
977 
usleep(unsigned useconds)978 int usleep(unsigned useconds)
979 {
980     return DoNanoSleep((UINT64)useconds * OS_SYS_NS_PER_US);
981 }
982 
nanosleep(const struct timespec * rqtp,struct timespec * rmtp)983 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
984 {
985     UINT64 nanoseconds;
986     INT32 ret = -1;
987 
988     (VOID)rmtp;
989     /* expire time */
990 
991     if (!ValidTimeSpec(rqtp)) {
992         errno = EINVAL;
993         return ret;
994     }
995 
996     nanoseconds = (UINT64)rqtp->tv_sec * OS_SYS_NS_PER_SECOND + rqtp->tv_nsec;
997 
998     return DoNanoSleep(nanoseconds);
999 }
1000 
sleep(unsigned int seconds)1001 unsigned int sleep(unsigned int seconds)
1002 {
1003     return DoNanoSleep((UINT64)seconds * OS_SYS_NS_PER_SECOND);
1004 }
1005 
difftime(time_t time2,time_t time1)1006 double difftime(time_t time2, time_t time1)
1007 {
1008     return (double)(time2 - time1);
1009 }
1010 
clock(VOID)1011 clock_t clock(VOID)
1012 {
1013     clock_t clockMsec;
1014     UINT64 nowNsec;
1015 
1016     nowNsec = LOS_CurrNanosec();
1017     clockMsec = (clock_t)(nowNsec / (OS_SYS_NS_PER_SECOND / CLOCKS_PER_SEC));
1018 
1019     return clockMsec;
1020 }
1021 
times(struct tms * buf)1022 clock_t times(struct tms *buf)
1023 {
1024     clock_t clockTick = -1;
1025 
1026     (void)buf;
1027     set_errno(ENOSYS);
1028 
1029     return clockTick;
1030 }
1031 
setitimer(int which,const struct itimerval * value,struct itimerval * ovalue)1032 int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
1033 {
1034     UINT32 intSave;
1035     LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
1036     LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
1037     timer_t timerID = 0;
1038     struct itimerspec spec;
1039     struct itimerspec ospec;
1040     int ret = LOS_OK;
1041 
1042     /* we only support the realtime clock timer currently */
1043     if (which != ITIMER_REAL || !value) {
1044         set_errno(EINVAL);
1045         return -1;
1046     }
1047 
1048     /* To avoid creating an invalid timer after the timer has already been create */
1049     if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1050         ret = OsTimerCreate(CLOCK_REALTIME, NULL, &timerID);
1051         if (ret != LOS_OK) {
1052             return ret;
1053         }
1054     }
1055 
1056     /* The initialization of this global timer must be in spinlock
1057      * OsTimerCreate cannot be located in spinlock.
1058      */
1059     SCHEDULER_LOCK(intSave);
1060     if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1061         processCB->timerID = timerID;
1062         SCHEDULER_UNLOCK(intSave);
1063     } else {
1064         SCHEDULER_UNLOCK(intSave);
1065         if (timerID) {
1066             timer_delete(timerID);
1067         }
1068     }
1069 
1070     if (!ValidTimeval(&value->it_value) || !ValidTimeval(&value->it_interval)) {
1071         set_errno(EINVAL);
1072         return -1;
1073     }
1074 
1075     TIMEVAL_TO_TIMESPEC(&value->it_value, &spec.it_value);
1076     TIMEVAL_TO_TIMESPEC(&value->it_interval, &spec.it_interval);
1077 
1078     ret = timer_settime(processCB->timerID, 0, &spec, ovalue ? &ospec : NULL);
1079     if (ret == LOS_OK && ovalue) {
1080         TIMESPEC_TO_TIMEVAL(&ovalue->it_value, &ospec.it_value);
1081         TIMESPEC_TO_TIMEVAL(&ovalue->it_interval, &ospec.it_interval);
1082     }
1083 
1084     return ret;
1085 }
1086 
getitimer(int which,struct itimerval * value)1087 int getitimer(int which, struct itimerval *value)
1088 {
1089     LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
1090     LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
1091     struct itimerspec spec = {};
1092 
1093     int ret = LOS_OK;
1094 
1095     /* we only support the realtime clock timer currently */
1096     if (which != ITIMER_REAL || !value) {
1097         set_errno(EINVAL);
1098         return -1;
1099     }
1100 
1101     if (processCB->timerID != (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
1102         ret = timer_gettime(processCB->timerID, &spec);
1103     }
1104 
1105     if (ret == LOS_OK) {
1106         TIMESPEC_TO_TIMEVAL(&value->it_value, &spec.it_value);
1107         TIMESPEC_TO_TIMEVAL(&value->it_interval, &spec.it_interval);
1108     }
1109 
1110     return ret;
1111 }
1112 
1113 #ifdef LOSCFG_KERNEL_VDSO
OsVdsoTimeGet(VdsoDataPage * vdsoDataPage)1114 VOID OsVdsoTimeGet(VdsoDataPage *vdsoDataPage)
1115 {
1116     UINT32 intSave;
1117     struct timespec64 tmp = {0};
1118     struct timespec64 hwTime = {0};
1119 
1120     if (vdsoDataPage == NULL) {
1121         return;
1122     }
1123 
1124     OsGetHwTime(&hwTime);
1125 
1126     LOS_SpinLockSave(&g_timeSpin, &intSave);
1127     tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
1128     vdsoDataPage->monoTimeSec = tmp.tv_sec;
1129     vdsoDataPage->monoTimeNsec = tmp.tv_nsec;
1130 
1131     tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
1132     vdsoDataPage->realTimeSec = tmp.tv_sec;
1133     vdsoDataPage->realTimeNsec = tmp.tv_nsec;
1134     LOS_SpinUnlockRestore(&g_timeSpin, intSave);
1135 }
1136 #endif
1137 
time(time_t * t)1138 time_t time(time_t *t)
1139 {
1140     struct timeval tp;
1141     int ret;
1142 
1143     /* Get the current time from the system */
1144     ret = gettimeofday(&tp, (struct timezone *)NULL);
1145     if (ret == LOS_OK) {
1146         /* Return the seconds since the epoch */
1147         if (t) {
1148             *t = tp.tv_sec;
1149         }
1150         return tp.tv_sec;
1151     }
1152     return (time_t)OS_ERROR;
1153 }
1154