time.c 13 KB

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