mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Alice Ryhl <aliceryhl@google.com>
To: "Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Lyude Paul" <lyude@redhat.com>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Wedson Almeida Filho" <walmeida@microsoft.com>,
	"Martin Rodriguez Reboredo" <yakoyoku@gmail.com>
Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	 stable@vger.kernel.org, Alice Ryhl <aliceryhl@google.com>
Subject: [PATCH] rust: sync: condvar: call finish_wait() before relocking
Date: Thu, 26 Nov 2026 12:32:00 +0000	[thread overview]
Message-ID: <20261126-condvar-finish-wait-v1-1-296b5a05045b@google.com> (raw)

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>


                 reply	other threads:[~2026-11-26 12:32 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126-condvar-finish-wait-v1-1-296b5a05045b@google.com \
    --to=aliceryhl@google.com \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=stable@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=walmeida@microsoft.com \
    --cc=work@onurozkan.dev \
    --cc=yakoyoku@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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®