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/core.rs

kernel/scheduler/
core.rs

1// Copyright 2026 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::ptr::NonNull;
17use core::sync::atomic::Ordering;
18
19use exit_status::ExitStatus;
20use foreign_box::ForeignBox;
21use list::*;
22use memory_config::MemoryConfig as _;
23use pw_atomic::{
24    AtomicAdd, AtomicCompareExchange, AtomicFalse, AtomicLoad, AtomicOne, AtomicStore, AtomicSub,
25    AtomicZero,
26};
27use pw_log::info;
28use pw_status::{Error, Result};
29use pw_time_core::Instant;
30
31#[cfg(feature = "user_space")]
32use crate::object::{NullObjectTable, SignalUpdate, Signals};
33use crate::scheduler::algorithm::{
34    RescheduleReason, SchedulerAlgorithm, SchedulerAlgorithmInterface as _,
35};
36use crate::scheduler::locks::WaitQueueLock;
37use crate::scheduler::process::{Process, ProcessHandle, ProcessListAdapter, ProcessState};
38use crate::scheduler::thread::{
39    State, Thread, ThreadArg, ThreadHandle, ThreadListAdapter, ThreadOwner, ThreadState,
40};
41use crate::scheduler::wait_queue::WaitType;
42use crate::sync::event::EventSignaler;
43use crate::sync::spinlock::SpinLockGuard;
44use crate::trace::trace_context_switch;
45use crate::{Arch, Kernel};
46
47const LOG_SCHEDULER_EVENTS: bool = false;
48
49// generic on `arch` instead of `kernel` as it appears in the `arch` interface.
50pub struct ThreadLocalState<A: Arch> {
51    pub(crate) preempt_disable_count: A::AtomicUsize,
52    pub(crate) needs_reschedule: A::AtomicBool,
53}
54
55impl<A: Arch> ThreadLocalState<A> {
56    #[must_use]
57    pub const fn new() -> Self {
58        Self {
59            preempt_disable_count: A::AtomicUsize::ZERO,
60            needs_reschedule: A::AtomicBool::FALSE,
61        }
62    }
63
64    #[must_use]
65    pub const fn new_preempt_disabled() -> Self {
66        Self {
67            preempt_disable_count: A::AtomicUsize::ONE,
68            needs_reschedule: A::AtomicBool::FALSE,
69        }
70    }
71}
72
73pub fn start_thread<K: Kernel>(kernel: K, mut thread: ForeignBox<Thread<K>>) -> ThreadHandle<K> {
74    log_if::info_if!(
75        LOG_SCHEDULER_EVENTS,
76        "Starting thread '{}' ({:#010x})",
77        thread.name as &str,
78        thread.id() as usize
79    );
80
81    pw_assert::assert!(thread.state == State::Initial);
82
83    thread.state = State::Ready;
84    let thread_handle = thread.get_ref(kernel);
85
86    let mut sched_state = kernel.get_scheduler().lock(kernel);
87
88    sched_state
89        .algorithm
90        .schedule_thread(thread, RescheduleReason::Started);
91
92    let _sched_state = sched_state.try_reschedule(kernel, RescheduleReason::Preempted);
93
94    thread_handle
95}
96
97pub fn initialize<K: Kernel>(kernel: K) {
98    let mut sched_state = kernel.get_scheduler().lock(kernel);
99
100    // The kernel process needs to be initialized before any kernel threads so
101    // that they can properly be parented underneath it.
102
103    // SAFETY: Per the contract in `SchedulerState` this is the one place that
104    // `kernel_process` is converted into a foreign box and its refcount is
105    // incremented.
106    unsafe {
107        let kernel_process = sched_state.kernel_process.get();
108        (*kernel_process).state = ProcessState::Active;
109        (*kernel_process).manually_increment_ref_count();
110        let kernel_process = ForeignBox::new(NonNull::new_unchecked(kernel_process));
111
112        sched_state.add_process_to_list(kernel_process);
113    }
114}
115
116pub fn add_process<K: Kernel>(kernel: K, mut process: ForeignBox<Process<K>>) -> ProcessHandle<K> {
117    let mut sched_state = kernel.get_scheduler().lock(kernel);
118    let process_handle = ProcessHandle::new(NonNull::from(&mut *process), kernel);
119
120    // The only way for a `ForeignBox<Process<K>>` to exist outside the scheduler,
121    // is for it to be newly created or to have been returned by the scheduler from a join.
122    // In both cases, the process is in the `Inactive` state.
123    pw_assert::assert!(process.state == ProcessState::Inactive);
124    process.state = ProcessState::Active;
125
126    // SAFETY: We are taking ownership of the ForeignBox and interacting with the
127    // scheduler state which we have locked.
128    sched_state.add_process_to_list(process);
129    process_handle
130}
131
132pub fn bootstrap_scheduler<K: Kernel>(
133    kernel: K,
134    preempt_guard: PreemptDisableGuard<K>,
135    mut thread: ForeignBox<Thread<K>>,
136) -> ! {
137    let mut sched_state = kernel.get_scheduler().lock(kernel);
138
139    // TODO: assert that this is called exactly once at bootup to switch
140    // to this particular thread.
141    pw_assert::assert!(thread.state == State::Initial);
142    thread.state = State::Ready;
143
144    sched_state
145        .algorithm
146        .schedule_thread(thread, RescheduleReason::Started);
147
148    info!("Context switching to first thread");
149
150    // Special case where we're switching from a non-thread to something real
151    let mut temp_arch_thread_state = K::ThreadState::NEW;
152    sched_state.current_arch_thread_state = &raw mut temp_arch_thread_state;
153
154    drop(preempt_guard);
155
156    let _ = block(
157        kernel,
158        sched_state,
159        Thread::<K>::null_id(),
160        State::Terminated,
161    );
162    pw_assert::panic!("Bootstrap scheduler returned unexpectedly");
163}
164
165pub struct PreemptDisableGuard<K: Kernel>(K);
166
167impl<K: Kernel> PreemptDisableGuard<K> {
168    pub fn new(kernel: K) -> Self {
169        let prev_count = kernel
170            .thread_local_state()
171            .preempt_disable_count
172            .fetch_add(1, core::sync::atomic::Ordering::SeqCst);
173
174        // atomics have wrapping semantics so overflow is explicitly checked.
175        if prev_count == usize::MAX {
176            pw_assert::debug_panic!("PreemptDisableGuard: preempt_disable_count overflow")
177        }
178
179        Self(kernel)
180    }
181
182    /// Reconstructs a [`PreemptDisableGuard`] when preemption is already disabled.
183    ///
184    /// # Safety
185    /// `preempt_disable_count` must already be `>= 1` for an active guard whose
186    /// ownership was transferred to this context.
187    #[inline]
188    pub(crate) unsafe fn adopt_locked(kernel: K) -> Self {
189        pw_assert::debug_assert!(
190            kernel
191                .thread_local_state()
192                .preempt_disable_count
193                .load(Ordering::SeqCst)
194                >= 1
195        );
196        Self(kernel)
197    }
198}
199
200impl<K: Kernel> Drop for PreemptDisableGuard<K> {
201    fn drop(&mut self) {
202        let prev_count = self
203            .0
204            .thread_local_state()
205            .preempt_disable_count
206            .fetch_sub(1, core::sync::atomic::Ordering::SeqCst);
207
208        if prev_count == 0 {
209            pw_assert::debug_panic!("PreemptDisableGuard: preempt_disable_count underflow")
210        }
211    }
212}
213
214// Global scheduler state (single processor for now)
215#[allow(dead_code)]
216pub struct SchedulerState<K: Kernel> {
217    // The scheduler owns the kernel process from which all kernel threads
218    // are parented.
219    //
220    // SAFETY: `kernel_process` must be converted to a `ForeignBox` exactly
221    // once while the scheduler is initialized.  This initialization must also
222    // increment the processes refcount.
223    pub(crate) kernel_process: UnsafeCell<Process<K>>,
224
225    pub(super) current_thread: Option<ForeignBox<Thread<K>>>,
226    pub(super) current_arch_thread_state: *mut K::ThreadState,
227    pub(super) process_list: ForeignList<Process<K>, ProcessListAdapter<K>>,
228
229    /// The algorithm used for choosing the next thread to run.
230    pub(super) algorithm: SchedulerAlgorithm<K>,
231
232    pub(super) termination_queue: ForeignList<Thread<K>, ThreadListAdapter<K>>,
233}
234
235unsafe impl<K: Kernel> Sync for SchedulerState<K> {}
236unsafe impl<K: Kernel> Send for SchedulerState<K> {}
237
238impl<K: Kernel> SchedulerState<K> {
239    #[allow(dead_code)]
240    #[allow(clippy::new_without_default)]
241    pub const fn new() -> Self {
242        #[cfg(feature = "user_space")]
243        static KERNEL_OBJECT_TABLE: NullObjectTable = NullObjectTable::new();
244        Self {
245            kernel_process: UnsafeCell::new(Process::new(
246                "kernel",
247                <K::ThreadState as ThreadState>::MemoryConfig::KERNEL_THREAD_MEMORY_CONFIG,
248                // SAFETY: In the event of multiple scheduler objects, they will
249                // refer to the same, immutable, instance of a zero sized type.
250                #[cfg(feature = "user_space")]
251                unsafe {
252                    ForeignBox::new(NonNull::from_ref(&KERNEL_OBJECT_TABLE))
253                },
254            )),
255            current_thread: None,
256            current_arch_thread_state: core::ptr::null_mut(),
257            process_list: ForeignList::new(),
258            algorithm: SchedulerAlgorithm::new(),
259            termination_queue: ForeignList::new(),
260        }
261    }
262
263    /// Returns a pointer to the current threads architecture thread state
264    /// struct.
265    ///
266    /// Only meant to be called from within an architecture implementation.
267    ///
268    /// # Safety
269    ///
270    /// Must be called with the scheduler lock held.  Pointer is only valid
271    /// while the current threads remains the current thread.
272    #[allow(dead_code)]
273    #[doc(hidden)]
274    pub unsafe fn get_current_arch_thread_state(&mut self) -> *mut K::ThreadState {
275        self.current_arch_thread_state
276    }
277
278    fn reschedule_current_thread(&mut self, reason: RescheduleReason) -> (usize, State) {
279        let Some(mut current_thread) = self.current_thread.take() else {
280            return (Thread::<K>::null_id(), State::New);
281        };
282
283        let current_thread_id = current_thread.id();
284        current_thread.state = State::Ready;
285        self.algorithm.schedule_thread(current_thread, reason);
286        (current_thread_id, State::Ready)
287    }
288
289    fn set_current_thread(&mut self, thread: ForeignBox<Thread<K>>) {
290        self.current_arch_thread_state = thread.arch_thread_state.get();
291        self.current_thread = Some(thread);
292    }
293
294    pub fn current_thread_id(&self) -> usize {
295        match &self.current_thread {
296            Some(thread) => thread.id(),
297            None => Thread::<K>::null_id(),
298        }
299    }
300
301    #[allow(dead_code)]
302    pub fn current_thread_name(&self) -> &'static str {
303        match &self.current_thread {
304            Some(thread) => thread.name,
305            None => "none",
306        }
307    }
308
309    pub fn take_current_thread(&mut self) -> ForeignBox<Thread<K>> {
310        let Some(thread) = self.current_thread.take() else {
311            pw_assert::panic!("No current thread");
312        };
313        thread
314    }
315
316    #[allow(dead_code)]
317    pub fn current_thread(&self) -> &Thread<K> {
318        let Some(thread) = &self.current_thread else {
319            pw_assert::panic!("No current thread");
320        };
321        thread
322    }
323
324    #[allow(dead_code)]
325    pub fn current_thread_mut(&mut self) -> &mut Thread<K> {
326        let Some(thread) = &mut self.current_thread else {
327            pw_assert::panic!("No current thread");
328        };
329        thread
330    }
331
332    pub fn current_process_handle(&self) -> ProcessHandle<K> {
333        self.current_thread().process()
334    }
335
336    /// # Safety
337    ///
338    /// This method has the same safety preconditions as
339    /// [`UnsafeList::push_front_unchecked`].
340    #[allow(dead_code)]
341    #[inline(never)]
342    pub fn add_process_to_list(&mut self, process: ForeignBox<Process<K>>) {
343        self.process_list.push_front(process);
344    }
345
346    fn get_kernel_process_handle(&self, kernel: K) -> ProcessHandle<K> {
347        let Some(process) = NonNull::new(self.kernel_process.get()) else {
348            pw_assert::panic!("Kernel process is null");
349        };
350        ProcessHandle::new(process, kernel)
351    }
352
353    #[allow(dead_code)]
354    pub fn dump(&self, kernel: K) {
355        info!("List of all threads:");
356        let _ = self
357            .process_list
358            .for_each(|process| -> core::result::Result<(), ()> {
359                process.dump(kernel);
360                Ok(())
361            });
362    }
363}
364
365pub enum JoinResult<K: Kernel> {
366    Joined(ForeignBox<Thread<K>>, ExitStatus),
367    Err {
368        error: Error,
369        thread: ThreadHandle<K>,
370    },
371}
372
373pub enum TryJoinResult<K: Kernel> {
374    Wait(ThreadHandle<K>),
375    Joined(ForeignBox<Thread<K>>, ExitStatus),
376    Err {
377        error: Error,
378        thread: ThreadHandle<K>,
379    },
380}
381
382pub enum ProcessJoinResult<K: Kernel> {
383    Joined(ForeignBox<Process<K>>, ExitStatus),
384    Err {
385        error: Error,
386        process: ProcessHandle<K>,
387    },
388}
389
390pub enum ProcessTryJoinResult<K: Kernel> {
391    Wait(ProcessHandle<K>),
392    Joined(ForeignBox<Process<K>>, ExitStatus),
393    Err {
394        error: Error,
395        process: ProcessHandle<K>,
396    },
397}
398
399// All thread lifecycle management is encapsulated in this `impl` block which
400// ensures the scheduler lock is held while the state is manipulated.
401impl<K: Kernel> SpinLockGuard<'_, K, SchedulerState<K>> {
402    /// Reschedule if preemption is enabled
403    #[must_use]
404    pub(super) fn try_reschedule(mut self, kernel: K, reason: RescheduleReason) -> Self {
405        if kernel
406            .thread_local_state()
407            .preempt_disable_count
408            .load(Ordering::SeqCst)
409            == 1
410        {
411            let (current_thread_id, current_thread_state) = self.reschedule_current_thread(reason);
412            let (guard, _switched) =
413                context_switch(kernel, self, current_thread_id, current_thread_state);
414            guard
415        } else {
416            kernel
417                .thread_local_state()
418                .needs_reschedule
419                .store(true, Ordering::SeqCst);
420            self
421        }
422    }
423
424    fn thread_initialize(
425        &self,
426        _kernel: K,
427        thread: &mut Thread<K>,
428        mut process_handle: ProcessHandle<K>,
429    ) -> Result<()> {
430        thread.state = State::Initial;
431
432        // SAFETY: *process is only accessed with the scheduler lock held.
433        unsafe {
434            let process = process_handle.process.as_mut();
435            // Assert that the parent process is active.
436            if process.state != ProcessState::Active {
437                return Err(Error::FailedPrecondition);
438            }
439            // Add thread to processes thread list.
440            process.add_to_thread_list(thread);
441        }
442
443        thread.set_process(process_handle);
444        Ok(())
445    }
446
447    pub fn thread_initialize_kernel<A: ThreadArg>(
448        &mut self,
449        kernel: K,
450        thread: &mut Thread<K>,
451        entry_point: fn(K, A),
452        arg: A,
453    ) {
454        pw_assert::assert!(thread.state == State::New);
455        let process_handle = self.get_kernel_process_handle(kernel);
456        let args = (entry_point as usize, kernel.into_usize(), arg.into_usize());
457
458        thread.stack.initialize();
459
460        unsafe {
461            (*thread.arch_thread_state.get()).initialize_kernel_state(
462                thread.stack,
463                &raw const process_handle.process.as_ref().memory_config,
464                Thread::<K>::trampoline::<A>,
465                args,
466            );
467        }
468
469        // The kernel process is bootstrapped as active, and any attempt to
470        // terminate it will panic. Therefore, this initialization must always succeed.
471        pw_assert::assert!(
472            self.thread_initialize(kernel, thread, process_handle)
473                .is_ok()
474        );
475    }
476
477    pub fn thread_reinitialize_kernel<A: ThreadArg>(
478        &mut self,
479        kernel: K,
480        thread: &mut Thread<K>,
481        entry_point: fn(K, A),
482        arg: A,
483    ) {
484        pw_assert::assert!(thread.state == State::Joined);
485        let process_handle = self.get_kernel_process_handle(kernel);
486        let args = (entry_point as usize, kernel.into_usize(), arg.into_usize());
487
488        thread.stack.initialize();
489
490        // SAFETY: The scheduler guarantees that a process' `memory_config`
491        // remains valid while it has any child threads ensuring that the
492        // `memory_config` is valid for the lifetime of the thread.
493        unsafe {
494            (*thread.arch_thread_state.get()).initialize_kernel_state(
495                thread.stack,
496                &raw const process_handle.process.as_ref().memory_config,
497                Thread::<K>::trampoline::<A>,
498                args,
499            );
500        }
501
502        // The kernel process is bootstrapped as active, and any attempt to
503        // terminate it will panic. Therefore, this initialization must always succeed.
504        pw_assert::assert!(
505            self.thread_initialize(kernel, thread, process_handle)
506                .is_ok()
507        );
508    }
509
510    #[cfg(feature = "user_space")]
511    /// # Safety
512    /// It is up to the caller to ensure that *process is valid.
513    /// Initialize the mutable parts of the non privileged thread, must be
514    /// called once per thread prior to starting it
515    #[allow(clippy::too_many_arguments)]
516    pub unsafe fn thread_initialize_non_priv(
517        &mut self,
518        kernel: K,
519        thread: &mut Thread<K>,
520        process_handle: ProcessHandle<K>,
521        initial_pc: usize,
522        initial_sp: usize,
523        args: (usize, usize, usize),
524    ) -> Result<()> {
525        pw_assert::assert!(matches!(thread.state, State::New | State::Joined));
526
527        thread.stack.initialize();
528
529        // SAFETY: The scheduler guarantees that a process' `memory_config`
530        // remains valid while it has any child threads.  This is because
531        // each `Thread` holds a `ProcessHandle` to its parent process, ensuring
532        // the `Process` and its `memory_config` are valid for the lifetime
533        // of the thread.
534        #[cfg(feature = "user_space")]
535        unsafe {
536            (*thread.arch_thread_state.get()).initialize_user_state(
537                thread.stack,
538                &raw const process_handle.process.as_ref().memory_config,
539                initial_sp,
540                initial_pc,
541                args,
542            )?;
543        }
544
545        self.thread_initialize(kernel, thread, process_handle)
546    }
547
548    pub(crate) fn thread_get_state(&self, thread: &ThreadHandle<K>) -> State {
549        // SAFETY: we have exclusive access to thread by virtue of the scheduler lock being held.
550        unsafe { thread.thread.as_ref().state }
551    }
552
553    /// Request termination of the referenced thread.
554    ///
555    /// This is an ASYNCHRONOUS operation. The thread is marked as terminating,
556    /// but it may not exit immediately.
557    pub fn thread_terminate(
558        &mut self,
559        thread_handle: &mut ThreadHandle<K>,
560        status: ExitStatus,
561    ) -> Result<()> {
562        // SAFETY: we have exclusive access to thread by virtue of the scheduler lock being held.
563        let thread = unsafe { thread_handle.thread.as_mut() };
564        self.thread_terminate_internal(thread, status)
565    }
566
567    pub(crate) fn thread_terminate_internal(
568        &mut self,
569        thread: &mut Thread<K>,
570        status: ExitStatus,
571    ) -> Result<()> {
572        thread.exit_status = Some(status);
573        match &mut thread.owner {
574            ThreadOwner::None => Err(Error::InvalidArgument),
575            // Threads in a `WakeList` are already dequeued from their
576            // `WaitQueue` and on their way to the scheduler.
577            ThreadOwner::Scheduler | ThreadOwner::WakeList => {
578                // Mark thread as terminating so that it can clean itself up.
579                thread.terminating = true;
580
581                // Should we signal the scheduling algorithm to give it the
582                // chance to move the thread to the front of the queue?
583
584                Ok(())
585            }
586            ThreadOwner::WaitQueue { queue, wait_type } => {
587                // First, mark the thread as being in the terminated state.
588                // SAFETY: Threads access is guarded by the scheduler lock.
589                thread.terminating = true;
590
591                // Second, wake the thread if it is in an interruptible wait.
592                if *wait_type == WaitType::Interruptible {
593                    // SAFETY: All thread and wait queue accesses are guarded by
594                    // the scheduler lock and the thread is guaranteed to be in
595                    // the queue by the fact that the queue is the ThreadOwner.
596                    let ret = unsafe {
597                        queue
598                            .as_mut()
599                            .queue
600                            .remove_element(NonNull::from_ref(thread))
601                    };
602                    let Some(thread_box) = ret else {
603                        // The a thread's owner is `ThreadOwner::WaitQueue` it will always
604                        // be in the `WaitQueue`'s queue.  A failure to remove here would
605                        // be the result of a bug or corruption.
606                        pw_assert::panic!("Could not remove thread from its owning WaitQueue");
607                    };
608                    thread.state = State::Ready;
609                    self.algorithm
610                        .schedule_thread(thread_box, RescheduleReason::Woken);
611                }
612                Ok(())
613            }
614        }
615    }
616
617    pub(crate) fn thread_signal_join(mut self, kernel: K, thread: &mut ThreadHandle<K>) -> Self {
618        if let Some(signaler) = unsafe { thread.thread.as_mut() }.join_event.take() {
619            self = signaler.signal_and_wake_locked(kernel, self);
620        }
621
622        self
623    }
624
625    pub(crate) fn thread_try_join(
626        mut self,
627        kernel: K,
628        mut thread_handle: ThreadHandle<K>,
629        signaler: Option<EventSignaler<K>>,
630    ) -> (Self, TryJoinResult<K>) {
631        // SAFETY: Exclusive access to thread is guaranteed by scheduler lock
632        let thread = unsafe { thread_handle.thread.as_mut() };
633
634        // If the thread is terminated and `thread_handle` is the singular reference to it,
635        // the thread is terminated
636        if thread.state == State::Terminated && thread.ref_count.load(Ordering::SeqCst) == 1 {
637            // SAFETY: Threads only enter the Terminated state through `exit_thread` which adds them
638            // to the termination_queue.  Join is the only method by which they are removed from the
639            // queue and the state is set to the Joined state when that happens.  Therefore, if the
640            // thread is in the Terminated state, it *must* be in the termination_queue.
641            thread.state = State::Joined;
642
643            self = self.thread_remove_from_parent_process(kernel, thread);
644
645            // Reset thread state.
646            thread.terminating = false;
647
648            // SAFETY: Thread is guaranteed to be in the termination queue by
649            // the fact that it is in the terminated state.
650            #[allow(unused_mut)]
651            let mut thread = unsafe {
652                self.termination_queue
653                    .remove_element_unchecked(thread_handle.thread)
654            };
655
656            // Clear JOINABLE signal.
657            #[cfg(feature = "user_space")]
658            if let Some(object) = thread.object.take() {
659                self = object.signal_locked(kernel, self, SignalUpdate::clear(Signals::JOINABLE));
660            }
661
662            let Some(status) = thread.exit_status.take() else {
663                pw_assert::panic!("Thread joined with no exit status set");
664            };
665            return (self, TryJoinResult::Joined(thread, status));
666        }
667
668        // Only one call to join is allowed to wait thread termination
669        if thread.join_event.is_some() {
670            return (
671                self,
672                TryJoinResult::Err {
673                    error: Error::AlreadyExists,
674                    thread: thread_handle,
675                },
676            );
677        }
678
679        // Register the signaler and return None indicating the thread is not yet
680        // joinable.
681        if let Some(signaler) = signaler {
682            thread.join_event = Some(signaler);
683        }
684        (self, TryJoinResult::Wait(thread_handle))
685    }
686
687    pub(crate) fn thread_cancel_try_join(&mut self, thread_handle: &mut ThreadHandle<K>) {
688        // SAFETY: Exclusive access to thread is guaranteed by scheduler lock
689        let thread = unsafe { thread_handle.thread.as_mut() };
690        pw_assert::assert!(thread.join_event.is_some());
691        thread.join_event = None;
692    }
693
694    /// Performs the low-level operations to exit the current thread.
695    ///
696    /// This method handles the actual state transitions and cleanup for thread exit.
697    /// It expects the `exit_status` to have been set by the caller if necessary.
698    ///
699    /// # Differences from other exit/terminate functions:
700    /// - **`exit_thread`**: A high-level wrapper that takes an explicit status,
701    ///   sets it on the thread, and then calls this method. It does not return.
702    /// - **`terminate`**: Asynchronous requests to terminate a thread/process.
703    ///   They set the target's state to terminating but rely on `thread_exit`
704    ///   being called later to perform the actual exit.
705    pub(crate) fn thread_exit(mut self, kernel: K) {
706        let mut current_thread = self.take_current_thread();
707        let current_thread_id = current_thread.id();
708
709        pw_assert::assert!(matches!(current_thread.owner, ThreadOwner::Scheduler));
710
711        log_if::info_if!(
712            LOG_SCHEDULER_EVENTS,
713            "Exiting thread '{}' ({:#010x})",
714            current_thread.name as &str,
715            current_thread.id() as usize
716        );
717
718        // Since the current thread has already been removed from the scheduler,
719        // a PreemptDisableGuard is taken to prevent any wakeups during thread
720        // and process teardown from triggering a reschedule before the final
721        // context_switch.
722        let guard = PreemptDisableGuard::new(kernel);
723        if let Some(signaler) = current_thread.as_mut().join_event.take() {
724            self = signaler.signal_and_wake_locked(kernel, self);
725        }
726        current_thread.state = State::Terminated;
727        current_thread.terminating = true;
728
729        #[cfg(feature = "user_space")]
730        {
731            let process_handle = current_thread.process();
732            let thread_object = current_thread.object.as_ref().cloned();
733
734            // It is important that we add the thread to the termination queue
735            // before possibly auto-joining the thread as join expects the thread
736            // to be in termination queue at that time.
737            self.termination_queue.push_back(current_thread);
738
739            if let Some(thread_object) = thread_object {
740                // Ensure we set them as JOINABLE again if it transitions to Terminated
741                self = thread_object.signal_locked(
742                    kernel,
743                    self,
744                    SignalUpdate::raise(Signals::JOINABLE),
745                );
746
747                if process_handle.get_state_locked(&self) == ProcessState::Terminating {
748                    (self, _) = thread_object.join_locked(kernel, self);
749                }
750            }
751            self = process_handle.drop_locked(kernel, self);
752        }
753        #[cfg(not(feature = "user_space"))]
754        {
755            self.termination_queue.push_back(current_thread);
756        }
757
758        drop(guard);
759        let _ = context_switch(kernel, self, current_thread_id, State::Terminated);
760
761        // On some systems like M-profile ARM context switch is deferred if called
762        // from an interrupt so this function may return.
763    }
764
765    pub(crate) fn thread_is_terminating(&self, thread: &ThreadHandle<K>) -> bool {
766        // SAFETY: Exclusive access to thread is guaranteed by scheduler lock
767        unsafe { thread.thread.as_ref().terminating }
768    }
769
770    fn thread_remove_from_parent_process(mut self, kernel: K, thread: &mut Thread<K>) -> Self {
771        let mut process_handle = thread.take_process();
772
773        // SAFETY: Thread is guaranteed to be in the process because the process
774        // was just taken from the thread.
775        self = unsafe { self.process_remove_from_thread_list(kernel, &mut process_handle, thread) };
776
777        // ProcessHandle's drop takes the scheduler lock.  Since that is already
778        // held, `drop_locked()` needs to be used instead to avoid recursively
779        // locking the scheduler lock.
780        process_handle.drop_locked(kernel, self)
781    }
782}
783
784impl<K: Kernel> SpinLockGuard<'_, K, SchedulerState<K>> {
785    /// Request termination of the referenced process and all its threads.
786    ///
787    /// This is an ASYNCHRONOUS operation. The process and its threads are marked
788    /// as terminating, but they may not exit immediately.
789    pub fn process_terminate(
790        &mut self,
791        _kernel: K,
792        process_handle: &ProcessHandle<K>,
793        status: ExitStatus,
794    ) {
795        let mut ptr = process_handle.process;
796        pw_assert::assert!(
797            ptr.as_ptr() != self.kernel_process.get(),
798            "Tried to terminate the kernel process"
799        );
800        // SAFETY: `process_handle` guarantees that the pointed-to process is alive.
801        // Holding the scheduler lock (via `&mut self`) guarantees exclusive mutable
802        // access. The returned reference `proc` is local to this function
803        // and does not outlive the lock.
804        let proc = unsafe { ptr.as_mut() };
805
806        if proc.state != ProcessState::Active {
807            return;
808        }
809
810        // Set state to terminating
811        proc.state = ProcessState::Terminating;
812        proc.exit_status = Some(status);
813
814        // Terminate all threads
815        unsafe {
816            proc.thread_list.filter(|thread| {
817                log_if::info_if!(
818                    LOG_SCHEDULER_EVENTS,
819                    "Terminating thread '{}'",
820                    thread.name as &str
821                );
822                let _ = self.thread_terminate_internal(thread, ExitStatus::ProcessTerminated);
823                true // Keep in list
824            });
825        }
826    }
827
828    #[must_use]
829    pub fn process_signal_join(mut self, kernel: K, process: &mut ProcessHandle<K>) -> Self {
830        // SAFETY: inner process is protected by the scheduler lock and the
831        // mutable reference does not live beyond the unsafe taking the signaler
832        let signaler = unsafe { process.process.as_mut().join_event.take() };
833        if let Some(signaler) = signaler {
834            self = signaler.signal_and_wake_locked(kernel, self);
835        }
836
837        // Raise JOINABLE signal.
838        #[cfg(feature = "user_space")]
839        if let Some(object) = unsafe { process.process.as_ref().object.as_ref() } {
840            self = object.signal_locked(kernel, self, SignalUpdate::raise(Signals::JOINABLE));
841        }
842        self
843    }
844
845    pub fn process_try_join(
846        mut self,
847        kernel: K,
848        mut process_handle: ProcessHandle<K>,
849        signaler: Option<EventSignaler<K>>,
850    ) -> (Self, ProcessTryJoinResult<K>) {
851        let process = unsafe { process_handle.process.as_ref() };
852
853        // If the process is terminated and `process_handle` is the singular reference to it,
854        // the process is terminated
855        if process.state == ProcessState::Terminated
856            && process.ref_count.load(Ordering::SeqCst) == 1
857        {
858            // SAFETY: The process is guaranteed to be in the process list
859            // because it was passed in by ProcessHandle and the scheduler is
860            // the only creator of those.
861            #[allow(unused_mut)]
862            let mut process_box = unsafe {
863                self.process_list
864                    .remove_element_unchecked(process_handle.process)
865            };
866            process_box.state = ProcessState::Inactive;
867
868            // Clear JOINABLE signal.
869            #[cfg(feature = "user_space")]
870            if let Some(object) = process_box.object.take() {
871                self = object.signal_locked(kernel, self, SignalUpdate::clear(Signals::JOINABLE));
872            }
873            #[cfg(not(feature = "user_space"))]
874            {
875                // `kernel` is only used above when `user_space` is enabled.
876                // Reference it here to suppress warning.
877                let _ = kernel;
878            }
879            let Some(status) = process_box.exit_status.take() else {
880                pw_assert::panic!("Process joined with no exit status set");
881            };
882            return (self, ProcessTryJoinResult::Joined(process_box, status));
883        }
884
885        // Only one call to join is allowed to wait for process termination.  If
886        // another caller is waiting, return an error.
887        if process.join_event.is_some() {
888            return (
889                self,
890                ProcessTryJoinResult::Err {
891                    error: Error::AlreadyExists,
892                    process: process_handle,
893                },
894            );
895        }
896
897        // Register the signaler and return None indicating the process is not yet
898        // joinable.
899        //
900        // SAFETY: Process mutability guarded by scheduler lock.
901        if let Some(signaler) = signaler {
902            unsafe { process_handle.process.as_mut().join_event = Some(signaler) };
903        }
904        (self, ProcessTryJoinResult::Wait(process_handle))
905    }
906
907    pub fn process_cancel_try_join(&mut self, process_handle: &mut ProcessHandle<K>) {
908        let process = unsafe { process_handle.process.as_mut() };
909        pw_assert::assert!(process.join_event.is_some());
910        process.join_event = None;
911    }
912
913    /// # Safety
914    ///
915    /// Caller must ensure that the thread is already in the processes thread list.
916    unsafe fn process_remove_from_thread_list(
917        mut self,
918        kernel: K,
919        process_handle: &mut ProcessHandle<K>,
920        thread: &mut Thread<K>,
921    ) -> Self {
922        // SAFETY: Scheduler lock is held so it is safe to manipulate the process
923        // list and the caller guarantees that the thread is in said list so it
924        // is safe to remove it.
925
926        // SAFETY: The scheduler lock ensures mutual exclusion and the mutable
927        // reference does not live out side this function.
928        let process = unsafe { process_handle.process.as_mut() };
929
930        // SAFETY: Caller guarantees that the thread is in the process' thread list
931        // and the list is protected by the scheduler lock.
932        let empty = unsafe {
933            process
934                .thread_list
935                .unlink_element_unchecked(NonNull::from(thread));
936
937            process.thread_list.is_empty()
938        };
939
940        if process.state == ProcessState::Terminating && empty {
941            process.state = ProcessState::Terminated;
942            self = self.process_signal_join(kernel, process_handle);
943        }
944        self
945    }
946
947    pub fn process_add_thread(
948        &self,
949        process_handle: &mut ProcessHandle<K>,
950        thread_handle: &mut ThreadHandle<K>,
951    ) -> Result<()> {
952        // SAFETY: Scheduler lock is held ensuring exclusive access to process_handle
953        // and thread_handle as well as fulfilling the precondition of `add_to_thread_list`.
954        unsafe {
955            let process = process_handle.process.as_mut();
956            if process.state != ProcessState::Active {
957                return Err(Error::FailedPrecondition);
958            }
959            process.add_to_thread_list(thread_handle.thread.as_mut());
960        }
961        Ok(())
962    }
963}
964
965#[must_use]
966pub(crate) fn block<K: Kernel>(
967    kernel: K,
968    sched_state: SpinLockGuard<K, SchedulerState<K>>,
969    current_thread_id: usize,
970    current_thread_state: State,
971) -> SpinLockGuard<K, SchedulerState<K>> {
972    let (sched_state, switched) =
973        context_switch(kernel, sched_state, current_thread_id, current_thread_state);
974    pw_assert::assert!(switched, "Blocking requires a context switch");
975    sched_state
976}
977
978#[must_use]
979pub(crate) fn context_switch<K: Kernel>(
980    kernel: K,
981    mut sched_state: SpinLockGuard<K, SchedulerState<K>>,
982    current_thread_id: usize,
983    current_thread_state: State,
984) -> (SpinLockGuard<K, SchedulerState<K>>, bool) {
985    // Caller to reschedule is responsible for removing current thread and
986    // put it in the correct run/wait queue.
987    pw_assert::assert!(sched_state.current_thread.is_none());
988
989    // Validate that the only mechanism disabling preemption is the scheduler
990    // lock which is passed in to this function.
991    pw_assert::assert!(
992        kernel
993            .thread_local_state()
994            .preempt_disable_count
995            .load(Ordering::SeqCst)
996            <= 1,
997        "Preemption count greater than 1"
998    );
999
1000    // Pop a new thread off the head of the run queue.
1001    // At the moment cannot handle an empty queue, so will panic in that case.
1002    // TODO: Implement either an idle thread or a special idle routine for that case.
1003    let Some(mut new_thread) = sched_state.algorithm.pop_next_thread() else {
1004        pw_assert::panic!("Run queue empty: no runnable threads (idle thread missing or blocked?)");
1005    };
1006
1007    pw_assert::assert!(
1008        new_thread.state == State::Ready,
1009        "<{}>({:#010x}) not ready",
1010        new_thread.name as &str,
1011        new_thread.id() as usize,
1012    );
1013    new_thread.state = State::Running;
1014
1015    if current_thread_id == new_thread.id() {
1016        sched_state.current_thread = Some(new_thread);
1017        return (sched_state, false);
1018    }
1019
1020    trace_context_switch(
1021        kernel,
1022        current_thread_id,
1023        new_thread.id(),
1024        current_thread_state,
1025    );
1026
1027    let old_thread_state = sched_state.current_arch_thread_state;
1028    let new_thread_state = new_thread.arch_thread_state.get();
1029    sched_state.set_current_thread(new_thread);
1030    unsafe { kernel.context_switch(sched_state, old_thread_state, new_thread_state) }
1031}
1032
1033/// If try_reschedule() was called while preemption was disabled, try to
1034/// reschedule again after the preempt guard is dropped.
1035pub fn try_deferred_reschedule<K: Kernel>(kernel: K, reason: RescheduleReason) {
1036    if Ok(true)
1037        == kernel
1038            .thread_local_state()
1039            .needs_reschedule
1040            .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
1041    {
1042        let _ = kernel
1043            .get_scheduler()
1044            .lock(kernel)
1045            .try_reschedule(kernel, reason);
1046    }
1047}
1048
1049#[allow(dead_code)]
1050pub fn yield_timeslice<K: Kernel>(kernel: K) {
1051    let sched_state = kernel.get_scheduler().lock(kernel);
1052    log_if::info_if!(
1053        LOG_SCHEDULER_EVENTS,
1054        "Yielding thread '{}' ({:#010x})",
1055        sched_state.current_thread_name() as &str,
1056        sched_state.current_thread_id() as usize
1057    );
1058    let _ = sched_state.try_reschedule(kernel, RescheduleReason::Ticked);
1059}
1060
1061// Tick that is called from a timer handler. The scheduler will evaluate if the current thread
1062// should be preempted or not
1063#[allow(dead_code)]
1064pub fn tick<K: Kernel>(
1065    kernel: K,
1066    now: Instant<K::Clock>,
1067    mut guard: crate::interrupt_controller::InterruptGuard<K>,
1068) -> crate::interrupt_controller::InterruptGuard<K> {
1069    log_if::info_if!(
1070        LOG_SCHEDULER_EVENTS,
1071        "Scheduler tick at {}",
1072        now.ticks() as u64
1073    );
1074    pw_assert::assert!(
1075        kernel
1076            .thread_local_state()
1077            .preempt_disable_count
1078            .load(Ordering::SeqCst)
1079            >= 1,
1080        "scheduler::tick() called with preemption enabled"
1081    );
1082
1083    // In lieu of a proper timer interface, the scheduler needs to be robust
1084    // to timer ticks arriving before it is initialized.
1085    if kernel.get_scheduler().lock(kernel).current_thread.is_none() {
1086        return guard;
1087    }
1088
1089    crate::scheduler::timer::process_queue(kernel, now);
1090
1091    guard.set_reschedule_reason(RescheduleReason::Ticked);
1092    let _ = kernel
1093        .get_scheduler()
1094        .lock(kernel)
1095        .try_reschedule(kernel, RescheduleReason::Ticked);
1096
1097    guard
1098}
1099
1100pub fn exit_thread<K: Kernel>(kernel: K, status: ExitStatus) -> ! {
1101    let mut sched = kernel.get_scheduler().lock(kernel);
1102    let current_thread = sched.current_thread_mut();
1103    current_thread.exit_status = Some(status);
1104    sched.thread_exit(kernel);
1105
1106    // This thread should never get scheduled again at this point.  This assert
1107    // firing indicates a scheduler or context switch bug.
1108    pw_assert::panic!("thread_exit returned unexpectedly");
1109}
1110
1111/// Handle a terminal exception in the current thread.
1112///
1113/// This should only be called from an architecture specific exception handler.
1114/// An InterruptGuard is passed in and out in order to allow it to take
1115/// architecturally specific action for thread termination.
1116///
1117/// If the exception occurred in user mode, the process will be terminated.
1118/// If the exception occurred in kernel mode, the kernel will panic.
1119pub fn handle_terminal_exception<K: Kernel>(
1120    kernel: K,
1121    guard: crate::interrupt_controller::InterruptGuard<K>,
1122) -> crate::interrupt_controller::InterruptGuard<K> {
1123    if !guard.from_userspace() {
1124        pw_assert::panic!("Terminal exception in kernel mode");
1125    }
1126
1127    let mut sched = kernel.get_scheduler().lock(kernel);
1128    let process_handle = sched.current_thread().process();
1129    sched.process_terminate(kernel, &process_handle, ExitStatus::UnhandledException(0));
1130
1131    guard
1132}
1133
1134pub fn sleep_until<K: Kernel>(kernel: K, deadline: Instant<K::Clock>) -> Result<()> {
1135    let wait_queue = WaitQueueLock::new(kernel, ());
1136
1137    let (_, ret) = wait_queue
1138        .lock()
1139        .wait_until(WaitType::Interruptible, deadline);
1140    match ret {
1141        // DeadlineExceeded is the expected result so return OK in that case.
1142        Err(Error::DeadlineExceeded) => Ok(()),
1143
1144        // In all other cases, pass on the return value.
1145        _ => ret,
1146    }
1147}