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

kernel/scheduler/
wait_queue.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;
17
18#[cfg(not(feature = "user_space"))]
19use foreign_box::ForeignBox;
20#[cfg(feature = "user_space")]
21use foreign_box::ForeignBox;
22use list::ForeignList;
23use pw_status::{Error, Result};
24use pw_time_core::Instant;
25
26use crate::scheduler::RescheduleReason;
27use crate::scheduler::locks::SchedLockGuard;
28use crate::scheduler::thread::{State, Thread, ThreadListAdapter, ThreadOwner};
29use crate::scheduler::timer::{self, Timer};
30use crate::{Kernel, SchedulerState, SpinLockGuard};
31
32const WAIT_QUEUE_DEBUG: bool = false;
33macro_rules! wait_queue_debug {
34    ($($args:expr),*) => {{
35        log_if::debug_if!(WAIT_QUEUE_DEBUG, $($args),*)
36    }}
37}
38
39pub struct WaitQueue<K: Kernel> {
40    pub(super) queue: ForeignList<Thread<K>, ThreadListAdapter<K>>,
41}
42
43unsafe impl<K: Kernel> Sync for WaitQueue<K> {}
44unsafe impl<K: Kernel> Send for WaitQueue<K> {}
45
46impl<K: Kernel> WaitQueue<K> {
47    #[allow(dead_code, clippy::new_without_default)]
48    #[must_use]
49    pub const fn new() -> Self {
50        Self {
51            queue: ForeignList::new(),
52        }
53    }
54}
55
56#[derive(Clone, Copy, Eq, PartialEq)]
57#[repr(u8)]
58pub enum WaitType {
59    // These variant values must mirror the values in thread `State` so conversions
60    // from WaitType to State can be optimized out.
61    Interruptible = 6,
62    NonInterruptible = 7,
63}
64
65const _: () = assert!(WaitType::Interruptible as u8 == State::WaitingInterruptible as u8);
66const _: () = assert!(WaitType::NonInterruptible as u8 == State::WaitingNonInterruptible as u8);
67
68impl From<WaitType> for State {
69    fn from(value: WaitType) -> Self {
70        // Note: Since the values align (see above) this is optimized out.
71        match value {
72            WaitType::Interruptible => State::WaitingInterruptible,
73            WaitType::NonInterruptible => State::WaitingNonInterruptible,
74        }
75    }
76}
77
78#[derive(Clone, Copy, Eq, PartialEq)]
79pub enum WakeResult {
80    Woken,
81    QueueEmpty,
82}
83
84/// A list of threads dequeued from a wait queue that are not yet runnable.
85///
86/// Dequeuing into a `WakeList` allows a caller to release all references to a
87/// wait queue (or an object embedding it, like a stack-allocated event) before
88/// the woken threads are made runnable and can destroy that storage.
89///
90/// Use [`WakeList::wake_and_reschedule`] to make the threads runnable.
91#[must_use = "threads in a WakeList are not runnable until they are woken"]
92pub struct WakeList<K: Kernel> {
93    threads: ForeignList<Thread<K>, ThreadListAdapter<K>>,
94}
95
96impl<K: Kernel> WakeList<K> {
97    pub const fn new() -> Self {
98        Self {
99            threads: ForeignList::new(),
100        }
101    }
102
103    #[must_use]
104    pub fn is_empty(&self) -> bool {
105        self.threads.is_empty()
106    }
107
108    pub(super) fn push(&mut self, thread: ForeignBox<Thread<K>>) {
109        self.threads.push_back(thread);
110    }
111
112    /// Makes all threads in the list runnable and reschedules if any were woken.
113    pub fn wake_and_reschedule<'a>(
114        mut self,
115        kernel: K,
116        mut sched: SpinLockGuard<'a, K, SchedulerState<K>>,
117    ) -> SpinLockGuard<'a, K, SchedulerState<K>> {
118        use crate::scheduler::algorithm::SchedulerAlgorithmInterface as _;
119
120        let mut woke_any = false;
121        while let Some(thread) = self.threads.pop_head() {
122            wait_queue_debug!(
123                "WakeList: waking thread '{}' ({:#010x})",
124                thread.name as &str,
125                thread.id() as usize
126            );
127            sched
128                .algorithm
129                .schedule_thread(thread, RescheduleReason::Woken);
130            woke_any = true;
131        }
132
133        if woke_any {
134            sched.try_reschedule(kernel, RescheduleReason::Preempted)
135        } else {
136            sched
137        }
138    }
139}
140
141impl<K: Kernel> Default for WakeList<K> {
142    fn default() -> Self {
143        Self::new()
144    }
145}
146
147impl<K: Kernel> WaitQueue<K> {
148    /// Removes the head of the wait queue and marks it ready, without scheduling it.
149    fn pop_head_to_wake(&mut self) -> Option<ForeignBox<Thread<K>>> {
150        let mut thread = self.queue.pop_head()?;
151        wait_queue_debug!(
152            "WaitQueue: dequeuing thread '{}' ({:#010x})",
153            thread.name as &str,
154            thread.id() as usize
155        );
156        thread.state = State::Ready;
157        thread.owner = ThreadOwner::WakeList;
158        Some(thread)
159    }
160
161    /// Dequeues the head of the wait queue into `list` without making it runnable.
162    pub(super) fn dequeue_one(&mut self, list: &mut WakeList<K>) -> WakeResult {
163        let Some(thread) = self.pop_head_to_wake() else {
164            return WakeResult::QueueEmpty;
165        };
166        list.push(thread);
167        WakeResult::Woken
168    }
169
170    /// Dequeues all threads from the wait queue into `list` without making them runnable.
171    pub(super) fn dequeue_all(&mut self, list: &mut WakeList<K>) -> WakeResult {
172        let mut woke_any = WakeResult::QueueEmpty;
173        while let Some(thread) = self.pop_head_to_wake() {
174            list.push(thread);
175            woke_any = WakeResult::Woken;
176        }
177        woke_any
178    }
179}
180
181impl<K: Kernel> SchedLockGuard<'_, '_, K, WaitQueue<K>> {
182    fn add_to_queue_and_reschedule(
183        mut self,
184        mut thread: ForeignBox<Thread<K>>,
185        wait_type: WaitType,
186    ) -> Self {
187        let current_thread_id = thread.id();
188        let current_thread_name = thread.name;
189        let new_state = wait_type.into();
190        thread.state = new_state;
191        thread.owner = ThreadOwner::WaitQueue {
192            queue: NonNull::from_ref(&self),
193            wait_type,
194        };
195        self.queue.push_back(thread);
196        wait_queue_debug!(
197            "WaitQueue: thread '{}' ({:#010x}) rescheduling",
198            current_thread_name as &str,
199            current_thread_id as usize
200        );
201        self.block(current_thread_id, new_state)
202    }
203
204    // Safety:
205    // Caller guarantees that thread is non-null, valid, and process_timeout
206    // has exclusive access to `waiting_thread`.
207    unsafe fn process_timeout(&mut self, waiting_thread: *mut Thread<K>) -> Option<Error> {
208        use crate::scheduler::algorithm::SchedulerAlgorithmInterface as _;
209
210        if !(unsafe { (*waiting_thread).state }.is_waiting()) {
211            // Thread has already been woken.
212            return None;
213        }
214
215        let Some(mut thread) = (unsafe {
216            self.queue
217                .remove_element(NonNull::new_unchecked(waiting_thread))
218        }) else {
219            pw_assert::panic!("Thread no longer in wait queue");
220        };
221
222        wait_queue_debug!(
223            "WaitQueue: timeout for thread '{}' ({:#010x})",
224            thread.name as &str,
225            thread.id() as usize
226        );
227        thread.state = State::Ready;
228        self.sched_mut()
229            .algorithm
230            .schedule_thread(thread, RescheduleReason::Woken);
231        Some(Error::DeadlineExceeded)
232    }
233
234    #[allow(clippy::return_self_not_must_use, clippy::must_use_candidate)]
235    pub fn wait(mut self, wait_type: WaitType) -> (Self, Result<()>) {
236        // If the current thread is terminating and this is an interruptible wait,
237        // return early with an error.
238        if self.sched().current_thread().terminating && wait_type == WaitType::Interruptible {
239            return (self, Err(Error::Cancelled));
240        }
241
242        let thread = self.sched_mut().take_current_thread();
243        wait_queue_debug!(
244            "WaitQueue: thread '{}' ({:#010x}) waiting",
245            thread.name as &str,
246            thread.id() as usize
247        );
248        self = self.add_to_queue_and_reschedule(thread, wait_type);
249        wait_queue_debug!(
250            "WaitQueue: thread '{}' ({:#010x}) resumed",
251            self.sched().current_thread_name() as &str,
252            self.sched().current_thread_id() as usize
253        );
254
255        // Return `Error::Cancelled` if the wait was interrupted because this
256        // thread was terminated while it was waiting.
257        if self.sched().current_thread().terminating && wait_type == WaitType::Interruptible {
258            (self, Err(Error::Cancelled))
259        } else {
260            (self, Ok(()))
261        }
262    }
263
264    pub fn wait_until(
265        mut self,
266        wait_type: WaitType,
267        deadline: Instant<K::Clock>,
268    ) -> (Self, Result<()>) {
269        // If the current thread is terminating and this is an interruptible wait,
270        // return early with an error.
271        if self.sched().current_thread().terminating && wait_type == WaitType::Interruptible {
272            return (self, Err(Error::Cancelled));
273        }
274
275        let mut thread = self.sched_mut().take_current_thread();
276        wait_queue_debug!(
277            "WaitQueue: thread '{}' ({:#010x}) wait_until",
278            thread.name as &str,
279            thread.id() as usize
280        );
281
282        // Smuggle references to the thread and wait queue into the callback.
283        // Safety:
284        // * The thread will always be active for the lifetime of the wait as
285        //   it can not be joined while in a WaitQueue.
286        // * The wait queue will outlive the callback because it will either
287        //   fire while the thread is in the wait queue or will be the timer
288        //   will be canceled before this function returns.
289        // * All access to thread_ptr and wait_queue_ptr in the callback are
290        //   done while the wait queue lock is held.
291        let thread_ptr = unsafe { thread.as_mut_ptr() };
292        let smuggled_wait_queue = unsafe { self.smuggle() };
293
294        // Safety:
295        // * Only accessed while the wait_queue_lock is held;
296        let result: UnsafeCell<Result<()>> = UnsafeCell::new(Ok(()));
297        let result_ptr = result.get();
298
299        // Timeout callback will remove the thread from the wait queue and put
300        // it back on the run queue.
301        let mut callback_closure = move |_kernel, callback: ForeignBox<Timer<K>>, _now| {
302            // Safety: wait queue lock is valid for the lifetime of the callback.
303            let mut wait_queue = unsafe { smuggled_wait_queue.lock() };
304
305            // Safety: the wait queue lock protects access to the thread.
306            wait_queue_debug!(
307                "WaitQueue: timeout callback for thread '{}' ({:#010x}) (state: {})",
308                unsafe { (*thread_ptr).name } as &str,
309                (unsafe { (*thread_ptr).id() }) as usize,
310                unsafe { crate::scheduler::thread::to_string((*thread_ptr).state) } as &str
311            );
312
313            // Safety: We know that thread_ptr is valid for the life of `wait_until`
314            // and this callback will either be called or canceled before `wait_until`
315            // returns.
316            if let Some(error) = unsafe { wait_queue.process_timeout(thread_ptr) } {
317                // Safety: Acquisition of the wait queue lock at the beginning of
318                // the callback ensures mutual exclusion with accesses from the
319                // body of `wait_until`.
320                unsafe { result_ptr.write_volatile(Err(error)) };
321            }
322
323            let _ = callback.consume();
324            None // Don't re-arm
325        };
326
327        let mut callback = Timer::new(deadline, unsafe {
328            ForeignBox::new_from_ptr(&raw mut callback_closure)
329        });
330        let callback_ptr = &raw mut callback;
331        timer::schedule_timer(self.kernel, unsafe {
332            ForeignBox::new_from_ptr(callback_ptr)
333        });
334
335        // Safety: It is important hold on to the WaitQueue lock that is returned
336        // from reschedule as the pointers needed by the timer canceling code
337        // below rely on it for correctness.
338        self = self.add_to_queue_and_reschedule(thread, wait_type);
339
340        wait_queue_debug!(
341            "WaitQueue: thread '{}' ({:#010x}) resumed",
342            self.sched().current_thread_name() as &str,
343            self.sched().current_thread_id() as usize
344        );
345
346        // Cancel timeout callback if has not already fired.
347        //
348        // Safety: callback_ptr is valid until callback goes out of scope.
349        unsafe {
350            timer::cancel_and_consume_timer(self.kernel, NonNull::new_unchecked(callback_ptr))
351        };
352
353        wait_queue_debug!(
354            "WaitQueue: thread '{}' ({:#010x}) exiting wait_until",
355            self.sched().current_thread_name() as &str,
356            self.sched().current_thread_id() as usize
357        );
358
359        // Safety:
360        //
361        // At this point the thread will be in the run queue by virtue of
362        // `reschedule()` return and the timer callback will have fired or be
363        // canceled.  This leaves no dangling references to our "smuggled"
364        // pointers.
365        //
366        // It is also now safe to read the result UnsafeCell
367
368        // Return `Error::Cancelled` if the wait was interrupted because this
369        // thread was terminated while it was waiting.
370        if self.sched().current_thread().terminating && wait_type == WaitType::Interruptible {
371            (self, Err(Error::Cancelled))
372        } else {
373            (self, unsafe { result.get().read_volatile() })
374        }
375    }
376}