kernel/sync/spinlock.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};
17
18use crate::scheduler::PreemptDisableGuard;
19use crate::{Arch, Kernel};
20
21/// Controls whether dropping a guard reconstructed via
22/// [`SpinLock::adopt_locked`] re-enables interrupts or keeps them disabled.
23#[derive(Copy, Clone, Debug, Eq, PartialEq)]
24pub enum InterruptsOnDrop {
25 /// Re-enable interrupts after unlocking when the guard is dropped.
26 Restore,
27 /// Leave interrupts disabled after unlocking when the guard is dropped.
28 KeepDisabled,
29}
30
31pub trait BareSpinLock: Send + Sync {
32 type Guard<'a>
33 where
34 Self: 'a;
35
36 const NEW: Self;
37
38 fn try_lock(&self) -> Option<Self::Guard<'_>>;
39
40 // This default implementation of `lock()` will usually be overridden by
41 // architecture-specific implementations.
42 #[inline(always)]
43 fn lock(&self) -> Self::Guard<'_> {
44 loop {
45 if let Some(sentinel) = self.try_lock() {
46 return sentinel;
47 }
48 }
49 }
50
51 /// Reconstructs a guard for a lock that is already held by the current core
52 /// (for example, when lock ownership is transferred across a context switch
53 /// into a newly started thread's entry trampoline).
54 ///
55 /// Do not call directly.
56 ///
57 /// `interrupts_on_drop` controls whether dropping the returned guard will
58 /// re-enable interrupts after unlocking ([`InterruptsOnDrop::Restore`]) or
59 /// leave interrupts disabled ([`InterruptsOnDrop::KeepDisabled`]).
60 ///
61 /// # Safety
62 /// The caller must guarantee that the lock is currently held, interrupts are
63 /// disabled, and no other active `Guard` will unlock it. See
64 /// [`SpinLock::adopt_locked()`] for use and safety information.
65 unsafe fn adopt_locked(&self, interrupts_on_drop: InterruptsOnDrop) -> Self::Guard<'_>;
66
67 // TODO - konkers: Add optimized path for functions that know they are in
68 // atomic context (i.e. interrupt handlers).
69}
70
71pub struct SpinLockGuard<'lock, K: Kernel, T> {
72 lock: &'lock SpinLock<K, T>,
73 _preempt_guard: PreemptDisableGuard<K>,
74 _inner_guard: <<K as Arch>::BareSpinLock as BareSpinLock>::Guard<'lock>,
75}
76
77impl<K: Kernel, T> Deref for SpinLockGuard<'_, K, T> {
78 type Target = T;
79
80 fn deref(&self) -> &T {
81 unsafe { &*self.lock.data.get() }
82 }
83}
84
85impl<K: Kernel, T> DerefMut for SpinLockGuard<'_, K, T> {
86 fn deref_mut(&mut self) -> &mut T {
87 unsafe { &mut *self.lock.data.get() }
88 }
89}
90
91pub struct SpinLock<K: Kernel, T> {
92 data: UnsafeCell<T>,
93 inner: K::BareSpinLock,
94}
95// As long as the inner type is `Send` and the bare spinlock is `Sync`, the lock
96// can be shared between threads.
97unsafe impl<K: Sync + Kernel, T: Send> Sync for SpinLock<K, T> {}
98
99impl<K: Kernel, T> SpinLock<K, T> {
100 pub const fn new(initial_value: T) -> Self {
101 Self {
102 data: UnsafeCell::new(initial_value),
103 inner: K::BareSpinLock::NEW,
104 }
105 }
106
107 pub fn try_lock(&self, kernel: K) -> Option<SpinLockGuard<'_, K, T>> {
108 self.inner.try_lock().map(|guard| SpinLockGuard {
109 lock: self,
110 _preempt_guard: PreemptDisableGuard::new(kernel),
111 _inner_guard: guard,
112 })
113 }
114
115 pub fn lock(&self, kernel: K) -> SpinLockGuard<'_, K, T> {
116 let inner_guard = self.inner.lock();
117 SpinLockGuard {
118 lock: self,
119 _preempt_guard: PreemptDisableGuard::new(kernel),
120 _inner_guard: inner_guard,
121 }
122 }
123
124 /// Reconstructs a [`SpinLockGuard`] for a lock that is already held and whose
125 /// ownership was transferred to the calling context (for example, across a
126 /// context switch into a newly started thread).
127 ///
128 /// `interrupts_on_drop` controls whether dropping the returned guard will
129 /// re-enable interrupts after unlocking ([`InterruptsOnDrop::Restore`]) or
130 /// leave interrupts disabled ([`InterruptsOnDrop::KeepDisabled`]).
131 ///
132 /// # Safety
133 /// The caller must guarantee that the underlying lock is currently held,
134 /// interrupts and preemption are disabled (`preempt_disable_count >= 1`),
135 /// and no other active guard exists for this lock.
136 #[inline]
137 pub unsafe fn adopt_locked(
138 &self,
139 kernel: K,
140 interrupts_on_drop: InterruptsOnDrop,
141 ) -> SpinLockGuard<'_, K, T> {
142 // SAFETY: Caller guarantees the underlying lock is currently held,
143 // interrupts are disabled, and no other active guard exists.
144 let inner_guard = unsafe { self.inner.adopt_locked(interrupts_on_drop) };
145 SpinLockGuard {
146 lock: self,
147 // SAFETY: Caller guarantees `preempt_disable_count >= 1` for an
148 // active guard whose ownership was transferred to this context.
149 _preempt_guard: unsafe { PreemptDisableGuard::adopt_locked(kernel) },
150 _inner_guard: inner_guard,
151 }
152 }
153}