esp_timer.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. /*
  2. * SPDX-FileCopyrightText: 2017-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <sys/param.h>
  7. #include <string.h>
  8. #include "soc/soc.h"
  9. #include "esp_types.h"
  10. #include "esp_attr.h"
  11. #include "esp_err.h"
  12. #include "esp_task.h"
  13. #include "esp_log.h"
  14. #include "freertos/FreeRTOS.h"
  15. #include "freertos/task.h"
  16. #include "freertos/semphr.h"
  17. #include "esp_ipc.h"
  18. #include "esp_timer.h"
  19. #include "esp_timer_impl.h"
  20. #include "esp_private/startup_internal.h"
  21. #include "esp_private/esp_timer_private.h"
  22. #include "esp_private/system_internal.h"
  23. #if CONFIG_IDF_TARGET_ESP32
  24. #include "esp32/rtc.h"
  25. #elif CONFIG_IDF_TARGET_ESP32S2
  26. #include "esp32s2/rtc.h"
  27. #elif CONFIG_IDF_TARGET_ESP32S3
  28. #include "esp32s3/rtc.h"
  29. #elif CONFIG_IDF_TARGET_ESP32C3
  30. #include "esp32c3/rtc.h"
  31. #elif CONFIG_IDF_TARGET_ESP32C2
  32. #include "esp32c2/rtc.h"
  33. #elif CONFIG_IDF_TARGET_ESP32C6
  34. #include "esp32c6/rtc.h"
  35. #elif CONFIG_IDF_TARGET_ESP32H2
  36. #include "esp32h2/rtc.h"
  37. #elif CONFIG_IDF_TARGET_ESP32P4
  38. #include "esp32p4/rtc.h"
  39. #endif
  40. #include "sdkconfig.h"
  41. #ifdef CONFIG_ESP_TIMER_PROFILING
  42. #define WITH_PROFILING 1
  43. #endif
  44. #ifndef NDEBUG
  45. // Enable built-in checks in queue.h in debug builds
  46. #define INVARIANTS
  47. #endif
  48. #include "sys/queue.h"
  49. #define EVENT_ID_DELETE_TIMER 0xF0DE1E1E
  50. typedef enum {
  51. FL_ISR_DISPATCH_METHOD = (1 << 0), //!< 0=Callback is called from timer task, 1=Callback is called from timer ISR
  52. FL_SKIP_UNHANDLED_EVENTS = (1 << 1), //!< 0=NOT skip unhandled events for periodic timers, 1=Skip unhandled events for periodic timers
  53. } flags_t;
  54. struct esp_timer {
  55. uint64_t alarm;
  56. uint64_t period:56;
  57. flags_t flags:8;
  58. union {
  59. esp_timer_cb_t callback;
  60. uint32_t event_id;
  61. };
  62. void* arg;
  63. #if WITH_PROFILING
  64. const char* name;
  65. size_t times_triggered;
  66. size_t times_armed;
  67. size_t times_skipped;
  68. uint64_t total_callback_run_time;
  69. #endif // WITH_PROFILING
  70. LIST_ENTRY(esp_timer) list_entry;
  71. };
  72. static inline bool is_initialized(void);
  73. static esp_err_t timer_insert(esp_timer_handle_t timer, bool without_update_alarm);
  74. static esp_err_t timer_remove(esp_timer_handle_t timer);
  75. static bool timer_armed(esp_timer_handle_t timer);
  76. static void timer_list_lock(esp_timer_dispatch_t timer_type);
  77. static void timer_list_unlock(esp_timer_dispatch_t timer_type);
  78. #if WITH_PROFILING
  79. static void timer_insert_inactive(esp_timer_handle_t timer);
  80. static void timer_remove_inactive(esp_timer_handle_t timer);
  81. #endif // WITH_PROFILING
  82. __attribute__((unused)) static const char* TAG = "esp_timer";
  83. // lists of currently armed timers for two dispatch methods: ISR and TASK
  84. static LIST_HEAD(esp_timer_list, esp_timer) s_timers[ESP_TIMER_MAX] = {
  85. [0 ... (ESP_TIMER_MAX - 1)] = LIST_HEAD_INITIALIZER(s_timers)
  86. };
  87. #if WITH_PROFILING
  88. // lists of unarmed timers for two dispatch methods: ISR and TASK,
  89. // used only to be able to dump statistics about all the timers
  90. static LIST_HEAD(esp_inactive_timer_list, esp_timer) s_inactive_timers[ESP_TIMER_MAX] = {
  91. [0 ... (ESP_TIMER_MAX - 1)] = LIST_HEAD_INITIALIZER(s_timers)
  92. };
  93. #endif
  94. // task used to dispatch timer callbacks
  95. static TaskHandle_t s_timer_task;
  96. // lock protecting s_timers, s_inactive_timers
  97. static portMUX_TYPE s_timer_lock[ESP_TIMER_MAX] = {
  98. [0 ... (ESP_TIMER_MAX - 1)] = portMUX_INITIALIZER_UNLOCKED
  99. };
  100. #ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
  101. // For ISR dispatch method, a callback function of the timer may require a context switch
  102. static volatile BaseType_t s_isr_dispatch_need_yield = pdFALSE;
  103. #endif // CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
  104. esp_err_t esp_timer_create(const esp_timer_create_args_t* args,
  105. esp_timer_handle_t* out_handle)
  106. {
  107. if (!is_initialized()) {
  108. return ESP_ERR_INVALID_STATE;
  109. }
  110. if (args == NULL || args->callback == NULL || out_handle == NULL ||
  111. args->dispatch_method < 0 || args->dispatch_method >= ESP_TIMER_MAX) {
  112. return ESP_ERR_INVALID_ARG;
  113. }
  114. esp_timer_handle_t result = (esp_timer_handle_t) heap_caps_calloc(1, sizeof(*result), MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  115. if (result == NULL) {
  116. return ESP_ERR_NO_MEM;
  117. }
  118. result->callback = args->callback;
  119. result->arg = args->arg;
  120. result->flags = (args->dispatch_method ? FL_ISR_DISPATCH_METHOD : 0) |
  121. (args->skip_unhandled_events ? FL_SKIP_UNHANDLED_EVENTS : 0);
  122. #if WITH_PROFILING
  123. result->name = args->name;
  124. esp_timer_dispatch_t dispatch_method = result->flags & FL_ISR_DISPATCH_METHOD;
  125. timer_list_lock(dispatch_method);
  126. timer_insert_inactive(result);
  127. timer_list_unlock(dispatch_method);
  128. #endif
  129. *out_handle = result;
  130. return ESP_OK;
  131. }
  132. /*
  133. * We have placed this function in IRAM to ensure consistency with the esp_timer API.
  134. * esp_timer_start_once, esp_timer_start_periodic and esp_timer_stop are in IRAM.
  135. * But actually in IDF esp_timer_restart is used only in one place, which requires keeping
  136. * in IRAM when PM_SLP_IRAM_OPT = y and ESP_TASK_WDT USE ESP_TIMER = y.
  137. */
  138. esp_err_t IRAM_ATTR esp_timer_restart(esp_timer_handle_t timer, uint64_t timeout_us)
  139. {
  140. esp_err_t ret = ESP_OK;
  141. if (timer == NULL) {
  142. return ESP_ERR_INVALID_ARG;
  143. }
  144. if (!is_initialized() || !timer_armed(timer)) {
  145. return ESP_ERR_INVALID_STATE;
  146. }
  147. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  148. timer_list_lock(dispatch_method);
  149. const int64_t now = esp_timer_impl_get_time();
  150. const uint64_t period = timer->period;
  151. /* We need to remove the timer to the list of timers and reinsert it at
  152. * the right position. In fact, the timers are sorted by their alarm value
  153. * (earliest first) */
  154. ret = timer_remove(timer);
  155. if (ret == ESP_OK) {
  156. /* Two cases here:
  157. * - if the alarm was a periodic one, i.e. `period` is not 0, the given timeout_us becomes the new period
  158. * - if the alarm was a one-shot one, i.e. `period` is 0, it remains non-periodic. */
  159. if (period != 0) {
  160. /* Remove function got rid of the alarm and period fields, restore them */
  161. const uint64_t new_period = MAX(timeout_us, esp_timer_impl_get_min_period_us());
  162. timer->alarm = now + new_period;
  163. timer->period = new_period;
  164. } else {
  165. /* The new one-shot alarm shall be triggered timeout_us after the current time */
  166. timer->alarm = now + timeout_us;
  167. timer->period = 0;
  168. }
  169. ret = timer_insert(timer, false);
  170. }
  171. timer_list_unlock(dispatch_method);
  172. return ret;
  173. }
  174. esp_err_t IRAM_ATTR esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us)
  175. {
  176. if (timer == NULL) {
  177. return ESP_ERR_INVALID_ARG;
  178. }
  179. if (!is_initialized()) {
  180. return ESP_ERR_INVALID_STATE;
  181. }
  182. int64_t alarm = esp_timer_get_time() + timeout_us;
  183. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  184. esp_err_t err;
  185. timer_list_lock(dispatch_method);
  186. /* Check if the timer is armed once the list is locked.
  187. * Otherwise another task may arm the timer inbetween the check
  188. * and us locking the list, resulting in us inserting the
  189. * timer to s_timers a second time. This will create a loop
  190. * in s_timers. */
  191. if (timer_armed(timer)) {
  192. err = ESP_ERR_INVALID_STATE;
  193. } else {
  194. timer->alarm = alarm;
  195. timer->period = 0;
  196. #if WITH_PROFILING
  197. timer->times_armed++;
  198. #endif
  199. err = timer_insert(timer, false);
  200. }
  201. timer_list_unlock(dispatch_method);
  202. return err;
  203. }
  204. esp_err_t IRAM_ATTR esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period_us)
  205. {
  206. if (timer == NULL) {
  207. return ESP_ERR_INVALID_ARG;
  208. }
  209. if (!is_initialized()) {
  210. return ESP_ERR_INVALID_STATE;
  211. }
  212. period_us = MAX(period_us, esp_timer_impl_get_min_period_us());
  213. int64_t alarm = esp_timer_get_time() + period_us;
  214. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  215. esp_err_t err;
  216. timer_list_lock(dispatch_method);
  217. /* Check if the timer is armed once the list is locked to avoid a data race */
  218. if (timer_armed(timer)) {
  219. err = ESP_ERR_INVALID_STATE;
  220. } else {
  221. timer->alarm = alarm;
  222. timer->period = period_us;
  223. #if WITH_PROFILING
  224. timer->times_armed++;
  225. timer->times_skipped = 0;
  226. #endif
  227. err = timer_insert(timer, false);
  228. }
  229. timer_list_unlock(dispatch_method);
  230. return err;
  231. }
  232. esp_err_t IRAM_ATTR esp_timer_stop(esp_timer_handle_t timer)
  233. {
  234. if (timer == NULL) {
  235. return ESP_ERR_INVALID_ARG;
  236. }
  237. if (!is_initialized()) {
  238. return ESP_ERR_INVALID_STATE;
  239. }
  240. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  241. esp_err_t err;
  242. timer_list_lock(dispatch_method);
  243. /* Check if the timer is armed once the list is locked to avoid a data race */
  244. if (!timer_armed(timer)) {
  245. err = ESP_ERR_INVALID_STATE;
  246. } else {
  247. err = timer_remove(timer);
  248. }
  249. timer_list_unlock(dispatch_method);
  250. return err;
  251. }
  252. esp_err_t esp_timer_delete(esp_timer_handle_t timer)
  253. {
  254. if (timer == NULL) {
  255. return ESP_ERR_INVALID_ARG;
  256. }
  257. int64_t alarm = esp_timer_get_time();
  258. esp_err_t err;
  259. timer_list_lock(ESP_TIMER_TASK);
  260. /* Check if the timer is armed once the list is locked to avoid a data race */
  261. if (timer_armed(timer)) {
  262. err = ESP_ERR_INVALID_STATE;
  263. } else {
  264. // A case for the timer with ESP_TIMER_ISR:
  265. // This ISR timer was removed from the ISR list in esp_timer_stop() or in timer_process_alarm() -> LIST_REMOVE(it, list_entry)
  266. // and here this timer will be added to another the TASK list, see below.
  267. // We do this because we want to free memory of the timer in a task context instead of an isr context.
  268. timer->flags &= ~FL_ISR_DISPATCH_METHOD;
  269. timer->event_id = EVENT_ID_DELETE_TIMER;
  270. timer->alarm = alarm;
  271. timer->period = 0;
  272. err = timer_insert(timer, false);
  273. }
  274. timer_list_unlock(ESP_TIMER_TASK);
  275. return err;
  276. }
  277. static IRAM_ATTR esp_err_t timer_insert(esp_timer_handle_t timer, bool without_update_alarm)
  278. {
  279. #if WITH_PROFILING
  280. timer_remove_inactive(timer);
  281. #endif
  282. esp_timer_handle_t it, last = NULL;
  283. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  284. if (LIST_FIRST(&s_timers[dispatch_method]) == NULL) {
  285. LIST_INSERT_HEAD(&s_timers[dispatch_method], timer, list_entry);
  286. } else {
  287. LIST_FOREACH(it, &s_timers[dispatch_method], list_entry) {
  288. if (timer->alarm < it->alarm) {
  289. LIST_INSERT_BEFORE(it, timer, list_entry);
  290. break;
  291. }
  292. last = it;
  293. }
  294. if (it == NULL) {
  295. assert(last);
  296. LIST_INSERT_AFTER(last, timer, list_entry);
  297. }
  298. }
  299. if (without_update_alarm == false && timer == LIST_FIRST(&s_timers[dispatch_method])) {
  300. esp_timer_impl_set_alarm_id(timer->alarm, dispatch_method);
  301. }
  302. return ESP_OK;
  303. }
  304. static IRAM_ATTR esp_err_t timer_remove(esp_timer_handle_t timer)
  305. {
  306. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  307. timer_list_lock(dispatch_method);
  308. esp_timer_handle_t first_timer = LIST_FIRST(&s_timers[dispatch_method]);
  309. LIST_REMOVE(timer, list_entry);
  310. timer->alarm = 0;
  311. timer->period = 0;
  312. if (timer == first_timer) { // if this timer was the first in the list.
  313. uint64_t next_timestamp = UINT64_MAX;
  314. first_timer = LIST_FIRST(&s_timers[dispatch_method]);
  315. if (first_timer) { // if after removing the timer from the list, this list is not empty.
  316. next_timestamp = first_timer->alarm;
  317. }
  318. esp_timer_impl_set_alarm_id(next_timestamp, dispatch_method);
  319. }
  320. #if WITH_PROFILING
  321. timer_insert_inactive(timer);
  322. #endif
  323. timer_list_unlock(dispatch_method);
  324. return ESP_OK;
  325. }
  326. #if WITH_PROFILING
  327. static IRAM_ATTR void timer_insert_inactive(esp_timer_handle_t timer)
  328. {
  329. /* May be locked or not, depending on where this is called from.
  330. * Lock recursively.
  331. */
  332. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  333. esp_timer_handle_t head = LIST_FIRST(&s_inactive_timers[dispatch_method]);
  334. if (head == NULL) {
  335. LIST_INSERT_HEAD(&s_inactive_timers[dispatch_method], timer, list_entry);
  336. } else {
  337. /* Insert as head element as this is the fastest thing to do.
  338. * Removal is O(1) anyway.
  339. */
  340. LIST_INSERT_BEFORE(head, timer, list_entry);
  341. }
  342. }
  343. static IRAM_ATTR void timer_remove_inactive(esp_timer_handle_t timer)
  344. {
  345. LIST_REMOVE(timer, list_entry);
  346. }
  347. #endif // WITH_PROFILING
  348. static IRAM_ATTR bool timer_armed(esp_timer_handle_t timer)
  349. {
  350. return timer->alarm > 0;
  351. }
  352. static IRAM_ATTR void timer_list_lock(esp_timer_dispatch_t timer_type)
  353. {
  354. portENTER_CRITICAL_SAFE(&s_timer_lock[timer_type]);
  355. }
  356. static IRAM_ATTR void timer_list_unlock(esp_timer_dispatch_t timer_type)
  357. {
  358. portEXIT_CRITICAL_SAFE(&s_timer_lock[timer_type]);
  359. }
  360. #ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
  361. static IRAM_ATTR bool timer_process_alarm(esp_timer_dispatch_t dispatch_method)
  362. #else
  363. static bool timer_process_alarm(esp_timer_dispatch_t dispatch_method)
  364. #endif
  365. {
  366. timer_list_lock(dispatch_method);
  367. bool processed = false;
  368. esp_timer_handle_t it;
  369. while (1) {
  370. it = LIST_FIRST(&s_timers[dispatch_method]);
  371. int64_t now = esp_timer_impl_get_time();
  372. if (it == NULL || it->alarm > now) {
  373. break;
  374. }
  375. processed = true;
  376. LIST_REMOVE(it, list_entry);
  377. if (it->event_id == EVENT_ID_DELETE_TIMER) {
  378. // It is handled only by ESP_TIMER_TASK (see esp_timer_delete()).
  379. // All the ESP_TIMER_ISR timers which should be deleted are moved by esp_timer_delete() to the ESP_TIMER_TASK list.
  380. // We want to free memory of the timer in a task context instead of an isr context.
  381. free(it);
  382. it = NULL;
  383. } else {
  384. if (it->period > 0) {
  385. int skipped = (now - it->alarm) / it->period;
  386. if ((it->flags & FL_SKIP_UNHANDLED_EVENTS) && (skipped > 1)) {
  387. it->alarm = now + it->period;
  388. #if WITH_PROFILING
  389. it->times_skipped += skipped;
  390. #endif
  391. } else {
  392. it->alarm += it->period;
  393. }
  394. timer_insert(it, true);
  395. } else {
  396. it->alarm = 0;
  397. #if WITH_PROFILING
  398. timer_insert_inactive(it);
  399. #endif
  400. }
  401. #if WITH_PROFILING
  402. uint64_t callback_start = now;
  403. #endif
  404. esp_timer_cb_t callback = it->callback;
  405. void* arg = it->arg;
  406. timer_list_unlock(dispatch_method);
  407. (*callback)(arg);
  408. timer_list_lock(dispatch_method);
  409. #if WITH_PROFILING
  410. it->times_triggered++;
  411. it->total_callback_run_time += esp_timer_impl_get_time() - callback_start;
  412. #endif
  413. }
  414. } // while(1)
  415. if (it) {
  416. if (dispatch_method == ESP_TIMER_TASK || (dispatch_method != ESP_TIMER_TASK && processed == true)) {
  417. esp_timer_impl_set_alarm_id(it->alarm, dispatch_method);
  418. }
  419. } else {
  420. if (processed) {
  421. esp_timer_impl_set_alarm_id(UINT64_MAX, dispatch_method);
  422. }
  423. }
  424. timer_list_unlock(dispatch_method);
  425. return processed;
  426. }
  427. static void timer_task(void* arg)
  428. {
  429. while (true){
  430. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  431. // all deferred events are processed at a time
  432. timer_process_alarm(ESP_TIMER_TASK);
  433. }
  434. }
  435. #ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
  436. IRAM_ATTR void esp_timer_isr_dispatch_need_yield(void)
  437. {
  438. assert(xPortInIsrContext());
  439. s_isr_dispatch_need_yield = pdTRUE;
  440. }
  441. #endif
  442. static void IRAM_ATTR timer_alarm_handler(void* arg)
  443. {
  444. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  445. bool isr_timers_processed = false;
  446. #ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
  447. esp_timer_impl_try_to_set_next_alarm();
  448. // process timers with ISR dispatch method
  449. isr_timers_processed = timer_process_alarm(ESP_TIMER_ISR);
  450. xHigherPriorityTaskWoken = s_isr_dispatch_need_yield;
  451. s_isr_dispatch_need_yield = pdFALSE;
  452. #endif
  453. if (isr_timers_processed == false) {
  454. vTaskNotifyGiveFromISR(s_timer_task, &xHigherPriorityTaskWoken);
  455. }
  456. if (xHigherPriorityTaskWoken == pdTRUE) {
  457. portYIELD_FROM_ISR();
  458. }
  459. }
  460. static IRAM_ATTR inline bool is_initialized(void)
  461. {
  462. return s_timer_task != NULL;
  463. }
  464. esp_err_t esp_timer_early_init(void)
  465. {
  466. esp_timer_impl_early_init();
  467. #if CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER
  468. esp_timer_impl_init_system_time();
  469. #endif
  470. return ESP_OK;
  471. }
  472. static esp_err_t init_timer_task(void)
  473. {
  474. esp_err_t err = ESP_OK;
  475. if (is_initialized()) {
  476. ESP_EARLY_LOGE(TAG, "Task is already initialized");
  477. err = ESP_ERR_INVALID_STATE;
  478. } else {
  479. int ret = xTaskCreatePinnedToCore(
  480. &timer_task, "esp_timer",
  481. ESP_TASK_TIMER_STACK, NULL, ESP_TASK_TIMER_PRIO,
  482. &s_timer_task, CONFIG_ESP_TIMER_TASK_AFFINITY);
  483. if (ret != pdPASS) {
  484. ESP_EARLY_LOGE(TAG, "Not enough memory to create timer task");
  485. err = ESP_ERR_NO_MEM;
  486. }
  487. }
  488. return err;
  489. }
  490. static void deinit_timer_task(void)
  491. {
  492. if (s_timer_task) {
  493. vTaskDelete(s_timer_task);
  494. s_timer_task = NULL;
  495. }
  496. }
  497. esp_err_t esp_timer_init(void)
  498. {
  499. esp_err_t err = ESP_OK;
  500. #ifndef CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY
  501. err = init_timer_task();
  502. #else
  503. /* This function will be run on all cores if CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY is enabled,
  504. * We do it that way because we need to allocate the timer ISR on MULTIPLE cores.
  505. * timer task will be created by CPU0.
  506. */
  507. if (xPortGetCoreID() == 0) {
  508. err = init_timer_task();
  509. }
  510. #endif // CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY
  511. if (err == ESP_OK) {
  512. err = esp_timer_impl_init(&timer_alarm_handler);
  513. if (err != ESP_OK) {
  514. ESP_EARLY_LOGE(TAG, "ISR init failed");
  515. deinit_timer_task();
  516. }
  517. }
  518. return err;
  519. }
  520. ESP_SYSTEM_INIT_FN(esp_timer_startup_init, CONFIG_ESP_TIMER_ISR_AFFINITY, 100)
  521. {
  522. return esp_timer_init();
  523. }
  524. esp_err_t esp_timer_deinit(void)
  525. {
  526. if (!is_initialized()) {
  527. return ESP_ERR_INVALID_STATE;
  528. }
  529. /* Check if there are any active timers */
  530. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  531. if (!LIST_EMPTY(&s_timers[dispatch_method])) {
  532. return ESP_ERR_INVALID_STATE;
  533. }
  534. }
  535. /* We can only check if there are any timers which are not deleted if
  536. * profiling is enabled.
  537. */
  538. #if WITH_PROFILING
  539. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  540. if (!LIST_EMPTY(&s_inactive_timers[dispatch_method])) {
  541. return ESP_ERR_INVALID_STATE;
  542. }
  543. }
  544. #endif
  545. esp_timer_impl_deinit();
  546. deinit_timer_task();
  547. return ESP_OK;
  548. }
  549. static void print_timer_info(esp_timer_handle_t t, char** dst, size_t* dst_size)
  550. {
  551. #if WITH_PROFILING
  552. size_t cb;
  553. // name is optional, might be missed.
  554. if (t->name) {
  555. cb = snprintf(*dst, *dst_size, "%-20.20s ", t->name);
  556. } else {
  557. cb = snprintf(*dst, *dst_size, "timer@%-10p ", t);
  558. }
  559. cb += snprintf(*dst + cb, *dst_size + cb, "%-10lld %-12lld %-12d %-12d %-12d %-12lld\n",
  560. (uint64_t)t->period, t->alarm, t->times_armed,
  561. t->times_triggered, t->times_skipped, t->total_callback_run_time);
  562. /* keep this in sync with the format string, used in esp_timer_dump */
  563. #define TIMER_INFO_LINE_LEN 90
  564. #else
  565. size_t cb = snprintf(*dst, *dst_size, "timer@%-14p %-10lld %-12lld\n", t, (uint64_t)t->period, t->alarm);
  566. #define TIMER_INFO_LINE_LEN 46
  567. #endif
  568. *dst += cb;
  569. *dst_size -= cb;
  570. }
  571. esp_err_t esp_timer_dump(FILE* stream)
  572. {
  573. /* Since timer lock is a critical section, we don't want to print directly
  574. * to stdout, since that may cause a deadlock if stdout is interrupt-driven
  575. * (via the UART driver). Allocate sufficiently large chunk of memory first,
  576. * print to it, then dump this memory to stdout.
  577. */
  578. esp_timer_handle_t it;
  579. /* First count the number of timers */
  580. size_t timer_count = 0;
  581. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  582. timer_list_lock(dispatch_method);
  583. LIST_FOREACH(it, &s_timers[dispatch_method], list_entry) {
  584. ++timer_count;
  585. }
  586. #if WITH_PROFILING
  587. LIST_FOREACH(it, &s_inactive_timers[dispatch_method], list_entry) {
  588. ++timer_count;
  589. }
  590. #endif
  591. timer_list_unlock(dispatch_method);
  592. }
  593. /* Allocate the memory for this number of timers. Since we have unlocked,
  594. * we may find that there are more timers. There's no bulletproof solution
  595. * for this (can't allocate from a critical section), but we allocate
  596. * slightly more and the output will be truncated if that is not enough.
  597. */
  598. size_t buf_size = TIMER_INFO_LINE_LEN * (timer_count + 3);
  599. char* print_buf = calloc(1, buf_size + 1);
  600. if (print_buf == NULL) {
  601. return ESP_ERR_NO_MEM;
  602. }
  603. /* Print to the buffer */
  604. char* pos = print_buf;
  605. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  606. timer_list_lock(dispatch_method);
  607. LIST_FOREACH(it, &s_timers[dispatch_method], list_entry) {
  608. print_timer_info(it, &pos, &buf_size);
  609. }
  610. #if WITH_PROFILING
  611. LIST_FOREACH(it, &s_inactive_timers[dispatch_method], list_entry) {
  612. print_timer_info(it, &pos, &buf_size);
  613. }
  614. #endif
  615. timer_list_unlock(dispatch_method);
  616. }
  617. if (stream != NULL) {
  618. fprintf(stream, "Timer stats:\n");
  619. #if WITH_PROFILING
  620. fprintf(stream, "%-20s %-10s %-12s %-12s %-12s %-12s %-12s\n",
  621. "Name", "Period", "Alarm", "Times_armed", "Times_trigg", "Times_skip", "Cb_exec_time");
  622. #else
  623. fprintf(stream, "%-20s %-10s %-12s\n", "Name", "Period", "Alarm");
  624. #endif
  625. /* Print the buffer */
  626. fputs(print_buf, stream);
  627. }
  628. free(print_buf);
  629. return ESP_OK;
  630. }
  631. int64_t IRAM_ATTR esp_timer_get_next_alarm(void)
  632. {
  633. int64_t next_alarm = INT64_MAX;
  634. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  635. timer_list_lock(dispatch_method);
  636. esp_timer_handle_t it = LIST_FIRST(&s_timers[dispatch_method]);
  637. if (it) {
  638. if (next_alarm > it->alarm) {
  639. next_alarm = it->alarm;
  640. }
  641. }
  642. timer_list_unlock(dispatch_method);
  643. }
  644. return next_alarm;
  645. }
  646. int64_t IRAM_ATTR esp_timer_get_next_alarm_for_wake_up(void)
  647. {
  648. int64_t next_alarm = INT64_MAX;
  649. for (esp_timer_dispatch_t dispatch_method = ESP_TIMER_TASK; dispatch_method < ESP_TIMER_MAX; ++dispatch_method) {
  650. timer_list_lock(dispatch_method);
  651. esp_timer_handle_t it = NULL;
  652. LIST_FOREACH(it, &s_timers[dispatch_method], list_entry) {
  653. // timers with the SKIP_UNHANDLED_EVENTS flag do not want to wake up CPU from a sleep mode.
  654. if ((it->flags & FL_SKIP_UNHANDLED_EVENTS) == 0) {
  655. if (next_alarm > it->alarm) {
  656. next_alarm = it->alarm;
  657. }
  658. break;
  659. }
  660. }
  661. timer_list_unlock(dispatch_method);
  662. }
  663. return next_alarm;
  664. }
  665. esp_err_t IRAM_ATTR esp_timer_get_period(esp_timer_handle_t timer, uint64_t *period)
  666. {
  667. if (timer == NULL || period == NULL) {
  668. return ESP_ERR_INVALID_ARG;
  669. }
  670. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  671. timer_list_lock(dispatch_method);
  672. *period = timer->period;
  673. timer_list_unlock(dispatch_method);
  674. return ESP_OK;
  675. }
  676. esp_err_t IRAM_ATTR esp_timer_get_expiry_time(esp_timer_handle_t timer, uint64_t *expiry)
  677. {
  678. if (timer == NULL || expiry == NULL) {
  679. return ESP_ERR_INVALID_ARG;
  680. }
  681. if (timer->period > 0) {
  682. /* Return error for periodic timers */
  683. return ESP_ERR_NOT_SUPPORTED;
  684. }
  685. esp_timer_dispatch_t dispatch_method = timer->flags & FL_ISR_DISPATCH_METHOD;
  686. timer_list_lock(dispatch_method);
  687. *expiry = timer->alarm;
  688. timer_list_unlock(dispatch_method);
  689. return ESP_OK;
  690. }
  691. bool IRAM_ATTR esp_timer_is_active(esp_timer_handle_t timer)
  692. {
  693. if (timer == NULL) {
  694. return false;
  695. }
  696. return timer_armed(timer);
  697. }