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

kernel/scheduler/
locks.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::ops::{Deref, DerefMut};
17use core::ptr::NonNull;
18
19use pw_status::Result;
20use pw_time_core::Instant;
21
22use crate::Kernel;
23use crate::scheduler::thread::State;
24use crate::scheduler::{SchedulerState, WaitQueue, WaitType};
25use crate::sync::spinlock::SpinLockGuard;
26
27pub struct SmuggledSchedLock<K, T> {
28    inner: NonNull<T>,
29    kernel: K,
30}
31
32impl<K: Kernel, T> SmuggledSchedLock<K, T> {
33    /// # Safety
34    /// The caller must guarantee that the underlying lock and it's enclosed data
35    /// is still valid.
36    // The `'static` lifetime applies to `'sched`, which is sound because
37    // `Kernel::get_scheduler()` returns a `&'static SpinLock`.
38    pub unsafe fn lock(&self) -> SchedLockGuard<'_, 'static, K, T> {
39        let guard = self.kernel.get_scheduler().lock(self.kernel);
40        SchedLockGuard {
41            guard,
42            inner: unsafe { &mut *self.inner.as_ptr() },
43            kernel: self.kernel,
44        }
45    }
46}
47
48pub struct SchedLockGuard<'lock, 'sched, K: Kernel, T> {
49    guard: SpinLockGuard<'sched, K, SchedulerState<K>>,
50    inner: &'lock mut T,
51    pub(super) kernel: K,
52}
53
54impl<'lock, 'sched, K: Kernel, T> SchedLockGuard<'lock, 'sched, K, T> {
55    #[must_use]
56    pub fn sched(&self) -> &SpinLockGuard<'sched, K, SchedulerState<K>> {
57        &self.guard
58    }
59
60    #[must_use]
61    pub fn sched_mut(&mut self) -> &mut SpinLockGuard<'sched, K, SchedulerState<K>> {
62        &mut self.guard
63    }
64
65    #[must_use]
66    pub fn block(self, current_thread_id: usize, current_thead_state: State) -> Self {
67        let inner = self.inner;
68        let kernel = self.kernel;
69        let guard = super::block(kernel, self.guard, current_thread_id, current_thead_state);
70        Self {
71            guard,
72            inner,
73            kernel,
74        }
75    }
76
77    /// # Safety
78    /// The caller must guarantee that the underlying lock remains valid and
79    /// un-moved for the live the smuggled lock.
80    #[must_use]
81    pub unsafe fn smuggle(&self) -> SmuggledSchedLock<K, T> {
82        let inner: *const T = self.inner;
83        SmuggledSchedLock {
84            inner: unsafe { NonNull::new_unchecked(inner.cast_mut()) },
85            kernel: self.kernel,
86        }
87    }
88}
89
90impl<K: Kernel, T> Deref for SchedLockGuard<'_, '_, K, T> {
91    type Target = T;
92
93    fn deref(&self) -> &T {
94        self.inner
95    }
96}
97
98impl<K: Kernel, T> DerefMut for SchedLockGuard<'_, '_, K, T> {
99    fn deref_mut(&mut self) -> &mut T {
100        self.inner
101    }
102}
103
104/// An owning lock that shares the global scheduler lock.
105///
106/// A [`SchedLockGuard`] can be turned into a `SpinLockGuard<'sched, SchedulerState>`
107/// so that it can be passed to `reschedule()`
108///
109/// # Safety
110/// Taking two different `SchedLock`s at the same time will deadlock as they
111/// share the same underlying lock.
112pub struct SchedLock<K, T> {
113    inner: UnsafeCell<T>,
114    kernel: K,
115}
116unsafe impl<K: Sync, T> Sync for SchedLock<K, T> {}
117unsafe impl<K: Send, T> Send for SchedLock<K, T> {}
118
119impl<K, T> SchedLock<K, T> {
120    pub const fn new(kernel: K, initial_value: T) -> Self {
121        Self {
122            inner: UnsafeCell::new(initial_value),
123            kernel,
124        }
125    }
126}
127
128impl<K: Kernel, T> SchedLock<K, T> {
129    // The `'static` lifetime applies to `'sched`, which is sound because
130    // `Kernel::get_scheduler()` returns a `&'static SpinLock`.
131    #[allow(unused)]
132    pub fn try_lock(&self) -> Option<SchedLockGuard<'_, 'static, K, T>> {
133        // Safety: The lock guarantees
134        self.kernel
135            .get_scheduler()
136            .try_lock(self.kernel)
137            .map(|guard| SchedLockGuard {
138                inner: unsafe { &mut *self.inner.get() },
139                guard,
140                kernel: self.kernel,
141            })
142    }
143
144    // The `'static` lifetime applies to `'sched`, which is sound because
145    // `Kernel::get_scheduler()` returns a `&'static SpinLock`.
146    pub fn lock(&self) -> SchedLockGuard<'_, 'static, K, T> {
147        let guard = self.kernel.get_scheduler().lock(self.kernel);
148        SchedLockGuard {
149            inner: unsafe { &mut *self.inner.get() },
150            guard,
151            kernel: self.kernel,
152        }
153    }
154}
155
156pub struct WaitQueueLockState<K: Kernel, T> {
157    queue: WaitQueue<K>,
158    inner: T,
159}
160
161pub struct WaitQueueLock<K: Kernel, T> {
162    state: SchedLock<K, WaitQueueLockState<K, T>>,
163}
164
165impl<K: Kernel, T> WaitQueueLock<K, T> {
166    pub const fn new(kernel: K, initial_value: T) -> Self {
167        Self {
168            state: SchedLock::new(
169                kernel,
170                WaitQueueLockState {
171                    queue: WaitQueue::new(),
172                    inner: initial_value,
173                },
174            ),
175        }
176    }
177
178    // The `'static` lifetime applies to `'sched`, which is sound because
179    // `SchedLock::lock()` locks the `&'static SpinLock` from `Kernel::get_scheduler()`.
180    pub fn lock(&self) -> WaitQueueLockGuard<'_, 'static, K, T> {
181        WaitQueueLockGuard {
182            inner: self.state.lock(),
183        }
184    }
185
186    pub(crate) fn inherit_sched_lock<'lock, 'sched>(
187        &'lock self,
188        guard: SpinLockGuard<'sched, K, SchedulerState<K>>,
189    ) -> WaitQueueLockGuard<'lock, 'sched, K, T> {
190        WaitQueueLockGuard {
191            inner: SchedLockGuard {
192                inner: unsafe { &mut *self.state.inner.get() },
193                guard,
194                kernel: self.state.kernel,
195            },
196        }
197    }
198}
199
200pub struct WaitQueueLockGuard<'lock, 'sched, K: Kernel, T> {
201    inner: SchedLockGuard<'lock, 'sched, K, WaitQueueLockState<K, T>>,
202}
203
204impl<'lock, 'sched, K: Kernel, T> WaitQueueLockGuard<'lock, 'sched, K, T> {
205    pub fn sched(&self) -> &SpinLockGuard<'sched, K, SchedulerState<K>> {
206        &self.inner.guard
207    }
208
209    pub fn into_sched(self) -> SpinLockGuard<'sched, K, SchedulerState<K>> {
210        self.inner.guard
211    }
212
213    #[allow(dead_code)]
214    pub fn sched_mut(&mut self) -> &mut SpinLockGuard<'sched, K, SchedulerState<K>> {
215        &mut self.inner.guard
216    }
217
218    #[must_use]
219    pub fn operate_on_wait_queue<F, R>(mut self, f: F) -> (Self, R)
220    where
221        F: FnOnce(
222            SchedLockGuard<'lock, 'sched, K, WaitQueue<K>>,
223        ) -> (SchedLockGuard<'lock, 'sched, K, WaitQueue<K>>, R),
224    {
225        let guard = SchedLockGuard::<'lock, 'sched, _, WaitQueue<K>> {
226            guard: self.inner.guard,
227            // Safety: Mutable reference only lives as long as the call into f()
228            #[allow(clippy::deref_addrof)]
229            inner: unsafe { &mut *&raw mut self.inner.inner.queue },
230            kernel: self.inner.kernel,
231        };
232        let (guard, result) = f(guard);
233        self.inner.guard = guard.guard;
234        (self, result)
235    }
236
237    pub fn wait_until(
238        self,
239        wait_type: WaitType,
240        deadline: Instant<K::Clock>,
241    ) -> (Self, Result<()>) {
242        self.operate_on_wait_queue(|guard| guard.wait_until(wait_type, deadline))
243    }
244
245    pub fn wait(self, wait_type: WaitType) -> (Self, Result<()>) {
246        self.operate_on_wait_queue(|guard| guard.wait(wait_type))
247    }
248
249    /// Wakes all threads in `wake_list` and reschedules if needed.
250    pub fn wake_list_and_reschedule(
251        self,
252        wake_list: super::WakeList<K>,
253    ) -> SpinLockGuard<'sched, K, SchedulerState<K>> {
254        let kernel = self.inner.kernel;
255        let sched = self.into_sched();
256        wake_list.wake_and_reschedule(kernel, sched)
257    }
258
259    /// Dequeues and wakes one waiter, rescheduling if needed.
260    pub fn wake_one_and_reschedule(mut self) -> SpinLockGuard<'sched, K, SchedulerState<K>> {
261        let mut wake_list = super::WakeList::new();
262        let _ = self.dequeue_one(&mut wake_list);
263        self.wake_list_and_reschedule(wake_list)
264    }
265
266    /// Dequeues and wakes all waiters, rescheduling if needed.
267    pub fn wake_all_and_reschedule(mut self) -> SpinLockGuard<'sched, K, SchedulerState<K>> {
268        let mut wake_list = super::WakeList::new();
269        let _ = self.dequeue_all(&mut wake_list);
270        self.wake_list_and_reschedule(wake_list)
271    }
272
273    /// Dequeues the head of the wait queue into `list` without waking it.
274    pub fn dequeue_one(&mut self, list: &mut super::WakeList<K>) -> super::WakeResult {
275        self.inner.inner.queue.dequeue_one(list)
276    }
277
278    /// Dequeues all threads from the wait queue into `list` without waking them.
279    pub fn dequeue_all(&mut self, list: &mut super::WakeList<K>) -> super::WakeResult {
280        self.inner.inner.queue.dequeue_all(list)
281    }
282}
283
284impl<K: Kernel, T> Deref for WaitQueueLockGuard<'_, '_, K, T> {
285    type Target = T;
286
287    fn deref(&self) -> &T {
288        &self.inner.inner.inner
289    }
290}
291
292impl<K: Kernel, T> DerefMut for WaitQueueLockGuard<'_, '_, K, T> {
293    fn deref_mut(&mut self) -> &mut T {
294        &mut self.inner.inner.inner
295    }
296}