ctime.c 30 KB

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