esp_timer_impl_lac.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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(uint64_t timestamp)
  138. {
  139. portENTER_CRITICAL_SAFE(&s_time_update_lock);
  140. int64_t offset = TICKS_PER_US * 2;
  141. uint64_t now_time = esp_timer_impl_get_counter_reg();
  142. timer_64b_reg_t alarm = { .val = MAX(timestamp * TICKS_PER_US, now_time + offset) };
  143. do {
  144. REG_CLR_BIT(CONFIG_REG, TIMG_LACT_ALARM_EN);
  145. REG_WRITE(ALARM_LO_REG, alarm.lo);
  146. REG_WRITE(ALARM_HI_REG, alarm.hi);
  147. REG_SET_BIT(CONFIG_REG, TIMG_LACT_ALARM_EN);
  148. now_time = esp_timer_impl_get_counter_reg();
  149. int64_t delta = (int64_t)alarm.val - (int64_t)now_time;
  150. if (delta <= 0 && REG_GET_FIELD(INT_ST_REG, TIMG_LACT_INT_ST) == 0) {
  151. // new alarm is less than the counter and the interrupt flag is not set
  152. offset += abs((int)delta) + TICKS_PER_US * 2;
  153. alarm.val = now_time + offset;
  154. } else {
  155. // finish if either (alarm > counter) or the interrupt flag is already set.
  156. break;
  157. }
  158. } while(1);
  159. portEXIT_CRITICAL_SAFE(&s_time_update_lock);
  160. }
  161. static void IRAM_ATTR timer_alarm_isr(void *arg)
  162. {
  163. /* Clear interrupt status */
  164. REG_WRITE(INT_CLR_REG, TIMG_LACT_INT_CLR);
  165. /* Call the upper layer handler */
  166. (*s_alarm_handler)(arg);
  167. }
  168. void IRAM_ATTR esp_timer_impl_update_apb_freq(uint32_t apb_ticks_per_us)
  169. {
  170. portENTER_CRITICAL(&s_time_update_lock);
  171. assert(apb_ticks_per_us >= 3 && "divider value too low");
  172. assert(apb_ticks_per_us % TICKS_PER_US == 0 && "APB frequency (in MHz) should be divisible by TICK_PER_US");
  173. REG_SET_FIELD(CONFIG_REG, TIMG_LACT_DIVIDER, apb_ticks_per_us / TICKS_PER_US);
  174. portEXIT_CRITICAL(&s_time_update_lock);
  175. }
  176. void esp_timer_impl_advance(int64_t time_diff_us)
  177. {
  178. portENTER_CRITICAL(&s_time_update_lock);
  179. uint64_t now = esp_timer_impl_get_time();
  180. timer_64b_reg_t dst = { .val = (now + time_diff_us) * TICKS_PER_US };
  181. REG_WRITE(LOAD_LO_REG, dst.lo);
  182. REG_WRITE(LOAD_HI_REG, dst.hi);
  183. REG_WRITE(LOAD_REG, 1);
  184. portEXIT_CRITICAL(&s_time_update_lock);
  185. }
  186. esp_err_t esp_timer_impl_init(intr_handler_t alarm_handler)
  187. {
  188. s_alarm_handler = alarm_handler;
  189. periph_module_enable(PERIPH_LACT);
  190. /* Reset the state */
  191. REG_WRITE(CONFIG_REG, 0);
  192. REG_WRITE(LOAD_LO_REG, 0);
  193. REG_WRITE(LOAD_HI_REG, 0);
  194. REG_WRITE(ALARM_LO_REG, UINT32_MAX);
  195. REG_WRITE(ALARM_HI_REG, UINT32_MAX);
  196. REG_WRITE(LOAD_REG, 1);
  197. REG_SET_BIT(INT_CLR_REG, TIMG_LACT_INT_CLR);
  198. esp_err_t err = esp_intr_alloc(INTR_SOURCE_LACT,
  199. ESP_INTR_FLAG_INTRDISABLED | ESP_INTR_FLAG_IRAM,
  200. &timer_alarm_isr, NULL, &s_timer_interrupt_handle);
  201. if (err != ESP_OK) {
  202. ESP_EARLY_LOGE(TAG, "esp_intr_alloc failed (0x%0x)", err);
  203. return err;
  204. }
  205. /* In theory, this needs a shared spinlock with the timer group driver.
  206. * However since esp_timer_impl_init is called early at startup, this
  207. * will not cause issues in practice.
  208. */
  209. REG_SET_BIT(INT_ENA_REG, TIMG_LACT_INT_ENA);
  210. esp_timer_impl_update_apb_freq(esp_clk_apb_freq() / 1000000);
  211. REG_SET_BIT(CONFIG_REG, TIMG_LACT_INCREASE |
  212. TIMG_LACT_LEVEL_INT_EN |
  213. TIMG_LACT_EN);
  214. // Set the step for the sleep mode when the timer will work
  215. // from a slow_clk frequency instead of the APB frequency.
  216. uint32_t slowclk_ticks_per_us = esp_clk_slowclk_cal_get() * TICKS_PER_US;
  217. REG_SET_FIELD(RTC_STEP_REG, TIMG_LACT_RTC_STEP_LEN, slowclk_ticks_per_us);
  218. ESP_ERROR_CHECK( esp_intr_enable(s_timer_interrupt_handle) );
  219. return ESP_OK;
  220. }
  221. void esp_timer_impl_deinit(void)
  222. {
  223. REG_WRITE(CONFIG_REG, 0);
  224. REG_SET_BIT(INT_CLR_REG, TIMG_LACT_INT_CLR);
  225. /* TODO: also clear TIMG_LACT_INT_ENA; however see the note in esp_timer_impl_init. */
  226. esp_intr_disable(s_timer_interrupt_handle);
  227. esp_intr_free(s_timer_interrupt_handle);
  228. s_timer_interrupt_handle = NULL;
  229. }
  230. /* FIXME: This value is safe for 80MHz APB frequency, should be modified to depend on clock frequency. */
  231. uint64_t IRAM_ATTR esp_timer_impl_get_min_period_us(void)
  232. {
  233. return 50;
  234. }
  235. uint64_t esp_timer_impl_get_alarm_reg(void)
  236. {
  237. portENTER_CRITICAL_SAFE(&s_time_update_lock);
  238. timer_64b_reg_t alarm = {
  239. .lo = REG_READ(ALARM_LO_REG),
  240. .hi = REG_READ(ALARM_HI_REG)
  241. };
  242. portEXIT_CRITICAL_SAFE(&s_time_update_lock);
  243. return alarm.val;
  244. }
  245. void esp_timer_private_update_apb_freq(uint32_t apb_ticks_per_us) __attribute__((alias("esp_timer_impl_update_apb_freq")));
  246. void esp_timer_private_advance(int64_t time_us) __attribute__((alias("esp_timer_impl_advance")));
  247. void esp_timer_private_lock(void) __attribute__((alias("esp_timer_impl_lock")));
  248. void esp_timer_private_unlock(void) __attribute__((alias("esp_timer_impl_unlock")));