time.c 14 KB

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