xref: /linux/rust/kernel/sync/condvar.rs (revision 00280272)
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::{
10f090f0d0SAlice Ryhl     init::PinInit,
11f090f0d0SAlice Ryhl     pin_init,
12f090f0d0SAlice Ryhl     str::CStr,
13f090f0d0SAlice Ryhl     task::{MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE},
14f090f0d0SAlice Ryhl     time::Jiffies,
15e7b9b1ffSAlice Ryhl     types::Opaque,
16e7b9b1ffSAlice Ryhl };
17f090f0d0SAlice Ryhl use core::ffi::{c_int, c_long};
1819096bceSWedson Almeida Filho use core::marker::PhantomPinned;
19f090f0d0SAlice Ryhl use core::ptr;
2019096bceSWedson Almeida Filho use macros::pin_data;
2119096bceSWedson Almeida Filho 
2219096bceSWedson Almeida Filho /// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class.
2319096bceSWedson Almeida Filho #[macro_export]
2419096bceSWedson Almeida Filho macro_rules! new_condvar {
2519096bceSWedson Almeida Filho     ($($name:literal)?) => {
2619096bceSWedson Almeida Filho         $crate::sync::CondVar::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
2719096bceSWedson Almeida Filho     };
2819096bceSWedson Almeida Filho }
29e283ee23SAlice Ryhl pub use new_condvar;
3019096bceSWedson Almeida Filho 
3119096bceSWedson Almeida Filho /// A conditional variable.
3219096bceSWedson Almeida Filho ///
3319096bceSWedson Almeida Filho /// Exposes the kernel's [`struct wait_queue_head`] as a condition variable. It allows the caller to
3419096bceSWedson Almeida Filho /// atomically release the given lock and go to sleep. It reacquires the lock when it wakes up. And
3519096bceSWedson Almeida Filho /// it wakes up when notified by another thread (via [`CondVar::notify_one`] or
3619096bceSWedson Almeida Filho /// [`CondVar::notify_all`]) or because the thread received a signal. It may also wake up
3719096bceSWedson Almeida Filho /// spuriously.
3819096bceSWedson Almeida Filho ///
3919096bceSWedson Almeida Filho /// Instances of [`CondVar`] need a lock class and to be pinned. The recommended way to create such
4019096bceSWedson Almeida Filho /// instances is with the [`pin_init`](crate::pin_init) and [`new_condvar`] macros.
4119096bceSWedson Almeida Filho ///
4219096bceSWedson Almeida Filho /// # Examples
4319096bceSWedson Almeida Filho ///
4419096bceSWedson Almeida Filho /// The following is an example of using a condvar with a mutex:
4519096bceSWedson Almeida Filho ///
4619096bceSWedson Almeida Filho /// ```
47e283ee23SAlice Ryhl /// use kernel::sync::{new_condvar, new_mutex, CondVar, Mutex};
4819096bceSWedson Almeida Filho ///
4919096bceSWedson Almeida Filho /// #[pin_data]
5019096bceSWedson Almeida Filho /// pub struct Example {
5119096bceSWedson Almeida Filho ///     #[pin]
5219096bceSWedson Almeida Filho ///     value: Mutex<u32>,
5319096bceSWedson Almeida Filho ///
5419096bceSWedson Almeida Filho ///     #[pin]
5519096bceSWedson Almeida Filho ///     value_changed: CondVar,
5619096bceSWedson Almeida Filho /// }
5719096bceSWedson Almeida Filho ///
5819096bceSWedson Almeida Filho /// /// Waits for `e.value` to become `v`.
5919096bceSWedson Almeida Filho /// fn wait_for_value(e: &Example, v: u32) {
6019096bceSWedson Almeida Filho ///     let mut guard = e.value.lock();
6119096bceSWedson Almeida Filho ///     while *guard != v {
620a7f5ba7SBoqun Feng ///         e.value_changed.wait(&mut guard);
6319096bceSWedson Almeida Filho ///     }
6419096bceSWedson Almeida Filho /// }
6519096bceSWedson Almeida Filho ///
6619096bceSWedson Almeida Filho /// /// Increments `e.value` and notifies all potential waiters.
6719096bceSWedson Almeida Filho /// fn increment(e: &Example) {
6819096bceSWedson Almeida Filho ///     *e.value.lock() += 1;
6919096bceSWedson Almeida Filho ///     e.value_changed.notify_all();
7019096bceSWedson Almeida Filho /// }
7119096bceSWedson Almeida Filho ///
7219096bceSWedson Almeida Filho /// /// Allocates a new boxed `Example`.
7319096bceSWedson Almeida Filho /// fn new_example() -> Result<Pin<Box<Example>>> {
7419096bceSWedson Almeida Filho ///     Box::pin_init(pin_init!(Example {
7519096bceSWedson Almeida Filho ///         value <- new_mutex!(0),
7619096bceSWedson Almeida Filho ///         value_changed <- new_condvar!(),
77*c34aa00dSWedson Almeida Filho ///     }), GFP_KERNEL)
7819096bceSWedson Almeida Filho /// }
7919096bceSWedson Almeida Filho /// ```
8019096bceSWedson Almeida Filho ///
81bc2e7d5cSMiguel Ojeda /// [`struct wait_queue_head`]: srctree/include/linux/wait.h
8219096bceSWedson Almeida Filho #[pin_data]
8319096bceSWedson Almeida Filho pub struct CondVar {
8419096bceSWedson Almeida Filho     #[pin]
856b1b2326SCharalampos Mitrodimas     pub(crate) wait_queue_head: Opaque<bindings::wait_queue_head>,
8619096bceSWedson Almeida Filho 
8719096bceSWedson Almeida Filho     /// A condvar needs to be pinned because it contains a [`struct list_head`] that is
8819096bceSWedson Almeida Filho     /// self-referential, so it cannot be safely moved once it is initialised.
89ed859653SValentin Obst     ///
90ed859653SValentin Obst     /// [`struct list_head`]: srctree/include/linux/types.h
9119096bceSWedson Almeida Filho     #[pin]
9219096bceSWedson Almeida Filho     _pin: PhantomPinned,
9319096bceSWedson Almeida Filho }
9419096bceSWedson Almeida Filho 
9519096bceSWedson Almeida Filho // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
9619096bceSWedson Almeida Filho #[allow(clippy::non_send_fields_in_send_ty)]
9719096bceSWedson Almeida Filho unsafe impl Send for CondVar {}
9819096bceSWedson Almeida Filho 
9919096bceSWedson Almeida Filho // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads
10019096bceSWedson Almeida Filho // concurrently.
10119096bceSWedson Almeida Filho unsafe impl Sync for CondVar {}
10219096bceSWedson Almeida Filho 
10319096bceSWedson Almeida Filho impl CondVar {
10419096bceSWedson Almeida Filho     /// Constructs a new condvar initialiser.
new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self>10519096bceSWedson Almeida Filho     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> {
10619096bceSWedson Almeida Filho         pin_init!(Self {
10719096bceSWedson Almeida Filho             _pin: PhantomPinned,
10819096bceSWedson Almeida Filho             // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
10919096bceSWedson Almeida Filho             // static lifetimes so they live indefinitely.
1106b1b2326SCharalampos Mitrodimas             wait_queue_head <- Opaque::ffi_init(|slot| unsafe {
11119096bceSWedson Almeida Filho                 bindings::__init_waitqueue_head(slot, name.as_char_ptr(), key.as_ptr())
11219096bceSWedson Almeida Filho             }),
11319096bceSWedson Almeida Filho         })
11419096bceSWedson Almeida Filho     }
11519096bceSWedson Almeida Filho 
wait_internal<T: ?Sized, B: Backend>( &self, wait_state: c_int, guard: &mut Guard<'_, T, B>, timeout_in_jiffies: c_long, ) -> c_long116e7b9b1ffSAlice Ryhl     fn wait_internal<T: ?Sized, B: Backend>(
117e7b9b1ffSAlice Ryhl         &self,
118f090f0d0SAlice Ryhl         wait_state: c_int,
119e7b9b1ffSAlice Ryhl         guard: &mut Guard<'_, T, B>,
120e7b9b1ffSAlice Ryhl         timeout_in_jiffies: c_long,
121e7b9b1ffSAlice Ryhl     ) -> c_long {
12219096bceSWedson Almeida Filho         let wait = Opaque::<bindings::wait_queue_entry>::uninit();
12319096bceSWedson Almeida Filho 
12419096bceSWedson Almeida Filho         // SAFETY: `wait` points to valid memory.
12519096bceSWedson Almeida Filho         unsafe { bindings::init_wait(wait.get()) };
12619096bceSWedson Almeida Filho 
1276b1b2326SCharalampos Mitrodimas         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
12819096bceSWedson Almeida Filho         unsafe {
129f090f0d0SAlice Ryhl             bindings::prepare_to_wait_exclusive(self.wait_queue_head.get(), wait.get(), wait_state)
13019096bceSWedson Almeida Filho         };
13119096bceSWedson Almeida Filho 
132e7b9b1ffSAlice Ryhl         // SAFETY: Switches to another thread. The timeout can be any number.
133e7b9b1ffSAlice Ryhl         let ret = guard.do_unlocked(|| unsafe { bindings::schedule_timeout(timeout_in_jiffies) });
13419096bceSWedson Almeida Filho 
1356b1b2326SCharalampos Mitrodimas         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
1366b1b2326SCharalampos Mitrodimas         unsafe { bindings::finish_wait(self.wait_queue_head.get(), wait.get()) };
137e7b9b1ffSAlice Ryhl 
138e7b9b1ffSAlice Ryhl         ret
13919096bceSWedson Almeida Filho     }
14019096bceSWedson Almeida Filho 
1410a7f5ba7SBoqun Feng     /// Releases the lock and waits for a notification in uninterruptible mode.
14219096bceSWedson Almeida Filho     ///
14319096bceSWedson Almeida Filho     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
14419096bceSWedson Almeida Filho     /// thread to sleep, reacquiring the lock on wake up. It wakes up when notified by
1450a7f5ba7SBoqun Feng     /// [`CondVar::notify_one`] or [`CondVar::notify_all`]. Note that it may also wake up
1460a7f5ba7SBoqun Feng     /// spuriously.
wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>)1470a7f5ba7SBoqun Feng     pub fn wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) {
148f090f0d0SAlice Ryhl         self.wait_internal(TASK_UNINTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
14919096bceSWedson Almeida Filho     }
15019096bceSWedson Almeida Filho 
1510a7f5ba7SBoqun Feng     /// Releases the lock and waits for a notification in interruptible mode.
15219096bceSWedson Almeida Filho     ///
1530a7f5ba7SBoqun Feng     /// Similar to [`CondVar::wait`], except that the wait is interruptible. That is, the thread may
1540a7f5ba7SBoqun Feng     /// wake up due to signals. It may also wake up spuriously.
1550a7f5ba7SBoqun Feng     ///
1560a7f5ba7SBoqun Feng     /// Returns whether there is a signal pending.
1570a7f5ba7SBoqun 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>) -> bool1580a7f5ba7SBoqun Feng     pub fn wait_interruptible<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) -> bool {
159f090f0d0SAlice Ryhl         self.wait_internal(TASK_INTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
1600a7f5ba7SBoqun Feng         crate::current!().signal_pending()
16119096bceSWedson Almeida Filho     }
16219096bceSWedson Almeida Filho 
163e7b9b1ffSAlice Ryhl     /// Releases the lock and waits for a notification in interruptible mode.
164e7b9b1ffSAlice Ryhl     ///
165e7b9b1ffSAlice Ryhl     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
166e7b9b1ffSAlice Ryhl     /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or
167e7b9b1ffSAlice Ryhl     /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal.
168e7b9b1ffSAlice Ryhl     #[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, ) -> CondVarTimeoutResult169e7b9b1ffSAlice Ryhl     pub fn wait_interruptible_timeout<T: ?Sized, B: Backend>(
170e7b9b1ffSAlice Ryhl         &self,
171e7b9b1ffSAlice Ryhl         guard: &mut Guard<'_, T, B>,
172e7b9b1ffSAlice Ryhl         jiffies: Jiffies,
173e7b9b1ffSAlice Ryhl     ) -> CondVarTimeoutResult {
174e7b9b1ffSAlice Ryhl         let jiffies = jiffies.try_into().unwrap_or(MAX_SCHEDULE_TIMEOUT);
175f090f0d0SAlice Ryhl         let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);
176e7b9b1ffSAlice Ryhl 
177e7b9b1ffSAlice Ryhl         match (res as Jiffies, crate::current!().signal_pending()) {
178e7b9b1ffSAlice Ryhl             (jiffies, true) => CondVarTimeoutResult::Signal { jiffies },
179e7b9b1ffSAlice Ryhl             (0, false) => CondVarTimeoutResult::Timeout,
180e7b9b1ffSAlice Ryhl             (jiffies, false) => CondVarTimeoutResult::Woken { jiffies },
181e7b9b1ffSAlice Ryhl         }
182e7b9b1ffSAlice Ryhl     }
183e7b9b1ffSAlice Ryhl 
184f090f0d0SAlice Ryhl     /// Calls the kernel function to notify the appropriate number of threads.
notify(&self, count: c_int)185f090f0d0SAlice Ryhl     fn notify(&self, count: c_int) {
1866b1b2326SCharalampos Mitrodimas         // SAFETY: `wait_queue_head` points to valid memory.
18719096bceSWedson Almeida Filho         unsafe {
18819096bceSWedson Almeida Filho             bindings::__wake_up(
1896b1b2326SCharalampos Mitrodimas                 self.wait_queue_head.get(),
190f090f0d0SAlice Ryhl                 TASK_NORMAL,
19119096bceSWedson Almeida Filho                 count,
192f090f0d0SAlice Ryhl                 ptr::null_mut(),
19319096bceSWedson Almeida Filho             )
19419096bceSWedson Almeida Filho         };
19519096bceSWedson Almeida Filho     }
19619096bceSWedson Almeida Filho 
1973e645417SAlice Ryhl     /// Calls the kernel function to notify one thread synchronously.
1983e645417SAlice Ryhl     ///
1993e645417SAlice Ryhl     /// This method behaves like `notify_one`, except that it hints to the scheduler that the
2003e645417SAlice Ryhl     /// current thread is about to go to sleep, so it should schedule the target thread on the same
2013e645417SAlice Ryhl     /// CPU.
notify_sync(&self)2023e645417SAlice Ryhl     pub fn notify_sync(&self) {
2033e645417SAlice Ryhl         // SAFETY: `wait_queue_head` points to valid memory.
204f090f0d0SAlice Ryhl         unsafe { bindings::__wake_up_sync(self.wait_queue_head.get(), TASK_NORMAL) };
2053e645417SAlice Ryhl     }
2063e645417SAlice Ryhl 
20719096bceSWedson Almeida Filho     /// Wakes a single waiter up, if any.
20819096bceSWedson Almeida Filho     ///
20919096bceSWedson Almeida Filho     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
21019096bceSWedson Almeida Filho     /// completely (as opposed to automatically waking up the next waiter).
notify_one(&self)21119096bceSWedson Almeida Filho     pub fn notify_one(&self) {
212f090f0d0SAlice Ryhl         self.notify(1);
21319096bceSWedson Almeida Filho     }
21419096bceSWedson Almeida Filho 
21519096bceSWedson Almeida Filho     /// Wakes all waiters up, if any.
21619096bceSWedson Almeida Filho     ///
21719096bceSWedson Almeida Filho     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
21819096bceSWedson Almeida Filho     /// completely (as opposed to automatically waking up the next waiter).
notify_all(&self)21919096bceSWedson Almeida Filho     pub fn notify_all(&self) {
220f090f0d0SAlice Ryhl         self.notify(0);
22119096bceSWedson Almeida Filho     }
22219096bceSWedson Almeida Filho }
223e7b9b1ffSAlice Ryhl 
224e7b9b1ffSAlice Ryhl /// The return type of `wait_timeout`.
225e7b9b1ffSAlice Ryhl pub enum CondVarTimeoutResult {
226e7b9b1ffSAlice Ryhl     /// The timeout was reached.
227e7b9b1ffSAlice Ryhl     Timeout,
228e7b9b1ffSAlice Ryhl     /// Somebody woke us up.
229e7b9b1ffSAlice Ryhl     Woken {
230e7b9b1ffSAlice Ryhl         /// Remaining sleep duration.
231e7b9b1ffSAlice Ryhl         jiffies: Jiffies,
232e7b9b1ffSAlice Ryhl     },
233e7b9b1ffSAlice Ryhl     /// A signal occurred.
234e7b9b1ffSAlice Ryhl     Signal {
235e7b9b1ffSAlice Ryhl         /// Remaining sleep duration.
236e7b9b1ffSAlice Ryhl         jiffies: Jiffies,
237e7b9b1ffSAlice Ryhl     },
238e7b9b1ffSAlice Ryhl }
239