rust: sync: add WaitQueue infrastructure
Subsystems (5)
Danilo Krummrich
reviewercover rust: sync: add WaitQueue infrastructure
Add a WaitQueue abstraction wrapping struct wait_queue_head, providing wait_event()-style methods that take a condition closure directly.
This is needed for a (subsequent) DRM patch series to wait for in-flight file close operations during driver unbind. The Tyr driver also needs it for "CSF firmware responses and other GPU-driven events" [1].
Convert CondVar (and PollCondVar) to use WaitQueue internally, removing duplicate code using WaitQueue as the base primitive.
Also replace the deprecated system_wq wrapper with system_percpu_wq and system_dfl_wq to avoid introducing more callers generating warnings that would need to be converted later.
[1] https://lore.kernel.org/dri-devel/[email protected]/
Danilo Krummrich (5):
rust: task: add safe schedule_timeout() wrapper
rust: workqueue: replace deprecated system_wq with
system_{percpu,dfl}_wq
rust: sync: add WaitQueue infrastructure
rust: sync: convert CondVar and PollCondVar to use WaitQueue
rust: sync: condvar: use task::schedule_timeout()
drivers/android/binder/process.rs | 4 +- rust/kernel/sync.rs | 6 + rust/kernel/sync/completion.rs | 2 +- rust/kernel/sync/condvar.rs | 104 +++----- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/sync/poll.rs | 14 +- rust/kernel/sync/wait.rs | 385 ++++++++++++++++++++++++++++++ rust/kernel/task.rs | 13 + rust/kernel/workqueue.rs | 40 ++-- 9 files changed, 469 insertions(+), 101 deletions(-) create mode 100644 rust/kernel/sync/wait.rs
base-commit: 6f6629ab2185d27cbc65d7d85908159b1293c082
Signature · 1 line
2.55.0
Danilo Krummrich
reviewerPATCH 1/5 rust: task: add safe schedule_timeout() wrapper
Add a safe wrapper around schedule_timeout() that takes and returns Jiffies, handling the c_long conversion internally.
--- rust/kernel/task.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+)
rust/kernel/task.rs +13 -0
@@ -10,6 +10,7 @@ pid_namespace::PidNamespace, prelude::*, sync::aref::ARef, + time::Jiffies, types::{NotThreadSafe, Opaque}, };use core::{
@@ -20,6 +21,18 @@/// A sentinel value used for infinite timeouts. pub const MAX_SCHEDULE_TIMEOUT :c_long = c_long::MAX ; +/// Sleeps for the given timeout in [`Jiffies`], or until woken. +/// +/// Returns the remaining time in [`Jiffies`], or zero if the timeout expired. The task state +/// should be set before calling this. +#[inline] +pub fn schedule_timeout (timeout:Jiffies ) ->Jiffies { +let timeout = timeout.try_into ().unwrap_or (MAX_SCHEDULE_TIMEOUT ); + +// SAFETY: `schedule_timeout()` is always safe to call. +unsafe { bindings::schedule_timeout (timeout)as Jiffies } +} +/// Bitmask for tasks that are sleeping in an interruptible state. pub const TASK_INTERRUPTIBLE :c_int = bindings::TASK_INTERRUPTIBLE as c_int ;/// Bitmask for tasks that are sleeping in an uninterruptible state.
Signature · 1 line
2.55.0
Danilo Krummrich
reviewerPATCH 2/5 rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq
In reply to Danilo Krummrichsystem_wq is deprecated and triggers a runtime warning:
[ 0.857414] workqueue: work func ...WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.Replace system() with system_percpu() and system_dfl(), to match the previous behavior of the deprecated system() and convert doc examples and tests to system_dfl().
--- drivers/android/binder/process.rs | 4 ++-- rust/kernel/sync/completion.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 40 +++++++++++++++++++------------ 4 files changed, 29 insertions(+), 19 deletions(-)
drivers/android/binder/process.rs +2 -2
@@ -1632,7 +1632,7 @@ pub(crate) fn release(this: Arc<Process>, _file: &File) {if should_schedule {// Ignore failures to schedule to the workqueue. Those just mean that we're already // scheduled for execution. -let _ = workqueue::system ().enqueue (this); +let _ = workqueue::system_percpu ().enqueue (this); }drop (binderfs_file);
@@ -1649,7 +1649,7 @@ pub(crate) fn flush(this: ArcBorrow<'_, Process>) -> Result {if should_schedule {// Ignore failures to schedule to the workqueue. Those just mean that we're already // scheduled for execution. -let _ = workqueue::system ().enqueue (Arc ::from (this)); +let _ = workqueue::system_percpu ().enqueue (Arc ::from (this)); }Ok (()) }
rust/kernel/sync/completion.rs +1 -1
@@ -38,7 +38,7 @@/// done <- Completion::new(), /// }), GFP_KERNEL)?; /// -/// let _ = workqueue::system().enqueue(this.clone()); +/// let _ = workqueue::system_dfl().enqueue(this.clone()); /// /// Ok(this) /// }
rust/kernel/sync/lock/spinlock.rs +1 -1
@@ -452,7 +452,7 @@ fn run(this: Arc<Self>) {fn spinlock_irq_condvar () ->Result {let testdata =Test ::new ()?; -let _ = workqueue::system ().enqueue (testdata.clone ()); +let _ = workqueue::system_dfl ().enqueue (testdata.clone ());// Let the updater know when we're ready to wait let mut state = testdata.state.lock ();
rust/kernel/workqueue.rs +25 -15
@@ -67,7 +67,7 @@//! /// This method will enqueue the struct for execution on the system workqueue, where its value //! /// will be printed. //! fn print_later(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue(val); +//! let _ = workqueue::system_dfl().enqueue(val); //! } //! # print_later(MyStruct::new(42).unwrap()); //! ```
@@ -121,11 +121,11 @@//! } //! //! fn print_1_later(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val); +//! let _ = workqueue::system_dfl().enqueue::<Arc<MyStruct>, 1>(val); //! } //! //! fn print_2_later(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val); +//! let _ = workqueue::system_dfl().enqueue::<Arc<MyStruct>, 2>(val); //! } //! # print_1_later(MyStruct::new(24, 25).unwrap()); //! # print_2_later(MyStruct::new(41, 42).unwrap());
@@ -171,13 +171,13 @@//! /// This method will enqueue the struct for execution on the system workqueue, where its value //! /// will be printed 12 jiffies later. //! fn print_later(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue_delayed(val, 12); +//! let _ = workqueue::system_dfl().enqueue_delayed(val, 12); //! } //! //! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This //! /// is equivalent to calling `enqueue_delayed` with a delay of zero. //! fn print_now(val: Arc<MyStruct>) { -//! let _ = workqueue::system().enqueue(val); +//! let _ = workqueue::system_dfl().enqueue(val); //! } //! # print_later(MyStruct::new(42).unwrap()); //! # print_now(MyStruct::new(42).unwrap());
@@ -1024,20 +1024,30 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for ARef<T> { } -/// Returns the system work queue (`system_wq`). +/// Returns the system per-cpu work queue (`system_percpu_wq`). /// /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are /// users which expect relatively short queue flush time. /// /// Callers shouldn't queue work items which can run for too long. -pub fn system () -> &'staticQueue { -// SAFETY: `system_wq` is a C global, always available. -unsafe {Queue ::from_raw (bindings::system_wq) } +pub fn system_percpu () -> &'staticQueue { +// SAFETY: `system_percpu_wq` is a C global, always available. +unsafe {Queue ::from_raw (bindings::system_percpu_wq) } +} + +/// Returns the system default (unbound) work queue (`system_dfl_wq`). +/// +/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items +/// are executed immediately as long as `max_active` limit is not reached and resources are +/// available. +pub fn system_dfl () -> &'staticQueue { +// SAFETY: `system_dfl_wq` is a C global, always available. +unsafe {Queue ::from_raw (bindings::system_dfl_wq) } }/// Returns the system high-priority work queue (`system_highpri_wq`). /// -/// It is similar to the one returned by [`system`] but for work items which require higher +/// It is similar to the one returned by [`system_percpu`] but for work items which require higher /// scheduling priority. pub fn system_highpri () -> &'staticQueue {// SAFETY: `system_highpri_wq` is a C global, always available.
@@ -1046,8 +1056,8 @@ pub fn system_highpri() -> &'static Queue {/// Returns the system work queue for potentially long-running work items (`system_long_wq`). /// -/// It is similar to the one returned by [`system`] but may host long running work items. Queue -/// flushing might take relatively long. +/// It is similar to the one returned by [`system_percpu`] but may host long running work items. +/// Queue flushing might take relatively long. pub fn system_long () -> &'staticQueue {// SAFETY: `system_long_wq` is a C global, always available. unsafe {Queue ::from_raw (bindings::system_long_wq) }
@@ -1065,7 +1075,7 @@ pub fn system_unbound() -> &'static Queue {/// Returns the system freezable work queue (`system_freezable_wq`). /// -/// It is equivalent to the one returned by [`system`] except that it's freezable. +/// It is equivalent to the one returned by [`system_percpu`] except that it's freezable. /// /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work /// items on the workqueue are drained and no new work item starts execution until thawed.
@@ -1078,7 +1088,7 @@ pub fn system_freezable() -> &'static Queue {/// /// It is inclined towards saving power and is converted to "unbound" variants if the /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one -/// returned by [`system`]. +/// returned by [`system_percpu`]. pub fn system_power_efficient () -> &'staticQueue {// SAFETY: `system_power_efficient_wq` is a C global, always available. unsafe {Queue ::from_raw (bindings::system_power_efficient_wq) }
@@ -1097,7 +1107,7 @@ pub fn system_freezable_power_efficient() -> &'static Queue {/// Returns the system bottom halves work queue (`system_bh_wq`). /// -/// It is similar to the one returned by [`system`] but for work items which +/// It is similar to the one returned by [`system_percpu`] but for work items which /// need to run from a softirq context. pub fn system_bh () -> &'staticQueue {// SAFETY: `system_bh_wq` is a C global, always available.
Signature · 1 line
2.55.0
Danilo Krummrich
reviewerPATCH 3/5 rust: sync: add WaitQueue infrastructure
In reply to Danilo KrummrichImplement a wait queue wrapping the kernel's struct wait_queue_head, with wait_event()-style methods that take a condition closure directly.
The API mirrors the C wait_event() family:
- wait_event()
- wait_event_interruptible()
- wait_event_timeout()
- wait_event_interruptible_timeout()
- wake_up() / wake_up_all() / wake_up_sync()
Interruptible and timeout variants return Result<(), WaitError>, where WaitError maps to ERESTARTSYS (signal) or ETIMEDOUT (timeout).
--- rust/kernel/sync.rs | 6 + rust/kernel/sync/wait.rs | 388 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 394 insertions(+) create mode 100644 rust/kernel/sync/wait.rs
rust/kernel/sync.rs +6 -0
@@ -21,6 +21,7 @@pub mod rcu;mod refcount;mod set_once; +mod wait;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ;
@@ -38,6 +39,11 @@pub use locked_by::LockedBy ;pub use refcount::Refcount ;pub use set_once::SetOnce ; +pub use wait::{ + new_waitqueue, +WaitError , +WaitQueue ,// +};/// Represents a lockdep class. ///
rust/kernel/sync/wait.rs new file +388 -0
388 lines not on this page · raw message
Signature · 1 line
2.55.0
Danilo Krummrich
reviewerPATCH 4/5 rust: sync: convert CondVar and PollCondVar to use WaitQueue
In reply to Danilo KrummrichCondVar currently wraps a raw wait_queue_head directly. Now that WaitQueue provides the same primitive, convert CondVar to use it instead. This removes duplicate init, pinning, Send/Sync, and wake-up code from CondVar.
Keep the wait logic in CondVar since it needs to release and reacquire a lock guard around the sleep, which WaitQueue's condition-based wait_event() methods do not handle. Use wait_once_exclusive() to perform a single prepare_to_wait_exclusive / finish_wait cycle with a caller-provided schedule function to implement the lock-aware sleep.
Adapt PollCondVar accordingly.
--- rust/kernel/sync/condvar.rs | 86 +++++++++++-------------------------- rust/kernel/sync/poll.rs | 14 +++--- rust/kernel/sync/wait.rs | 3 -- 3 files changed, 30 insertions(+), 73 deletions(-)
rust/kernel/sync/condvar.rs +24 -62
@@ -5,18 +5,26 @@//! This module allows Rust code to use the kernel's [`struct wait_queue_head`] as a condition //! variable. -use super ::{lock::Backend , lock::Guard ,LockClassKey }; +use super ::{ + lock::Backend , + lock::Guard , +LockClassKey , +WaitQueue ,// +}; +use crate ::{ - ffi::{c_int, c_long}, - str::{CStr ,CStrExt as _}, + prelude::*, + str::CStr , task::{ -MAX_SCHEDULE_TIMEOUT ,TASK_FREEZABLE ,TASK_INTERRUPTIBLE ,TASK_NORMAL ,TASK_UNINTERRUPTIBLE , +MAX_SCHEDULE_TIMEOUT , +TASK_FREEZABLE , +TASK_INTERRUPTIBLE , +TASK_UNINTERRUPTIBLE ,// }, time::Jiffies , - types::Opaque , }; -use core::{marker::PhantomPinned , pin::Pin , ptr}; -use pin_init::{pin_data, pin_init,PinInit }; + +use core::pin::Pin ;/// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class. #[macro_export]
@@ -81,33 +89,14 @@ macro_rules! new_condvar {#[pin_data] pub struct CondVar {#[pin] -pub (crate ) wait_queue_head:Opaque <bindings::wait_queue_head >, - -/// A condvar needs to be pinned because it contains a [`struct list_head`] that is -/// self-referential, so it cannot be safely moved once it is initialised. -/// -/// [`struct list_head`]: srctree/include/linux/types.h -#[pin] - _pin:PhantomPinned , +pub (crate ) wq:WaitQueue , } -// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread. -unsafe impl Send for CondVar {} - -// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads -// concurrently. -unsafe impl Sync for CondVar {} -impl CondVar {/// Constructs a new condvar initialiser. pub fn new (name: &'staticCStr , key:Pin <&'staticLockClassKey >) ->impl PinInit <Self > {pin_init! (Self { - _pin:PhantomPinned , -// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have -// static lifetimes so they live indefinitely. - wait_queue_head <-Opaque ::ffi_init (|slot|unsafe { - bindings::__init_waitqueue_head (slot, name.as_char_ptr (), key.as_ptr ()) - }), + wq <-WaitQueue ::new (name, key), }) }
@@ -117,23 +106,10 @@ fn wait_internal<T: ?Sized, B: Backend>( guard: &mut Guard<'_, T, B>, timeout_in_jiffies: c_long, ) -> c_long { -let wait =Opaque ::<bindings::wait_queue_entry >::uninit (); - -// SAFETY: `wait` points to valid memory. -unsafe { bindings::init_wait (wait.get ()) }; - -// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. -unsafe { - bindings::prepare_to_wait_exclusive (self.wait_queue_head.get (), wait.get (), wait_state) - }; - -// SAFETY: Switches to another thread. The timeout can be any number. -let ret = guard.do_unlocked (||unsafe { bindings::schedule_timeout (timeout_in_jiffies) }); - -// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. -unsafe { bindings::finish_wait (self.wait_queue_head.get (), wait.get ()) }; - - ret + self.wq.wait_once_exclusive (wait_state, || { +// SAFETY: Switches to another thread. The timeout can be any number. + guard.do_unlocked (||unsafe { bindings::schedule_timeout (timeout_in_jiffies) }) + }) }/// Releases the lock and waits for a notification in uninterruptible mode.
@@ -198,19 +174,6 @@ pub fn wait_interruptible_timeout<T: ?Sized, B: Backend>( } } -/// Calls the kernel function to notify the appropriate number of threads. -fn notify (&self, count:c_int ) { -// SAFETY: `wait_queue_head` points to valid memory. -unsafe { - bindings::__wake_up ( - self.wait_queue_head.get (), -TASK_NORMAL , - count, - ptr::null_mut (), - ) - }; - } -/// Calls the kernel function to notify one thread synchronously. /// /// This method behaves like `notify_one`, except that it hints to the scheduler that the
@@ -218,8 +181,7 @@ fn notify(&self, count: c_int) {/// CPU. #[inline] pub fn notify_sync (&self) { -// SAFETY: `wait_queue_head` points to valid memory. -unsafe { bindings::__wake_up_sync (self.wait_queue_head.get (),TASK_NORMAL ) }; + self.wq.wake_up_sync (); }/// Wakes a single waiter up, if any.
@@ -228,7 +190,7 @@ pub fn notify_sync(&self) {/// completely (as opposed to automatically waking up the next waiter). #[inline] pub fn notify_one (&self) { - self.notify (1 ); + self.wq.wake_up (); }/// Wakes all waiters up, if any.
@@ -237,7 +199,7 @@ pub fn notify_one(&self) {/// completely (as opposed to automatically waking up the next waiter). #[inline] pub fn notify_all (&self) { - self.notify (0 ); + self.wq.wake_up_all (); } }
rust/kernel/sync/poll.rs +6 -8
@@ -58,11 +58,11 @@ pub fn register_wait(&self, file: &File, cv: &PollCondVar) {// * `file.as_ptr()` references a valid file for the duration of this call. // * `self.table` is null or references a valid poll_table for the duration of this call. // * Since `PollCondVar` is pinned, its destructor is guaranteed to run before the memory -// containing `cv.wait_queue_head` is invalidated. Since the destructor clears all -// waiters and then waits for an rcu grace period, it's guaranteed that -// `cv.wait_queue_head` remains valid for at least an rcu grace period after the removal -// of the last waiter. -unsafe { bindings::poll_wait (file.as_ptr (), cv.wait_queue_head.get (), self.table) } +// containing the wait queue head is invalidated. Since the destructor clears all +// waiters and then waits for an rcu grace period, it's guaranteed that the wait queue +// head remains valid for at least an rcu grace period after the removal of the last +// waiter. +unsafe { bindings::poll_wait (file.as_ptr (), cv.wq.as_raw (), self.table) } } }
@@ -98,9 +98,7 @@ impl PinnedDrop for PollCondVar {#[inline] fn drop (self:Pin <&mut Self >) {// Clear anything registered using `register_wait`. -// -// SAFETY: The pointer points at a valid `wait_queue_head`. -unsafe { bindings::__wake_up_pollfree (self.inner.wait_queue_head.get ()) }; + self.inner.wq.wake_up_pollfree ();// Wait for epoll items to be properly removed. synchronize_rcu ();
rust/kernel/sync/wait.rs +0 -3
@@ -102,7 +102,6 @@ pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit }/// Returns a raw pointer to the underlying `wait_queue_head`. -#[expect(unused)] #[inline] pub (super )fn as_raw (&self) -> *mut bindings::wait_queue_head { self.wait_queue_head.get ()
@@ -213,7 +212,6 @@ fn wait_event_timeout_internal(/// Performs a single exclusive prepare-to-wait / finish-wait cycle, calling `schedule_fn` /// in between. -#[expect(unused)] pub (super )fn wait_once_exclusive <F ,R >(&self, wait_state:c_int , schedule_fn:F ) ->R where F :FnOnce () ->R ,
@@ -269,7 +267,6 @@ pub fn wake_up_sync(&self) {/// Used when a wait queue is about to be freed, to ensure epoll items are properly removed. /// Matches C's `wake_up_pollfree()`. #[inline] -#[expect(unused)] pub (super )fn wake_up_pollfree (&self) {// SAFETY: `wait_queue_head` points to valid memory. unsafe { bindings::__wake_up_pollfree (self.wait_queue_head.get ()) };
Signature · 1 line
2.55.0
Danilo Krummrich
reviewerPATCH 5/5 rust: sync: condvar: use task::schedule_timeout()
In reply to Danilo KrummrichConvert CondVar::wait_internal() from calling bindings::schedule_timeout() directly to using the safe task::schedule_timeout() wrapper. This removes the unsafe call and the Jiffies-to-c_long conversion from CondVar, since the wrapper handles it.
--- rust/kernel/sync/condvar.rs | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-)
rust/kernel/sync/condvar.rs +9 -15
@@ -16,7 +16,7 @@ prelude::*, str::CStr, task::{ -MAX_SCHEDULE_TIMEOUT , + self,TASK_FREEZABLE ,TASK_INTERRUPTIBLE ,TASK_UNINTERRUPTIBLE ,//
@@ -104,11 +104,10 @@ fn wait_internal<T: ?Sized, B: Backend>( &self, wait_state: c_int, guard: &mut Guard<'_, T, B>, - timeout_in_jiffies: c_long, - ) -> c_long { + timeout: Jiffies, + ) -> Jiffies { self.wq.wait_once_exclusive(wait_state, || { -// SAFETY: Switches to another thread. The timeout can be any number. - guard.do_unlocked (||unsafe { bindings::schedule_timeout (timeout_in_jiffies) }) + guard.do_unlocked (|| task::schedule_timeout (timeout)) }) }
@@ -119,7 +118,7 @@ fn wait_internal<T: ?Sized, B: Backend>(/// [`CondVar::notify_one`] or [`CondVar::notify_all`]. Note that it may also wake up /// spuriously. pub fn wait <T : ?Sized ,B :Backend >(&self, guard: &mut Guard <'_,T ,B >) { - self.wait_internal (TASK_UNINTERRUPTIBLE , guard,MAX_SCHEDULE_TIMEOUT ); + self.wait_internal (TASK_UNINTERRUPTIBLE , guard,Jiffies ::MAX ); }/// Releases the lock and waits for a notification in interruptible mode.
@@ -130,7 +129,7 @@ pub fn wait<T: ?Sized, B: Backend>(&self, guard: &mut Guard<'_, T, B>) {/// Returns whether there is a signal pending. #[must_use = "wait_interruptible returns if a signal is pending, so the caller must check the return value" ] pub fn wait_interruptible <T : ?Sized ,B :Backend >(&self, guard: &mut Guard <'_,T ,B >) ->bool { - self.wait_internal (TASK_INTERRUPTIBLE , guard,MAX_SCHEDULE_TIMEOUT ); + self.wait_internal (TASK_INTERRUPTIBLE , guard,Jiffies ::MAX );crate ::current!().signal_pending () }
@@ -145,11 +144,7 @@ pub fn wait_interruptible_freezable<T: ?Sized, B: Backend>( &self, guard: &mut Guard<'_, T, B>, ) -> bool { - self.wait_internal ( -TASK_INTERRUPTIBLE |TASK_FREEZABLE , - guard, -MAX_SCHEDULE_TIMEOUT , - ); + self.wait_internal (TASK_INTERRUPTIBLE |TASK_FREEZABLE , guard,Jiffies ::MAX );crate ::current!().signal_pending () }
@@ -164,10 +159,9 @@ pub fn wait_interruptible_timeout<T: ?Sized, B: Backend>( guard: &mut Guard<'_, T, B>, jiffies: Jiffies, ) -> CondVarTimeoutResult { -let jiffies = jiffies.try_into ().unwrap_or (MAX_SCHEDULE_TIMEOUT ); -let res = self.wait_internal (TASK_INTERRUPTIBLE , guard, jiffies); +let remaining = self.wait_internal (TASK_INTERRUPTIBLE , guard, jiffies); -match (resas Jiffies ,crate ::current!().signal_pending ()) { +match (remaining,current! ().signal_pending ()) { (jiffies,true ) =>CondVarTimeoutResult ::Signal { jiffies }, (0 ,false ) =>CondVarTimeoutResult ::Timeout , (jiffies,false ) =>CondVarTimeoutResult ::Woken { jiffies },
Signature · 1 line
2.55.0
Gary Guo
maintainerRe: [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq
In reply to Danilo KrummrichQuoted 7 lines · Danilo Krummrich
system_wqis deprecated and triggers a runtime warning:[ 0.857414] workqueue: work func ...WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.Replace
system()withsystem_percpu()andsystem_dfl(), to match the previous behavior of the deprecatedsystem()and convert doc examples and tests tosystem_dfl().
Hmm, it looks like
https://lore.kernel.org/rust-for-linux/[email protected]/
was never applied.
Best,
Gary
Quoted 8 lines
Signed-off-by Danilo Krummrich <[email protected]>--- drivers/android/binder/process.rs | 4 ++-- rust/kernel/sync/completion.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 40 +++++++++++++++++++------------ 4 files changed, 29 insertions(+), 19 deletions(-)
Gary Guo
maintainerQuoted 56 lines · Danilo Krummrich
Implement a wait queue wrapping the kernel's struct
wait_queue_head, with wait_event()-style methods that take a condition closure directly.The API mirrors the C
wait_event()family:-
wait_event()
-wait_event_interruptible()
-wait_event_timeout()
-wait_event_interruptible_timeout()
-wake_up()/wake_up_all()/wake_up_sync()Interruptible and timeout variants return Result<(), WaitError>, where WaitError maps to ERESTARTSYS (signal) or ETIMEDOUT (timeout).
Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/sync.rs | 6 + rust/kernel/sync/wait.rs | 388 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 394 insertions(+) create mode 100644 rust/kernel/sync/wait.rsrust/kernel/sync.rs +6
-0@@ -21,6 +21,7 @@pub mod rcu;mod refcount;mod set_once; +mod wait;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ;@@ -38,6 +39,11 @@pub use locked_by::LockedBy ;pub use refcount::Refcount ;pub use set_once::SetOnce ; +pub use wait::{ + new_waitqueue, +WaitError , +WaitQueue ,// +};/// Represents a lockdep class. /// rust/kernel/sync/wait.rs new file +5
-0@@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Wait queue. +//! +//! C header: [`include/linux/wait.h`](srctree/include/linux/wait.h)
rust/kernel/sync/wait.rs line 15
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+ +use super ::LockClassKey ; +use crate ::{ + prelude::*, + str::CStr , + task::{ + self, +TASK_INTERRUPTIBLE , +TASK_NORMAL , +TASK_UNINTERRUPTIBLE ,//
Hmm, I am not sure why we are exposing these as constants from kernel::task. Regardless, Given that you're using them for bindings, you should probably get them from bindings::TASK_* instead.
Quoted 77 lines
rust/kernel/sync/wait.rs new file +75
-0+ }, + time::Jiffies, + types::Opaque, +}; + +use core::{ + pin::Pin , + ptr,// +}; + +/// Creates a [`WaitQueue`] initialiser with the given name and a newly-created lock class. +#[macro_export] +macro_rules! new_waitqueue { + ($($name:literal)?) => { + $crate::sync::WaitQueue ::new ( + $crate::optional_name!($($name)?), + $crate::static_lock_class!(), + ) + }; +} +pub use new_waitqueue; + +/// Exposes the kernel's [`struct wait_queue_head`] as a Rust wait queue. +/// +/// A `WaitQueue` allows a thread to sleep until a caller-supplied condition becomes true, +/// re-checking the condition on each wake-up. This matches the C `wait_event()` family of macros. +/// +/// For waiting with a lock guard (the condition variable pattern), use [`CondVar`](super::CondVar) +/// instead. +/// +/// Instances of `WaitQueue` need a lock class and to be pinned. The recommended way to create such +/// instances is with the [`pin_init!`] and [`new_waitqueue!`] macros. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::{ +/// atomic::{ +/// Atomic, +/// Relaxed, +/// }, +/// new_waitqueue, +/// WaitQueue, +/// }; +/// +/// #[pin_data] +/// pub struct Example { +/// value: Atomic<i32>, +/// #[pin] +/// queue: WaitQueue, +/// } +/// +/// fn wait_for_value(e: &Example, v: i32) { +/// e.queue.wait_event(|| e.value.load(Relaxed) == v); +/// } +/// +/// fn set_value(e: &Example, v: i32) { +/// e.value.store(v, Relaxed); +/// e.queue.wake_up(); +/// } +/// ``` +/// +/// [`struct wait_queue_head`]: srctree/include/linux/wait.h +#[pin_data] +pub struct WaitQueue { +#[pin] + wait_queue_head:Opaque <bindings::wait_queue_head >, +} + +// SAFETY: `WaitQueue` only uses a `struct wait_queue_head`, which is safe to use on any thread. +unsafe impl Send for WaitQueue {} + +// SAFETY: `WaitQueue` only uses a `struct wait_queue_head`, which is safe to use on multiple +// threads concurrently. +unsafe impl Sync for WaitQueue {}
rust/kernel/sync/wait.rs line 102
Quoted 10 lines
rust/kernel/sync/wait.rs new file +9
-0+ +/// Error returned by [`WaitQueue`] wait functions. +#[derive( Debug , PartialEq )] +pub enum WaitError { +/// Interrupted by a signal. +Signal , +/// The timeout elapsed without the condition being met. +Timeout , +}
Do we want
/// Interrupted by a signal
pub struct Interrupted;
/// Timed out
pub struct TimedOut;
pub enum WaitError { ... }
impl From<Interrupted> for WaitError { ... }
impl From<TimedOut> for WaitError { ... }so that the user of wait_event_interruptible won't need to handle WaitError::Timeout and vice versa?
(I'd say that both these "error" types are quite commonly special handled so they probably do deserve there own error type)
Best,
Gary
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+ +impl From <WaitError >for Error { +#[inline] +fn from (e:WaitError ) ->Error { +match e { +WaitError ::Signal =>ERESTARTSYS , +WaitError ::Timeout =>ETIMEDOUT , + } + } +}
Danilo Krummrich
reviewerQuoted 12 lines · Gary Guo
Quoted 12 lines
rust/kernel/sync/wait.rs new file +11
-0@@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Wait queue. +//! +//! C header: [`include/linux/wait.h`](srctree/include/linux/wait.h) + +use super ::LockClassKey ; +use crate ::{ + prelude::*, + str::CStr , + task::{
Quoted 8 lines
rust/kernel/sync/wait.rs line 15
Quoted 4 lines
rust/kernel/sync/wait.rs new file +4
-0+ self, + TASK_INTERRUPTIBLE, + TASK_NORMAL, + TASK_UNINTERRUPTIBLE, //Hmm, I am not sure why we are exposing these as constants from
kernel::task. Regardless, Given that you're using them for bindings, you should probably get them from bindings::TASK_* instead.
See commit f090f0d0eea9 ("rust: sync: update integer types in CondVar"); personally I don't mind either way.
Gary Guo
maintainerQuoted 22 lines · Danilo Krummrich
Quoted 12 lines · Gary Guo
Quoted 12 lines
rust/kernel/sync/wait.rs new file +11
-0@@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Wait queue. +//! +//! C header: [`include/linux/wait.h`](srctree/include/linux/wait.h) + +use super ::LockClassKey ; +use crate ::{ + prelude::*, + str::CStr , + task::{Quoted 8 lines
rust/kernel/sync/wait.rs line 15
Quoted 4 lines
rust/kernel/sync/wait.rs new file +4
-0+ self, + TASK_INTERRUPTIBLE, + TASK_NORMAL, + TASK_UNINTERRUPTIBLE, //Hmm, I am not sure why we are exposing these as constants from
kernel::task. Regardless, Given that you're using them for bindings, you should probably get them from bindings::TASK_* instead.
Quoted 2 lines
See commit
f090f0d0eea9("rust: sync: update integer types in CondVar"); personally I don't mind either way.
We should probably find a way to do type casting in bindings crate for these instead.
I suppose the C API is also being inconsistent there, given that __state is unsigned int, while prepare_to_wait_event and friends use int. Not really an issue because TASK_ANY is 0xFFFF. But it does feel to me that we should actually be using unsigned int here.
Best,
Gary
Onur Özkan
reviewerQuoted 219 lines · On Mon, 27 Jul 2026 00:36:09 +0200 Danilo Krummrich <[email protected]> wrote:
Implement a wait queue wrapping the kernel's struct
wait_queue_head, with wait_event()-style methods that take a condition closure directly.The API mirrors the C
wait_event()family:-
wait_event()
-wait_event_interruptible()
-wait_event_timeout()
-wait_event_interruptible_timeout()
-wake_up()/wake_up_all()/wake_up_sync()Interruptible and timeout variants return Result<(), WaitError>, where WaitError maps to ERESTARTSYS (signal) or ETIMEDOUT (timeout).
Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/sync.rs | 6 + rust/kernel/sync/wait.rs | 388 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 394 insertions(+) create mode 100644 rust/kernel/sync/wait.rsrust/kernel/sync.rs +6
-0@@ -21,6 +21,7 @@pub mod rcu;mod refcount;mod set_once; +mod wait;pub use arc::{Arc ,ArcBorrow ,UniqueArc };pub use completion::Completion ;@@ -38,6 +39,11 @@pub use locked_by::LockedBy ;pub use refcount::Refcount ;pub use set_once::SetOnce ; +pub use wait::{ + new_waitqueue, +WaitError , +WaitQueue ,// +};/// Represents a lockdep class. /// rust/kernel/sync/wait.rs new file +168
-0@@ -0,0 +1,388 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Wait queue. +//! +//! C header: [`include/linux/wait.h`](srctree/include/linux/wait.h) + +use super ::LockClassKey ; +use crate ::{ + prelude::*, + str::CStr , + task::{ + self, +TASK_INTERRUPTIBLE , +TASK_NORMAL , +TASK_UNINTERRUPTIBLE ,// + }, + time::Jiffies , + types::Opaque , +}; + +use core::{ + pin::Pin , + ptr,// +}; + +/// Creates a [`WaitQueue`] initialiser with the given name and a newly-created lock class. +#[macro_export] +macro_rules! new_waitqueue { + ($($name:literal)?) => { + $crate::sync::WaitQueue ::new ( + $crate::optional_name!($($name)?), + $crate::static_lock_class!(), + ) + }; +} +pub use new_waitqueue; + +/// Exposes the kernel's [`struct wait_queue_head`] as a Rust wait queue. +/// +/// A `WaitQueue` allows a thread to sleep until a caller-supplied condition becomes true, +/// re-checking the condition on each wake-up. This matches the C `wait_event()` family of macros. +/// +/// For waiting with a lock guard (the condition variable pattern), use [`CondVar`](super::CondVar) +/// instead. +/// +/// Instances of `WaitQueue` need a lock class and to be pinned. The recommended way to create such +/// instances is with the [`pin_init!`] and [`new_waitqueue!`] macros. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::{ +/// atomic::{ +/// Atomic, +/// Relaxed, +/// }, +/// new_waitqueue, +/// WaitQueue, +/// }; +/// +/// #[pin_data] +/// pub struct Example { +/// value: Atomic<i32>, +/// #[pin] +/// queue: WaitQueue, +/// } +/// +/// fn wait_for_value(e: &Example, v: i32) { +/// e.queue.wait_event(|| e.value.load(Relaxed) == v); +/// } +/// +/// fn set_value(e: &Example, v: i32) { +/// e.value.store(v, Relaxed); +/// e.queue.wake_up(); +/// } +/// ``` +/// +/// [`struct wait_queue_head`]: srctree/include/linux/wait.h +#[pin_data] +pub struct WaitQueue { +#[pin] + wait_queue_head:Opaque <bindings::wait_queue_head >, +} + +// SAFETY: `WaitQueue` only uses a `struct wait_queue_head`, which is safe to use on any thread. +unsafe impl Send for WaitQueue {} + +// SAFETY: `WaitQueue` only uses a `struct wait_queue_head`, which is safe to use on multiple +// threads concurrently. +unsafe impl Sync for WaitQueue {} + +impl WaitQueue { +/// Constructs a new wait queue initialiser. +pub fn new (name: &'staticCStr , key:Pin <&'staticLockClassKey >) ->impl PinInit <Self > { +pin_init! (Self { +// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have +// static lifetimes so they live indefinitely. + wait_queue_head <-Opaque ::ffi_init (|slot|unsafe { + bindings::__init_waitqueue_head (slot, name.as_char_ptr (), key.as_ptr ()) + }), + }) + } + +/// Returns a raw pointer to the underlying `wait_queue_head`. +#[expect(unused)] +#[inline] +pub (super )fn as_raw (&self) -> *mut bindings::wait_queue_head { + self.wait_queue_head.get () + } + +/// Sleeps until the condition returns `true`. +/// +/// The condition is checked before each sleep and after each wake-up. The wait is +/// uninterruptible. +#[inline] +pub fn wait_event <F :Fn () ->bool >(&self, condition:F ) { + self.wait_event_timeout_internal (TASK_UNINTERRUPTIBLE , &condition,Jiffies ::MAX ); + } + +/// Sleeps until the condition returns `true` or a signal is received. +/// +/// Returns `Ok(())` when the condition is met, or `Err(WaitError::Signal)` if interrupted +/// by a signal. +#[inline] +pub fn wait_event_interruptible <F :Fn () ->bool >(&self, condition:F ) ->Result <(),WaitError > { + self.wait_event_timeout_internal (TASK_INTERRUPTIBLE , &condition,Jiffies ::MAX ); +if !condition () &¤t! ().signal_pending () { +Err (WaitError ::Signal ) + }else { +Ok (()) + } + } + +/// Sleeps until the condition returns `true` or the timeout expires. +/// +/// Returns `Ok(())` when the condition is met, or `Err(WaitError::Timeout)` if the timeout +/// elapsed first. +#[inline] +pub fn wait_event_timeout <F :Fn () ->bool >( + &self, + condition:F , + jiffies:Jiffies , + ) ->Result <(),WaitError > { +let remaining = self.wait_event_timeout_internal (TASK_UNINTERRUPTIBLE , &condition, jiffies); +if remaining ==0 && !condition () { +Err (WaitError ::Timeout ) + }else { +Ok (()) + } + } + +/// Sleeps until the condition returns `true`, a signal is received, or the timeout expires. +/// +/// Returns `Ok(())` when the condition is met, or `Err(WaitError)` on signal or timeout. +#[inline] +pub fn wait_event_interruptible_timeout <F :Fn () ->bool >( + &self, + condition:F , + jiffies:Jiffies , + ) ->Result <(),WaitError > { +let remaining = self.wait_event_timeout_internal (TASK_INTERRUPTIBLE , &condition, jiffies); +if condition () { +Ok (()) + }else if current! ().signal_pending () { +Err (WaitError ::Signal ) + }else if remaining ==0 { +Err (WaitError ::Timeout ) + }else {
rust/kernel/sync/wait.rs line 178
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+Ok (()) + } + } + +fn wait_event_timeout_internal ( + &self, + wait_state:c_int , + condition: &dyn Fn () ->bool , + jiffies:Jiffies , + ) ->Jiffies {
Would it make sense to check condition() first and return early?
Quoted 213 lines
rust/kernel/sync/wait.rs new file +210
-0+let wait =Opaque ::<bindings::wait_queue_entry >::uninit (); + +// SAFETY: `wait` points to valid memory. +unsafe { bindings::init_wait (wait.get ()) }; + +let mut remaining = jiffies; + +loop { +// SAFETY: Both `wait` and `wait_queue_head` point to valid memory, and `wait` was +// initialised by `init_wait()` above. +let ret =unsafe { + bindings::prepare_to_wait_event (self.wait_queue_head.get (), wait.get (), wait_state) + }; + +if condition () { +break ; + } + +if ret !=0 || remaining ==0 { +break ; + } + + remaining = task::schedule_timeout (remaining); + +if condition () { +break ; + } + } + +// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. +unsafe { bindings::finish_wait (self.wait_queue_head.get (), wait.get ()) }; + + remaining + } + +/// Performs a single exclusive prepare-to-wait / finish-wait cycle, calling `schedule_fn` +/// in between. +#[expect(unused)] +pub (super )fn wait_once_exclusive <F ,R >(&self, wait_state:c_int , schedule_fn:F ) ->R +where +F :FnOnce () ->R , + { +let wait =Opaque ::<bindings::wait_queue_entry >::uninit (); + +// SAFETY: `wait` points to valid memory. +unsafe { bindings::init_wait (wait.get ()) }; + +// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. +unsafe { + bindings::prepare_to_wait_exclusive (self.wait_queue_head.get (), wait.get (), wait_state) + }; + +let ret =schedule_fn (); + +// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. +unsafe { bindings::finish_wait (self.wait_queue_head.get (), wait.get ()) }; + + ret + } + +/// Wakes up waiters. +/// +/// Wakes all non-exclusive waiters and one exclusive waiter, if any. Matches C's `wake_up()`. +#[inline] +pub fn wake_up (&self) { +// SAFETY: `wait_queue_head` points to valid memory. +unsafe { bindings::__wake_up (self.wait_queue_head.get (),TASK_NORMAL ,1 , ptr::null_mut ()) }; + } + +/// Wakes up all waiters. +/// +/// Wakes all non-exclusive and all exclusive waiters, if any. +/// Matches C's `wake_up_all()`. +#[inline] +pub fn wake_up_all (&self) { +// SAFETY: `wait_queue_head` points to valid memory. +unsafe { bindings::__wake_up (self.wait_queue_head.get (),TASK_NORMAL ,0 , ptr::null_mut ()) }; + } + +/// Like [`wake_up()`](Self::wake_up), but hints to the scheduler that the current task is +/// about to sleep, so the woken task should be scheduled on the same CPU to avoid unnecessary +/// migration. Matches C's `wake_up_sync()`. +#[inline] +pub fn wake_up_sync (&self) { +// SAFETY: `wait_queue_head` points to valid memory. +unsafe { bindings::__wake_up_sync (self.wait_queue_head.get (),TASK_NORMAL ) }; + } + +/// Wakes up all waiters and clears poll registrations. +/// +/// Used when a wait queue is about to be freed, to ensure epoll items are properly removed. +/// Matches C's `wake_up_pollfree()`. +#[inline] +#[expect(unused)] +pub (super )fn wake_up_pollfree (&self) { +// SAFETY: `wait_queue_head` points to valid memory. +unsafe { bindings::__wake_up_pollfree (self.wait_queue_head.get ()) }; + } +} + +/// Error returned by [`WaitQueue`] wait functions. +#[derive( Debug , PartialEq )] +pub enum WaitError { +/// Interrupted by a signal. +Signal , +/// The timeout elapsed without the condition being met. +Timeout , +} + +impl From <WaitError >for Error { +#[inline] +fn from (e:WaitError ) ->Error { +match e { +WaitError ::Signal =>ERESTARTSYS , +WaitError ::Timeout =>ETIMEDOUT , + } + } +} + +#[macros::kunit_tests(rust_waitqueue)] +mod tests { +use super ::*; +use crate ::{ + sync::{ + atomic::{ +Atomic , +Relaxed ,// + }, +Arc , + }, + time::{ + delay::fsleep, +Delta ,// + }, + workqueue, + }; + +#[pin_data] +struct State { + value:Atomic <i32 >, +#[pin] + wq:WaitQueue , + } + +impl State { +fn new () ->Result <Arc <Self >> { +Arc ::pin_init ( +pin_init! (Self { + value:Atomic ::new (0 ), + wq <-new_waitqueue! (), + }), +GFP_KERNEL , + ) + } + } + +#[test] +fn wait_event_from_work () { +let s =State ::new ().unwrap (); + +let s2 = s.clone (); + workqueue::system_dfl () + .try_spawn (GFP_KERNEL ,move || { + s2.value.store (1 ,Relaxed ); + s2.wq.wake_up (); + }) + .unwrap (); + + s.wq.wait_event (|| s.value.load (Relaxed ) ==1 ); +assert_eq! (s.value.load (Relaxed ),1 ); + } + +#[test] +fn wait_event_condition_already_true () { +let s =State ::new ().unwrap (); + s.value.store (1 ,Relaxed ); + + s.wq.wait_event (|| s.value.load (Relaxed ) ==1 ); +assert_eq! (s.value.load (Relaxed ),1 ); + } + +#[test] +fn wait_event_condition_not_yet_met () { +let s =State ::new ().unwrap (); + +let s2 = s.clone (); + workqueue::system_dfl () + .try_spawn (GFP_KERNEL ,move || { + s2.value.store (1 ,Relaxed ); + s2.wq.wake_up_all (); + +fsleep (Delta ::from_millis (50 )); + + s2.value.store (2 ,Relaxed ); + s2.wq.wake_up_all (); + }) + .unwrap (); + + s.wq.wait_event (|| s.value.load (Relaxed ) ==2 ); +assert_eq! (s.value.load (Relaxed ),2 ); + } + +#[test] +fn wait_event_timeout_expires () { +let s =State ::new ().unwrap (); + +let ret = s.wq.wait_event_timeout (|| s.value.load (Relaxed ) ==1 ,1 ); +assert_eq! (ret,Err (WaitError ::Timeout )); + } +}Signature · 1 line
2.55.0
Alice Ryhl
maintainerrust/kernel/sync/wait.rs line 107
Quoted 4 lines · Danilo Krummrich
rust/kernel/sync/wait.rs new file +4
-0+/// Returns a raw pointer to the underlying `wait_queue_head`. +#[expect(unused)] +#[inline] +pub (super )fn as_raw (&self) -> *mut bindings::wait_queue_head {
This should 'pub'. Then you can drop #[expect(unused)].
rust/kernel/sync/wait.rs line 131
Quoted 12 lines
rust/kernel/sync/wait.rs new file +12
-0+/// Sleeps until the condition returns `true` or a signal is received. +/// +/// Returns `Ok(())` when the condition is met, or `Err(WaitError::Signal)` if interrupted +/// by a signal. +#[inline] +pub fn wait_event_interruptible <F :Fn () ->bool >(&self, condition:F ) ->Result <(),WaitError > { + self.wait_event_timeout_internal (TASK_INTERRUPTIBLE , &condition,Jiffies ::MAX ); +if !condition () &¤t! ().signal_pending () { +Err (WaitError ::Signal ) + }else { +Ok (()) + }
I don't think we should call condition() again here. Instead, I think we should base it on which 'break' statement was used in wait_event_timeout_internal().
Quoted 6 lines
rust/kernel/sync/wait.rs new file +6
-0+/// Sleeps until the condition returns `true` or the timeout expires. +/// +/// Returns `Ok(())` when the condition is met, or `Err(WaitError::Timeout)` if the timeout +/// elapsed first. +#[inline] + pub fn wait_event_timeout<F: Fn() -> bool>(
rust/kernel/sync/wait.rs line 149
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+ &self, + condition: F, + jiffies: Jiffies, + ) -> Result<(), WaitError> { +let remaining = self.wait_event_timeout_internal (TASK_UNINTERRUPTIBLE , &condition, jiffies); +if remaining ==0 && !condition () { +Err (WaitError ::Timeout ) + }else { +Ok (()) + }
Ditto here.
rust/kernel/sync/wait.rs line 178
Quoted 6 lines
rust/kernel/sync/wait.rs new file +6
-0+fn wait_event_timeout_internal ( + &self, + wait_state:c_int , + condition: &dyn Fn () ->bool , + jiffies:Jiffies , + ) ->Jiffies {
Why are we using dynamic dispatch here?
Quoted 5 lines
rust/kernel/sync/wait.rs new file +5
-0+/// Performs a single exclusive prepare-to-wait / finish-wait cycle, calling `schedule_fn` +/// in between. +#[expect(unused)] +pub (super )fn wait_once_exclusive <F ,R >(&self, wait_state:c_int , schedule_fn:F ) ->R +where
rust/kernel/sync/wait.rs line 228
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+ F: FnOnce() -> R, + { +let wait =Opaque ::<bindings::wait_queue_entry >::uninit (); + +// SAFETY: `wait` points to valid memory. +unsafe { bindings::init_wait (wait.get ()) }; + +// SAFETY: Both `wait` and `wait_queue_head` point to valid memory. +unsafe { + bindings::prepare_to_wait_exclusive (self.wait_queue_head.get (), wait.get (), wait_state)
What about the non-exclusive prepare_to_wait? That's the one Rust Binder *should* be using here. It's not ideal that it's using the exclusive wait.
Quoted 8 lines
rust/kernel/sync/wait.rs new file +8
-0+/// Error returned by [`WaitQueue`] wait functions. +#[derive( Debug , PartialEq )] +pub enum WaitError { +/// Interrupted by a signal. +Signal , +/// The timeout elapsed without the condition being met. +Timeout , +}
rust/kernel/sync/wait.rs line 296
Quoted 10 lines
rust/kernel/sync/wait.rs new file +10
-0+ +impl From <WaitError >for Error { +#[inline] +fn from (e:WaitError ) ->Error { +match e { +WaitError ::Signal =>ERESTARTSYS , +WaitError ::Timeout =>ETIMEDOUT , + } + } +}
I agree with Gary's comment about splitting up this error type.
Alice