xref: /openbmc/linux/rust/kernel/sync.rs (revision 36db6e8484ed455bbb320d89a119378897ae991c)
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::types::Opaque;
9 
10 mod arc;
11 mod condvar;
12 pub mod lock;
13 mod locked_by;
14 
15 pub use arc::{Arc, ArcBorrow, UniqueArc};
16 pub use condvar::CondVar;
17 pub use lock::{mutex::Mutex, spinlock::SpinLock};
18 pub use locked_by::LockedBy;
19 
20 /// Represents a lockdep class. It's a wrapper around C's `lock_class_key`.
21 #[repr(transparent)]
22 pub struct LockClassKey(Opaque<bindings::lock_class_key>);
23 
24 // SAFETY: `bindings::lock_class_key` is designed to be used concurrently from multiple threads and
25 // provides its own synchronization.
26 unsafe impl Sync for LockClassKey {}
27 
28 impl LockClassKey {
as_ptr(&self) -> *mut bindings::lock_class_key29     pub(crate) fn as_ptr(&self) -> *mut bindings::lock_class_key {
30         self.0.get()
31     }
32 }
33 
34 /// Defines a new static lock class and returns a pointer to it.
35 #[doc(hidden)]
36 #[macro_export]
37 macro_rules! static_lock_class {
38     () => {{
39         static CLASS: $crate::sync::LockClassKey =
40             // SAFETY: lockdep expects uninitialized memory when it's handed a statically allocated
41             // lock_class_key
42             unsafe { ::core::mem::MaybeUninit::uninit().assume_init() };
43         &CLASS
44     }};
45 }
46 
47 /// Returns the given string, if one is provided, otherwise generates one based on the source code
48 /// location.
49 #[doc(hidden)]
50 #[macro_export]
51 macro_rules! optional_name {
52     () => {
53         $crate::c_str!(::core::concat!(::core::file!(), ":", ::core::line!()))
54     };
55     ($name:literal) => {
56         $crate::c_str!($name)
57     };
58 }
59