esp_timer_impl_lac.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2020 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 "sys/param.h"
  15. #include "esp_timer_impl.h"
  16. #include "esp_timer.h"
  17. #include "esp_err.h"
  18. #include "esp_system.h"
  19. #include "esp_task.h"
  20. #include "esp_attr.h"
  21. #include "esp_intr_alloc.h"
  22. #include "esp_log.h"
  23. #include "esp32/clk.h"
  24. #include "driver/periph_ctrl.h"
  25. #include "soc/soc.h"
  26. #include "soc/timer_group_reg.h"
  27. #include "soc/rtc.h"
  28. #include "freertos/FreeRTOS.h"
  29. /**
  30. * @file esp_timer_lac.c
  31. * @brief Implementation of chip-specific part of esp_timer
  32. *
  33. * This implementation uses TG0 LAC timer of the ESP32. This timer is
  34. * a 64-bit up-counting timer, with a programmable compare value (called 'alarm'
  35. * hereafter). When the timer reaches compare value, interrupt is raised.
  36. * The timer can be configured to produce an edge or a level interrupt.
  37. */
  38. /* Selects which Timer Group peripheral to use */
  39. #define LACT_MODULE 0
  40. #if LACT_MODULE == 0
  41. #define INTR_SOURCE_LACT ETS_TG0_LACT_LEVEL_INTR_SOURCE
  42. #define PERIPH_LACT PERIPH_TIMG0_MODULE
  43. #elif LACT_MODULE == 1
  44. #define INTR_SOURCE_LACT ETS_TG1_LACT_LEVEL_INTR_SOURCE
  45. #define PERIPH_LACT PERIPH_TIMG1_MODULE
  46. #else
  47. #error "Incorrect the number of LACT module (only 0 or 1)"
  48. #endif
  49. /* Desired number of timer ticks per microsecond.
  50. * This value should be small enough so that all possible APB frequencies
  51. * could be divided by it without remainder.
  52. * On the other hand, the smaller this value is, the longer we need to wait
  53. * after setting UPDATE_REG before the timer value can be read.
  54. * If TICKS_PER_US == 1, then we need to wait up to 1 microsecond, which
  55. * makes esp_timer_impl_get_time function take too much time.
  56. * The value TICKS_PER_US == 2 allows for most of the APB frequencies, and
  57. * allows reading the counter quickly enough.
  58. */
  59. #define TICKS_PER_US 2
  60. /* Shorter register names, used in this file */
  61. #define CONFIG_REG (TIMG_LACTCONFIG_REG(LACT_MODULE))
  62. #define RTC_STEP_REG (TIMG_LACTRTC_REG(LACT_MODULE))
  63. #define ALARM_LO_REG (TIMG_LACTALARMLO_REG(LACT_MODULE))
  64. #define ALARM_HI_REG (TIMG_LACTALARMHI_REG(LACT_MODULE))
  65. #define COUNT_LO_REG (TIMG_LACTLO_REG(LACT_MODULE))
  66. #define COUNT_HI_REG (TIMG_LACTHI_REG(LACT_MODULE))
  67. #define UPDATE_REG (TIMG_LACTUPDATE_REG(LACT_MODULE))
  68. #define LOAD_REG (TIMG_LACTLOAD_REG(LACT_MODULE))
  69. #define LOAD_LO_REG (TIMG_LACTLOADLO_REG(LACT_MODULE))
  70. #define LOAD_HI_REG (TIMG_LACTLOADHI_REG(LACT_MODULE))
  71. #define INT_ENA_REG (TIMG_INT_ENA_TIMERS_REG(LACT_MODULE))
  72. #define INT_ST_REG (TIMG_INT_ST_TIMERS_REG(LACT_MODULE))
  73. #define INT_CLR_REG (TIMG_INT_CLR_TIMERS_REG(LACT_MODULE))
  74. /* Helper type to convert between a 64-bit value and a pair of 32-bit values without shifts and masks */
  75. typedef struct {
  76. union {
  77. struct {
  78. uint32_t lo;
  79. uint32_t hi;
  80. };
  81. uint64_t val;
  82. };
  83. } timer_64b_reg_t;
  84. static const char* TAG = "esp_timer_impl";
  85. /* Interrupt handle returned by the interrupt allocator */
  86. static intr_handle_t s_timer_interrupt_handle;
  87. /* Function from the upper layer to be called when the interrupt happens.
  88. * Registered in esp_timer_impl_init.
  89. */
  90. static intr_handler_t s_alarm_handler = NULL;
  91. /* Spinlock used to protect access to the hardware registers. */
  92. portMUX_TYPE s_time_update_lock = portMUX_INITIALIZER_UNLOCKED;
  93. void esp_timer_impl_lock(void)
  94. {
  95. portENTER_CRITICAL(&s_time_update_lock);
  96. }
  97. void esp_timer_impl_unlock(void)
  98. {
  99. portEXIT_CRITICAL(&s_time_update_lock);
  100. }
  101. uint64_t IRAM_ATTR esp_timer_impl_get_counter_reg(void)
  102. {
  103. uint32_t lo, hi;
  104. uint32_t lo_start = REG_READ(COUNT_LO_REG);
  105. uint32_t div = REG_GET_FIELD(CONFIG_REG, TIMG_LACT_DIVIDER);
  106. /* The peripheral doesn't have a bit to indicate that the update is done, so we poll the
  107. * lower 32 bit part of the counter until it changes, or a timeout expires.
  108. */
  109. REG_WRITE(UPDATE_REG, 1);
  110. do {
  111. lo = REG_READ(COUNT_LO_REG);
  112. } while (lo == lo_start && div-- > 0);
  113. /* Since this function is called without a critical section, verify that LO and HI
  114. * registers are consistent. That is, if an interrupt happens between reading LO and
  115. * HI registers, and esp_timer_impl_get_time is called from an ISR, then try to
  116. * detect this by the change in LO register value, and re-read both registers.
  117. */
  118. do {
  119. lo_start = lo;
  120. hi = REG_READ(COUNT_HI_REG);
  121. lo = REG_READ(COUNT_LO_REG);
  122. } while (lo != lo_start);
  123. timer_64b_reg_t result = {
  124. .lo = lo,
  125. .hi = hi
  126. };
  127. return result.val;
  128. }
  129. int64_t IRAM_ATTR esp_timer_impl_get_time(void)
  130. {
  131. if (s_alarm_handler == NULL) {
  132. return 0;
  133. }
  134. return esp_timer_impl_get_counter_reg() / TICKS_PER_US;
  135. }
  136. int64_t esp_timer_get_time(void) __attribute__((alias("esp_timer_impl_get_time")));
  137. void IRAM_ATTR esp_timer_impl_set_alarm_id(uint64_t timestamp, unsigned alarm_id)
  138. {
  139. static uint64_t timestamp_id[2] = { UINT64_MAX, UINT64_MAX };
  140. portENTER_CRITICAL_SAFE(&s_time_update_lock);
  141. timestamp_id[alarm_id] = timestamp;
  142. timestamp = MIN(timestamp_id[0], timestamp_id[1]);
  143. if (timestamp != UINT64_MAX) {
  144. int64_t offset = TICKS_PER_US * 2;
  145. uint64_t now_time = esp_timer_impl_get_counter_reg();
  146. timer_64b_reg_t alarm = { .val = MAX(timestamp * TICKS_PER_US, now_time + offset) };
  147. do {
  148. REG_CLR_BIT(CONFIG_REG, TIMG_LACT_ALARM_EN);
  149. REG_WRITE(ALARM_LO_REG, alarm.lo);
  150. REG_WRITE(ALARM_HI_REG, alarm.hi);
  151. REG_SET_BIT(CONFIG_REG, TIMG_LACT_ALARM_EN);
  152. now_time = esp_timer_impl_get_counter_reg();
  153. int64_t delta = (int64_t)alarm.val - (int64_t)now_time;
  154. if (delta <= 0 && REG_GET_FIELD(INT_ST_REG, TIMG_LACT_INT_ST) == 0) {
  155. // new alarm is less than the counter and the interrupt flag is not set
  156. offset += abs((int)delta) + TICKS_PER_US * 2;
  157. alarm.val = now_time + offset;
  158. } else {
  159. // finish if either (alarm > counter) or the interrupt flag is already set.
  160. break;
  161. }
  162. } while(1);
  163. }
  164. portEXIT_CRITICAL_SAFE(&s_time_update_lock);
  165. }
  166. void IRAM_ATTR esp_timer_impl_set_alarm(uint64_t timestamp)
  167. {
  168. esp_timer_impl_set_alarm_id(timestamp, 0);
  169. }
  170. static void IRAM_ATTR timer_alarm_isr(void *arg)
  171. {
  172. /* Clear interrupt status */
  173. REG_WRITE(INT_CLR_REG, TIMG_LACT_INT_CLR);
  174. /* Call the upper layer handler */
  175. (*s_alarm_handler)(arg);
  176. }
  177. void IRAM_ATTR esp_timer_impl_update_apb_freq(uint32_t apb_ticks_per_us)
  178. {
  179. portENTER_CRITICAL(&s_time_update_lock);
  180. assert(apb_ticks_per_us >= 3 && "divider value too low");
  181. assert(apb_ticks_per_us % TICKS_PER_US == 0 && "APB frequency (in MHz) should be divisible by TICK_PER_US");
  182. REG_SET_FIELD(CONFIG_REG, TIMG_LACT_DIVIDER, apb_ticks_per_us / TICKS_PER_US);
  183. portEXIT_CRITICAL(&s_time_update_lock);
  184. }
  185. void esp_timer_impl_advance(int64_t time_diff_us)
  186. {
  187. portENTER_CRITICAL(&s_time_update_lock);
  188. uint64_t now = esp_timer_impl_get_time();
  189. timer_64b_reg_t dst = { .val = (now + time_diff_us) * TICKS_PER_US };
  190. REG_WRITE(LOAD_LO_REG, dst.lo);
  191. REG_WRITE(LOAD_HI_REG, dst.hi);
  192. REG_WRITE(LOAD_REG, 1);
  193. portEXIT_CRITICAL(&s_time_update_lock);
  194. }
  195. esp_err_t esp_timer_impl_init(intr_handler_t alarm_handler)
  196. {
  197. s_alarm_handler = alarm_handler;
  198. periph_module_enable(PERIPH_LACT);
  199. /* Reset the state */
  200. REG_WRITE(CONFIG_REG, 0);
  201. REG_WRITE(LOAD_LO_REG, 0);
  202. REG_WRITE(LOAD_HI_REG, 0);
  203. REG_WRITE(ALARM_LO_REG, UINT32_MAX);
  204. REG_WRITE(ALARM_HI_REG, UINT32_MAX);
  205. REG_WRITE(LOAD_REG, 1);
  206. REG_SET_BIT(INT_CLR_REG, TIMG_LACT_INT_CLR);
  207. const int interrupt_lvl = (1 << CONFIG_ESP_TIMER_INTERRUPT_LEVEL) & ESP_INTR_FLAG_LEVELMASK;
  208. esp_err_t err = esp_intr_alloc(INTR_SOURCE_LACT,
  209. ESP_INTR_FLAG_INTRDISABLED | ESP_INTR_FLAG_IRAM | interrupt_lvl,
  210. &timer_alarm_isr, NULL, &s_timer_interrupt_handle);
  211. if (err != ESP_OK) {
  212. ESP_EARLY_LOGE(TAG, "esp_intr_alloc failed (0x%0x)", err);
  213. return err;
  214. }
  215. /* In theory, this needs a shared spinlock with the timer group driver.
  216. * However since esp_timer_impl_init is called early at startup, this
  217. * will not cause issues in practice.
  218. */
  219. REG_SET_BIT(INT_ENA_REG, TIMG_LACT_INT_ENA);
  220. esp_timer_impl_update_apb_freq(esp_clk_apb_freq() / 1000000);
  221. REG_SET_BIT(CONFIG_REG, TIMG_LACT_INCREASE |
  222. TIMG_LACT_LEVEL_INT_EN |
  223. TIMG_LACT_EN);
  224. // Set the step for the sleep mode when the timer will work
  225. // from a slow_clk frequency instead of the APB frequency.
  226. uint32_t slowclk_ticks_per_us = esp_clk_slowclk_cal_get() * TICKS_PER_US;
  227. REG_SET_FIELD(RTC_STEP_REG, TIMG_LACT_RTC_STEP_LEN, slowclk_ticks_per_us);
  228. ESP_ERROR_CHECK( esp_intr_enable(s_timer_interrupt_handle) );
  229. return ESP_OK;
  230. }
  231. void esp_timer_impl_deinit(void)
  232. {
  233. REG_WRITE(CONFIG_REG, 0);
  234. REG_SET_BIT(INT_CLR_REG, TIMG_LACT_INT_CLR);
  235. /* TODO: also clear TIMG_LACT_INT_ENA; however see the note in esp_timer_impl_init. */
  236. esp_intr_disable(s_timer_interrupt_handle);
  237. esp_intr_free(s_timer_interrupt_handle);
  238. s_timer_interrupt_handle = NULL;
  239. }
  240. /* FIXME: This value is safe for 80MHz APB frequency, should be modified to depend on clock frequency. */
  241. uint64_t IRAM_ATTR esp_timer_impl_get_min_period_us(void)
  242. {
  243. return 50;
  244. }
  245. uint64_t esp_timer_impl_get_alarm_reg(void)
  246. {
  247. portENTER_CRITICAL_SAFE(&s_time_update_lock);
  248. timer_64b_reg_t alarm = {
  249. .lo = REG_READ(ALARM_LO_REG),
  250. .hi = REG_READ(ALARM_HI_REG)
  251. };
  252. portEXIT_CRITICAL_SAFE(&s_time_update_lock);
  253. return alarm.val;
  254. }
  255. void esp_timer_private_update_apb_freq(uint32_t apb_ticks_per_us) __attribute__((alias("esp_timer_impl_update_apb_freq")));
  256. void esp_timer_private_advance(int64_t time_us) __attribute__((alias("esp_timer_impl_advance")));
  257. void esp_timer_private_lock(void) __attribute__((alias("esp_timer_impl_lock")));
  258. void esp_timer_private_unlock(void) __attribute__((alias("esp_timer_impl_unlock")));