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