time.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <errno.h>
  15. #include <stdlib.h>
  16. #include <time.h>
  17. #include <reent.h>
  18. #include <unistd.h>
  19. #include <sys/types.h>
  20. #include <sys/reent.h>
  21. #include <sys/time.h>
  22. #include <sys/times.h>
  23. #include <sys/lock.h>
  24. #include "esp_attr.h"
  25. #include "esp_intr_alloc.h"
  26. #include "esp_timer.h"
  27. #include "soc/soc.h"
  28. #include "soc/rtc.h"
  29. #include "soc/frc_timer_reg.h"
  30. #include "freertos/FreeRTOS.h"
  31. #include "freertos/xtensa_api.h"
  32. #include "freertos/task.h"
  33. #include "limits.h"
  34. #include "sdkconfig.h"
  35. #if CONFIG_IDF_TARGET_ESP32
  36. #include "esp32/rom/ets_sys.h"
  37. #include "esp32/clk.h"
  38. #include "esp32/rom/rtc.h"
  39. #elif CONFIG_IDF_TARGET_ESP32S2
  40. #include "esp32s2/clk.h"
  41. #include "esp32s2/rom/rtc.h"
  42. #include "esp32s2/rom/ets_sys.h"
  43. #endif
  44. #ifdef CONFIG_SDK_TOOLCHAIN_SUPPORTS_TIME_WIDE_64_BITS
  45. _Static_assert(sizeof(time_t) == 8, "The toolchain does not support time_t wide 64-bits");
  46. #else
  47. _Static_assert(sizeof(time_t) == 4, "The toolchain supports time_t wide 64-bits. Please enable CONFIG_SDK_TOOLCHAIN_SUPPORTS_TIME_WIDE_64_BITS.");
  48. #endif
  49. #if defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC ) || defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
  50. #define WITH_RTC 1
  51. #endif
  52. #if defined( CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 ) || defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_FRC1 ) || defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
  53. #define WITH_FRC 1
  54. #endif
  55. #ifdef WITH_RTC
  56. static uint64_t get_rtc_time_us(void)
  57. {
  58. const uint64_t ticks = rtc_time_get();
  59. const uint32_t cal = esp_clk_slowclk_cal_get();
  60. /* RTC counter result is up to 2^48, calibration factor is up to 2^24,
  61. * for a 32kHz clock. We need to calculate (assuming no overflow):
  62. * (ticks * cal) >> RTC_CLK_CAL_FRACT
  63. *
  64. * An overflow in the (ticks * cal) multiplication would cause time to
  65. * wrap around after approximately 13 days, which is probably not enough
  66. * for some applications.
  67. * Therefore multiplication is split into two terms, for the lower 32-bit
  68. * and the upper 16-bit parts of "ticks", i.e.:
  69. * ((ticks_low + 2^32 * ticks_high) * cal) >> RTC_CLK_CAL_FRACT
  70. */
  71. const uint64_t ticks_low = ticks & UINT32_MAX;
  72. const uint64_t ticks_high = ticks >> 32;
  73. return ((ticks_low * cal) >> RTC_CLK_CAL_FRACT) +
  74. ((ticks_high * cal) << (32 - RTC_CLK_CAL_FRACT));
  75. }
  76. #endif // WITH_RTC
  77. // s_boot_time: time from Epoch to the first boot time
  78. #ifdef WITH_RTC
  79. // when RTC is used to persist time, two RTC_STORE registers are used to store boot time
  80. #elif defined(WITH_FRC)
  81. static uint64_t s_boot_time;
  82. #endif // WITH_RTC
  83. #if defined(WITH_RTC) || defined(WITH_FRC)
  84. static _lock_t s_boot_time_lock;
  85. static _lock_t s_adjust_time_lock;
  86. // stores the start time of the slew
  87. static uint64_t adjtime_start = 0;
  88. // is how many microseconds total to slew
  89. static int64_t adjtime_total_correction = 0;
  90. #define ADJTIME_CORRECTION_FACTOR 6
  91. static uint64_t get_time_since_boot(void);
  92. #endif
  93. // Offset between FRC timer and the RTC.
  94. // Initialized after reset or light sleep.
  95. #if defined(WITH_RTC) && defined(WITH_FRC)
  96. uint64_t s_microseconds_offset;
  97. #endif
  98. #if defined(WITH_RTC) || defined(WITH_FRC)
  99. static void set_boot_time(uint64_t time_us)
  100. {
  101. _lock_acquire(&s_boot_time_lock);
  102. #ifdef WITH_RTC
  103. REG_WRITE(RTC_BOOT_TIME_LOW_REG, (uint32_t) (time_us & 0xffffffff));
  104. REG_WRITE(RTC_BOOT_TIME_HIGH_REG, (uint32_t) (time_us >> 32));
  105. #else
  106. s_boot_time = time_us;
  107. #endif
  108. _lock_release(&s_boot_time_lock);
  109. }
  110. static uint64_t get_boot_time(void)
  111. {
  112. uint64_t result;
  113. _lock_acquire(&s_boot_time_lock);
  114. #ifdef WITH_RTC
  115. result = ((uint64_t) REG_READ(RTC_BOOT_TIME_LOW_REG)) + (((uint64_t) REG_READ(RTC_BOOT_TIME_HIGH_REG)) << 32);
  116. #else
  117. result = s_boot_time;
  118. #endif
  119. _lock_release(&s_boot_time_lock);
  120. return result;
  121. }
  122. // This function gradually changes boot_time to the correction value and immediately updates it.
  123. static uint64_t adjust_boot_time(void)
  124. {
  125. uint64_t boot_time = get_boot_time();
  126. if ((boot_time == 0) || (get_time_since_boot() < adjtime_start)) {
  127. adjtime_start = 0;
  128. }
  129. if (adjtime_start > 0) {
  130. uint64_t since_boot = get_time_since_boot();
  131. // If to call this function once per second, then (since_boot - adjtime_start) will be 1_000_000 (1 second),
  132. // and the correction will be equal to (1_000_000us >> 6) = 15_625 us.
  133. // The minimum possible correction step can be (64us >> 6) = 1us.
  134. // Example: if the time error is 1 second, then it will be compensate for 1 sec / 0,015625 = 64 seconds.
  135. int64_t correction = (since_boot >> ADJTIME_CORRECTION_FACTOR) - (adjtime_start >> ADJTIME_CORRECTION_FACTOR);
  136. if (correction > 0) {
  137. adjtime_start = since_boot;
  138. if (adjtime_total_correction < 0) {
  139. if ((adjtime_total_correction + correction) >= 0) {
  140. boot_time = boot_time + adjtime_total_correction;
  141. adjtime_start = 0;
  142. } else {
  143. adjtime_total_correction += correction;
  144. boot_time -= correction;
  145. }
  146. } else {
  147. if ((adjtime_total_correction - correction) <= 0) {
  148. boot_time = boot_time + adjtime_total_correction;
  149. adjtime_start = 0;
  150. } else {
  151. adjtime_total_correction -= correction;
  152. boot_time += correction;
  153. }
  154. }
  155. set_boot_time(boot_time);
  156. }
  157. }
  158. return boot_time;
  159. }
  160. // Get the adjusted boot time.
  161. static uint64_t get_adjusted_boot_time (void)
  162. {
  163. _lock_acquire(&s_adjust_time_lock);
  164. uint64_t adjust_time = adjust_boot_time();
  165. _lock_release(&s_adjust_time_lock);
  166. return adjust_time;
  167. }
  168. // Applying the accumulated correction to boot_time and stopping the smooth time adjustment.
  169. static void adjtime_corr_stop (void)
  170. {
  171. _lock_acquire(&s_adjust_time_lock);
  172. if (adjtime_start != 0){
  173. adjust_boot_time();
  174. adjtime_start = 0;
  175. }
  176. _lock_release(&s_adjust_time_lock);
  177. }
  178. #endif //defined(WITH_RTC) || defined(WITH_FRC)
  179. int adjtime(const struct timeval *delta, struct timeval *outdelta)
  180. {
  181. #if defined( WITH_FRC ) || defined( WITH_RTC )
  182. if(outdelta != NULL){
  183. _lock_acquire(&s_adjust_time_lock);
  184. adjust_boot_time();
  185. if (adjtime_start != 0) {
  186. outdelta->tv_sec = adjtime_total_correction / 1000000L;
  187. outdelta->tv_usec = adjtime_total_correction % 1000000L;
  188. } else {
  189. outdelta->tv_sec = 0;
  190. outdelta->tv_usec = 0;
  191. }
  192. _lock_release(&s_adjust_time_lock);
  193. }
  194. if(delta != NULL){
  195. int64_t sec = delta->tv_sec;
  196. int64_t usec = delta->tv_usec;
  197. if(llabs(sec) > ((INT_MAX / 1000000L) - 1L)) {
  198. return -1;
  199. }
  200. /*
  201. * If adjusting the system clock by adjtime () is already done during the second call adjtime (),
  202. * and the delta of the second call is not NULL, the earlier tuning is stopped,
  203. * but the already completed part of the adjustment is not canceled.
  204. */
  205. _lock_acquire(&s_adjust_time_lock);
  206. // If correction is already in progress (adjtime_start != 0), then apply accumulated corrections.
  207. adjust_boot_time();
  208. adjtime_start = get_time_since_boot();
  209. adjtime_total_correction = sec * 1000000L + usec;
  210. _lock_release(&s_adjust_time_lock);
  211. }
  212. return 0;
  213. #else
  214. return -1;
  215. #endif
  216. }
  217. void esp_clk_slowclk_cal_set(uint32_t new_cal)
  218. {
  219. #if defined(WITH_RTC)
  220. /* To force monotonic time values even when clock calibration value changes,
  221. * we adjust boot time, given current time and the new calibration value:
  222. * T = boot_time_old + cur_cal * ticks / 2^19
  223. * T = boot_time_adj + new_cal * ticks / 2^19
  224. * which results in:
  225. * boot_time_adj = boot_time_old + ticks * (cur_cal - new_cal) / 2^19
  226. */
  227. const int64_t ticks = (int64_t) rtc_time_get();
  228. const uint32_t cur_cal = REG_READ(RTC_SLOW_CLK_CAL_REG);
  229. int32_t cal_diff = (int32_t) (cur_cal - new_cal);
  230. int64_t boot_time_diff = ticks * cal_diff / (1LL << RTC_CLK_CAL_FRACT);
  231. uint64_t boot_time_adj = get_boot_time() + boot_time_diff;
  232. set_boot_time(boot_time_adj);
  233. #endif // WITH_RTC
  234. REG_WRITE(RTC_SLOW_CLK_CAL_REG, new_cal);
  235. }
  236. uint32_t esp_clk_slowclk_cal_get(void)
  237. {
  238. return REG_READ(RTC_SLOW_CLK_CAL_REG);
  239. }
  240. void esp_set_time_from_rtc(void)
  241. {
  242. #if defined( WITH_FRC ) && defined( WITH_RTC )
  243. // initialize time from RTC clock
  244. s_microseconds_offset = get_rtc_time_us() - esp_timer_get_time();
  245. #endif // WITH_FRC && WITH_RTC
  246. }
  247. uint64_t esp_clk_rtc_time(void)
  248. {
  249. #ifdef WITH_RTC
  250. return get_rtc_time_us();
  251. #else
  252. return 0;
  253. #endif
  254. }
  255. clock_t IRAM_ATTR _times_r(struct _reent *r, struct tms *ptms)
  256. {
  257. clock_t t = xTaskGetTickCount() * (portTICK_PERIOD_MS * CLK_TCK / 1000);
  258. ptms->tms_cstime = 0;
  259. ptms->tms_cutime = 0;
  260. ptms->tms_stime = t;
  261. ptms->tms_utime = 0;
  262. struct timeval tv = {0, 0};
  263. _gettimeofday_r(r, &tv, NULL);
  264. return (clock_t) tv.tv_sec;
  265. }
  266. #if defined( WITH_FRC ) || defined( WITH_RTC )
  267. static uint64_t get_time_since_boot(void)
  268. {
  269. uint64_t microseconds = 0;
  270. #ifdef WITH_FRC
  271. #ifdef WITH_RTC
  272. microseconds = s_microseconds_offset + esp_timer_get_time();
  273. #else
  274. microseconds = esp_timer_get_time();
  275. #endif // WITH_RTC
  276. #elif defined(WITH_RTC)
  277. microseconds = get_rtc_time_us();
  278. #endif // WITH_FRC
  279. return microseconds;
  280. }
  281. #endif // defined( WITH_FRC ) || defined( WITH_RTC )
  282. int IRAM_ATTR _gettimeofday_r(struct _reent *r, struct timeval *tv, void *tz)
  283. {
  284. (void) tz;
  285. #if defined( WITH_FRC ) || defined( WITH_RTC )
  286. if (tv) {
  287. uint64_t microseconds = get_adjusted_boot_time() + get_time_since_boot();
  288. tv->tv_sec = microseconds / 1000000;
  289. tv->tv_usec = microseconds % 1000000;
  290. }
  291. return 0;
  292. #else
  293. __errno_r(r) = ENOSYS;
  294. return -1;
  295. #endif // defined( WITH_FRC ) || defined( WITH_RTC )
  296. }
  297. int settimeofday(const struct timeval *tv, const struct timezone *tz)
  298. {
  299. (void) tz;
  300. #if defined( WITH_FRC ) || defined( WITH_RTC )
  301. if (tv) {
  302. adjtime_corr_stop();
  303. uint64_t now = ((uint64_t) tv->tv_sec) * 1000000LL + tv->tv_usec;
  304. uint64_t since_boot = get_time_since_boot();
  305. set_boot_time(now - since_boot);
  306. }
  307. return 0;
  308. #else
  309. errno = ENOSYS;
  310. return -1;
  311. #endif
  312. }
  313. int usleep(useconds_t us)
  314. {
  315. const int us_per_tick = portTICK_PERIOD_MS * 1000;
  316. if (us < us_per_tick) {
  317. ets_delay_us((uint32_t) us);
  318. } else {
  319. /* since vTaskDelay(1) blocks for anywhere between 0 and portTICK_PERIOD_MS,
  320. * round up to compensate.
  321. */
  322. vTaskDelay((us + us_per_tick - 1) / us_per_tick);
  323. }
  324. return 0;
  325. }
  326. unsigned int sleep(unsigned int seconds)
  327. {
  328. usleep(seconds*1000000UL);
  329. return 0;
  330. }
  331. uint32_t system_get_time(void)
  332. {
  333. #if defined( WITH_FRC ) || defined( WITH_RTC )
  334. return get_time_since_boot();
  335. #else
  336. return 0;
  337. #endif
  338. }
  339. uint32_t system_get_current_time(void) __attribute__((alias("system_get_time")));
  340. uint32_t system_relative_time(uint32_t current_time)
  341. {
  342. #if defined( WITH_FRC ) || defined( WITH_RTC )
  343. return get_time_since_boot() - current_time;
  344. #else
  345. return 0;
  346. #endif
  347. }
  348. uint64_t system_get_rtc_time(void)
  349. {
  350. #ifdef WITH_RTC
  351. return get_rtc_time_us();
  352. #else
  353. return 0;
  354. #endif
  355. }
  356. void esp_sync_counters_rtc_and_frc(void)
  357. {
  358. #if defined( WITH_FRC ) && defined( WITH_RTC )
  359. adjtime_corr_stop();
  360. int64_t s_microseconds_offset_cur = get_rtc_time_us() - esp_timer_get_time();
  361. set_boot_time(get_adjusted_boot_time() + ((int64_t)s_microseconds_offset - s_microseconds_offset_cur));
  362. #endif
  363. }
  364. int clock_settime (clockid_t clock_id, const struct timespec *tp)
  365. {
  366. #if defined( WITH_FRC ) || defined( WITH_RTC )
  367. if (tp == NULL) {
  368. errno = EINVAL;
  369. return -1;
  370. }
  371. struct timeval tv;
  372. switch (clock_id) {
  373. case CLOCK_REALTIME:
  374. tv.tv_sec = tp->tv_sec;
  375. tv.tv_usec = tp->tv_nsec / 1000L;
  376. settimeofday(&tv, NULL);
  377. break;
  378. default:
  379. errno = EINVAL;
  380. return -1;
  381. }
  382. return 0;
  383. #else
  384. errno = ENOSYS;
  385. return -1;
  386. #endif
  387. }
  388. int clock_gettime (clockid_t clock_id, struct timespec *tp)
  389. {
  390. #if defined( WITH_FRC ) || defined( WITH_RTC )
  391. if (tp == NULL) {
  392. errno = EINVAL;
  393. return -1;
  394. }
  395. struct timeval tv;
  396. uint64_t monotonic_time_us = 0;
  397. switch (clock_id) {
  398. case CLOCK_REALTIME:
  399. _gettimeofday_r(NULL, &tv, NULL);
  400. tp->tv_sec = tv.tv_sec;
  401. tp->tv_nsec = tv.tv_usec * 1000L;
  402. break;
  403. case CLOCK_MONOTONIC:
  404. #if defined( WITH_FRC )
  405. monotonic_time_us = (uint64_t) esp_timer_get_time();
  406. #elif defined( WITH_RTC )
  407. monotonic_time_us = get_rtc_time_us();
  408. #endif // WITH_FRC
  409. tp->tv_sec = monotonic_time_us / 1000000LL;
  410. tp->tv_nsec = (monotonic_time_us % 1000000LL) * 1000L;
  411. break;
  412. default:
  413. errno = EINVAL;
  414. return -1;
  415. }
  416. return 0;
  417. #else
  418. errno = ENOSYS;
  419. return -1;
  420. #endif
  421. }
  422. int clock_getres (clockid_t clock_id, struct timespec *res)
  423. {
  424. #if defined( WITH_FRC ) || defined( WITH_RTC )
  425. if (res == NULL) {
  426. errno = EINVAL;
  427. return -1;
  428. }
  429. #if defined( WITH_FRC )
  430. res->tv_sec = 0;
  431. res->tv_nsec = 1000L;
  432. #elif defined( WITH_RTC )
  433. res->tv_sec = 0;
  434. uint32_t rtc_freq = rtc_clk_slow_freq_get_hz();
  435. assert(rtc_freq != 0);
  436. res->tv_nsec = 1000000000L / rtc_freq;
  437. #endif // WITH_FRC
  438. return 0;
  439. #else
  440. errno = ENOSYS;
  441. return -1;
  442. #endif
  443. }