rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
To: alex.gaynor@gmail.com, ojeda@kernel.org
Cc: a.hindborg@kernel.org, aliceryhl@google.com,
	bjorn3_gh@protonmail.com, boqun.feng@gmail.com, dakr@kernel.org,
	gary@garyguo.net, lossin@kernel.org,
	rust-for-linux@vger.kernel.org, tmgross@umich.edu
Subject: [PATCH v2 1/2] rust: Add support for calling a function exactly once
Date: Wed, 12 Nov 2025 22:16:18 +0900	[thread overview]
Message-ID: <20251112131619.3585510-2-fujita.tomonori@gmail.com> (raw)
In-Reply-To: <20251112131619.3585510-1-fujita.tomonori@gmail.com>

Add the Rust equivalent of the kernel's `DO_ONCE_LITE` macro. While it
would be possible to implement the feature entirely as a Rust macro,
the functionality that can be implemented as regular functions has
been extracted and implemented as the `OnceLite` struct for better
code maintainability.

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
 rust/kernel/sync.rs           |  1 +
 rust/kernel/sync/once_lite.rs | 83 +++++++++++++++++++++++++++++++++++
 2 files changed, 84 insertions(+)
 create mode 100644 rust/kernel/sync/once_lite.rs

diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs
index cf5b638a097d..03789283e2ec 100644
--- a/rust/kernel/sync.rs
+++ b/rust/kernel/sync.rs
@@ -17,6 +17,7 @@
 mod condvar;
 pub mod lock;
 mod locked_by;
+pub mod once_lite;
 pub mod poll;
 pub mod rcu;
 mod refcount;
diff --git a/rust/kernel/sync/once_lite.rs b/rust/kernel/sync/once_lite.rs
new file mode 100644
index 000000000000..04c48d18ca39
--- /dev/null
+++ b/rust/kernel/sync/once_lite.rs
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Support for calling a function exactly once.
+//!
+//! C header: [`include/linux/once_lite.h`](srctree/include/linux/once_lite.h)
+
+use super::atomic::{
+    Atomic,
+    AtomicType,
+    Relaxed, //
+};
+
+/// A lightweight `call_once` primitive.
+///
+/// This structure provides the Rust equivalent of the kernel's `DO_ONCE_LITE` macro.
+/// While it would be possible to implement the feature entirely as a Rust macro,
+/// the functionality that can be implemented as regular functions has been
+/// extracted and implemented as the `OnceLite` struct for better code maintainability.
+pub struct OnceLite(Atomic<State>);
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(i32)]
+enum State {
+    Incomplete = 0,
+    Complete = 1,
+}
+
+// SAFETY: `State` and `i32` has the same size and alignment, and it's round-trip
+// transmutable to `i32`.
+unsafe impl AtomicType for State {
+    type Repr = i32;
+}
+
+impl OnceLite {
+    /// Creates a new [`OnceLite`] in the incomplete state.
+    #[inline(always)]
+    #[allow(clippy::new_without_default)]
+    pub const fn new() -> Self {
+        OnceLite(Atomic::new(State::Incomplete))
+    }
+
+    /// Calls the provided function exactly once.
+    ///
+    /// There is no other synchronization between two `call_once()`s
+    /// except that only one will execute `f`, in other words, callers
+    /// should not use a failed `call_once()` as a proof that another
+    /// `call_once()` has already finished and the effect is observable
+    /// to this thread.
+    pub fn call_once<F>(&self, f: F) -> bool
+    where
+        F: FnOnce(),
+    {
+        // ORDERING: `Relaxed` is used here since no synchronization is required
+        // for `call_once()`.
+        let old = self.0.xchg(State::Complete, Relaxed);
+        if old == State::Complete {
+            return false;
+        }
+
+        f();
+        true
+    }
+}
+
+/// Run the given function exactly once.
+///
+/// This is equivalent to the kernel's `DO_ONCE_LITE` macro.
+///
+/// # Examples
+///
+/// ```
+/// kernel::do_once_lite! {
+///     kernel::pr_info!("This will be printed only once\n");
+/// };
+/// ```
+#[macro_export]
+macro_rules! do_once_lite {
+    { $($e:tt)* } => {{
+        #[link_section = ".data..once"]
+        static ONCE: $crate::sync::once_lite::OnceLite = $crate::sync::once_lite::OnceLite::new();
+        ONCE.call_once(|| { $($e)* });
+    }};
+}
-- 
2.43.0


  reply	other threads:[~2025-11-12 13:16 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-11-12 13:16 [PATCH v2 0/2] Add support for print exactly once FUJITA Tomonori
2025-11-12 13:16 ` FUJITA Tomonori [this message]
2025-11-12 13:16 ` [PATCH v2 2/2] rust: Add pr_*_once macros FUJITA Tomonori

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=20251112131619.3585510-2-fujita.tomonori@gmail.com \
    --to=fujita.tomonori@gmail.com \
    --cc=a.hindborg@kernel.org \
    --cc=alex.gaynor@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=gary@garyguo.net \
    --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;
as well as URLs for NNTP newsgroup(s).