strat9_kernel/sync/spinlock.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Generic spinlock with configurable guard behaviour.
24//!
25//! # Choosing a guardian
26//!
27//! ```text
28//! SpinLock<T> => SpinLock<T, IrqDisabled> (default)
29//! SpinLock<T, IrqDisabled> => saves RFLAGS + clears IF (equiv. spin_lock_irqsave)
30//! SpinLock<T, PreemptDisabled> => disables preemption only, IRQs untouched
31//! ```
32//!
33//! **Use `IrqDisabled` (the default) for**:
34//! - Data shared across CPUs (heap, VFS, IPC queues, network rings, …)
35//! - Any data touched from interrupt handlers
36//!
37//! **Use `PreemptDisabled` for**:
38//! - Per-CPU data never accessed from interrupt handlers
39//! (scheduler run-queues, per-CPU frame caches, statistics counters …)
40//!
41//! All call sites that use `SpinLock<T>` without a type argument continue to
42//! compile unchanged : `IrqDisabled` is the default guardian.
43//!
44//! # Debug helpers
45//!
46//! `debug_set_watch_lock_addr` / `debug_clear_watch_lock_addr` emit a serial
47//! trace on every `drop` of a specific lock instance : useful when hunting
48//! deadlocks.
49
50use super::{
51 guardian::{Guardian, GuardianState, IrqDisabled},
52 IrqDisabledToken,
53};
54use core::{
55 cell::UnsafeCell,
56 marker::PhantomData,
57 mem::ManuallyDrop,
58 ops::{Deref, DerefMut},
59 sync::atomic::{AtomicBool, AtomicUsize, Ordering},
60};
61
62static DEBUG_WATCH_LOCK_ADDR: AtomicUsize = AtomicUsize::new(usize::MAX);
63
64// =========================== SpinLock ========================================
65
66/// A spinlock parameterised by a [`Guardian`].
67///
68/// The default guardian is [`IrqDisabled`], preserving existing call-site
69/// semantics with no source changes required.
70///
71/// Supports `T: ?Sized` for `SpinLock<dyn Trait>` and other DST types.
72/// The `data` field is last so that the struct can hold dynamically sized types.
73pub struct SpinLock<T: ?Sized, G: Guardian = IrqDisabled> {
74 locked: AtomicBool,
75 /// CPU index of the current lock holder (`usize::MAX` when unlocked).
76 /// Used for deadlock diagnostics only.
77 owner_cpu: AtomicUsize,
78 _guardian: PhantomData<G>,
79 /// Must be the last field: when `T: ?Sized`, this is a DST and Rust
80 /// requires the dynamically sized field to be last in the struct.
81 data: UnsafeCell<T>,
82}
83
84// SAFETY: The guardian ensures mutual exclusion; T must itself be Send.
85unsafe impl<T: ?Sized + Send, G: Guardian> Sync for SpinLock<T, G> {}
86unsafe impl<T: ?Sized + Send, G: Guardian> Send for SpinLock<T, G> {}
87
88impl<T, G: Guardian> SpinLock<T, G> {
89 /// Create a new, unlocked spinlock.
90 ///
91 /// `T` must be `Sized` here because we construct a new value.
92 pub const fn new(data: T) -> Self {
93 SpinLock {
94 locked: AtomicBool::new(false),
95 owner_cpu: AtomicUsize::new(usize::MAX),
96 _guardian: PhantomData,
97 data: UnsafeCell::new(data),
98 }
99 }
100}
101
102impl<T: ?Sized, G: Guardian> SpinLock<T, G> {
103 /// Acquire the lock, spinning until available.
104 ///
105 /// The guardian's `enter()` hook runs **before** the spin loop so that the
106 /// CPU is already in the protected mode while we wait. This closes the
107 /// window where an IRQ or preempt-switch could occur between protect and
108 /// acquire.
109 pub fn lock(&self) -> SpinLockGuard<'_, T, G> {
110 let state = G::enter();
111 let mut spins: usize = 0;
112 let this_cpu = crate::arch::percpu::current_cpu_index();
113
114 while self
115 .locked
116 .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
117 .is_err()
118 {
119 spins = spins.saturating_add(1);
120 if spins == 5_000_000 {
121 let owner = self.owner_cpu.load(Ordering::Relaxed);
122 crate::serial_println!(
123 "[trace][spin] long-wait lock={:#x} cpu={} owner_cpu={}",
124 self as *const _ as *const () as usize,
125 this_cpu,
126 owner,
127 );
128 spins = 0;
129 }
130 // A CPU spinning here with IRQs disabled cannot run its TLB
131 // shootdown IPI handler; service the local mailbox so an initiator
132 // waiting on us does not time out (see tlb::service_pending_local).
133 crate::arch::service_pending_tlb_local();
134 core::hint::spin_loop();
135 }
136 self.owner_cpu.store(this_cpu, Ordering::Relaxed);
137 // Race/corruption diagnostic: E9 trace when watched locks are acquired.
138 emit_trace_e9(self as *const _ as *const () as usize, 0);
139
140 SpinLockGuard {
141 lock: self,
142 state: ManuallyDrop::new(state),
143 }
144 }
145
146 /// Try to acquire the lock without spinning.
147 pub fn try_lock(&self) -> Option<SpinLockGuard<'_, T, G>> {
148 let state = G::enter();
149 if self
150 .locked
151 .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
152 .is_ok()
153 {
154 let this_cpu = crate::arch::percpu::current_cpu_index();
155 self.owner_cpu.store(this_cpu, Ordering::Relaxed);
156 emit_trace_e9(self as *const _ as *const () as usize, 0);
157 Some(SpinLockGuard {
158 lock: self,
159 state: ManuallyDrop::new(state),
160 })
161 } else {
162 G::exit(state);
163 None
164 }
165 }
166
167 /// Returns the owner CPU index (`usize::MAX` if unlocked).
168 pub fn owner_cpu(&self) -> usize {
169 self.owner_cpu.load(Ordering::Relaxed)
170 }
171
172 /// Returns a mutable reference to the underlying data.
173 ///
174 /// By holding `&mut self`, the compiler guarantees exclusive access to the
175 /// lock; no other reference exists, so the inner data can be accessed
176 /// without acquiring the lock.
177 pub fn get_mut(&mut self) -> &mut T {
178 self.data.get_mut()
179 }
180}
181
182// =========================== IrqDisabled-specific extensions
183
184impl<T: ?Sized> SpinLock<T, IrqDisabled> {
185 /// Try to acquire without touching RFLAGS.
186 ///
187 /// Returns `None` if IRQs are currently enabled (no `IrqDisabledToken` can
188 /// be produced) or the lock is already held. The caller must ensure that
189 /// IRQs remain disabled for the entire lifetime of the returned guard.
190 pub fn try_lock_no_irqsave(&self) -> Option<SpinLockGuard<'_, T, IrqDisabled>> {
191 let token = match IrqDisabledToken::verify() {
192 Some(token) => token,
193 None => {
194 // Diagnostic only: distinguish "IRQs enabled" from ordinary
195 // lock contention at call sites that intentionally treat both
196 // as a best-effort `None` return in hot paths.
197 // F10: ring-0 port I/O compiled out under kernel_l2_host.
198 #[cfg(all(not(kernel_l2_host), target_arch = "x86_64"))]
199 unsafe {
200 core::arch::asm!("mov al, 'V'; out 0xe9, al", out("al") _)
201 };
202 #[cfg(any(kernel_l2_host, target_arch = "riscv64"))]
203 let _ = 0u8;
204 return None;
205 }
206 };
207 if self
208 .locked
209 .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
210 .is_ok()
211 {
212 let this_cpu = crate::arch::percpu::current_cpu_index();
213 self.owner_cpu.store(this_cpu, Ordering::Relaxed);
214 emit_trace_e9(self as *const _ as *const () as usize, 0);
215 Some(SpinLockGuard {
216 lock: self,
217 state: ManuallyDrop::new(GuardianState {
218 token,
219 saved_flags: 0,
220 restore_flags: false,
221 }),
222 })
223 } else {
224 None
225 }
226 }
227}
228
229// =========================== Debug helpers ====================================
230
231/// Register a lock address to trace on every drop (serial console output).
232pub fn debug_set_watch_lock_addr(addr: usize) {
233 DEBUG_WATCH_LOCK_ADDR.store(addr, Ordering::Relaxed);
234}
235
236/// Clear the watched lock address.
237pub fn debug_clear_watch_lock_addr() {
238 DEBUG_WATCH_LOCK_ADDR.store(usize::MAX, Ordering::Relaxed);
239}
240
241/// Maximum number of locks that can be traced simultaneously via E9 port.
242const DEBUG_TRACE_WATCH_SLOTS: usize = 8;
243
244/// Fixed-size array of watched lock addresses for E9 trace.
245/// Each slot emits a unique ASCII tag ('A'..'H') on acquire/release.
246static DEBUG_TRACE_WATCH_ADDRS: [AtomicUsize; DEBUG_TRACE_WATCH_SLOTS] =
247 [const { AtomicUsize::new(usize::MAX) }; DEBUG_TRACE_WATCH_SLOTS];
248
249/// Register a lock address for E9 trace. Returns the slot index (0..7),
250/// or `None` if all slots are in use.
251pub fn debug_set_trace_lock_addr(addr: usize) -> Option<usize> {
252 // Disabled by default: with no registered slot, acquire/release emit nothing.
253 if !crate::debug_cfg::E9_TRACE_LOCKS {
254 return None;
255 }
256 for (i, slot) in DEBUG_TRACE_WATCH_ADDRS.iter().enumerate() {
257 if slot.load(Ordering::Relaxed) == usize::MAX {
258 slot.store(addr, Ordering::Relaxed);
259 return Some(i);
260 }
261 }
262 None
263}
264
265/// Clear a specific trace slot by index.
266#[allow(dead_code)] // Retained lock-trace maintenance helper.
267pub fn debug_clear_trace_slot(index: usize) {
268 if index < DEBUG_TRACE_WATCH_SLOTS {
269 DEBUG_TRACE_WATCH_ADDRS[index].store(usize::MAX, Ordering::Relaxed);
270 }
271}
272
273/// Legacy alias: register the first available trace slot.
274pub fn debug_set_trace_buddy_addr(addr: usize) {
275 let _ = debug_set_trace_lock_addr(addr);
276}
277
278/// Legacy alias: register the first available trace slot.
279pub fn debug_set_trace_slab_addr(addr: usize) {
280 let _ = debug_set_trace_lock_addr(addr);
281}
282
283/// Emit an E9 byte for each matching trace slot (acquire = uppercase, release = lowercase).
284#[inline]
285fn emit_trace_e9(lock_addr: usize, tag_offset: u8) {
286 if !crate::debug_cfg::E9_TRACE_LOCKS {
287 return;
288 }
289 for (i, slot) in DEBUG_TRACE_WATCH_ADDRS.iter().enumerate() {
290 if slot.load(Ordering::Relaxed) == lock_addr {
291 let ch = b'A' + tag_offset + (i as u8);
292 // L2 host harness (testing-findings.md F10): `out 0xe9` is ring-0
293 // port I/O; executing it from userspace faults with SIGSEGV.
294 // Compiled out only under the kernel-l2-tests harness cfg;
295 // production behavior is unchanged.
296 #[cfg(all(not(kernel_l2_host), target_arch = "x86_64"))]
297 unsafe {
298 core::arch::asm!("out 0xe9, al", in("al") ch)
299 };
300 #[cfg(any(kernel_l2_host, target_arch = "riscv64"))]
301 let _ = ch;
302 }
303 }
304}
305
306// =========================== SpinLockGuard ====================================
307
308/// RAII guard that holds the lock and carries the guardian state.
309pub struct SpinLockGuard<'a, T: ?Sized, G: Guardian = IrqDisabled> {
310 lock: &'a SpinLock<T, G>,
311 /// Wrapped in ManuallyDrop so that `Drop::drop` can move it into
312 /// `G::exit()` without triggering a compiler-generated second drop of
313 /// the field.
314 state: ManuallyDrop<GuardianState<G::Token>>,
315}
316
317impl<'a, T: ?Sized> SpinLockGuard<'a, T, IrqDisabled> {
318 /// Return the typed proof that IRQs are disabled.
319 #[inline]
320 pub fn token(&self) -> &IrqDisabledToken {
321 &self.state.token
322 }
323
324 #[inline]
325 pub(crate) fn with_mut_and_token<R>(
326 &mut self,
327 f: impl FnOnce(&mut T, &IrqDisabledToken) -> R,
328 ) -> R {
329 let token = &self.state.token;
330 // SAFETY: this guard owns the lock, guaranteeing exclusive access.
331 let data = unsafe { &mut *self.lock.data.get() };
332 f(data, token)
333 }
334}
335
336impl<'a, T: ?Sized, G: Guardian> Deref for SpinLockGuard<'a, T, G> {
337 type Target = T;
338
339 fn deref(&self) -> &T {
340 // SAFETY: we hold the lock.
341 unsafe { &*self.lock.data.get() }
342 }
343}
344
345impl<'a, T: ?Sized, G: Guardian> DerefMut for SpinLockGuard<'a, T, G> {
346 fn deref_mut(&mut self) -> &mut T {
347 // SAFETY: we hold the lock.
348 unsafe { &mut *self.lock.data.get() }
349 }
350}
351
352impl<'a, T: ?Sized, G: Guardian> Drop for SpinLockGuard<'a, T, G> {
353 fn drop(&mut self) {
354 let lock_addr = self.lock as *const _ as *const () as usize;
355 let watched = DEBUG_WATCH_LOCK_ADDR.load(Ordering::Relaxed);
356 let trace = watched == lock_addr;
357
358 if trace {
359 crate::serial_force_println!(
360 "[trace][spin] drop begin lock={:#x} owner_cpu={} saved_flags={:#x}",
361 lock_addr,
362 self.lock.owner_cpu.load(Ordering::Relaxed),
363 self.state.saved_flags,
364 );
365 }
366
367 self.lock.owner_cpu.store(usize::MAX, Ordering::Relaxed);
368 self.lock.locked.store(false, Ordering::Release);
369
370 if trace {
371 crate::serial_force_println!("[trace][spin] drop unlocked lock={:#x}", lock_addr);
372 }
373 // Race/corruption diagnostic: E9 trace when watched locks are released.
374 // Use lowercase tags to distinguish release from acquire.
375 for (i, slot) in DEBUG_TRACE_WATCH_ADDRS.iter().enumerate() {
376 if !crate::debug_cfg::E9_TRACE_LOCKS {
377 break;
378 }
379 if slot.load(Ordering::Relaxed) == lock_addr {
380 let ch = b'a' + (i as u8);
381 // F10: see acquire-side note above.
382 #[cfg(all(not(kernel_l2_host), target_arch = "x86_64"))]
383 unsafe {
384 core::arch::asm!("out 0xe9, al", in("al") ch)
385 };
386 #[cfg(any(kernel_l2_host, target_arch = "riscv64"))]
387 let _ = ch;
388 }
389 }
390
391 // SAFETY: `state` is valid and initialised. We move it out of its
392 // ManuallyDrop wrapper so that G::exit() can consume it. The compiler
393 // will NOT run a second destructor on the field because ManuallyDrop
394 // suppresses automatic drops.
395 let state = unsafe { ManuallyDrop::take(&mut self.state) };
396 G::exit(state);
397
398 if trace {
399 crate::serial_force_println!(
400 "[trace][spin] drop guardian-exit done lock={:#x}",
401 lock_addr
402 );
403 }
404 }
405}
406
407// The guardian's invariant (e.g. preemption depth, IF flag) is per-CPU.
408// Sending the guard to another CPU would violate it.
409impl<T: ?Sized, G: Guardian> !Send for SpinLockGuard<'_, T, G> {}