time.c 13 KB

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