thread.c 17 KB

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