Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/scheduler/thread.rs

kernel/scheduler/
thread.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use 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/// The memory backing a thread's stack before it has been started.
44///
45/// Stacks are aligned to 8 bytes for broad ABI compatibility.
46///
47/// After a thread has been started, ownership of its stack's memory is (from
48/// the Rust Abstract Machine (AM) perspective) relinquished, and so the type we
49/// use to represent that memory is irrelevant.
50///
51/// However, while we are initializing a thread in preparation for starting it,
52/// we are operating on that memory as a normal Rust variable, and so its type
53/// is important.
54///
55/// Using `MaybeUninit<u8>` instead of `u8` is important for two reasons:
56/// - It ensures that it is sound to write values which are not entirely
57///   initialized (e.g., which contain padding bytes).
58/// - It ensures that pointers written to the stack [retain
59///   provenance][provenance].
60///
61/// [provenance]: https://github.com/rust-lang/unsafe-code-guidelines/issues/286#issuecomment-2837585644
62#[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    // Starting (lowest) address of the stack.  Inclusive.
80    start: *const MaybeUninit<u8>,
81
82    // Ending (highest) address of the stack.  Exclusive.
83    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        // Safety: offset based on known size of slice.
92        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    /// # Safety
115    /// Caller must ensure exclusive mutable access to underlying data
116    #[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    /// Initialize the stack for thread execution.
148    ///
149    /// Initializes the stack to a known pattern to avoid leaking data between
150    /// thread invocations as well as to provide a signature for calculating
151    /// high water stack usage.
152    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            // SAFETY: `ptr` is always aligned to 4 bytes and is contained within
161            // the specified stack memory region.  Additionally, only writes
162            // are performed for the MaybeUninit constraint is not violated.
163            unsafe {
164                ptr.write_volatile(magic_values::UNUSED_STACK_PATTERN);
165                ptr = ptr.add(1);
166            }
167        }
168    }
169}
170
171/// Runtime state of a Thread.
172// TODO: want to name this ThreadState, but collides with ArchThreadstate
173#[derive(Copy, Clone, PartialEq)]
174#[repr(u8)]
175pub enum State {
176    /// Thread has been created but not initialized.
177    New = 0,
178
179    /// Thread has been initialized and added to its parent process but has not
180    /// been added to the scheduler.
181    Initial = 1,
182
183    /// Thread is ready to run and owned by the scheduling algorithm.
184    Ready = 2,
185
186    /// Thread is currently running on a CPU core.
187    Running = 3,
188
189    /// Thread has been successfully terminated and is waiting to be joined.
190    Terminated = 4,
191
192    /// Thread has been joined, removed from its parent process, and no longer
193    /// participates in the system scheduler.
194    Joined = 5,
195
196    /// Thread is interruptibly waiting in a [`WaitQueue`].
197    WaitingInterruptible = 6,
198
199    /// Thread is non-interruptibly waiting in a [`WaitQueue`].
200    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
213// TODO: use From or Into trait (unclear how to do it with 'static str)
214pub(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    // TODO: Maybe have a `MemoryConfigContext` super-trait of `ThreadState`?
231    type MemoryConfig: memory_config::MemoryConfig;
232
233    /// Initialize the default frame of a kernel thread
234    ///
235    /// Arranges for the thread to start at `initial_function` with arguments
236    /// passed in the first two argument slots.  The stack pointer of the thread
237    /// is set to the top of the kernel stack.
238    ///
239    /// # Safety
240    /// Caller guarantees that the `memory_config` pointer remains valid for the
241    /// lifetime of the thread.
242    ///
243    /// # Implementation Note
244    /// The implementation is responsible for ensuring that `initial_function`
245    /// is called with interrupts enabled and without the scheduler lock held.
246    /// This call must initialize the `ThreadLocalState` returned by
247    /// `thread_local_state()`.
248    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    /// Initialize the default frame of a user thread
257    ///
258    /// Arranges for the thread to start at `initial_function` with arguments
259    /// passed in the first two argument slots
260    ///
261    /// # Safety
262    /// Caller guarantees that the `memory_config` pointer remains valid for the
263    /// lifetime of the thread.
264    ///
265    /// # Implementation Note
266    /// The implementation is responsible for ensuring that `initial_function`
267    /// is called with interrupts enabled, memory_config enabled, non-privileged
268    /// mode, and without the scheduler lock held.
269    /// This call must initialize the `ThreadLocalState` returned by
270    /// `thread_local_state()`.
271    #[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
292/// A reference counted reference to a [`Thread`].
293///
294/// A `ThreadHandle` can has a limited set of APIs that are safe to call without
295/// holding the scheduler lock.
296pub struct ThreadHandle<K: Kernel> {
297    pub(crate) thread: NonNull<Thread<K>>,
298    kernel: K,
299}
300
301// Safety: ThreadHandle is a handle to a reference counted thread.  All operations
302// on the thread are protected by the scheduler lock or atomic operations.
303unsafe impl<K: Kernel> Send for ThreadHandle<K> {}
304unsafe impl<K: Kernel> Sync for ThreadHandle<K> {}
305
306impl<K: Kernel> ThreadHandle<K> {
307    /// Join the referenced thread.
308    ///
309    /// Waits until the all other references to the thread are dropped and the
310    /// thread terminates.  Returns a `ForeignBox<Thread<K>>` which can be used
311    /// to restart the thread.
312    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    /// Join the referenced thread with a deadline
337    ///
338    /// Waits until the all other references to the thread are dropped and the
339    /// thread terminates.
340    ///
341    /// Returns:
342    /// - `Ok(thread)`: Success. `thread` can be used to restart the thread.
343    /// - `Err(Error::DeadlineExceeded: The thread did not enter a joinable state
344    ///   before `deadline` was passed.
345    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    /// Request termination of the thread.
384    ///
385    /// Asynchronously requests the referenced thread to terminate.  While in the terminating
386    /// state:
387    /// - The thread's `terminating` field will be set to `true`.
388    /// - Any active interruptible waits will be canceled with `Error::Cancelled`.
389    /// - Any new interruptible wait will immediately return `Error::Cancelled`.
390    /// - All non-interruptible waits will work as normal.
391    ///
392    /// This is an ASYNCHRONOUS operation. The thread is marked as terminating,
393    /// but it may not exit immediately.
394    ///
395    /// To wait for the thread to terminate, call [`ThreadHandle::join()`] or
396    /// [`ThreadHandle::join_until()`].
397    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    /// Returns the current state of the thread.
405    pub fn get_state(&self, kernel: K) -> State {
406        kernel.get_scheduler().lock(kernel).thread_get_state(self)
407    }
408
409    /// Returns true if the thread is in the terminating state.
410    ///
411    /// Note: This is a parallel state to the state returned by [`ThreadHandle::is_terminating()`].
412    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 this ref was one of two outstanding references to the thread,
446            // the other reference may be attempting to join.  Let the scheduler
447            // notify the join request if it is outstanding.
448            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    // List of threads in a given process.
460    pub process_link: Link,
461
462    // Active state link (run queue, wait queue, etc)
463    pub active_link: Link,
464
465    process: Option<ProcessHandle<K>>,
466
467    pub(super) state: State,
468    pub(super) stack: Stack,
469
470    // Architecturally specific thread state, saved on context switch
471    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    // TODO - konkers: allow this to be tokenized.
480    pub name: &'static str,
481
482    /// The state for the scheduler algorithm.
483    pub algorithm_state: SchedulerAlgorithmThreadState,
484
485    /// CPU affinity mask.
486    #[cfg(feature = "smp")]
487    pub(super) affinity: AffinityMask,
488
489    /// Last CPU core this thread was assigned to or ran on.
490    #[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
497// SAFETY: Thread internal state is protected by the scheduler lock or atomic operations.
498unsafe 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    /// Sets the CPU affinity mask for this thread.
525    #[cfg(not(feature = "smp"))]
526    #[inline]
527    pub fn set_affinity(&mut self, _affinity: AffinityMask) {}
528
529    /// Sets the CPU affinity mask for this thread.
530    #[cfg(feature = "smp")]
531    #[inline]
532    pub fn set_affinity(&mut self, affinity: AffinityMask) {
533        self.affinity = affinity;
534
535        // Reset the last core to clear any outdated scheduling decisions.
536        self.last_core = None;
537    }
538
539    // Create an empty, uninitialized thread
540    #[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        // SAFETY: `self.process` will always outlive `self`.
572        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        // SAFETY: This function is only ever passed to the
588        // architecture-specific call to `initialize_frame` below. It is
589        // never called directly. In `initialize_frame`, the first argument
590        // is `entry_point as usize`. `entry_point` is a `fn(usize)`. Thus,
591        // this transmute preserves validity, and the preceding
592        // `with_exposed_provenance` ensures that the resulting `fn(usize)`
593        // has valid provenance for its referent.
594        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    /// # Safety
630    /// It is up to the caller to ensure that *process is valid.
631    /// Initialize the mutable parts of the non privileged thread, must be
632    /// called once per thread prior to starting it
633    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    /// Returns a reference to the thread's parent process.
660    pub fn process(&self) -> ProcessHandle<K> {
661        // SAFETY: The returned process references is bound to an immutable
662        // borrow of the thread the `process` pointer can not change.
663        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    /// Return a reference counted `ThreadHandle` for this thread.
670    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    /// A simple ID for debugging purposes
679    ///
680    /// Currently this is a pointer to the architecture specific thread state
681    /// allowing it to match debugging output from the architecture implementation.
682    ///
683    /// # Safety
684    ///
685    /// The returned value should not be relied upon as being a valid pointer.
686    /// Even in the current implementation, `id` does not expose the pointer's
687    /// provenance.
688    #[must_use]
689    pub fn id(&self) -> usize {
690        // Note: any changes to this also need to be reflected in
691        // `const_id_from_thread_address`.
692        self.arch_thread_state.get().addr()
693    }
694
695    /// Computes the ID of a thread from its address.
696    ///
697    /// # Safety
698    ///
699    /// This exists to allow thread annotations to be generated at compile time
700    /// for static threads that are initialized at runtime. This should not be
701    /// called in any other circumstance.
702    #[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    // An ID that can not be assigned to any thread in the system.
708    #[must_use]
709    pub const fn null_id() -> usize {
710        // `core::ptr::null::<Self>() as usize` can not be evaluated at const time
711        // and a null pointer is defined to be at address 0 (see
712        // https://doc.rust-lang.org/beta/core/ptr/fn.null.html).
713        0usize
714    }
715}
716
717pub use arg::ThreadArg;
718mod arg {
719    pub trait ThreadArg {
720        fn into_usize(self) -> usize;
721
722        /// # Safety
723        ///
724        /// `u` must have previously been returned by [`x.into_usize()`]. The
725        /// returned `Self` is guaranteed to be equal to `x`.
726        ///
727        /// [`x.into_usize()`]: ThreadArg::into_usize
728        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            // SAFETY: The caller promises that `u` was previously returned by
770            // `into_usize`, which is implemented as `<*const T as
771            // ThreadArg>::into_usize`. Thus, `u` was previously returned by
772            // `<*const T as ThreadArg>::into_usize`.
773            let ptr = unsafe { <*const T>::from_usize(u) };
774            // SAFETY: By the preceding safety comment, `ptr` is equal to `self
775            // as *const T` where `self: &'a T`, including provenance.
776            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            // SAFETY: The caller promises that `u` was previously returned by
789            // `into_usize`, which is implemented as `<*mut T as
790            // ThreadArg>::into_usize`. Thus, `u` was previously returned by
791            // `<*mut T as ThreadArg>::into_usize`.
792            let ptr = unsafe { <*mut T>::from_usize(u) };
793            // SAFETY: By the preceding safety comment, `ptr` is equal to `self
794            // as *mut T` where `self: &'a mut T`, including provenance. Since
795            // `into_usize` consumes `self` by value, no other references to the
796            // same referent exist, and so mutable aliasing is satisfied.
797            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                    // SAFETY: We asserted above that `size_of::<$t>() == 0`, so
812                    // there is only one value of `Self`. Thus, this
813                    // implementation of `from_usize` returns the same value
814                    // passed to any call to `into_usize`, as there is only one
815                    // possible such value.
816                    <$t as Default>::default()
817                }
818            }
819        };
820    }
821}
822
823/// Add debug annotations for a static thread
824///
825/// This macro is called by `init_non_priv_thread` and should not be called
826/// directly.
827#[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/// Add debug annotations for a stack.
851///
852/// This macro is called by `init_process` and should not be called directly.
853#[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/// Declare a static stack.
875///
876/// This macro is called by `init_process` and should not be called directly.
877#[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/// Constructs a new [`Thread`] in global static storage.
894///
895/// # Safety
896///
897/// Each invocation of `init_thread!` must be executed at most once at run time.
898// TODO: davidroth - Add const assertions to ensure stack sizes aren't too
899// small, once the sizing analysis has been done to understand what a reasonable
900// minimum is.
901#[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        /// SAFETY: This must be executed at most once at run time.
909        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            // SAFETY: The caller promises that this function will be
913            // executed at most once.
914            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/// Constructs a new [`Thread`] in global static storage and registers it.
933///
934/// # Safety
935///
936/// Each invocation of `declare_non_priv_thread!` must be executed at most once at
937/// run time.
938#[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        /// SAFETY: This must be executed at most once at run time.
948        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            // SAFETY: The caller promises that this function will be executed
955            // at most once.
956            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            // SAFETY: The caller promises that this function will be
966            // executed at most once.
967            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
979/// Initializes a thread in the given storage.
980pub 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}