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