Re: [PATCH v5 02/10] rust: sync: Add basic atomic operation mapping framework

Boqun Feng <[email protected]>
Newsgroups dev.linux.lists.lkmm,org.kernel.vger.linux-arch,org.kernel.vger.linux-kernel,org.kernel.vger.rust-for-linux
Message-ID <[email protected]>
On Thu, Jun 26, 2025 at 12:17:14PM +0200, Andreas Hindborg wrote:
> "Boqun Feng" <[email protected]> writes:
> 
> > Preparation for generic atomic implementation. To unify the
> > implementation of a generic method over `i32` and `i64`, the C side
> > atomic methods need to be grouped so that in a generic method, they can
> > be referred as <type>::<method>, otherwise their parameters and return
> > value are different between `i32` and `i64`, which would require using
> > `transmute()` to unify the type into a `T`.
> 
> I can't follow this, could you expand a bit?
> 

So let's say I want to implement a generic `Atomic::load()`, without the
unification, what I can use are:

    pub fn atomic_read(ptr: *mut i32) -> i32

and

    pub fn atomic64_read(ptr: *mut i64) -> i64

and the implementation of `Atomic::load()` would be:

    impl<T:...> Atomic<T> {
        pub fn load(&self) -> T {
	    if size_of::<T> == 4 {
	        unsafe { transmute(atomic_read(self.0.get())) }
	    } else {
	        unsafe { transmute(atomic64_read(self.0.get())) }
	    }
	}
    }

because although load() is function of a generic struct, "if ... else
..." expression requires each branch has the same return type, so the
`transmute()` would be needed. What I meant was a trait method was
provided to `i32` and `i64`:

    impl AtomicImpl for i32 {
        fn atomic_read(ptr: *mut Self) -> Self;
    }

    impl AtomicImpl for i64 {
        fn atomic_read(ptr: *mut Self) -> Self;
    }

so that I could do:

    impl<T:...> Atomic<T> {
        pub fn load(&self) -> T {
	    T::atomic_read(self.0.get())
	}
    }

> >
> > Introduce `AtomicImpl` to represent a basic type in Rust that has the
> > direct mapping to an atomic implementation from C. This trait is sealed,
> > and currently only `i32` and `i64` impl this.
> >
> > Further, different methods are put into different `*Ops` trait groups,
> > and this is for the future when smaller types like `i8`/`i16` are
> > supported but only with a limited set of API (e.g. only set(), load(),
> > xchg() and cmpxchg(), no add() or sub() etc).
> >
> > While the atomic mod is introduced, documentation is also added for
> > memory models and data races.
> >
> > Also bump my role to the maintainer of ATOMIC INFRASTRUCTURE to reflect
> > my responsiblity on the Rust atomic mod.
> >
> > Signed-off-by: Boqun Feng <[email protected]>
> > ---
> >  MAINTAINERS                    |   4 +-
> >  rust/kernel/sync.rs            |   1 +
> >  rust/kernel/sync/atomic.rs     |  19 ++++
> >  rust/kernel/sync/atomic/ops.rs | 199 +++++++++++++++++++++++++++++++++
> >  4 files changed, 222 insertions(+), 1 deletion(-)
> >  create mode 100644 rust/kernel/sync/atomic.rs
> >  create mode 100644 rust/kernel/sync/atomic/ops.rs
> >
> > diff --git a/MAINTAINERS b/MAINTAINERS
> > index 0c1d245bf7b8..5eef524975ca 100644
> > --- a/MAINTAINERS
> > +++ b/MAINTAINERS
> > @@ -3894,7 +3894,7 @@ F:	drivers/input/touchscreen/atmel_mxt_ts.c
> >  ATOMIC INFRASTRUCTURE
> >  M:	Will Deacon <[email protected]>
> >  M:	Peter Zijlstra <[email protected]>
> > -R:	Boqun Feng <[email protected]>
> > +M:	Boqun Feng <[email protected]>
> >  R:	Mark Rutland <[email protected]>
> >  L:	[email protected]
> >  S:	Maintained
> > @@ -3903,6 +3903,8 @@ F:	arch/*/include/asm/atomic*.h
> >  F:	include/*/atomic*.h
> >  F:	include/linux/refcount.h
> >  F:	scripts/atomic/
> > +F:	rust/kernel/sync/atomic.rs
> > +F:	rust/kernel/sync/atomic/
> >
> >  ATTO EXPRESSSAS SAS/SATA RAID SCSI DRIVER
> >  M:	Bradley Grove <[email protected]>
> > diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs
> > index 36a719015583..b620027e0641 100644
> > --- a/rust/kernel/sync.rs
> > +++ b/rust/kernel/sync.rs
> > @@ -10,6 +10,7 @@
> >  use pin_init;
> >
> >  mod arc;
> > +pub mod atomic;
> >  mod condvar;
> >  pub mod lock;
> >  mod locked_by;
> > diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs
> > new file mode 100644
> > index 000000000000..65e41dba97b7
> > --- /dev/null
> > +++ b/rust/kernel/sync/atomic.rs
> > @@ -0,0 +1,19 @@
> > +// SPDX-License-Identifier: GPL-2.0
> > +
> > +//! Atomic primitives.
> > +//!
> > +//! These primitives have the same semantics as their C counterparts: and the precise definitions of
> > +//! semantics can be found at [`LKMM`]. Note that Linux Kernel Memory (Consistency) Model is the
> > +//! only model for Rust code in kernel, and Rust's own atomics should be avoided.
> > +//!
> > +//! # Data races
> > +//!
> > +//! [`LKMM`] atomics have different rules regarding data races:
> > +//!
> > +//! - A normal write from C side is treated as an atomic write if
> > +//!   CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=y.
> > +//! - Mixed-size atomic accesses don't cause data races.
> > +//!
> > +//! [`LKMM`]: srctree/tools/memory-mode/
> > +
> > +pub mod ops;
> > diff --git a/rust/kernel/sync/atomic/ops.rs b/rust/kernel/sync/atomic/ops.rs
> > new file mode 100644
> > index 000000000000..f8825f7c84f0
> > --- /dev/null
> > +++ b/rust/kernel/sync/atomic/ops.rs
> > @@ -0,0 +1,199 @@
> > +// SPDX-License-Identifier: GPL-2.0
> > +
> > +//! Atomic implementations.
> > +//!
> > +//! Provides 1:1 mapping of atomic implementations.
> > +
> > +use crate::bindings::*;
> > +use crate::macros::paste;
> > +
> > +mod private {
> > +    /// Sealed trait marker to disable customized impls on atomic implementation traits.
> > +    pub trait Sealed {}
> > +}
> > +
> > +// `i32` and `i64` are only supported atomic implementations.
> > +impl private::Sealed for i32 {}
> > +impl private::Sealed for i64 {}
> > +
> > +/// A marker trait for types that implement atomic operations with C side primitives.
> > +///
> > +/// This trait is sealed, and only types that have directly mapping to the C side atomics should
> > +/// impl this:
> > +///
> > +/// - `i32` maps to `atomic_t`.
> > +/// - `i64` maps to `atomic64_t`.
> > +pub trait AtomicImpl: Sized + Send + Copy + private::Sealed {}
> > +
> > +// `atomic_t` implements atomic operations on `i32`.
> > +impl AtomicImpl for i32 {}
> > +
> > +// `atomic64_t` implements atomic operations on `i64`.
> > +impl AtomicImpl for i64 {}
> > +
> > +// This macro generates the function signature with given argument list and return type.
> 
> Perhaps could we add an example expansion to make the macro easier for
> people to parse the first time:
> 

That might be a good idea, I will see what I can. However, note that
these macros are only for internal usage (i.e. not an export macro)
similar to impl_item_type!() in configfs.rs, so you can just expand the
file to see the result.

Actually, I could use scripts (similar to patch #1) to generate these,
but was suggested to use macros instead.

The current hesitation from me is because I need to change these macros
and I would probably look into adding expansion examples when things are
stable (i.e. I don't need to change) again. So maybe not the next
version.

> declare_atomic_method!(
>     read[acquire](ptr: *mut Self) -> Self
> );
> 
> ->
> 
> #[doc = "Atomic read_acquire"]
> ..
> unsafe fn atomic_read_acquire(ptr: *mut Self) -> Self;
> 
> #[doc = "Atomic read"]
> ..
> unsafe fn atomic_read(ptr: *mut Self) -> Self;
> 
> 
[..]
> 
> Lastly, perhaps we should do `ptr.cast()` rather than `as *mut _` ?
> 

Sure, that makes sense. I missed that because clippy cannot work on
macro'd code?

Regards,
Boqun

> 
> Best regards,
> Andreas Hindborg
> 
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.