esp_timer.c 14 KB

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