xref: /linux/rust/kernel/sync/lock/spinlock.rs (revision 71dfa617ea9f18e4585fe78364217cd32b1fc382)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! A kernel spinlock.
4 //!
5 //! This module allows Rust code to use the kernel's `spinlock_t`.
6 
7 use crate::bindings;
8 
9 /// Creates a [`SpinLock`] initialiser with the given name and a newly-created lock class.
10 ///
11 /// It uses the name if one is given, otherwise it generates one based on the file name and line
12 /// number.
13 #[macro_export]
14 macro_rules! new_spinlock {
15     ($inner:expr $(, $name:literal)? $(,)?) => {
16         $crate::sync::SpinLock::new(
17             $inner, $crate::optional_name!($($name)?), $crate::static_lock_class!())
18     };
19 }
20 pub use new_spinlock;
21 
22 /// A spinlock.
23 ///
24 /// Exposes the kernel's [`spinlock_t`]. When multiple CPUs attempt to lock the same spinlock, only
25 /// one at a time is allowed to progress, the others will block (spinning) until the spinlock is
26 /// unlocked, at which point another CPU will be allowed to make progress.
27 ///
28 /// Instances of [`SpinLock`] need a lock class and to be pinned. The recommended way to create such
29 /// instances is with the [`pin_init`](crate::pin_init) and [`new_spinlock`] macros.
30 ///
31 /// # Examples
32 ///
33 /// The following example shows how to declare, allocate and initialise a struct (`Example`) that
34 /// contains an inner struct (`Inner`) that is protected by a spinlock.
35 ///
36 /// ```
37 /// use kernel::sync::{new_spinlock, SpinLock};
38 ///
39 /// struct Inner {
40 ///     a: u32,
41 ///     b: u32,
42 /// }
43 ///
44 /// #[pin_data]
45 /// struct Example {
46 ///     c: u32,
47 ///     #[pin]
48 ///     d: SpinLock<Inner>,
49 /// }
50 ///
51 /// impl Example {
52 ///     fn new() -> impl PinInit<Self> {
53 ///         pin_init!(Self {
54 ///             c: 10,
55 ///             d <- new_spinlock!(Inner { a: 20, b: 30 }),
56 ///         })
57 ///     }
58 /// }
59 ///
60 /// // Allocate a boxed `Example`.
61 /// let e = Box::pin_init(Example::new())?;
62 /// assert_eq!(e.c, 10);
63 /// assert_eq!(e.d.lock().a, 20);
64 /// assert_eq!(e.d.lock().b, 30);
65 /// # Ok::<(), Error>(())
66 /// ```
67 ///
68 /// The following example shows how to use interior mutability to modify the contents of a struct
69 /// protected by a spinlock despite only having a shared reference:
70 ///
71 /// ```
72 /// use kernel::sync::SpinLock;
73 ///
74 /// struct Example {
75 ///     a: u32,
76 ///     b: u32,
77 /// }
78 ///
79 /// fn example(m: &SpinLock<Example>) {
80 ///     let mut guard = m.lock();
81 ///     guard.a += 10;
82 ///     guard.b += 20;
83 /// }
84 /// ```
85 ///
86 /// [`spinlock_t`]: srctree/include/linux/spinlock.h
87 pub type SpinLock<T> = super::Lock<T, SpinLockBackend>;
88 
89 /// A kernel `spinlock_t` lock backend.
90 pub struct SpinLockBackend;
91 
92 // SAFETY: The underlying kernel `spinlock_t` object ensures mutual exclusion. `relock` uses the
93 // default implementation that always calls the same locking method.
94 unsafe impl super::Backend for SpinLockBackend {
95     type State = bindings::spinlock_t;
96     type GuardState = ();
97 
98     unsafe fn init(
99         ptr: *mut Self::State,
100         name: *const core::ffi::c_char,
101         key: *mut bindings::lock_class_key,
102     ) {
103         // SAFETY: The safety requirements ensure that `ptr` is valid for writes, and `name` and
104         // `key` are valid for read indefinitely.
105         unsafe { bindings::__spin_lock_init(ptr, name, key) }
106     }
107 
108     unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState {
109         // SAFETY: The safety requirements of this function ensure that `ptr` points to valid
110         // memory, and that it has been initialised before.
111         unsafe { bindings::spin_lock(ptr) }
112     }
113 
114     unsafe fn unlock(ptr: *mut Self::State, _guard_state: &Self::GuardState) {
115         // SAFETY: The safety requirements of this function ensure that `ptr` is valid and that the
116         // caller is the owner of the spinlock.
117         unsafe { bindings::spin_unlock(ptr) }
118     }
119 }
120