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