1use 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 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 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 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 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 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 (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 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 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 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
208unsafe impl<K: Kernel, T: Send> Sync for Mutex<K, T> {}
216
217unsafe 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 _marker: PhantomData<*const ()>,
229}
230
231impl<K: Kernel, T> Drop for MutexGuard<'_, K, T> {
232 fn drop(&mut self) {
233 unsafe {
236 self.mutex.raw.unlock();
237 }
238 }
239}
240
241unsafe 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 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 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}