Skip to contentSkip to conversation

rust: add `register!` macro

PATCH Superseded Alexandre Courbot 4 participants 23 messages Feb 16 – Feb 22

Subsystems (8)
DRM drivers Kbuild Rust DRM Rust +4 more subsystems

v6 of 9 Superseded Latest is v9 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v6 cover rust: add `register!` macro

This new revision took some time because it is (yet another) overhaul. ^_^;

Thanks to a breakthrough by Gary, we found a way to have the I/O type perform the actual I/O instead of the register type, which moves us from this access pattern:

    let boot0 = regs::NV_PMC_BOOT_0::read(bar);

to this arguably more natural one:

    let boot0 = bar.read(regs::NV_PMC_BOOT_0);

It also has the benefit of taking advantage of deref coercion for types that wrap an Io, something the register-based methods couldn't do and which would have required extra AsRef implementations just for this purpose.

Furthermore, this resolves the inconsistency of the former register API that couldn't use the try_ I/O accessors (and even had methods whose names clashed with them). Now if Io supports it, it can be done on a register.

Another benefit is that there is less work done within macros, and more in generic code, which is (generally) a win for readability. The register! macro is considerably smaller and easier to work on, and now mostly made up of the bitfield accessors that will eventually be moved into another macro.

I decided to remove a couple of tags because the code has changed quite a bit since they were obtained.

Gary is listed as co-developer on two patches that bring his idea to life; I took the freedom to add his signoff for convenience, but would be more comfortable to get an explicit ack after he sees the code. :)

This revision is based on driver-core-testing as of 2026-01-16 with
[1] applied. A tree with this series and its dependencies is available at [2].

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/Gnurou/linux/tree/b4/register

Initial cover letter follows:

Add an improved version of nova-core's register! macro to the kernel crate for all drivers to use.

This is not a direct move from nova-core, but rather a new introduction to facilitate code review and introduce features that are missing in the nova-core versions. Differences notably include:

- Use of Bounded to prevent any data truncation when manipulating bitfields,
- Much better syntax (thanks to Gary for all the suggestions!),
- Extended documentation,
- Doccomments now build and run,
- Supports visibility and different storage sizes,
- I/O accesses are performed by Io instead of the register type.

The bitfield! macro of nova-core has for the moment been wrapped into register!, as a set of private rules, to allow register! to be merged first while bitfield! undergoes review during the next cycle. Thus, some of the code from v1 (including bitfield!'s doccomments and Kunit tests) are kept for later.

The first patch enables the generic_arg_infer feature, which is required for generic type inference and used in subsequent patches. This feature is stable since rustc 1.89.

The second patch adds shr and shl methods to Bounded. These were suggested by Alice during LPC as a way to avoid the use of the controversial Bounded::from_expr in both the bitfield macro and the Nova code. The third patch adds another convenience method to obtain a bool from single-bit Boundeds, while the fourth patch turns Bounded::get into a const method in order to make register setter methods const.

Patches 5 and 6 introduce the IoRef and IoWrite types around which I/O accesses are centered. This allows registers to be accessed using the same read and write methods as primitive types.

Patch 7 adds the register! macro and the types it requires.

Patch 8 updates the Rust PCI sample driver to use register!, as per its TODO item.

The last patch illustrates more extensively how this macro is used by converting nova-core to use it, and removing the local implementation. This patch is to be merged one cycle after the other patches.

---
Changes in v6:
- Remove Tested-by tags as the code has considerably changed.
- Make Bounded::get const so it can be used with registers.
- Use the pin_init::zeroed() const function instead of defining our own method.
- Generalize all Io around the new IoRef and IoWrite types, and make registers use these as well.
- Use the more natural pattern of having the Io type perform the I/O access instead of the register type.
- Convert the whole PCI driver example, and not only the PCI configuration space.
- Rename Bounded::as_bool to Bounded::into_bool.
- Drop Bounded::into_inner in favor of making Bounded::get const.
- Link to v5: https://patch.msgid.link/[email protected]

Changes in v5:
- Rename all setters to with_* and with_const_*.
- Use , stride = to specify the stride of register arrays.
- Remove Deref requirement on the RegisterIo trait and make it #[doc(hidden).
- Simplify the top dispatch rule a bit.
- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- Add with_ const field setter methods (removing the need to call Bounded::new for constant field values).
- Add into_inner const method for Bounded.
- Add from_raw and const zeroed method to create initial register values.
- More documentation improvements.
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Sort the Rust features list alphabetically.
- Rebase on top of latest driver-core-next including the new Io trait.
- Allow several registers to be defined from the same macro invocation.
- Remove references to bitfield! macro.
- Fix doccomment of shr and shl.
- Use + syntax for relative register offsets.
- Move register arrays size and stride to after the backing type declaration.
- Use regular doccomments to document registers and fields (thanks Gary!).
- Remove Default implementation and implement the more predictable Zeroable instead.
- Improve doccomments a bit.
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Remove bitfield! and put its rules into register! to give it more time to get reviewed.
- Allow output type larger than strictly required for shr and shl on Bounded.
- Enable the generic_arg_infer feature, required for rustc < 1.89.
- Link to v1: https://patch.msgid.link/[email protected]

---
Alexandre Courbot (9):
rust: enable the generic_arg_infer feature
rust: num: add shr and shl methods to Bounded
rust: num: add into_bool method to Bounded
rust: num: make Bounded::get const
rust: io: add IoRef and IoWrite types
rust: io: use generic read/write accessors for primitive accesses
rust: io: add register! macro
sample: rust: pci: use register! macro
[FOR REFERENCE] gpu: nova-core: use the kernel register! macro

 drivers/gpu/nova-core/falcon.rs           |  249 +++----
 drivers/gpu/nova-core/falcon/gsp.rs       |   23 +-
 drivers/gpu/nova-core/falcon/hal/ga102.rs |   65 +-
 drivers/gpu/nova-core/falcon/hal/tu102.rs |   11 +-
 drivers/gpu/nova-core/falcon/sec2.rs      |   17 +-
 drivers/gpu/nova-core/fb.rs               |    6 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |   40 +-
 drivers/gpu/nova-core/fb/hal/ga102.rs     |    7 +-
 drivers/gpu/nova-core/fb/hal/tu102.rs     |   22 +-
 drivers/gpu/nova-core/gfw.rs              |   11 +-
 drivers/gpu/nova-core/gpu.rs              |   36 +-
 drivers/gpu/nova-core/gsp/boot.rs         |   11 +-
 drivers/gpu/nova-core/gsp/cmdq.rs         |   10 +-
 drivers/gpu/nova-core/regs.rs             |  544 ++++++++------
 drivers/gpu/nova-core/regs/macros.rs      |  739 -------------------
 rust/kernel/io.rs                         |  345 +++++++--
 rust/kernel/io/register.rs                | 1125 +++++++++++++++++++++++++++++
 rust/kernel/lib.rs                        |    3 +
 rust/kernel/num/bounded.rs                |   70 +-
 samples/rust/rust_driver_pci.rs           |   84 ++-
 scripts/Makefile.build                    |    3 +-
 21 files changed, 2106 insertions(+), 1315 deletions(-)

---
base-commit: 916328497055bdfc1d633f04a33ab7d4dc91f45f
change-id: 20260117-register-ccaba1d21713

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author maintainer
#1 lore raw

PATCH v6 1/9 rust: enable the `generic_arg_infer` feature

This feature is stable since 1.89, and used in subsequent patches.

---
 rust/kernel/lib.rs     | 3 +++
 scripts/Makefile.build | 3 ++-
 2 files changed, 5 insertions(+), 1 deletion(-)
rust/kernel/lib.rs +3 -0
index 3da92f18f4ee..cddeae8b6cb2 100644
@@ -37,6 +37,9 @@
 #![feature(const_ptr_write)]
 #![feature(const_refs_to_cell)]
 //
+// Stable since Rust 1.89.0.
+#![feature(generic_arg_infer)]
+//
 // Expected to become stable.
 #![feature(arbitrary_self_types)]
 //
scripts/Makefile.build +2 -1
index 32e209bc7985..923886735299 100644
@@ -314,12 +314,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE
 #   - Stable since Rust 1.82.0: `feature(asm_const)`,
 #     `feature(offset_of_nested)`, `feature(raw_ref_op)`.
 #   - Stable since Rust 1.87.0: `feature(asm_goto)`.
+#   - Stable since Rust 1.89.0: `feature(generic_arg_infer)`.
 #   - Expected to become stable: `feature(arbitrary_self_types)`.
 #   - To be determined: `feature(used_with_arg)`.
 #
 # Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on
 # the unstable features in use.
-rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg
+rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,generic_arg_infer,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg
 
 # `--out-dir` is required to avoid temporaries being created by `rustc` in the
 # current working directory, which may be not accessible in the out-of-tree
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

PATCH v6 2/9 rust: num: add `shr` and `shl` methods to `Bounded`

In reply to Alexandre Courbot

Shifting a Bounded left or right changes the number of bits required to represent the value. Add methods that perform the shift and return a Bounded with the appropriately adjusted bit width.

These methods are particularly useful for bitfield extraction.

---
 rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
rust/kernel/num/bounded.rs +42 -0
index fa81acbdc8c2..7014b5be66db 100644
@@ -473,6 +473,48 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `N` bits, and with the same signedness.
         unsafe { Bounded::__new(value) }
     }
+
+    /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >=
+    /// N - SHIFT`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::num::Bounded;
+    ///
+    /// let v = Bounded::<u32, 16>::new::<0xff00>();
+    /// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>();
+    ///
+    /// assert_eq!(v_shifted.get(), 0xff);
+    /// ```
+    pub fn shr<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
+        const { assert!(RES >= N - SHIFT) }
+
+        // SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to
+        // represent the shifted value by as much, and just asserted that `RES >= N - SHIFT`.
+        unsafe { Bounded::__new(self.0 >> SHIFT) }
+    }
+
+    /// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >=
+    /// N + SHIFT`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::num::Bounded;
+    ///
+    /// let v = Bounded::<u32, 8>::new::<0xff>();
+    /// let v_shifted: Bounded::<u32, 16> = v.shl::<8, _>();
+    ///
+    /// assert_eq!(v_shifted.get(), 0xff00);
+    /// ```
+    pub fn shl<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
+        const { assert!(RES >= N + SHIFT) }
+
+        // SAFETY: We shift the value left by `SHIFT`, augmenting the number of bits needed to
+        // represent the shifted value by as much, and just asserted that `RES >= N + SHIFT`.
+        unsafe { Bounded::__new(self.0 << SHIFT) }
+    }
 }
 
 impl<T, const N: u32> Deref for Bounded<T, N>
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

PATCH v6 3/9 rust: num: add `into_bool` method to `Bounded`

In reply to Alexandre Courbot

Single-bit numbers are typically treated as booleans. There is an Into<bool> implementation for those, but invoking it from contexts that lack type expectations is not always convenient.

Add an into_bool method as a simpler shortcut.

---
 rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/num/bounded.rs +21 -0
index 7014b5be66db..8e4c08924d96 100644
@@ -1101,3 +1101,24 @@ fn from(value: bool) -> Self {
         unsafe { Self::__new(T::from(value)) }
     }
 }
+
+impl<T> Bounded<T, 1>
+where
+    T: Integer + Zeroable,
+{
+    /// Converts this [`Bounded`] into a [`bool`].
+    ///
+    /// This is a shorter way of writing `bool::from(self)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::num::Bounded;
+    ///
+    /// assert_eq!(Bounded::<u8, 1>::new::<0>().into_bool(), false);
+    /// assert_eq!(Bounded::<u8, 1>::new::<1>().into_bool(), true);
+    /// ```
+    pub fn into_bool(self) -> bool {
+        self.into()
+    }
+}
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH v6 4/9 rust: num: make Bounded::get const

In reply to Alexandre Courbot

There is a need to access the inner value of a Bounded in const context, notably for bitfields and registers. Remove the invariant check of Bounded::get, which allows us to make it const.

---
 rust/kernel/num/bounded.rs | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
rust/kernel/num/bounded.rs +5 -2
index 8e4c08924d96..b09b93cd0c5c 100644
@@ -379,6 +379,9 @@ pub fn from_expr(expr: T) -> Self {
 
     /// Returns the wrapped value as the backing type.
     ///
+    /// This is similar to the [`Deref`] implementation, but doesn't enforce the size invariant of
+    /// the [`Bounded`], which might produce slightly less optimal code.
+    ///
     /// # Examples
     ///
     /// ```
@@ -387,8 +390,8 @@ pub fn from_expr(expr: T) -> Self {
     /// let v = Bounded::<u32, 4>::new::<7>();
     /// assert_eq!(v.get(), 7u32);
     /// ```
-    pub fn get(self) -> T {
-        *self.deref()
+    pub const fn get(self) -> T {
+        self.0
     }
 
     /// Increases the number of bits usable for `self`.
Signature · 1 line
2.53.0
author maintainer
#8 lore raw

PATCH v6 5/9 rust: io: add IoRef and IoWrite types

In reply to Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +243 -0
index b150743ffa4f..6da8593f7858 100644
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.
+///
+/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`]
+/// to work uniformly with both raw `usize` offsets (for primitive types like `u32`) and typed
+/// references.
+///
+/// An `IoRef<T>` carries three pieces of information:
+///
+/// - The offset to access (returned by [`IoRef::offset`]),
+/// - The width of the access (determined by [`IoRef::IoType`]),
+/// - The type `T` in which data is returned or provided.
+///
+/// `T` and `IoType` may differ: for instance, a typed register has `T` = the register type with
+/// its bitfields, and `IoType` = its backing primitive (e.g. `u32`), with `From`/`Into`
+/// conversions between them.
+///
+/// An `IoRef` can be passed directly to [`Io::read`] or [`Io::try_read`] to obtain a value, or
+/// turned into an [`IoWrite`] via [`IoRef::set`] to be passed to [`Io::write`] or
+/// [`Io::try_write`].
+pub trait IoRef<T>: Copy
+where
+    T: From<Self::IoType> + Into<Self::IoType>,
+{
+    /// Size (`u8`, `u16`, etc) of the I/O performed on this reference.
+    type IoType;
+
+    /// Returns the offset of this reference.
+    fn offset(self) -> usize;
+
+    /// Turns this reference into an [`IoWrite`] with the initial `value`.
+    fn set(self, value: T) -> IoWrite<T, Self> {
+        IoWrite {
+            value,
+            reference: self,
+        }
+    }
+
+    /// Turns this reference into an [`IoWrite`] with the initial value `0`.
+    fn zeroed(self) -> IoWrite<T, Self>
+    where
+        T: Zeroable,
+    {
+        self.set(pin_init::zeroed())
+    }
+
+    /// Turns this reference into an [`IoWrite`] with the initial [`Default`] value of `T`.
+    fn default(self) -> IoWrite<T, Self>
+    where
+        T: Default,
+    {
+        self.set(Default::default())
+    }
+
+    /// Turns this reference into an [`IoWrite`] initialized from `0` and transformed by `f`.
+    ///
+    /// This is a shortcut for `self.zeroed().update(f)`.
+    fn init<F>(self, f: F) -> IoWrite<T, Self>
+    where
+        T: Zeroable,
+        F: FnOnce(T) -> T,
+    {
+        self.zeroed().update(f)
+    }
+
+    /// Turns this reference into an [`IoWrite`] initialized from `0` and transformed by `f`.
+    ///
+    /// `f` is expected to return a [`Result<T>`].
+    ///
+    /// This is a shortcut for `self.zeroed().try_update(f)`.
+    fn try_init<F, E>(self, f: F) -> Result<IoWrite<T, Self>, E>
+    where
+        T: Zeroable,
+        F: FnOnce(T) -> Result<T, E>,
+    {
+        self.zeroed().try_update(f)
+    }
+
+    /// Turns this reference into an [`IoWrite`] initialized from [`Default`] and transformed
+    /// by `f`.
+    ///
+    /// This is a shortcut for `self.default().update(f)`.
+    fn init_default<F>(self, f: F) -> IoWrite<T, Self>
+    where
+        T: Default,
+        F: FnOnce(T) -> T,
+    {
+        self.default().update(f)
+    }
+
+    /// Turns this reference into an [`IoWrite`] initialized from [`Default`] and transformed by
+    /// `f`.
+    ///
+    /// `f` is expected to return a [`Result<T>`].
+    ///
+    /// This is a shortcut for `self.default().try_update(f)`.
+    fn try_init_default<F, E>(self, f: F) -> Result<IoWrite<T, Self>, E>
+    where
+        T: Default,
+        F: FnOnce(T) -> Result<T, E>,
+    {
+        self.default().try_update(f)
+    }
+}
+
+/// A pending I/O write operation, bundling a value with the [`IoRef`] it should be written to.
+///
+/// Created by [`IoRef::set`], [`IoRef::zeroed`], [`IoRef::default`], [`IoRef::init`], or
+/// [`IoRef::init_default`], and consumed by [`Io::write`] or [`Io::try_write`] to perform the
+/// actual write.
+///
+/// The value can be modified before writing using [`IoWrite::update`] or [`IoWrite::try_update`],
+/// enabling a builder pattern:
+///
+/// ```ignore
+/// io.write(REGISTER.init(|v| v.with_field(x)));
+/// ```
+pub struct IoWrite<T, R>
+where
+    R: IoRef<T>,
+    T: From<R::IoType> + Into<R::IoType>,
+{
+    value: T,
+    reference: R,
+}
+
+impl<R, T> IoWrite<T, R>
+where
+    R: IoRef<T>,
+    T: From<R::IoType> + Into<R::IoType>,
+{
+    /// Transforms the value to be written by applying `f`, returning the modified [`IoWrite`].
+    #[inline(always)]
+    pub fn update<F>(mut self, f: F) -> Self
+    where
+        F: FnOnce(T) -> T,
+    {
+        self.value = f(self.value);
+
+        self
+    }
+
+    /// Transforms the value to be written by applying `f`, returning the modified [`IoWrite`] on
+    /// success.
+    #[inline(always)]
+    pub fn try_update<F, E>(mut self, f: F) -> Result<Self, E>
+    where
+        F: FnOnce(T) -> Result<T, E>,
+    {
+        self.value = f(self.value)?;
+
+        Ok(self)
+    }
+}
+
 /// Types implementing this trait (e.g. MMIO BARs or PCI config regions)
 /// can perform I/O operations on regions of memory.
 ///
@@ -406,6 +560,95 @@ fn write64(&self, value: u64, offset: usize)
         // SAFETY: `address` has been validated by `io_addr_assert`.
         unsafe { self.io_write(value, address) }
     }
+
+    /// Generic fallible read with runtime bounds check.
+    #[inline(always)]
+    fn try_read<T, R>(&self, r: R) -> Result<T>
+    where
+        T: From<R::IoType> + Into<R::IoType>,
+        R: IoRef<T>,
+        Self: IoCapable<R::IoType>,
+    {
+        let address = self.io_addr::<R::IoType>(r.offset())?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        Ok(T::from(unsafe { self.io_read(address) }))
+    }
+
+    /// Generic fallible write with runtime bounds check.
+    #[inline(always)]
+    fn try_write<T, R>(&self, access: IoWrite<T, R>) -> Result
+    where
+        T: From<R::IoType> + Into<R::IoType>,
+        R: IoRef<T>,
+        Self: IoCapable<R::IoType>,
+    {
+        let address = self.io_addr::<R::IoType>(access.reference.offset())?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        unsafe { self.io_write(access.value.into(), address) };
+        Ok(())
+    }
+
+    /// Generic fallible update with runtime bounds check.
+    ///
+    /// Caution: this does not perform any synchronization. Race conditions can occur in case of
+    /// concurrent access.
+    #[inline(always)]
+    fn try_update<T, R, F>(&self, r: R, f: F) -> Result
+    where
+        T: From<R::IoType> + Into<R::IoType>,
+        R: IoRef<T>,
+        Self: IoCapable<R::IoType>,
+        F: FnOnce(T) -> T,
+    {
+        let v = self.try_read(r)?;
+        self.try_write(r.set(f(v)))
+    }
+
+    /// Generic infallible read with compile-time bounds check.
+    #[inline(always)]
+    fn read<T, R>(&self, r: R) -> T
+    where
+        T: From<R::IoType> + Into<R::IoType>,
+        R: IoRef<T>,
+        Self: IoKnownSize + IoCapable<R::IoType>,
+    {
+        let address = self.io_addr_assert::<R::IoType>(r.offset());
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        T::from(unsafe { self.io_read(address) })
+    }
+
+    /// Generic infallible write with compile-time bounds check.
+    #[inline(always)]
+    fn write<T, R>(&self, access: IoWrite<T, R>)
+    where
+        R: IoRef<T>,
+        T: From<R::IoType> + Into<R::IoType>,
+        Self: IoKnownSize + IoCapable<R::IoType>,
+    {
+        let address = self.io_addr_assert::<R::IoType>(access.reference.offset());
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_write(access.value.into(), address) }
+    }
+
+    /// Generic infallible update with compile-time bounds check.
+    ///
+    /// Caution: this does not perform any synchronization. Race conditions can occur in case of
+    /// concurrent access.
+    #[inline(always)]
+    fn update<T, R, F>(&self, r: R, f: F)
+    where
+        T: From<R::IoType> + Into<R::IoType>,
+        R: IoRef<T>,
+        Self: IoKnownSize + IoCapable<R::IoType> + Sized,
+        F: FnOnce(T) -> T,
+    {
+        let v = self.read(r);
+        self.write(r.set(f(v)));
+    }
 }
 
 /// Trait for types with a known size at compile time.
Signature · 1 line
2.53.0
author maintainer
#17 lore raw

PATCH v6 6/9 rust: io: use generic read/write accessors for primitive accesses

In reply to Alexandre Courbot

By providing the required IoRef implementation on usize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.

---
 rust/kernel/io.rs | 103 +++++++++++++++++++-----------------------------------
 1 file changed, 35 insertions(+), 68 deletions(-)
rust/kernel/io.rs +35 -68
index 6da8593f7858..053c6385842a 100644
@@ -277,6 +277,25 @@ fn try_init_default<F, E>(self, f: F) -> Result<IoWrite<T, Self>, E>
     }
 }
 
+/// Implements [`IoRef<$primitive>`] for [`usize`], allowing to use `usize` as a parameter of
+/// [`Io::read`] and [`Io::write`].
+macro_rules! impl_usize_ioref {
+    ($($ty:ty),*) => {
+        $(
+            impl IoRef<$ty> for usize {
+                type IoType = $ty;
+
+                fn offset(self) -> usize {
+                    self
+                }
+            }
+        )*
+    }
+}
+
+// Provide the ability to read any primitive type from a [`usize`].
+impl_usize_ioref!(u8, u16, u32, u64);
+
 /// A pending I/O write operation, bundling a value with the [`IoRef`] it should be written to.
 ///
 /// Created by [`IoRef::set`], [`IoRef::zeroed`], [`IoRef::default`], [`IoRef::init`], or
@@ -371,10 +390,7 @@ fn try_read8(&self, offset: usize) -> Result<u8>
     where
         Self: IoCapable<u8>,
     {
-        let address = self.io_addr::<u8>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        Ok(unsafe { self.io_read(address) })
+        self.try_read(offset)
     }
 
     /// Fallible 16-bit read with runtime bounds check.
@@ -383,10 +399,7 @@ fn try_read16(&self, offset: usize) -> Result<u16>
     where
         Self: IoCapable<u16>,
     {
-        let address = self.io_addr::<u16>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        Ok(unsafe { self.io_read(address) })
+        self.try_read(offset)
     }
 
     /// Fallible 32-bit read with runtime bounds check.
@@ -395,10 +408,7 @@ fn try_read32(&self, offset: usize) -> Result<u32>
     where
         Self: IoCapable<u32>,
     {
-        let address = self.io_addr::<u32>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        Ok(unsafe { self.io_read(address) })
+        self.try_read(offset)
     }
 
     /// Fallible 64-bit read with runtime bounds check.
@@ -407,10 +417,7 @@ fn try_read64(&self, offset: usize) -> Result<u64>
     where
         Self: IoCapable<u64>,
     {
-        let address = self.io_addr::<u64>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        Ok(unsafe { self.io_read(address) })
+        self.try_read(offset)
     }
 
     /// Fallible 8-bit write with runtime bounds check.
@@ -419,11 +426,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Result
     where
         Self: IoCapable<u8>,
     {
-        let address = self.io_addr::<u8>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        unsafe { self.io_write(value, address) };
-        Ok(())
+        self.try_write(offset.set(value))
     }
 
     /// Fallible 16-bit write with runtime bounds check.
@@ -432,11 +435,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Result
     where
         Self: IoCapable<u16>,
     {
-        let address = self.io_addr::<u16>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        unsafe { self.io_write(value, address) };
-        Ok(())
+        self.try_write(offset.set(value))
     }
 
     /// Fallible 32-bit write with runtime bounds check.
@@ -445,11 +444,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Result
     where
         Self: IoCapable<u32>,
     {
-        let address = self.io_addr::<u32>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        unsafe { self.io_write(value, address) };
-        Ok(())
+        self.try_write(offset.set(value))
     }
 
     /// Fallible 64-bit write with runtime bounds check.
@@ -458,11 +453,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Result
     where
         Self: IoCapable<u64>,
     {
-        let address = self.io_addr::<u64>(offset)?;
-
-        // SAFETY: `address` has been validated by `io_addr`.
-        unsafe { self.io_write(value, address) };
-        Ok(())
+        self.try_write(offset.set(value))
     }
 
     /// Infallible 8-bit read with compile-time bounds check.
@@ -471,10 +462,7 @@ fn read8(&self, offset: usize) -> u8
     where
         Self: IoKnownSize + IoCapable<u8>,
     {
-        let address = self.io_addr_assert::<u8>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_read(address) }
+        self.read(offset)
     }
 
     /// Infallible 16-bit read with compile-time bounds check.
@@ -483,10 +471,7 @@ fn read16(&self, offset: usize) -> u16
     where
         Self: IoKnownSize + IoCapable<u16>,
     {
-        let address = self.io_addr_assert::<u16>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_read(address) }
+        self.read(offset)
     }
 
     /// Infallible 32-bit read with compile-time bounds check.
@@ -495,10 +480,7 @@ fn read32(&self, offset: usize) -> u32
     where
         Self: IoKnownSize + IoCapable<u32>,
     {
-        let address = self.io_addr_assert::<u32>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_read(address) }
+        self.read(offset)
     }
 
     /// Infallible 64-bit read with compile-time bounds check.
@@ -507,10 +489,7 @@ fn read64(&self, offset: usize) -> u64
     where
         Self: IoKnownSize + IoCapable<u64>,
     {
-        let address = self.io_addr_assert::<u64>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_read(address) }
+        self.read(offset)
     }
 
     /// Infallible 8-bit write with compile-time bounds check.
@@ -519,10 +498,7 @@ fn write8(&self, value: u8, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u8>,
     {
-        let address = self.io_addr_assert::<u8>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_write(value, address) }
+        self.write(offset.set(value))
     }
 
     /// Infallible 16-bit write with compile-time bounds check.
@@ -531,10 +507,7 @@ fn write16(&self, value: u16, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u16>,
     {
-        let address = self.io_addr_assert::<u16>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_write(value, address) }
+        self.write(offset.set(value))
     }
 
     /// Infallible 32-bit write with compile-time bounds check.
@@ -543,10 +516,7 @@ fn write32(&self, value: u32, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u32>,
     {
-        let address = self.io_addr_assert::<u32>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_write(value, address) }
+        self.write(offset.set(value))
     }
 
     /// Infallible 64-bit write with compile-time bounds check.
@@ -555,10 +525,7 @@ fn write64(&self, value: u64, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u64>,
     {
-        let address = self.io_addr_assert::<u64>(offset);
-
-        // SAFETY: `address` has been validated by `io_addr_assert`.
-        unsafe { self.io_write(value, address) }
+        self.write(offset.set(value))
     }
 
     /// Generic fallible read with runtime bounds check.
Signature · 1 line
2.53.0
author maintainer
#19 lore raw

PATCH v6 8/9 sample: rust: pci: use `register!` macro

In reply to Alexandre Courbot

Convert the direct IO accesses to properly defined registers.

---
 samples/rust/rust_driver_pci.rs | 84 +++++++++++++++++++++++++++++++----------
 1 file changed, 64 insertions(+), 20 deletions(-)
samples/rust/rust_driver_pci.rs +64 -20
index d3d4a7931deb..f2e1904507f1 100644
@@ -8,27 +8,58 @@
     device::Bound,
     device::Core,
     devres::Devres,
-    io::Io,
+    io::{
+        Io,
+        IoRef, //
+    },
+    num::Bounded,
     pci,
     prelude::*,
+    register,
     sync::aref::ARef, //
 };
 
-struct Regs;
+mod regs {
+    use super::*;
 
-impl Regs {
-    const TEST: usize = 0x0;
-    const OFFSET: usize = 0x4;
-    const DATA: usize = 0x8;
-    const COUNT: usize = 0xC;
-    const END: usize = 0x10;
+    register! {
+        pub(super) TEST(u8) @ 0x0 {
+            7:0 index => TestIndex;
+        }
+
+        pub(super) OFFSET(u32) @ 0x4 {
+            31:0 offset;
+        }
+
+        pub(super) DATA(u8) @ 0x8 {
+            7:0 data;
+        }
+
+        pub(super) COUNT(u32) @ 0xC {
+            31:0 count;
+        }
+    }
+
+    pub(super) const END: usize = 0x10;
 }
 
-type Bar0 = pci::Bar<{ Regs::END }>;
+type Bar0 = pci::Bar<{ regs::END }>;
 
 #[derive(Copy, Clone, Debug)]
 struct TestIndex(u8);
 
+impl From<Bounded<u8, 8>> for TestIndex {
+    fn from(value: Bounded<u8, 8>) -> Self {
+        Self(value.into())
+    }
+}
+
+impl From<TestIndex> for Bounded<u8, 8> {
+    fn from(value: TestIndex) -> Self {
+        value.0.into()
+    }
+}
+
 impl TestIndex {
     const NO_EVENTFD: Self = Self(0);
 }
@@ -54,40 +85,53 @@ struct SampleDriver {
 impl SampleDriver {
     fn testdev(index: &TestIndex, bar: &Bar0) -> Result<u32> {
         // Select the test.
-        bar.write8(index.0, Regs::TEST);
+        bar.write(regs::TEST.init(|r| r.with_index(*index)));
 
-        let offset = bar.read32(Regs::OFFSET) as usize;
-        let data = bar.read8(Regs::DATA);
+        let offset = bar.read(regs::OFFSET).into_raw() as usize;
+        let data = bar.read(regs::DATA).into();
 
         // Write `data` to `offset` to increase `count` by one.
         //
         // Note that we need `try_write8`, since `offset` can't be checked at compile-time.
         bar.try_write8(data, offset)?;
 
-        Ok(bar.read32(Regs::COUNT))
+        Ok(bar.read(regs::COUNT).into())
     }
 
     fn config_space(pdev: &pci::Device<Bound>) {
         let config = pdev.config_space();
 
-        // TODO: use the register!() macro for defining PCI configuration space registers once it
-        // has been move out of nova-core.
+        // Some PCI configuration space registers.
+        register! {
+            VENDOR_ID(u16) @ 0x0 {
+                15:0 vendor_id;
+            }
+
+            REVISION_ID(u8) @ 0x8 {
+                7:0 revision_id;
+            }
+
+            BAR(u32)[6] @ 0x10 {
+                31:0 value;
+            }
+        }
+
         dev_info!(
             pdev,
             "pci-testdev config space read8 rev ID: {:x}\n",
-            config.read8(0x8)
+            config.read(REVISION_ID).revision_id()
         );
 
         dev_info!(
             pdev,
             "pci-testdev config space read16 vendor ID: {:x}\n",
-            config.read16(0)
+            config.read(VENDOR_ID).vendor_id()
         );
 
         dev_info!(
             pdev,
             "pci-testdev config space read32 BAR 0: {:x}\n",
-            config.read32(0x10)
+            config.read(BAR::at(0)).value()
         );
     }
 }
@@ -111,7 +155,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Er
             pdev.set_master();
 
             Ok(try_pin_init!(Self {
-                bar <- pdev.iomap_region_sized::<{ Regs::END }>(0, c"rust_driver_pci"),
+                bar <- pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci"),
                 index: *info,
                 _: {
                     let bar = bar.access(pdev.as_ref())?;
@@ -131,7 +175,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Er
     fn unbind(pdev: &pci::Device<Core>, this: Pin<&Self>) {
         if let Ok(bar) = this.bar.access(pdev.as_ref()) {
             // Reset pci-testdev by writing a new test index.
-            bar.write8(this.index.0, Regs::TEST);
+            bar.write(regs::TEST.init(|r| r.with_index(this.index)));
         }
     }
 }
Signature · 1 line
2.53.0
author maintainer
#18 lore raw

PATCH v6 7/9 rust: io: add `register!` macro

In reply to Alexandre Courbot

Add a macro for defining hardware register types with I/O accessors.

Each register field is represented as a Bounded of the appropriate bit width, ensuring field values are never silently truncated.

Fields can optionally be converted to/from custom types, either fallibly or infallibly.

The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.

---
 rust/kernel/io.rs          |    5 +-
 rust/kernel/io/register.rs | 1125 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1129 insertions(+), 1 deletion(-)
rust/kernel/io.rs +4 -1
index 053c6385842a..c2dddf5b9dfd 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
@@ -177,7 +178,7 @@ pub trait IoCapable<T> {
 ///
 /// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`]
 /// to work uniformly with both raw `usize` offsets (for primitive types like `u32`) and typed
-/// references.
+/// references (like those generated by the [`register!`] macro).
 ///
 /// An `IoRef<T>` carries three pieces of information:
 ///
@@ -192,6 +193,8 @@ pub trait IoCapable<T> {
 /// An `IoRef` can be passed directly to [`Io::read`] or [`Io::try_read`] to obtain a value, or
 /// turned into an [`IoWrite`] via [`IoRef::set`] to be passed to [`Io::write`] or
 /// [`Io::try_write`].
+///
+/// [`register!`]: kernel::register!
 pub trait IoRef<T>: Copy
 where
     T: From<Self::IoType> + Into<Self::IoType>,
rust/kernel/io/register.rs new file +1125 -0

1,125 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#20 lore raw

PATCH v6 9/9 gpu: nova-core: use the kernel `register!` macro

In reply to Alexandre Courbot

Replace the nova-core internal register! macro by the one defined in the kernel crate and remove our own private implementations.

---
 drivers/gpu/nova-core/falcon.rs           | 249 +++++-----
 drivers/gpu/nova-core/falcon/gsp.rs       |  23 +-
 drivers/gpu/nova-core/falcon/hal/ga102.rs |  65 +--
 drivers/gpu/nova-core/falcon/hal/tu102.rs |  11 +-
 drivers/gpu/nova-core/falcon/sec2.rs      |  17 +-
 drivers/gpu/nova-core/fb.rs               |   6 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |  40 +-
 drivers/gpu/nova-core/fb/hal/ga102.rs     |   7 +-
 drivers/gpu/nova-core/fb/hal/tu102.rs     |  22 +-
 drivers/gpu/nova-core/gfw.rs              |  11 +-
 drivers/gpu/nova-core/gpu.rs              |  36 +-
 drivers/gpu/nova-core/gsp/boot.rs         |  11 +-
 drivers/gpu/nova-core/gsp/cmdq.rs         |  10 +-
 drivers/gpu/nova-core/regs.rs             | 544 ++++++++++++----------
 drivers/gpu/nova-core/regs/macros.rs      | 739 ------------------------------
 15 files changed, 565 insertions(+), 1226 deletions(-)
drivers/gpu/nova-core/falcon.rs +110 -139
index 37bfee1d0949..bd3154a140ac 100644
@@ -12,7 +12,13 @@
         DmaAddress,
         DmaMask, //
     },
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        register::RegisterBase,
+        Io,
+        IoRef, //
+    },
+    num::Bounded,
     prelude::*,
     sync::aref::ARef,
     time::{
@@ -30,7 +36,6 @@
         IntoSafeCast, //
     },
     regs,
-    regs::macros::RegisterBase, //
 };
 
 pub(crate) mod gsp;
@@ -38,11 +43,11 @@
 pub(crate) mod sec2;
 
 // TODO[FPRI]: Replace with `ToPrimitive`.
-macro_rules! impl_from_enum_to_u8 {
-    ($enum_type:ty) => {
-        impl From<$enum_type> for u8 {
+macro_rules! impl_from_enum_to_bounded {
+    ($enum_type:ty, $length:literal) => {
+        impl From<$enum_type> for Bounded<u32, $length> {
             fn from(value: $enum_type) -> Self {
-                value as u8
+                Bounded::from_expr(value as u32)
             }
         }
     };
@@ -50,10 +55,8 @@ fn from(value: $enum_type) -> Self {
 
 /// Revision number of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`]
 /// register.
-#[repr(u8)]
-#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
 pub(crate) enum FalconCoreRev {
-    #[default]
     Rev1 = 1,
     Rev2 = 2,
     Rev3 = 3,
@@ -62,16 +65,16 @@ pub(crate) enum FalconCoreRev {
     Rev6 = 6,
     Rev7 = 7,
 }
-impl_from_enum_to_u8!(FalconCoreRev);
+impl_from_enum_to_bounded!(FalconCoreRev, 4);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconCoreRev {
+impl TryFrom<Bounded<u32, 4>> for FalconCoreRev {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
+    fn try_from(value: Bounded<u32, 4>) -> Result<Self> {
         use FalconCoreRev::*;
 
-        let rev = match value {
+        let rev = match value.get() {
             1 => Rev1,
             2 => Rev2,
             3 => Rev3,
@@ -88,46 +91,38 @@ fn try_from(value: u8) -> Result<Self> {
 
 /// Revision subversion number of a falcon core, used in the
 /// [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] register.
-#[repr(u8)]
-#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
 pub(crate) enum FalconCoreRevSubversion {
-    #[default]
     Subversion0 = 0,
     Subversion1 = 1,
     Subversion2 = 2,
     Subversion3 = 3,
 }
-impl_from_enum_to_u8!(FalconCoreRevSubversion);
+impl_from_enum_to_bounded!(FalconCoreRevSubversion, 2);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconCoreRevSubversion {
-    type Error = Error;
-
-    fn try_from(value: u8) -> Result<Self> {
+impl From<Bounded<u32, 2>> for FalconCoreRevSubversion {
+    fn from(value: Bounded<u32, 2>) -> Self {
         use FalconCoreRevSubversion::*;
 
-        let sub_version = match value & 0b11 {
+        match value.get() {
             0 => Subversion0,
             1 => Subversion1,
             2 => Subversion2,
             3 => Subversion3,
-            _ => return Err(EINVAL),
-        };
-
-        Ok(sub_version)
+            // SAFETY: `value` comes from a 2-bit `Bounded`, and we just checked all possible
+            // values.
+            _ => unsafe { core::hint::unreachable_unchecked() },
+        }
     }
 }
 
-/// Security model of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`]
-/// register.
-#[repr(u8)]
-#[derive(Debug, Default, Copy, Clone)]
 /// Security mode of the Falcon microprocessor.
 ///
 /// See `falcon.rst` for more details.
+#[derive(Debug, Copy, Clone)]
 pub(crate) enum FalconSecurityModel {
     /// Non-Secure: runs unsigned code without privileges.
-    #[default]
     None = 0,
     /// Light-Secured (LS): Runs signed code with some privileges.
     /// Entry into this mode is only possible from 'Heavy-secure' mode, which verifies the code's
@@ -141,16 +136,16 @@ pub(crate) enum FalconSecurityModel {
     /// Also known as High-Secure, Privilege Level 3 or PL3.
     Heavy = 3,
 }
-impl_from_enum_to_u8!(FalconSecurityModel);
+impl_from_enum_to_bounded!(FalconSecurityModel, 2);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconSecurityModel {
+impl TryFrom<Bounded<u32, 2>> for FalconSecurityModel {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
+    fn try_from(value: Bounded<u32, 2>) -> Result<Self> {
         use FalconSecurityModel::*;
 
-        let sec_model = match value {
+        let sec_model = match value.get() {
             0 => None,
             2 => Light,
             3 => Heavy,
@@ -163,24 +158,22 @@ fn try_from(value: u8) -> Result<Self> {
 
 /// Signing algorithm for a given firmware, used in the [`crate::regs::NV_PFALCON2_FALCON_MOD_SEL`]
 /// register. It is passed to the Falcon Boot ROM (BROM) as a parameter.
-#[repr(u8)]
-#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
 pub(crate) enum FalconModSelAlgo {
     /// AES.
-    #[expect(dead_code)]
     Aes = 0,
     /// RSA3K.
-    #[default]
     Rsa3k = 1,
 }
-impl_from_enum_to_u8!(FalconModSelAlgo);
+impl_from_enum_to_bounded!(FalconModSelAlgo, 8);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconModSelAlgo {
+impl TryFrom<Bounded<u32, 8>> for FalconModSelAlgo {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
-        match value {
+    fn try_from(value: Bounded<u32, 8>) -> Result<Self> {
+        match value.get() {
+            0 => Ok(FalconModSelAlgo::Aes),
             1 => Ok(FalconModSelAlgo::Rsa3k),
             _ => Err(EINVAL),
         }
@@ -188,21 +181,19 @@ fn try_from(value: u8) -> Result<Self> {
 }
 
 /// Valid values for the `size` field of the [`crate::regs::NV_PFALCON_FALCON_DMATRFCMD`] register.
-#[repr(u8)]
-#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
 pub(crate) enum DmaTrfCmdSize {
     /// 256 bytes transfer.
-    #[default]
     Size256B = 0x6,
 }
-impl_from_enum_to_u8!(DmaTrfCmdSize);
+impl_from_enum_to_bounded!(DmaTrfCmdSize, 3);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for DmaTrfCmdSize {
+impl TryFrom<Bounded<u32, 3>> for DmaTrfCmdSize {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
-        match value {
+    fn try_from(value: Bounded<u32, 3>) -> Result<Self> {
+        match value.get() {
             0x6 => Ok(Self::Size256B),
             _ => Err(EINVAL),
         }
@@ -210,33 +201,24 @@ fn try_from(value: u8) -> Result<Self> {
 }
 
 /// Currently active core on a dual falcon/riscv (Peregrine) controller.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub(crate) enum PeregrineCoreSelect {
     /// Falcon core is active.
-    #[default]
     Falcon = 0,
     /// RISC-V core is active.
     Riscv = 1,
 }
+impl_from_enum_to_bounded!(PeregrineCoreSelect, 1);
 
-impl From<bool> for PeregrineCoreSelect {
-    fn from(value: bool) -> Self {
-        match value {
+impl From<Bounded<u32, 1>> for PeregrineCoreSelect {
+    fn from(value: Bounded<u32, 1>) -> Self {
+        match bool::from(value) {
             false => PeregrineCoreSelect::Falcon,
             true => PeregrineCoreSelect::Riscv,
         }
     }
 }
 
-impl From<PeregrineCoreSelect> for bool {
-    fn from(value: PeregrineCoreSelect) -> Self {
-        match value {
-            PeregrineCoreSelect::Falcon => false,
-            PeregrineCoreSelect::Riscv => true,
-        }
-    }
-}
-
 /// Different types of memory present in a falcon core.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub(crate) enum FalconMem {
@@ -252,10 +234,8 @@ pub(crate) enum FalconMem {
 /// Defines the Framebuffer Interface (FBIF) aperture type.
 /// This determines the memory type for external memory access during a DMA transfer, which is
 /// performed by the Falcon's Framebuffer DMA (FBDMA) engine. See falcon.rst for more details.
-#[derive(Debug, Clone, Default)]
+#[derive(Debug, Clone)]
 pub(crate) enum FalconFbifTarget {
-    /// VRAM.
-    #[default]
     /// Local Framebuffer (GPU's VRAM memory).
     LocalFb = 0,
     /// Coherent system memory (System DRAM).
@@ -263,14 +243,14 @@ pub(crate) enum FalconFbifTarget {
     /// Non-coherent system memory (System DRAM).
     NoncoherentSysmem = 2,
 }
-impl_from_enum_to_u8!(FalconFbifTarget);
+impl_from_enum_to_bounded!(FalconFbifTarget, 2);
 
 // TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconFbifTarget {
+impl TryFrom<Bounded<u32, 2>> for FalconFbifTarget {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
-        let res = match value {
+    fn try_from(value: Bounded<u32, 2>) -> Result<Self> {
+        let res = match value.get() {
             0 => Self::LocalFb,
             1 => Self::CoherentSysmem,
             2 => Self::NoncoherentSysmem,
@@ -282,34 +262,25 @@ fn try_from(value: u8) -> Result<Self> {
 }
 
 /// Type of memory addresses to use.
-#[derive(Debug, Clone, Default)]
+#[derive(Debug, Clone)]
 pub(crate) enum FalconFbifMemType {
     /// Virtual memory addresses.
-    #[default]
     Virtual = 0,
     /// Physical memory addresses.
     Physical = 1,
 }
+impl_from_enum_to_bounded!(FalconFbifMemType, 1);
 
 /// Conversion from a single-bit register field.
-impl From<bool> for FalconFbifMemType {
-    fn from(value: bool) -> Self {
-        match value {
+impl From<Bounded<u32, 1>> for FalconFbifMemType {
+    fn from(value: Bounded<u32, 1>) -> Self {
+        match bool::from(value) {
             false => Self::Virtual,
             true => Self::Physical,
         }
     }
 }
 
-impl From<FalconFbifMemType> for bool {
-    fn from(value: FalconFbifMemType) -> Self {
-        match value {
-            FalconFbifMemType::Virtual => false,
-            FalconFbifMemType::Physical => true,
-        }
-    }
-}
-
 /// Type used to represent the `PFALCON` registers address base for a given falcon engine.
 pub(crate) struct PFalconBase(());
 
@@ -318,13 +289,10 @@ fn from(value: FalconFbifMemType) -> Self {
 
 /// Trait defining the parameters of a given Falcon engine.
 ///
-/// Each engine provides one base for `PFALCON` and `PFALCON2` registers. The `ID` constant is used
-/// to identify a given Falcon instance with register I/O methods.
+/// Each engine provides one base for `PFALCON` and `PFALCON2` registers.
 pub(crate) trait FalconEngine:
     Send + Sync + RegisterBase<PFalconBase> + RegisterBase<PFalcon2Base> + Sized
 {
-    /// Singleton of the engine, used to identify it with register I/O methods.
-    const ID: Self;
 }
 
 /// Represents a portion of the firmware to be loaded into a particular memory (e.g. IMEM or DMEM).
@@ -394,8 +362,10 @@ pub(crate) fn new(dev: &device::Device, chipset: Chipset) -> Result<Self> {
 
     /// Resets DMA-related registers.
     pub(crate) fn dma_reset(&self, bar: &Bar0) {
-        regs::NV_PFALCON_FBIF_CTL::update(bar, &E::ID, |v| v.set_allow_phys_no_ctx(true));
-        regs::NV_PFALCON_FALCON_DMACTL::default().write(bar, &E::ID);
+        bar.update(regs::NV_PFALCON_FBIF_CTL::of::<E>(), |v| {
+            v.with_allow_phys_no_ctx(true)
+        });
+        bar.write(regs::NV_PFALCON_FALCON_DMACTL::of::<E>().zeroed());
     }
 
     /// Reset the controller, select the falcon core, and wait for memory scrubbing to complete.
@@ -404,9 +374,10 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result {
         self.hal.select_core(self, bar)?;
         self.hal.reset_wait_mem_scrubbing(bar)?;
 
-        regs::NV_PFALCON_FALCON_RM::default()
-            .set_value(regs::NV_PMC_BOOT_0::read(bar).into())
-            .write(bar, &E::ID);
+        bar.write(
+            regs::NV_PFALCON_FALCON_RM::of::<E>()
+                .init(|r| r.with_value(bar.read(regs::NV_PMC_BOOT_0).into_raw())),
+        );
 
         Ok(())
     }
@@ -475,36 +446,37 @@ fn dma_wr<F: FalconFirmware<Target = E>>(
 
         // Set up the base source DMA address.
 
-        regs::NV_PFALCON_FALCON_DMATRFBASE::default()
-            // CAST: `as u32` is used on purpose since we do want to strip the upper bits, which
-            // will be written to `NV_PFALCON_FALCON_DMATRFBASE1`.
-            .set_base((dma_start >> 8) as u32)
-            .write(bar, &E::ID);
-        regs::NV_PFALCON_FALCON_DMATRFBASE1::default()
-            // CAST: `as u16` is used on purpose since the remaining bits are guaranteed to fit
-            // within a `u16`.
-            .set_base((dma_start >> 40) as u16)
-            .write(bar, &E::ID);
+        bar.write(regs::NV_PFALCON_FALCON_DMATRFBASE::of::<E>().init(|r|
+                    // CAST: `as u32` is used on purpose since we do want to strip the upper bits,
+                    // which will be written to `NV_PFALCON_FALCON_DMATRFBASE1`.
+                    r.with_base((dma_start >> 8) as u32)));
+        bar.write(
+            regs::NV_PFALCON_FALCON_DMATRFBASE1::of::<E>()
+                .try_init(|r| r.try_with_base(dma_start >> 40))?,
+        );
 
-        let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD::default()
-            .set_size(DmaTrfCmdSize::Size256B)
+        let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD::zeroed()
+            .with_size(DmaTrfCmdSize::Size256B)
             .with_falcon_mem(target_mem);
 
         for pos in (0..num_transfers).map(|i| i * DMA_LEN) {
             // Perform a transfer of size `DMA_LEN`.
-            regs::NV_PFALCON_FALCON_DMATRFMOFFS::default()
-                .set_offs(load_offsets.dst_start + pos)
-                .write(bar, &E::ID);
-            regs::NV_PFALCON_FALCON_DMATRFFBOFFS::default()
-                .set_offs(src_start + pos)
-                .write(bar, &E::ID);
-            cmd.write(bar, &E::ID);
+            bar.write(
+                regs::NV_PFALCON_FALCON_DMATRFMOFFS::of::<E>()
+                    .try_init(|r| r.try_with_offs(load_offsets.dst_start + pos))?,
+            );
+            bar.write(
+                regs::NV_PFALCON_FALCON_DMATRFFBOFFS::of::<E>()
+                    .init(|r| r.with_offs(src_start + pos)),
+            );
+
+            bar.write(regs::NV_PFALCON_FALCON_DMATRFCMD::of::<E>().set(cmd));
 
             // Wait for the transfer to complete.
             // TIMEOUT: arbitrarily large value, no DMA transfer to the falcon's small memories
             // should ever take that long.
             read_poll_timeout(
-                || Ok(regs::NV_PFALCON_FALCON_DMATRFCMD::read(bar, &E::ID)),
+                || Ok(bar.read(regs::NV_PFALCON_FALCON_DMATRFCMD::of::<E>())),
                 |r| r.idle(),
                 Delta::ZERO,
                 Delta::from_secs(2),
@@ -524,9 +496,9 @@ fn dma_load<F: FalconFirmware<Target = E>>(&self, bar: &Bar0, fw: &F) -> Result
         }
 
         self.dma_reset(bar);
-        regs::NV_PFALCON_FBIF_TRANSCFG::update(bar, &E::ID, 0, |v| {
-            v.set_target(FalconFbifTarget::CoherentSysmem)
-                .set_mem_type(FalconFbifMemType::Physical)
+        bar.update(regs::NV_PFALCON_FBIF_TRANSCFG::of::<E>().at(0), |v| {
+            v.with_target(FalconFbifTarget::CoherentSysmem)
+                .with_mem_type(FalconFbifMemType::Physical)
         });
 
         self.dma_wr(bar, fw, FalconMem::ImemSecure, fw.imem_sec_load_params())?;
@@ -535,9 +507,9 @@ fn dma_load<F: FalconFirmware<Target = E>>(&self, bar: &Bar0, fw: &F) -> Result
         self.hal.program_brom(self, bar, &fw.brom_params())?;
 
         // Set `BootVec` to start of non-secure code.
-        regs::NV_PFALCON_FALCON_BOOTVEC::default()
-            .set_value(fw.boot_addr())
-            .write(bar, &E::ID);
+        bar.write(
+            regs::NV_PFALCON_FALCON_BOOTVEC::of::<E>().init(|r| r.with_value(fw.boot_addr())),
+        );
 
         Ok(())
     }
@@ -546,7 +518,7 @@ fn dma_load<F: FalconFirmware<Target = E>>(&self, bar: &Bar0, fw: &F) -> Result
     pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> Result<()> {
         // TIMEOUT: arbitrarily large value, firmwares should complete in less than 2 seconds.
         read_poll_timeout(
-            || Ok(regs::NV_PFALCON_FALCON_CPUCTL::read(bar, &E::ID)),
+            || Ok(bar.read(regs::NV_PFALCON_FALCON_CPUCTL::of::<E>())),
             |r| r.halted(),
             Delta::ZERO,
             Delta::from_secs(2),
@@ -557,13 +529,16 @@ pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> Result<()> {
 
     /// Start the falcon CPU.
     pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {
-        match regs::NV_PFALCON_FALCON_CPUCTL::read(bar, &E::ID).alias_en() {
-            true => regs::NV_PFALCON_FALCON_CPUCTL_ALIAS::default()
-                .set_startcpu(true)
-                .write(bar, &E::ID),
-            false => regs::NV_PFALCON_FALCON_CPUCTL::default()
-                .set_startcpu(true)
-                .write(bar, &E::ID),
+        match bar
+            .read(regs::NV_PFALCON_FALCON_CPUCTL::of::<E>())
+            .alias_en()
+        {
+            true => bar.write(
+                regs::NV_PFALCON_FALCON_CPUCTL_ALIAS::of::<E>().init(|r| r.with_startcpu(true)),
+            ),
+            false => {
+                bar.write(regs::NV_PFALCON_FALCON_CPUCTL::of::<E>().init(|r| r.with_startcpu(true)))
+            }
         }
 
         Ok(())
@@ -572,26 +547,24 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {
     /// Writes values to the mailbox registers if provided.
     pub(crate) fn write_mailboxes(&self, bar: &Bar0, mbox0: Option<u32>, mbox1: Option<u32>) {
         if let Some(mbox0) = mbox0 {
-            regs::NV_PFALCON_FALCON_MAILBOX0::default()
-                .set_value(mbox0)
-                .write(bar, &E::ID);
+            bar.write(regs::NV_PFALCON_FALCON_MAILBOX0::of::<E>().init(|r| r.with_value(mbox0)));
         }
 
         if let Some(mbox1) = mbox1 {
-            regs::NV_PFALCON_FALCON_MAILBOX1::default()
-                .set_value(mbox1)
-                .write(bar, &E::ID);
+            bar.write(regs::NV_PFALCON_FALCON_MAILBOX1::of::<E>().init(|r| r.with_value(mbox1)));
         }
     }
 
     /// Reads the value from `mbox0` register.
     pub(crate) fn read_mailbox0(&self, bar: &Bar0) -> u32 {
-        regs::NV_PFALCON_FALCON_MAILBOX0::read(bar, &E::ID).value()
+        bar.read(regs::NV_PFALCON_FALCON_MAILBOX0::of::<E>())
+            .value()
     }
 
     /// Reads the value from `mbox1` register.
     pub(crate) fn read_mailbox1(&self, bar: &Bar0) -> u32 {
-        regs::NV_PFALCON_FALCON_MAILBOX1::read(bar, &E::ID).value()
+        bar.read(regs::NV_PFALCON_FALCON_MAILBOX1::of::<E>())
+            .value()
     }
 
     /// Reads values from both mailbox registers.
@@ -650,8 +623,6 @@ pub(crate) fn load<F: FalconFirmware<Target = E>>(&self, bar: &Bar0, fw: &F) ->
 
     /// Write the application version to the OS register.
     pub(crate) fn write_os_version(&self, bar: &Bar0, app_version: u32) {
-        regs::NV_PFALCON_FALCON_OS::default()
-            .set_value(app_version)
-            .write(bar, &E::ID);
+        bar.write(regs::NV_PFALCON_FALCON_OS::of::<E>().init(|r| r.with_value(app_version)));
     }
 }
drivers/gpu/nova-core/falcon/gsp.rs +10 -13
index 67edef3636c1..2031c6e760b4 100644
@@ -1,7 +1,12 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use kernel::{
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        register::RegisterBase,
+        Io,
+        IoRef, //
+    },
     prelude::*,
     time::Delta, //
 };
@@ -14,13 +19,9 @@
         PFalcon2Base,
         PFalconBase, //
     },
-    regs::{
-        self,
-        macros::RegisterBase, //
-    },
+    regs,
 };
 
-/// Type specifying the `Gsp` falcon engine. Cannot be instantiated.
 pub(crate) struct Gsp(());
 
 impl RegisterBase<PFalconBase> for Gsp {
@@ -31,23 +32,19 @@ impl RegisterBase<PFalcon2Base> for Gsp {
     const BASE: usize = 0x00111000;
 }
 
-impl FalconEngine for Gsp {
-    const ID: Self = Gsp(());
-}
+impl FalconEngine for Gsp {}
 
 impl Falcon<Gsp> {
     /// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to
     /// allow GSP to signal CPU for processing new messages in message queue.
     pub(crate) fn clear_swgen0_intr(&self, bar: &Bar0) {
-        regs::NV_PFALCON_FALCON_IRQSCLR::default()
-            .set_swgen0(true)
-            .write(bar, &Gsp::ID);
+        bar.write(regs::NV_PFALCON_FALCON_IRQSCLR::of::<Gsp>().init(|r| r.with_swgen0(true)));
     }
 
     /// Checks if GSP reload/resume has completed during the boot process.
     pub(crate) fn check_reload_completed(&self, bar: &Bar0, timeout: Delta) -> Result<bool> {
         read_poll_timeout(
-            || Ok(regs::NV_PGC6_BSI_SECURE_SCRATCH_14::read(bar)),
+            || Ok(bar.read(regs::NV_PGC6_BSI_SECURE_SCRATCH_14)),
             |val| val.boot_stage_3_handoff(),
             Delta::ZERO,
             timeout,
drivers/gpu/nova-core/falcon/hal/ga102.rs +38 -27

119 lines not on this page · raw message

drivers/gpu/nova-core/falcon/hal/tu102.rs +7 -4
index 7de6f24cc0a0..cd4ac53e32af 100644
@@ -3,7 +3,10 @@
 use core::marker::PhantomData;
 
 use kernel::{
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        Io, //
+    },
     prelude::*,
     time::Delta, //
 };
@@ -49,14 +52,14 @@ fn program_brom(&self, _falcon: &Falcon<E>, _bar: &Bar0, _params: &FalconBromPar
     }
 
     fn is_riscv_active(&self, bar: &Bar0) -> bool {
-        let cpuctl = regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS::read(bar, &E::ID);
-        cpuctl.active_stat()
+        bar.read(regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS::of::<E>())
+            .active_stat()
     }
 
     fn reset_wait_mem_scrubbing(&self, bar: &Bar0) -> Result {
         // TIMEOUT: memory scrubbing should complete in less than 10ms.
         read_poll_timeout(
-            || Ok(regs::NV_PFALCON_FALCON_DMACTL::read(bar, &E::ID)),
+            || Ok(bar.read(regs::NV_PFALCON_FALCON_DMACTL::of::<E>())),
             |r| r.mem_scrubbing_done(),
             Delta::ZERO,
             Delta::from_millis(10),
drivers/gpu/nova-core/falcon/sec2.rs +7 -10
index b57d362e576a..91ec7d49c1f5 100644
@@ -1,12 +1,11 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use crate::{
-    falcon::{
-        FalconEngine,
-        PFalcon2Base,
-        PFalconBase, //
-    },
-    regs::macros::RegisterBase,
+use kernel::io::register::RegisterBase;
+
+use crate::falcon::{
+    FalconEngine,
+    PFalcon2Base,
+    PFalconBase, //
 };
 
 /// Type specifying the `Sec2` falcon engine. Cannot be instantiated.
@@ -20,6 +19,4 @@ impl RegisterBase<PFalcon2Base> for Sec2 {
     const BASE: usize = 0x00841000;
 }
 
-impl FalconEngine for Sec2 {
-    const ID: Self = Sec2(());
-}
+impl FalconEngine for Sec2 {}
drivers/gpu/nova-core/fb.rs +5 -1
index c62abcaed547..6b392588f766 100644
@@ -4,6 +4,7 @@
 
 use kernel::{
     device,
+    io::Io,
     prelude::*,
     ptr::{
         Alignable,
@@ -134,7 +135,10 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0, gsp_fw: &GspFirmware) -> Result<
                 let base = fb.end - NV_PRAMIN_SIZE;
 
                 if hal.supports_display(bar) {
-                    match regs::NV_PDISP_VGA_WORKSPACE_BASE::read(bar).vga_workspace_addr() {
+                    match bar
+                        .read(regs::NV_PDISP_VGA_WORKSPACE_BASE)
+                        .vga_workspace_addr()
+                    {
                         Some(addr) => {
                             if addr < base {
                                 const VBIOS_WORKSPACE_SIZE: u64 = usize_as_u64(SZ_128K);
drivers/gpu/nova-core/fb/hal/ga100.rs +26 -14
index e0acc41aa7cd..9c95733f1a48 100644
@@ -1,6 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    io::{
+        Io,
+        IoRef, //
+    },
+    num::Bounded,
+    prelude::*, //
+};
 
 use crate::{
     driver::Bar0,
@@ -13,26 +20,31 @@
 struct Ga100;
 
 pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) -> u64 {
-    u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::read(bar).adr_39_08()) << FLUSH_SYSMEM_ADDR_SHIFT
-        | u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::read(bar).adr_63_40())
+    u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR).adr_39_08()) << FLUSH_SYSMEM_ADDR_SHIFT
+        | u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI).adr_63_40())
             << FLUSH_SYSMEM_ADDR_SHIFT_HI
 }
 
 pub(super) fn write_sysmem_flush_page_ga100(bar: &Bar0, addr: u64) {
-    regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::default()
-        // CAST: `as u32` is used on purpose since the remaining bits are guaranteed to fit within
-        // a `u32`.
-        .set_adr_63_40((addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI) as u32)
-        .write(bar);
-    regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default()
-        // CAST: `as u32` is used on purpose since we want to strip the upper bits that have been
-        // written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`.
-        .set_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32)
-        .write(bar);
+    bar.write(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI.init(|r| {
+        r.with_adr_63_40(
+            Bounded::<u64, _>::from(addr)
+                .shr::<FLUSH_SYSMEM_ADDR_SHIFT_HI, _>()
+                .cast(),
+        )
+    }));
+
+    bar.write(
+        regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR
+            // CAST: `as u32` is used on purpose since we want to strip the upper bits that have
+            // been written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`.
+            .init(|r| r.with_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32)),
+    );
 }
 
 pub(super) fn display_enabled_ga100(bar: &Bar0) -> bool {
-    !regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY::read(bar).display_disabled()
+    !bar.read(regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY)
+        .display_disabled()
 }
 
 /// Shift applied to the sysmem address before it is written into
drivers/gpu/nova-core/fb/hal/ga102.rs +5 -2
index 734605905031..4b9f0f74d0e7 100644
@@ -1,6 +1,9 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    io::Io,
+    prelude::*, //
+};
 
 use crate::{
     driver::Bar0,
@@ -9,7 +12,7 @@
 };
 
 fn vidmem_size_ga102(bar: &Bar0) -> u64 {
-    regs::NV_USABLE_FB_SIZE_IN_MB::read(bar).usable_fb_size()
+    bar.read(regs::NV_USABLE_FB_SIZE_IN_MB).usable_fb_size()
 }
 
 struct Ga102;
drivers/gpu/nova-core/fb/hal/tu102.rs +13 -9
index eec984f4e816..58894fb870f7 100644
@@ -1,6 +1,12 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    io::{
+        Io,
+        IoRef, //
+    },
+    prelude::*, //
+};
 
 use crate::{
     driver::Bar0,
@@ -13,26 +19,24 @@
 pub(super) const FLUSH_SYSMEM_ADDR_SHIFT: u32 = 8;
 
 pub(super) fn read_sysmem_flush_page_gm107(bar: &Bar0) -> u64 {
-    u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::read(bar).adr_39_08()) << FLUSH_SYSMEM_ADDR_SHIFT
+    u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR).adr_39_08()) << FLUSH_SYSMEM_ADDR_SHIFT
 }
 
 pub(super) fn write_sysmem_flush_page_gm107(bar: &Bar0, addr: u64) -> Result {
     // Check that the address doesn't overflow the receiving 32-bit register.
     u32::try_from(addr >> FLUSH_SYSMEM_ADDR_SHIFT)
         .map_err(|_| EINVAL)
-        .map(|addr| {
-            regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default()
-                .set_adr_39_08(addr)
-                .write(bar)
-        })
+        .map(|addr| bar.write(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR.init(|r| r.with_adr_39_08(addr))))
 }
 
 pub(super) fn display_enabled_gm107(bar: &Bar0) -> bool {
-    !regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY::read(bar).display_disabled()
+    !bar.read(regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY)
+        .display_disabled()
 }
 
 pub(super) fn vidmem_size_gp102(bar: &Bar0) -> u64 {
-    regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE::read(bar).usable_fb_size()
+    bar.read(regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE)
+        .usable_fb_size()
 }
 
 struct Tu102;
drivers/gpu/nova-core/gfw.rs +8 -3
index 9121f400046d..fb75dd10a172 100644
@@ -19,7 +19,10 @@
 //! Note that the devinit sequence also needs to run during suspend/resume.
 
 use kernel::{
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        Io, //
+    },
     prelude::*,
     time::Delta, //
 };
@@ -58,9 +61,11 @@ pub(crate) fn wait_gfw_boot_completion(bar: &Bar0) -> Result {
             Ok(
                 // Check that FWSEC has lowered its protection level before reading the GFW_BOOT
                 // status.
-                regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK::read(bar)
+                bar.read(regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK)
                     .read_protection_level0()
-                    && regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT::read(bar).completed(),
+                    && bar
+                        .read(regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT)
+                        .completed(),
             )
         },
         |&gfw_booted| gfw_booted,
drivers/gpu/nova-core/gpu.rs +18 -18
index 9b042ef1a308..ca2c153cf87f 100644
@@ -4,6 +4,8 @@
     device,
     devres::Devres,
     fmt,
+    io::Io,
+    num::Bounded,
     pci,
     prelude::*,
     sync::Arc, //
@@ -122,24 +124,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 }
 
 /// Enum representation of the GPU generation.
-///
-/// TODO: remove the `Default` trait implementation, and the `#[default]`
-/// attribute, once the register!() macro (which creates Architecture items) no
-/// longer requires it for read-only fields.
-#[derive(fmt::Debug, Default, Copy, Clone)]
+#[derive(fmt::Debug, Copy, Clone)]
 #[repr(u8)]
 pub(crate) enum Architecture {
-    #[default]
     Turing = 0x16,
     Ampere = 0x17,
     Ada = 0x19,
 }
 
-impl TryFrom<u8> for Architecture {
+impl TryFrom<Bounded<u32, 6>> for Architecture {
     type Error = Error;
 
-    fn try_from(value: u8) -> Result<Self> {
-        match value {
+    fn try_from(value: Bounded<u32, 6>) -> Result<Self> {
+        match u8::from(value) {
             0x16 => Ok(Self::Turing),
             0x17 => Ok(Self::Ampere),
             0x19 => Ok(Self::Ada),
@@ -148,23 +145,26 @@ fn try_from(value: u8) -> Result<Self> {
     }
 }
 
-impl From<Architecture> for u8 {
+impl From<Architecture> for Bounded<u32, 6> {
     fn from(value: Architecture) -> Self {
-        // CAST: `Architecture` is `repr(u8)`, so this cast is always lossless.
-        value as u8
+        match value {
+            Architecture::Turing => Bounded::<u8, 6>::new::<0x16>().cast(),
+            Architecture::Ampere => Bounded::<u8, 6>::new::<0x17>().cast(),
+            Architecture::Ada => Bounded::<u8, 6>::new::<0x19>().cast(),
+        }
     }
 }
 
 pub(crate) struct Revision {
-    major: u8,
-    minor: u8,
+    major: Bounded<u8, 4>,
+    minor: Bounded<u8, 4>,
 }
 
 impl From<regs::NV_PMC_BOOT_42> for Revision {
     fn from(boot0: regs::NV_PMC_BOOT_42) -> Self {
         Self {
-            major: boot0.major_revision(),
-            minor: boot0.minor_revision(),
+            major: boot0.major_revision().cast(),
+            minor: boot0.minor_revision().cast(),
         }
     }
 }
@@ -201,13 +201,13 @@ fn new(dev: &device::Device, bar: &Bar0) -> Result<Spec> {
         //     from an earlier (pre-Fermi) era, and then using boot42 to precisely identify the GPU.
         //     Somewhere in the Rubin timeframe, boot0 will no longer have space to add new GPU IDs.
 
-        let boot0 = regs::NV_PMC_BOOT_0::read(bar);
+        let boot0 = bar.read(regs::NV_PMC_BOOT_0);
 
         if boot0.is_older_than_fermi() {
             return Err(ENODEV);
         }
 
-        let boot42 = regs::NV_PMC_BOOT_42::read(bar);
+        let boot42 = bar.read(regs::NV_PMC_BOOT_42);
         Spec::try_from(boot42).inspect_err(|_| {
             dev_err!(dev, "Unsupported chipset: {}\n", boot42);
         })
drivers/gpu/nova-core/gsp/boot.rs +7 -4
index be427fe26a58..154a2bc4655e 100644
@@ -5,6 +5,7 @@
     dma::CoherentAllocation,
     dma_write,
     io::poll::read_poll_timeout,
+    io::Io,
     pci,
     prelude::*,
     time::Delta, //
@@ -55,7 +56,7 @@ fn run_fwsec_frts(
     ) -> Result<()> {
         // Check that the WPR2 region does not already exists - if it does, we cannot run
         // FWSEC-FRTS until the GPU is reset.
-        if regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI::read(bar).higher_bound() != 0 {
+        if bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound() != 0 {
             dev_err!(
                 dev,
                 "WPR2 region already exists - GPU needs to be reset to proceed\n"
@@ -78,7 +79,9 @@ fn run_fwsec_frts(
         fwsec_frts.run(dev, falcon, bar)?;
 
         // SCRATCH_E contains the error code for FWSEC-FRTS.
-        let frts_status = regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR::read(bar).frts_err_code();
+        let frts_status = bar
+            .read(regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR)
+            .frts_err_code();
         if frts_status != 0 {
             dev_err!(
                 dev,
@@ -91,8 +94,8 @@ fn run_fwsec_frts(
 
         // Check that the WPR2 region has been created as we requested.
         let (wpr2_lo, wpr2_hi) = (
-            regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO::read(bar).lower_bound(),
-            regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI::read(bar).higher_bound(),
+            bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO).lower_bound(),
+            bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound(),
         );
 
         match (wpr2_lo, wpr2_hi) {
drivers/gpu/nova-core/gsp/cmdq.rs +6 -4
index 46819a82a51a..0b01515c39f6 100644
@@ -16,7 +16,11 @@
         DmaAddress, //
     },
     dma_write,
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        Io,
+        IoRef, //
+    },
     prelude::*,
     sync::aref::ARef,
     time::Delta,
@@ -475,9 +479,7 @@ fn calculate_checksum<T: Iterator<Item = u8>>(it: T) -> u32 {
 
     /// Notifies the GSP that we have updated the command queue pointers.
     fn notify_gsp(bar: &Bar0) {
-        regs::NV_PGSP_QUEUE_HEAD::default()
-            .set_address(0)
-            .write(bar);
+        bar.write(regs::NV_PGSP_QUEUE_HEAD.init(|r| r.with_address(0u32)));
     }
 
     /// Sends `command` to the GSP.
drivers/gpu/nova-core/regs.rs +305 -239

681 lines not on this page · raw message

drivers/gpu/nova-core/regs/macros.rs deleted +0 -739

739 lines not on this page · raw message

Signature · 1 line
2.53.0
maintainer
#3 lore raw

Re: [PATCH v6 2/9] rust: num: add `shr` and `shl` methods to `Bounded`

In reply to Alexandre Courbot
Quoted 31 lines · Alexandre Courbot

Shifting a Bounded left or right changes the number of bits required to represent the value. Add methods that perform the shift and return a Bounded with the appropriately adjusted bit width.

These methods are particularly useful for bitfield extraction.

---
 rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
rust/kernel/num/bounded.rs +6 -0
index fa81acbdc8c2..7014b5be66db 100644
@@ -473,6 +473,48 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `N` bits, and with the same signedness.
         unsafe { Bounded::__new(value) }
     }
+
+    /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >=
+    /// N - SHIFT`.
+    ///
+    /// # Examples
+    ///

rust/kernel/num/bounded.rs pub fn cast<U>(self) -> Bounded<U, N> · line 491

Quoted 10 lines
rust/kernel/num/bounded.rs +10 -0
+    /// ```
+    /// use kernel::num::Bounded;
+    ///
+    /// let v = Bounded::<u32, 16>::new::<0xff00>();
+    /// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>();
+    ///
+    /// assert_eq!(v_shifted.get(), 0xff);
+    /// ```
+    pub fn shr<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
+        const { assert!(RES >= N - SHIFT) }

Perhaps slightly better as:

	const { assert!(RES + SHIFT >= N) }

Alice

maintainer
#6 lore raw

Re: [PATCH v6 4/9] rust: num: make Bounded::get const

In reply to Alexandre Courbot
Quoted 14 lines · Alexandre Courbot

There is a need to access the inner value of a Bounded in const context, notably for bitfields and registers. Remove the invariant check of Bounded::get, which allows us to make it const.

---
 rust/kernel/num/bounded.rs | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
rust/kernel/num/bounded.rs +0 -0
index 8e4c08924d96..b09b93cd0c5c 100644

rust/kernel/num/bounded.rs pub fn from_expr(expr: T) -> Self { · line 383

Quoted 5 lines
rust/kernel/num/bounded.rs +2 -0
@@ -379,6 +379,9 @@ pub fn from_expr(expr: T) -> Self {
 
     /// Returns the wrapped value as the backing type.
     ///
+    /// This is similar to the [`Deref`] implementation, but doesn't enforce the size invariant of
+    /// the [`Bounded`], which might produce slightly less optimal code.

The unreachable_unchecked() hint is const, so I see no reason you couldn't add the same call in fn get.

Alice

maintainer
#9 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

In reply to Alexandre Courbot
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 10 lines
rust/kernel/io.rs +10 -0
+/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`]
+/// to work uniformly with both raw `usize` offsets (for primitive types like `u32`) and typed
+/// references.
+///
+/// An `IoRef<T>` carries three pieces of information:
+///
+/// - The offset to access (returned by [`IoRef::offset`]),
+/// - The width of the access (determined by [`IoRef::IoType`]),
+/// - The type `T` in which data is returned or provided.
+///

rust/kernel/io.rs pub trait IoCapable<T> { · line 197

Quoted 10 lines
rust/kernel/io.rs +10 -0
+/// `T` and `IoType` may differ: for instance, a typed register has `T` = the register type with
+/// its bitfields, and `IoType` = its backing primitive (e.g. `u32`), with `From`/`Into`
+/// conversions between them.
+///
+/// An `IoRef` can be passed directly to [`Io::read`] or [`Io::try_read`] to obtain a value, or
+/// turned into an [`IoWrite`] via [`IoRef::set`] to be passed to [`Io::write`] or
+/// [`Io::try_write`].
+pub trait IoRef<T>: Copy
+where
+    T: From<Self::IoType> + Into<Self::IoType>,

Prefer to use Into for trait bounds:

where

    T: Into<Self::IoType>,
    Self::IoType: Into<T>,

Alice

reviewer
#7 lore raw

Re: [PATCH v6 4/9] rust: num: make Bounded::get const

In reply to Alice Ryhl
Quoted 16 lines · Alice Ryhl
Quoted 15 lines · Alexandre Courbot

There is a need to access the inner value of a Bounded in const context, notably for bitfields and registers. Remove the invariant check of Bounded::get, which allows us to make it const.

---
 rust/kernel/num/bounded.rs | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
rust/kernel/num/bounded.rs +0 -0
index 8e4c08924d96..b09b93cd0c5c 100644
@@ -379,6 +379,9 @@ pub fn from_expr(expr: T) -> Self {
 
Quoted 9 lines
Quoted 6 lines
rust/kernel/num/bounded.rs +1 -0
     /// Returns the wrapped value as the backing type.
     ///
+    /// This is similar to the [`Deref`] implementation, but doesn't 

enforce the size invariant of
+ /// the [Bounded], which might produce slightly less optimal
code.

The unreachable_unchecked() hint is const, so I see no reason you couldn't add the same call in fn get.

The issue is that trait impls are not const, so the if condition cannot be represented in const yet.

Best,
Gary

author maintainer
#10 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

In reply to Alice Ryhl
Quoted 37 lines · Alice Ryhl
Quoted 36 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
Quoted 5 lines

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 1 line
rust/kernel/io.rs +1 -0
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

maintainer
#11 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

Quoted 38 lines · Alexandre Courbot
Quoted 37 lines · Alice Ryhl
Quoted 36 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
Quoted 8 lines
Quoted 5 lines

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 1 line
rust/kernel/io.rs +1 -0
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

Alice

author maintainer
#12 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

Quoted 45 lines · Alice Ryhl
Quoted 44 lines · Alexandre Courbot
Quoted 42 lines · Alice Ryhl
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 5 lines
Quoted 2 lines

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

"index" looks more accurate indeed for something that is not a pointer type.

author maintainer
#13 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

Quoted 46 lines · Alexandre Courbot
Quoted 45 lines · Alice Ryhl
Quoted 44 lines · Alexandre Courbot
Quoted 42 lines · Alice Ryhl
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

"index" looks more accurate indeed for something that is not a pointer type.

Actually this creates a bit of confusion in register.rs, where we have arrays of registers, which RegisterArrayRef was built using the index of a particular register within that array. If we rename IoRef to IoIndex and transitively RegisterArrayRef to RegisterArrayIndex, we now have an index that takes an index...

Besides IoRef is more than just an index - it is also an access width, and a type to convert that access from/to. Would IoSpec and specification be acceptable?

maintainer
#14 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

Quoted 62 lines · Alexandre Courbot
Quoted 46 lines · Alexandre Courbot
Quoted 45 lines · Alice Ryhl
Quoted 44 lines · Alexandre Courbot
Quoted 42 lines · Alice Ryhl
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

"index" looks more accurate indeed for something that is not a pointer type.

Actually this creates a bit of confusion in register.rs, where we have arrays of registers, which RegisterArrayRef was built using the index of a particular register within that array. If we rename IoRef to IoIndex and transitively RegisterArrayRef to RegisterArrayIndex, we now have an index that takes an index...

Quoted 3 lines

Besides IoRef is more than just an index - it is also an access width, and a type to convert that access from/to. Would IoSpec and specification be acceptable?

Not using "index" make sense to me, but I don't really understand how "spec" fits in either. How about "place" or "location"?

Alice

#21 lore raw
In reply to Alexandre Courbot

Hi Alexandre,

Quoted 23 lines · Alexandre Courbot

This new revision took some time because it is (yet another) overhaul. ^_^;

Thanks to a breakthrough by Gary, we found a way to have the I/O type perform the actual I/O instead of the register type, which moves us from this access pattern:

    let boot0 = regs::NV_PMC_BOOT_0::read(bar);

to this arguably more natural one:

    let boot0 = bar.read(regs::NV_PMC_BOOT_0);

It also has the benefit of taking advantage of deref coercion for types that wrap an Io, something the register-based methods couldn't do and which would have required extra AsRef implementations just for this purpose.

Furthermore, this resolves the inconsistency of the former register API that couldn't use the try_ I/O accessors (and even had methods whose names clashed with them). Now if Io supports it, it can be done on a register.

Quoted 8 lines

Another benefit is that there is less work done within macros, and more in generic code, which is (generally) a win for readability. The register! macro is considerably smaller and easier to work on, and now mostly made up of the bitfield accessors that will eventually be moved into another macro.

I decided to remove a couple of tags because the code has changed quite a bit since they were obtained.

Last time I gave this a try was with v2. From my aarch64 simple timer test on that version I have [1] below. Could you give a hint how to convert this to v6? :)

Many thanks!

Dirk

[1]

register!(TCR(u16) @ 0x10 {
        9:9    icpf;
        8:8    unf;
        7:6    icpe;
	5:5    unie;
	4:3    ckeg;
	2:0    tpsc;
});
impl TCR {
	fn handle_underflow<const SIZE: usize, T>(io: &T)
	where
	    T: Deref<Target = Io<SIZE>>,
	{
	    let tcr = Self::read(io);
	    if tcr.unf().into() {
	        tcr.set_unf(false).write(io);
	    }
	}
}

...

// Reset the underflow flag
TCR::handle_underflow(io);

author maintainer
#15 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

In reply to Alice Ryhl
Quoted 63 lines · Alice Ryhl
Quoted 62 lines · Alexandre Courbot
Quoted 46 lines · Alexandre Courbot
Quoted 45 lines · Alice Ryhl
Quoted 44 lines · Alexandre Courbot
Quoted 42 lines · Alice Ryhl
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

"index" looks more accurate indeed for something that is not a pointer type.

Actually this creates a bit of confusion in register.rs, where we have arrays of registers, which RegisterArrayRef was built using the index of a particular register within that array. If we rename IoRef to IoIndex and transitively RegisterArrayRef to RegisterArrayIndex, we now have an index that takes an index...

Quoted 6 lines
Quoted 3 lines

Besides IoRef is more than just an index - it is also an access width, and a type to convert that access from/to. Would IoSpec and specification be acceptable?

Not using "index" make sense to me, but I don't really understand how "spec" fits in either. How about "place" or "location"?

Well it's a specification of how to access an I/O area... kind of.

"Location" sounds good too, and abbreviates nicely to "Loc", let me see how that looks in practice.

maintainer
#16 lore raw

Re: [PATCH v6 5/9] rust: io: add IoRef and IoWrite types

Quoted 68 lines · Alexandre Courbot
Quoted 67 lines · Alice Ryhl
Quoted 65 lines · Alexandre Courbot
Quoted 46 lines · Alexandre Courbot
Quoted 45 lines · Alice Ryhl
Quoted 44 lines · Alexandre Courbot
Quoted 42 lines · Alice Ryhl
Quoted 33 lines · Alexandre Courbot

I/O accesses are defined by the following properties:

- For reads, a start address, a width, and a type to interpret the read value as,
- For writes, the same as above, and a value to write.

Introduce the IoRef trait, which allows implementing types to specify the address a type expects to be accessed at, as well as the width of the access, and the user-facing type used to perform the access.

This allows read operations to be made generic with the read method over an IoRef argument.

Write operations need a value to write on top of the IoRef: fulfill that purpose with the IoWrite, which is the combination of an IoRef and a value of the type it expects. This allows write operations to be made generic with the write method over a single IoWrite argument.

The main purpose of these new entities is to allow register types to be written using these generic read and write methods of Io.

---
 rust/kernel/io.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 243 insertions(+)
rust/kernel/io.rs +0 -0
index b150743ffa4f..6da8593f7858 100644

rust/kernel/io.rs pub trait IoCapable<T> { · line 176

Quoted 4 lines
rust/kernel/io.rs +1 -0
@@ -173,6 +173,160 @@ pub trait IoCapable<T> {
     unsafe fn io_write(&self, value: T, address: usize);
 }
 
+/// Reference to an I/O location, describing the offset, width, and return type of an access.

In the next patch you implement this for usize, but here you say it's a reference to an I/O location. I'm pretty sure usize is not a reference to an I/O location.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Methods like read_u8 use a usize to reference the location we want to read, so aren't they in that context?

Oh .. I wouldn't use the word "reference" like that. How about "index" instead?

"index" looks more accurate indeed for something that is not a pointer type.

Actually this creates a bit of confusion in register.rs, where we have arrays of registers, which RegisterArrayRef was built using the index of a particular register within that array. If we rename IoRef to IoIndex and transitively RegisterArrayRef to RegisterArrayIndex, we now have an index that takes an index...

Besides IoRef is more than just an index - it is also an access width, and a type to convert that access from/to. Would IoSpec and specification be acceptable?

Quoted 7 lines
Quoted 2 lines

Not using "index" make sense to me, but I don't really understand how "spec" fits in either. How about "place" or "location"?

Well it's a specification of how to access an I/O area... kind of.

"Location" sounds good too, and abbreviates nicely to "Loc", let me see how that looks in practice.

Ok, I like location too.

Alice

author maintainer
#22 lore raw
In reply to Dirk Behme

Hi Dirk,

Quoted 32 lines · Dirk Behme

Hi Alexandre,

Quoted 29 lines · Alexandre Courbot

This new revision took some time because it is (yet another) overhaul. ^_^;

Thanks to a breakthrough by Gary, we found a way to have the I/O type perform the actual I/O instead of the register type, which moves us from this access pattern:

    let boot0 = regs::NV_PMC_BOOT_0::read(bar);

to this arguably more natural one:

    let boot0 = bar.read(regs::NV_PMC_BOOT_0);

It also has the benefit of taking advantage of deref coercion for types that wrap an Io, something the register-based methods couldn't do and which would have required extra AsRef implementations just for this purpose.

Furthermore, this resolves the inconsistency of the former register API that couldn't use the try_ I/O accessors (and even had methods whose names clashed with them). Now if Io supports it, it can be done on a register.

Another benefit is that there is less work done within macros, and more in generic code, which is (generally) a win for readability. The register! macro is considerably smaller and easier to work on, and now mostly made up of the bitfield accessors that will eventually be moved into another macro.

Quoted 6 lines
Quoted 2 lines

I decided to remove a couple of tags because the code has changed quite a bit since they were obtained.

Last time I gave this a try was with v2. From my aarch64 simple timer test on that version I have [1] below. Could you give a hint how to convert this to v6? :)

Yeah I'm sorry, this is quite a heavy change. An LLM should do a good job at updating your code once you give it an example.

Quoted 7 lines

Many thanks!

Dirk

[1]

Quoted 8 lines
register!(TCR(u16) @ 0x10 {
        9:9    icpf;
        8:8    unf;
        7:6    icpe;
	5:5    unie;
	4:3    ckeg;
	2:0    tpsc;
});

This would become:

register! {
    TCR(u16) @ 0x10 {
        9:9    icpf;
        8:8    unf;
        7:6    icpe;
        5:5    unie;
        4:3    ckeg;
        2:0    tpsc;
    }
}

This part doesn't change much - it would however if the fields were documented.

Note also that you can now declare several registers in the same register! invocation.

Quoted 6 lines

impl TCR {
fn handle_underflow<const SIZE: usize, T>(io: &T) where
T: Deref<Target = Io<SIZE>>,

Io is a trait now, so this will need updating as well.

Quoted 2 lines
	{
	    let tcr = Self::read(io);
        // Note `TCR` exists as both the type and the contant. `read`
        // expects the latter, so you cannot use `Self` here.
        let tcr = io.read(TCR);
Quoted 3 lines
	    if tcr.unf().into() {
	        tcr.set_unf(false).write(io);
	    }
        if tcr.unf().into_bool() {
            // You will need to have `IoRef` (`IoLoc` in v7) in scope
            // for `set` to be visible.
            io.write(TCR.set(tcr.with_unf(false)));
        }

The direction of read and write is now more natural (and more flexible with respect to the way I/O now works).

I am also contemplating allowing the following syntax for the write:

            io.write(tcr.with_unf(false));

which is shorter, but will also only work for fixed registers. Guess I should ask for opinions as an RFC patch.

Hope this helps - let me know if anything is unclear or if you notice pain points!