thread.c 15 KB

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