1use 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 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 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#[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 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 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 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 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 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 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 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 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 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 let thread_ptr = unsafe { thread.as_mut_ptr() };
292 let smuggled_wait_queue = unsafe { self.smuggle() };
293
294 let result: UnsafeCell<Result<()>> = UnsafeCell::new(Ok(()));
297 let result_ptr = result.get();
298
299 let mut callback_closure = move |_kernel, callback: ForeignBox<Timer<K>>, _now| {
302 let mut wait_queue = unsafe { smuggled_wait_queue.lock() };
304
305 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 if let Some(error) = unsafe { wait_queue.process_timeout(thread_ptr) } {
317 unsafe { result_ptr.write_volatile(Err(error)) };
321 }
322
323 let _ = callback.consume();
324 None };
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 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 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 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}