thread.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. // Check if thread was started
  169. if(thread->task_handle == NULL) {
  170. return false;
  171. }
  172. // Wait for thread to stop
  173. while(eTaskGetState(thread->task_handle) != eDeleted) {
  174. furi_delay_ms(10);
  175. }
  176. return true;
  177. }
  178. FuriThreadId furi_thread_get_id(FuriThread* thread) {
  179. furi_assert(thread);
  180. return thread->task_handle;
  181. }
  182. void furi_thread_enable_heap_trace(FuriThread* thread) {
  183. furi_assert(thread);
  184. furi_assert(thread->state == FuriThreadStateStopped);
  185. furi_assert(thread->heap_trace_enabled == false);
  186. thread->heap_trace_enabled = true;
  187. }
  188. void furi_thread_disable_heap_trace(FuriThread* thread) {
  189. furi_assert(thread);
  190. furi_assert(thread->state == FuriThreadStateStopped);
  191. furi_assert(thread->heap_trace_enabled == true);
  192. thread->heap_trace_enabled = false;
  193. }
  194. size_t furi_thread_get_heap_size(FuriThread* thread) {
  195. furi_assert(thread);
  196. furi_assert(thread->heap_trace_enabled == true);
  197. return thread->heap_size;
  198. }
  199. int32_t furi_thread_get_return_code(FuriThread* thread) {
  200. furi_assert(thread);
  201. furi_assert(thread->state == FuriThreadStateStopped);
  202. return thread->ret;
  203. }
  204. FuriThreadId furi_thread_get_current_id() {
  205. return xTaskGetCurrentTaskHandle();
  206. }
  207. FuriThread* furi_thread_get_current() {
  208. FuriThread* thread = pvTaskGetThreadLocalStoragePointer(NULL, 0);
  209. furi_assert(thread != NULL);
  210. return thread;
  211. }
  212. void furi_thread_yield() {
  213. furi_assert(!FURI_IS_IRQ_MODE());
  214. taskYIELD();
  215. }
  216. /* Limits */
  217. #define MAX_BITS_TASK_NOTIFY 31U
  218. #define MAX_BITS_EVENT_GROUPS 24U
  219. #define THREAD_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_TASK_NOTIFY) - 1U))
  220. #define EVENT_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_EVENT_GROUPS) - 1U))
  221. uint32_t furi_thread_flags_set(FuriThreadId thread_id, uint32_t flags) {
  222. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  223. uint32_t rflags;
  224. BaseType_t yield;
  225. if((hTask == NULL) || ((flags & THREAD_FLAGS_INVALID_BITS) != 0U)) {
  226. rflags = (uint32_t)FuriStatusErrorParameter;
  227. } else {
  228. rflags = (uint32_t)FuriStatusError;
  229. if(FURI_IS_IRQ_MODE()) {
  230. yield = pdFALSE;
  231. (void)xTaskNotifyIndexedFromISR(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits, &yield);
  232. (void)xTaskNotifyAndQueryIndexedFromISR(
  233. hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags, NULL);
  234. portYIELD_FROM_ISR(yield);
  235. } else {
  236. (void)xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, flags, eSetBits);
  237. (void)xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags);
  238. }
  239. }
  240. /* Return flags after setting */
  241. return (rflags);
  242. }
  243. uint32_t furi_thread_flags_clear(uint32_t flags) {
  244. TaskHandle_t hTask;
  245. uint32_t rflags, cflags;
  246. if(FURI_IS_IRQ_MODE()) {
  247. rflags = (uint32_t)FuriStatusErrorISR;
  248. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  249. rflags = (uint32_t)FuriStatusErrorParameter;
  250. } else {
  251. hTask = xTaskGetCurrentTaskHandle();
  252. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &cflags) ==
  253. pdPASS) {
  254. rflags = cflags;
  255. cflags &= ~flags;
  256. if(xTaskNotifyIndexed(hTask, THREAD_NOTIFY_INDEX, cflags, eSetValueWithOverwrite) !=
  257. pdPASS) {
  258. rflags = (uint32_t)FuriStatusError;
  259. }
  260. } else {
  261. rflags = (uint32_t)FuriStatusError;
  262. }
  263. }
  264. /* Return flags before clearing */
  265. return (rflags);
  266. }
  267. uint32_t furi_thread_flags_get(void) {
  268. TaskHandle_t hTask;
  269. uint32_t rflags;
  270. if(FURI_IS_IRQ_MODE()) {
  271. rflags = (uint32_t)FuriStatusErrorISR;
  272. } else {
  273. hTask = xTaskGetCurrentTaskHandle();
  274. if(xTaskNotifyAndQueryIndexed(hTask, THREAD_NOTIFY_INDEX, 0, eNoAction, &rflags) !=
  275. pdPASS) {
  276. rflags = (uint32_t)FuriStatusError;
  277. }
  278. }
  279. return (rflags);
  280. }
  281. uint32_t furi_thread_flags_wait(uint32_t flags, uint32_t options, uint32_t timeout) {
  282. uint32_t rflags, nval;
  283. uint32_t clear;
  284. TickType_t t0, td, tout;
  285. BaseType_t rval;
  286. if(FURI_IS_IRQ_MODE()) {
  287. rflags = (uint32_t)FuriStatusErrorISR;
  288. } else if((flags & THREAD_FLAGS_INVALID_BITS) != 0U) {
  289. rflags = (uint32_t)FuriStatusErrorParameter;
  290. } else {
  291. if((options & FuriFlagNoClear) == FuriFlagNoClear) {
  292. clear = 0U;
  293. } else {
  294. clear = flags;
  295. }
  296. rflags = 0U;
  297. tout = timeout;
  298. t0 = xTaskGetTickCount();
  299. do {
  300. rval = xTaskNotifyWaitIndexed(THREAD_NOTIFY_INDEX, 0, clear, &nval, tout);
  301. if(rval == pdPASS) {
  302. rflags &= flags;
  303. rflags |= nval;
  304. if((options & FuriFlagWaitAll) == FuriFlagWaitAll) {
  305. if((flags & rflags) == flags) {
  306. break;
  307. } else {
  308. if(timeout == 0U) {
  309. rflags = (uint32_t)FuriStatusErrorResource;
  310. break;
  311. }
  312. }
  313. } else {
  314. if((flags & rflags) != 0) {
  315. break;
  316. } else {
  317. if(timeout == 0U) {
  318. rflags = (uint32_t)FuriStatusErrorResource;
  319. break;
  320. }
  321. }
  322. }
  323. /* Update timeout */
  324. td = xTaskGetTickCount() - t0;
  325. if(td > tout) {
  326. tout = 0;
  327. } else {
  328. tout -= td;
  329. }
  330. } else {
  331. if(timeout == 0) {
  332. rflags = (uint32_t)FuriStatusErrorResource;
  333. } else {
  334. rflags = (uint32_t)FuriStatusErrorTimeout;
  335. }
  336. }
  337. } while(rval != pdFAIL);
  338. }
  339. /* Return flags before clearing */
  340. return (rflags);
  341. }
  342. uint32_t furi_thread_enumerate(FuriThreadId* thread_array, uint32_t array_items) {
  343. uint32_t i, count;
  344. TaskStatus_t* task;
  345. if(FURI_IS_IRQ_MODE() || (thread_array == NULL) || (array_items == 0U)) {
  346. count = 0U;
  347. } else {
  348. vTaskSuspendAll();
  349. count = uxTaskGetNumberOfTasks();
  350. task = pvPortMalloc(count * sizeof(TaskStatus_t));
  351. if(task != NULL) {
  352. count = uxTaskGetSystemState(task, count, NULL);
  353. for(i = 0U; (i < count) && (i < array_items); i++) {
  354. thread_array[i] = (FuriThreadId)task[i].xHandle;
  355. }
  356. count = i;
  357. }
  358. (void)xTaskResumeAll();
  359. vPortFree(task);
  360. }
  361. return (count);
  362. }
  363. const char* furi_thread_get_name(FuriThreadId thread_id) {
  364. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  365. const char* name;
  366. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  367. name = NULL;
  368. } else {
  369. name = pcTaskGetName(hTask);
  370. }
  371. return (name);
  372. }
  373. uint32_t furi_thread_get_stack_space(FuriThreadId thread_id) {
  374. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  375. uint32_t sz;
  376. if(FURI_IS_IRQ_MODE() || (hTask == NULL)) {
  377. sz = 0U;
  378. } else {
  379. sz = (uint32_t)(uxTaskGetStackHighWaterMark(hTask) * sizeof(StackType_t));
  380. }
  381. return (sz);
  382. }
  383. static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size) {
  384. if(thread->output.write_callback != NULL) {
  385. thread->output.write_callback(data, size);
  386. } else {
  387. furi_hal_console_tx((const uint8_t*)data, size);
  388. }
  389. return size;
  390. }
  391. static int32_t __furi_thread_stdout_flush(FuriThread* thread) {
  392. string_ptr buffer = thread->output.buffer;
  393. size_t size = string_size(buffer);
  394. if(size > 0) {
  395. __furi_thread_stdout_write(thread, string_get_cstr(buffer), size);
  396. string_reset(buffer);
  397. }
  398. return 0;
  399. }
  400. bool furi_thread_set_stdout_callback(FuriThreadStdoutWriteCallback callback) {
  401. FuriThread* thread = furi_thread_get_current();
  402. __furi_thread_stdout_flush(thread);
  403. thread->output.write_callback = callback;
  404. return true;
  405. }
  406. size_t furi_thread_stdout_write(const char* data, size_t size) {
  407. FuriThread* thread = furi_thread_get_current();
  408. if(size == 0 || data == NULL) {
  409. return __furi_thread_stdout_flush(thread);
  410. } else {
  411. if(data[size - 1] == '\n') {
  412. // if the last character is a newline, we can flush buffer and write data as is, wo buffers
  413. __furi_thread_stdout_flush(thread);
  414. __furi_thread_stdout_write(thread, data, size);
  415. } else {
  416. // string_cat doesn't work here because we need to write the exact size data
  417. for(size_t i = 0; i < size; i++) {
  418. string_push_back(thread->output.buffer, data[i]);
  419. if(data[i] == '\n') {
  420. __furi_thread_stdout_flush(thread);
  421. }
  422. }
  423. }
  424. }
  425. return size;
  426. }
  427. int32_t furi_thread_stdout_flush() {
  428. return __furi_thread_stdout_flush(furi_thread_get_current());
  429. }
  430. void furi_thread_suspend(FuriThreadId thread_id) {
  431. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  432. vTaskSuspend(hTask);
  433. }
  434. void furi_thread_resume(FuriThreadId thread_id) {
  435. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  436. if(FURI_IS_IRQ_MODE()) {
  437. xTaskResumeFromISR(hTask);
  438. } else {
  439. vTaskResume(hTask);
  440. }
  441. }
  442. bool furi_thread_is_suspended(FuriThreadId thread_id) {
  443. TaskHandle_t hTask = (TaskHandle_t)thread_id;
  444. return eTaskGetState(hTask) == eSuspended;
  445. }