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/sync/mutex.rs

kernel/sync/
mutex.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::marker::PhantomData;
17use core::ops::{Deref, DerefMut};
18
19use pw_status::Result;
20use pw_time_core::Instant;
21
22use crate::Kernel;
23use crate::scheduler::{Thread, WaitQueueLock, WaitType};
24
25const MUTEX_DEBUG: bool = false;
26macro_rules! mutex_debug {
27  ($($args:expr),*) => {{
28    log_if::debug_if!(MUTEX_DEBUG, $($args),*)
29  }}
30}
31
32struct MutexState {
33    count: usize,
34    holder_thread_id: usize,
35}
36
37pub struct RawMutex<K: Kernel> {
38    // An future optimization can be made by keeping an atomic count outside of
39    // the spinlock.  However, not all architectures support atomics so a pure
40    // SchedLock based approach will always be needed.
41    state: WaitQueueLock<K, MutexState>,
42}
43
44impl<K: Kernel> RawMutex<K> {
45    pub const fn new(kernel: K) -> Self {
46        Self {
47            state: WaitQueueLock::new(
48                kernel,
49                MutexState {
50                    count: 0,
51                    holder_thread_id: Thread::<K>::null_id(),
52                },
53            ),
54        }
55    }
56
57    pub fn lock(&self) {
58        let mut state = self.state.lock();
59        pw_assert::ne!(
60            state.holder_thread_id as usize,
61            state.sched().current_thread_id() as usize,
62            "Mutex attempted to be locked by holding thread"
63        );
64
65        #[allow(clippy::needless_else)]
66        if let Some(val) = state.count.checked_add(1) {
67            state.count = val;
68        } else {
69            pw_assert::debug_assert!(false);
70        }
71
72        // TODO - konkers: investigate using core::intrinsics::unlikely() or
73        //                 core::hint::unlikely()
74        if state.count > 1 {
75            mutex_debug!(
76                "Mutex {:#010x}: lock wait by thread '{}' ({:#010x})",
77                &raw const *self as usize,
78                state.sched().current_thread_name() as &str,
79                state.sched().current_thread_id() as usize
80            );
81            // Mutexes use uninterruptible waits because cleaning up a terminating
82            // thread may involve aquisiation of mutex protected resources.
83            let res;
84            (state, res) = state.wait(WaitType::NonInterruptible);
85            pw_assert::debug_assert!(res.is_ok());
86        }
87        mutex_debug!(
88            "Mutex {:#010x}: lock acquired by thread '{}' ({:#010x})",
89            &raw const *self as usize,
90            state.sched().current_thread_name() as &str,
91            state.sched().current_thread_id() as usize
92        );
93
94        state.holder_thread_id = state.sched().current_thread_id();
95    }
96
97    pub fn try_lock(&self) -> bool {
98        let mut state = self.state.lock();
99        if state.count != 0 {
100            return false;
101        }
102        state.count = 1;
103        state.holder_thread_id = state.sched().current_thread_id();
104        true
105    }
106
107    // TODO - konkers: Investigate combining with lock().
108    pub fn lock_until(&self, deadline: Instant<K::Clock>) -> Result<()> {
109        let mut state = self.state.lock();
110
111        #[allow(clippy::needless_else)]
112        if let Some(val) = state.count.checked_add(1) {
113            state.count = val;
114        } else {
115            pw_assert::debug_assert!(false);
116        }
117
118        // TODO - konkers: investigate using core::intrinsics::unlikely() or
119        //                 core::hint::unlikely()
120        if state.count > 1 {
121            let result;
122            mutex_debug!(
123                "Mutex {:#010x}: lock_until({}) wait by thread '{}' ({:#010x})",
124                &raw const *self as usize,
125                deadline.ticks() as u64,
126                state.sched().current_thread_name() as &str,
127                state.sched().current_thread_id() as usize
128            );
129
130            // Mutexes use uninterruptible waits because cleaning up a terminating
131            // thread may involve aquisiation of mutex protected resources.
132            (state, result) = state.wait_until(WaitType::NonInterruptible, deadline);
133
134            if let Err(e) = result {
135                mutex_debug!(
136                    "Mutex {:#010x}: lock_until error: {} for thread '{}' ({:#010x})",
137                    &raw const *self as usize,
138                    e as u32,
139                    state.sched().current_thread_name() as &str,
140                    state.sched().current_thread_id() as usize
141                );
142
143                if let Some(val) = state.count.checked_sub(1) {
144                    state.count = val;
145                } else {
146                    // use assert not debug_assert, as it's possible a
147                    // real bug could trigger this assert,
148                    pw_assert::assert!(false)
149                }
150                return Err(e);
151            }
152        }
153        mutex_debug!(
154            "Mutex {:#010x}: lock_until acquired by thread '{}' ({:#010x})",
155            &raw const *self as usize,
156            state.sched().current_thread_name() as &str,
157            state.sched().current_thread_id() as usize
158        );
159
160        state.holder_thread_id = state.sched().current_thread_id();
161
162        Ok(())
163    }
164
165    /// Unlocks the mutex.
166    ///
167    /// # Safety
168    ///
169    /// The caller must ensure that:
170    /// - The mutex is currently locked.
171    /// - The current thread is the holder of the lock.
172    ///
173    /// # Panics
174    ///
175    /// Panics if:
176    /// - The mutex is not currently locked (`state.count == 0`).
177    /// - The current thread is not the holder of the lock.
178    pub unsafe fn unlock(&self) {
179        let mut state = self.state.lock();
180
181        pw_assert::assert!(state.count > 0);
182        pw_assert::eq!(
183            state.holder_thread_id as usize,
184            state.sched().current_thread_id() as usize
185        );
186        state.holder_thread_id = Thread::<K>::null_id();
187
188        state.count -= 1;
189
190        // TODO - konkers: investigate using core::intrinsics::unlikely() or
191        //                 core::hint::unlikely()
192        //
193        // Unify the guard drop site at function exit to avoid duplicate drop glue.
194        // This saves ~20 bytes of code space.
195        let _sched = if state.count > 0 {
196            state.wake_one_and_reschedule()
197        } else {
198            state.into_sched()
199        };
200    }
201}
202
203pub struct Mutex<K: Kernel, T> {
204    raw: RawMutex<K>,
205    data: UnsafeCell<T>,
206}
207
208// SAFETY: Sharing a `&Mutex<K, T>` across threads allows another thread to obtain
209// exclusive `&mut T` access via `MutexGuard`, which is safe as long as `T: Send`
210// as the Mutex's contract ensure that only one thread had access (mutable or
211// or otherwise to the enclosed data.
212//
213// For more information see:
214// https://doc.rust-lang.org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E
215unsafe impl<K: Kernel, T: Send> Sync for Mutex<K, T> {}
216
217// SAFETY: Moving a `Mutex<K, T>` to another thread transfers ownership of `T`,
218// which is safe as long as `T: Send`.
219//
220// For more information see:
221// https://doc.rust-lang.org/std/sync/struct.Mutex.html#impl-Send-for-Mutex%3CT%3E
222unsafe impl<K: Kernel, T: Send> Send for Mutex<K, T> {}
223
224pub struct MutexGuard<'a, K: Kernel, T> {
225    mutex: &'a Mutex<K, T>,
226    // Implicitly mark MutexGuard as !Send and !Sync.  !Sync is re-implemented
227    // below.  This is a workaround for `negative_impls` being unstable.
228    _marker: PhantomData<*const ()>,
229}
230
231impl<K: Kernel, T> Drop for MutexGuard<'_, K, T> {
232    fn drop(&mut self) {
233        // SAFETY: `MutexGuard` is only created when the current thread successfully
234        // acquires the mutex, so it is safe to unlock the underlying `RawMutex`.
235        unsafe {
236            self.mutex.raw.unlock();
237        }
238    }
239}
240
241// SAFETY: Shared reference access (`&MutexGuard`) provides `&T` through `Deref`,
242// which is safe across threads when `T: Sync`.
243unsafe impl<K: Kernel, T: Sync> Sync for MutexGuard<'_, K, T> {}
244
245impl<K: Kernel, T> Deref for MutexGuard<'_, K, T> {
246    type Target = T;
247
248    fn deref(&self) -> &Self::Target {
249        // SAFETY: The mutex is held for the lifetime of `MutexGuard`, guaranteeing
250        // exclusive access to `data`.  Lifetime of underlying data is tied to
251        // the lifetime of the guard.
252        unsafe { &*self.mutex.data.get() }
253    }
254}
255
256impl<K: Kernel, T> DerefMut for MutexGuard<'_, K, T> {
257    fn deref_mut(&mut self) -> &mut Self::Target {
258        // SAFETY: The mutex is held for the lifetime of `MutexGuard`, guaranteeing
259        // exclusive access to `data`.  Lifetime of underlying data is tied to
260        // the lifetime of the guard.
261        unsafe { &mut *self.mutex.data.get() }
262    }
263}
264
265impl<K: Kernel, T> Mutex<K, T> {
266    pub const fn new(kernel: K, initial_value: T) -> Self {
267        Self {
268            raw: RawMutex::new(kernel),
269            data: UnsafeCell::new(initial_value),
270        }
271    }
272
273    pub fn lock(&self) -> MutexGuard<'_, K, T> {
274        self.raw.lock();
275        MutexGuard {
276            mutex: self,
277            _marker: PhantomData,
278        }
279    }
280
281    pub fn try_lock(&self) -> Option<MutexGuard<'_, K, T>> {
282        self.raw.try_lock().then(|| MutexGuard {
283            mutex: self,
284            _marker: PhantomData,
285        })
286    }
287
288    pub fn lock_until(&self, deadline: Instant<K::Clock>) -> Result<MutexGuard<'_, K, T>> {
289        self.raw.lock_until(deadline).map(|()| MutexGuard {
290            mutex: self,
291            _marker: PhantomData,
292        })
293    }
294}