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