thread.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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() {
  40. asm volatile("nop"); // extra magic
  41. furi_crash("You are doing it wrong");
  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(
  68. thread->heap_size ? FuriLogLevelError : FuriLogLevelInfo,
  69. TAG,
  70. "%s allocation balance: %d",
  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_E(
  78. TAG,
  79. "%s service thread exited. Thread memory cannot 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. void furi_thread_free(FuriThread* thread) {
  109. furi_assert(thread);
  110. furi_assert(thread->state == FuriThreadStateStopped);
  111. if(thread->name) free((void*)thread->name);
  112. furi_string_free(thread->output.buffer);
  113. free(thread);
  114. }
  115. void furi_thread_set_name(FuriThread* thread, const char* name) {
  116. furi_assert(thread);
  117. furi_assert(thread->state == FuriThreadStateStopped);
  118. if(thread->name) free((void*)thread->name);
  119. thread->name = name ? strdup(name) : NULL;
  120. }
  121. void furi_thread_mark_as_service(FuriThread* thread) {
  122. thread->is_service = true;
  123. }
  124. void furi_thread_set_stack_size(FuriThread* thread, size_t stack_size) {
  125. furi_assert(thread);
  126. furi_assert(thread->state == FuriThreadStateStopped);
  127. furi_assert(stack_size % 4 == 0);
  128. thread->stack_size = stack_size;
  129. }
  130. void furi_thread_set_callback(FuriThread* thread, FuriThreadCallback callback) {
  131. furi_assert(thread);
  132. furi_assert(thread->state == FuriThreadStateStopped);
  133. thread->callback = callback;
  134. }
  135. void furi_thread_set_context(FuriThread* thread, void* context) {
  136. furi_assert(thread);
  137. furi_assert(thread->state == FuriThreadStateStopped);
  138. thread->context = context;
  139. }
  140. void furi_thread_set_priority(FuriThread* thread, FuriThreadPriority priority) {
  141. furi_assert(thread);
  142. furi_assert(thread->state == FuriThreadStateStopped);
  143. furi_assert(priority >= FuriThreadPriorityIdle && priority <= FuriThreadPriorityIsr);
  144. thread->priority = priority;
  145. }
  146. void furi_thread_set_state_callback(FuriThread* thread, FuriThreadStateCallback callback) {
  147. furi_assert(thread);
  148. furi_assert(thread->state == FuriThreadStateStopped);
  149. thread->state_callback = callback;
  150. }
  151. void furi_thread_set_state_context(FuriThread* thread, void* context) {
  152. furi_assert(thread);
  153. furi_assert(thread->state == FuriThreadStateStopped);
  154. thread->state_context = context;
  155. }
  156. FuriThreadState furi_thread_get_state(FuriThread* thread) {
  157. furi_assert(thread);
  158. return thread->state;
  159. }
  160. void furi_thread_start(FuriThread* thread) {
  161. furi_assert(thread);
  162. furi_assert(thread->callback);
  163. furi_assert(thread->state == FuriThreadStateStopped);
  164. furi_assert(thread->stack_size > 0 && thread->stack_size < 0xFFFF * 4);
  165. furi_thread_set_state(thread, FuriThreadStateStarting);
  166. uint32_t stack = thread->stack_size / 4;
  167. UBaseType_t priority = thread->priority ? thread->priority : FuriThreadPriorityNormal;
  168. if(thread->is_service) {
  169. thread->task_handle = xTaskCreateStatic(
  170. furi_thread_body,
  171. thread->name,
  172. stack,
  173. thread,
  174. priority,
  175. memmgr_alloc_from_pool(sizeof(StackType_t) * stack),
  176. memmgr_alloc_from_pool(sizeof(StaticTask_t)));
  177. } else {
  178. BaseType_t ret = xTaskCreate(
  179. furi_thread_body, thread->name, stack, thread, priority, &thread->task_handle);
  180. furi_check(ret == pdPASS);
  181. }
  182. furi_check(thread->task_handle);
  183. }
  184. bool furi_thread_join(FuriThread* thread) {
  185. furi_assert(thread);
  186. furi_check(furi_thread_get_current() != thread);
  187. // Wait for thread to stop
  188. while(thread->task_handle) {
  189. furi_delay_ms(10);
  190. }
  191. return true;
  192. }
  193. FuriThreadId furi_thread_get_id(FuriThread* thread) {
  194. furi_assert(thread);
  195. return thread->task_handle;
  196. }
  197. void furi_thread_enable_heap_trace(FuriThread* thread) {
  198. furi_assert(thread);
  199. furi_assert(thread->state == FuriThreadStateStopped);
  200. thread->heap_trace_enabled = true;
  201. }
  202. void furi_thread_disable_heap_trace(FuriThread* thread) {
  203. furi_assert(thread);
  204. furi_assert(thread->state == FuriThreadStateStopped);
  205. thread->heap_trace_enabled = false;
  206. }
  207. size_t furi_thread_get_heap_size(FuriThread* thread) {
  208. furi_assert(thread);
  209. furi_assert(thread->heap_trace_enabled == true);
  210. return thread->heap_size;
  211. }
  212. int32_t furi_thread_get_return_code(FuriThread* thread) {
  213. furi_assert(thread);
  214. furi_assert(thread->state == FuriThreadStateStopped);
  215. return thread->ret;
  216. }
  217. FuriThreadId furi_thread_get_current_id() {
  218. return xTaskGetCurrentTaskHandle();
  219. }
  220. FuriThread* furi_thread_get_current() {
  221. FuriThread* thread = pvTaskGetThreadLocalStoragePointer(NULL, 0);
  222. furi_assert(thread != NULL);
  223. return thread;
  224. }
  225. void furi_thread_yield() {
  226. furi_assert(!FURI_IS_IRQ_MODE());
  227. taskYIELD();
  228. }
  229. /* Limits */
  230. #define MAX_BITS_TASK_NOTIFY 31U
  231. #define MAX_BITS_EVENT_GROUPS 24U
  232. #define THREAD_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_TASK_NOTIFY) - 1U))
  233. #define EVENT_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_EVENT_GROUPS) - 1U))
  234. uint32_t furi_thread_flags_set(FuriThreadId thread_id, uint32_t flags) {
  235. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  236. uint32_t rflags;
  237. BaseType_t yield;
  238. if((hTask == NULL) || ((flags & THREAD_FLAGS_INVALID_BITS) != 0U)) {
  239. rflags = (uint32_t)FuriStatusErrorParameter;
  240. } else {
  241. rflags = (uint32_t)FuriStatusError;
  242. if(FURI_IS_IRQ_MODE()) {
  243. yield = pdFALSE;
  244. (void)xTaskNotifyIndexedFromISR(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits, &yield);
  245. (void)xTaskNotifyAndQueryIndexedFromISR(
  246. hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags, NULL);
  247. portYIELD_FROM_ISR(yield);
  248. } else {
  249. (void)xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits);
  250. (void)xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags);
  251. }
  252. }
  253. /* Return flags after setting */
  254. return (rflags);
  255. }
  256. uint32_t furi_thread_flags_clear(uint32_t flags) {
  257. TaskHandle_t hTask;
  258. uint32_t rflags, cflags;
  259. if(FURI_IS_IRQ_MODE()) {
  260. rflags = (uint32_t)FuriStatusErrorISR;
  261. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  262. rflags = (uint32_t)FuriStatusErrorParameter;
  263. } else {
  264. hTask = xTaskGetCurrentTaskHandle();
  265. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &cflags) ==
  266. pdPASS) {
  267. rflags = cflags;
  268. cflags &= ~flags;
  269. if(xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, cflags, eSetValueWithOverwrite) !=
  270. pdPASS) {
  271. rflags = (uint32_t)FuriStatusError;
  272. }
  273. } else {
  274. rflags = (uint32_t)FuriStatusError;
  275. }
  276. }
  277. /* Return flags before clearing */
  278. return (rflags);
  279. }
  280. uint32_t furi_thread_flags_get(void) {
  281. TaskHandle_t hTask;
  282. uint32_t rflags;
  283. if(FURI_IS_IRQ_MODE()) {
  284. rflags = (uint32_t)FuriStatusErrorISR;
  285. } else {
  286. hTask = xTaskGetCurrentTaskHandle();
  287. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags) !=
  288. pdPASS) {
  289. rflags = (uint32_t)FuriStatusError;
  290. }
  291. }
  292. return (rflags);
  293. }
  294. uint32_t furi_thread_flags_wait(uint32_t flags, uint32_t options, uint32_t timeout) {
  295. uint32_t rflags, nval;
  296. uint32_t clear;
  297. TickType_t t0, td, tout;
  298. BaseType_t rval;
  299. if(FURI_IS_IRQ_MODE()) {
  300. rflags = (uint32_t)FuriStatusErrorISR;
  301. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  302. rflags = (uint32_t)FuriStatusErrorParameter;
  303. } else {
  304. if((options & FuriFlagNoClear) == FuriFlagNoClear) {
  305. clear = 0U;
  306. } else {
  307. clear = flags;
  308. }
  309. rflags = 0U;
  310. tout = timeout;
  311. t0 = xTaskGetTickCount();
  312. do {
  313. rval = xTaskNotifyWaitIndexed(THREAD_NOTIFY_INDEX, 0, clear, &nval, tout);
  314. if(rval == pdPASS) {
  315. rflags &= flags;
  316. rflags |= nval;
  317. if((options & FuriFlagWaitAll) == FuriFlagWaitAll) {
  318. if((flags & rflags) == flags) {
  319. break;
  320. } else {
  321. if(timeout == 0U) {
  322. rflags = (uint32_t)FuriStatusErrorResource;
  323. break;
  324. }
  325. }
  326. } else {
  327. if((flags & rflags) != 0) {
  328. break;
  329. } else {
  330. if(timeout == 0U) {
  331. rflags = (uint32_t)FuriStatusErrorResource;
  332. break;
  333. }
  334. }
  335. }
  336. /* Update timeout */
  337. td = xTaskGetTickCount() - t0;
  338. if(td > tout) {
  339. tout = 0;
  340. } else {
  341. tout -= td;
  342. }
  343. } else {
  344. if(timeout == 0) {
  345. rflags = (uint32_t)FuriStatusErrorResource;
  346. } else {
  347. rflags = (uint32_t)FuriStatusErrorTimeout;
  348. }
  349. }
  350. } while(rval != pdFAIL);
  351. }
  352. /* Return flags before clearing */
  353. return (rflags);
  354. }
  355. uint32_t furi_thread_enumerate(FuriThreadId* thread_array, uint32_t array_items) {
  356. uint32_t i, count;
  357. TaskStatus_t* task;
  358. if(FURI_IS_IRQ_MODE() || (thread_array == NULL) || (array_items == 0U)) {
  359. count = 0U;
  360. } else {
  361. vTaskSuspendAll();
  362. count = uxTaskGetNumberOfTasks();
  363. task = pvPortMalloc(count * sizeof(TaskStatus_t));
  364. if(task != NULL) {
  365. count = uxTaskGetSystemState(task, count, NULL);
  366. for(i = 0U; (i < count) && (i < array_items); i++) {
  367. thread_array[i] = (FuriThreadId)task[i].xHandle;
  368. }
  369. count = i;
  370. }
  371. (void)xTaskResumeAll();
  372. vPortFree(task);
  373. }
  374. return (count);
  375. }
  376. const char* furi_thread_get_name(FuriThreadId thread_id) {
  377. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  378. const char* name;
  379. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  380. name = NULL;
  381. } else {
  382. name = pcTaskGetName(hTask);
  383. }
  384. return (name);
  385. }
  386. uint32_t furi_thread_get_stack_space(FuriThreadId thread_id) {
  387. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  388. uint32_t sz;
  389. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  390. sz = 0U;
  391. } else {
  392. sz = (uint32_t)(uxTaskGetStackHighWaterMark(hTask) * sizeof(StackType_t));
  393. }
  394. return (sz);
  395. }
  396. static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size) {
  397. if(thread->output.write_callback != NULL) {
  398. thread->output.write_callback(data, size);
  399. } else {
  400. furi_hal_console_tx((const uint8_t*)data, size);
  401. }
  402. return size;
  403. }
  404. static int32_t __furi_thread_stdout_flush(FuriThread* thread) {
  405. FuriString* buffer = thread->output.buffer;
  406. size_t size = furi_string_size(buffer);
  407. if(size > 0) {
  408. __furi_thread_stdout_write(thread, furi_string_get_cstr(buffer), size);
  409. furi_string_reset(buffer);
  410. }
  411. return 0;
  412. }
  413. bool furi_thread_set_stdout_callback(FuriThreadStdoutWriteCallback callback) {
  414. FuriThread* thread = furi_thread_get_current();
  415. __furi_thread_stdout_flush(thread);
  416. thread->output.write_callback = callback;
  417. return true;
  418. }
  419. size_t furi_thread_stdout_write(const char* data, size_t size) {
  420. FuriThread* thread = furi_thread_get_current();
  421. if(size == 0 || data == NULL) {
  422. return __furi_thread_stdout_flush(thread);
  423. } else {
  424. if(data[size - 1] == '\n') {
  425. // if the last character is a newline, we can flush buffer and write data as is, wo buffers
  426. __furi_thread_stdout_flush(thread);
  427. __furi_thread_stdout_write(thread, data, size);
  428. } else {
  429. // string_cat doesn't work here because we need to write the exact size data
  430. for(size_t i = 0; i < size; i++) {
  431. furi_string_push_back(thread->output.buffer, data[i]);
  432. if(data[i] == '\n') {
  433. __furi_thread_stdout_flush(thread);
  434. }
  435. }
  436. }
  437. }
  438. return size;
  439. }
  440. int32_t furi_thread_stdout_flush() {
  441. return __furi_thread_stdout_flush(furi_thread_get_current());
  442. }
  443. void furi_thread_suspend(FuriThreadId thread_id) {
  444. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  445. vTaskSuspend(hTask);
  446. }
  447. void furi_thread_resume(FuriThreadId thread_id) {
  448. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  449. if(FURI_IS_IRQ_MODE()) {
  450. xTaskResumeFromISR(hTask);
  451. } else {
  452. vTaskResume(hTask);
  453. }
  454. }
  455. bool furi_thread_is_suspended(FuriThreadId thread_id) {
  456. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  457. return eTaskGetState(hTask) == eSuspended;
  458. }