esp_timer.c 14 KB

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