esp_timer.c 14 KB

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