xref: /linux/rust/kernel/sync.rs (revision 2387fb2a9b84950dfe2eaa0b170f429e04b38168)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Synchronisation primitives.
4 //!
5 //! This module contains the kernel APIs related to synchronisation that have been ported or
6 //! wrapped for usage by Rust code in the kernel.
7 
8 use crate::prelude::*;
9 use crate::types::Opaque;
10 use pin_init;
11 
12 mod arc;
13 pub mod aref;
14 pub mod atomic;
15 pub mod completion;
16 mod condvar;
17 pub mod lock;
18 mod locked_by;
19 pub mod poll;
20 pub mod rcu;
21 
22 pub use arc::{Arc, ArcBorrow, UniqueArc};
23 pub use completion::Completion;
24 pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult};
25 pub use lock::global::{global_lock, GlobalGuard, GlobalLock, GlobalLockBackend, GlobalLockedBy};
26 pub use lock::mutex::{new_mutex, Mutex, MutexGuard};
27 pub use lock::spinlock::{new_spinlock, SpinLock, SpinLockGuard};
28 pub use locked_by::LockedBy;
29 
30 /// Represents a lockdep class. It's a wrapper around C's `lock_class_key`.
31 #[repr(transparent)]
32 #[pin_data(PinnedDrop)]
33 pub struct LockClassKey {
34     #[pin]
35     inner: Opaque<bindings::lock_class_key>,
36 }
37 
38 // SAFETY: `bindings::lock_class_key` is designed to be used concurrently from multiple threads and
39 // provides its own synchronization.
40 unsafe impl Sync for LockClassKey {}
41 
42 impl LockClassKey {
43     /// Initializes a dynamically allocated lock class key. In the common case of using a
44     /// statically allocated lock class key, the static_lock_class! macro should be used instead.
45     ///
46     /// # Examples
47     /// ```
48     /// # use kernel::c_str;
49     /// # use kernel::alloc::KBox;
50     /// # use kernel::types::ForeignOwnable;
51     /// # use kernel::sync::{LockClassKey, SpinLock};
52     /// # use pin_init::stack_pin_init;
53     ///
54     /// let key = KBox::pin_init(LockClassKey::new_dynamic(), GFP_KERNEL)?;
55     /// let key_ptr = key.into_foreign();
56     ///
57     /// {
58     ///     stack_pin_init!(let num: SpinLock<u32> = SpinLock::new(
59     ///         0,
60     ///         c_str!("my_spinlock"),
61     ///         // SAFETY: `key_ptr` is returned by the above `into_foreign()`, whose
62     ///         // `from_foreign()` has not yet been called.
63     ///         unsafe { <Pin<KBox<LockClassKey>> as ForeignOwnable>::borrow(key_ptr) }
64     ///     ));
65     /// }
66     ///
67     /// // SAFETY: We dropped `num`, the only use of the key, so the result of the previous
68     /// // `borrow` has also been dropped. Thus, it's safe to use from_foreign.
69     /// unsafe { drop(<Pin<KBox<LockClassKey>> as ForeignOwnable>::from_foreign(key_ptr)) };
70     ///
71     /// # Ok::<(), Error>(())
72     /// ```
73     pub fn new_dynamic() -> impl PinInit<Self> {
74         pin_init!(Self {
75             // SAFETY: lockdep_register_key expects an uninitialized block of memory
76             inner <- Opaque::ffi_init(|slot| unsafe { bindings::lockdep_register_key(slot) })
77         })
78     }
79 
80     pub(crate) fn as_ptr(&self) -> *mut bindings::lock_class_key {
81         self.inner.get()
82     }
83 }
84 
85 #[pinned_drop]
86 impl PinnedDrop for LockClassKey {
87     fn drop(self: Pin<&mut Self>) {
88         // SAFETY: self.as_ptr was registered with lockdep and self is pinned, so the address
89         // hasn't changed. Thus, it's safe to pass to unregister.
90         unsafe { bindings::lockdep_unregister_key(self.as_ptr()) }
91     }
92 }
93 
94 /// Defines a new static lock class and returns a pointer to it.
95 #[doc(hidden)]
96 #[macro_export]
97 macro_rules! static_lock_class {
98     () => {{
99         static CLASS: $crate::sync::LockClassKey =
100             // Lockdep expects uninitialized memory when it's handed a statically allocated `struct
101             // lock_class_key`.
102             //
103             // SAFETY: `LockClassKey` transparently wraps `Opaque` which permits uninitialized
104             // memory.
105             unsafe { ::core::mem::MaybeUninit::uninit().assume_init() };
106         $crate::prelude::Pin::static_ref(&CLASS)
107     }};
108 }
109 
110 /// Returns the given string, if one is provided, otherwise generates one based on the source code
111 /// location.
112 #[doc(hidden)]
113 #[macro_export]
114 macro_rules! optional_name {
115     () => {
116         $crate::c_str!(::core::concat!(::core::file!(), ":", ::core::line!()))
117     };
118     ($name:literal) => {
119         $crate::c_str!($name)
120     };
121 }
122