xref: /linux-6.15/rust/kernel/sync/condvar.rs (revision dbd5058b)
119096bceSWedson Almeida Filho // SPDX-License-Identifier: GPL-2.0
219096bceSWedson Almeida Filho 
319096bceSWedson Almeida Filho //! A condition variable.
419096bceSWedson Almeida Filho //!
519096bceSWedson Almeida Filho //! This module allows Rust code to use the kernel's [`struct wait_queue_head`] as a condition
619096bceSWedson Almeida Filho //! variable.
719096bceSWedson Almeida Filho 
819096bceSWedson Almeida Filho use super::{lock::Backend, lock::Guard, LockClassKey};
9e7b9b1ffSAlice Ryhl use crate::{
10d072acdaSGary Guo     ffi::{c_int, c_long},
11f090f0d0SAlice Ryhl     str::CStr,
12f090f0d0SAlice Ryhl     task::{
13f090f0d0SAlice Ryhl         MAX_SCHEDULE_TIMEOUT, TASK_FREEZABLE, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE,
14e7b9b1ffSAlice Ryhl     },
15e7b9b1ffSAlice Ryhl     time::Jiffies,
1619096bceSWedson Almeida Filho     types::Opaque,
17f090f0d0SAlice Ryhl };
18*dbd5058bSBenno Lossin use core::{marker::PhantomPinned, pin::Pin, ptr};
1919096bceSWedson Almeida Filho use pin_init::{pin_data, pin_init, PinInit};
2019096bceSWedson Almeida Filho 
2119096bceSWedson Almeida Filho /// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class.
2219096bceSWedson Almeida Filho #[macro_export]
2319096bceSWedson Almeida Filho macro_rules! new_condvar {
2419096bceSWedson Almeida Filho     ($($name:literal)?) => {
2519096bceSWedson Almeida Filho         $crate::sync::CondVar::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
2619096bceSWedson Almeida Filho     };
27e283ee23SAlice Ryhl }
2819096bceSWedson Almeida Filho pub use new_condvar;
2919096bceSWedson Almeida Filho 
3019096bceSWedson Almeida Filho /// A conditional variable.
3119096bceSWedson Almeida Filho ///
3219096bceSWedson Almeida Filho /// Exposes the kernel's [`struct wait_queue_head`] as a condition variable. It allows the caller to
3319096bceSWedson Almeida Filho /// atomically release the given lock and go to sleep. It reacquires the lock when it wakes up. And
3419096bceSWedson Almeida Filho /// it wakes up when notified by another thread (via [`CondVar::notify_one`] or
3519096bceSWedson Almeida Filho /// [`CondVar::notify_all`]) or because the thread received a signal. It may also wake up
3619096bceSWedson Almeida Filho /// spuriously.
3719096bceSWedson Almeida Filho ///
38129e97beSBenno Lossin /// Instances of [`CondVar`] need a lock class and to be pinned. The recommended way to create such
3919096bceSWedson Almeida Filho /// instances is with the [`pin_init`](crate::pin_init!) and [`new_condvar`] macros.
4019096bceSWedson Almeida Filho ///
4119096bceSWedson Almeida Filho /// # Examples
4219096bceSWedson Almeida Filho ///
4319096bceSWedson Almeida Filho /// The following is an example of using a condvar with a mutex:
4419096bceSWedson Almeida Filho ///
45e283ee23SAlice Ryhl /// ```
4619096bceSWedson Almeida Filho /// use kernel::sync::{new_condvar, new_mutex, CondVar, Mutex};
4719096bceSWedson Almeida Filho ///
4819096bceSWedson Almeida Filho /// #[pin_data]
4919096bceSWedson Almeida Filho /// pub struct Example {
5019096bceSWedson Almeida Filho ///     #[pin]
5119096bceSWedson Almeida Filho ///     value: Mutex<u32>,
5219096bceSWedson Almeida Filho ///
5319096bceSWedson Almeida Filho ///     #[pin]
5419096bceSWedson Almeida Filho ///     value_changed: CondVar,
5519096bceSWedson Almeida Filho /// }
5619096bceSWedson Almeida Filho ///
5719096bceSWedson Almeida Filho /// /// Waits for `e.value` to become `v`.
5819096bceSWedson Almeida Filho /// fn wait_for_value(e: &Example, v: u32) {
5919096bceSWedson Almeida Filho ///     let mut guard = e.value.lock();
600a7f5ba7SBoqun Feng ///     while *guard != v {
6119096bceSWedson Almeida Filho ///         e.value_changed.wait(&mut guard);
6219096bceSWedson Almeida Filho ///     }
6319096bceSWedson Almeida Filho /// }
6419096bceSWedson Almeida Filho ///
6519096bceSWedson Almeida Filho /// /// Increments `e.value` and notifies all potential waiters.
6619096bceSWedson Almeida Filho /// fn increment(e: &Example) {
6719096bceSWedson Almeida Filho ///     *e.value.lock() += 1;
6819096bceSWedson Almeida Filho ///     e.value_changed.notify_all();
6919096bceSWedson Almeida Filho /// }
7019096bceSWedson Almeida Filho ///
718373147cSDanilo Krummrich /// /// Allocates a new boxed `Example`.
728373147cSDanilo Krummrich /// fn new_example() -> Result<Pin<KBox<Example>>> {
7319096bceSWedson Almeida Filho ///     KBox::pin_init(pin_init!(Example {
7419096bceSWedson Almeida Filho ///         value <- new_mutex!(0),
75c34aa00dSWedson Almeida Filho ///         value_changed <- new_condvar!(),
7619096bceSWedson Almeida Filho ///     }), GFP_KERNEL)
7719096bceSWedson Almeida Filho /// }
7819096bceSWedson Almeida Filho /// ```
79bc2e7d5cSMiguel Ojeda ///
8019096bceSWedson Almeida Filho /// [`struct wait_queue_head`]: srctree/include/linux/wait.h
8119096bceSWedson Almeida Filho #[pin_data]
8219096bceSWedson Almeida Filho pub struct CondVar {
836b1b2326SCharalampos Mitrodimas     #[pin]
8419096bceSWedson Almeida Filho     pub(crate) wait_queue_head: Opaque<bindings::wait_queue_head>,
8519096bceSWedson Almeida Filho 
8619096bceSWedson Almeida Filho     /// A condvar needs to be pinned because it contains a [`struct list_head`] that is
87ed859653SValentin Obst     /// self-referential, so it cannot be safely moved once it is initialised.
88ed859653SValentin Obst     ///
8919096bceSWedson Almeida Filho     /// [`struct list_head`]: srctree/include/linux/types.h
9019096bceSWedson Almeida Filho     #[pin]
9119096bceSWedson Almeida Filho     _pin: PhantomPinned,
9219096bceSWedson Almeida Filho }
93db4f72c9SMiguel Ojeda 
9419096bceSWedson Almeida Filho // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
9519096bceSWedson Almeida Filho unsafe impl Send for CondVar {}
9619096bceSWedson Almeida Filho 
9719096bceSWedson Almeida Filho // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads
9819096bceSWedson Almeida Filho // concurrently.
9919096bceSWedson Almeida Filho unsafe impl Sync for CondVar {}
10019096bceSWedson Almeida Filho 
10119096bceSWedson Almeida Filho impl CondVar {
10219096bceSWedson Almeida Filho     /// Constructs a new condvar initialiser.
new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self>10319096bceSWedson Almeida Filho     pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self> {
10419096bceSWedson Almeida Filho         pin_init!(Self {
10519096bceSWedson Almeida Filho             _pin: PhantomPinned,
10619096bceSWedson Almeida Filho             // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
1076b1b2326SCharalampos Mitrodimas             // static lifetimes so they live indefinitely.
10819096bceSWedson Almeida Filho             wait_queue_head <- Opaque::ffi_init(|slot| unsafe {
10919096bceSWedson Almeida Filho                 bindings::__init_waitqueue_head(slot, name.as_char_ptr(), key.as_ptr())
11019096bceSWedson Almeida Filho             }),
11119096bceSWedson Almeida Filho         })
11219096bceSWedson Almeida Filho     }
113e7b9b1ffSAlice Ryhl 
wait_internal<T: ?Sized, B: Backend>( &self, wait_state: c_int, guard: &mut Guard<'_, T, B>, timeout_in_jiffies: c_long, ) -> c_long114e7b9b1ffSAlice Ryhl     fn wait_internal<T: ?Sized, B: Backend>(
115f090f0d0SAlice Ryhl         &self,
116e7b9b1ffSAlice Ryhl         wait_state: c_int,
117e7b9b1ffSAlice Ryhl         guard: &mut Guard<'_, T, B>,
118e7b9b1ffSAlice Ryhl         timeout_in_jiffies: c_long,
11919096bceSWedson Almeida Filho     ) -> c_long {
12019096bceSWedson Almeida Filho         let wait = Opaque::<bindings::wait_queue_entry>::uninit();
12119096bceSWedson Almeida Filho 
12219096bceSWedson Almeida Filho         // SAFETY: `wait` points to valid memory.
12319096bceSWedson Almeida Filho         unsafe { bindings::init_wait(wait.get()) };
1246b1b2326SCharalampos Mitrodimas 
12519096bceSWedson Almeida Filho         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
126f090f0d0SAlice Ryhl         unsafe {
12719096bceSWedson Almeida Filho             bindings::prepare_to_wait_exclusive(self.wait_queue_head.get(), wait.get(), wait_state)
12819096bceSWedson Almeida Filho         };
129e7b9b1ffSAlice Ryhl 
130e7b9b1ffSAlice Ryhl         // SAFETY: Switches to another thread. The timeout can be any number.
13119096bceSWedson Almeida Filho         let ret = guard.do_unlocked(|| unsafe { bindings::schedule_timeout(timeout_in_jiffies) });
1326b1b2326SCharalampos Mitrodimas 
1336b1b2326SCharalampos Mitrodimas         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
134e7b9b1ffSAlice Ryhl         unsafe { bindings::finish_wait(self.wait_queue_head.get(), wait.get()) };
135e7b9b1ffSAlice Ryhl 
13619096bceSWedson Almeida Filho         ret
13719096bceSWedson Almeida Filho     }
1380a7f5ba7SBoqun Feng 
13919096bceSWedson Almeida Filho     /// Releases the lock and waits for a notification in uninterruptible mode.
14019096bceSWedson Almeida Filho     ///
14119096bceSWedson Almeida Filho     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
1420a7f5ba7SBoqun Feng     /// thread to sleep, reacquiring the lock on wake up. It wakes up when notified by
1430a7f5ba7SBoqun Feng     /// [`CondVar::notify_one`] or [`CondVar::notify_all`]. Note that it may also wake up
1440a7f5ba7SBoqun Feng     /// spuriously.
wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>)145f090f0d0SAlice Ryhl     pub fn wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) {
14619096bceSWedson Almeida Filho         self.wait_internal(TASK_UNINTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
14719096bceSWedson Almeida Filho     }
1480a7f5ba7SBoqun Feng 
14919096bceSWedson Almeida Filho     /// Releases the lock and waits for a notification in interruptible mode.
1500a7f5ba7SBoqun Feng     ///
1510a7f5ba7SBoqun Feng     /// Similar to [`CondVar::wait`], except that the wait is interruptible. That is, the thread may
1520a7f5ba7SBoqun Feng     /// wake up due to signals. It may also wake up spuriously.
1530a7f5ba7SBoqun Feng     ///
1540a7f5ba7SBoqun Feng     /// Returns whether there is a signal pending.
1550a7f5ba7SBoqun Feng     #[must_use = "wait_interruptible returns if a signal is pending, so the caller must check the return value"]
wait_interruptible<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) -> bool156f090f0d0SAlice Ryhl     pub fn wait_interruptible<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) -> bool {
1570a7f5ba7SBoqun Feng         self.wait_internal(TASK_INTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
15819096bceSWedson Almeida Filho         crate::current!().signal_pending()
15919096bceSWedson Almeida Filho     }
160e7b9b1ffSAlice Ryhl 
161e7b9b1ffSAlice Ryhl     /// Releases the lock and waits for a notification in interruptible and freezable mode.
162e7b9b1ffSAlice Ryhl     ///
163e7b9b1ffSAlice Ryhl     /// The process is allowed to be frozen during this sleep. No lock should be held when calling
164e7b9b1ffSAlice Ryhl     /// this function, and there is a lockdep assertion for this. Freezing a task that holds a lock
165e7b9b1ffSAlice Ryhl     /// can trivially deadlock vs another task that needs that lock to complete before it too can
166e7b9b1ffSAlice Ryhl     /// hit freezable.
167e7b9b1ffSAlice Ryhl     #[must_use = "wait_interruptible_freezable returns if a signal is pending, so the caller must check the return value"]
wait_interruptible_freezable<T: ?Sized, B: Backend>( &self, guard: &mut Guard<'_, T, B>, ) -> bool168e7b9b1ffSAlice Ryhl     pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>(
169e7b9b1ffSAlice Ryhl         &self,
170e7b9b1ffSAlice Ryhl         guard: &mut Guard<'_, T, B>,
171e7b9b1ffSAlice Ryhl     ) -> bool {
172f090f0d0SAlice Ryhl         self.wait_internal(
173e7b9b1ffSAlice Ryhl             TASK_INTERRUPTIBLE | TASK_FREEZABLE,
174e7b9b1ffSAlice Ryhl             guard,
175e7b9b1ffSAlice Ryhl             MAX_SCHEDULE_TIMEOUT,
176e7b9b1ffSAlice Ryhl         );
177e7b9b1ffSAlice Ryhl         crate::current!().signal_pending()
178e7b9b1ffSAlice Ryhl     }
179e7b9b1ffSAlice Ryhl 
180e7b9b1ffSAlice Ryhl     /// Releases the lock and waits for a notification in interruptible mode.
181f090f0d0SAlice Ryhl     ///
182f090f0d0SAlice Ryhl     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
1836b1b2326SCharalampos Mitrodimas     /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or
18419096bceSWedson Almeida Filho     /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal.
18519096bceSWedson Almeida Filho     #[must_use = "wait_interruptible_timeout returns if a signal is pending, so the caller must check the return value"]
wait_interruptible_timeout<T: ?Sized, B: Backend>( &self, guard: &mut Guard<'_, T, B>, jiffies: Jiffies, ) -> CondVarTimeoutResult1866b1b2326SCharalampos Mitrodimas     pub fn wait_interruptible_timeout<T: ?Sized, B: Backend>(
187f090f0d0SAlice Ryhl         &self,
18819096bceSWedson Almeida Filho         guard: &mut Guard<'_, T, B>,
189f090f0d0SAlice Ryhl         jiffies: Jiffies,
19019096bceSWedson Almeida Filho     ) -> CondVarTimeoutResult {
19119096bceSWedson Almeida Filho         let jiffies = jiffies.try_into().unwrap_or(MAX_SCHEDULE_TIMEOUT);
19219096bceSWedson Almeida Filho         let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);
19319096bceSWedson Almeida Filho 
1943e645417SAlice Ryhl         match (res as Jiffies, crate::current!().signal_pending()) {
1953e645417SAlice Ryhl             (jiffies, true) => CondVarTimeoutResult::Signal { jiffies },
1963e645417SAlice Ryhl             (0, false) => CondVarTimeoutResult::Timeout,
1973e645417SAlice Ryhl             (jiffies, false) => CondVarTimeoutResult::Woken { jiffies },
1983e645417SAlice Ryhl         }
1993e645417SAlice Ryhl     }
2003e645417SAlice Ryhl 
201f090f0d0SAlice Ryhl     /// Calls the kernel function to notify the appropriate number of threads.
notify(&self, count: c_int)2023e645417SAlice Ryhl     fn notify(&self, count: c_int) {
2033e645417SAlice Ryhl         // SAFETY: `wait_queue_head` points to valid memory.
20419096bceSWedson Almeida Filho         unsafe {
20519096bceSWedson Almeida Filho             bindings::__wake_up(
20619096bceSWedson Almeida Filho                 self.wait_queue_head.get(),
20719096bceSWedson Almeida Filho                 TASK_NORMAL,
20819096bceSWedson Almeida Filho                 count,
209f090f0d0SAlice Ryhl                 ptr::null_mut(),
21019096bceSWedson Almeida Filho             )
21119096bceSWedson Almeida Filho         };
21219096bceSWedson Almeida Filho     }
21319096bceSWedson Almeida Filho 
21419096bceSWedson Almeida Filho     /// Calls the kernel function to notify one thread synchronously.
21519096bceSWedson Almeida Filho     ///
21619096bceSWedson Almeida Filho     /// This method behaves like `notify_one`, except that it hints to the scheduler that the
217f090f0d0SAlice Ryhl     /// current thread is about to go to sleep, so it should schedule the target thread on the same
21819096bceSWedson Almeida Filho     /// CPU.
notify_sync(&self)21919096bceSWedson Almeida Filho     pub fn notify_sync(&self) {
220e7b9b1ffSAlice Ryhl         // SAFETY: `wait_queue_head` points to valid memory.
221e7b9b1ffSAlice Ryhl         unsafe { bindings::__wake_up_sync(self.wait_queue_head.get(), TASK_NORMAL) };
222e7b9b1ffSAlice Ryhl     }
223e7b9b1ffSAlice Ryhl 
224e7b9b1ffSAlice Ryhl     /// Wakes a single waiter up, if any.
225e7b9b1ffSAlice Ryhl     ///
226e7b9b1ffSAlice Ryhl     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
227e7b9b1ffSAlice Ryhl     /// completely (as opposed to automatically waking up the next waiter).
notify_one(&self)228e7b9b1ffSAlice Ryhl     pub fn notify_one(&self) {
229e7b9b1ffSAlice Ryhl         self.notify(1);
230e7b9b1ffSAlice Ryhl     }
231e7b9b1ffSAlice Ryhl 
232e7b9b1ffSAlice Ryhl     /// Wakes all waiters up, if any.
233e7b9b1ffSAlice Ryhl     ///
234e7b9b1ffSAlice Ryhl     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
235e7b9b1ffSAlice Ryhl     /// completely (as opposed to automatically waking up the next waiter).
notify_all(&self)236     pub fn notify_all(&self) {
237         self.notify(0);
238     }
239 }
240 
241 /// The return type of `wait_timeout`.
242 pub enum CondVarTimeoutResult {
243     /// The timeout was reached.
244     Timeout,
245     /// Somebody woke us up.
246     Woken {
247         /// Remaining sleep duration.
248         jiffies: Jiffies,
249     },
250     /// A signal occurred.
251     Signal {
252         /// Remaining sleep duration.
253         jiffies: Jiffies,
254     },
255 }
256