xref: /linux/rust/kernel/sync/condvar.rs (revision e6ea10d5dbe082c54add289b44f08c9fcfe658af)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! A condition variable.
4 //!
5 //! This module allows Rust code to use the kernel's [`struct wait_queue_head`] as a condition
6 //! variable.
7 
8 use super::{lock::Backend, lock::Guard, LockClassKey};
9 use crate::{
10     ffi::{c_int, c_long},
11     str::CStr,
12     task::{MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE},
13     time::Jiffies,
14     types::Opaque,
15 };
16 use core::marker::PhantomPinned;
17 use core::ptr;
18 use pin_init::{pin_data, pin_init, PinInit};
19 
20 /// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class.
21 #[macro_export]
22 macro_rules! new_condvar {
23     ($($name:literal)?) => {
24         $crate::sync::CondVar::new($crate::optional_name!($($name)?), $crate::static_lock_class!())
25     };
26 }
27 pub use new_condvar;
28 
29 /// A conditional variable.
30 ///
31 /// Exposes the kernel's [`struct wait_queue_head`] as a condition variable. It allows the caller to
32 /// atomically release the given lock and go to sleep. It reacquires the lock when it wakes up. And
33 /// it wakes up when notified by another thread (via [`CondVar::notify_one`] or
34 /// [`CondVar::notify_all`]) or because the thread received a signal. It may also wake up
35 /// spuriously.
36 ///
37 /// Instances of [`CondVar`] need a lock class and to be pinned. The recommended way to create such
38 /// instances is with the [`pin_init`](crate::pin_init!) and [`new_condvar`] macros.
39 ///
40 /// # Examples
41 ///
42 /// The following is an example of using a condvar with a mutex:
43 ///
44 /// ```
45 /// use kernel::sync::{new_condvar, new_mutex, CondVar, Mutex};
46 ///
47 /// #[pin_data]
48 /// pub struct Example {
49 ///     #[pin]
50 ///     value: Mutex<u32>,
51 ///
52 ///     #[pin]
53 ///     value_changed: CondVar,
54 /// }
55 ///
56 /// /// Waits for `e.value` to become `v`.
57 /// fn wait_for_value(e: &Example, v: u32) {
58 ///     let mut guard = e.value.lock();
59 ///     while *guard != v {
60 ///         e.value_changed.wait(&mut guard);
61 ///     }
62 /// }
63 ///
64 /// /// Increments `e.value` and notifies all potential waiters.
65 /// fn increment(e: &Example) {
66 ///     *e.value.lock() += 1;
67 ///     e.value_changed.notify_all();
68 /// }
69 ///
70 /// /// Allocates a new boxed `Example`.
71 /// fn new_example() -> Result<Pin<KBox<Example>>> {
72 ///     KBox::pin_init(pin_init!(Example {
73 ///         value <- new_mutex!(0),
74 ///         value_changed <- new_condvar!(),
75 ///     }), GFP_KERNEL)
76 /// }
77 /// ```
78 ///
79 /// [`struct wait_queue_head`]: srctree/include/linux/wait.h
80 #[pin_data]
81 pub struct CondVar {
82     #[pin]
83     pub(crate) wait_queue_head: Opaque<bindings::wait_queue_head>,
84 
85     /// A condvar needs to be pinned because it contains a [`struct list_head`] that is
86     /// self-referential, so it cannot be safely moved once it is initialised.
87     ///
88     /// [`struct list_head`]: srctree/include/linux/types.h
89     #[pin]
90     _pin: PhantomPinned,
91 }
92 
93 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
94 unsafe impl Send for CondVar {}
95 
96 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads
97 // concurrently.
98 unsafe impl Sync for CondVar {}
99 
100 impl CondVar {
101     /// Constructs a new condvar initialiser.
102     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> {
103         pin_init!(Self {
104             _pin: PhantomPinned,
105             // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
106             // static lifetimes so they live indefinitely.
107             wait_queue_head <- Opaque::ffi_init(|slot| unsafe {
108                 bindings::__init_waitqueue_head(slot, name.as_char_ptr(), key.as_ptr())
109             }),
110         })
111     }
112 
113     fn wait_internal<T: ?Sized, B: Backend>(
114         &self,
115         wait_state: c_int,
116         guard: &mut Guard<'_, T, B>,
117         timeout_in_jiffies: c_long,
118     ) -> c_long {
119         let wait = Opaque::<bindings::wait_queue_entry>::uninit();
120 
121         // SAFETY: `wait` points to valid memory.
122         unsafe { bindings::init_wait(wait.get()) };
123 
124         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
125         unsafe {
126             bindings::prepare_to_wait_exclusive(self.wait_queue_head.get(), wait.get(), wait_state)
127         };
128 
129         // SAFETY: Switches to another thread. The timeout can be any number.
130         let ret = guard.do_unlocked(|| unsafe { bindings::schedule_timeout(timeout_in_jiffies) });
131 
132         // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
133         unsafe { bindings::finish_wait(self.wait_queue_head.get(), wait.get()) };
134 
135         ret
136     }
137 
138     /// Releases the lock and waits for a notification in uninterruptible mode.
139     ///
140     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
141     /// thread to sleep, reacquiring the lock on wake up. It wakes up when notified by
142     /// [`CondVar::notify_one`] or [`CondVar::notify_all`]. Note that it may also wake up
143     /// spuriously.
144     pub fn wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) {
145         self.wait_internal(TASK_UNINTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
146     }
147 
148     /// Releases the lock and waits for a notification in interruptible mode.
149     ///
150     /// Similar to [`CondVar::wait`], except that the wait is interruptible. That is, the thread may
151     /// wake up due to signals. It may also wake up spuriously.
152     ///
153     /// Returns whether there is a signal pending.
154     #[must_use = "wait_interruptible returns if a signal is pending, so the caller must check the return value"]
155     pub fn wait_interruptible<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) -> bool {
156         self.wait_internal(TASK_INTERRUPTIBLE, guard, MAX_SCHEDULE_TIMEOUT);
157         crate::current!().signal_pending()
158     }
159 
160     /// Releases the lock and waits for a notification in interruptible mode.
161     ///
162     /// Atomically releases the given lock (whose ownership is proven by the guard) and puts the
163     /// thread to sleep. It wakes up when notified by [`CondVar::notify_one`] or
164     /// [`CondVar::notify_all`], or when a timeout occurs, or when the thread receives a signal.
165     #[must_use = "wait_interruptible_timeout returns if a signal is pending, so the caller must check the return value"]
166     pub fn wait_interruptible_timeout<T: ?Sized, B: Backend>(
167         &self,
168         guard: &mut Guard<'_, T, B>,
169         jiffies: Jiffies,
170     ) -> CondVarTimeoutResult {
171         let jiffies = jiffies.try_into().unwrap_or(MAX_SCHEDULE_TIMEOUT);
172         let res = self.wait_internal(TASK_INTERRUPTIBLE, guard, jiffies);
173 
174         match (res as Jiffies, crate::current!().signal_pending()) {
175             (jiffies, true) => CondVarTimeoutResult::Signal { jiffies },
176             (0, false) => CondVarTimeoutResult::Timeout,
177             (jiffies, false) => CondVarTimeoutResult::Woken { jiffies },
178         }
179     }
180 
181     /// Calls the kernel function to notify the appropriate number of threads.
182     fn notify(&self, count: c_int) {
183         // SAFETY: `wait_queue_head` points to valid memory.
184         unsafe {
185             bindings::__wake_up(
186                 self.wait_queue_head.get(),
187                 TASK_NORMAL,
188                 count,
189                 ptr::null_mut(),
190             )
191         };
192     }
193 
194     /// Calls the kernel function to notify one thread synchronously.
195     ///
196     /// This method behaves like `notify_one`, except that it hints to the scheduler that the
197     /// current thread is about to go to sleep, so it should schedule the target thread on the same
198     /// CPU.
199     pub fn notify_sync(&self) {
200         // SAFETY: `wait_queue_head` points to valid memory.
201         unsafe { bindings::__wake_up_sync(self.wait_queue_head.get(), TASK_NORMAL) };
202     }
203 
204     /// Wakes a single waiter up, if any.
205     ///
206     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
207     /// completely (as opposed to automatically waking up the next waiter).
208     pub fn notify_one(&self) {
209         self.notify(1);
210     }
211 
212     /// Wakes all waiters up, if any.
213     ///
214     /// This is not 'sticky' in the sense that if no thread is waiting, the notification is lost
215     /// completely (as opposed to automatically waking up the next waiter).
216     pub fn notify_all(&self) {
217         self.notify(0);
218     }
219 }
220 
221 /// The return type of `wait_timeout`.
222 pub enum CondVarTimeoutResult {
223     /// The timeout was reached.
224     Timeout,
225     /// Somebody woke us up.
226     Woken {
227         /// Remaining sleep duration.
228         jiffies: Jiffies,
229     },
230     /// A signal occurred.
231     Signal {
232         /// Remaining sleep duration.
233         jiffies: Jiffies,
234     },
235 }
236