* [PATCH 1/5] rust: task: add safe schedule_timeout() wrapper
2026-07-26 22:36 [PATCH 0/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
@ 2026-07-26 22:36 ` Danilo Krummrich
2026-07-26 22:36 ` [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq Danilo Krummrich
` (3 subsequent siblings)
4 siblings, 0 replies; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-26 22:36 UTC (permalink / raw)
To: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, gary,
lyude, daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel, Danilo Krummrich
Add a safe wrapper around schedule_timeout() that takes and returns
Jiffies, handling the c_long conversion internally.
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
rust/kernel/task.rs | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs
index 38273f4eedb5..0d63beb3fb37 100644
--- a/rust/kernel/task.rs
+++ b/rust/kernel/task.rs
@@ -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.
--
2.55.0
^ permalink raw reply related [flat|nested] 9+ messages in thread* [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq
2026-07-26 22:36 [PATCH 0/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
2026-07-26 22:36 ` [PATCH 1/5] rust: task: add safe schedule_timeout() wrapper Danilo Krummrich
@ 2026-07-26 22:36 ` Danilo Krummrich
2026-07-27 11:53 ` Gary Guo
2026-07-26 22:36 ` [PATCH 3/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
` (2 subsequent siblings)
4 siblings, 1 reply; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-26 22:36 UTC (permalink / raw)
To: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, gary,
lyude, daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel, Danilo Krummrich
system_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().
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
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(-)
diff --git a/drivers/android/binder/process.rs b/drivers/android/binder/process.rs
index 96b8440ceac6..c0266fdaa598 100644
--- a/drivers/android/binder/process.rs
+++ b/drivers/android/binder/process.rs
@@ -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(())
}
diff --git a/rust/kernel/sync/completion.rs b/rust/kernel/sync/completion.rs
index 35ff049ff078..1771bfc0ade2 100644
--- a/rust/kernel/sync/completion.rs
+++ b/rust/kernel/sync/completion.rs
@@ -38,7 +38,7 @@
/// done <- Completion::new(),
/// }), GFP_KERNEL)?;
///
-/// let _ = workqueue::system().enqueue(this.clone());
+/// let _ = workqueue::system_dfl().enqueue(this.clone());
///
/// Ok(this)
/// }
diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spinlock.rs
index 069fcdb58735..c6fba8d0f5b2 100644
--- a/rust/kernel/sync/lock/spinlock.rs
+++ b/rust/kernel/sync/lock/spinlock.rs
@@ -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();
diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index 7e253b6f299c..3194b9c441aa 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -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() -> &'static Queue {
- // SAFETY: `system_wq` is a C global, always available.
- unsafe { Queue::from_raw(bindings::system_wq) }
+pub fn system_percpu() -> &'static Queue {
+ // 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() -> &'static Queue {
+ // 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() -> &'static Queue {
// 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() -> &'static Queue {
// 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() -> &'static Queue {
// 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() -> &'static Queue {
// SAFETY: `system_bh_wq` is a C global, always available.
--
2.55.0
^ permalink raw reply related [flat|nested] 9+ messages in thread* Re: [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq
2026-07-26 22:36 ` [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq Danilo Krummrich
@ 2026-07-27 11:53 ` Gary Guo
0 siblings, 0 replies; 9+ messages in thread
From: Gary Guo @ 2026-07-27 11:53 UTC (permalink / raw)
To: Danilo Krummrich, gregkh, arve, tkjos, brauner, cmllamas,
aliceryhl, boqun, gary, lyude, daniel.almeida, work, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg,
tmgross, tamird, acourbot, peterz, mingo, will, longman, viro,
jack, tj, jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel
On Sun Jul 26, 2026 at 11:36 PM BST, Danilo Krummrich wrote:
> system_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().
Hmm, it looks like
https://lore.kernel.org/rust-for-linux/20260203152818.317806-1-marco.crivellari@suse.com/
was never applied.
Best,
Gary
>
> Signed-off-by: Danilo Krummrich <dakr@kernel.org>
> ---
> 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(-)
^ permalink raw reply [flat|nested] 9+ messages in thread
* [PATCH 3/5] rust: sync: add WaitQueue infrastructure
2026-07-26 22:36 [PATCH 0/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
2026-07-26 22:36 ` [PATCH 1/5] rust: task: add safe schedule_timeout() wrapper Danilo Krummrich
2026-07-26 22:36 ` [PATCH 2/5] rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq Danilo Krummrich
@ 2026-07-26 22:36 ` Danilo Krummrich
2026-07-27 12:02 ` Gary Guo
2026-07-26 22:36 ` [PATCH 4/5] rust: sync: convert CondVar and PollCondVar to use WaitQueue Danilo Krummrich
2026-07-26 22:36 ` [PATCH 5/5] rust: sync: condvar: use task::schedule_timeout() Danilo Krummrich
4 siblings, 1 reply; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-26 22:36 UTC (permalink / raw)
To: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, gary,
lyude, daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel, 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 <dakr@kernel.org>
---
rust/kernel/sync.rs | 6 +
rust/kernel/sync/wait.rs | 388 +++++++++++++++++++++++++++++++++++++++
2 files changed, 394 insertions(+)
create mode 100644 rust/kernel/sync/wait.rs
diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs
index df4f2604ff9b..31f0999e5747 100644
--- a/rust/kernel/sync.rs
+++ b/rust/kernel/sync.rs
@@ -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.
///
diff --git a/rust/kernel/sync/wait.rs b/rust/kernel/sync/wait.rs
new file mode 100644
index 000000000000..ba4ee0f8d4d4
--- /dev/null
+++ b/rust/kernel/sync/wait.rs
@@ -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: &'static CStr, key: Pin<&'static LockClassKey>) -> 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() && current!().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 {
+ Ok(())
+ }
+ }
+
+ fn wait_event_timeout_internal(
+ &self,
+ wait_state: c_int,
+ condition: &dyn Fn() -> bool,
+ jiffies: Jiffies,
+ ) -> Jiffies {
+ 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));
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 9+ messages in thread* Re: [PATCH 3/5] rust: sync: add WaitQueue infrastructure
2026-07-26 22:36 ` [PATCH 3/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
@ 2026-07-27 12:02 ` Gary Guo
2026-07-27 12:46 ` Danilo Krummrich
0 siblings, 1 reply; 9+ messages in thread
From: Gary Guo @ 2026-07-27 12:02 UTC (permalink / raw)
To: Danilo Krummrich, gregkh, arve, tkjos, brauner, cmllamas,
aliceryhl, boqun, gary, lyude, daniel.almeida, work, juri.lelli,
vincent.guittot, dietmar.eggemann, rostedt, bsegall, mgorman,
vschneid, kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg,
tmgross, tamird, acourbot, peterz, mingo, will, longman, viro,
jack, tj, jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel
On Sun Jul 26, 2026 at 11:36 PM BST, Danilo Krummrich 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 <dakr@kernel.org>
> ---
> rust/kernel/sync.rs | 6 +
> rust/kernel/sync/wait.rs | 388 +++++++++++++++++++++++++++++++++++++++
> 2 files changed, 394 insertions(+)
> create mode 100644 rust/kernel/sync/wait.rs
>
> diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs
> index df4f2604ff9b..31f0999e5747 100644
> --- a/rust/kernel/sync.rs
> +++ b/rust/kernel/sync.rs
> @@ -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.
> ///
> diff --git a/rust/kernel/sync/wait.rs b/rust/kernel/sync/wait.rs
> new file mode 100644
> index 000000000000..ba4ee0f8d4d4
> --- /dev/null
> +++ b/rust/kernel/sync/wait.rs
> @@ -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, //
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.
> + },
> + 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 {}
>
> [snip]
>
> +
> +/// 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
> +
> +impl From<WaitError> for Error {
> + #[inline]
> + fn from(e: WaitError) -> Error {
> + match e {
> + WaitError::Signal => ERESTARTSYS,
> + WaitError::Timeout => ETIMEDOUT,
> + }
> + }
> +}
^ permalink raw reply [flat|nested] 9+ messages in thread* Re: [PATCH 3/5] rust: sync: add WaitQueue infrastructure
2026-07-27 12:02 ` Gary Guo
@ 2026-07-27 12:46 ` Danilo Krummrich
0 siblings, 0 replies; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-27 12:46 UTC (permalink / raw)
To: Gary Guo
Cc: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, lyude,
daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai, linux-kernel, rust-for-linux, linux-fsdevel
On Mon Jul 27, 2026 at 2:02 PM CEST, Gary Guo wrote:
>> @@ -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, //
>
> 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.
^ permalink raw reply [flat|nested] 9+ messages in thread
* [PATCH 4/5] rust: sync: convert CondVar and PollCondVar to use WaitQueue
2026-07-26 22:36 [PATCH 0/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
` (2 preceding siblings ...)
2026-07-26 22:36 ` [PATCH 3/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
@ 2026-07-26 22:36 ` Danilo Krummrich
2026-07-26 22:36 ` [PATCH 5/5] rust: sync: condvar: use task::schedule_timeout() Danilo Krummrich
4 siblings, 0 replies; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-26 22:36 UTC (permalink / raw)
To: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, gary,
lyude, daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel, Danilo Krummrich
CondVar 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.
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
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(-)
diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs
index 69d58dfbad7b..d4bfc936423e 100644
--- a/rust/kernel/sync/condvar.rs
+++ b/rust/kernel/sync/condvar.rs
@@ -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: &'static CStr, key: Pin<&'static LockClassKey>) -> 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();
}
}
diff --git a/rust/kernel/sync/poll.rs b/rust/kernel/sync/poll.rs
index 5aa0ce9ba01b..405fb814cc3c 100644
--- a/rust/kernel/sync/poll.rs
+++ b/rust/kernel/sync/poll.rs
@@ -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();
diff --git a/rust/kernel/sync/wait.rs b/rust/kernel/sync/wait.rs
index ba4ee0f8d4d4..1fd07b03d6ba 100644
--- a/rust/kernel/sync/wait.rs
+++ b/rust/kernel/sync/wait.rs
@@ -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()) };
--
2.55.0
^ permalink raw reply related [flat|nested] 9+ messages in thread* [PATCH 5/5] rust: sync: condvar: use task::schedule_timeout()
2026-07-26 22:36 [PATCH 0/5] rust: sync: add WaitQueue infrastructure Danilo Krummrich
` (3 preceding siblings ...)
2026-07-26 22:36 ` [PATCH 4/5] rust: sync: convert CondVar and PollCondVar to use WaitQueue Danilo Krummrich
@ 2026-07-26 22:36 ` Danilo Krummrich
4 siblings, 0 replies; 9+ messages in thread
From: Danilo Krummrich @ 2026-07-26 22:36 UTC (permalink / raw)
To: gregkh, arve, tkjos, brauner, cmllamas, aliceryhl, boqun, gary,
lyude, daniel.almeida, work, juri.lelli, vincent.guittot,
dietmar.eggemann, rostedt, bsegall, mgorman, vschneid,
kprateek.nayak, ojeda, bjorn3_gh, lossin, a.hindborg, tmgross,
tamird, acourbot, peterz, mingo, will, longman, viro, jack, tj,
jiangshanlai
Cc: linux-kernel, rust-for-linux, linux-fsdevel, Danilo Krummrich
Convert 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.
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
rust/kernel/sync/condvar.rs | 24 +++++++++---------------
1 file changed, 9 insertions(+), 15 deletions(-)
diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs
index d4bfc936423e..e1bafaa69ab4 100644
--- a/rust/kernel/sync/condvar.rs
+++ b/rust/kernel/sync/condvar.rs
@@ -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 (res as Jiffies, crate::current!().signal_pending()) {
+ match (remaining, current!().signal_pending()) {
(jiffies, true) => CondVarTimeoutResult::Signal { jiffies },
(0, false) => CondVarTimeoutResult::Timeout,
(jiffies, false) => CondVarTimeoutResult::Woken { jiffies },
--
2.55.0
^ permalink raw reply related [flat|nested] 9+ messages in thread