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