thread.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. #include "thread.h"
  2. #include "kernel.h"
  3. #include "memmgr.h"
  4. #include "memmgr_heap.h"
  5. #include "check.h"
  6. #include "common_defines.h"
  7. #include "mutex.h"
  8. #include "string.h"
  9. #include <task.h>
  10. #include "log.h"
  11. #include <furi_hal_rtc.h>
  12. #include <furi_hal_console.h>
  13. #define THREAD_NOTIFY_INDEX 1 // Index 0 is used for stream buffers
  14. typedef struct FuriThreadStdout FuriThreadStdout;
  15. struct FuriThreadStdout {
  16. FuriThreadStdoutWriteCallback write_callback;
  17. FuriString* buffer;
  18. };
  19. struct FuriThread {
  20. bool is_service;
  21. FuriThreadState state;
  22. int32_t ret;
  23. FuriThreadCallback callback;
  24. void* context;
  25. FuriThreadStateCallback state_callback;
  26. void* state_context;
  27. char* name;
  28. configSTACK_DEPTH_TYPE stack_size;
  29. FuriThreadPriority priority;
  30. TaskHandle_t task_handle;
  31. bool heap_trace_enabled;
  32. size_t heap_size;
  33. FuriThreadStdout output;
  34. };
  35. static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size);
  36. static int32_t __furi_thread_stdout_flush(FuriThread* thread);
  37. /** Catch threads that are trying to exit wrong way */
  38. __attribute__((__noreturn__)) void furi_thread_catch() {
  39. asm volatile("nop"); // extra magic
  40. furi_crash("You are doing it wrong");
  41. }
  42. static void furi_thread_set_state(FuriThread* thread, FuriThreadState state) {
  43. furi_assert(thread);
  44. thread->state = state;
  45. if(thread->state_callback) {
  46. thread->state_callback(state, thread->state_context);
  47. }
  48. }
  49. static void furi_thread_body(void* context) {
  50. furi_assert(context);
  51. FuriThread* thread = context;
  52. // store thread instance to thread local storage
  53. furi_assert(pvTaskGetThreadLocalStoragePointer(NULL, 0) == NULL);
  54. vTaskSetThreadLocalStoragePointer(NULL, 0, thread);
  55. furi_assert(thread->state == FuriThreadStateStarting);
  56. furi_thread_set_state(thread, FuriThreadStateRunning);
  57. TaskHandle_t task_handle = xTaskGetCurrentTaskHandle();
  58. if(thread->heap_trace_enabled == true) {
  59. memmgr_heap_enable_thread_trace((FuriThreadId)task_handle);
  60. }
  61. thread->ret = thread->callback(thread->context);
  62. if(thread->heap_trace_enabled == true) {
  63. furi_delay_ms(33);
  64. thread->heap_size = memmgr_heap_get_thread_memory((FuriThreadId)task_handle);
  65. memmgr_heap_disable_thread_trace((FuriThreadId)task_handle);
  66. }
  67. furi_assert(thread->state == FuriThreadStateRunning);
  68. if(thread->is_service) {
  69. FURI_LOG_E(
  70. "Service",
  71. "%s thread exited. Thread memory cannot be reclaimed.",
  72. thread->name ? thread->name : "<unknown service>");
  73. }
  74. // flush stdout
  75. __furi_thread_stdout_flush(thread);
  76. // from here we can't use thread pointer
  77. furi_thread_set_state(thread, FuriThreadStateStopped);
  78. // clear thread local storage
  79. furi_assert(pvTaskGetThreadLocalStoragePointer(NULL, 0) != NULL);
  80. vTaskSetThreadLocalStoragePointer(NULL, 0, NULL);
  81. thread->task_handle = NULL;
  82. vTaskDelete(NULL);
  83. furi_thread_catch();
  84. }
  85. FuriThread* furi_thread_alloc() {
  86. FuriThread* thread = malloc(sizeof(FuriThread));
  87. thread->output.buffer = furi_string_alloc();
  88. thread->is_service = false;
  89. return thread;
  90. }
  91. void furi_thread_free(FuriThread* thread) {
  92. furi_assert(thread);
  93. furi_assert(thread->state == FuriThreadStateStopped);
  94. if(thread->name) free((void*)thread->name);
  95. furi_string_free(thread->output.buffer);
  96. free(thread);
  97. }
  98. void furi_thread_set_name(FuriThread* thread, const char* name) {
  99. furi_assert(thread);
  100. furi_assert(thread->state == FuriThreadStateStopped);
  101. if(thread->name) free((void*)thread->name);
  102. thread->name = name ? strdup(name) : NULL;
  103. }
  104. void furi_thread_mark_as_service(FuriThread* thread) {
  105. thread->is_service = true;
  106. }
  107. void furi_thread_set_stack_size(FuriThread* thread, size_t stack_size) {
  108. furi_assert(thread);
  109. furi_assert(thread->state == FuriThreadStateStopped);
  110. furi_assert(stack_size % 4 == 0);
  111. thread->stack_size = stack_size;
  112. }
  113. void furi_thread_set_callback(FuriThread* thread, FuriThreadCallback callback) {
  114. furi_assert(thread);
  115. furi_assert(thread->state == FuriThreadStateStopped);
  116. thread->callback = callback;
  117. }
  118. void furi_thread_set_context(FuriThread* thread, void* context) {
  119. furi_assert(thread);
  120. furi_assert(thread->state == FuriThreadStateStopped);
  121. thread->context = context;
  122. }
  123. void furi_thread_set_priority(FuriThread* thread, FuriThreadPriority priority) {
  124. furi_assert(thread);
  125. furi_assert(thread->state == FuriThreadStateStopped);
  126. furi_assert(priority >= FuriThreadPriorityIdle && priority <= FuriThreadPriorityIsr);
  127. thread->priority = priority;
  128. }
  129. void furi_thread_set_state_callback(FuriThread* thread, FuriThreadStateCallback callback) {
  130. furi_assert(thread);
  131. furi_assert(thread->state == FuriThreadStateStopped);
  132. thread->state_callback = callback;
  133. }
  134. void furi_thread_set_state_context(FuriThread* thread, void* context) {
  135. furi_assert(thread);
  136. furi_assert(thread->state == FuriThreadStateStopped);
  137. thread->state_context = context;
  138. }
  139. FuriThreadState furi_thread_get_state(FuriThread* thread) {
  140. furi_assert(thread);
  141. return thread->state;
  142. }
  143. void furi_thread_start(FuriThread* thread) {
  144. furi_assert(thread);
  145. furi_assert(thread->callback);
  146. furi_assert(thread->state == FuriThreadStateStopped);
  147. furi_assert(thread->stack_size > 0 && thread->stack_size < 0xFFFF * 4);
  148. furi_thread_set_state(thread, FuriThreadStateStarting);
  149. uint32_t stack = thread->stack_size / 4;
  150. UBaseType_t priority = thread->priority ? thread->priority : FuriThreadPriorityNormal;
  151. if(thread->is_service) {
  152. thread->task_handle = xTaskCreateStatic(
  153. furi_thread_body,
  154. thread->name,
  155. stack,
  156. thread,
  157. priority,
  158. memmgr_alloc_from_pool(sizeof(StackType_t) * stack),
  159. memmgr_alloc_from_pool(sizeof(StaticTask_t)));
  160. } else {
  161. BaseType_t ret = xTaskCreate(
  162. furi_thread_body, thread->name, stack, thread, priority, &thread->task_handle);
  163. furi_check(ret == pdPASS);
  164. }
  165. furi_check(thread->task_handle);
  166. }
  167. bool furi_thread_join(FuriThread* thread) {
  168. furi_assert(thread);
  169. furi_check(furi_thread_get_current() != thread);
  170. // Wait for thread to stop
  171. while(thread->task_handle) {
  172. furi_delay_ms(10);
  173. }
  174. return true;
  175. }
  176. FuriThreadId furi_thread_get_id(FuriThread* thread) {
  177. furi_assert(thread);
  178. return thread->task_handle;
  179. }
  180. void furi_thread_enable_heap_trace(FuriThread* thread) {
  181. furi_assert(thread);
  182. furi_assert(thread->state == FuriThreadStateStopped);
  183. furi_assert(thread->heap_trace_enabled == false);
  184. thread->heap_trace_enabled = true;
  185. }
  186. void furi_thread_disable_heap_trace(FuriThread* thread) {
  187. furi_assert(thread);
  188. furi_assert(thread->state == FuriThreadStateStopped);
  189. furi_assert(thread->heap_trace_enabled == true);
  190. thread->heap_trace_enabled = false;
  191. }
  192. size_t furi_thread_get_heap_size(FuriThread* thread) {
  193. furi_assert(thread);
  194. furi_assert(thread->heap_trace_enabled == true);
  195. return thread->heap_size;
  196. }
  197. int32_t furi_thread_get_return_code(FuriThread* thread) {
  198. furi_assert(thread);
  199. furi_assert(thread->state == FuriThreadStateStopped);
  200. return thread->ret;
  201. }
  202. FuriThreadId furi_thread_get_current_id() {
  203. return xTaskGetCurrentTaskHandle();
  204. }
  205. FuriThread* furi_thread_get_current() {
  206. FuriThread* thread = pvTaskGetThreadLocalStoragePointer(NULL, 0);
  207. furi_assert(thread != NULL);
  208. return thread;
  209. }
  210. void furi_thread_yield() {
  211. furi_assert(!FURI_IS_IRQ_MODE());
  212. taskYIELD();
  213. }
  214. /* Limits */
  215. #define MAX_BITS_TASK_NOTIFY 31U
  216. #define MAX_BITS_EVENT_GROUPS 24U
  217. #define THREAD_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_TASK_NOTIFY) - 1U))
  218. #define EVENT_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_EVENT_GROUPS) - 1U))
  219. uint32_t furi_thread_flags_set(FuriThreadId thread_id, uint32_t flags) {
  220. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  221. uint32_t rflags;
  222. BaseType_t yield;
  223. if((hTask == NULL) || ((flags & THREAD_FLAGS_INVALID_BITS) != 0U)) {
  224. rflags = (uint32_t)FuriStatusErrorParameter;
  225. } else {
  226. rflags = (uint32_t)FuriStatusError;
  227. if(FURI_IS_IRQ_MODE()) {
  228. yield = pdFALSE;
  229. (void)xTaskNotifyIndexedFromISR(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits, &yield);
  230. (void)xTaskNotifyAndQueryIndexedFromISR(
  231. hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags, NULL);
  232. portYIELD_FROM_ISR(yield);
  233. } else {
  234. (void)xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits);
  235. (void)xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags);
  236. }
  237. }
  238. /* Return flags after setting */
  239. return (rflags);
  240. }
  241. uint32_t furi_thread_flags_clear(uint32_t flags) {
  242. TaskHandle_t hTask;
  243. uint32_t rflags, cflags;
  244. if(FURI_IS_IRQ_MODE()) {
  245. rflags = (uint32_t)FuriStatusErrorISR;
  246. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  247. rflags = (uint32_t)FuriStatusErrorParameter;
  248. } else {
  249. hTask = xTaskGetCurrentTaskHandle();
  250. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &cflags) ==
  251. pdPASS) {
  252. rflags = cflags;
  253. cflags &= ~flags;
  254. if(xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, cflags, eSetValueWithOverwrite) !=
  255. pdPASS) {
  256. rflags = (uint32_t)FuriStatusError;
  257. }
  258. } else {
  259. rflags = (uint32_t)FuriStatusError;
  260. }
  261. }
  262. /* Return flags before clearing */
  263. return (rflags);
  264. }
  265. uint32_t furi_thread_flags_get(void) {
  266. TaskHandle_t hTask;
  267. uint32_t rflags;
  268. if(FURI_IS_IRQ_MODE()) {
  269. rflags = (uint32_t)FuriStatusErrorISR;
  270. } else {
  271. hTask = xTaskGetCurrentTaskHandle();
  272. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags) !=
  273. pdPASS) {
  274. rflags = (uint32_t)FuriStatusError;
  275. }
  276. }
  277. return (rflags);
  278. }
  279. uint32_t furi_thread_flags_wait(uint32_t flags, uint32_t options, uint32_t timeout) {
  280. uint32_t rflags, nval;
  281. uint32_t clear;
  282. TickType_t t0, td, tout;
  283. BaseType_t rval;
  284. if(FURI_IS_IRQ_MODE()) {
  285. rflags = (uint32_t)FuriStatusErrorISR;
  286. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  287. rflags = (uint32_t)FuriStatusErrorParameter;
  288. } else {
  289. if((options & FuriFlagNoClear) == FuriFlagNoClear) {
  290. clear = 0U;
  291. } else {
  292. clear = flags;
  293. }
  294. rflags = 0U;
  295. tout = timeout;
  296. t0 = xTaskGetTickCount();
  297. do {
  298. rval = xTaskNotifyWaitIndexed(THREAD_NOTIFY_INDEX, 0, clear, &nval, tout);
  299. if(rval == pdPASS) {
  300. rflags &= flags;
  301. rflags |= nval;
  302. if((options & FuriFlagWaitAll) == FuriFlagWaitAll) {
  303. if((flags & rflags) == flags) {
  304. break;
  305. } else {
  306. if(timeout == 0U) {
  307. rflags = (uint32_t)FuriStatusErrorResource;
  308. break;
  309. }
  310. }
  311. } else {
  312. if((flags & rflags) != 0) {
  313. break;
  314. } else {
  315. if(timeout == 0U) {
  316. rflags = (uint32_t)FuriStatusErrorResource;
  317. break;
  318. }
  319. }
  320. }
  321. /* Update timeout */
  322. td = xTaskGetTickCount() - t0;
  323. if(td > tout) {
  324. tout = 0;
  325. } else {
  326. tout -= td;
  327. }
  328. } else {
  329. if(timeout == 0) {
  330. rflags = (uint32_t)FuriStatusErrorResource;
  331. } else {
  332. rflags = (uint32_t)FuriStatusErrorTimeout;
  333. }
  334. }
  335. } while(rval != pdFAIL);
  336. }
  337. /* Return flags before clearing */
  338. return (rflags);
  339. }
  340. uint32_t furi_thread_enumerate(FuriThreadId* thread_array, uint32_t array_items) {
  341. uint32_t i, count;
  342. TaskStatus_t* task;
  343. if(FURI_IS_IRQ_MODE() || (thread_array == NULL) || (array_items == 0U)) {
  344. count = 0U;
  345. } else {
  346. vTaskSuspendAll();
  347. count = uxTaskGetNumberOfTasks();
  348. task = pvPortMalloc(count * sizeof(TaskStatus_t));
  349. if(task != NULL) {
  350. count = uxTaskGetSystemState(task, count, NULL);
  351. for(i = 0U; (i < count) && (i < array_items); i++) {
  352. thread_array[i] = (FuriThreadId)task[i].xHandle;
  353. }
  354. count = i;
  355. }
  356. (void)xTaskResumeAll();
  357. vPortFree(task);
  358. }
  359. return (count);
  360. }
  361. const char* furi_thread_get_name(FuriThreadId thread_id) {
  362. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  363. const char* name;
  364. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  365. name = NULL;
  366. } else {
  367. name = pcTaskGetName(hTask);
  368. }
  369. return (name);
  370. }
  371. uint32_t furi_thread_get_stack_space(FuriThreadId thread_id) {
  372. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  373. uint32_t sz;
  374. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  375. sz = 0U;
  376. } else {
  377. sz = (uint32_t)(uxTaskGetStackHighWaterMark(hTask) * sizeof(StackType_t));
  378. }
  379. return (sz);
  380. }
  381. static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size) {
  382. if(thread->output.write_callback != NULL) {
  383. thread->output.write_callback(data, size);
  384. } else {
  385. furi_hal_console_tx((const uint8_t*)data, size);
  386. }
  387. return size;
  388. }
  389. static int32_t __furi_thread_stdout_flush(FuriThread* thread) {
  390. FuriString* buffer = thread->output.buffer;
  391. size_t size = furi_string_size(buffer);
  392. if(size > 0) {
  393. __furi_thread_stdout_write(thread, furi_string_get_cstr(buffer), size);
  394. furi_string_reset(buffer);
  395. }
  396. return 0;
  397. }
  398. bool furi_thread_set_stdout_callback(FuriThreadStdoutWriteCallback callback) {
  399. FuriThread* thread = furi_thread_get_current();
  400. __furi_thread_stdout_flush(thread);
  401. thread->output.write_callback = callback;
  402. return true;
  403. }
  404. size_t furi_thread_stdout_write(const char* data, size_t size) {
  405. FuriThread* thread = furi_thread_get_current();
  406. if(size == 0 || data == NULL) {
  407. return __furi_thread_stdout_flush(thread);
  408. } else {
  409. if(data[size - 1] == '\n') {
  410. // if the last character is a newline, we can flush buffer and write data as is, wo buffers
  411. __furi_thread_stdout_flush(thread);
  412. __furi_thread_stdout_write(thread, data, size);
  413. } else {
  414. // string_cat doesn't work here because we need to write the exact size data
  415. for(size_t i = 0; i < size; i++) {
  416. furi_string_push_back(thread->output.buffer, data[i]);
  417. if(data[i] == '\n') {
  418. __furi_thread_stdout_flush(thread);
  419. }
  420. }
  421. }
  422. }
  423. return size;
  424. }
  425. int32_t furi_thread_stdout_flush() {
  426. return __furi_thread_stdout_flush(furi_thread_get_current());
  427. }
  428. void furi_thread_suspend(FuriThreadId thread_id) {
  429. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  430. vTaskSuspend(hTask);
  431. }
  432. void furi_thread_resume(FuriThreadId thread_id) {
  433. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  434. if(FURI_IS_IRQ_MODE()) {
  435. xTaskResumeFromISR(hTask);
  436. } else {
  437. vTaskResume(hTask);
  438. }
  439. }
  440. bool furi_thread_is_suspended(FuriThreadId thread_id) {
  441. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  442. return eTaskGetState(hTask) == eSuspended;
  443. }