rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v1 1/3] rust: sync: set_once: Add fast-path check to avoid expensive cmpxchg
@ 2025-12-11 23:09 FUJITA Tomonori
  2025-12-11 23:09 ` [PATCH v1 2/3] rust: sync: set_once: Implement Send and Sync FUJITA Tomonori
  2025-12-11 23:09 ` [PATCH v1 3/3] rust: sync: set_once: fix doc section heading FUJITA Tomonori
  0 siblings, 2 replies; 5+ messages in thread
From: FUJITA Tomonori @ 2025-12-11 23:09 UTC (permalink / raw)
  To: ojeda, a.hindborg
  Cc: aliceryhl, bjorn3_gh, boqun.feng, dakr, gary, lossin, tmgross,
	rust-for-linux

Check if already initialized before calling cmpxchg in populate().

When SetOnce is already populated, this avoids the expensive LOCK
CMPXCHG operation and uses a simple load instead.

The Relaxed load is safe here because it's only a hint; the subsequent
cmpxchg provides the actual synchronization. Even if we read a stale
value (0), the cmpxchg will correctly fail.

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
 rust/kernel/sync/set_once.rs | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8..889d37dfd17f 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -80,6 +80,10 @@ pub fn as_ref(&self) -> Option<&T> {
     ///
     /// Returns `true` if the [`SetOnce`] was successfully populated.
     pub fn populate(&self, value: T) -> bool {
+        // Avoid expensive cmpxchg if already initialized.
+        if self.init.load(Relaxed) != 0 {
+            return false;
+        }
         // INVARIANT: If the swap succeeds:
         //  - We increase `init`.
         //  - We write the valid value `1` to `init`.

base-commit: d358e5254674b70f34c847715ca509e46eb81e6f
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2025-12-12  2:07 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-12-11 23:09 [PATCH v1 1/3] rust: sync: set_once: Add fast-path check to avoid expensive cmpxchg FUJITA Tomonori
2025-12-11 23:09 ` [PATCH v1 2/3] rust: sync: set_once: Implement Send and Sync FUJITA Tomonori
2025-12-12  0:34   ` Gary Guo
2025-12-12  2:07     ` FUJITA Tomonori
2025-12-11 23:09 ` [PATCH v1 3/3] rust: sync: set_once: fix doc section heading FUJITA Tomonori

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).