esp_timer.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Copyright 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 <sys/param.h>
  15. #include <string.h>
  16. #include "soc/soc.h"
  17. #include "esp_types.h"
  18. #include "esp_attr.h"
  19. #include "esp_err.h"
  20. #include "esp_task.h"
  21. #include "esp_log.h"
  22. #include "freertos/FreeRTOS.h"
  23. #include "freertos/task.h"
  24. #include "freertos/semphr.h"
  25. #include "freertos/xtensa_api.h"
  26. #include "soc/spinlock.h"
  27. #include "esp_timer.h"
  28. #include "esp_timer_impl.h"
  29. #include "esp_private/startup_internal.h"
  30. #include "esp_private/esp_timer_private.h"
  31. #include "esp_private/system_internal.h"
  32. #if CONFIG_IDF_TARGET_ESP32
  33. #include "esp32/rtc.h"
  34. #elif CONFIG_IDF_TARGET_ESP32S2
  35. #include "esp32s2/rtc.h"
  36. #endif
  37. #include "sdkconfig.h"
  38. #if defined( CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 ) || \
  39. defined( CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1 ) || \
  40. defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_FRC1 ) || \
  41. defined( CONFIG_ESP32S2_TIME_SYSCALL_USE_RTC_FRC1 )
  42. #define WITH_FRC 1
  43. #endif
  44. #ifdef CONFIG_ESP_TIMER_PROFILING
  45. #define WITH_PROFILING 1
  46. #endif
  47. #ifndef NDEBUG
  48. // Enable built-in checks in queue.h in debug builds
  49. #define INVARIANTS
  50. #endif
  51. #include "sys/queue.h"
  52. #define EVENT_ID_DELETE_TIMER 0xF0DE1E1E
  53. #define TIMER_EVENT_QUEUE_SIZE 16
  54. struct esp_timer {
  55. uint64_t alarm;
  56. uint64_t period;
  57. union {
  58. esp_timer_cb_t callback;
  59. uint32_t event_id;
  60. };
  61. void* arg;
  62. #if WITH_PROFILING
  63. const char* name;
  64. size_t times_triggered;
  65. size_t times_armed;
  66. uint64_t total_callback_run_time;
  67. #endif // WITH_PROFILING
  68. LIST_ENTRY(esp_timer) list_entry;
  69. };
  70. static bool is_initialized(void);
  71. static esp_err_t timer_insert(esp_timer_handle_t timer);
  72. static esp_err_t timer_remove(esp_timer_handle_t timer);
  73. static bool timer_armed(esp_timer_handle_t timer);
  74. static void timer_list_lock(void);
  75. static void timer_list_unlock(void);
  76. #if WITH_PROFILING
  77. static void timer_insert_inactive(esp_timer_handle_t timer);
  78. static void timer_remove_inactive(esp_timer_handle_t timer);
  79. #endif // WITH_PROFILING
  80. static const char* TAG = "esp_timer";
  81. // list of currently armed timers
  82. static LIST_HEAD(esp_timer_list, esp_timer) s_timers =
  83. LIST_HEAD_INITIALIZER(s_timers);
  84. #if WITH_PROFILING
  85. // list of unarmed timers, used only to be able to dump statistics about
  86. // all the timers
  87. static LIST_HEAD(esp_inactive_timer_list, esp_timer) s_inactive_timers =
  88. LIST_HEAD_INITIALIZER(s_timers);
  89. #endif
  90. // task used to dispatch timer callbacks
  91. static TaskHandle_t s_timer_task;
  92. // counting semaphore used to notify the timer task from ISR
  93. static SemaphoreHandle_t s_timer_semaphore;
  94. #if CONFIG_SPIRAM_USE_MALLOC
  95. // memory for s_timer_semaphore
  96. static StaticQueue_t s_timer_semaphore_memory;
  97. #endif
  98. // lock protecting s_timers, s_inactive_timers
  99. static portMUX_TYPE s_timer_lock = portMUX_INITIALIZER_UNLOCKED;
  100. esp_err_t esp_timer_create(const esp_timer_create_args_t* args,
  101. esp_timer_handle_t* out_handle)
  102. {
  103. if (!is_initialized()) {
  104. return ESP_ERR_INVALID_STATE;
  105. }
  106. if (args == NULL || args->callback == NULL || out_handle == NULL) {
  107. return ESP_ERR_INVALID_ARG;
  108. }
  109. esp_timer_handle_t result = (esp_timer_handle_t) calloc(1, sizeof(*result));
  110. if (result == NULL) {
  111. return ESP_ERR_NO_MEM;
  112. }
  113. result->callback = args->callback;
  114. result->arg = args->arg;
  115. #if WITH_PROFILING
  116. result->name = args->name;
  117. timer_insert_inactive(result);
  118. #endif
  119. *out_handle = result;
  120. return ESP_OK;
  121. }
  122. esp_err_t IRAM_ATTR esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us)
  123. {
  124. if (timer == NULL) {
  125. return ESP_ERR_INVALID_ARG;
  126. }
  127. if (!is_initialized() || timer_armed(timer)) {
  128. return ESP_ERR_INVALID_STATE;
  129. }
  130. timer_list_lock();
  131. timer->alarm = esp_timer_get_time() + timeout_us;
  132. timer->period = 0;
  133. #if WITH_PROFILING
  134. timer->times_armed++;
  135. #endif
  136. esp_err_t err = timer_insert(timer);
  137. timer_list_unlock();
  138. return err;
  139. }
  140. esp_err_t IRAM_ATTR esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period_us)
  141. {
  142. if (timer == NULL) {
  143. return ESP_ERR_INVALID_ARG;
  144. }
  145. if (!is_initialized() || timer_armed(timer)) {
  146. return ESP_ERR_INVALID_STATE;
  147. }
  148. timer_list_lock();
  149. period_us = MAX(period_us, esp_timer_impl_get_min_period_us());
  150. timer->alarm = esp_timer_get_time() + period_us;
  151. timer->period = period_us;
  152. #if WITH_PROFILING
  153. timer->times_armed++;
  154. #endif
  155. esp_err_t err = timer_insert(timer);
  156. timer_list_unlock();
  157. return err;
  158. }
  159. esp_err_t IRAM_ATTR esp_timer_stop(esp_timer_handle_t timer)
  160. {
  161. if (timer == NULL) {
  162. return ESP_ERR_INVALID_ARG;
  163. }
  164. if (!is_initialized() || !timer_armed(timer)) {
  165. return ESP_ERR_INVALID_STATE;
  166. }
  167. return timer_remove(timer);
  168. }
  169. esp_err_t esp_timer_delete(esp_timer_handle_t timer)
  170. {
  171. if (timer == NULL) {
  172. return ESP_ERR_INVALID_ARG;
  173. }
  174. if (timer_armed(timer)) {
  175. return ESP_ERR_INVALID_STATE;
  176. }
  177. timer_list_lock();
  178. timer->event_id = EVENT_ID_DELETE_TIMER;
  179. timer->alarm = esp_timer_get_time();
  180. timer->period = 0;
  181. timer_insert(timer);
  182. timer_list_unlock();
  183. return ESP_OK;
  184. }
  185. static IRAM_ATTR esp_err_t timer_insert(esp_timer_handle_t timer)
  186. {
  187. #if WITH_PROFILING
  188. timer_remove_inactive(timer);
  189. #endif
  190. esp_timer_handle_t it, last = NULL;
  191. if (LIST_FIRST(&s_timers) == NULL) {
  192. LIST_INSERT_HEAD(&s_timers, timer, list_entry);
  193. } else {
  194. LIST_FOREACH(it, &s_timers, list_entry) {
  195. if (timer->alarm < it->alarm) {
  196. LIST_INSERT_BEFORE(it, timer, list_entry);
  197. break;
  198. }
  199. last = it;
  200. }
  201. if (it == NULL) {
  202. assert(last);
  203. LIST_INSERT_AFTER(last, timer, list_entry);
  204. }
  205. }
  206. if (timer == LIST_FIRST(&s_timers)) {
  207. esp_timer_impl_set_alarm(timer->alarm);
  208. }
  209. return ESP_OK;
  210. }
  211. static IRAM_ATTR esp_err_t timer_remove(esp_timer_handle_t timer)
  212. {
  213. timer_list_lock();
  214. LIST_REMOVE(timer, list_entry);
  215. timer->alarm = 0;
  216. timer->period = 0;
  217. #if WITH_PROFILING
  218. timer_insert_inactive(timer);
  219. #endif
  220. timer_list_unlock();
  221. return ESP_OK;
  222. }
  223. #if WITH_PROFILING
  224. static IRAM_ATTR void timer_insert_inactive(esp_timer_handle_t timer)
  225. {
  226. /* May be locked or not, depending on where this is called from.
  227. * Lock recursively.
  228. */
  229. timer_list_lock();
  230. esp_timer_handle_t head = LIST_FIRST(&s_inactive_timers);
  231. if (head == NULL) {
  232. LIST_INSERT_HEAD(&s_inactive_timers, timer, list_entry);
  233. } else {
  234. /* Insert as head element as this is the fastest thing to do.
  235. * Removal is O(1) anyway.
  236. */
  237. LIST_INSERT_BEFORE(head, timer, list_entry);
  238. }
  239. timer_list_unlock();
  240. }
  241. static IRAM_ATTR void timer_remove_inactive(esp_timer_handle_t timer)
  242. {
  243. timer_list_lock();
  244. LIST_REMOVE(timer, list_entry);
  245. timer_list_unlock();
  246. }
  247. #endif // WITH_PROFILING
  248. static IRAM_ATTR bool timer_armed(esp_timer_handle_t timer)
  249. {
  250. return timer->alarm > 0;
  251. }
  252. static IRAM_ATTR void timer_list_lock(void)
  253. {
  254. portENTER_CRITICAL_SAFE(&s_timer_lock);
  255. }
  256. static IRAM_ATTR void timer_list_unlock(void)
  257. {
  258. portEXIT_CRITICAL_SAFE(&s_timer_lock);
  259. }
  260. static void timer_process_alarm(esp_timer_dispatch_t dispatch_method)
  261. {
  262. /* unused, provision to allow running callbacks from ISR */
  263. (void) dispatch_method;
  264. timer_list_lock();
  265. int64_t now = esp_timer_impl_get_time();
  266. esp_timer_handle_t it = LIST_FIRST(&s_timers);
  267. while (it != NULL &&
  268. it->alarm < now) { // NOLINT(clang-analyzer-unix.Malloc)
  269. // Static analyser reports "Use of memory after it is freed" since the "it" variable
  270. // is freed below (if EVENT_ID_DELETE_TIMER) and assigned to the (new) LIST_FIRST()
  271. // so possibly (if the "it" hasn't been removed from the list) it might keep the same ptr.
  272. // Ignoring this warning, as this couldn't happen if queue.h used to populate the list
  273. LIST_REMOVE(it, list_entry);
  274. if (it->event_id == EVENT_ID_DELETE_TIMER) {
  275. free(it);
  276. it = LIST_FIRST(&s_timers);
  277. continue;
  278. }
  279. if (it->period > 0) {
  280. it->alarm += it->period;
  281. timer_insert(it);
  282. } else {
  283. it->alarm = 0;
  284. #if WITH_PROFILING
  285. timer_insert_inactive(it);
  286. #endif
  287. }
  288. #if WITH_PROFILING
  289. uint64_t callback_start = now;
  290. #endif
  291. esp_timer_cb_t callback = it->callback;
  292. void* arg = it->arg;
  293. timer_list_unlock();
  294. (*callback)(arg);
  295. timer_list_lock();
  296. now = esp_timer_impl_get_time();
  297. #if WITH_PROFILING
  298. it->times_triggered++;
  299. it->total_callback_run_time += now - callback_start;
  300. #endif
  301. it = LIST_FIRST(&s_timers);
  302. }
  303. esp_timer_handle_t first = LIST_FIRST(&s_timers);
  304. if (first) {
  305. esp_timer_impl_set_alarm(first->alarm);
  306. }
  307. timer_list_unlock();
  308. }
  309. static void timer_task(void* arg)
  310. {
  311. while (true){
  312. int res = xSemaphoreTake(s_timer_semaphore, portMAX_DELAY);
  313. assert(res == pdTRUE);
  314. timer_process_alarm(ESP_TIMER_TASK);
  315. }
  316. }
  317. static void IRAM_ATTR timer_alarm_handler(void* arg)
  318. {
  319. int need_yield;
  320. if (xSemaphoreGiveFromISR(s_timer_semaphore, &need_yield) != pdPASS) {
  321. ESP_EARLY_LOGD(TAG, "timer queue overflow");
  322. return;
  323. }
  324. if (need_yield == pdTRUE) {
  325. portYIELD_FROM_ISR();
  326. }
  327. }
  328. static IRAM_ATTR bool is_initialized(void)
  329. {
  330. return s_timer_task != NULL;
  331. }
  332. esp_err_t esp_timer_init(void)
  333. {
  334. esp_err_t err;
  335. if (is_initialized()) {
  336. return ESP_ERR_INVALID_STATE;
  337. }
  338. #if CONFIG_SPIRAM_USE_MALLOC
  339. memset(&s_timer_semaphore_memory, 0, sizeof(StaticQueue_t));
  340. s_timer_semaphore = xSemaphoreCreateCountingStatic(TIMER_EVENT_QUEUE_SIZE, 0, &s_timer_semaphore_memory);
  341. #else
  342. s_timer_semaphore = xSemaphoreCreateCounting(TIMER_EVENT_QUEUE_SIZE, 0);
  343. #endif
  344. if (!s_timer_semaphore) {
  345. err = ESP_ERR_NO_MEM;
  346. goto out;
  347. }
  348. int ret = xTaskCreatePinnedToCore(&timer_task, "esp_timer",
  349. ESP_TASK_TIMER_STACK, NULL, ESP_TASK_TIMER_PRIO, &s_timer_task, PRO_CPU_NUM);
  350. if (ret != pdPASS) {
  351. err = ESP_ERR_NO_MEM;
  352. goto out;
  353. }
  354. err = esp_timer_impl_init(&timer_alarm_handler);
  355. if (err != ESP_OK) {
  356. goto out;
  357. }
  358. #if WITH_FRC
  359. // [refactor-todo] this logic, "esp_rtc_get_time_us() - g_startup_time", is also
  360. // the weak definition of esp_system_get_time; find a way to remove this duplication.
  361. esp_timer_private_advance(esp_rtc_get_time_us() - g_startup_time);
  362. #endif
  363. return ESP_OK;
  364. out:
  365. if (s_timer_task) {
  366. vTaskDelete(s_timer_task);
  367. s_timer_task = NULL;
  368. }
  369. if (s_timer_semaphore) {
  370. vSemaphoreDelete(s_timer_semaphore);
  371. s_timer_semaphore = NULL;
  372. }
  373. return ESP_ERR_NO_MEM;
  374. }
  375. esp_err_t esp_timer_deinit(void)
  376. {
  377. if (!is_initialized()) {
  378. return ESP_ERR_INVALID_STATE;
  379. }
  380. /* Check if there are any active timers */
  381. if (!LIST_EMPTY(&s_timers)) {
  382. return ESP_ERR_INVALID_STATE;
  383. }
  384. /* We can only check if there are any timers which are not deleted if
  385. * profiling is enabled.
  386. */
  387. #if WITH_PROFILING
  388. if (!LIST_EMPTY(&s_inactive_timers)) {
  389. return ESP_ERR_INVALID_STATE;
  390. }
  391. #endif
  392. esp_timer_impl_deinit();
  393. vTaskDelete(s_timer_task);
  394. s_timer_task = NULL;
  395. vSemaphoreDelete(s_timer_semaphore);
  396. s_timer_semaphore = NULL;
  397. return ESP_OK;
  398. }
  399. static void print_timer_info(esp_timer_handle_t t, char** dst, size_t* dst_size)
  400. {
  401. size_t cb = snprintf(*dst, *dst_size,
  402. #if WITH_PROFILING
  403. "%-12s %12lld %12lld %9d %9d %12lld\n",
  404. t->name, t->period, t->alarm,
  405. t->times_armed, t->times_triggered, t->total_callback_run_time);
  406. /* keep this in sync with the format string, used in esp_timer_dump */
  407. #define TIMER_INFO_LINE_LEN 78
  408. #else
  409. "timer@%p %12lld %12lld\n", t, t->period, t->alarm);
  410. #define TIMER_INFO_LINE_LEN 46
  411. #endif
  412. *dst += cb;
  413. *dst_size -= cb;
  414. }
  415. esp_err_t esp_timer_dump(FILE* stream)
  416. {
  417. /* Since timer lock is a critical section, we don't want to print directly
  418. * to stdout, since that may cause a deadlock if stdout is interrupt-driven
  419. * (via the UART driver). Allocate sufficiently large chunk of memory first,
  420. * print to it, then dump this memory to stdout.
  421. */
  422. esp_timer_handle_t it;
  423. /* First count the number of timers */
  424. size_t timer_count = 0;
  425. timer_list_lock();
  426. LIST_FOREACH(it, &s_timers, list_entry) {
  427. ++timer_count;
  428. }
  429. #if WITH_PROFILING
  430. LIST_FOREACH(it, &s_inactive_timers, list_entry) {
  431. ++timer_count;
  432. }
  433. #endif
  434. timer_list_unlock();
  435. /* Allocate the memory for this number of timers. Since we have unlocked,
  436. * we may find that there are more timers. There's no bulletproof solution
  437. * for this (can't allocate from a critical section), but we allocate
  438. * slightly more and the output will be truncated if that is not enough.
  439. */
  440. size_t buf_size = TIMER_INFO_LINE_LEN * (timer_count + 3);
  441. char* print_buf = calloc(1, buf_size + 1);
  442. if (print_buf == NULL) {
  443. return ESP_ERR_NO_MEM;
  444. }
  445. /* Print to the buffer */
  446. timer_list_lock();
  447. char* pos = print_buf;
  448. LIST_FOREACH(it, &s_timers, list_entry) {
  449. print_timer_info(it, &pos, &buf_size);
  450. }
  451. #if WITH_PROFILING
  452. LIST_FOREACH(it, &s_inactive_timers, list_entry) {
  453. print_timer_info(it, &pos, &buf_size);
  454. }
  455. #endif
  456. timer_list_unlock();
  457. /* Print the buffer */
  458. fputs(print_buf, stream);
  459. free(print_buf);
  460. return ESP_OK;
  461. }
  462. int64_t IRAM_ATTR esp_timer_get_next_alarm(void)
  463. {
  464. int64_t next_alarm = INT64_MAX;
  465. timer_list_lock();
  466. esp_timer_handle_t it = LIST_FIRST(&s_timers);
  467. if (it) {
  468. next_alarm = it->alarm;
  469. }
  470. timer_list_unlock();
  471. return next_alarm;
  472. }
  473. int64_t IRAM_ATTR esp_timer_get_time(void)
  474. {
  475. if(is_initialized()) {
  476. return esp_timer_impl_get_time();
  477. } else {
  478. return 0;
  479. }
  480. }
  481. // Provides strong definition for system time functions relied upon
  482. // by core components.
  483. #if WITH_FRC
  484. int64_t IRAM_ATTR esp_system_get_time(void)
  485. {
  486. return esp_timer_get_time();
  487. }
  488. uint32_t IRAM_ATTR esp_system_get_time_resolution(void)
  489. {
  490. return 1;
  491. }
  492. #endif