thread.c 15 KB

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