From: Andreas Hindborg <a.hindborg@kernel.org>
To: "Miguel Ojeda" <ojeda@kernel.org>,
"Boqun Feng" <boqun.feng@gmail.com>,
"Gary Guo" <gary@garyguo.net>,
"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
"Benno Lossin" <lossin@kernel.org>,
"Alice Ryhl" <aliceryhl@google.com>,
"Trevor Gross" <tmgross@umich.edu>,
"Danilo Krummrich" <dakr@kernel.org>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
Andreas Hindborg <a.hindborg@kernel.org>
Subject: [PATCH] rust: sync: add lazy initialization methods to SetOnce
Date: Sun, 15 Feb 2026 21:27:17 +0100 [thread overview]
Message-ID: <20260215-set-once-lazy-v1-1-6f5bd2efda11@kernel.org> (raw)
Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
next reply other threads:[~2026-02-15 20:27 UTC|newest]
Thread overview: 17+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-02-15 20:27 Andreas Hindborg [this message]
2026-02-15 23:28 ` Benno Lossin
2026-02-16 8:46 ` Alice Ryhl
2026-02-16 11:10 ` Andreas Hindborg
2026-02-16 11:26 ` Alice Ryhl
2026-02-16 11:35 ` Alice Ryhl
2026-02-16 13:32 ` Andreas Hindborg
2026-05-12 8:39 ` Andreas Hindborg
2026-05-12 8:52 ` Alice Ryhl
2026-05-12 9:41 ` Andreas Hindborg
2026-05-12 10:42 ` Andreas Hindborg
2026-05-13 7:47 ` Alice Ryhl
2026-05-13 9:29 ` Andreas Hindborg
2026-02-27 14:56 ` Gary Guo
2026-02-27 19:15 ` Andreas Hindborg
2026-05-12 8:07 ` Andreas Hindborg
2026-05-12 11:26 ` Gary Guo
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=20260215-set-once-lazy-v1-1-6f5bd2efda11@kernel.org \
--to=a.hindborg@kernel.org \
--cc=aliceryhl@google.com \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=dakr@kernel.org \
--cc=gary@garyguo.net \
--cc=linux-kernel@vger.kernel.org \
--cc=lossin@kernel.org \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=tmgross@umich.edu \
/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®