thread.c 16 KB

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