scheduler_mp.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. /*
  2. * Copyright (c) 2006-2025 RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2006-03-17 Bernard the first version
  9. * 2006-04-28 Bernard fix the scheduler algorthm
  10. * 2006-04-30 Bernard add SCHEDULER_DEBUG
  11. * 2006-05-27 Bernard fix the scheduler algorthm for same priority
  12. * thread schedule
  13. * 2006-06-04 Bernard rewrite the scheduler algorithm
  14. * 2006-08-03 Bernard add hook support
  15. * 2006-09-05 Bernard add 32 priority level support
  16. * 2006-09-24 Bernard add rt_system_scheduler_start function
  17. * 2009-09-16 Bernard fix _rt_scheduler_stack_check
  18. * 2010-04-11 yi.qiu add module feature
  19. * 2010-07-13 Bernard fix the maximal number of rt_scheduler_lock_nest
  20. * issue found by kuronca
  21. * 2010-12-13 Bernard add defunct list initialization even if not use heap.
  22. * 2011-05-10 Bernard clean scheduler debug log.
  23. * 2013-12-21 Grissiom add rt_critical_level
  24. * 2018-11-22 Jesven remove the current task from ready queue
  25. * add per cpu ready queue
  26. * add _scheduler_get_highest_priority_thread to find highest priority task
  27. * rt_schedule_insert_thread won't insert current task to ready queue
  28. * in smp version, rt_hw_context_switch_interrupt maybe switch to
  29. * new task directly
  30. * 2022-01-07 Gabriel Moving __on_rt_xxxxx_hook to scheduler.c
  31. * 2023-03-27 rose_man Split into scheduler upc and scheduler_mp.c
  32. * 2023-09-15 xqyjlj perf rt_hw_interrupt_disable/enable
  33. * 2023-12-10 xqyjlj use rt_hw_spinlock
  34. * 2024-01-05 Shell Fixup of data racing in rt_critical_level
  35. * 2024-01-18 Shell support rt_sched_thread of scheduling status for better mt protection
  36. * 2024-01-18 Shell support rt_hw_thread_self to improve overall performance
  37. */
  38. #include <rtthread.h>
  39. #include <rthw.h>
  40. #define DBG_TAG "kernel.scheduler"
  41. #define DBG_LVL DBG_INFO
  42. #include <rtdbg.h>
  43. rt_list_t rt_thread_priority_table[RT_THREAD_PRIORITY_MAX];
  44. static struct rt_spinlock _mp_scheduler_lock;
  45. #define SCHEDULER_LOCK_FLAG(percpu) ((percpu)->sched_lock_flag)
  46. #define SCHEDULER_ENTER_CRITICAL(curthr) \
  47. do \
  48. { \
  49. if (curthr) RT_SCHED_CTX(curthr).critical_lock_nest++; \
  50. } while (0)
  51. #define SCHEDULER_EXIT_CRITICAL(curthr) \
  52. do \
  53. { \
  54. if (curthr) RT_SCHED_CTX(curthr).critical_lock_nest--; \
  55. } while (0)
  56. #define SCHEDULER_CONTEXT_LOCK(percpu) \
  57. do \
  58. { \
  59. RT_ASSERT(SCHEDULER_LOCK_FLAG(percpu) == 0); \
  60. _fast_spin_lock(&_mp_scheduler_lock); \
  61. SCHEDULER_LOCK_FLAG(percpu) = 1; \
  62. } while (0)
  63. #define SCHEDULER_CONTEXT_UNLOCK(percpu) \
  64. do \
  65. { \
  66. RT_ASSERT(SCHEDULER_LOCK_FLAG(percpu) == 1); \
  67. SCHEDULER_LOCK_FLAG(percpu) = 0; \
  68. _fast_spin_unlock(&_mp_scheduler_lock); \
  69. } while (0)
  70. #define SCHEDULER_LOCK(level) \
  71. do \
  72. { \
  73. rt_thread_t _curthr; \
  74. struct rt_cpu *_percpu; \
  75. level = rt_hw_local_irq_disable(); \
  76. _percpu = rt_cpu_self(); \
  77. _curthr = _percpu->current_thread; \
  78. SCHEDULER_ENTER_CRITICAL(_curthr); \
  79. SCHEDULER_CONTEXT_LOCK(_percpu); \
  80. } while (0)
  81. #define SCHEDULER_UNLOCK(level) \
  82. do \
  83. { \
  84. rt_thread_t _curthr; \
  85. struct rt_cpu *_percpu; \
  86. _percpu = rt_cpu_self(); \
  87. _curthr = _percpu->current_thread; \
  88. SCHEDULER_CONTEXT_UNLOCK(_percpu); \
  89. SCHEDULER_EXIT_CRITICAL(_curthr); \
  90. rt_hw_local_irq_enable(level); \
  91. } while (0)
  92. #ifdef ARCH_USING_HW_THREAD_SELF
  93. #define IS_CRITICAL_SWITCH_PEND(pcpu, curthr) (RT_SCHED_CTX(curthr).critical_switch_flag)
  94. #define SET_CRITICAL_SWITCH_FLAG(pcpu, curthr) (RT_SCHED_CTX(curthr).critical_switch_flag = 1)
  95. #define CLR_CRITICAL_SWITCH_FLAG(pcpu, curthr) (RT_SCHED_CTX(curthr).critical_switch_flag = 0)
  96. #else /* !ARCH_USING_HW_THREAD_SELF */
  97. #define IS_CRITICAL_SWITCH_PEND(pcpu, curthr) ((pcpu)->critical_switch_flag)
  98. #define SET_CRITICAL_SWITCH_FLAG(pcpu, curthr) ((pcpu)->critical_switch_flag = 1)
  99. #define CLR_CRITICAL_SWITCH_FLAG(pcpu, curthr) ((pcpu)->critical_switch_flag = 0)
  100. #endif /* ARCH_USING_HW_THREAD_SELF */
  101. static rt_uint32_t rt_thread_ready_priority_group;
  102. #if RT_THREAD_PRIORITY_MAX > 32
  103. /* Maximum priority level, 256 */
  104. static rt_uint8_t rt_thread_ready_table[32];
  105. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  106. /**
  107. * Used only on scheduler for optimization of control flows, where the critical
  108. * region is already guaranteed.
  109. */
  110. rt_inline void _fast_spin_lock(struct rt_spinlock *lock)
  111. {
  112. rt_hw_spin_lock(&lock->lock);
  113. RT_SPIN_LOCK_DEBUG(lock);
  114. }
  115. rt_inline void _fast_spin_unlock(struct rt_spinlock *lock)
  116. {
  117. rt_base_t critical_level;
  118. RT_SPIN_UNLOCK_DEBUG(lock, critical_level);
  119. /* for the scenario of sched, we don't check critical level */
  120. RT_UNUSED(critical_level);
  121. rt_hw_spin_unlock(&lock->lock);
  122. }
  123. #if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR)
  124. static void (*rt_scheduler_hook)(struct rt_thread *from, struct rt_thread *to);
  125. static void (*rt_scheduler_switch_hook)(struct rt_thread *tid);
  126. /**
  127. * @addtogroup group_hook
  128. */
  129. /**@{*/
  130. /**
  131. * @brief This function will set a hook function, which will be invoked when thread
  132. * switch happens.
  133. *
  134. * @param hook is the hook function.
  135. */
  136. void rt_scheduler_sethook(void (*hook)(struct rt_thread *from, struct rt_thread *to))
  137. {
  138. rt_scheduler_hook = hook;
  139. }
  140. /**
  141. * @brief This function will set a hook function, which will be invoked when context
  142. * switch happens.
  143. *
  144. * @param hook is the hook function.
  145. */
  146. void rt_scheduler_switch_sethook(void (*hook)(struct rt_thread *tid))
  147. {
  148. rt_scheduler_switch_hook = hook;
  149. }
  150. /**@}*/
  151. #endif /* RT_USING_HOOK */
  152. /**
  153. * @addtogroup group_thread_management
  154. *
  155. * @cond DOXYGEN_SMP
  156. *
  157. * @{
  158. */
  159. #if RT_THREAD_PRIORITY_MAX > 32
  160. rt_inline rt_base_t _get_global_highest_ready_prio(void)
  161. {
  162. rt_ubase_t number;
  163. rt_ubase_t highest_ready_priority;
  164. number = __rt_ffs(rt_thread_ready_priority_group) - 1;
  165. if (number != -1)
  166. {
  167. highest_ready_priority = (number << 3) + __rt_ffs(rt_thread_ready_table[number]) - 1;
  168. }
  169. else
  170. {
  171. highest_ready_priority = -1;
  172. }
  173. return highest_ready_priority;
  174. }
  175. rt_inline rt_base_t _get_local_highest_ready_prio(struct rt_cpu* pcpu)
  176. {
  177. rt_ubase_t number;
  178. rt_ubase_t local_highest_ready_priority;
  179. number = __rt_ffs(pcpu->priority_group) - 1;
  180. if (number != -1)
  181. {
  182. local_highest_ready_priority = (number << 3) + __rt_ffs(pcpu->ready_table[number]) - 1;
  183. }
  184. else
  185. {
  186. local_highest_ready_priority = -1;
  187. }
  188. return local_highest_ready_priority;
  189. }
  190. #else /* if RT_THREAD_PRIORITY_MAX <= 32 */
  191. rt_inline rt_base_t _get_global_highest_ready_prio(void)
  192. {
  193. return __rt_ffs(rt_thread_ready_priority_group) - 1;
  194. }
  195. rt_inline rt_base_t _get_local_highest_ready_prio(struct rt_cpu* pcpu)
  196. {
  197. return __rt_ffs(pcpu->priority_group) - 1;
  198. }
  199. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  200. /*
  201. * get the highest priority thread in ready queue
  202. */
  203. static struct rt_thread* _scheduler_get_highest_priority_thread(rt_ubase_t *highest_prio)
  204. {
  205. struct rt_thread *highest_priority_thread;
  206. rt_ubase_t highest_ready_priority, local_highest_ready_priority;
  207. struct rt_cpu* pcpu = rt_cpu_self();
  208. highest_ready_priority = _get_global_highest_ready_prio();
  209. local_highest_ready_priority = _get_local_highest_ready_prio(pcpu);
  210. /* get highest ready priority thread */
  211. if (highest_ready_priority < local_highest_ready_priority)
  212. {
  213. *highest_prio = highest_ready_priority;
  214. highest_priority_thread = RT_THREAD_LIST_NODE_ENTRY(
  215. rt_thread_priority_table[highest_ready_priority].next);
  216. }
  217. else
  218. {
  219. *highest_prio = local_highest_ready_priority;
  220. if (local_highest_ready_priority != -1)
  221. {
  222. highest_priority_thread = RT_THREAD_LIST_NODE_ENTRY(
  223. pcpu->priority_table[local_highest_ready_priority].next);
  224. }
  225. else
  226. {
  227. highest_priority_thread = RT_NULL;
  228. }
  229. }
  230. RT_ASSERT(!highest_priority_thread ||
  231. rt_object_get_type(&highest_priority_thread->parent) == RT_Object_Class_Thread);
  232. return highest_priority_thread;
  233. }
  234. /**
  235. * @brief set READY and insert thread to ready queue
  236. *
  237. * @note caller must holding the `_mp_scheduler_lock` lock
  238. */
  239. static void _sched_insert_thread_locked(struct rt_thread *thread)
  240. {
  241. int cpu_id;
  242. int bind_cpu;
  243. rt_uint32_t cpu_mask;
  244. if ((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) == RT_THREAD_READY)
  245. {
  246. /* already in ready queue */
  247. return ;
  248. }
  249. else if (RT_SCHED_CTX(thread).oncpu != RT_CPU_DETACHED)
  250. {
  251. /**
  252. * only YIELD -> READY, SUSPEND -> READY is allowed by this API. However,
  253. * this is a RUNNING thread. So here we reset it's status and let it go.
  254. */
  255. RT_SCHED_CTX(thread).stat = RT_THREAD_RUNNING | (RT_SCHED_CTX(thread).stat & ~RT_THREAD_STAT_MASK);
  256. return ;
  257. }
  258. /* READY thread, insert to ready queue */
  259. RT_SCHED_CTX(thread).stat = RT_THREAD_READY | (RT_SCHED_CTX(thread).stat & ~RT_THREAD_STAT_MASK);
  260. cpu_id = rt_hw_cpu_id();
  261. bind_cpu = RT_SCHED_CTX(thread).bind_cpu;
  262. /* insert thread to ready list */
  263. if (bind_cpu == RT_CPUS_NR)
  264. {
  265. #if RT_THREAD_PRIORITY_MAX > 32
  266. rt_thread_ready_table[RT_SCHED_PRIV(thread).number] |= RT_SCHED_PRIV(thread).high_mask;
  267. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  268. rt_thread_ready_priority_group |= RT_SCHED_PRIV(thread).number_mask;
  269. /* there is no time slices left(YIELD), inserting thread before ready list*/
  270. if((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_YIELD_MASK) != 0)
  271. {
  272. rt_list_insert_before(&(rt_thread_priority_table[RT_SCHED_PRIV(thread).current_priority]),
  273. &RT_THREAD_LIST_NODE(thread));
  274. }
  275. /* there are some time slices left, inserting thread after ready list to schedule it firstly at next time*/
  276. else
  277. {
  278. rt_list_insert_after(&(rt_thread_priority_table[RT_SCHED_PRIV(thread).current_priority]),
  279. &RT_THREAD_LIST_NODE(thread));
  280. }
  281. cpu_mask = RT_CPU_MASK ^ (1 << cpu_id);
  282. rt_hw_ipi_send(RT_SCHEDULE_IPI, cpu_mask);
  283. }
  284. else
  285. {
  286. struct rt_cpu *pcpu = rt_cpu_index(bind_cpu);
  287. #if RT_THREAD_PRIORITY_MAX > 32
  288. pcpu->ready_table[RT_SCHED_PRIV(thread).number] |= RT_SCHED_PRIV(thread).high_mask;
  289. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  290. pcpu->priority_group |= RT_SCHED_PRIV(thread).number_mask;
  291. /* there is no time slices left(YIELD), inserting thread before ready list*/
  292. if((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_YIELD_MASK) != 0)
  293. {
  294. rt_list_insert_before(&(rt_cpu_index(bind_cpu)->priority_table[RT_SCHED_PRIV(thread).current_priority]),
  295. &RT_THREAD_LIST_NODE(thread));
  296. }
  297. /* there are some time slices left, inserting thread after ready list to schedule it firstly at next time*/
  298. else
  299. {
  300. rt_list_insert_after(&(rt_cpu_index(bind_cpu)->priority_table[RT_SCHED_PRIV(thread).current_priority]),
  301. &RT_THREAD_LIST_NODE(thread));
  302. }
  303. if (cpu_id != bind_cpu)
  304. {
  305. cpu_mask = 1 << bind_cpu;
  306. rt_hw_ipi_send(RT_SCHEDULE_IPI, cpu_mask);
  307. }
  308. }
  309. LOG_D("insert thread[%.*s], the priority: %d",
  310. RT_NAME_MAX, thread->parent.name, RT_SCHED_PRIV(thread).current_priority);
  311. }
  312. /* remove thread from ready queue */
  313. static void _sched_remove_thread_locked(struct rt_thread *thread)
  314. {
  315. LOG_D("%s [%.*s], the priority: %d", __func__,
  316. RT_NAME_MAX, thread->parent.name,
  317. RT_SCHED_PRIV(thread).current_priority);
  318. /* remove thread from ready list */
  319. rt_list_remove(&RT_THREAD_LIST_NODE(thread));
  320. if (RT_SCHED_CTX(thread).bind_cpu == RT_CPUS_NR)
  321. {
  322. if (rt_list_isempty(&(rt_thread_priority_table[RT_SCHED_PRIV(thread).current_priority])))
  323. {
  324. #if RT_THREAD_PRIORITY_MAX > 32
  325. rt_thread_ready_table[RT_SCHED_PRIV(thread).number] &= ~RT_SCHED_PRIV(thread).high_mask;
  326. if (rt_thread_ready_table[RT_SCHED_PRIV(thread).number] == 0)
  327. {
  328. rt_thread_ready_priority_group &= ~RT_SCHED_PRIV(thread).number_mask;
  329. }
  330. #else
  331. rt_thread_ready_priority_group &= ~RT_SCHED_PRIV(thread).number_mask;
  332. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  333. }
  334. }
  335. else
  336. {
  337. struct rt_cpu *pcpu = rt_cpu_index(RT_SCHED_CTX(thread).bind_cpu);
  338. if (rt_list_isempty(&(pcpu->priority_table[RT_SCHED_PRIV(thread).current_priority])))
  339. {
  340. #if RT_THREAD_PRIORITY_MAX > 32
  341. pcpu->ready_table[RT_SCHED_PRIV(thread).number] &= ~RT_SCHED_PRIV(thread).high_mask;
  342. if (pcpu->ready_table[RT_SCHED_PRIV(thread).number] == 0)
  343. {
  344. pcpu->priority_group &= ~RT_SCHED_PRIV(thread).number_mask;
  345. }
  346. #else
  347. pcpu->priority_group &= ~RT_SCHED_PRIV(thread).number_mask;
  348. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  349. }
  350. }
  351. }
  352. /**
  353. * @brief Initialize the system scheduler.
  354. *
  355. * @note This function must be called before any thread scheduling can occur.
  356. * It prepares the scheduler data structures for multi-core operation.
  357. *
  358. * @note This function has both MP version and UP version.
  359. */
  360. /*
  361. * Don't include below in doxygen document due to they are MP version only.
  362. * @details This function performs the following initialization tasks:
  363. * - Initializes the global scheduler spinlock for multi-core synchronization.
  364. * - Initializes the global priority table for saving ready threads of all priority levels.
  365. * - For each CPU core:
  366. * * Initializes per-CPU priority tables
  367. * * Sets initial CPU state (irq_switch_flag, current_priority, etc.)
  368. * * Initializes per-CPU ready tables (if priority > 32)
  369. * * Initializes per-CPU spinlock (if RT_USING_SMART is defined)
  370. * - Initializes the global ready priority group and tables (if priority > 32) as bitmaps for all priorities.
  371. */
  372. void rt_system_scheduler_init(void)
  373. {
  374. int cpu;
  375. rt_base_t offset;
  376. LOG_D("start scheduler: max priority 0x%02x",
  377. RT_THREAD_PRIORITY_MAX);
  378. rt_spin_lock_init(&_mp_scheduler_lock);
  379. for (offset = 0; offset < RT_THREAD_PRIORITY_MAX; offset ++)
  380. {
  381. rt_list_init(&rt_thread_priority_table[offset]);
  382. }
  383. for (cpu = 0; cpu < RT_CPUS_NR; cpu++)
  384. {
  385. struct rt_cpu *pcpu = rt_cpu_index(cpu);
  386. for (offset = 0; offset < RT_THREAD_PRIORITY_MAX; offset ++)
  387. {
  388. rt_list_init(&pcpu->priority_table[offset]);
  389. }
  390. pcpu->irq_switch_flag = 0;
  391. pcpu->current_priority = RT_THREAD_PRIORITY_MAX - 1;
  392. pcpu->current_thread = RT_NULL;
  393. pcpu->priority_group = 0;
  394. #if RT_THREAD_PRIORITY_MAX > 32
  395. rt_memset(pcpu->ready_table, 0, sizeof(pcpu->ready_table));
  396. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  397. #ifdef RT_USING_SMART
  398. rt_spin_lock_init(&(pcpu->spinlock));
  399. #endif
  400. }
  401. /* initialize ready priority group */
  402. rt_thread_ready_priority_group = 0;
  403. #if RT_THREAD_PRIORITY_MAX > 32
  404. /* initialize ready table */
  405. rt_memset(rt_thread_ready_table, 0, sizeof(rt_thread_ready_table));
  406. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  407. }
  408. /**
  409. * @brief Start the system scheduler and switch to the highest priority thread.
  410. *
  411. * @note This function will not return after successful execution.
  412. * It performs the initial thread switch during system startup.
  413. * The scheduler must be initialized before calling this function.
  414. *
  415. * @note This function has both MP version and UP version.
  416. */
  417. /*
  418. * Don't include below in doxygen document due to they are MP version only.
  419. * @details This function performs the following operations:
  420. * - Releases legacy CPU lock (if any)
  421. * - Disables interrupts to ensure atomic operation
  422. * - Acquires scheduler lock for thread safety
  423. * - Selects the highest priority thread from ready queue
  424. * - Removes the selected thread from ready queue
  425. * - Assigns current CPU core to the selected thread
  426. * - Performs context switch to the selected thread
  427. */
  428. void rt_system_scheduler_start(void)
  429. {
  430. struct rt_thread *to_thread;
  431. rt_ubase_t highest_ready_priority;
  432. /*
  433. * legacy rt_cpus_lock. some bsp codes still use it as for it's critical
  434. * region. Since scheduler is never touching this, here we just release it
  435. * on the entry.
  436. */
  437. rt_hw_spin_unlock(&_cpus_lock);
  438. /* ISR will corrupt the coherency of running frame */
  439. rt_hw_local_irq_disable();
  440. /*
  441. * for the accessing of the scheduler context. Noted that we don't have
  442. * current_thread at this point
  443. */
  444. _fast_spin_lock(&_mp_scheduler_lock);
  445. /* get the thread scheduling to */
  446. to_thread = _scheduler_get_highest_priority_thread(&highest_ready_priority);
  447. RT_ASSERT(to_thread);
  448. /* to_thread is picked to running on current core, so remove it from ready queue */
  449. _sched_remove_thread_locked(to_thread);
  450. /* dedigate current core to `to_thread` */
  451. RT_SCHED_CTX(to_thread).oncpu = rt_hw_cpu_id();
  452. RT_SCHED_CTX(to_thread).stat = RT_THREAD_RUNNING;
  453. LOG_D("[cpu#%d] switch to priority#%d thread:%.*s(sp:0x%08x)",
  454. rt_hw_cpu_id(), RT_SCHED_PRIV(to_thread).current_priority,
  455. RT_NAME_MAX, to_thread->parent.name, to_thread->sp);
  456. _fast_spin_unlock(&_mp_scheduler_lock);
  457. /* switch to new thread */
  458. rt_hw_context_switch_to((rt_ubase_t)&to_thread->sp, to_thread);
  459. /* never come back */
  460. }
  461. /**
  462. * @brief This function will handle IPI interrupt and do a scheduling in system.
  463. *
  464. * This function should be invoke or register as ISR in BSP.
  465. *
  466. * @param vector The number of IPI interrupt for system scheduling.
  467. *
  468. * @param param Not used, and can be set to RT_NULL.
  469. *
  470. * @note This function only has MP version.
  471. */
  472. void rt_scheduler_ipi_handler(int vector, void *param)
  473. {
  474. rt_schedule();
  475. }
  476. /**
  477. * @brief Lock the system scheduler
  478. *
  479. * @param plvl Pointer to the object where lock level stores to
  480. *
  481. * @return rt_err_t
  482. * - RT_EOK on success
  483. * - -RT_EINVAL if plvl is NULL
  484. *
  485. * @note This function has both MP version and UP version.
  486. */
  487. rt_err_t rt_sched_lock(rt_sched_lock_level_t *plvl)
  488. {
  489. rt_base_t level;
  490. if (!plvl)
  491. return -RT_EINVAL;
  492. SCHEDULER_LOCK(level);
  493. *plvl = level;
  494. return RT_EOK;
  495. }
  496. /**
  497. * @brief Unlock the scheduler and restore the interrupt level
  498. *
  499. * @param level The interrupt level to restore (previously saved by rt_sched_lock)
  500. *
  501. * @return rt_err_t Always returns RT_EOK
  502. *
  503. * @note This function has both MP version and UP version.
  504. */
  505. rt_err_t rt_sched_unlock(rt_sched_lock_level_t level)
  506. {
  507. SCHEDULER_UNLOCK(level);
  508. return RT_EOK;
  509. }
  510. /**
  511. * @brief Check if the scheduler is currently locked
  512. *
  513. * This function checks the scheduler lock status in a thread-safe manner
  514. * by temporarily disabling interrupts to get consistent state.
  515. *
  516. * @return rt_bool_t Returns RT_TRUE if scheduler is locked, RT_FALSE otherwise
  517. *
  518. * @note This function only has MP version.
  519. */
  520. rt_bool_t rt_sched_is_locked(void)
  521. {
  522. rt_bool_t rc;
  523. rt_base_t level;
  524. struct rt_cpu *pcpu;
  525. level = rt_hw_local_irq_disable();
  526. pcpu = rt_cpu_self();
  527. /* get lock stat which is a boolean value */
  528. rc = pcpu->sched_lock_flag;
  529. rt_hw_local_irq_enable(level);
  530. return rc;
  531. }
  532. /**
  533. * @brief Pick the highest runnable thread, and pass the control to it
  534. *
  535. * @note caller should hold the scheduler context lock. lock will be released
  536. * before return from this routine
  537. */
  538. static rt_thread_t _prepare_context_switch_locked(int cpu_id,
  539. struct rt_cpu *pcpu,
  540. rt_thread_t current_thread)
  541. {
  542. rt_thread_t to_thread = RT_NULL;
  543. rt_ubase_t highest_ready_priority;
  544. /* quickly check if any other ready threads queuing */
  545. if (rt_thread_ready_priority_group != 0 || pcpu->priority_group != 0)
  546. {
  547. /* pick the highest ready thread */
  548. to_thread = _scheduler_get_highest_priority_thread(&highest_ready_priority);
  549. /* detach current thread from percpu scheduling context */
  550. RT_SCHED_CTX(current_thread).oncpu = RT_CPU_DETACHED;
  551. /* check if current thread should be put to ready queue, or scheduling again */
  552. if ((RT_SCHED_CTX(current_thread).stat & RT_THREAD_STAT_MASK) == RT_THREAD_RUNNING)
  553. {
  554. /* check if current thread can be running on current core again */
  555. if (RT_SCHED_CTX(current_thread).bind_cpu == RT_CPUS_NR
  556. || RT_SCHED_CTX(current_thread).bind_cpu == cpu_id)
  557. {
  558. /* if current_thread is the highest runnable thread */
  559. if (RT_SCHED_PRIV(current_thread).current_priority < highest_ready_priority)
  560. {
  561. to_thread = current_thread;
  562. }
  563. /* or no higher-priority thread existed and it has remaining ticks */
  564. else if (RT_SCHED_PRIV(current_thread).current_priority == highest_ready_priority &&
  565. (RT_SCHED_CTX(current_thread).stat & RT_THREAD_STAT_YIELD_MASK) == 0)
  566. {
  567. to_thread = current_thread;
  568. }
  569. /* otherwise give out the core */
  570. else
  571. {
  572. _sched_insert_thread_locked(current_thread);
  573. }
  574. }
  575. else
  576. {
  577. /* put current_thread to ready queue of another core */
  578. _sched_insert_thread_locked(current_thread);
  579. }
  580. /* consume the yield flags after scheduling */
  581. RT_SCHED_CTX(current_thread).stat &= ~RT_THREAD_STAT_YIELD_MASK;
  582. }
  583. /**
  584. * Now destination thread is determined, core is passed to it. Though
  585. * the percpu scheduling context is not updated here, since the cpu
  586. * is locked contiguously before all the scheduling works are done, it's
  587. * safe to observe that current thread as the running thread on this
  588. * core for any observers if they properly do the synchronization
  589. * (take the SCHEDULER_LOCK).
  590. */
  591. RT_SCHED_CTX(to_thread).oncpu = cpu_id;
  592. /* check if context switch is required */
  593. if (to_thread != current_thread)
  594. {
  595. pcpu->current_priority = (rt_uint8_t)highest_ready_priority;
  596. RT_OBJECT_HOOK_CALL(rt_scheduler_hook, (current_thread, to_thread));
  597. /* remove to_thread from ready queue and update its status to RUNNING */
  598. _sched_remove_thread_locked(to_thread);
  599. RT_SCHED_CTX(to_thread).stat = RT_THREAD_RUNNING | (RT_SCHED_CTX(to_thread).stat & ~RT_THREAD_STAT_MASK);
  600. RT_SCHEDULER_STACK_CHECK(to_thread);
  601. RT_OBJECT_HOOK_CALL(rt_scheduler_switch_hook, (current_thread));
  602. }
  603. else
  604. {
  605. /* current thread is still the best runnable thread */
  606. to_thread = RT_NULL;
  607. }
  608. }
  609. else
  610. {
  611. /* no ready threads */
  612. to_thread = RT_NULL;
  613. }
  614. return to_thread;
  615. }
  616. #ifdef RT_USING_SIGNALS
  617. /**
  618. * @brief Preprocess pending signals for a suspended thread
  619. *
  620. * @param current_thread The thread to check for pending signals
  621. *
  622. * @details This function checks if the specified thread is suspended and has pending signals.
  623. * If both conditions are met, it will wake up/resume the thread to process the signals.
  624. */
  625. static void _sched_thread_preprocess_signal(struct rt_thread *current_thread)
  626. {
  627. /* should process signal? */
  628. if (rt_sched_thread_is_suspended(current_thread))
  629. {
  630. /* if current_thread signal is in pending */
  631. if ((RT_SCHED_CTX(current_thread).stat & RT_THREAD_STAT_SIGNAL_MASK) & RT_THREAD_STAT_SIGNAL_PENDING)
  632. {
  633. #ifdef RT_USING_SMART
  634. rt_thread_wakeup(current_thread);
  635. #else
  636. rt_thread_resume(current_thread);
  637. #endif
  638. }
  639. }
  640. }
  641. /**
  642. * @brief Process pending signals for the current thread
  643. *
  644. * @param current_thread The thread to process signals for
  645. *
  646. * @details This function:
  647. * - Locks the scheduler to ensure thread safety
  648. * - Checks if the thread has pending signals
  649. * - If signals are pending:
  650. * * Clears the pending flag
  651. * * Unlocks the scheduler
  652. * * Calls signal handler to process the signals
  653. * - If no signals pending, simply unlocks the scheduler
  654. */
  655. static void _sched_thread_process_signal(struct rt_thread *current_thread)
  656. {
  657. rt_base_t level;
  658. SCHEDULER_LOCK(level);
  659. /* check stat of thread for signal */
  660. if (RT_SCHED_CTX(current_thread).stat & RT_THREAD_STAT_SIGNAL_PENDING)
  661. {
  662. extern void rt_thread_handle_sig(rt_bool_t clean_state);
  663. RT_SCHED_CTX(current_thread).stat &= ~RT_THREAD_STAT_SIGNAL_PENDING;
  664. SCHEDULER_UNLOCK(level);
  665. /* check signal status */
  666. rt_thread_handle_sig(RT_TRUE);
  667. }
  668. else
  669. {
  670. SCHEDULER_UNLOCK(level);
  671. }
  672. /* lock is released above */
  673. }
  674. #define SCHED_THREAD_PREPROCESS_SIGNAL(pcpu, curthr) \
  675. do \
  676. { \
  677. SCHEDULER_CONTEXT_LOCK(pcpu); \
  678. _sched_thread_preprocess_signal(curthr); \
  679. SCHEDULER_CONTEXT_UNLOCK(pcpu); \
  680. } while (0)
  681. #define SCHED_THREAD_PREPROCESS_SIGNAL_LOCKED(curthr) \
  682. _sched_thread_preprocess_signal(curthr)
  683. #define SCHED_THREAD_PROCESS_SIGNAL(curthr) _sched_thread_process_signal(curthr)
  684. #else /* ! RT_USING_SIGNALS */
  685. #define SCHED_THREAD_PREPROCESS_SIGNAL(pcpu, curthr)
  686. #define SCHED_THREAD_PREPROCESS_SIGNAL_LOCKED(curthr)
  687. #define SCHED_THREAD_PROCESS_SIGNAL(curthr)
  688. #endif /* RT_USING_SIGNALS */
  689. /**
  690. * @brief Unlock scheduler and perform rescheduling if needed
  691. *
  692. * @param level The scheduler lock level obtained from rt_sched_lock()
  693. *
  694. * @return rt_err_t
  695. * - RT_EOK: Success
  696. * - -RT_EBUSY: Scheduler not available
  697. * - -RT_ESCHEDISR: Called in interrupt context
  698. * - -RT_ESCHEDLOCKED: Scheduler still locked by others
  699. *
  700. * @details This function:
  701. * - Releases scheduler lock at specified level
  702. * - Checks if rescheduling is needed
  703. * - If needed, finds highest priority thread and switches to it
  704. * - Processes pending signals for current thread
  705. * - Handles various error conditions
  706. *
  707. * @note Must be called in pair with rt_sched_lock()
  708. * May trigger context switch if conditions met
  709. *
  710. * @note This function has both MP version and UP version.
  711. */
  712. rt_err_t rt_sched_unlock_n_resched(rt_sched_lock_level_t level)
  713. {
  714. struct rt_thread *to_thread;
  715. struct rt_thread *current_thread;
  716. struct rt_cpu *pcpu;
  717. int cpu_id;
  718. rt_err_t error = RT_EOK;
  719. cpu_id = rt_hw_cpu_id();
  720. pcpu = rt_cpu_index(cpu_id);
  721. current_thread = pcpu->current_thread;
  722. if (!current_thread)
  723. {
  724. /* scheduler is unavailable yet */
  725. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  726. SCHEDULER_EXIT_CRITICAL(current_thread);
  727. rt_hw_local_irq_enable(level);
  728. return -RT_EBUSY;
  729. }
  730. /* whether do switch in interrupt */
  731. if (rt_atomic_load(&(pcpu->irq_nest)))
  732. {
  733. pcpu->irq_switch_flag = 1;
  734. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  735. SCHEDULER_EXIT_CRITICAL(current_thread);
  736. rt_hw_local_irq_enable(level);
  737. return -RT_ESCHEDISR;
  738. }
  739. /* prepare current_thread for processing if signals existed */
  740. SCHED_THREAD_PREPROCESS_SIGNAL_LOCKED(current_thread);
  741. /* whether caller had locked the local scheduler already */
  742. if (RT_SCHED_CTX(current_thread).critical_lock_nest > 1)
  743. {
  744. /* leaving critical region of global context since we can't schedule */
  745. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  746. SET_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  747. error = -RT_ESCHEDLOCKED;
  748. SCHEDULER_EXIT_CRITICAL(current_thread);
  749. }
  750. else
  751. {
  752. /* flush critical switch flag since a scheduling is done */
  753. CLR_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  754. /* pick the highest runnable thread, and pass the control to it */
  755. to_thread = _prepare_context_switch_locked(cpu_id, pcpu, current_thread);
  756. if (to_thread)
  757. {
  758. /* switch to new thread */
  759. LOG_D("[cpu#%d] UNLOCK switch to priority#%d "
  760. "thread:%.*s(sp:0x%08x), "
  761. "from thread:%.*s(sp: 0x%08x)",
  762. cpu_id, RT_SCHED_PRIV(to_thread).current_priority,
  763. RT_NAME_MAX, to_thread->parent.name, to_thread->sp,
  764. RT_NAME_MAX, current_thread->parent.name, current_thread->sp);
  765. rt_hw_context_switch((rt_ubase_t)&current_thread->sp,
  766. (rt_ubase_t)&to_thread->sp, to_thread);
  767. }
  768. else
  769. {
  770. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  771. SCHEDULER_EXIT_CRITICAL(current_thread);
  772. }
  773. }
  774. /* leaving critical region of percpu scheduling context */
  775. rt_hw_local_irq_enable(level);
  776. /* process signals on thread if any existed */
  777. SCHED_THREAD_PROCESS_SIGNAL(current_thread);
  778. return error;
  779. }
  780. /**
  781. * @brief This function will perform one scheduling. It will select one thread
  782. * with the highest priority level in global ready queue or local ready queue,
  783. * then switch to it.
  784. *
  785. * @note This function has both MP version and UP version.
  786. */
  787. /*
  788. * NOTE: not in doxygen due to these info. are special for MP version
  789. * @details This function performs the following operations:
  790. * - Disables interrupts to enter critical section
  791. * - Gets current CPU and thread context
  792. * - Checks if called from interrupt context
  793. * - Finds highest priority ready thread
  794. * - Performs context switch if needed
  795. * - Processes pending signals
  796. * - Restores interrupt state
  797. */
  798. void rt_schedule(void)
  799. {
  800. rt_base_t level;
  801. struct rt_thread *to_thread;
  802. struct rt_thread *current_thread;
  803. struct rt_cpu *pcpu;
  804. int cpu_id;
  805. /* enter ciritical region of percpu scheduling context */
  806. level = rt_hw_local_irq_disable();
  807. /* get percpu scheduling context */
  808. cpu_id = rt_hw_cpu_id();
  809. pcpu = rt_cpu_index(cpu_id);
  810. current_thread = pcpu->current_thread;
  811. /* whether do switch in interrupt */
  812. if (rt_atomic_load(&(pcpu->irq_nest)))
  813. {
  814. pcpu->irq_switch_flag = 1;
  815. rt_hw_local_irq_enable(level);
  816. return ; /* -RT_ESCHEDISR */
  817. }
  818. /* forbid any recursive entries of schedule() */
  819. SCHEDULER_ENTER_CRITICAL(current_thread);
  820. /* prepare current_thread for processing if signals existed */
  821. SCHED_THREAD_PREPROCESS_SIGNAL(pcpu, current_thread);
  822. /* whether caller had locked the local scheduler already */
  823. if (RT_SCHED_CTX(current_thread).critical_lock_nest > 1)
  824. {
  825. SET_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  826. SCHEDULER_EXIT_CRITICAL(current_thread);
  827. /* -RT_ESCHEDLOCKED */
  828. }
  829. else
  830. {
  831. /* flush critical switch flag since a scheduling is done */
  832. CLR_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  833. pcpu->irq_switch_flag = 0;
  834. /*
  835. * take the context lock before we do the real scheduling works. Context
  836. * lock will be released before returning from this _schedule_locked()
  837. */
  838. SCHEDULER_CONTEXT_LOCK(pcpu);
  839. /* pick the highest runnable thread, and pass the control to it */
  840. to_thread = _prepare_context_switch_locked(cpu_id, pcpu, current_thread);
  841. if (to_thread)
  842. {
  843. LOG_D("[cpu#%d] switch to priority#%d "
  844. "thread:%.*s(sp:0x%08x), "
  845. "from thread:%.*s(sp: 0x%08x)",
  846. cpu_id, RT_SCHED_PRIV(to_thread).current_priority,
  847. RT_NAME_MAX, to_thread->parent.name, to_thread->sp,
  848. RT_NAME_MAX, current_thread->parent.name, current_thread->sp);
  849. rt_hw_context_switch((rt_ubase_t)&current_thread->sp,
  850. (rt_ubase_t)&to_thread->sp, to_thread);
  851. }
  852. else
  853. {
  854. /* current thread continue to take the core */
  855. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  856. SCHEDULER_EXIT_CRITICAL(current_thread);
  857. }
  858. }
  859. /* leaving critical region of percpu scheduling context */
  860. rt_hw_local_irq_enable(level);
  861. /* process signals on thread if any existed */
  862. SCHED_THREAD_PROCESS_SIGNAL(current_thread);
  863. }
  864. /**
  865. * @brief Perform thread scheduling after an interrupt context switch
  866. *
  867. * @param context The interrupt context pointer
  868. *
  869. * @details This function handles scheduling when returning from interrupt context:
  870. * - Checks if scheduling is needed (irq_switch_flag set)
  871. * - If needed, finds highest priority ready thread
  872. * - Performs context switch to new thread if available
  873. * - Handles cases where scheduler is locked or still in interrupt context
  874. * - Processes pending signals before scheduling
  875. *
  876. * @note This function only has MP version.
  877. */
  878. void rt_scheduler_do_irq_switch(void *context)
  879. {
  880. int cpu_id;
  881. rt_base_t level;
  882. struct rt_cpu *pcpu;
  883. struct rt_thread *to_thread;
  884. struct rt_thread *current_thread;
  885. level = rt_hw_local_irq_disable();
  886. cpu_id = rt_hw_cpu_id();
  887. pcpu = rt_cpu_index(cpu_id);
  888. current_thread = pcpu->current_thread;
  889. /* forbid any recursive entries of schedule() */
  890. SCHEDULER_ENTER_CRITICAL(current_thread);
  891. SCHED_THREAD_PREPROCESS_SIGNAL(pcpu, current_thread);
  892. /* any pending scheduling existed? */
  893. if (pcpu->irq_switch_flag == 0)
  894. {
  895. /* if no, just continue execution of current_thread */
  896. SCHEDULER_EXIT_CRITICAL(current_thread);
  897. rt_hw_local_irq_enable(level);
  898. return;
  899. }
  900. /* whether caller had locked the local scheduler already */
  901. if (RT_SCHED_CTX(current_thread).critical_lock_nest > 1)
  902. {
  903. SET_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  904. SCHEDULER_EXIT_CRITICAL(current_thread);
  905. }
  906. else if (rt_atomic_load(&(pcpu->irq_nest)) == 0)
  907. {
  908. /* flush critical & irq switch flag since a scheduling is done */
  909. CLR_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  910. pcpu->irq_switch_flag = 0;
  911. SCHEDULER_CONTEXT_LOCK(pcpu);
  912. /* pick the highest runnable thread, and pass the control to it */
  913. to_thread = _prepare_context_switch_locked(cpu_id, pcpu, current_thread);
  914. if (to_thread)
  915. {
  916. LOG_D("[cpu#%d] IRQ switch to priority#%d "
  917. "thread:%.*s(sp:0x%08x), "
  918. "from thread:%.*s(sp: 0x%08x)",
  919. cpu_id, RT_SCHED_PRIV(to_thread).current_priority,
  920. RT_NAME_MAX, to_thread->parent.name, to_thread->sp,
  921. RT_NAME_MAX, current_thread->parent.name, current_thread->sp);
  922. rt_hw_context_switch_interrupt(context, (rt_ubase_t)&current_thread->sp,
  923. (rt_ubase_t)&to_thread->sp, to_thread);
  924. }
  925. else
  926. {
  927. /* current thread continue to take the core */
  928. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  929. SCHEDULER_EXIT_CRITICAL(current_thread);
  930. }
  931. }
  932. else
  933. {
  934. SCHEDULER_EXIT_CRITICAL(current_thread);
  935. }
  936. /* leaving critical region of percpu scheduling context */
  937. rt_hw_local_irq_enable(level);
  938. }
  939. /**
  940. * @brief This function will insert a thread to the system ready queue. The state of
  941. * thread will be set as READY and the thread will be removed from suspend queue.
  942. *
  943. * @param thread The thread to be inserted.
  944. *
  945. * @note Please do not invoke this function in user application.
  946. * Caller must hold the scheduler lock
  947. *
  948. * @note This function has both MP version and UP version.
  949. */
  950. void rt_sched_insert_thread(struct rt_thread *thread)
  951. {
  952. RT_ASSERT(thread != RT_NULL);
  953. RT_SCHED_DEBUG_IS_LOCKED;
  954. /* set READY and insert thread to ready queue */
  955. _sched_insert_thread_locked(thread);
  956. }
  957. /**
  958. * @brief This function will remove a thread from system ready queue.
  959. *
  960. * @param thread The thread to be removed.
  961. *
  962. * @note Please do not invoke this function in user application.
  963. *
  964. * @note This function has both MP version and UP version.
  965. */
  966. void rt_sched_remove_thread(struct rt_thread *thread)
  967. {
  968. RT_ASSERT(thread != RT_NULL);
  969. RT_SCHED_DEBUG_IS_LOCKED;
  970. /* remove thread from scheduler ready list */
  971. _sched_remove_thread_locked(thread);
  972. RT_SCHED_CTX(thread).stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE;
  973. }
  974. /**
  975. * @brief Initialize thread's scheduling private data
  976. *
  977. * @param thread The thread to be initialized
  978. * @param tick Initial time slice value for the thread
  979. * @param priority Initial priority of the thread
  980. *
  981. * @details This function performs the following initialization:
  982. * - Initializes thread's ready list node
  983. * - Sets initial and current priority (must be < RT_THREAD_PRIORITY_MAX)
  984. * - Initializes priority bitmasks (handles >32 priorities if needed)
  985. * - Sets initial time slice values
  986. * - For SMP systems, initializes critical section nesting counter
  987. *
  988. * @note This function has both MP version and UP version.
  989. */
  990. void rt_sched_thread_init_priv(struct rt_thread *thread, rt_uint32_t tick, rt_uint8_t priority)
  991. {
  992. rt_list_init(&RT_THREAD_LIST_NODE(thread));
  993. /* priority init */
  994. RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX);
  995. RT_SCHED_PRIV(thread).init_priority = priority;
  996. RT_SCHED_PRIV(thread).current_priority = priority;
  997. /* don't add to scheduler queue as init thread */
  998. RT_SCHED_PRIV(thread).number_mask = 0;
  999. #if RT_THREAD_PRIORITY_MAX > 32
  1000. RT_SCHED_PRIV(thread).number = 0;
  1001. RT_SCHED_PRIV(thread).high_mask = 0;
  1002. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  1003. /* tick init */
  1004. RT_SCHED_PRIV(thread).init_tick = tick;
  1005. RT_SCHED_PRIV(thread).remaining_tick = tick;
  1006. #ifdef RT_USING_SMP
  1007. /* lock init */
  1008. RT_SCHED_CTX(thread).critical_lock_nest = 0;
  1009. #endif /* RT_USING_SMP */
  1010. }
  1011. /**
  1012. * @brief Initialize thread scheduling attributes for startup
  1013. *
  1014. * @param thread The thread to be initialized
  1015. *
  1016. * @details This function:
  1017. * - For systems with >32 priorities:
  1018. * * Sets priority number (5 bits)
  1019. * * Initializes number_mask and high_mask (3 bits)
  1020. * - For systems with <=32 priorities:
  1021. * * Initializes number_mask
  1022. * - Sets thread state to SUSPEND
  1023. *
  1024. * @note This is a lockless operation as it's called during thread creation
  1025. * when no concurrent access is possible
  1026. *
  1027. * @note This function has both MP version and UP version.
  1028. */
  1029. void rt_sched_thread_startup(struct rt_thread *thread)
  1030. {
  1031. #if RT_THREAD_PRIORITY_MAX > 32
  1032. RT_SCHED_PRIV(thread).number = RT_SCHED_PRIV(thread).current_priority >> 3; /* 5bit */
  1033. RT_SCHED_PRIV(thread).number_mask = 1L << RT_SCHED_PRIV(thread).number;
  1034. RT_SCHED_PRIV(thread).high_mask = 1L << (RT_SCHED_PRIV(thread).current_priority & 0x07); /* 3bit */
  1035. #else
  1036. RT_SCHED_PRIV(thread).number_mask = 1L << RT_SCHED_PRIV(thread).current_priority;
  1037. #endif /* RT_THREAD_PRIORITY_MAX > 32 */
  1038. /* change thread stat, so we can resume it */
  1039. RT_SCHED_CTX(thread).stat = RT_THREAD_SUSPEND;
  1040. }
  1041. /**
  1042. * @brief Update thread scheduling status after context switch
  1043. *
  1044. * @param thread The thread that will be running after the context switch
  1045. *
  1046. * @details This function performs critical post-context-switch operations:
  1047. * - Verifies interrupts are disabled (RT_ASSERT)
  1048. * - Releases scheduler lock from previous thread if exists
  1049. * - Updates current thread pointer for the CPU
  1050. * - Must be called with interrupts disabled
  1051. *
  1052. * @note this operation is taken as an atomic operation of the update of SP.
  1053. * Since the local irq is disabled, it's okay to assume that the stack
  1054. * will not be modified meanwhile.
  1055. *
  1056. * @note This function only has MP version.
  1057. */
  1058. void rt_sched_post_ctx_switch(struct rt_thread *thread)
  1059. {
  1060. struct rt_cpu* pcpu = rt_cpu_self();
  1061. rt_thread_t from_thread = pcpu->current_thread;
  1062. RT_ASSERT(rt_hw_interrupt_is_disabled());
  1063. if (from_thread)
  1064. {
  1065. RT_ASSERT(RT_SCHED_CTX(from_thread).critical_lock_nest == 1);
  1066. /* release the scheduler lock since we are done with critical region */
  1067. RT_SCHED_CTX(from_thread).critical_lock_nest = 0;
  1068. SCHEDULER_CONTEXT_UNLOCK(pcpu);
  1069. }
  1070. /* safe to access since irq is masked out */
  1071. pcpu->current_thread = thread;
  1072. }
  1073. #ifdef RT_DEBUGING_CRITICAL
  1074. static volatile int _critical_error_occurred = 0;
  1075. /**
  1076. * @brief Safely exit critical section with level checking
  1077. *
  1078. * @param critical_level The expected critical level to match
  1079. *
  1080. * @details This function provides a safe way to exit critical sections by:
  1081. * - Verifying the current critical level matches the expected level
  1082. * - If mismatch detected (debug build only):
  1083. * * Prints error message with current and expected levels
  1084. * * Triggers backtrace for debugging
  1085. * * Enters infinite loop to halt execution
  1086. * - Always calls rt_exit_critical() to ensure critical section is exited
  1087. *
  1088. * @note This is primarily used for debugging critical section mismatches.
  1089. *
  1090. * @note This function has both MP version and UP version.
  1091. */
  1092. void rt_exit_critical_safe(rt_base_t critical_level)
  1093. {
  1094. struct rt_cpu *pcpu = rt_cpu_self();
  1095. rt_thread_t current_thread = pcpu->current_thread;
  1096. if (current_thread && !_critical_error_occurred)
  1097. {
  1098. if (critical_level != RT_SCHED_CTX(current_thread).critical_lock_nest)
  1099. {
  1100. int dummy = 1;
  1101. _critical_error_occurred = 1;
  1102. rt_kprintf("%s: un-compatible critical level\n" \
  1103. "\tCurrent %d\n\tCaller %d\n",
  1104. __func__, RT_SCHED_CTX(current_thread).critical_lock_nest,
  1105. critical_level);
  1106. rt_backtrace();
  1107. while (dummy) ;
  1108. }
  1109. }
  1110. rt_exit_critical();
  1111. }
  1112. #else /* !RT_DEBUGING_CRITICAL */
  1113. /**
  1114. * @brief Safely exit critical section (non-debug version)
  1115. *
  1116. * @param critical_level The expected critical level (unused in non-debug build)
  1117. *
  1118. * @details This is the non-debug version that simply calls rt_exit_critical().
  1119. * The critical_level parameter is ignored in this implementation.
  1120. *
  1121. * @note This function has both MP version and UP version.
  1122. */
  1123. void rt_exit_critical_safe(rt_base_t critical_level)
  1124. {
  1125. RT_UNUSED(critical_level);
  1126. return rt_exit_critical();
  1127. }
  1128. #endif /* RT_DEBUGING_CRITICAL */
  1129. RTM_EXPORT(rt_exit_critical_safe);
  1130. #ifdef ARCH_USING_HW_THREAD_SELF
  1131. #define FREE_THREAD_SELF(lvl)
  1132. #else /* !ARCH_USING_HW_THREAD_SELF */
  1133. #define FREE_THREAD_SELF(lvl) \
  1134. do \
  1135. { \
  1136. rt_hw_local_irq_enable(lvl); \
  1137. } while (0)
  1138. #endif /* ARCH_USING_HW_THREAD_SELF */
  1139. /**
  1140. * @brief Enter a critical section and lock the scheduler
  1141. *
  1142. * @return The critical level after entering (nesting count)
  1143. * Returns -RT_EINVAL if scheduler is unavailable
  1144. *
  1145. * @details This function:
  1146. * - Disables interrupts to ensure atomic operation
  1147. * - Gets current thread context
  1148. * - Increments critical section nesting counter
  1149. * - Returns the new nesting level
  1150. * - Handles both hardware-assisted and software thread context cases
  1151. *
  1152. * @note Must be paired with rt_exit_critical()
  1153. * Can be nested, each call must have matching exit call
  1154. *
  1155. * @note This function has both MP version and UP version.
  1156. */
  1157. rt_base_t rt_enter_critical(void)
  1158. {
  1159. rt_base_t critical_level;
  1160. struct rt_thread *current_thread;
  1161. #ifndef ARCH_USING_HW_THREAD_SELF
  1162. rt_base_t level;
  1163. struct rt_cpu *pcpu;
  1164. /* disable interrupt */
  1165. level = rt_hw_local_irq_disable();
  1166. pcpu = rt_cpu_self();
  1167. current_thread = pcpu->current_thread;
  1168. #else /* !ARCH_USING_HW_THREAD_SELF */
  1169. current_thread = rt_hw_thread_self();
  1170. #endif /* ARCH_USING_HW_THREAD_SELF */
  1171. if (!current_thread)
  1172. {
  1173. FREE_THREAD_SELF(level);
  1174. /* scheduler unavailable */
  1175. return -RT_EINVAL;
  1176. }
  1177. /* critical for local cpu */
  1178. RT_SCHED_CTX(current_thread).critical_lock_nest++;
  1179. critical_level = RT_SCHED_CTX(current_thread).critical_lock_nest;
  1180. FREE_THREAD_SELF(level);
  1181. return critical_level;
  1182. }
  1183. RTM_EXPORT(rt_enter_critical);
  1184. /**
  1185. * @brief Exit a critical section and unlock the scheduler
  1186. *
  1187. * @details This function performs the following operations:
  1188. * - Gets current thread context (using hardware-assisted or software method)
  1189. * - Decrements critical section nesting counter
  1190. * - If nesting level reaches 0:
  1191. * * Checks if rescheduling is needed
  1192. * * Clears critical switch flag
  1193. * * Performs rescheduling if needed
  1194. * - Verifies critical section nesting is valid (debug assertion)
  1195. * - Restores interrupt state
  1196. *
  1197. * @note Must be called in pair with rt_enter_critical()
  1198. * Handles both hardware-assisted and software thread context cases
  1199. * May trigger rescheduling if conditions met
  1200. *
  1201. * @note This function has both MP version and UP version.
  1202. */
  1203. void rt_exit_critical(void)
  1204. {
  1205. struct rt_thread *current_thread;
  1206. rt_bool_t need_resched;
  1207. #ifndef ARCH_USING_HW_THREAD_SELF
  1208. rt_base_t level;
  1209. struct rt_cpu *pcpu;
  1210. /* disable interrupt */
  1211. level = rt_hw_local_irq_disable();
  1212. pcpu = rt_cpu_self();
  1213. current_thread = pcpu->current_thread;
  1214. #else /* !ARCH_USING_HW_THREAD_SELF */
  1215. current_thread = rt_hw_thread_self();
  1216. #endif /* ARCH_USING_HW_THREAD_SELF */
  1217. if (!current_thread)
  1218. {
  1219. FREE_THREAD_SELF(level);
  1220. return;
  1221. }
  1222. /* the necessary memory barrier is done on irq_(dis|en)able */
  1223. RT_SCHED_CTX(current_thread).critical_lock_nest--;
  1224. /* may need a rescheduling */
  1225. if (RT_SCHED_CTX(current_thread).critical_lock_nest == 0)
  1226. {
  1227. /* is there any scheduling request unfinished? */
  1228. need_resched = IS_CRITICAL_SWITCH_PEND(pcpu, current_thread);
  1229. CLR_CRITICAL_SWITCH_FLAG(pcpu, current_thread);
  1230. FREE_THREAD_SELF(level);
  1231. if (need_resched)
  1232. rt_schedule();
  1233. }
  1234. else
  1235. {
  1236. /* each exit_critical is strictly corresponding to an enter_critical */
  1237. RT_ASSERT(RT_SCHED_CTX(current_thread).critical_lock_nest > 0);
  1238. FREE_THREAD_SELF(level);
  1239. }
  1240. }
  1241. RTM_EXPORT(rt_exit_critical);
  1242. /**
  1243. * @brief Get the scheduler lock level.
  1244. *
  1245. * @return The level of the scheduler lock. 0 means unlocked.
  1246. *
  1247. * @note This function has both MP version and UP version.
  1248. */
  1249. rt_uint16_t rt_critical_level(void)
  1250. {
  1251. rt_base_t level;
  1252. rt_uint16_t critical_lvl;
  1253. struct rt_thread *current_thread;
  1254. level = rt_hw_local_irq_disable();
  1255. current_thread = rt_cpu_self()->current_thread;
  1256. if (current_thread)
  1257. {
  1258. /* the necessary memory barrier is done on irq_(dis|en)able */
  1259. critical_lvl = RT_SCHED_CTX(current_thread).critical_lock_nest;
  1260. }
  1261. else
  1262. {
  1263. critical_lvl = 0;
  1264. }
  1265. rt_hw_local_irq_enable(level);
  1266. return critical_lvl;
  1267. }
  1268. RTM_EXPORT(rt_critical_level);
  1269. /**
  1270. * @brief Bind a thread to a specific CPU core
  1271. *
  1272. * @param thread The thread to be bound
  1273. * @param cpu The target CPU core index (RT_CPUS_NR for no binding)
  1274. *
  1275. * @return rt_err_t
  1276. * - RT_EOK: Operation successful
  1277. *
  1278. * @details This function handles thread-CPU binding with the following logic:
  1279. * - If thread is READY:
  1280. * * Removes from current ready queue
  1281. * * Updates bind CPU information
  1282. * * Inserts to new ready queue
  1283. * * Triggers rescheduling if needed
  1284. * - If thread is RUNNING:
  1285. * * Updates bind CPU information
  1286. * * Sends IPI to target CPU if binding changed
  1287. * * Triggers rescheduling if needed
  1288. * - For other states, just updates bind CPU info
  1289. *
  1290. * @note Caller must ensure scheduler is not locked before calling
  1291. * This function will acquire scheduler lock internally
  1292. *
  1293. * @note This function has both MP version and UP version, but UP version does
  1294. * nothing and always returns -RT_EINVAL.
  1295. */
  1296. rt_err_t rt_sched_thread_bind_cpu(struct rt_thread *thread, int cpu)
  1297. {
  1298. rt_sched_lock_level_t slvl;
  1299. rt_uint8_t thread_stat;
  1300. RT_SCHED_DEBUG_IS_UNLOCKED;
  1301. if (cpu >= RT_CPUS_NR)
  1302. {
  1303. cpu = RT_CPUS_NR;
  1304. }
  1305. rt_sched_lock(&slvl);
  1306. thread_stat = rt_sched_thread_get_stat(thread);
  1307. if (thread_stat == RT_THREAD_READY)
  1308. {
  1309. /* unbind */
  1310. /* remove from old ready queue */
  1311. rt_sched_remove_thread(thread);
  1312. /* change thread bind cpu */
  1313. RT_SCHED_CTX(thread).bind_cpu = cpu;
  1314. /* add to new ready queue */
  1315. rt_sched_insert_thread(thread);
  1316. if (rt_thread_self() != RT_NULL)
  1317. {
  1318. rt_sched_unlock_n_resched(slvl);
  1319. }
  1320. else
  1321. {
  1322. rt_sched_unlock(slvl);
  1323. }
  1324. }
  1325. else
  1326. {
  1327. RT_SCHED_CTX(thread).bind_cpu = cpu;
  1328. if (thread_stat == RT_THREAD_RUNNING)
  1329. {
  1330. /* thread is running on a cpu */
  1331. int current_cpu = rt_hw_cpu_id();
  1332. if (cpu != RT_CPUS_NR)
  1333. {
  1334. if (RT_SCHED_CTX(thread).oncpu == current_cpu)
  1335. {
  1336. /* current thread on current cpu */
  1337. if (cpu != current_cpu)
  1338. {
  1339. /* bind to other cpu */
  1340. rt_hw_ipi_send(RT_SCHEDULE_IPI, 1U << cpu);
  1341. /* self cpu need reschedule */
  1342. rt_sched_unlock_n_resched(slvl);
  1343. }
  1344. else
  1345. {
  1346. /* else do nothing */
  1347. rt_sched_unlock(slvl);
  1348. }
  1349. }
  1350. else
  1351. {
  1352. /* no running on self cpu, but dest cpu can be itself */
  1353. rt_hw_ipi_send(RT_SCHEDULE_IPI, 1U << RT_SCHED_CTX(thread).oncpu);
  1354. rt_sched_unlock(slvl);
  1355. }
  1356. }
  1357. else
  1358. {
  1359. /* else do nothing */
  1360. rt_sched_unlock(slvl);
  1361. }
  1362. }
  1363. else
  1364. {
  1365. rt_sched_unlock(slvl);
  1366. }
  1367. }
  1368. return RT_EOK;
  1369. }
  1370. /**
  1371. * @} group_thread_management
  1372. *
  1373. * @endcond
  1374. */