NVIDIA GPU driver infrastructure
 help / color / mirror / Atom feed
From: Gary Guo <gary@garyguo.net>
To: "Danilo Krummrich" <dakr@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"David Airlie" <airlied@gmail.com>,
	"Simona Vetter" <simona@ffwll.ch>,
	"Bjorn Helgaas" <bhelgaas@google.com>,
	"Krzysztof Wilczyński" <kwilczynski@kernel.org>
Cc: driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org,
	 linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev,
	 dri-devel@lists.freedesktop.org, linux-pci@vger.kernel.org,
	 Gary Guo <gary@garyguo.net>
Subject: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
Date: Tue, 01 Sep 2026 17:50:27 +0100	[thread overview]
Message-ID: <20260901-typed_register-v4-3-5552b1d59525@garyguo.net> (raw)
In-Reply-To: <20260901-typed_register-v4-0-5552b1d59525@garyguo.net>

Some API like atomics and I/O operate on primitives only; therefore other
types would need to converted to these primitive first. Add two traits
`AsRepr` and `AsReprMut` to indicate that the type can be turned into a
primitive for these operations.

`T: AsRepr` means that `&T` can be viewed as `&T::Repr` and thus it needs
to support transmutability in one direction. `T: AsReprMut` means that
`&mut T` can be viewed as `&mut T::Repr` and thus it needs to support
bi-directional transmutability.

To avoid duplicating implementations, all repr types are normalized to
unsigned integers.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
Changes since v3:
- Added `as_repr` and `as_repr_mut` so the name makes sense (Alex).
  I did not add `Copy` bound because it is not necessary (adding it won't
  simplify the implementation without also requring `Self: Copy`, which I
  don't want to add).

- Dropped round-trip transmutability as a concept, as it can be proved
  correct because `from_repr_unchecked(into_repr(v))` is basically just
  `move v`.

  Even for the `AtomicType`'s use case where copies are made, it can still
  be proven by observing that `from_repr_unchecked(copy into_repr(v))` is
  not distinguishable from `from_repr_unchecked(into_repr(copy v))`.
---
 rust/kernel/mem.rs | 132 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 132 insertions(+)

diff --git a/rust/kernel/mem.rs b/rust/kernel/mem.rs
index 958e43bbcc3a..0bfd6929ae45 100644
--- a/rust/kernel/mem.rs
+++ b/rust/kernel/mem.rs
@@ -97,3 +97,135 @@ pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst {
     // SAFETY: transmute is safe with `IntoBytes` and `FromBytes` bounds.
     unsafe { transmute(val) }
 }
+
+/// Type that is layout-compatible with a primitive representation.
+///
+/// # Safety
+///
+/// - `Self` must have the same size and alignment as [`Self::Repr`].
+/// - `Self` can be [transmutable] to [`Self::Repr`].
+/// - Neither `Self` nor [`Self::Repr`] contains interior mutability.
+///
+/// The above basically says that `&Self` can be transmuted to `&Self::Repr`.
+///
+/// [transmutable]: core::mem::transmute
+pub unsafe trait AsRepr: Sized {
+    /// Primitive representation of this type.
+    type Repr;
+
+    /// Convert from `&Self` to [`&Self::Repr`](AsRepr::Repr).
+    #[inline(always)]
+    fn as_repr(this: &Self) -> &Self::Repr {
+        // SAFETY: Per safety requirement of the trait.
+        unsafe { core::mem::transmute(this) }
+    }
+
+    /// Convert from `Self` to [`Self::Repr`].
+    #[inline(always)]
+    fn into_repr(this: Self) -> Self::Repr {
+        // SAFETY: Per safety requirement of the trait.
+        unsafe { transmute(this) }
+    }
+
+    /// Convert from [`Self::Repr`] to `Self`.
+    ///
+    /// # Safety
+    ///
+    /// `repr` must be a valid bit pattern of `Self` and satisfy type-specific invariants of it.
+    ///
+    /// Alternatively, if `repr` is previously obtained using [`Self::into_repr`], and each
+    /// `from_repr_unchecked` should corresponds to a unique `into_repr` call, then it is safe to
+    /// call as well (this means that we're undoing a `into_repr` call getting the exact bytes
+    /// back).
+    ///
+    /// This method makes no guarantee if a `into_repr` corresponds to multiple
+    /// `from_repr_unchecked` (i.e. copies are made), to allow for cases where `Repr` is a pointer
+    /// and the user of the API wants ownership transfer. Users that want the ability to call
+    /// `from_repr_unchecked` after copying can require `Copy` bound explicitly.
+    #[inline(always)]
+    unsafe fn from_repr_unchecked(repr: Self::Repr) -> Self {
+        // SAFETY: Per safety requirement, `repr` is valid repr of `Self`, or it is previously from
+        // `into_repr`, in which case we're undoing the transmute so it is also safe.
+        unsafe { transmute(repr) }
+    }
+}
+
+/// Type that is bi-directionally transmutable with a primitive representation.
+///
+/// # Safety
+///
+/// - [`Self`] must be [transmutable] from [`Self::Repr`].
+///
+/// [transmutable]: core::mem::transmute
+/// [`Self::Repr`]: AsRepr::Repr
+pub unsafe trait AsReprMut: AsRepr {
+    /// Convert from `&mut Self` to [`&mut Self::Repr`](AsRepr::Repr).
+    #[inline(always)]
+    fn as_repr_mut(this: &mut Self) -> &mut Self::Repr {
+        // SAFETY: Per safety requirement of the trait.
+        unsafe { core::mem::transmute(this) }
+    }
+
+    /// Convert from [`Self::Repr`](AsRepr::Repr) to `Self`.
+    #[inline(always)]
+    fn from_repr(repr: Self::Repr) -> Self {
+        // SAFETY: Per safety requirement of the trait.
+        unsafe { transmute(repr) }
+    }
+}
+
+// SAFETY: `bool` has the same size and alignment as `u8`, and Rust guarantees that `bool` has
+// only two valid bit patterns: 0 (false) and 1 (true). Thus `bool` can be transmuted to `u8`.
+// Neither types contain interior mutability.
+unsafe impl AsRepr for bool {
+    type Repr = u8;
+}
+
+// SAFETY: `*mut T` has the same size and alignment with `*const c_void`, and thus `*mut T` is
+// transmutable to `*const c_void`. Neither types contain interior mutability.
+unsafe impl<T> AsRepr for *mut T {
+    type Repr = *const c_void;
+}
+
+// SAFETY: `*mut T` is transmutable from `*const c_void`.
+unsafe impl<T> AsReprMut for *mut T {}
+
+// SAFETY: `*const T` has the same size and alignment with `*const c_void`, and is transmutable to
+// `*const c_void`. Neither types contain interior mutability.
+unsafe impl<T> AsRepr for *const T {
+    type Repr = *const c_void;
+}
+
+// SAFETY: `*const T` is transmutable from `*const c_void`.
+unsafe impl<T> AsReprMut for *const T {}
+
+macro_rules! int_impl {
+    ($($unsigned:ident $signed:ident ,)*) => {$(
+        // SAFETY: $unsigned has the same size and alignment with itself, and is transmutable to
+        // itself. It does not contain interior mutability.
+        unsafe impl AsRepr for $unsigned {
+            type Repr = $unsigned;
+        }
+
+        // SAFETY: $unsigned is transmutable from itself.
+        unsafe impl AsReprMut for $unsigned {}
+
+        // SAFETY: $signed has the same size and alignment with $unsigned, and is transmutable to it
+        // Neither types contain interior mutability.
+        unsafe impl AsRepr for $signed {
+            type Repr = $unsigned;
+        }
+
+        // SAFETY: $signed is transmutable from $unsigned.
+        unsafe impl AsReprMut for $signed {}
+    )*};
+}
+
+int_impl! {
+    u8 i8,
+    u16 i16,
+    u32 i32,
+    u64 i64,
+    // `usize` is not normalized to particular integer for portability.
+    usize isize,
+}

-- 
2.54.0


  parent reply	other threads:[~2026-09-01 16:50 UTC|newest]

Thread overview: 28+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-09-01 16:50 [PATCH v4 00/16] rust: io: support register projections and remove relative registers Gary Guo
2026-09-01 16:50 ` [PATCH v4 01/16] rust: io: register: reimplement as proc macro Gary Guo
2026-09-03 11:46   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 02/16] rust: mem: add `transmute` with deferred size check Gary Guo
2026-09-03 11:46   ` Alexandre Courbot
2026-09-01 16:50 ` Gary Guo [this message]
2026-09-03 12:02   ` [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 04/16] rust: io: perform conversions using `AsRepr` Gary Guo
2026-09-01 16:50 ` [PATCH v4 05/16] rust: io: support register projections Gary Guo
2026-09-01 16:50 ` [PATCH v4 06/16] rust: io: register: allow explicit base type specification Gary Guo
2026-09-03 12:16   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 07/16] gpu: nova-core: specify base type for registers Gary Guo
2026-09-01 16:50 ` [PATCH v4 08/16] drm/tyr: " Gary Guo
2026-09-01 16:50 ` [PATCH v4 09/16] samples: rust: pci: " Gary Guo
2026-09-01 16:50 ` [PATCH v4 10/16] rust: io: register: make register have a typed base Gary Guo
2026-09-03 12:27   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 11/16] rust: io: register: support fixed offset register without bitfield Gary Guo
2026-09-01 16:50 ` [PATCH v4 12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers Gary Guo
2026-09-03 12:34   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 13/16] gpu: nova-core: convert hshub0 from relative register to projection Gary Guo
2026-09-03 12:41   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 14/16] rust: io: register: remove relative registers Gary Guo
2026-09-01 16:50 ` [PATCH v4 15/16] rust: io: register: remove `Register` trait and cleanup macro Gary Guo
2026-09-03 12:43   ` Alexandre Courbot
2026-09-01 16:50 ` [PATCH v4 16/16] rust: io: register: unify handling of register with/without bitfields Gary Guo
2026-09-03 12:49 ` [PATCH v4 00/16] rust: io: support register projections and remove relative registers Alexandre Courbot
2026-09-03 19:22 ` Danilo Krummrich
2026-09-03 19:27   ` Danilo Krummrich

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=20260901-typed_register-v4-3-5552b1d59525@garyguo.net \
    --to=gary@garyguo.net \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=airlied@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=bhelgaas@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=dri-devel@lists.freedesktop.org \
    --cc=driver-core@lists.linux.dev \
    --cc=kwilczynski@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-pci@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=nova-gpu@lists.linux.dev \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=simona@ffwll.ch \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    /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