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