1use core::cell::UnsafeCell;
16use core::mem::MaybeUninit;
17use core::ptr::NonNull;
18use core::sync::atomic::Ordering;
19
20use exit_status::ExitStatus;
21#[cfg(not(feature = "user_space"))]
22use foreign_box::ForeignBox;
23#[cfg(feature = "user_space")]
24use foreign_box::{ForeignBox, ForeignRc};
25use list::*;
26use pw_atomic::{AtomicAdd, AtomicSub, AtomicZero};
27use pw_log::info;
28use pw_status::Result;
29use pw_time_core::Instant;
30
31use crate::Kernel;
32#[cfg(feature = "user_space")]
33use crate::object::KernelObject;
34use crate::scheduler::affinity::AffinityMask;
35#[cfg(feature = "smp")]
36use crate::scheduler::affinity::CoreId;
37use crate::scheduler::algorithm::SchedulerAlgorithmThreadState;
38use crate::scheduler::process::ProcessHandle;
39use crate::scheduler::{JoinResult, Priority, SchedulerState, TryJoinResult, WaitQueue, WaitType};
40use crate::sync::event::{Event, EventConfig, EventSignaler};
41use crate::sync::spinlock::SpinLockGuard;
42
43#[repr(align(8))]
63pub struct StackStorage<const N: usize> {
64 pub stack: [MaybeUninit<u8>; N],
65}
66
67pub trait StackStorageExt {
68 const ZEROED: Self;
69}
70
71impl<const N: usize> StackStorageExt for StackStorage<N> {
72 const ZEROED: StackStorage<N> = StackStorage {
73 stack: [MaybeUninit::new(0); N],
74 };
75}
76
77#[derive(Clone, Copy)]
78pub struct Stack {
79 start: *const MaybeUninit<u8>,
81
82 end: *const MaybeUninit<u8>,
84}
85
86#[allow(dead_code)]
87impl Stack {
88 #[must_use]
89 pub const fn from_slice(slice: &[MaybeUninit<u8>]) -> Self {
90 let start: *const MaybeUninit<u8> = slice.as_ptr();
91 let end = unsafe { start.add(slice.len()) };
93 Self { start, end }
94 }
95
96 #[must_use]
97 pub const fn new() -> Self {
98 Self {
99 start: core::ptr::null(),
100 end: core::ptr::null(),
101 }
102 }
103
104 #[must_use]
105 pub fn start(&self) -> *const MaybeUninit<u8> {
106 self.start
107 }
108
109 #[must_use]
110 pub fn end(&self) -> *const MaybeUninit<u8> {
111 self.end
112 }
113
114 #[must_use]
117 pub unsafe fn end_mut(&self) -> *mut MaybeUninit<u8> {
118 self.end as *mut MaybeUninit<u8>
119 }
120
121 #[must_use]
122 pub fn contains(&self, ptr: *const MaybeUninit<u8>) -> bool {
123 ptr >= self.start && ptr < self.end
124 }
125
126 #[must_use]
127 pub fn aligned_stack_allocation_mut<T: Sized>(
128 sp: *mut MaybeUninit<u8>,
129 alignment: usize,
130 ) -> *mut T {
131 let sp = sp.wrapping_byte_sub(size_of::<T>());
132 let offset = sp.align_offset(alignment);
133 if offset > 0 {
134 sp.wrapping_byte_sub(alignment - offset).cast()
135 } else {
136 sp.cast()
137 }
138 }
139
140 pub fn aligned_stack_allocation<T: Sized>(
141 sp: *mut MaybeUninit<u8>,
142 alignment: usize,
143 ) -> *const T {
144 Self::aligned_stack_allocation_mut::<*mut T>(sp, alignment).cast()
145 }
146
147 pub fn initialize(&self) {
153 let mut ptr = self.start as *mut u32;
154 let end = self.end as *mut u32;
155
156 pw_assert::assert!(ptr.is_aligned(), "Stack start is not aligned");
157 pw_assert::assert!(end.is_aligned(), "Stack end is not aligned");
158
159 while ptr < end {
160 unsafe {
164 ptr.write_volatile(magic_values::UNUSED_STACK_PATTERN);
165 ptr = ptr.add(1);
166 }
167 }
168 }
169}
170
171#[derive(Copy, Clone, PartialEq)]
174#[repr(u8)]
175pub enum State {
176 New = 0,
178
179 Initial = 1,
182
183 Ready = 2,
185
186 Running = 3,
188
189 Terminated = 4,
191
192 Joined = 5,
195
196 WaitingInterruptible = 6,
198
199 WaitingNonInterruptible = 7,
201}
202
203impl State {
204 #[must_use]
205 pub fn is_waiting(&self) -> bool {
206 matches!(
207 self,
208 Self::WaitingInterruptible | Self::WaitingNonInterruptible
209 )
210 }
211}
212
213pub(super) fn to_string(s: State) -> &'static str {
215 match s {
216 State::New => "New",
217 State::Initial => "Initial",
218 State::Ready => "Ready",
219 State::Running => "Running",
220 State::Terminated => "Terminated",
221 State::Joined => "Joined",
222 State::WaitingInterruptible => "WaitingInterruptible",
223 State::WaitingNonInterruptible => "WaitingNonInterruptible",
224 }
225}
226
227pub trait ThreadState: 'static + Sized {
228 const NEW: Self;
229
230 type MemoryConfig: memory_config::MemoryConfig;
232
233 unsafe fn initialize_kernel_state(
249 &mut self,
250 kernel_stack: Stack,
251 memory_config: *const Self::MemoryConfig,
252 initial_function: extern "C" fn(usize, usize, usize),
253 args: (usize, usize, usize),
254 );
255
256 #[cfg(feature = "user_space")]
272 unsafe fn initialize_user_state(
273 &mut self,
274 kernel_stack: Stack,
275 memory_config: *const Self::MemoryConfig,
276 initial_sp: usize,
277 initial_pc: usize,
278 args: (usize, usize, usize),
279 ) -> Result<()>;
280}
281
282pub enum ThreadOwner<K: Kernel> {
283 None,
284 Scheduler,
285 WakeList,
286 WaitQueue {
287 queue: NonNull<WaitQueue<K>>,
288 wait_type: WaitType,
289 },
290}
291
292pub struct ThreadHandle<K: Kernel> {
297 pub(crate) thread: NonNull<Thread<K>>,
298 kernel: K,
299}
300
301unsafe impl<K: Kernel> Send for ThreadHandle<K> {}
304unsafe impl<K: Kernel> Sync for ThreadHandle<K> {}
305
306impl<K: Kernel> ThreadHandle<K> {
307 pub fn join(self, kernel: K) -> Result<(ForeignBox<Thread<K>>, ExitStatus)> {
313 match self.join_until(kernel, Instant::<K::Clock>::MAX) {
314 JoinResult::Joined(thread, status) => Ok((thread, status)),
315 JoinResult::Err { error, .. } => Err(error),
316 }
317 }
318
319 pub fn try_join(self, kernel: K) -> crate::scheduler::TryJoinResult<K> {
320 let sched = kernel.get_scheduler().lock(kernel);
321 let (_sched, res) = self.try_join_locked(kernel, sched);
322 res
323 }
324
325 pub fn try_join_locked<'a>(
326 self,
327 kernel: K,
328 sched: SpinLockGuard<'a, K, SchedulerState<K>>,
329 ) -> (
330 SpinLockGuard<'a, K, SchedulerState<K>>,
331 crate::scheduler::TryJoinResult<K>,
332 ) {
333 sched.thread_try_join(kernel, self, None)
334 }
335
336 pub fn join_until(mut self, kernel: K, deadline: Instant<K::Clock>) -> JoinResult<K> {
346 let join_event = Event::new(kernel, EventConfig::ManualReset);
347 loop {
348 let (_, res) = kernel.get_scheduler().lock(kernel).thread_try_join(
349 kernel,
350 self,
351 Some(join_event.get_signaler()),
352 );
353 match res {
354 TryJoinResult::Err {
355 error: e,
356 thread: thread_handle,
357 } => {
358 return JoinResult::Err {
359 error: e,
360 thread: thread_handle,
361 };
362 }
363 TryJoinResult::Joined(thread_box, status) => {
364 return JoinResult::Joined(thread_box, status);
365 }
366 TryJoinResult::Wait(thread_handle) => self = thread_handle,
367 };
368
369 if let Err(e) = join_event.wait_until(deadline) {
370 kernel
371 .get_scheduler()
372 .lock(kernel)
373 .thread_cancel_try_join(&mut self);
374
375 return JoinResult::Err {
376 error: e,
377 thread: self,
378 };
379 }
380 }
381 }
382
383 pub fn terminate(&mut self, kernel: K, status: ExitStatus) -> Result<()> {
398 kernel
399 .get_scheduler()
400 .lock(kernel)
401 .thread_terminate(self, status)
402 }
403
404 pub fn get_state(&self, kernel: K) -> State {
406 kernel.get_scheduler().lock(kernel).thread_get_state(self)
407 }
408
409 pub fn is_terminating(&self, kernel: K) -> bool {
413 kernel
414 .get_scheduler()
415 .lock(kernel)
416 .thread_is_terminating(self)
417 }
418}
419
420impl<K: Kernel> Clone for ThreadHandle<K> {
421 fn clone(&self) -> Self {
422 unsafe {
423 self.thread
424 .as_ref()
425 .ref_count
426 .fetch_add(1, Ordering::Acquire);
427 }
428
429 Self {
430 thread: self.thread,
431 kernel: self.kernel,
432 }
433 }
434}
435
436impl<K: Kernel> Drop for ThreadHandle<K> {
437 fn drop(&mut self) {
438 unsafe {
439 let prev_value = self
440 .thread
441 .as_ref()
442 .ref_count
443 .fetch_sub(1, Ordering::Release);
444
445 if prev_value == 2 {
449 self.kernel
450 .get_scheduler()
451 .lock(self.kernel)
452 .thread_signal_join(self.kernel, self);
453 }
454 };
455 }
456}
457
458pub struct Thread<K: Kernel> {
459 pub process_link: Link,
461
462 pub active_link: Link,
464
465 process: Option<ProcessHandle<K>>,
466
467 pub(super) state: State,
468 pub(super) stack: Stack,
469
470 pub arch_thread_state: UnsafeCell<K::ThreadState>,
472
473 pub(super) owner: ThreadOwner<K>,
474 pub(super) ref_count: K::AtomicUsize,
475 pub(super) terminating: bool,
476 pub(super) join_event: Option<EventSignaler<K>>,
477 pub(super) exit_status: Option<ExitStatus>,
478
479 pub name: &'static str,
481
482 pub algorithm_state: SchedulerAlgorithmThreadState,
484
485 #[cfg(feature = "smp")]
487 pub(super) affinity: AffinityMask,
488
489 #[cfg(feature = "smp")]
491 pub(super) last_core: Option<CoreId>,
492
493 #[cfg(feature = "user_space")]
494 pub object: Option<foreign_box::ForeignRc<K::AtomicUsize, crate::object::ThreadObject<K>>>,
495}
496
497unsafe impl<K: Kernel> Send for Thread<K> {}
499unsafe impl<K: Kernel> Sync for Thread<K> {}
500
501list::define_adapter!(pub ThreadListAdapter<K: Kernel> => Thread<K>::active_link);
502
503impl<K: Kernel> Thread<K> {
504 pub(super) fn take_process(&mut self) -> ProcessHandle<K> {
505 let Some(process) = self.process.take() else {
506 pw_assert::panic!("Thread does not have a process");
507 };
508 process
509 }
510
511 pub fn get_exit_status(&self) -> Option<ExitStatus> {
512 self.exit_status
513 }
514
515 pub fn is_terminating(&self) -> bool {
516 self.terminating
517 }
518
519 pub fn set_stack(&mut self, stack: Stack) {
520 pw_assert::assert!(matches!(self.state, State::New | State::Joined));
521 self.stack = stack;
522 }
523
524 #[cfg(not(feature = "smp"))]
526 #[inline]
527 pub fn set_affinity(&mut self, _affinity: AffinityMask) {}
528
529 #[cfg(feature = "smp")]
531 #[inline]
532 pub fn set_affinity(&mut self, affinity: AffinityMask) {
533 self.affinity = affinity;
534
535 self.last_core = None;
537 }
538
539 #[must_use]
541 pub const fn new(name: &'static str, priority: Priority, stack: Stack) -> Self {
542 Thread {
543 process_link: Link::new(),
544 active_link: Link::new(),
545 process: None,
546 state: State::New,
547 arch_thread_state: UnsafeCell::new(K::ThreadState::NEW),
548 owner: ThreadOwner::None,
549 stack,
550 ref_count: K::AtomicUsize::ZERO,
551 terminating: false,
552 join_event: None,
553 exit_status: None,
554 name,
555 algorithm_state: SchedulerAlgorithmThreadState::new(priority),
556 #[cfg(feature = "smp")]
557 affinity: AffinityMask::all(),
558 #[cfg(feature = "smp")]
559 last_core: None,
560 #[cfg(feature = "user_space")]
561 object: None,
562 }
563 }
564
565 #[cfg(feature = "user_space")]
566 pub fn get_object(
567 &self,
568 kernel: K,
569 handle: u32,
570 ) -> Option<ForeignRc<K::AtomicUsize, dyn KernelObject<K>>> {
571 unsafe {
573 self.process
574 .as_ref()?
575 .process
576 .as_ref()
577 .get_object(kernel, handle)
578 }
579 }
580
581 pub(super) extern "C" fn trampoline<A1: ThreadArg>(
582 entry_point: usize,
583 arg0: usize,
584 arg1: usize,
585 ) {
586 let entry_point = core::ptr::with_exposed_provenance::<()>(entry_point);
587 let entry_point: fn(K, A1) = unsafe { core::mem::transmute(entry_point) };
595 let kernel = unsafe { K::from_usize(arg0) };
596 let arg1 = unsafe { A1::from_usize(arg1) };
597 entry_point(kernel, arg1);
598 }
599
600 pub fn re_initialize_kernel_thread<A: ThreadArg>(
601 &mut self,
602 kernel: K,
603 entry_point: fn(K, A),
604 arg: A,
605 ) {
606 kernel
607 .get_scheduler()
608 .lock(kernel)
609 .thread_reinitialize_kernel(kernel, self, entry_point, arg)
610 }
611
612 pub fn initialize_kernel_thread<A: ThreadArg>(
613 &mut self,
614 kernel: K,
615 entry_point: fn(K, A),
616 arg: A,
617 ) {
618 kernel
619 .get_scheduler()
620 .lock(kernel)
621 .thread_initialize_kernel(kernel, self, entry_point, arg)
622 }
623
624 pub(super) fn set_process(&mut self, process: ProcessHandle<K>) {
625 self.process = Some(process);
626 }
627
628 #[cfg(feature = "user_space")]
629 pub unsafe fn initialize_non_priv_thread(
634 &mut self,
635 kernel: K,
636 process: ProcessHandle<K>,
637 initial_pc: usize,
638 initial_sp: usize,
639 args: (usize, usize, usize),
640 ) -> Result<()> {
641 unsafe {
642 kernel
643 .get_scheduler()
644 .lock(kernel)
645 .thread_initialize_non_priv(kernel, self, process, initial_pc, initial_sp, args)
646 }
647 }
648
649 #[allow(dead_code)]
650 pub fn dump(&self) {
651 info!(
652 " - Thread '{}' ({:#010x}) state: {}",
653 self.name as &str,
654 self.id() as usize,
655 to_string(self.state) as &str
656 );
657 }
658
659 pub fn process(&self) -> ProcessHandle<K> {
661 let Some(process_handle) = self.process.as_ref() else {
664 pw_assert::panic!("Thread does not have a process");
665 };
666 process_handle.clone()
667 }
668
669 pub(super) fn get_ref(&self, kernel: K) -> ThreadHandle<K> {
671 self.ref_count.fetch_add(1, Ordering::Acquire);
672 ThreadHandle {
673 thread: NonNull::from_ref(self),
674 kernel,
675 }
676 }
677
678 #[must_use]
689 pub fn id(&self) -> usize {
690 self.arch_thread_state.get().addr()
693 }
694
695 #[must_use]
703 pub const unsafe fn const_id_from_thread_address(addr: *const ()) -> *const () {
704 unsafe { addr.byte_add(core::mem::offset_of!(Self, arch_thread_state)) }
705 }
706
707 #[must_use]
709 pub const fn null_id() -> usize {
710 0usize
714 }
715}
716
717pub use arg::ThreadArg;
718mod arg {
719 pub trait ThreadArg {
720 fn into_usize(self) -> usize;
721
722 unsafe fn from_usize(u: usize) -> Self;
729 }
730
731 impl ThreadArg for usize {
732 fn into_usize(self) -> usize {
733 self
734 }
735
736 unsafe fn from_usize(u: usize) -> Self {
737 u
738 }
739 }
740
741 impl<T> ThreadArg for *const T {
742 fn into_usize(self) -> usize {
743 self.expose_provenance()
744 }
745
746 unsafe fn from_usize(u: usize) -> Self {
747 core::ptr::with_exposed_provenance(u)
748 }
749 }
750
751 impl<T> ThreadArg for *mut T {
752 fn into_usize(self) -> usize {
753 self.expose_provenance()
754 }
755
756 unsafe fn from_usize(u: usize) -> Self {
757 core::ptr::with_exposed_provenance_mut(u)
758 }
759 }
760
761 #[allow(clippy::needless_lifetimes)]
762 impl<'a, T> ThreadArg for &'a T {
763 fn into_usize(self) -> usize {
764 let s: *const T = self;
765 s.into_usize()
766 }
767
768 unsafe fn from_usize(u: usize) -> Self {
769 let ptr = unsafe { <*const T>::from_usize(u) };
774 unsafe { &*ptr }
777 }
778 }
779
780 #[allow(clippy::needless_lifetimes)]
781 impl<'a, T> ThreadArg for &'a mut T {
782 fn into_usize(self) -> usize {
783 let s: *mut T = self;
784 s.into_usize()
785 }
786
787 unsafe fn from_usize(u: usize) -> Self {
788 let ptr = unsafe { <*mut T>::from_usize(u) };
793 unsafe { &mut *ptr }
798 }
799 }
800
801 #[macro_export]
802 macro_rules! impl_thread_arg_for_default_zst {
803 ($t:ty) => {
804 const _: () = assert!(size_of::<$t>() == 0);
805 impl $crate::scheduler::ThreadArg for $t {
806 fn into_usize(self) -> usize {
807 0
808 }
809
810 unsafe fn from_usize(_u: usize) -> Self {
811 <$t as Default>::default()
817 }
818 }
819 };
820 }
821}
822
823#[macro_export]
828macro_rules! annotate_thread_from_address {
829 ($name:expr, $arch:ty, $thread_address:expr, $parent_id: expr) => {{
830 #[repr(C, packed(1))]
831 struct ThreadAnnotation {
832 name: &'static str,
833 id: *const (),
834 parent_id: *const (),
835 }
836 unsafe impl Sync for ThreadAnnotation {};
837
838 #[unsafe(link_section = ".pw_kernel.annotations.thread")]
839 #[used]
840 static _THREAD_ANNOTATION: ThreadAnnotation = ThreadAnnotation {
841 name: $name,
842 id: unsafe {
843 $crate::Thread::<$arch>::const_id_from_thread_address($thread_address as *const ())
844 },
845 parent_id: $parent_id as *const (),
846 };
847 }};
848}
849
850#[macro_export]
854macro_rules! annotate_stack {
855 ($name:expr, $addr:expr, $size:expr) => {{
856 #[repr(C, packed(1))]
857 struct StackAnnotation {
858 name: &'static str,
859 addr: *const (),
860 size: usize,
861 }
862 unsafe impl Sync for StackAnnotation {};
863
864 #[unsafe(link_section = ".pw_kernel.annotations.stack")]
865 #[used]
866 static _STACK_ANNOTATION: StackAnnotation = StackAnnotation {
867 name: $name,
868 addr: $addr as *const (),
869 size: $size,
870 };
871 }};
872}
873
874#[macro_export]
878macro_rules! static_stack {
879 ($thread_name:expr, $stack_size:expr) => {{
880 use core::cell::UnsafeCell;
881 use core::mem::MaybeUninit;
882
883 use kernel::{StackStorage, StackStorageExt};
884
885 static mut __STATIC: UnsafeCell<MaybeUninit<StackStorage<$stack_size>>> =
886 UnsafeCell::new(core::mem::MaybeUninit::uninit());
887 $crate::annotate_stack!($thread_name, unsafe { __STATIC.get() }, $stack_size);
888
889 unsafe { (*__STATIC.get()).write(StackStorageExt::ZEROED) }
890 }};
891}
892
893#[macro_export]
902macro_rules! init_thread {
903 ($name:literal, $priority:expr, $entry:expr, $stack_size:expr $(,)?) => {{
904 use $crate::__private::foreign_box::ForeignBox;
905 use $crate::scheduler::{Stack, StackStorage, StackStorageExt, Thread};
906 use $crate::static_mut_ref;
907
908 unsafe fn __init_thread() -> ForeignBox<Thread<arch::Arch>> {
910 info!("Initializing thread '{}'", $name as &'static str);
911 let stack = $crate::static_stack!($name, $stack_size);
912 let stack = Stack::from_slice(&stack.stack);
915
916 let thread = unsafe { static_mut_ref!(Thread<arch::Arch> = Thread::new($name, $priority, stack)) };
917 let mut thread = ForeignBox::from(thread);
918
919 thread.initialize_kernel_thread(
920 $crate::arch::Arch,
921 $entry,
922 0
923 );
924
925 thread
926 }
927
928 __init_thread()
929 }};
930}
931
932#[cfg(feature = "user_space")]
939#[macro_export]
940macro_rules! declare_non_priv_thread {
941 ($name:literal, $priority:expr, $process_id:expr, $kernel_stack_size:expr $(,)?) => {{
942 use core::mem::MaybeUninit;
943
944 use $crate::__private::foreign_box::ForeignBox;
945 use $crate::scheduler::{Stack, StackStorage, StackStorageExt, Thread};
946
947 unsafe fn __init_non_priv_thread() -> (ForeignBox<Thread<arch::Arch>>, Stack) {
949 use pw_log::info;
950 info!(
951 "Allocating non-privileged thread '{}'",
952 $name as &'static str
953 );
954 use $crate::__private::foreign_box::StaticStorage;
957 static mut __STATIC: StaticStorage<Thread<arch::Arch>> = StaticStorage::new();
958 $crate::annotate_thread_from_address!(
959 $name,
960 arch::Arch,
961 unsafe { __STATIC.address() },
962 $process_id
963 );
964 let stack = $crate::static_stack!($name, $kernel_stack_size);
965 let stack = Stack::from_slice(&stack.stack);
968
969 let thread = __STATIC.init(Thread::new($name, $priority, stack));
970 let mut thread = ForeignBox::from(thread);
971
972 (thread, stack)
973 }
974
975 __init_non_priv_thread()
976 }};
977}
978
979pub fn init_thread_in<K: Kernel, T: ThreadArg, const STACK_SIZE: usize>(
981 kernel: K,
982 thread: &'static mut Thread<K>,
983 stack: &'static mut StackStorage<STACK_SIZE>,
984 name: &'static str,
985 priority: Priority,
986 entry: fn(K, T),
987 arg: T,
988) -> ForeignBox<Thread<K>> {
989 let stack_obj = Stack::from_slice(&stack.stack);
990 *thread = Thread::new(name, priority, stack_obj);
991 let mut thread = ForeignBox::from(thread);
992 thread.initialize_kernel_thread(kernel, entry, arg);
993 thread
994}