mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH] rust: sync: condvar: call finish_wait() before relocking
@ 2026-11-26 12:32 Alice Ryhl
  0 siblings, 0 replies; only message in thread
From: Alice Ryhl @ 2026-11-26 12:32 UTC (permalink / raw)
  To: Boqun Feng, Gary Guo, Lyude Paul, Daniel Almeida,
	Onur Özkan, Miguel Ojeda, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Trevor Gross, Danilo Krummrich,
	Tamir Duberstein, Alexandre Courbot, Wedson Almeida Filho,
	Martin Rodriguez Reboredo
  Cc: linux-kernel, rust-for-linux, stable, Alice Ryhl

When schedule_timeout() returns due to a signal or timeout, you must
invoke finish_wait() right away, before invoking any potentially
sleeping operations.

However, the CondVar will currently relock the lock before invoking
finish_wait(), which may sleep in mutex_lock() while the wait queue
entry is still queued. For exclusive waiters, a concurrent notify_one()
or notify_sync() can then match the task in TASK_UNINTERRUPTIBLE and
lose the wakeup for other waiters.

For non-exclusive waiters or notify_all(), keeping the wait entry queued
across relock does not lose wakeups, but it can still cause a spurious
wakeup inside mutex_lock() and nests wq_head->lock under the guard's
lock.

Thus, have the callback invoke finish_wait() at an appropriate time
instead of letting WaitQueue::wait_once*() do it. A token is used to
enforce that this method is called.

Cc: stable@vger.kernel.org
Fixes: 19096bce8157 ("rust: sync: introduce `CondVar`")
Fixes: 4afe54ecfe50 ("rust: sync: convert CondVar and PollCondVar to use WaitQueue")
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/sync/condvar.rs | 19 ++++++++++++-------
 rust/kernel/sync/wait.rs    | 44 +++++++++++++++++++++++++++++++++++++-------
 2 files changed, 49 insertions(+), 14 deletions(-)

diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs
index 89f1a31afb89..d1f9b8d78680 100644
--- a/rust/kernel/sync/condvar.rs
+++ b/rust/kernel/sync/condvar.rs
@@ -109,8 +109,11 @@ fn wait_internal<T: ?Sized, B: Backend>(
         guard: &mut Guard<'_, T, B>,
         timeout: Delta<Jiffy>,
     ) -> Delta<Jiffy> {
-        self.wq.wait_once_exclusive(wait_state, || {
-            guard.do_unlocked(|| task::schedule_timeout(timeout))
+        self.wq.wait_once_exclusive(wait_state, |finish| {
+            guard.do_unlocked(|| {
+                let ret = task::schedule_timeout(timeout);
+                (ret, finish.finish_wait())
+            })
         })
     }
 
@@ -180,11 +183,13 @@ pub fn wait_interruptible_freezable_nonexclusive<T: ?Sized, B: Backend>(
         &self,
         guard: &mut Guard<'_, T, B>,
     ) -> bool {
-        self.wq.wait_once(TASK_INTERRUPTIBLE | TASK_FREEZABLE, || {
-            guard.do_unlocked(|| {
-                task::schedule_timeout(Delta::from_jiffies(task::MAX_SCHEDULE_TIMEOUT))
-            })
-        });
+        self.wq
+            .wait_once(TASK_INTERRUPTIBLE | TASK_FREEZABLE, |finish| {
+                guard.do_unlocked(|| {
+                    task::schedule_timeout(Delta::from_jiffies(task::MAX_SCHEDULE_TIMEOUT));
+                    ((), finish.finish_wait())
+                })
+            });
         crate::current!().signal_pending()
     }
 
diff --git a/rust/kernel/sync/wait.rs b/rust/kernel/sync/wait.rs
index 399760e475cc..f378f0b0f110 100644
--- a/rust/kernel/sync/wait.rs
+++ b/rust/kernel/sync/wait.rs
@@ -18,6 +18,7 @@
 };
 
 use core::{
+    marker::PhantomData,
     pin::Pin,
     ptr, //
 };
@@ -228,27 +229,33 @@ fn wait_event_timeout_internal<F: FnMut() -> bool>(
 
     /// Performs a single non-exclusive prepare-to-wait / finish-wait cycle, calling `schedule_fn`
     /// in between. Non-exclusive waiters are all woken by [`wake_up()`](Self::wake_up).
+    ///
+    /// `schedule_fn` receives a [`WaitFinish`] token and must call [`WaitFinish::finish_wait`]
+    /// before returning (e.g. before reacquiring a lock).
     #[inline]
     pub(super) fn wait_once<F, R>(&self, wait_state: c_int, schedule_fn: F) -> R
     where
-        F: FnOnce() -> R,
+        F: for<'a> FnOnce(WaitFinish<'a>) -> (R, WaitFinishCalled<'a>),
     {
         self.wait_once_internal(wait_state, false, schedule_fn)
     }
 
     /// Performs a single exclusive prepare-to-wait / finish-wait cycle, calling `schedule_fn`
     /// in between.
+    ///
+    /// `schedule_fn` receives a [`WaitFinish`] token and must call [`WaitFinish::finish_wait`]
+    /// before returning (e.g. before reacquiring a lock).
     #[inline]
     pub(super) fn wait_once_exclusive<F, R>(&self, wait_state: c_int, schedule_fn: F) -> R
     where
-        F: FnOnce() -> R,
+        F: for<'a> FnOnce(WaitFinish<'a>) -> (R, WaitFinishCalled<'a>),
     {
         self.wait_once_internal(wait_state, true, schedule_fn)
     }
 
     fn wait_once_internal<F, R>(&self, wait_state: c_int, exclusive: bool, schedule_fn: F) -> R
     where
-        F: FnOnce() -> R,
+        F: for<'a> FnOnce(WaitFinish<'a>) -> (R, WaitFinishCalled<'a>),
     {
         let wait = Opaque::<bindings::wait_queue_entry>::uninit();
 
@@ -268,10 +275,11 @@ fn wait_once_internal<F, R>(&self, wait_state: c_int, exclusive: bool, schedule_
             }
         };
 
-        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()) };
+        let (ret, _finished) = schedule_fn(WaitFinish {
+            wq: self,
+            wait: &wait,
+            _invariant: PhantomData,
+        });
 
         ret
     }
@@ -328,6 +336,28 @@ pub(super) fn wake_up_pollfree(&self) {
     }
 }
 
+#[must_use]
+pub(super) struct WaitFinish<'a> {
+    wq: &'a WaitQueue,
+    wait: &'a Opaque<bindings::wait_queue_entry>,
+    _invariant: PhantomData<fn(&'a ()) -> &'a ()>,
+}
+
+impl<'a> WaitFinish<'a> {
+    #[inline]
+    pub(super) fn finish_wait(self) -> WaitFinishCalled<'a> {
+        // SAFETY: Both `wait` and `wait_queue_head` point to valid memory.
+        unsafe { bindings::finish_wait(self.wq.wait_queue_head.get(), self.wait.get()) };
+        WaitFinishCalled {
+            _invariant: PhantomData,
+        }
+    }
+}
+
+pub(super) struct WaitFinishCalled<'a> {
+    _invariant: PhantomData<fn(&'a ()) -> &'a ()>,
+}
+
 /// A wait was interrupted by a signal.
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
 pub struct Interrupted;

---
base-commit: 7402dd230f4497954b465145a22cff7a5a488629
change-id: 20261125-condvar-finish-wait-453cbda470da

Best regards,
-- 
Alice Ryhl <aliceryhl@google.com>


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2026-11-26 12:32 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26 12:32 [PATCH] rust: sync: condvar: call finish_wait() before relocking Alice Ryhl

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®