Skip to contentSkip to conversation

Remove the usage of Rust native atomics in debugfs

PATCH Applied Boqun Feng 8 participants 16 messages Oct 22, 2025 – Nov 14, 2025

Subsystems (4)
lore
Share & tools
lore

Boqun Feng

author
#0 lore raw

cover Remove the usage of Rust native atomics in debugfs

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

(help is appreciated if anyone wants to help in other subsystem)

Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomics

 rust/kernel/debugfs/traits.rs       | 53 +++++++++--------------------
 rust/kernel/sync/atomic.rs          | 12 ++++++-
 samples/rust/rust_debugfs.rs        | 12 +++----
 samples/rust/rust_debugfs_scoped.rs |  6 ++--
 4 files changed, 36 insertions(+), 47 deletions(-)
Signature · 1 line
2.51.0
author
#1 lore raw

PATCH 1/3 rust: sync: atomic: Make Atomic*Ops pub(crate)

In order to write code over a generate Atomic<T> we need to make Atomic*Ops public so that functions like .load() and .store() are available. Make these pub(crate) at the beginning so the usage in kernel crate is supported.

---
 rust/kernel/sync/atomic.rs | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
rust/kernel/sync/atomic.rs +2 -1
index 016a6bcaf080..0bc6e7b04d67 100644
@@ -22,9 +22,10 @@
 
 pub use internal::AtomicImpl;
 pub use ordering::{Acquire, Full, Relaxed, Release};
+pub(crate) use internal::{AtomicArithmeticOps, AtomicBasicOps, AtomicExchangeOps};
 
 use crate::build_error;
-use internal::{AtomicArithmeticOps, AtomicBasicOps, AtomicExchangeOps, AtomicRepr};
+use internal::AtomicRepr;
 use ordering::OrderingType;
 
 /// A memory location which can be safely modified from multiple execution contexts.
Signature · 1 line
2.51.0
merge bot Applied
#2 lore raw

[tip: locking/core] rust: sync: atomic: Make Atomic*Ops pub(crate)

The following commit has been merged into the locking/core branch of tip:

The following commit has been merged into the locking/core branch of tip:

Commit-ID:     14e9a18b07ec463a85094cc8942788336164319f
Gitweb:        https://git.kernel.org/tip/14e9a18b07ec463a85094cc8942788336164319f
Author:        Boqun Feng <[email protected]>
AuthorDate:    Tue, 21 Oct 2025 23:53:22 -04:00
Committer:     Boqun Feng <[email protected]>
CommitterDate: Wed, 12 Nov 2025 08:56:38 -08:00

rust: sync: atomic: Make Atomic*Ops pub(crate)

In order to write code over a generate Atomic<T> we need to make Atomic*Ops public so that functions like .load() and .store() are available. Make these pub(crate) at the beginning so the usage in kernel crate is supported.

---
 rust/kernel/sync/atomic.rs | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
rust/kernel/sync/atomic.rs +2 -1
index 016a6bc..0bc6e7b 100644
@@ -22,9 +22,10 @@ mod predefine;
 
 pub use internal::AtomicImpl;
 pub use ordering::{Acquire, Full, Relaxed, Release};
+pub(crate) use internal::{AtomicArithmeticOps, AtomicBasicOps, AtomicExchangeOps};
 
 use crate::build_error;
-use internal::{AtomicArithmeticOps, AtomicBasicOps, AtomicExchangeOps, AtomicRepr};
+use internal::AtomicRepr;
 use ordering::OrderingType;
 
 /// A memory location which can be safely modified from multiple execution contexts.
author
#3 lore raw

PATCH 2/3 rust: sync: atomic: Implement Debug for Atomic<Debug>

In reply to Boqun Feng

If Atomic<T> is Debug then it's a debugfs::Writer, therefore make it so since 1) debugfs needs to support Atomic<T> and 2) it's rather trivial to implement Debug for Atomic<Debug>.

---
 rust/kernel/sync/atomic.rs | 9 +++++++++
 1 file changed, 9 insertions(+)
rust/kernel/sync/atomic.rs +9 -0
index 0bc6e7b04d67..3afc376be42d 100644
@@ -307,6 +307,15 @@ pub fn store<Ordering: ordering::ReleaseOrRelaxed>(&self, v: T, _: Ordering) {
     }
 }
 
+impl<T: AtomicType + core::fmt::Debug> core::fmt::Debug for Atomic<T>
+where
+    T::Repr: AtomicBasicOps,
+{
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        core::fmt::Debug::fmt(&self.load(Relaxed), f)
+    }
+}
+
 impl<T: AtomicType> Atomic<T>
 where
     T::Repr: AtomicExchangeOps,
Signature · 1 line
2.51.0
merge bot Applied
#4 lore raw

[tip: locking/core] rust: sync: atomic: Implement Debug for Atomic<Debug>

The following commit has been merged into the locking/core branch of tip:

The following commit has been merged into the locking/core branch of tip:

Commit-ID:     013f912eb5fa7c06b3648ca630acfc4ff26456fa
Gitweb:        https://git.kernel.org/tip/013f912eb5fa7c06b3648ca630acfc4ff26456fa
Author:        Boqun Feng <[email protected]>
AuthorDate:    Tue, 21 Oct 2025 23:53:23 -04:00
Committer:     Boqun Feng <[email protected]>
CommitterDate: Wed, 12 Nov 2025 08:56:41 -08:00

rust: sync: atomic: Implement Debug for Atomic<Debug>

If Atomic<T> is Debug then it's a debugfs::Writer, therefore make it so since 1) debugfs needs to support Atomic<T> and 2) it's rather trivial to implement Debug for Atomic<Debug>.

---
 rust/kernel/sync/atomic.rs |  9 +++++++++
 1 file changed, 9 insertions(+)
rust/kernel/sync/atomic.rs +9 -0
index 0bc6e7b..3afc376 100644
@@ -307,6 +307,15 @@ where
     }
 }
 
+impl<T: AtomicType + core::fmt::Debug> core::fmt::Debug for Atomic<T>
+where
+    T::Repr: AtomicBasicOps,
+{
+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+        core::fmt::Debug::fmt(&self.load(Relaxed), f)
+    }
+}
+
 impl<T: AtomicType> Atomic<T>
 where
     T::Repr: AtomicExchangeOps,
author
#5 lore raw

PATCH 3/3 rust: debugfs: Replace the usage of Rust native atomics

In reply to Boqun Feng

Rust native atomics are not allowed to use in kernel due to the mismatch of memory model with Linux kernel memory model, hence remove the usage of Rust native atomics in debufs.

---
 rust/kernel/debugfs/traits.rs       | 53 +++++++++--------------------
 samples/rust/rust_debugfs.rs        | 12 +++----
 samples/rust/rust_debugfs_scoped.rs |  6 ++--
 3 files changed, 25 insertions(+), 46 deletions(-)
rust/kernel/debugfs/traits.rs +17 -36
index ab009eb254b3..1bcfb3b3dd2f 100644
@@ -4,14 +4,11 @@
 //! Traits for rendering or updating values exported to DebugFS.
 
 use crate::prelude::*;
+use crate::sync::atomic::{Atomic, AtomicBasicOps, AtomicType, Relaxed};
 use crate::sync::Mutex;
 use crate::uaccess::UserSliceReader;
 use core::fmt::{self, Debug, Formatter};
 use core::str::FromStr;
-use core::sync::atomic::{
-    AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
-    AtomicU8, AtomicUsize, Ordering,
-};
 
 /// A trait for types that can be written into a string.
 ///
@@ -66,37 +63,21 @@ fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
     }
 }
 
-macro_rules! impl_reader_for_atomic {
-    ($(($atomic_type:ty, $int_type:ty)),*) => {
-        $(
-            impl Reader for $atomic_type {
-                fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
-                    let mut buf = [0u8; 21]; // Enough for a 64-bit number.
-                    if reader.len() > buf.len() {
-                        return Err(EINVAL);
-                    }
-                    let n = reader.len();
-                    reader.read_slice(&mut buf[..n])?;
+impl<T: AtomicType + FromStr> Reader for Atomic<T>
+where
+    T::Repr: AtomicBasicOps,
+{
+    fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
+        let mut buf = [0u8; 21]; // Enough for a 64-bit number.
+        if reader.len() > buf.len() {
+            return Err(EINVAL);
+        }
+        let n = reader.len();
+        reader.read_slice(&mut buf[..n])?;
 
-                    let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
-                    let val = s.trim().parse::<$int_type>().map_err(|_| EINVAL)?;
-                    self.store(val, Ordering::Relaxed);
-                    Ok(())
-                }
-            }
-        )*
-    };
+        let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
+        let val = s.trim().parse::<T>().map_err(|_| EINVAL)?;
+        self.store(val, Relaxed);
+        Ok(())
+    }
 }
-
-impl_reader_for_atomic!(
-    (AtomicI16, i16),
-    (AtomicI32, i32),
-    (AtomicI64, i64),
-    (AtomicI8, i8),
-    (AtomicIsize, isize),
-    (AtomicU16, u16),
-    (AtomicU32, u32),
-    (AtomicU64, u64),
-    (AtomicU8, u8),
-    (AtomicUsize, usize)
-);
samples/rust/rust_debugfs.rs +5 -7
index 82b61a15a34b..711faa07bece 100644
@@ -32,14 +32,12 @@
 //! ```
 
 use core::str::FromStr;
-use core::sync::atomic::AtomicUsize;
-use core::sync::atomic::Ordering;
 use kernel::c_str;
 use kernel::debugfs::{Dir, File};
 use kernel::new_mutex;
 use kernel::prelude::*;
+use kernel::sync::atomic::{Atomic, Relaxed};
 use kernel::sync::Mutex;
-
 use kernel::{acpi, device::Core, of, platform, str::CString, types::ARef};
 
 kernel::module_platform_driver! {
@@ -59,7 +57,7 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
-    counter: File<AtomicUsize>,
+    counter: File<Atomic<usize>>,
     #[pin]
     inner: File<Mutex<Inner>>,
 }
@@ -109,7 +107,7 @@ fn probe(
     ) -> Result<Pin<KBox<Self>>> {
         let result = KBox::try_pin_init(RustDebugFs::new(pdev), GFP_KERNEL)?;
         // We can still mutate fields through the files which are atomic or mutexed:
-        result.counter.store(91, Ordering::Relaxed);
+        result.counter.store(91, Relaxed);
         {
             let mut guard = result.inner.lock();
             guard.x = guard.y;
@@ -120,8 +118,8 @@ fn probe(
 }
 
 impl RustDebugFs {
-    fn build_counter(dir: &Dir) -> impl PinInit<File<AtomicUsize>> + '_ {
-        dir.read_write_file(c_str!("counter"), AtomicUsize::new(0))
+    fn build_counter(dir: &Dir) -> impl PinInit<File<Atomic<usize>>> + '_ {
+        dir.read_write_file(c_str!("counter"), Atomic::<usize>::new(0))
     }
 
     fn build_inner(dir: &Dir) -> impl PinInit<File<Mutex<Inner>>> + '_ {
samples/rust/rust_debugfs_scoped.rs +3 -3
index b0c4e76b123e..9f0ec5f24cda 100644
@@ -6,9 +6,9 @@
 //! `Scope::dir` to create a variety of files without the need to separately
 //! track them all.
 
-use core::sync::atomic::AtomicUsize;
 use kernel::debugfs::{Dir, Scope};
 use kernel::prelude::*;
+use kernel::sync::atomic::Atomic;
 use kernel::sync::Mutex;
 use kernel::{c_str, new_mutex, str::CString};
 
@@ -62,7 +62,7 @@ fn create_file_write(
     let file_name = CString::try_from_fmt(fmt!("{name_str}"))?;
     for sub in items {
         nums.push(
-            AtomicUsize::new(sub.parse().map_err(|_| EINVAL)?),
+            Atomic::<usize>::new(sub.parse().map_err(|_| EINVAL)?),
             GFP_KERNEL,
         )?;
     }
@@ -109,7 +109,7 @@ fn init(device_dir: Dir) -> impl PinInit<Self> {
 
 struct DeviceData {
     name: CString,
-    nums: KVec<AtomicUsize>,
+    nums: KVec<Atomic<usize>>,
 }
 
 fn init_control(base_dir: &Dir, dyn_dirs: Dir) -> impl PinInit<Scope<ModuleData>> + '_ {
Signature · 1 line
2.51.0
merge bot Applied
#8 lore raw

[tip: locking/core] rust: debugfs: Replace the usage of Rust native atomics

In reply to Boqun Feng
The following commit has been merged into the locking/core branch of tip:

The following commit has been merged into the locking/core branch of tip:

Commit-ID:     f74cf399e02e24c544b0bd4b1fe8fa2c5ae30b18
Gitweb:        https://git.kernel.org/tip/f74cf399e02e24c544b0bd4b1fe8fa2c5ae30b18
Author:        Boqun Feng <[email protected]>
AuthorDate:    Tue, 21 Oct 2025 23:53:24 -04:00
Committer:     Boqun Feng <[email protected]>
CommitterDate: Wed, 12 Nov 2025 08:56:42 -08:00

rust: debugfs: Replace the usage of Rust native atomics

Rust native atomics are not allowed to use in kernel due to the mismatch of memory model with Linux kernel memory model, hence remove the usage of Rust native atomics in debufs.

---
 rust/kernel/debugfs/traits.rs       | 53 ++++++++--------------------
 samples/rust/rust_debugfs.rs        | 12 ++----
 samples/rust/rust_debugfs_scoped.rs |  6 +--
 3 files changed, 25 insertions(+), 46 deletions(-)
rust/kernel/debugfs/traits.rs +17 -36
index ba7ec5a..92054fe 100644
@@ -4,14 +4,11 @@
 //! Traits for rendering or updating values exported to DebugFS.
 
 use crate::prelude::*;
+use crate::sync::atomic::{Atomic, AtomicBasicOps, AtomicType, Relaxed};
 use crate::sync::Mutex;
 use crate::uaccess::UserSliceReader;
 use core::fmt::{self, Debug, Formatter};
 use core::str::FromStr;
-use core::sync::atomic::{
-    AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
-    AtomicU8, AtomicUsize, Ordering,
-};
 
 /// A trait for types that can be written into a string.
 ///
@@ -66,37 +63,21 @@ impl<T: FromStr + Unpin> Reader for Mutex<T> {
     }
 }
 
-macro_rules! impl_reader_for_atomic {
-    ($(($atomic_type:ty, $int_type:ty)),*) => {
-        $(
-            impl Reader for $atomic_type {
-                fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
-                    let mut buf = [0u8; 21]; // Enough for a 64-bit number.
-                    if reader.len() > buf.len() {
-                        return Err(EINVAL);
-                    }
-                    let n = reader.len();
-                    reader.read_slice(&mut buf[..n])?;
+impl<T: AtomicType + FromStr> Reader for Atomic<T>
+where
+    T::Repr: AtomicBasicOps,
+{
+    fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
+        let mut buf = [0u8; 21]; // Enough for a 64-bit number.
+        if reader.len() > buf.len() {
+            return Err(EINVAL);
+        }
+        let n = reader.len();
+        reader.read_slice(&mut buf[..n])?;
 
-                    let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
-                    let val = s.trim().parse::<$int_type>().map_err(|_| EINVAL)?;
-                    self.store(val, Ordering::Relaxed);
-                    Ok(())
-                }
-            }
-        )*
-    };
+        let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
+        let val = s.trim().parse::<T>().map_err(|_| EINVAL)?;
+        self.store(val, Relaxed);
+        Ok(())
+    }
 }
-
-impl_reader_for_atomic!(
-    (AtomicI16, i16),
-    (AtomicI32, i32),
-    (AtomicI64, i64),
-    (AtomicI8, i8),
-    (AtomicIsize, isize),
-    (AtomicU16, u16),
-    (AtomicU32, u32),
-    (AtomicU64, u64),
-    (AtomicU8, u8),
-    (AtomicUsize, usize)
-);
samples/rust/rust_debugfs.rs +5 -7
index 82b61a1..711faa0 100644
@@ -32,14 +32,12 @@
 //! ```
 
 use core::str::FromStr;
-use core::sync::atomic::AtomicUsize;
-use core::sync::atomic::Ordering;
 use kernel::c_str;
 use kernel::debugfs::{Dir, File};
 use kernel::new_mutex;
 use kernel::prelude::*;
+use kernel::sync::atomic::{Atomic, Relaxed};
 use kernel::sync::Mutex;
-
 use kernel::{acpi, device::Core, of, platform, str::CString, types::ARef};
 
 kernel::module_platform_driver! {
@@ -59,7 +57,7 @@ struct RustDebugFs {
     #[pin]
     _compatible: File<CString>,
     #[pin]
-    counter: File<AtomicUsize>,
+    counter: File<Atomic<usize>>,
     #[pin]
     inner: File<Mutex<Inner>>,
 }
@@ -109,7 +107,7 @@ impl platform::Driver for RustDebugFs {
     ) -> Result<Pin<KBox<Self>>> {
         let result = KBox::try_pin_init(RustDebugFs::new(pdev), GFP_KERNEL)?;
         // We can still mutate fields through the files which are atomic or mutexed:
-        result.counter.store(91, Ordering::Relaxed);
+        result.counter.store(91, Relaxed);
         {
             let mut guard = result.inner.lock();
             guard.x = guard.y;
@@ -120,8 +118,8 @@ impl platform::Driver for RustDebugFs {
 }
 
 impl RustDebugFs {
-    fn build_counter(dir: &Dir) -> impl PinInit<File<AtomicUsize>> + '_ {
-        dir.read_write_file(c_str!("counter"), AtomicUsize::new(0))
+    fn build_counter(dir: &Dir) -> impl PinInit<File<Atomic<usize>>> + '_ {
+        dir.read_write_file(c_str!("counter"), Atomic::<usize>::new(0))
     }
 
     fn build_inner(dir: &Dir) -> impl PinInit<File<Mutex<Inner>>> + '_ {
samples/rust/rust_debugfs_scoped.rs +3 -3
index b0c4e76..9f0ec5f 100644
@@ -6,9 +6,9 @@
 //! `Scope::dir` to create a variety of files without the need to separately
 //! track them all.
 
-use core::sync::atomic::AtomicUsize;
 use kernel::debugfs::{Dir, Scope};
 use kernel::prelude::*;
+use kernel::sync::atomic::Atomic;
 use kernel::sync::Mutex;
 use kernel::{c_str, new_mutex, str::CString};
 
@@ -62,7 +62,7 @@ fn create_file_write(
     let file_name = CString::try_from_fmt(fmt!("{name_str}"))?;
     for sub in items {
         nums.push(
-            AtomicUsize::new(sub.parse().map_err(|_| EINVAL)?),
+            Atomic::<usize>::new(sub.parse().map_err(|_| EINVAL)?),
             GFP_KERNEL,
         )?;
     }
@@ -109,7 +109,7 @@ impl ModuleData {
 
 struct DeviceData {
     name: CString,
-    nums: KVec<AtomicUsize>,
+    nums: KVec<Atomic<usize>>,
 }
 
 fn init_control(base_dir: &Dir, dyn_dirs: Dir) -> impl PinInit<Scope<ModuleData>> + '_ {
maintainer
#9 lore raw
In reply to Boqun Feng
Quoted 3 lines · Boqun Feng

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

Doesn't rust have a language feature that allows you to blacklist them; ensuring they are not used?

maintainer
#10 lore raw
Quoted 7 lines · Peter Zijlstra
Quoted 3 lines · Boqun Feng

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

Doesn't rust have a language feature that allows you to blacklist them; ensuring they are not used?

I believe clippy lets you do that.

Alice

author
#11 lore raw
In reply to Peter Zijlstra
Quoted 8 lines · Peter Zijlstra
Quoted 3 lines · Boqun Feng

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

Doesn't rust have a language feature that allows you to blacklist them; ensuring they are not used?

Although I don't know whether it's available today, but I believe that can be done (in the future probably?).

However, this patchset is about cleaning up the existing usage, which was introduced before we have LKMM atomics on the Rust side.

Regards,
Boqun

Quoted 1 line
maintainer Acked-by on the v1 series
#12 lore raw
In reply to Boqun Feng
Quoted 11 lines · Boqun Feng

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

(help is appreciated if anyone wants to help in other subsystem)

Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomics

Quoted 10 lines
 rust/kernel/debugfs/traits.rs       | 53 +++++++++--------------------
 rust/kernel/sync/atomic.rs          | 12 ++++++-
 samples/rust/rust_debugfs.rs        | 12 +++----
 samples/rust/rust_debugfs_scoped.rs |  6 ++--
 4 files changed, 36 insertions(+), 47 deletions(-)
Signature · 1 line
2.51.0
Tested-by on the v1 series
#13 lore raw
In reply to Boqun Feng
Quoted 7 lines · Boqun Feng

Rust native atomics are not supposed to be used in kernel due to the mismatch of memory model, since we now have the LKMM atomics in Rust, remove the usage of Rust native atomics in debugfs.

(help is appreciated if anyone wants to help in other subsystem)

Thanks very much, Boqun. I can confirm this fixes the build issues (and seems to work) on 32-bit x86 (both UML, and -- with some -Zregparm patches -- otherwise).

Cheers,
-- David

maintainer
#14 lore raw
In reply to Boqun Feng
Quoted 4 lines · Boqun Feng

Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomics

I ack'd patch three for you to pick it up, but I now wonder if you want me to pick it up through the driver-core tree?

author
#15 lore raw
Quoted 7 lines · Danilo Krummrich
Quoted 4 lines · Boqun Feng

Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomics

I ack'd patch three for you to pick it up, but I now wonder if you want me to

Thanks!

Quoted 1 line

pick it up through the driver-core tree?

Given there are some atomic library changes, I will send it as a PR to tip. Thanks for the offering!

Regards,
Boqun