Re: [PATCH v3] rust: page: add byte-wise atomic memory copy methods

From: Boqun Feng

Date: Fri Feb 13 2026 - 12:44:32 EST


On Fri, Feb 13, 2026 at 07:42:53AM +0100, Andreas Hindborg wrote:
[...]
> diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs
> index 4aebeacb961a2..8ab20126a88cf 100644
> --- a/rust/kernel/sync/atomic.rs
> +++ b/rust/kernel/sync/atomic.rs
> @@ -560,3 +560,35 @@ pub fn fetch_add<Rhs, Ordering: ordering::Ordering>(&self, v: Rhs, _: Ordering)
> unsafe { from_repr(ret) }
> }
> }
> +
> +/// Copy `len` bytes from `src` to `dst` using byte-wise atomic operations.
> +///

Given Greg and Peter's feedback, I think it's better to call out why we
need `atomic_per_byte_memcpy()` and why we use bindings::memcpy() to
implement it. How about a paragraph as follow:

/// This is the concurrent-safe version of `core::ptr::copy()` (the
/// counterpart of standard C's `memcpy()`). Because of the atomicity at
/// byte level, when racing with another concurrent atomic access (or
/// a normal read races with an atomic read) or an external access (from
/// DMA or userspace), the behavior of this function is defined:
/// copying memory at the (at least) byte granularity.
///
/// Implementation note: it's currently implemented by kernel's
/// `memcpy()`, because kernel's `memcpy()` is implemented in a way that
/// byte-wise atomic memory load/store instructions are used.

And probably we make it a separate patch for this
atomic_per_byte_memcpy().

Thoughts?

Regards,
Boqun

> +/// This copy operation is volatile.
> +///
> +/// # Safety
> +///
> +/// Callers must ensure that:
> +///
> +/// - `src` is valid for reads for `len` bytes for the duration of the call.
> +/// - `dst` is valid for writes for `len` bytes for the duration of the call.
> +/// - For the duration of the call, other accesses to the areas described by `src`, `dst` and `len`,
> +/// must not cause data races (defined by [`LKMM`]) against atomic operations executed by this
> +/// function. Note that if all other accesses are atomic, then this safety requirement is
> +/// trivially fulfilled.
> +///
> +/// [`LKMM`]: srctree/tools/memory-model
> +pub unsafe fn atomic_per_byte_memcpy(src: *const u8, dst: *mut u8, len: usize) {
> + // SAFETY: By the safety requirements of this function, the following operation will not:
> + // - Trap.
> + // - Invalidate any reference invariants.
> + // - Race with any operation by the Rust AM, as `bindings::memcpy` is a byte-wise atomic
> + // operation and all operations by the Rust AM to the involved memory areas use byte-wise
> + // atomic semantics.
> + unsafe {
> + bindings::memcpy(
> + dst.cast::<kernel::ffi::c_void>(),
> + src.cast::<kernel::ffi::c_void>(),
> + len,
> + )
> + };
> +}
>
> ---
> base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
> change-id: 20260130-page-volatile-io-05ff595507d3
>
> Best regards,
> --
> Andreas Hindborg <a.hindborg@xxxxxxxxxx>
>
>