Files
linux/rust/kernel/sync.rs
Linus Torvalds 83684c4e4d Merge tag 'rcu.2026.08.18a' of git://git.kernel.org/pub/scm/linux/kernel/git/rcu/linux
Pull RCU updates from Paul McKenney:
 "Make expedited grace periods expedite normal RCU callbacks

  Miscellaneous fixes:
   - Improve diagnostic output with character task states
   - Mark accesses to inform KCSAN of concurrency design
   - Move from kmalloc() to kmalloc_obj()
   - Documentation updates
   - Improve handling of RCU deferred quiescent states
   - Clean up unused function arguments and structure fields
   - Reduce show_rcu_gp_kthreads() stack space

  Tasks RCU updates:
   - Clean up after SRCU re-implementation of Tasks Trace RCU
   - Mark accesses to inform KCSAN of concurrency design
   - Add ->lazy_timer status to diagnostic output
   - Remove an unnecessary memory barrier
   - Fix a data race, courtesy of KCSAN
   - Documentation updates
   - Convert cond_resched_tasks_rcu_qs() from macro to static inline
     function

  SRCU updates:
   - Add Rust helpers for SRCU
   - Avoid losing queued work at cleanup_srcu_struct() time

  Torture-test updates:
   - Preparation work for immediate RCU priority deboosting
   - Test RCU readers from real interrupt handlers (as opposed to
     softirq)
   - Simplify code through use of cpumask_next_wrap()
   - Improve diagnostic output with character task states
   - Add rcutorture.nwriters parameter to allow lightweight stall
     testing, and rcutorture.stall_only to make doing so easier
   - Test an RCU Tasks Trace grace period implying an RCU grace period
   - Make RCU Tasks Trace torturing track reader batches
   - Fix a data race, courtesy of KCSAN
   - Plug a shuffle_tmp_mask memory leak on kthread spawn failure"

* tag 'rcu.2026.08.18a' of git://git.kernel.org/pub/scm/linux/kernel/git/rcu/linux: (59 commits)
  rcu: Add closing parenthesis in comment in rcu_read_unlock_strict()
  rcutorture: Make {,s}rcu_read_delay() better handle forward-progress testing
  rcutorture: Announce declining to forward-progress test
  torture: Don't leak shuffle_tmp_mask when shuffler kthread fails to start
  rcutorture: Use this_cpu_inc() for rcu_torture_count[] and rcu_torture_batch[]
  rcutorture: Make RCU Tasks Trace track Reader Batches
  rcutorture: Test RCU Tasks Trace GP implying RCU GP
  rcutorture: Add a stall_only module parameter
  rcutorture: Add nwriters module parameter
  rcutorture: Use task_state_to_char() for task-state reporting
  rcutorture: Use cpumask_next_wrap() in rcu_torture_preempt()
  rcutorture: Test RCU readers from hardware interrupt handlers
  rcutorture: Check for immediate deboosting at reader end
  srcu: Queue sdp->work when the delay timer is successfully deleted
  rcu-tasks: Convert cond_resched_tasks_rcu_qs() to static inline
  rcu-tasks: Fix some comments for call_rcu_tasks() and call_rcu_tasks_rude()
  rcu-tasks: Rename tasks_rcu_exit_srcu_stall_timer to tasks_rcu_exit_stall_timer
  rcu: Mark interrupts-enabled accesses to rdp->cpu_no_qs.s
  rcu: Reduce stack usage in show_rcu_gp_kthreads()
  rcu: Mark accesses to ->rcu_urgent_qs and ->rcu_need_heavy_qs
  ...
2026-08-23 18:00:22 -07:00

172 lines
5.2 KiB
Rust

// SPDX-License-Identifier: GPL-2.0
//! Synchronisation primitives.
//!
//! This module contains the kernel APIs related to synchronisation that have been ported or
//! wrapped for usage by Rust code in the kernel.
use crate::prelude::*;
use crate::types::Opaque;
use pin_init;
mod arc;
pub mod aref;
pub mod atomic;
pub mod barrier;
pub mod completion;
mod condvar;
pub mod lock;
mod locked_by;
pub mod poll;
pub mod rcu;
mod refcount;
mod set_once;
pub mod srcu;
pub use arc::{Arc, ArcBorrow, UniqueArc};
pub use completion::Completion;
pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult};
pub use lock::global::{global_lock, GlobalGuard, GlobalLock, GlobalLockBackend, GlobalLockedBy};
pub use lock::mutex::{new_mutex, Mutex, MutexGuard};
pub use lock::spinlock::{
new_spinlock,
new_spinlock_irq,
SpinLock,
SpinLockGuard,
SpinLockIrq,
SpinLockIrqGuard, //
};
pub use locked_by::LockedBy;
pub use refcount::Refcount;
pub use set_once::SetOnce;
pub use srcu::Srcu;
/// Represents a lockdep class.
///
/// Wraps the kernel's `struct lock_class_key`.
#[repr(transparent)]
#[pin_data(PinnedDrop)]
pub struct LockClassKey {
#[pin]
inner: Opaque<bindings::lock_class_key>,
}
// SAFETY: Unregistering a lock class key from a different thread than where it was registered is
// allowed.
unsafe impl Send for LockClassKey {}
// SAFETY: `bindings::lock_class_key` is designed to be used concurrently from multiple threads and
// provides its own synchronization.
unsafe impl Sync for LockClassKey {}
impl LockClassKey {
/// Initializes a statically allocated lock class key.
///
/// This is usually used indirectly through the [`static_lock_class!`] macro. See its
/// documentation for more information.
///
/// # Safety
///
/// * Before using the returned value, it must be pinned in a static memory location.
/// * The destructor must never run on the returned `LockClassKey`.
pub const unsafe fn new_static() -> Self {
LockClassKey {
inner: Opaque::uninit(),
}
}
/// Initializes a dynamically allocated lock class key.
///
/// In the common case of using a statically allocated lock class key, the
/// [`static_lock_class!`] macro should be used instead.
///
/// # Examples
///
/// ```
/// use kernel::alloc::KBox;
/// use kernel::types::ForeignOwnable;
/// use kernel::sync::{LockClassKey, SpinLock};
/// use pin_init::stack_pin_init;
///
/// let key = KBox::pin_init(LockClassKey::new_dynamic(), GFP_KERNEL)?;
/// let key_ptr = key.into_foreign();
///
/// {
/// stack_pin_init!(let num: SpinLock<u32> = SpinLock::new(
/// 0,
/// c"my_spinlock",
/// // SAFETY: `key_ptr` is returned by the above `into_foreign()`, whose
/// // `from_foreign()` has not yet been called.
/// unsafe { <Pin<KBox<LockClassKey>> as ForeignOwnable>::borrow(key_ptr) }
/// ));
/// }
///
/// // SAFETY: We dropped `num`, the only use of the key, so the result of the previous
/// // `borrow` has also been dropped. Thus, it's safe to use from_foreign.
/// unsafe { drop(<Pin<KBox<LockClassKey>> as ForeignOwnable>::from_foreign(key_ptr)) };
/// # Ok::<(), Error>(())
/// ```
pub fn new_dynamic() -> impl PinInit<Self> {
pin_init!(Self {
// SAFETY: lockdep_register_key expects an uninitialized block of memory
inner <- Opaque::ffi_init(|slot| unsafe { bindings::lockdep_register_key(slot) })
})
}
/// Returns a raw pointer to the inner C struct.
///
/// It is up to the caller to use the raw pointer correctly.
pub fn as_ptr(&self) -> *mut bindings::lock_class_key {
self.inner.get()
}
}
#[pinned_drop]
impl PinnedDrop for LockClassKey {
fn drop(self: Pin<&mut Self>) {
// SAFETY: `self.as_ptr()` was registered with lockdep and `self` is pinned, so the address
// hasn't changed. Thus, it's safe to pass it to unregister.
unsafe { bindings::lockdep_unregister_key(self.as_ptr()) }
}
}
/// Defines a new static lock class and returns a pointer to it.
///
/// # Examples
///
/// ```
/// use kernel::sync::{static_lock_class, Arc, SpinLock};
///
/// fn new_locked_int() -> Result<Arc<SpinLock<u32>>> {
/// Arc::pin_init(SpinLock::new(
/// 42,
/// c"new_locked_int",
/// static_lock_class!(),
/// ), GFP_KERNEL)
/// }
/// ```
#[macro_export]
macro_rules! static_lock_class {
() => {{
static CLASS: $crate::sync::LockClassKey =
// SAFETY: The returned `LockClassKey` is stored in static memory and we pin it. Drop
// never runs on a static global.
unsafe { $crate::sync::LockClassKey::new_static() };
$crate::prelude::Pin::static_ref(&CLASS)
}};
}
pub use static_lock_class;
/// Returns the given string, if one is provided, otherwise generates one based on the source code
/// location.
#[doc(hidden)]
#[macro_export]
macro_rules! optional_name {
() => {
$crate::c_str!(::core::concat!(::core::file!(), ":", ::core::line!()))
};
($name:literal) => {
$crate::c_str!($name)
};
}