esp_timer.c 12 KB

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