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 bindings, init::PinInit, pin_init, str::CStr, task::MAX_SCHEDULE_TIMEOUT, time::Jiffies, 11 types::Opaque, 12 }; 13 use core::ffi::c_long; 14 use core::marker::PhantomPinned; 15 use macros::pin_data; 16 17 /// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class. 18 #[macro_export] 19 macro_rules! new_condvar { 20 ($($name:literal)?) => { 21 $crate::sync::CondVar::new($crate::optional_name!($($name)?), $crate::static_lock_class!()) 22 }; 23 } 24 25 /// A conditional variable. 26 /// 27 /// Exposes the kernel's [`struct wait_queue_head`] as a condition variable. It allows the caller to 28 /// atomically release the given lock and go to sleep. It reacquires the lock when it wakes up. And 29 /// it wakes up when notified by another thread (via [`CondVar::notify_one`] or 30 /// [`CondVar::notify_all`]) or because the thread received a signal. It may also wake up 31 /// spuriously. 32 /// 33 /// Instances of [`CondVar`] need a lock class and to be pinned. The recommended way to create such 34 /// instances is with the [`pin_init`](crate::pin_init) and [`new_condvar`] macros. 35 /// 36 /// # Examples 37 /// 38 /// The following is an example of using a condvar with a mutex: 39 /// 40 /// ``` 41 /// use kernel::sync::{CondVar, Mutex}; 42 /// use kernel::{new_condvar, new_mutex}; 43 /// 44 /// #[pin_data] 45 /// pub struct Example { 46 /// #[pin] 47 /// value: Mutex<u32>, 48 /// 49 /// #[pin] 50 /// value_changed: CondVar, 51 /// } 52 /// 53 /// /// Waits for `e.value` to become `v`. 54 /// fn wait_for_value(e: &Example, v: u32) { 55 /// let mut guard = e.value.lock(); 56 /// while *guard != v { 57 /// e.value_changed.wait(&mut guard); 58 /// } 59 /// } 60 /// 61 /// /// Increments `e.value` and notifies all potential waiters. 62 /// fn increment(e: &Example) { 63 /// *e.value.lock() += 1; 64 /// e.value_changed.notify_all(); 65 /// } 66 /// 67 /// /// Allocates a new boxed `Example`. 68 /// fn new_example() -> Result<Pin<Box<Example>>> { 69 /// Box::pin_init(pin_init!(Example { 70 /// value <- new_mutex!(0), 71 /// value_changed <- new_condvar!(), 72 /// })) 73 /// } 74 /// ``` 75 /// 76 /// [`struct wait_queue_head`]: srctree/include/linux/wait.h 77 #[pin_data] 78 pub struct CondVar { 79 #[pin] 80 pub(crate) wait_queue_head: Opaque<bindings::wait_queue_head>, 81 82 /// A condvar needs to be pinned because it contains a [`struct list_head`] that is 83 /// self-referential, so it cannot be safely moved once it is initialised. 84 #[pin] 85 _pin: PhantomPinned, 86 } 87 88 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread. 89 #[allow(clippy::non_send_fields_in_send_ty)] 90 unsafe impl Send for CondVar {} 91 92 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads 93 // concurrently. 94 unsafe impl Sync for CondVar {} 95 96 impl CondVar { 97 /// Constructs a new condvar initialiser. 98 pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> { 99 pin_init!(Self { 100 _pin: PhantomPinned, 101 // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have 102 // static lifetimes so they live indefinitely. 103 wait_queue_head <- Opaque::ffi_init(|slot| unsafe { 104 bindings::__init_waitqueue_head(slot, name.as_char_ptr(), key.as_ptr()) 105 }), 106 }) 107 } 108 109 fn wait_internal<T: ?Sized, B: Backend>( 110 &self, 111 wait_state: u32, 112 guard: &mut Guard<'_, T, B>, 113 timeout_in_jiffies: c_long, 114 ) -> c_long { 115 let wait = Opaque::<bindings::wait_queue_entry>::uninit(); 116 117 // SAFETY: `wait` points to valid memory. 118 unsafe { bindings::init_wait(wait.get()) }; 119 120 // SAFETY: Both `wait` and `wait_queue_head` point to valid memory. 121 unsafe { 122 bindings::prepare_to_wait_exclusive( 123 self.wait_queue_head.get(), 124 wait.get(), 125 wait_state as _, 126 ) 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(bindings::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(bindings::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(bindings::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 with the given flags. 182 fn notify(&self, count: i32, flags: u32) { 183 // SAFETY: `wait_queue_head` points to valid memory. 184 unsafe { 185 bindings::__wake_up( 186 self.wait_queue_head.get(), 187 bindings::TASK_NORMAL, 188 count, 189 flags as _, 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(), bindings::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, 0); 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, 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