thread.c 15 KB

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