ctime.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2019-08-21 zhangjun copy from minilibc
  9. * 2020-09-07 Meco Man combine gcc armcc iccarm
  10. * 2021-02-05 Meco Man add timegm()
  11. * 2021-02-07 Meco Man fixed gettimeofday()
  12. * 2021-02-08 Meco Man add settimeofday() stime()
  13. * 2021-02-10 Meco Man add ctime_r() and re-implement ctime()
  14. * 2021-02-11 Meco Man fix bug #3183 - align days[] and months[] to 4 bytes
  15. * 2021-02-12 Meco Man add errno
  16. * 2012-12-08 Bernard <clock_time.c> fix the issue of _timevalue.tv_usec initialization,
  17. * which found by Rob <rdent@iinet.net.au>
  18. * 2021-02-12 Meco Man move all of the functions located in <clock_time.c> to this file
  19. * 2021-03-15 Meco Man fixed a bug of leaking memory in asctime()
  20. * 2021-05-01 Meco Man support fixed timezone
  21. * 2021-07-21 Meco Man implement that change/set timezone APIs
  22. * 2023-07-03 xqyjlj refactor posix time and timer
  23. * 2023-07-16 Shell update signal generation routine for lwp
  24. * adapt to new api and do the signal handling in thread context
  25. * 2023-08-12 Meco Man re-implement RT-Thread lightweight timezone API
  26. * 2023-09-15 xqyjlj perf rt_hw_interrupt_disable/enable
  27. * 2023-10-23 Shell add lock for _g_timerid
  28. * 2023-11-16 Shell Fixup of nanosleep if previous call was interrupted
  29. */
  30. #include "sys/time.h"
  31. #include <rthw.h>
  32. #include <rtdevice.h>
  33. #include <drivers/rtc.h>
  34. #include <sys/errno.h>
  35. #include <unistd.h>
  36. #ifdef RT_USING_SMART
  37. #include <lwp.h>
  38. #endif
  39. #ifdef RT_USING_POSIX_DELAY
  40. #include <delay.h>
  41. #endif
  42. #ifdef RT_USING_KTIME
  43. #include <ktime.h>
  44. #endif
  45. #define DBG_TAG "time"
  46. #define DBG_LVL DBG_INFO
  47. #include <rtdbg.h>
  48. #define _WARNING_NO_RTC "Cannot find a RTC device!"
  49. /* days per month -- nonleap! */
  50. static const short __spm[13] =
  51. {
  52. 0,
  53. (31),
  54. (31 + 28),
  55. (31 + 28 + 31),
  56. (31 + 28 + 31 + 30),
  57. (31 + 28 + 31 + 30 + 31),
  58. (31 + 28 + 31 + 30 + 31 + 30),
  59. (31 + 28 + 31 + 30 + 31 + 30 + 31),
  60. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31),
  61. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30),
  62. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31),
  63. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30),
  64. (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31),
  65. };
  66. rt_align(RT_ALIGN_SIZE) static const char *days = "Sun Mon Tue Wed Thu Fri Sat ";
  67. rt_align(RT_ALIGN_SIZE) static const char *months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ";
  68. #ifndef __isleap
  69. static int __isleap(int year)
  70. {
  71. /* every fourth year is a leap year except for century years that are
  72. * not divisible by 400. */
  73. /* return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); */
  74. return (!(year % 4) && ((year % 100) || !(year % 400)));
  75. }
  76. #endif
  77. static void num2str(char *c, int i)
  78. {
  79. c[0] = i / 10 + '0';
  80. c[1] = i % 10 + '0';
  81. }
  82. static rt_err_t _control_rtc(int cmd, void *arg)
  83. {
  84. #ifdef RT_USING_RTC
  85. static rt_device_t device = RT_NULL;
  86. rt_err_t rst = -RT_ERROR;
  87. if (device == RT_NULL)
  88. {
  89. device = rt_device_find("rtc");
  90. }
  91. /* read timestamp from RTC device */
  92. if (device != RT_NULL)
  93. {
  94. if (rt_device_open(device, 0) == RT_EOK)
  95. {
  96. rst = rt_device_control(device, cmd, arg);
  97. rt_device_close(device);
  98. }
  99. }
  100. else
  101. {
  102. LOG_W(_WARNING_NO_RTC);
  103. return -RT_ENOSYS;
  104. }
  105. return rst;
  106. #else
  107. LOG_W(_WARNING_NO_RTC);
  108. return -RT_ENOSYS;
  109. #endif /* RT_USING_RTC */
  110. }
  111. /* lightweight timezone and daylight saving time */
  112. #ifdef RT_LIBC_USING_LIGHT_TZ_DST
  113. #ifndef RT_LIBC_TZ_DEFAULT_HOUR
  114. #define RT_LIBC_TZ_DEFAULT_HOUR (8U)
  115. #endif /* RT_LIBC_TZ_DEFAULT_HOUR */
  116. #ifndef RT_LIBC_TZ_DEFAULT_MIN
  117. #define RT_LIBC_TZ_DEFAULT_MIN (0U)
  118. #endif /* RT_LIBC_TZ_DEFAULT_MIN */
  119. #ifndef RT_LIBC_TZ_DEFAULT_SEC
  120. #define RT_LIBC_TZ_DEFAULT_SEC (0U)
  121. #endif /* RT_LIBC_TZ_DEFAULT_SEC */
  122. static volatile int32_t _current_tz_offset_sec = \
  123. RT_LIBC_TZ_DEFAULT_HOUR * 3600U + RT_LIBC_TZ_DEFAULT_MIN * 60U + RT_LIBC_TZ_DEFAULT_SEC;
  124. /* return current timezone offset in seconds */
  125. void rt_tz_set(int32_t offset_sec)
  126. {
  127. _current_tz_offset_sec = offset_sec;
  128. }
  129. int32_t rt_tz_get(void)
  130. {
  131. return _current_tz_offset_sec;
  132. }
  133. int8_t rt_tz_is_dst(void)
  134. {
  135. return 0U; /* TODO */
  136. }
  137. #endif /* RT_LIBC_USING_LIGHT_TZ_DST */
  138. struct tm *gmtime_r(const time_t *timep, struct tm *r)
  139. {
  140. int i;
  141. int work;
  142. if(timep == RT_NULL || r == RT_NULL)
  143. {
  144. rt_set_errno(EFAULT);
  145. return RT_NULL;
  146. }
  147. rt_memset(r, RT_NULL, sizeof(struct tm));
  148. work = *timep % (24*60*60);
  149. r->tm_sec = work % 60;
  150. work /= 60;
  151. r->tm_min = work % 60;
  152. r->tm_hour = work / 60;
  153. work = (int)(*timep / (24*60*60));
  154. r->tm_wday = (4 + work) % 7;
  155. for (i = 1970;; ++i)
  156. {
  157. int k = __isleap(i) ? 366 : 365;
  158. if (work >= k)
  159. work -= k;
  160. else
  161. break;
  162. }
  163. r->tm_year = i - 1900;
  164. r->tm_yday = work;
  165. r->tm_mday = 1;
  166. if (__isleap(i) && (work > 58))
  167. {
  168. if (work == 59)
  169. r->tm_mday = 2; /* 29.2. */
  170. work -= 1;
  171. }
  172. for (i = 11; i && (__spm[i] > work); --i);
  173. r->tm_mon = i;
  174. r->tm_mday += work - __spm[i];
  175. #if defined(RT_LIBC_USING_LIGHT_TZ_DST)
  176. r->tm_isdst = rt_tz_is_dst();
  177. #else
  178. r->tm_isdst = 0U;
  179. #endif /* RT_LIBC_USING_LIGHT_TZ_DST */
  180. return r;
  181. }
  182. RTM_EXPORT(gmtime_r);
  183. struct tm* gmtime(const time_t* t)
  184. {
  185. static struct tm tmp;
  186. return gmtime_r(t, &tmp);
  187. }
  188. RTM_EXPORT(gmtime);
  189. struct tm* localtime_r(const time_t* t, struct tm* r)
  190. {
  191. time_t local_tz;
  192. #if defined(RT_LIBC_USING_LIGHT_TZ_DST)
  193. local_tz = *t + rt_tz_get();
  194. #else
  195. local_tz = *t + 0U;
  196. #endif /* RT_LIBC_USING_LIGHT_TZ_DST */
  197. return gmtime_r(&local_tz, r);
  198. }
  199. RTM_EXPORT(localtime_r);
  200. struct tm* localtime(const time_t* t)
  201. {
  202. static struct tm tmp;
  203. return localtime_r(t, &tmp);
  204. }
  205. RTM_EXPORT(localtime);
  206. time_t mktime(struct tm * const t)
  207. {
  208. time_t timestamp;
  209. timestamp = timegm(t);
  210. #if defined(RT_LIBC_USING_LIGHT_TZ_DST)
  211. timestamp = timestamp - rt_tz_get();
  212. #else
  213. timestamp = timestamp - 0U;
  214. #endif /* RT_LIBC_USING_LIGHT_TZ_DST */
  215. return timestamp;
  216. }
  217. RTM_EXPORT(mktime);
  218. char* asctime_r(const struct tm *t, char *buf)
  219. {
  220. if(t == RT_NULL || buf == RT_NULL)
  221. {
  222. rt_set_errno(EFAULT);
  223. return RT_NULL;
  224. }
  225. rt_memset(buf, RT_NULL, 26);
  226. /* Checking input validity */
  227. if ((int)rt_strlen(days) <= (t->tm_wday << 2) || (int)rt_strlen(months) <= (t->tm_mon << 2))
  228. {
  229. LOG_W("asctime_r: the input parameters exceeded the limit, please check it.");
  230. *(int*) buf = *(int*) days;
  231. *(int*) (buf + 4) = *(int*) months;
  232. num2str(buf + 8, t->tm_mday);
  233. if (buf[8] == '0')
  234. buf[8] = ' ';
  235. buf[10] = ' ';
  236. num2str(buf + 11, t->tm_hour);
  237. buf[13] = ':';
  238. num2str(buf + 14, t->tm_min);
  239. buf[16] = ':';
  240. num2str(buf + 17, t->tm_sec);
  241. buf[19] = ' ';
  242. num2str(buf + 20, 2000 / 100);
  243. num2str(buf + 22, 2000 % 100);
  244. buf[24] = '\n';
  245. buf[25] = '\0';
  246. return buf;
  247. }
  248. /* "Wed Jun 30 21:49:08 1993\n" */
  249. *(int*) buf = *(int*) (days + (t->tm_wday << 2));
  250. *(int*) (buf + 4) = *(int*) (months + (t->tm_mon << 2));
  251. num2str(buf + 8, t->tm_mday);
  252. if (buf[8] == '0')
  253. buf[8] = ' ';
  254. buf[10] = ' ';
  255. num2str(buf + 11, t->tm_hour);
  256. buf[13] = ':';
  257. num2str(buf + 14, t->tm_min);
  258. buf[16] = ':';
  259. num2str(buf + 17, t->tm_sec);
  260. buf[19] = ' ';
  261. num2str(buf + 20, (t->tm_year + 1900) / 100);
  262. num2str(buf + 22, (t->tm_year + 1900) % 100);
  263. buf[24] = '\n';
  264. buf[25] = '\0';
  265. return buf;
  266. }
  267. RTM_EXPORT(asctime_r);
  268. char *asctime(const struct tm *timeptr)
  269. {
  270. static char buf[26];
  271. return asctime_r(timeptr, buf);
  272. }
  273. RTM_EXPORT(asctime);
  274. char *ctime_r(const time_t * tim_p, char * result)
  275. {
  276. struct tm tm;
  277. return asctime_r(localtime_r(tim_p, &tm), result);
  278. }
  279. RTM_EXPORT(ctime_r);
  280. char *ctime(const time_t *tim_p)
  281. {
  282. return asctime(localtime(tim_p));
  283. }
  284. RTM_EXPORT(ctime);
  285. #if (!defined __ARMCC_VERSION) && (!defined __CC_ARM) && (!defined __ICCARM__)
  286. double difftime(time_t time1, time_t time2)
  287. {
  288. return (double)(time1 - time2);
  289. }
  290. #endif
  291. RTM_EXPORT(difftime);
  292. RTM_EXPORT(strftime); /* inherent in the toolchain */
  293. /**
  294. * Returns the current time.
  295. *
  296. * @param time_t * t the timestamp pointer, if not used, keep NULL.
  297. *
  298. * @return The value ((time_t)-1) is returned if the calendar time is not available.
  299. * If timer is not a NULL pointer, the return value is also stored in timer.
  300. *
  301. */
  302. rt_weak time_t time(time_t *t)
  303. {
  304. time_t _t;
  305. if (_control_rtc(RT_DEVICE_CTRL_RTC_GET_TIME, &_t) != RT_EOK)
  306. {
  307. rt_set_errno(EFAULT);
  308. return (time_t)-1;
  309. }
  310. if (t)
  311. *t = _t;
  312. return _t;
  313. }
  314. RTM_EXPORT(time);
  315. rt_weak clock_t clock(void)
  316. {
  317. return rt_tick_get(); // TODO should return cpu usage time
  318. }
  319. RTM_EXPORT(clock);
  320. int stime(const time_t *t)
  321. {
  322. if ((t != RT_NULL) && (_control_rtc(RT_DEVICE_CTRL_RTC_SET_TIME, (void *)t) == RT_EOK))
  323. {
  324. return 0;
  325. }
  326. rt_set_errno(EFAULT);
  327. return -1;
  328. }
  329. RTM_EXPORT(stime);
  330. time_t timegm(struct tm * const t)
  331. {
  332. time_t day;
  333. time_t i;
  334. time_t years;
  335. if(t == RT_NULL)
  336. {
  337. rt_set_errno(EFAULT);
  338. return (time_t)-1;
  339. }
  340. years = (time_t)t->tm_year - 70;
  341. if (t->tm_sec > 60) /* seconds after the minute - [0, 60] including leap second */
  342. {
  343. t->tm_min += t->tm_sec / 60;
  344. t->tm_sec %= 60;
  345. }
  346. if (t->tm_min >= 60) /* minutes after the hour - [0, 59] */
  347. {
  348. t->tm_hour += t->tm_min / 60;
  349. t->tm_min %= 60;
  350. }
  351. if (t->tm_hour >= 24) /* hours since midnight - [0, 23] */
  352. {
  353. t->tm_mday += t->tm_hour / 24;
  354. t->tm_hour %= 24;
  355. }
  356. if (t->tm_mon >= 12) /* months since January - [0, 11] */
  357. {
  358. t->tm_year += t->tm_mon / 12;
  359. t->tm_mon %= 12;
  360. }
  361. while (t->tm_mday > __spm[1 + t->tm_mon])
  362. {
  363. if (t->tm_mon == 1 && __isleap(t->tm_year + 1900))
  364. {
  365. --t->tm_mday;
  366. }
  367. t->tm_mday -= __spm[t->tm_mon];
  368. ++t->tm_mon;
  369. if (t->tm_mon > 11)
  370. {
  371. t->tm_mon = 0;
  372. ++t->tm_year;
  373. }
  374. }
  375. if (t->tm_year < 70)
  376. {
  377. rt_set_errno(EINVAL);
  378. return (time_t) -1;
  379. }
  380. /* Days since 1970 is 365 * number of years + number of leap years since 1970 */
  381. day = years * 365 + (years + 1) / 4;
  382. /* After 2100 we have to substract 3 leap years for every 400 years
  383. This is not intuitive. Most mktime implementations do not support
  384. dates after 2059, anyway, so we might leave this out for it's
  385. bloat. */
  386. if (years >= 131)
  387. {
  388. years -= 131;
  389. years /= 100;
  390. day -= (years >> 2) * 3 + 1;
  391. if ((years &= 3) == 3)
  392. years--;
  393. day -= years;
  394. }
  395. day += t->tm_yday = __spm[t->tm_mon] + t->tm_mday - 1 +
  396. (__isleap(t->tm_year + 1900) & (t->tm_mon > 1));
  397. /* day is now the number of days since 'Jan 1 1970' */
  398. i = 7;
  399. t->tm_wday = (int)((day + 4) % i); /* Sunday=0, Monday=1, ..., Saturday=6 */
  400. i = 24;
  401. day *= i;
  402. i = 60;
  403. return ((day + t->tm_hour) * i + t->tm_min) * i + t->tm_sec;
  404. }
  405. RTM_EXPORT(timegm);
  406. int gettimeofday(struct timeval *tv, struct timezone *tz)
  407. {
  408. /* The use of the timezone structure is obsolete;
  409. * the tz argument should normally be specified as NULL.
  410. * The tz_dsttime field has never been used under Linux.
  411. * Thus, the following is purely of historic interest.
  412. */
  413. if(tz != RT_NULL)
  414. {
  415. tz->tz_dsttime = DST_NONE;
  416. #if defined(RT_LIBC_USING_LIGHT_TZ_DST)
  417. tz->tz_minuteswest = -(rt_tz_get() / 60);
  418. #else
  419. tz->tz_minuteswest = 0;
  420. #endif /* RT_LIBC_USING_LIGHT_TZ_DST */
  421. }
  422. if (tv != RT_NULL)
  423. {
  424. tv->tv_sec = 0;
  425. tv->tv_usec = 0;
  426. if (_control_rtc(RT_DEVICE_CTRL_RTC_GET_TIMEVAL, tv) == RT_EOK)
  427. {
  428. return 0;
  429. }
  430. else
  431. {
  432. if (_control_rtc(RT_DEVICE_CTRL_RTC_GET_TIME, (void *)&tv->tv_sec) == RT_EOK)
  433. {
  434. return 0;
  435. }
  436. }
  437. }
  438. rt_set_errno(EINVAL);
  439. return -1;
  440. }
  441. RTM_EXPORT(gettimeofday);
  442. int settimeofday(const struct timeval *tv, const struct timezone *tz)
  443. {
  444. /* The use of the timezone structure is obsolete;
  445. * the tz argument should normally be specified as NULL.
  446. * The tz_dsttime field has never been used under Linux.
  447. * Thus, the following is purely of historic interest.
  448. */
  449. if (tv != RT_NULL && (long)tv->tv_usec >= 0 && (long)tv->tv_sec >= 0)
  450. {
  451. if (_control_rtc(RT_DEVICE_CTRL_RTC_SET_TIMEVAL, (void *)tv) == RT_EOK)
  452. {
  453. return 0;
  454. }
  455. else
  456. {
  457. if (_control_rtc(RT_DEVICE_CTRL_RTC_SET_TIME, (void *)&tv->tv_sec) == RT_EOK)
  458. {
  459. return 0;
  460. }
  461. }
  462. }
  463. rt_set_errno(EINVAL);
  464. return -1;
  465. }
  466. RTM_EXPORT(settimeofday);
  467. #if defined(RT_USING_POSIX_DELAY) && defined(RT_USING_KTIME)
  468. int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
  469. {
  470. struct timespec old_ts = {0};
  471. struct timespec new_ts = {0};
  472. if (rqtp == RT_NULL)
  473. {
  474. rt_set_errno(EFAULT);
  475. return -1;
  476. }
  477. if (rqtp->tv_sec < 0 || rqtp->tv_nsec < 0 || rqtp->tv_nsec >= NANOSECOND_PER_SECOND)
  478. {
  479. rt_set_errno(EINVAL);
  480. return -1;
  481. }
  482. unsigned long ns = rqtp->tv_sec * NANOSECOND_PER_SECOND + rqtp->tv_nsec;
  483. rt_ktime_boottime_get_ns(&old_ts);
  484. rt_ktime_hrtimer_ndelay(ns);
  485. if (rt_get_errno() == RT_EINTR)
  486. {
  487. if (rmtp)
  488. {
  489. rt_base_t rsec, rnsec;
  490. rt_ktime_boottime_get_ns(&new_ts);
  491. rsec = old_ts.tv_sec + rqtp->tv_sec - new_ts.tv_sec;
  492. rnsec = old_ts.tv_nsec + rqtp->tv_nsec - new_ts.tv_nsec;
  493. if (rnsec < 0)
  494. {
  495. rmtp->tv_sec = rsec - 1;
  496. rmtp->tv_nsec = NANOSECOND_PER_SECOND + rnsec;
  497. }
  498. else
  499. {
  500. rmtp->tv_sec = rsec;
  501. rmtp->tv_nsec = rnsec;
  502. }
  503. }
  504. rt_set_errno(EINTR);
  505. return -1;
  506. }
  507. return 0;
  508. }
  509. RTM_EXPORT(nanosleep);
  510. #endif /* RT_USING_POSIX_DELAY && RT_USING_KTIME */
  511. #if defined(RT_USING_POSIX_CLOCK) && defined(RT_USING_KTIME)
  512. int clock_getres(clockid_t clockid, struct timespec *res)
  513. {
  514. if (res == RT_NULL)
  515. {
  516. rt_set_errno(EFAULT);
  517. return -1;
  518. }
  519. switch (clockid)
  520. {
  521. case CLOCK_REALTIME: // use RTC
  522. case CLOCK_REALTIME_COARSE:
  523. return _control_rtc(RT_DEVICE_CTRL_RTC_GET_TIMERES, res);
  524. case CLOCK_MONOTONIC: // use cputimer
  525. case CLOCK_MONOTONIC_COARSE:
  526. case CLOCK_MONOTONIC_RAW:
  527. case CLOCK_BOOTTIME:
  528. case CLOCK_PROCESS_CPUTIME_ID:
  529. case CLOCK_THREAD_CPUTIME_ID:
  530. res->tv_sec = 0;
  531. res->tv_nsec = (rt_ktime_cputimer_getres() / RT_KTIME_RESMUL);
  532. return 0;
  533. default:
  534. rt_set_errno(EINVAL);
  535. return -1;
  536. }
  537. }
  538. RTM_EXPORT(clock_getres);
  539. int clock_gettime(clockid_t clockid, struct timespec *tp)
  540. {
  541. if (tp == RT_NULL)
  542. {
  543. rt_set_errno(EFAULT);
  544. return -1;
  545. }
  546. switch (clockid)
  547. {
  548. case CLOCK_REALTIME: // use RTC
  549. case CLOCK_REALTIME_COARSE:
  550. return _control_rtc(RT_DEVICE_CTRL_RTC_GET_TIMESPEC, tp);
  551. case CLOCK_MONOTONIC: // use boottime
  552. case CLOCK_MONOTONIC_COARSE:
  553. case CLOCK_MONOTONIC_RAW:
  554. case CLOCK_BOOTTIME:
  555. return rt_ktime_boottime_get_ns(tp);
  556. case CLOCK_PROCESS_CPUTIME_ID:
  557. case CLOCK_THREAD_CPUTIME_ID:
  558. return rt_ktime_boottime_get_ns(tp); // TODO not yet implemented
  559. default:
  560. tp->tv_sec = 0;
  561. tp->tv_nsec = 0;
  562. rt_set_errno(EINVAL);
  563. return -1;
  564. }
  565. }
  566. RTM_EXPORT(clock_gettime);
  567. int clock_nanosleep(clockid_t clockid, int flags, const struct timespec *rqtp, struct timespec *rmtp)
  568. {
  569. struct timespec ts = {0};
  570. rt_err_t err = -RT_EINVAL;
  571. if (rqtp == RT_NULL)
  572. {
  573. rt_set_errno(EFAULT);
  574. return -1;
  575. }
  576. if (rqtp->tv_sec < 0 || rqtp->tv_nsec < 0 || rqtp->tv_nsec >= NANOSECOND_PER_SECOND)
  577. {
  578. rt_set_errno(EINVAL);
  579. return -1;
  580. }
  581. switch (clockid)
  582. {
  583. case CLOCK_REALTIME: // use RTC
  584. if (flags & TIMER_ABSTIME)
  585. err = _control_rtc(RT_DEVICE_CTRL_RTC_GET_TIMESPEC, &ts);
  586. break;
  587. case CLOCK_MONOTONIC: // use boottime
  588. case CLOCK_PROCESS_CPUTIME_ID:
  589. if (flags & TIMER_ABSTIME)
  590. err = rt_ktime_boottime_get_ns(&ts);
  591. break;
  592. default:
  593. rt_set_errno(EINVAL);
  594. return -1;
  595. }
  596. if (err != RT_EOK)
  597. return err;
  598. int64_t ns = rqtp->tv_nsec - ts.tv_nsec + (rqtp->tv_sec - ts.tv_sec) * NANOSECOND_PER_SECOND;
  599. if (ns <= 0)
  600. return 0;
  601. if (flags & TIMER_ABSTIME)
  602. {
  603. ts.tv_nsec = ns % NANOSECOND_PER_SECOND;
  604. ts.tv_sec = ns / NANOSECOND_PER_SECOND;
  605. return nanosleep(&ts, rmtp);
  606. }
  607. else
  608. {
  609. return nanosleep(rqtp, rmtp);
  610. }
  611. }
  612. RTM_EXPORT(clock_nanosleep);
  613. int clock_settime(clockid_t clockid, const struct timespec *tp)
  614. {
  615. if (tp == RT_NULL)
  616. {
  617. rt_set_errno(EFAULT);
  618. return -1;
  619. }
  620. if (tp->tv_sec < 0 || tp->tv_nsec < 0 || tp->tv_nsec >= NANOSECOND_PER_SECOND)
  621. {
  622. rt_set_errno(EINVAL);
  623. return -1;
  624. }
  625. switch (clockid)
  626. {
  627. case CLOCK_REALTIME:
  628. return _control_rtc(RT_DEVICE_CTRL_RTC_SET_TIMESPEC, (void *)tp);
  629. case CLOCK_REALTIME_COARSE:
  630. case CLOCK_MONOTONIC:
  631. case CLOCK_MONOTONIC_COARSE:
  632. case CLOCK_MONOTONIC_RAW:
  633. case CLOCK_BOOTTIME:
  634. case CLOCK_PROCESS_CPUTIME_ID:
  635. case CLOCK_THREAD_CPUTIME_ID:
  636. rt_set_errno(EPERM);
  637. return -1;
  638. default:
  639. rt_set_errno(EINVAL);
  640. return -1;
  641. }
  642. }
  643. RTM_EXPORT(clock_settime);
  644. int rt_timespec_to_tick(const struct timespec *time)
  645. {
  646. int tick;
  647. int second;
  648. long long nsecond;
  649. struct timespec tp = {0};
  650. RT_ASSERT(time != RT_NULL);
  651. tick = RT_WAITING_FOREVER;
  652. if (time != NULL)
  653. {
  654. /* get current tp */
  655. clock_gettime(CLOCK_REALTIME, &tp);
  656. if ((time->tv_nsec - tp.tv_nsec) < 0)
  657. {
  658. nsecond = NANOSECOND_PER_SECOND - (tp.tv_nsec - time->tv_nsec);
  659. second = time->tv_sec - tp.tv_sec - 1;
  660. }
  661. else
  662. {
  663. nsecond = time->tv_nsec - tp.tv_nsec;
  664. second = time->tv_sec - tp.tv_sec;
  665. }
  666. tick = second * RT_TICK_PER_SECOND + nsecond * RT_TICK_PER_SECOND / NANOSECOND_PER_SECOND;
  667. if (tick < 0) tick = 0;
  668. }
  669. return tick;
  670. }
  671. RTM_EXPORT(rt_timespec_to_tick);
  672. #endif /* RT_USING_POSIX_CLOCK && RT_USING_KTIME */
  673. #if defined(RT_USING_POSIX_TIMER) && defined(RT_USING_KTIME)
  674. #include <resource_id.h>
  675. #define ACTIVE 1
  676. #define NOT_ACTIVE 0
  677. struct timer_obj
  678. {
  679. struct rt_ktime_hrtimer hrtimer;
  680. void (*sigev_notify_function)(union sigval val);
  681. union sigval val;
  682. struct timespec interval; /* Reload value */
  683. struct timespec value; /* Reload value */
  684. unsigned long reload; /* Reload value in ms */
  685. rt_uint32_t status;
  686. int sigev_signo;
  687. clockid_t clockid;
  688. timer_t timer_id;
  689. #ifdef RT_USING_SMART
  690. pid_t pid;
  691. struct rt_work *work;
  692. rt_list_t lwp_node;
  693. #endif
  694. };
  695. #ifdef RT_USING_SMART
  696. struct lwp_timer_event_param
  697. {
  698. struct rt_work work;
  699. union
  700. {
  701. int tid;
  702. pid_t pid;
  703. };
  704. int signo;
  705. };
  706. static void _lwp_timer_event_from_tid(struct rt_work *work, void *param)
  707. {
  708. rt_err_t ret;
  709. struct lwp_timer_event_param *data = rt_container_of(work, struct lwp_timer_event_param, work);
  710. rt_thread_t thread;
  711. RT_ASSERT(data->tid);
  712. /* stop others from delete thread */
  713. thread = lwp_tid_get_thread_and_inc_ref(data->tid);
  714. /** The tid of thread is a READ ONLY value, but here still facing the risk of thread already been delete error */
  715. ret = lwp_thread_signal_kill(thread, data->signo, SI_TIMER, 0);
  716. lwp_tid_dec_ref(thread);
  717. if (ret)
  718. {
  719. LOG_D("%s: Do kill failed(tid %d) returned %d", __func__, data->tid, ret);
  720. }
  721. }
  722. static void _lwp_timer_event_from_pid(struct rt_work *work, void *param)
  723. {
  724. rt_err_t ret;
  725. struct lwp_timer_event_param *data = rt_container_of(work, struct lwp_timer_event_param, work);
  726. struct rt_lwp *lwp;
  727. lwp_pid_lock_take();
  728. lwp = lwp_from_pid_locked(data->pid);
  729. if (lwp)
  730. lwp_ref_inc(lwp);
  731. lwp_pid_lock_release();
  732. ret = lwp_signal_kill(lwp, data->signo, SI_TIMER, 0);
  733. if (lwp)
  734. lwp_ref_dec(lwp);
  735. if (ret)
  736. {
  737. LOG_D("%s: Do kill failed(pid %d) returned %d", __func__, data->pid, ret);
  738. }
  739. }
  740. int timer_list_free(rt_list_t *timer_list)
  741. {
  742. struct timer_obj *pos, *n;
  743. rt_list_for_each_entry_safe(pos, n, timer_list, lwp_node)
  744. {
  745. timer_delete(pos->timer_id);
  746. }
  747. return 0;
  748. }
  749. #endif /* RT_USING_SMART */
  750. static void rtthread_timer_wrapper(void *timerobj)
  751. {
  752. struct timer_obj *timer;
  753. timer = (struct timer_obj *)timerobj;
  754. if (timer->reload == 0U)
  755. {
  756. timer->status = NOT_ACTIVE;
  757. }
  758. timer->reload = ((timer->interval.tv_sec * NANOSECOND_PER_SECOND + timer->interval.tv_nsec) * RT_KTIME_RESMUL) /
  759. rt_ktime_cputimer_getres();
  760. if (timer->reload)
  761. {
  762. rt_ktime_hrtimer_control(&timer->hrtimer, RT_TIMER_CTRL_SET_TIME, &(timer->reload));
  763. rt_ktime_hrtimer_start(&timer->hrtimer);
  764. }
  765. #ifdef RT_USING_SMART
  766. /* this field is named as tid in musl */
  767. void *ptid = &timer->sigev_notify_function;
  768. int tid = *(int *)ptid;
  769. struct lwp_timer_event_param *data = rt_container_of(timer->work, struct lwp_timer_event_param, work);
  770. data->signo = timer->sigev_signo;
  771. if (!tid)
  772. {
  773. data->pid = timer->pid;
  774. rt_work_init(timer->work, _lwp_timer_event_from_pid, 0);
  775. }
  776. else
  777. {
  778. data->tid = tid;
  779. rt_work_init(timer->work, _lwp_timer_event_from_tid, 0);
  780. }
  781. if (rt_work_submit(timer->work, 0))
  782. RT_ASSERT(0);
  783. #else
  784. if(timer->sigev_notify_function != RT_NULL)
  785. {
  786. (timer->sigev_notify_function)(timer->val);
  787. }
  788. #endif /* RT_USING_SMART */
  789. }
  790. #define TIMER_ID_MAX 50
  791. static struct rt_spinlock _timer_id_lock = RT_SPINLOCK_INIT;
  792. static struct timer_obj *_g_timerid[TIMER_ID_MAX];
  793. static void *timer_id[TIMER_ID_MAX];
  794. static resource_id_t id_timer = RESOURCE_ID_INIT(TIMER_ID_MAX, timer_id);
  795. /**
  796. * @brief Create a per-process timer.
  797. *
  798. * This API does not accept SIGEV_THREAD as valid signal event notification
  799. * type.
  800. *
  801. * See IEEE 1003.1
  802. */
  803. int timer_create(clockid_t clockid, struct sigevent *evp, timer_t *timerid)
  804. {
  805. static int num = 0;
  806. int _timerid = 0;
  807. struct timer_obj *timer;
  808. char timername[RT_NAME_MAX] = {0};
  809. if (evp == RT_NULL || timerid == RT_NULL)
  810. {
  811. rt_set_errno(EINVAL);
  812. return -1;
  813. }
  814. if (evp->sigev_notify == SIGEV_THREAD) // TODO need to implement
  815. {
  816. rt_set_errno(EINVAL);
  817. return -1;
  818. }
  819. switch (clockid)
  820. {
  821. case CLOCK_REALTIME:
  822. case CLOCK_REALTIME_ALARM:
  823. case CLOCK_MONOTONIC:
  824. case CLOCK_BOOTTIME:
  825. case CLOCK_BOOTTIME_ALARM:
  826. case CLOCK_PROCESS_CPUTIME_ID:
  827. case CLOCK_THREAD_CPUTIME_ID:
  828. break; // Only these ids are supported
  829. default:
  830. rt_set_errno(EINVAL);
  831. return -1;
  832. }
  833. timer = rt_malloc(sizeof(struct timer_obj));
  834. if(timer == RT_NULL)
  835. {
  836. rt_set_errno(ENOMEM);
  837. return -1;
  838. }
  839. rt_snprintf(timername, RT_NAME_MAX, "psx_tm%02d", num++);
  840. num %= 100;
  841. timer->sigev_signo = evp->sigev_signo;
  842. #ifdef RT_USING_SMART
  843. struct rt_work *work;
  844. struct rt_lwp *lwp = lwp_self();
  845. struct lwp_timer_event_param *param;
  846. param = rt_malloc(sizeof(struct lwp_timer_event_param));
  847. work = &param->work;
  848. if (!work)
  849. {
  850. rt_set_errno(ENOMEM);
  851. return -1;
  852. }
  853. if (lwp)
  854. {
  855. timer->pid = lwp_self()->pid;
  856. rt_list_insert_after(&lwp->timer, &timer->lwp_node);
  857. }
  858. else
  859. {
  860. timer->pid = 0; /* pid 0 is never used */
  861. }
  862. timer->work = work;
  863. #endif /* RT_USING_SMART */
  864. timer->sigev_notify_function = evp->sigev_notify_function;
  865. timer->val = evp->sigev_value;
  866. timer->interval.tv_sec = 0;
  867. timer->interval.tv_nsec = 0;
  868. timer->reload = 0U;
  869. timer->status = NOT_ACTIVE;
  870. timer->clockid = clockid;
  871. rt_ktime_hrtimer_init(&timer->hrtimer, timername, 0, RT_TIMER_FLAG_ONE_SHOT | RT_TIMER_FLAG_HARD_TIMER,
  872. rtthread_timer_wrapper, timer);
  873. _timerid = resource_id_get(&id_timer);
  874. if (_timerid < 0)
  875. {
  876. #ifdef RT_USING_SMART
  877. rt_free(param);
  878. #endif /* RT_USING_SMART */
  879. rt_ktime_hrtimer_detach(&timer->hrtimer);
  880. rt_free(timer);
  881. rt_set_errno(ENOMEM);
  882. return -1;
  883. }
  884. _g_timerid[_timerid] = timer;
  885. timer->timer_id = (timer_t)(rt_ubase_t)_timerid;
  886. *timerid = (timer_t)(rt_ubase_t)_timerid;
  887. return 0;
  888. }
  889. RTM_EXPORT(timer_create);
  890. /**
  891. * @brief Delete a per-process timer.
  892. *
  893. * See IEEE 1003.1
  894. */
  895. int timer_delete(timer_t timerid)
  896. {
  897. struct timer_obj *timer;
  898. rt_ubase_t ktimerid;
  899. ktimerid = (rt_ubase_t)timerid;
  900. if (ktimerid < 0 || ktimerid >= TIMER_ID_MAX)
  901. {
  902. rt_set_errno(EINVAL);
  903. return -1;
  904. }
  905. RT_DEBUG_NOT_IN_INTERRUPT;
  906. rt_spin_lock(&_timer_id_lock);
  907. timer = _g_timerid[ktimerid];
  908. if (timer != NULL)
  909. {
  910. _g_timerid[ktimerid] = RT_NULL;
  911. resource_id_put(&id_timer, ktimerid);
  912. }
  913. rt_spin_unlock(&_timer_id_lock);
  914. if (timer == RT_NULL)
  915. {
  916. rt_set_errno(EINVAL);
  917. LOG_D("can not find timer %ld", ktimerid);
  918. return -1;
  919. }
  920. if (timer->status == ACTIVE)
  921. {
  922. timer->status = NOT_ACTIVE;
  923. rt_ktime_hrtimer_stop(&timer->hrtimer);
  924. }
  925. rt_ktime_hrtimer_detach(&timer->hrtimer);
  926. #ifdef RT_USING_SMART
  927. if (timer->pid)
  928. rt_list_remove(&timer->lwp_node);
  929. rt_free(timer->work);
  930. #endif
  931. rt_free(timer);
  932. return 0;
  933. }
  934. RTM_EXPORT(timer_delete);
  935. /**
  936. *
  937. * Return the overrun count for the last timer expiration.
  938. * It is subefficient to create a new structure to get overrun count.
  939. **/
  940. int timer_getoverrun(timer_t timerid)
  941. {
  942. rt_set_errno(ENOSYS);
  943. return -1;
  944. }
  945. /**
  946. * @brief Get amount of time left for expiration on a per-process timer.
  947. *
  948. * See IEEE 1003.1
  949. */
  950. int timer_gettime(timer_t timerid, struct itimerspec *its)
  951. {
  952. struct timer_obj *timer;
  953. rt_uint32_t seconds, nanoseconds;
  954. timer = _g_timerid[(rt_ubase_t)timerid];
  955. if (timer == NULL)
  956. {
  957. rt_set_errno(EINVAL);
  958. return -1;
  959. }
  960. if (its == NULL)
  961. {
  962. rt_set_errno(EFAULT);
  963. return -1;
  964. }
  965. if (timer->status == ACTIVE)
  966. {
  967. unsigned long remain_cnt;
  968. rt_ktime_hrtimer_control(&timer->hrtimer, RT_TIMER_CTRL_GET_REMAIN_TIME, &remain_cnt);
  969. nanoseconds = ((remain_cnt - rt_ktime_cputimer_getcnt()) * rt_ktime_cputimer_getres()) / RT_KTIME_RESMUL;
  970. seconds = nanoseconds / NANOSECOND_PER_SECOND;
  971. nanoseconds = nanoseconds % NANOSECOND_PER_SECOND;
  972. its->it_value.tv_sec = (rt_int32_t)seconds;
  973. its->it_value.tv_nsec = (rt_int32_t)nanoseconds;
  974. }
  975. else
  976. {
  977. /* Timer is disarmed */
  978. its->it_value.tv_sec = 0;
  979. its->it_value.tv_nsec = 0;
  980. }
  981. /* The interval last set by timer_settime() */
  982. its->it_interval = timer->interval;
  983. return 0;
  984. }
  985. RTM_EXPORT(timer_gettime);
  986. /**
  987. * @brief Sets expiration time of per-process timer.
  988. *
  989. * See IEEE 1003.1
  990. */
  991. int timer_settime(timer_t timerid, int flags, const struct itimerspec *value,
  992. struct itimerspec *ovalue)
  993. {
  994. struct timespec ts = {0};
  995. rt_err_t err = RT_EOK;
  996. struct timer_obj *timer;
  997. timer = _g_timerid[(rt_ubase_t)timerid];
  998. if (timer == NULL ||
  999. value->it_interval.tv_nsec < 0 ||
  1000. value->it_interval.tv_nsec >= NANOSECOND_PER_SECOND ||
  1001. value->it_interval.tv_sec < 0 ||
  1002. value->it_value.tv_nsec < 0 ||
  1003. value->it_value.tv_nsec >= NANOSECOND_PER_SECOND ||
  1004. value->it_value.tv_sec < 0)
  1005. {
  1006. rt_set_errno(EINVAL);
  1007. return -1;
  1008. }
  1009. /* Save time to expire and old reload value. */
  1010. if (ovalue != NULL)
  1011. {
  1012. timer_gettime(timerid, ovalue);
  1013. }
  1014. /* Stop the timer if the value is 0 */
  1015. if ((value->it_value.tv_sec == 0) && (value->it_value.tv_nsec == 0))
  1016. {
  1017. if (timer->status == ACTIVE)
  1018. {
  1019. rt_ktime_hrtimer_stop(&timer->hrtimer);
  1020. }
  1021. timer->status = NOT_ACTIVE;
  1022. return 0;
  1023. }
  1024. switch (timer->clockid)
  1025. {
  1026. case CLOCK_REALTIME:
  1027. case CLOCK_REALTIME_ALARM:
  1028. if (flags & TIMER_ABSTIME)
  1029. err = _control_rtc(RT_DEVICE_CTRL_RTC_GET_TIMESPEC, &ts);
  1030. break;
  1031. case CLOCK_MONOTONIC:
  1032. case CLOCK_BOOTTIME:
  1033. case CLOCK_BOOTTIME_ALARM:
  1034. case CLOCK_PROCESS_CPUTIME_ID:
  1035. case CLOCK_THREAD_CPUTIME_ID:
  1036. if (flags & TIMER_ABSTIME)
  1037. err = rt_ktime_boottime_get_ns(&ts);
  1038. break;
  1039. default:
  1040. rt_set_errno(EINVAL);
  1041. return -1;
  1042. }
  1043. if (err != RT_EOK)
  1044. return err;
  1045. int64_t ns = value->it_value.tv_nsec - ts.tv_nsec + (value->it_value.tv_sec - ts.tv_sec) * NANOSECOND_PER_SECOND;
  1046. if (ns <= 0)
  1047. return 0;
  1048. unsigned long res = rt_ktime_cputimer_getres();
  1049. timer->reload = (ns * RT_KTIME_RESMUL) / res;
  1050. timer->interval.tv_sec = value->it_interval.tv_sec;
  1051. timer->interval.tv_nsec = value->it_interval.tv_nsec;
  1052. timer->value.tv_sec = value->it_value.tv_sec;
  1053. timer->value.tv_nsec = value->it_value.tv_nsec;
  1054. if (timer->status == ACTIVE)
  1055. {
  1056. rt_ktime_hrtimer_stop(&timer->hrtimer);
  1057. }
  1058. timer->status = ACTIVE;
  1059. if ((value->it_interval.tv_sec == 0) && (value->it_interval.tv_nsec == 0))
  1060. rt_ktime_hrtimer_control(&timer->hrtimer, RT_TIMER_CTRL_SET_ONESHOT, RT_NULL);
  1061. else
  1062. rt_ktime_hrtimer_control(&timer->hrtimer, RT_TIMER_CTRL_SET_PERIODIC, RT_NULL);
  1063. rt_ktime_hrtimer_control(&timer->hrtimer, RT_TIMER_CTRL_SET_TIME, &(timer->reload));
  1064. rt_ktime_hrtimer_start(&timer->hrtimer);
  1065. return 0;
  1066. }
  1067. RTM_EXPORT(timer_settime);
  1068. #endif /* RT_USING_POSIX_TIMER && RT_USING_KTIME */