esp_timer.c 12 KB

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