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