condvar.rs 8.4 KB

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