esp_timer.c 13 KB

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