Skip to main content

kernel/
sync.rs

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