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