Skip to contentSkip to conversation

rust: add `register!` macro

PATCH Superseded Alexandre Courbot 6 participants 25 messages Jan 21 – Jan 26

Subsystems (7)
DRM drivers Kbuild Rust DRM Rust +3 more subsystems

v2 of 9 Superseded Latest is v9 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v2 cover rust: add `register!` macro

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,
- Extended documentation,
- Doccomments now build and run,
- Supports visibility and different storage sizes.

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. Third patch adds another convenience method to obtain a bool from single-bit Boundeds.

Patch 4 adds the register! macro. Since it falls under rust/kernel/io it is covered by the corresponding MAINTAINERS entry so I refrained from adding one just for this file, especially since the bitfield-related parts will eventually move and what remains is very tightly related to I/O.

The last patch illustrates 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.

Previous work to extract the macros was done in the partially-merged [1]. The current series can be considered a reboot with more features and the bitfield! macro being postponed.

This patchset is based on driver-core-next.

Note that it also need rust-fixes to avoid an unused_unsafe warning.

[1] https://lore.kernel.org/all/[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 (5):
rust: enable the generic_arg_infer feature
rust: num: add shr and shl methods to Bounded
rust: num: add as_bool method to Bounded<_, 1>
rust: io: add register! macro
[FOR REFERENCE] gpu: nova-core: use the kernel register! macro

 drivers/gpu/nova-core/falcon.rs           |  127 ++-
 drivers/gpu/nova-core/falcon/gsp.rs       |   10 +-
 drivers/gpu/nova-core/falcon/hal/ga102.rs |    5 +-
 drivers/gpu/nova-core/falcon/sec2.rs      |   13 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |    9 +-
 drivers/gpu/nova-core/gpu.rs              |   24 +-
 drivers/gpu/nova-core/gsp/cmdq.rs         |    2 +-
 drivers/gpu/nova-core/regs.rs             |  265 +++----
 drivers/gpu/nova-core/regs/macros.rs      |  721 -----------------
 rust/kernel/io.rs                         |    1 +
 rust/kernel/io/register.rs                | 1198 +++++++++++++++++++++++++++++
 rust/kernel/lib.rs                        |    3 +
 rust/kernel/num/bounded.rs                |   61 ++
 scripts/Makefile.build                    |    3 +-
 14 files changed, 1485 insertions(+), 957 deletions(-)

---
base-commit: c259cd7ea3c9ad369c473ba2385d82e3432088b1
change-id: 20260117-register-ccaba1d21713

Best regards,

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

PATCH v2 1/5 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 6d637e2fed1b..122ad64880cd 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 5037f4715d74..8fd0e7096bd1 100644
@@ -312,12 +312,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,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg,generic_arg_infer
 
 # `--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.52.0
reviewer
#2 lore raw

Re: [PATCH v2 1/5] rust: enable the `generic_arg_infer` feature

Quoted 28 lines · Alexandre Courbot

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 6d637e2fed1b..122ad64880cd 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 +0 -0
index 5037f4715d74..8fd0e7096bd1 100644
@@ -312,12 +312,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE
 #   - Stable since Rust 1.82.0: `feature(asm_const)`,

scripts/Makefile.build $(obj)/%.lst: $(obj)/%.c FORCE · line 321

Quoted 10 lines
scripts/Makefile.build +2 -1
 #     `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,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg,generic_arg_infer

This is an alphabetically sorted list.

Best,
Gary

Quoted 3 lines
scripts/Makefile.build +0 -0
 # `--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
author maintainer
#3 lore raw

PATCH v2 2/5 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 | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)
rust/kernel/num/bounded.rs +40 -0
index f870080af8ac..8782535770f1 100644
@@ -470,6 +470,46 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `N` bits, and with the same signedness.
         Bounded::__new(value)
     }
+
+    /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, { 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<_, { 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.52.0
reviewer
#4 lore raw

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

Quoted 18 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 | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)
rust/kernel/num/bounded.rs +0 -0
index f870080af8ac..8782535770f1 100644

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

Quoted 2 lines
rust/kernel/num/bounded.rs +0 -0
@@ -470,6 +470,46 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `N` bits, and with the same signedness.
         Bounded::__new(value)

This patch doesn't apply cleanly. Looks like you send it from the wrong base commit.

The __new call here is still safe while your code has unsafe {} in it.

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

Quoted 3 lines
rust/kernel/num/bounded.rs +2 -0
     }
+
+    /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, { N - SHIFT }>`.

The returned bound can be larger given the assert below?

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

Quoted 13 lines
rust/kernel/num/bounded.rs +13 -0
+    ///
+    /// # 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) }

Quite surprised that rustfmt didn't ask for the block to be expanded into multiple lines.

I think we probably want to create a new assert macro for this pattern (obviously this doesn't block this patch).

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

Quoted 7 lines
rust/kernel/num/bounded.rs +7 -0
+
+        // 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<_, { N + SHIFT }>`.

Same, the bound can be actually larger.

Best,
Gary

Quoted 21 lines
rust/kernel/num/bounded.rs +18 -0
+    ///
+    /// # 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>
author maintainer
#5 lore raw

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

Quoted 25 lines · Gary Guo
Quoted 18 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 | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)
rust/kernel/num/bounded.rs +0 -0
index f870080af8ac..8782535770f1 100644

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

Quoted 2 lines
rust/kernel/num/bounded.rs +0 -0
@@ -470,6 +470,46 @@ pub fn cast<U>(self) -> Bounded<U, N>
         // `N` bits, and with the same signedness.
         Bounded::__new(value)

This patch doesn't apply cleanly. Looks like you send it from the wrong base commit.

Quoted 1 line

The __new call here is still safe while your code has unsafe {} in it.

The cover letter mentions that the base for this patchset is driver-core-next, since register! lands in kernel/rust/io and we need to rebase on top of Zhi's Io patchset, which will land there as well.

This indeed creates a minor conflict with rust-next as it includes a couple of patches for bounded.rs.

Quoted 6 lines

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

Quoted 4 lines
rust/kernel/num/bounded.rs +2 -0
     }
+
+    /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, { N - SHIFT }>`.

The returned bound can be larger given the assert below?

Indeed, I forgot to update this comment - thanks!

Quoted 21 lines
Quoted 4 lines
rust/kernel/num/bounded.rs +3 -0
+    ///
+    /// # Examples
+    ///

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

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) }

Quite surprised that rustfmt didn't ask for the block to be expanded into multiple lines.

I think we probably want to create a new assert macro for this pattern (obviously this doesn't block this patch).

Quoted 9 lines

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

Quoted 7 lines
rust/kernel/num/bounded.rs +7 -0
+
+        // 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<_, { N + SHIFT }>`.

Same, the bound can be actually larger.

Fixed, thanks.

#6 lore raw

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

Quoted 3 lines · Alexandre Courbot

This indeed creates a minor conflict with rust-next as it includes a couple of patches for bounded.rs.

rust-fixes, i.e. it will be in mainline soon, but yeah :)

Cheers,
Miguel

#7 lore raw

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

In reply to Alexandre Courbot
kernel test robot noticed the following build warnings:

Hi Alexandre,

kernel test robot noticed the following build warnings:

[auto build test WARNING on c259cd7ea3c9ad369c473ba2385d82e3432088b1]

url:    https://github.com/intel-lab-lkp/linux/commits/Alexandre-Courbot/rust-enable-the-generic_arg_infer-feature/20260121-152936
base:   c259cd7ea3c9ad369c473ba2385d82e3432088b1
patch link:    https://lore.kernel.org/r/20260121-register-v2-2-79d9b8d5e36a%40nvidia.com
patch subject: [PATCH v2 2/5] rust: num: add `shr` and `shl` methods to `Bounded`
config: x86_64-randconfig-071-20260121 (https://download.01.org/0day-ci/archive/20260122/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260122/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> warning: unnecessary `unsafe` block

--> rust/kernel/num/bounded.rs:491:9
|
491 | unsafe { Bounded::__new(self.0 >> SHIFT) }
| ^^^^^^ unnecessary unsafe block
|
= note: #[warn(unused_unsafe)] on by default
--

>> warning: unnecessary `unsafe` block

--> rust/kernel/num/bounded.rs:511:9
|
511 | unsafe { Bounded::__new(self.0 << SHIFT) }
| ^^^^^^ unnecessary unsafe block

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author maintainer
#8 lore raw

PATCH v2 3/5 rust: num: add `as_bool` method to `Bounded<_, 1>`

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 as_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 8782535770f1..8407606f2fa7 100644
@@ -1096,3 +1096,24 @@ fn from(value: bool) -> Self {
         Self::__new(T::from(value))
     }
 }
+
+impl<T> Bounded<T, 1>
+where
+    T: Integer + Zeroable,
+{
+    /// Returns the value of this `Bounded` as a `bool`.
+    ///
+    /// This is a shorter way of writing `bool::from(self)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::num::Bounded;
+    ///
+    /// assert_eq!(Bounded::<u8, 1>::new::<0>().as_bool(), false);
+    /// assert_eq!(Bounded::<u8, 1>::new::<1>().as_bool(), true);
+    /// ```
+    pub fn as_bool(self) -> bool {
+        self.into()
+    }
+}
Signature · 1 line
2.52.0
reviewer Reviewed-by on v2 3/5
#9 lore raw

Re: [PATCH v2 3/5] rust: num: add `as_bool` method to `Bounded<_, 1>`

Quoted 8 lines · 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 as_bool method as a simpler shortcut.

Quoted 3 lines
---
 rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
author maintainer
#10 lore raw

PATCH v2 4/5 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          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
rust/kernel/io.rs +1 -0
index a97eb44a9a87..eccaa176b6b9 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
rust/kernel/io/register.rs new file +1198 -0

1,198 lines not on this page · raw message

Signature · 1 line
2.52.0
author maintainer
#11 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 40 lines · 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          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
rust/kernel/io.rs +1 -0
index a97eb44a9a87..eccaa176b6b9 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
rust/kernel/io/register.rs new file +5 -0
new file mode 100644
index 000000000000..e414aebe4c86
@@ -0,0 +1,1198 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! A macro to define register layout and accessors.
+//!
+//! A single register typically includes several fields, which are accessed through a combination

rust/kernel/io/register.rs line 15

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because
+//! not all possible field values are necessarily valid.
+//!
+//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a
+//! dedicated type for each register. Each such type comes with its own field accessors that can
+//! return an error if a field's value is invalid. Please look at the [`bitfield!`] macro for the
+//! complete syntax of fields definitions.
+//!
+//! [`register!`]: kernel::register!
+//! [`bitfield!`]: crate::bitfield!

Oops, I should remove these references to bitfield!...

reviewer
#12 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

In reply to Alexandre Courbot
Quoted 5 lines · 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.

Quoted 7 lines

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.

It looks like this is still based on the current Io impl. I think with Zhi's new Io trait this will look quite different.

Best,
Gary

Quoted 4 lines
---
 rust/kernel/io.rs          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
author maintainer
#13 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 9 lines · Gary Guo
Quoted 8 lines · 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.

Quoted 7 lines
Quoted 4 lines

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

It looks like this is still based on the current Io impl. I think with Zhi's new Io trait this will look quite different.

Correct. The next version will be rebased on top of it now that it is merged into driver-core-next.

reviewer
#14 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

In reply to Alexandre Courbot
Quoted 43 lines · 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          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
rust/kernel/io.rs +1 -0
index a97eb44a9a87..eccaa176b6b9 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
rust/kernel/io/register.rs new file +8 -0
new file mode 100644
index 000000000000..e414aebe4c86
@@ -0,0 +1,1198 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/// Defines a dedicated type for a register with an absolute offset, including getter and setter
+/// methods for its fields and methods to read and write it from an `Io` region.
+///
+/// A register is essentially a [`bitfield!`] with I/O capabilities. The syntax of the `register!`
+/// macro reflects that fact, being essentially identical to that of [`bitfield!`] with the
+/// addition of addressing information after the `@` token.

rust/kernel/io/register.rs line 18

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///
+/// Example:
+///
+/// ```
+/// use kernel::register;
+///
+/// register!(pub BOOT_0(u32) @ 0x00000100, "Basic revision information about the chip" {
+///     7:4 major_revision, "Major revision of the chip";
+///     3:0 minor_revision, "Minor revision of the chip";
+/// });

The comment is inserted as doc comment, but it uses the string syntax.

I guess the idea is that you want write everything in a single line so you can visually align the fields? I think it
looks fine on the fields, but the same-line documentation of the type itself looks a bit off.

Something like this will definitely feel much more Rusty:

register!(

    /// Basic revision information about the chip.
    pub struct BOOT_0(u32) @ 0x00000100 {
        /// Major revision of the chip.
        major_version: [7:4],
        /// Minor revision of the chip.
        ///
        /// This would also allow you easily expand the documentation into
        /// multiple lines!
        ///
        /// Perhaps useful to document some quirks about the register!
        /// I know currently registers and their fields are very underdocumented
        /// and they probably don't need multiple lines, but I hope that'll not
        /// true in the future and we would have detailed docs in the driver --
        /// in which case visually aligning becomes impossible anyway.
        minor_version: [3:0],
        //           ^~ closer to the variable syntax in Rust
        //             ^~ I keep the hi:lo syntax which I suppose is to reflect Verilog.
    }

)

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

(Although, they use a completely different strategy in generating register mapping; all registers are becoming fields in the same struct).

Quoted 14 lines
rust/kernel/io/register.rs new file +14 -0
+/// ```
+///
+/// This defines a `BOOT_0` type which can be read or written from offset `0x100` of an `Io`
+/// region. For instance, `minor_revision` is made of the 4 least significant bits of the
+/// register. Each field can be accessed and modified using accessor
+/// methods:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::num::Bounded;
+///
+/// # register!(pub BOOT_0(u32) @ 0x00000100, "Basic revision information about the chip" {
+/// #     7:4 major_revision, "Major revision of the chip";
+/// #     3:0 minor_revision, "Minor revision of the chip";

rust/kernel/io/register.rs line 157

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+/// # });
+/// # fn test(bar: &kernel::io::Io) {
+/// // Read from the register's defined offset (0x100).
+/// let boot0 = BOOT_0::read(&bar);
+/// pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.minor_revision().get());
+///
+/// // Update some fields and write the value back.
+/// boot0
+///     .set_major_revision(Bounded::<u32, _>::new::<3>())
+///     .set_minor_revision(Bounded::<u32, _>::new::<10>())

This looks very verbose...

Quoted 27 lines
rust/kernel/io/register.rs new file +27 -0
+///     .write(&bar);
+///
+/// // Or, just read and update the register in a single step:
+/// BOOT_0::update(&bar, |r| r
+///     .set_major_revision(Bounded::<u32, _>::new::<3>())
+///     .set_minor_revision(Bounded::<u32, _>::new::<10>())
+/// );
+/// # }
+/// ```
+///
+/// The documentation strings are optional. If present, they will be added to the type's
+/// definition, or the field getter and setter methods they are attached to.
+///
+/// Attributes can be applied to the generated struct. The `#[allow(non_camel_case_types)]`
+/// attribute is automatically added since register names typically use SCREAMING_CASE:
+///
+/// ```
+/// use kernel::register;
+///
+/// register! {
+///     pub STATUS(u32) @ 0x00000000, "Status register" {
+///         0:0 ready, "Device ready flag";
+///     }
+/// }
+/// ```
+///
+/// It is also possible to create an alias register by using the `=> ALIAS` syntax. This is useful

rust/kernel/io/register.rs line 194

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+/// for cases where a register's interpretation depends on the context:
+///
+/// ```
+/// use kernel::register;
+///
+/// register!(pub SCRATCH(u32) @ 0x00000200, "Scratch register" {
+///     31:0 value, "Raw value";
+/// });
+///
+/// register!(pub SCRATCH_BOOT_STATUS(u32) => SCRATCH, "Boot status of the firmware" {

How about "as"?

register!(pub SCRATCH_BOOT_STATUS(u32) as SCRATCH);

Quoted 60 lines
rust/kernel/io/register.rs new file +60 -0
+///     0:0 completed, "Whether the firmware has completed booting";
+/// });
+/// ```
+///
+/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also
+/// providing its own `completed` field.
+///
+/// ## Relative registers
+///
+/// A register can be defined as being accessible from a fixed offset of a provided base. For
+/// instance, imagine the following I/O space:
+///
+/// ```text
+///           +-----------------------------+
+///           |             ...             |
+///           |                             |
+///  0x100--->+------------CPU0-------------+
+///           |                             |
+///  0x110--->+-----------------------------+
+///           |           CPU_CTL           |
+///           +-----------------------------+
+///           |             ...             |
+///           |                             |
+///           |                             |
+///  0x200--->+------------CPU1-------------+
+///           |                             |
+///  0x210--->+-----------------------------+
+///           |           CPU_CTL           |
+///           +-----------------------------+
+///           |             ...             |
+///           +-----------------------------+
+/// ```
+///
+/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O
+/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define
+/// them twice and would prefer a way to select which one to use from a single definition
+///
+/// This can be done using the `Base[Offset]` syntax when specifying the register's address.
+///
+/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the
+/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for
+/// this register needs to implement `RegisterBase<Base>`. Here is the above example translated
+/// into code:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::io::register::RegisterBase;
+///
+/// // Type used to identify the base.
+/// pub struct CpuCtlBase;
+///
+/// // ZST describing `CPU0`.
+/// struct Cpu0;
+/// impl RegisterBase<CpuCtlBase> for Cpu0 {
+///     const BASE: usize = 0x100;
+/// }
+/// // Singleton of `CPU0` used to identify it.
+/// const CPU0: Cpu0 = Cpu0;
+///
+/// // ZST describing `CPU1`.

rust/kernel/io/register.rs line 264

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+/// struct Cpu1;
+/// impl RegisterBase<CpuCtlBase> for Cpu1 {
+///     const BASE: usize = 0x200;
+/// }
+/// // Singleton of `CPU1` used to identify it.
+/// const CPU1: Cpu1 = Cpu1;
+///
+/// # fn test(bar: &kernel::io::Io) {
+/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`.
+/// register!(pub CPU_CTL(u32) @ CpuCtlBase[0x10], "CPU core control" {

Maybe CpuCtlBase + 0x10? I think this means the offset is going to be differ by 0x10, not that it's going to be the 17th register?

Quoted 29 lines
rust/kernel/io/register.rs new file +29 -0
+///     0:0 start, "Start the CPU core";
+/// });
+///
+/// // The `read`, `write` and `update` methods of relative registers take an extra `base` argument
+/// // that is used to resolve its final address by adding its `BASE` to the offset of the
+/// // register.
+///
+/// // Start `CPU0`.
+/// CPU_CTL::update(&bar, &CPU0, |r| r.set_start(true));
+///
+/// // Start `CPU1`.
+/// CPU_CTL::update(&bar, &CPU1, |r| r.set_start(true));
+///
+/// // Aliases can also be defined for relative register.
+/// register!(pub CPU_CTL_ALIAS(u32) => CpuCtlBase[CPU_CTL], "Alias to CPU core control" {
+///     1:1 alias_start, "Start the aliased CPU core";
+/// });
+///
+/// // Start the aliased `CPU0`.
+/// CPU_CTL_ALIAS::update(&bar, &CPU0, |r| r.set_alias_start(true));
+/// # }
+/// ```
+///
+/// ## Arrays of registers
+///
+/// Some I/O areas contain consecutive values that can be interpreted in the same way. These areas
+/// can be defined as an array of identical registers, allowing them to be accessed by index with
+/// compile-time or runtime bound checking. Simply define their address as `Address[Size]`, and add
+/// an `idx` parameter to their `read`, `write` and `update` methods:

rust/kernel/io/register.rs line 303

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///
+/// ```no_run
+/// use kernel::register;
+///
+/// # fn no_run(bar: &kernel::io::Io) -> Result<(), Error> {
+/// # fn get_scratch_idx() -> usize {
+/// #   0x15
+/// # }
+/// // Array of 64 consecutive registers with the same layout starting at offset `0x80`.
+/// register!(pub SCRATCH(u32) @ 0x00000080[64], "Scratch registers" {

This syntax is way to close to the base syntax above.

Perhaps pub SCRATCH([u32; 64]) @ 0x00000080 would make more sense?

Quoted 61 lines
rust/kernel/io/register.rs new file +61 -0
+///     31:0 value;
+/// });
+///
+/// // Read scratch register 0, i.e. I/O address `0x80`.
+/// let scratch_0 = SCRATCH::read(&bar, 0).value();
+/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`.
+/// let scratch_15 = SCRATCH::read(&bar, 15).value();
+///
+/// // This is out of bounds and won't build.
+/// // let scratch_128 = SCRATCH::read(&bar, 128).value();
+///
+/// // Runtime-obtained array index.
+/// let scratch_idx = get_scratch_idx();
+/// // Access on a runtime index returns an error if it is out-of-bounds.
+/// let some_scratch = SCRATCH::try_read(&bar, scratch_idx)?.value();
+///
+/// // Alias to a particular register in an array.
+/// // Here `SCRATCH[8]` is used to convey the firmware exit code.
+/// register!(pub FIRMWARE_STATUS(u32) => SCRATCH[8], "Firmware exit status code" {
+///     7:0 status;
+/// });
+///
+/// let status = FIRMWARE_STATUS::read(&bar).status();
+///
+/// // Non-contiguous register arrays can be defined by adding a stride parameter.
+/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the
+/// // registers of the two declarations below are interleaved.
+/// register!(pub SCRATCH_INTERLEAVED_0(u32) @ 0x000000c0[16 ; 8], "Scratch registers bank 0" {
+///     31:0 value;
+/// });
+/// register!(pub SCRATCH_INTERLEAVED_1(u32) @ 0x000000c4[16 ; 8], "Scratch registers bank 1" {
+///     31:0 value;
+/// });
+/// # Ok(())
+/// # }
+/// ```
+///
+/// ## Relative arrays of registers
+///
+/// Combining the two features described in the sections above, arrays of registers accessible from
+/// a base can also be defined:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::io::register::RegisterBase;
+///
+/// # fn no_run(bar: &kernel::io::Io) -> Result<(), Error> {
+/// # fn get_scratch_idx() -> usize {
+/// #   0x15
+/// # }
+/// // Type used as parameter of `RegisterBase` to specify the base.
+/// pub struct CpuCtlBase;
+///
+/// // ZST describing `CPU0`.
+/// struct Cpu0;
+/// impl RegisterBase<CpuCtlBase> for Cpu0 {
+///     const BASE: usize = 0x100;
+/// }
+/// // Singleton of `CPU0` used to identify it.
+/// const CPU0: Cpu0 = Cpu0;
+///

rust/kernel/io/register.rs line 374

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+/// // ZST describing `CPU1`.
+/// struct Cpu1;
+/// impl RegisterBase<CpuCtlBase> for Cpu1 {
+///     const BASE: usize = 0x200;
+/// }
+/// // Singleton of `CPU1` used to identify it.
+/// const CPU1: Cpu1 = Cpu1;
+///
+/// // 64 per-cpu scratch registers, arranged as a contiguous array.
+/// register!(pub CPU_SCRATCH(u32) @ CpuCtlBase[0x00000080[64]], "Per-CPU scratch registers" {

Ah... I don't like this.

Quoted 16 lines
rust/kernel/io/register.rs new file +16 -0
+///     31:0 value;
+/// });
+///
+/// let cpu0_scratch_0 = CPU_SCRATCH::read(&bar, &Cpu0, 0).value();
+/// let cpu1_scratch_15 = CPU_SCRATCH::read(&bar, &Cpu1, 15).value();
+///
+/// // This won't build.
+/// // let cpu0_scratch_128 = CPU_SCRATCH::read(&bar, &Cpu0, 128).value();
+///
+/// // Runtime-obtained array index.
+/// let scratch_idx = get_scratch_idx();
+/// // Access on a runtime value returns an error if it is out-of-bounds.
+/// let cpu0_some_scratch = CPU_SCRATCH::try_read(&bar, &Cpu0, scratch_idx)?.value();
+///
+/// // `SCRATCH[8]` is used to convey the firmware exit code.
+/// register!(pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase[CPU_SCRATCH[8]],

rust/kernel/io/register.rs line 400

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///     "Per-CPU firmware exit status code" {
+///     7:0 status;
+/// });
+///
+/// let cpu0_status = CPU_FIRMWARE_STATUS::read(&bar, &Cpu0).status();
+///
+/// // Non-contiguous register arrays can be defined by adding a stride parameter.
+/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the
+/// // registers of the two declarations below are interleaved.
+/// register!(pub CPU_SCRATCH_INTERLEAVED_0(u32) @ CpuCtlBase[0x00000d00[16 ; 8]],

For striding, SystemRDL uses syntax like this:

    type name[len] @ addr += stride;

which I think is better as this won't be confused with array length syntax in Rust.

Crazy idea: is it possible to just use SystemRDL (maybe via a proc macro).

Best,
Gary

Quoted 11 lines
rust/kernel/io/register.rs new file +11 -0
+///     "Scratch registers bank 0" {
+///     31:0 value;
+/// });
+/// register!(pub CPU_SCRATCH_INTERLEAVED_1(u32) @ CpuCtlBase[0x00000d04[16 ; 8]],
+///     "Scratch registers bank 1" {
+///     31:0 value;
+/// });
+/// # Ok(())
+/// # }
+/// ```
+/// [`bitfield!`]: crate::bitfield!
#15 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 4 lines · Gary Guo

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

Yeah, I suggested a multi-register one for something similar in 2021 and even tackling extra automatic codegen there, like e.g. adjusting the value as needed to get to the proper unit from a sensor.

Not sure how useful the multi-register part in practice it would be, but it would allow to relate several registers together if needed (is that even common nowadays?). Or perhaps things like the interleaving/striding example in the patch could be done "at once".

https://lore.kernel.org/all/CANiq72mAYE6Wh8AikfuuNm8Asr4+c90_bYbj8XdBGJ1Pb4kzvQ@mail.gmail.com/

Cheers,
Miguel

#16 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 6 lines · Miguel Ojeda
Quoted 4 lines · Gary Guo

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

Quoted 7 lines

Yeah, I suggested a multi-register one for something similar in 2021 and even tackling extra automatic codegen there, like e.g. adjusting the value as needed to get to the proper unit from a sensor.

Not sure how useful the multi-register part in practice it would be, but it would allow to relate several registers together if needed (is that even common nowadays?). Or perhaps things like the

For the NVIDIA GPU drivers, maybe not. Just a data point.

thanks,

Signature · 1 line
John Hubbard
#17 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 11 lines · John Hubbard
Quoted 10 lines · Miguel Ojeda
Quoted 4 lines · Gary Guo

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

Yeah, I suggested a multi-register one for something similar in 2021 and even tackling extra automatic codegen there, like e.g. adjusting the value as needed to get to the proper unit from a sensor.

Quoted 5 lines
Quoted 3 lines

Not sure how useful the multi-register part in practice it would be, but it would allow to relate several registers together if needed (is that even common nowadays?). Or perhaps things like the

For the NVIDIA GPU drivers, maybe not. Just a data point.

...although it depends on what you mean. We do have lots of registers with a common base MMIO address. It's just that they are not all invoked in one shot, is what I'm trying (struggling) to say.

thanks,

Signature · 1 line
John Hubbard
author maintainer
#18 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

In reply to Gary Guo
Quoted 83 lines · Gary Guo
Quoted 43 lines · 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          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
rust/kernel/io.rs +1 -0
index a97eb44a9a87..eccaa176b6b9 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
rust/kernel/io/register.rs new file +8 -0
new file mode 100644
index 000000000000..e414aebe4c86
@@ -0,0 +1,1198 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/// Defines a dedicated type for a register with an absolute offset, including getter and setter
+/// methods for its fields and methods to read and write it from an `Io` region.
+///
+/// A register is essentially a [`bitfield!`] with I/O capabilities. The syntax of the `register!`
+/// macro reflects that fact, being essentially identical to that of [`bitfield!`] with the
+/// addition of addressing information after the `@` token.

rust/kernel/io/register.rs line 18

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///
+/// Example:
+///
+/// ```
+/// use kernel::register;
+///
+/// register!(pub BOOT_0(u32) @ 0x00000100, "Basic revision information about the chip" {
+///     7:4 major_revision, "Major revision of the chip";
+///     3:0 minor_revision, "Minor revision of the chip";
+/// });

The comment is inserted as doc comment, but it uses the string syntax.

I guess the idea is that you want write everything in a single line so you can visually align the fields? I think it
looks fine on the fields, but the same-line documentation of the type itself looks a bit off.

Something like this will definitely feel much more Rusty:

register!(

    /// Basic revision information about the chip.
    pub struct BOOT_0(u32) @ 0x00000100 {
        /// Major revision of the chip.
        major_version: [7:4],
        /// Minor revision of the chip.
        ///
        /// This would also allow you easily expand the documentation into
        /// multiple lines!
        ///
        /// Perhaps useful to document some quirks about the register!
        /// I know currently registers and their fields are very underdocumented
        /// and they probably don't need multiple lines, but I hope that'll not
        /// true in the future and we would have detailed docs in the driver --
        /// in which case visually aligning becomes impossible anyway.
        minor_version: [3:0],
        //           ^~ closer to the variable syntax in Rust
        //             ^~ I keep the hi:lo syntax which I suppose is to reflect Verilog.
    }
Quoted 1 line

)

That would definitely be better, unfortunately since this is a declarative macro it cannot match against comments, hence the current syntax.

Quoted 4 lines

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

I agree that would be nice, especially as it opens the way for better syntax for e.g. register blocks with a base.

I am having trouble adding that to the current design though. Some rules use the tt muncher pattern and these will greedily consume all tokens, including those for the next register. I am a bit at my wit's end here, but if you have an idea for how to do it nicely then by all means. :)

Quoted 22 lines

(Although, they use a completely different strategy in generating register mapping; all registers are becoming fields in the same struct).

Quoted 18 lines
rust/kernel/io/register.rs new file +18 -0
+/// ```
+///
+/// This defines a `BOOT_0` type which can be read or written from offset `0x100` of an `Io`
+/// region. For instance, `minor_revision` is made of the 4 least significant bits of the
+/// register. Each field can be accessed and modified using accessor
+/// methods:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::num::Bounded;
+///
+/// # register!(pub BOOT_0(u32) @ 0x00000100, "Basic revision information about the chip" {
+/// #     7:4 major_revision, "Major revision of the chip";
+/// #     3:0 minor_revision, "Minor revision of the chip";
+/// # });
+/// # fn test(bar: &kernel::io::Io) {
+/// // Read from the register's defined offset (0x100).
+/// let boot0 = BOOT_0::read(&bar);
Quoted 8 lines

rust/kernel/io/register.rs line 157

Quoted 6 lines
rust/kernel/io/register.rs new file +6 -0
+/// pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.minor_revision().get());
+///
+/// // Update some fields and write the value back.
+/// boot0
+///     .set_major_revision(Bounded::<u32, _>::new::<3>())
+///     .set_minor_revision(Bounded::<u32, _>::new::<10>())

This looks very verbose...

Yes, it is a bit unfortunate (although real-life code is unlikely to be that verbose if you look at the top patch).

And a bit frustrating as one could expect the first generic parameter to be inferred, so we could write Bounded::new<3>(). But due to how the new constructor of Bounded is declared (using one dedicated impl block per dedicated type as we cannot use generics with const code), the compiler requires the backing type to be explicitly specified. :/

Once we have the ability to use const trait methods this can be improved though.

Quoted 41 lines
Quoted 28 lines
rust/kernel/io/register.rs new file +27 -0
+///     .write(&bar);
+///
+/// // Or, just read and update the register in a single step:
+/// BOOT_0::update(&bar, |r| r
+///     .set_major_revision(Bounded::<u32, _>::new::<3>())
+///     .set_minor_revision(Bounded::<u32, _>::new::<10>())
+/// );
+/// # }
+/// ```
+///
+/// The documentation strings are optional. If present, they will be added to the type's
+/// definition, or the field getter and setter methods they are attached to.
+///
+/// Attributes can be applied to the generated struct. The `#[allow(non_camel_case_types)]`
+/// attribute is automatically added since register names typically use SCREAMING_CASE:
+///
+/// ```
+/// use kernel::register;
+///
+/// register! {
+///     pub STATUS(u32) @ 0x00000000, "Status register" {
+///         0:0 ready, "Device ready flag";
+///     }
+/// }
+/// ```
+///
+/// It is also possible to create an alias register by using the `=> ALIAS` syntax. This is useful

rust/kernel/io/register.rs line 194

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+/// for cases where a register's interpretation depends on the context:
+///
+/// ```
+/// use kernel::register;
+///
+/// register!(pub SCRATCH(u32) @ 0x00000200, "Scratch register" {
+///     31:0 value, "Raw value";
+/// });
+///
+/// register!(pub SCRATCH_BOOT_STATUS(u32) => SCRATCH, "Boot status of the firmware" {

How about "as"?

Quoted 1 line

register!(pub SCRATCH_BOOT_STATUS(u32) as SCRATCH);

I'd rather not, this could be interpreted as the conversion being done using the as keyword while we are using Into.

Quoted 66 lines
Quoted 66 lines
rust/kernel/io/register.rs new file +65 -0
+///     0:0 completed, "Whether the firmware has completed booting";
+/// });
+/// ```
+///
+/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also
+/// providing its own `completed` field.
+///
+/// ## Relative registers
+///
+/// A register can be defined as being accessible from a fixed offset of a provided base. For
+/// instance, imagine the following I/O space:
+///
+/// ```text
+///           +-----------------------------+
+///           |             ...             |
+///           |                             |
+///  0x100--->+------------CPU0-------------+
+///           |                             |
+///  0x110--->+-----------------------------+
+///           |           CPU_CTL           |
+///           +-----------------------------+
+///           |             ...             |
+///           |                             |
+///           |                             |
+///  0x200--->+------------CPU1-------------+
+///           |                             |
+///  0x210--->+-----------------------------+
+///           |           CPU_CTL           |
+///           +-----------------------------+
+///           |             ...             |
+///           +-----------------------------+
+/// ```
+///
+/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O
+/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define
+/// them twice and would prefer a way to select which one to use from a single definition
+///
+/// This can be done using the `Base[Offset]` syntax when specifying the register's address.
+///
+/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the
+/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for
+/// this register needs to implement `RegisterBase<Base>`. Here is the above example translated
+/// into code:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::io::register::RegisterBase;
+///
+/// // Type used to identify the base.
+/// pub struct CpuCtlBase;
+///
+/// // ZST describing `CPU0`.
+/// struct Cpu0;
+/// impl RegisterBase<CpuCtlBase> for Cpu0 {
+///     const BASE: usize = 0x100;
+/// }
+/// // Singleton of `CPU0` used to identify it.
+/// const CPU0: Cpu0 = Cpu0;
+///
+/// // ZST describing `CPU1`.
+/// struct Cpu1;
+/// impl RegisterBase<CpuCtlBase> for Cpu1 {
+///     const BASE: usize = 0x200;
+/// }
+/// // Singleton of `CPU1` used to identify it.
Quoted 8 lines

rust/kernel/io/register.rs line 264

Quoted 5 lines
rust/kernel/io/register.rs new file +5 -0
+/// const CPU1: Cpu1 = Cpu1;
+///
+/// # fn test(bar: &kernel::io::Io) {
+/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`.
+/// register!(pub CPU_CTL(u32) @ CpuCtlBase[0x10], "CPU core control" {

Maybe CpuCtlBase + 0x10? I think this means the offset is going to be differ by 0x10, not that it's going to be the 17th register?

Yup, I tend to agree with you on the readability side. This requires changing some captures from ty to ident as + is not allowed after ty though, which will forbid namespaces from being specified in the type's path. Do you think this is an acceptable compromise?

Quoted 43 lines
Quoted 30 lines
rust/kernel/io/register.rs new file +29 -0
+///     0:0 start, "Start the CPU core";
+/// });
+///
+/// // The `read`, `write` and `update` methods of relative registers take an extra `base` argument
+/// // that is used to resolve its final address by adding its `BASE` to the offset of the
+/// // register.
+///
+/// // Start `CPU0`.
+/// CPU_CTL::update(&bar, &CPU0, |r| r.set_start(true));
+///
+/// // Start `CPU1`.
+/// CPU_CTL::update(&bar, &CPU1, |r| r.set_start(true));
+///
+/// // Aliases can also be defined for relative register.
+/// register!(pub CPU_CTL_ALIAS(u32) => CpuCtlBase[CPU_CTL], "Alias to CPU core control" {
+///     1:1 alias_start, "Start the aliased CPU core";
+/// });
+///
+/// // Start the aliased `CPU0`.
+/// CPU_CTL_ALIAS::update(&bar, &CPU0, |r| r.set_alias_start(true));
+/// # }
+/// ```
+///
+/// ## Arrays of registers
+///
+/// Some I/O areas contain consecutive values that can be interpreted in the same way. These areas
+/// can be defined as an array of identical registers, allowing them to be accessed by index with
+/// compile-time or runtime bound checking. Simply define their address as `Address[Size]`, and add
+/// an `idx` parameter to their `read`, `write` and `update` methods:

rust/kernel/io/register.rs line 303

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///
+/// ```no_run
+/// use kernel::register;
+///
+/// # fn no_run(bar: &kernel::io::Io) -> Result<(), Error> {
+/// # fn get_scratch_idx() -> usize {
+/// #   0x15
+/// # }
+/// // Array of 64 consecutive registers with the same layout starting at offset `0x80`.
+/// register!(pub SCRATCH(u32) @ 0x00000080[64], "Scratch registers" {

This syntax is way to close to the base syntax above.

Quoted 1 line

Perhaps pub SCRATCH([u32; 64]) @ 0x00000080 would make more sense?

So we also need to specify the optional stride of the array, which adds one more parameter. We can go with the following though:

pub SCRATCH(u32)[64] @ 0x00000080

or with the stride:

pub SCRATCH(u32)[64; 16] @ 0x00000080

How does it look?

Quoted 66 lines
Quoted 66 lines
rust/kernel/io/register.rs new file +65 -0
+///     31:0 value;
+/// });
+///
+/// // Read scratch register 0, i.e. I/O address `0x80`.
+/// let scratch_0 = SCRATCH::read(&bar, 0).value();
+/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`.
+/// let scratch_15 = SCRATCH::read(&bar, 15).value();
+///
+/// // This is out of bounds and won't build.
+/// // let scratch_128 = SCRATCH::read(&bar, 128).value();
+///
+/// // Runtime-obtained array index.
+/// let scratch_idx = get_scratch_idx();
+/// // Access on a runtime index returns an error if it is out-of-bounds.
+/// let some_scratch = SCRATCH::try_read(&bar, scratch_idx)?.value();
+///
+/// // Alias to a particular register in an array.
+/// // Here `SCRATCH[8]` is used to convey the firmware exit code.
+/// register!(pub FIRMWARE_STATUS(u32) => SCRATCH[8], "Firmware exit status code" {
+///     7:0 status;
+/// });
+///
+/// let status = FIRMWARE_STATUS::read(&bar).status();
+///
+/// // Non-contiguous register arrays can be defined by adding a stride parameter.
+/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the
+/// // registers of the two declarations below are interleaved.
+/// register!(pub SCRATCH_INTERLEAVED_0(u32) @ 0x000000c0[16 ; 8], "Scratch registers bank 0" {
+///     31:0 value;
+/// });
+/// register!(pub SCRATCH_INTERLEAVED_1(u32) @ 0x000000c4[16 ; 8], "Scratch registers bank 1" {
+///     31:0 value;
+/// });
+/// # Ok(())
+/// # }
+/// ```
+///
+/// ## Relative arrays of registers
+///
+/// Combining the two features described in the sections above, arrays of registers accessible from
+/// a base can also be defined:
+///
+/// ```no_run
+/// use kernel::register;
+/// use kernel::io::register::RegisterBase;
+///
+/// # fn no_run(bar: &kernel::io::Io) -> Result<(), Error> {
+/// # fn get_scratch_idx() -> usize {
+/// #   0x15
+/// # }
+/// // Type used as parameter of `RegisterBase` to specify the base.
+/// pub struct CpuCtlBase;
+///
+/// // ZST describing `CPU0`.
+/// struct Cpu0;
+/// impl RegisterBase<CpuCtlBase> for Cpu0 {
+///     const BASE: usize = 0x100;
+/// }
+/// // Singleton of `CPU0` used to identify it.
+/// const CPU0: Cpu0 = Cpu0;
+///
+/// // ZST describing `CPU1`.
+/// struct Cpu1;
+/// impl RegisterBase<CpuCtlBase> for Cpu1 {
+///     const BASE: usize = 0x200;
Quoted 8 lines

rust/kernel/io/register.rs line 374

Quoted 6 lines
rust/kernel/io/register.rs new file +6 -0
+/// }
+/// // Singleton of `CPU1` used to identify it.
+/// const CPU1: Cpu1 = Cpu1;
+///
+/// // 64 per-cpu scratch registers, arranged as a contiguous array.
+/// register!(pub CPU_SCRATCH(u32) @ CpuCtlBase[0x00000080[64]], "Per-CPU scratch registers" {

Ah... I don't like this.

If we adopt your syntax suggestions this should thankfully look much better.

Quoted 30 lines
Quoted 17 lines
rust/kernel/io/register.rs new file +16 -0
+///     31:0 value;
+/// });
+///
+/// let cpu0_scratch_0 = CPU_SCRATCH::read(&bar, &Cpu0, 0).value();
+/// let cpu1_scratch_15 = CPU_SCRATCH::read(&bar, &Cpu1, 15).value();
+///
+/// // This won't build.
+/// // let cpu0_scratch_128 = CPU_SCRATCH::read(&bar, &Cpu0, 128).value();
+///
+/// // Runtime-obtained array index.
+/// let scratch_idx = get_scratch_idx();
+/// // Access on a runtime value returns an error if it is out-of-bounds.
+/// let cpu0_some_scratch = CPU_SCRATCH::try_read(&bar, &Cpu0, scratch_idx)?.value();
+///
+/// // `SCRATCH[8]` is used to convey the firmware exit code.
+/// register!(pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase[CPU_SCRATCH[8]],

rust/kernel/io/register.rs line 400

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///     "Per-CPU firmware exit status code" {
+///     7:0 status;
+/// });
+///
+/// let cpu0_status = CPU_FIRMWARE_STATUS::read(&bar, &Cpu0).status();
+///
+/// // Non-contiguous register arrays can be defined by adding a stride parameter.
+/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the
+/// // registers of the two declarations below are interleaved.
+/// register!(pub CPU_SCRATCH_INTERLEAVED_0(u32) @ CpuCtlBase[0x00000d00[16 ; 8]],

For striding, SystemRDL uses syntax like this:

Quoted 6 lines
    type name[len] @ addr += stride;

which I think is better as this won't be confused with array length syntax in Rust.

Crazy idea: is it possible to just use SystemRDL (maybe via a proc macro).

I wasn't familiar with SystemRDL, your comment made me take a look. Interestingly some of the syntax is already close to that of this macro (notably the use of @). That makes me think that we should try to align when possible/relevant.

There are also lots of ideas that we could probably integrate (like register blocks and address maps), but parsing the syntax as-is seems overkill to me, and would delay this work quite a bit as we would probably reach the limits of what we can do with declarative macros.

author maintainer
#19 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 11 lines · Alexandre Courbot
Quoted 3 lines

Another top-level question I have is whether we should define multiple registers (perhaps all) in one macro invocation. That's the strategy of tock-registers crate which is widely used in embedded Rust.

I agree that would be nice, especially as it opens the way for better syntax for e.g. register blocks with a base.

I am having trouble adding that to the current design though. Some rules use the tt muncher pattern and these will greedily consume all tokens, including those for the next register. I am a bit at my wit's end here, but if you have an idea for how to do it nicely then by all means. :)

Actually I found a way to do it. V3 will support multiple register definitions per invocation, thanks for the suggestion!

author maintainer
#20 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

In reply to Alexandre Courbot
Quoted 86 lines · Alexandre Courbot
Quoted 83 lines · Gary Guo
Quoted 43 lines · 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          |    1 +
 rust/kernel/io/register.rs | 1198 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1199 insertions(+)
rust/kernel/io.rs +1 -0
index a97eb44a9a87..eccaa176b6b9 100644
@@ -11,6 +11,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
rust/kernel/io/register.rs new file +8 -0
new file mode 100644
index 000000000000..e414aebe4c86
@@ -0,0 +1,1198 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/// Defines a dedicated type for a register with an absolute offset, including getter and setter
+/// methods for its fields and methods to read and write it from an `Io` region.
+///
+/// A register is essentially a [`bitfield!`] with I/O capabilities. The syntax of the `register!`
+/// macro reflects that fact, being essentially identical to that of [`bitfield!`] with the
+/// addition of addressing information after the `@` token.

rust/kernel/io/register.rs line 18

Quoted 10 lines
rust/kernel/io/register.rs new file +10 -0
+///
+/// Example:
+///
+/// ```
+/// use kernel::register;
+///
+/// register!(pub BOOT_0(u32) @ 0x00000100, "Basic revision information about the chip" {
+///     7:4 major_revision, "Major revision of the chip";
+///     3:0 minor_revision, "Minor revision of the chip";
+/// });

The comment is inserted as doc comment, but it uses the string syntax.

I guess the idea is that you want write everything in a single line so you can visually align the fields? I think it
looks fine on the fields, but the same-line documentation of the type itself looks a bit off.

Something like this will definitely feel much more Rusty:

register!(

    /// Basic revision information about the chip.
    pub struct BOOT_0(u32) @ 0x00000100 {
        /// Major revision of the chip.
        major_version: [7:4],
        /// Minor revision of the chip.
        ///
        /// This would also allow you easily expand the documentation into
        /// multiple lines!
        ///
        /// Perhaps useful to document some quirks about the register!
        /// I know currently registers and their fields are very underdocumented
        /// and they probably don't need multiple lines, but I hope that'll not
        /// true in the future and we would have detailed docs in the driver --
        /// in which case visually aligning becomes impossible anyway.
        minor_version: [3:0],
        //           ^~ closer to the variable syntax in Rust
        //             ^~ I keep the hi:lo syntax which I suppose is to reflect Verilog.
    }
Quoted 1 line

)

Quoted 3 lines

That would definitely be better, unfortunately since this is a declarative macro it cannot match against comments, hence the current syntax.

Looks like I might be wrong here as well. Doccomments can apparently be matched as meta items, which would allow them to be re-emitted inside the rule. If that works (LSP unfortunately doesn't let me check that at the moment), then we should be able to do as you suggested, which would be great.

I also only noticed now the proposed reordering:

    minor_version: [3:0],

I don't have a strong opinion on that, but fwiw SystemRDL seems to do something like

    field minor_version[3:0];

If we agree to align on it the latter might be preferable?

author maintainer
#21 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

Quoted 10 lines · Alexandre Courbot

I also only noticed now the proposed reordering:

    minor_version: [3:0],

I don't have a strong opinion on that, but fwiw SystemRDL seems to do something like

    field minor_version[3:0];

If we agree to align on it the latter might be preferable?

I have tried implementing the alternative syntaxes, and I think this is a case where the original one was more readable. The bit fields are better aligned and easier to skim when they are put before the field name.

I'll keep it for v3, but of course remain open to alternatives.

#22 lore raw

Re: [PATCH v2 4/5] rust: io: add `register!` macro

In reply to Alexandre Courbot
kernel test robot noticed the following build warnings:

Hi Alexandre,

kernel test robot noticed the following build warnings:

[auto build test WARNING on c259cd7ea3c9ad369c473ba2385d82e3432088b1]

url:    https://github.com/intel-lab-lkp/linux/commits/Alexandre-Courbot/rust-enable-the-generic_arg_infer-feature/20260121-152936
base:   c259cd7ea3c9ad369c473ba2385d82e3432088b1
patch link:    https://lore.kernel.org/r/20260121-register-v2-4-79d9b8d5e36a%40nvidia.com
patch subject: [PATCH v2 4/5] rust: io: add `register!` macro
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260121/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260121/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> warning: unresolved link to `crate::bitfield`

--> rust/kernel/io/register.rs:15:20
|
15 | //! [bitfield!]: crate::bitfield!
| ^^^^^^^^^^^^^^^^ no item named bitfield in module kernel
|
= note: #[warn(rustdoc::broken_intra_doc_links)] on by default
--

>> warning: unresolved link to `crate::bitfield`

--> rust/kernel/io/register.rs:411:20
|
411 | /// [bitfield!]: crate::bitfield!
| ^^^^^^^^^^^^^^^^ no item named bitfield in module kernel

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author maintainer
#23 lore raw

PATCH v2 5/5 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           | 127 +++---
 drivers/gpu/nova-core/falcon/gsp.rs       |  10 +-
 drivers/gpu/nova-core/falcon/hal/ga102.rs |   5 +-
 drivers/gpu/nova-core/falcon/sec2.rs      |  13 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |   9 +-
 drivers/gpu/nova-core/gpu.rs              |  24 +-
 drivers/gpu/nova-core/gsp/cmdq.rs         |   2 +-
 drivers/gpu/nova-core/regs.rs             | 265 +++++------
 drivers/gpu/nova-core/regs/macros.rs      | 721 ------------------------------
 9 files changed, 220 insertions(+), 956 deletions(-)
drivers/gpu/nova-core/falcon.rs +53 -74
index 82c661aef594..2d0c4cbd9e67 100644
@@ -9,12 +9,16 @@
 use kernel::{
     device,
     dma::DmaAddress,
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        register::RegisterBase, //
+    },
+    num::Bounded,
     prelude::*,
     sync::aref::ARef,
     time::{
-        delay::fsleep,
-        Delta, //
+        delay::fsleep, //
+        Delta,
     },
 };
 
@@ -27,7 +31,6 @@
         IntoSafeCast, //
     },
     regs,
-    regs::macros::RegisterBase, //
 };
 
 pub(crate) mod gsp;
@@ -35,11 +38,12 @@
 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 {
+// TODO: macro that defines the struct and impls, like for Chipset.
+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)
             }
         }
     };
@@ -47,7 +51,6 @@ 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)]
 pub(crate) enum FalconCoreRev {
     #[default]
@@ -59,16 +62,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,
@@ -85,7 +88,6 @@ 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)]
 pub(crate) enum FalconCoreRevSubversion {
     #[default]
@@ -94,30 +96,27 @@ pub(crate) enum FalconCoreRevSubversion {
     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.
 ///
@@ -138,16 +137,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,
@@ -160,24 +159,23 @@ 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)]
 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),
         }
@@ -185,21 +183,20 @@ 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)]
 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),
         }
@@ -215,25 +212,17 @@ pub(crate) enum PeregrineCoreSelect {
     /// 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 {
@@ -257,14 +246,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,
@@ -284,26 +273,18 @@ pub(crate) enum FalconFbifMemType {
     /// 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(());
 
@@ -432,7 +413,7 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result {
         self.reset_wait_mem_scrubbing(bar)?;
 
         regs::NV_PFALCON_FALCON_RM::default()
-            .set_value(regs::NV_PMC_BOOT_0::read(bar).into())
+            .set_value(regs::NV_PMC_BOOT_0::read(bar).as_raw())
             .write(bar, &E::ID);
 
         Ok(())
@@ -501,20 +482,18 @@ fn dma_wr<F: FalconFirmware<Target = E>>(
             .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)
+            .try_set_base(dma_start >> 40)?
             .write(bar, &E::ID);
 
         let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD::default()
             .set_size(DmaTrfCmdSize::Size256B)
             .set_imem(target_mem == FalconMem::Imem)
-            .set_sec(if sec { 1 } else { 0 });
+            .set_sec(sec);
 
         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)
+                .try_set_offs(load_offsets.dst_start + pos)?
                 .write(bar, &E::ID);
             regs::NV_PFALCON_FALCON_DMATRFFBOFFS::default()
                 .set_offs(src_start + pos)
drivers/gpu/nova-core/falcon/gsp.rs +5 -5
index 67edef3636c1..dcdf3962ab0d 100644
@@ -1,7 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use kernel::{
-    io::poll::read_poll_timeout,
+    io::{
+        poll::read_poll_timeout,
+        register::RegisterBase, //
+    },
     prelude::*,
     time::Delta, //
 };
@@ -14,10 +17,7 @@
         PFalcon2Base,
         PFalconBase, //
     },
-    regs::{
-        self,
-        macros::RegisterBase, //
-    },
+    regs,
 };
 
 /// Type specifying the `Gsp` falcon engine. Cannot be instantiated.
drivers/gpu/nova-core/falcon/hal/ga102.rs +3 -2
index 69a7a95cac16..72afbd9101cf 100644
@@ -59,7 +59,7 @@ fn signature_reg_fuse_version_ga102(
 
     // `ucode_idx` is guaranteed to be in the range [0..15], making the `read` calls provable valid
     // at build-time.
-    let reg_fuse_version = if engine_id_mask & 0x0001 != 0 {
+    let reg_fuse_version: u16 = if engine_id_mask & 0x0001 != 0 {
         regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION::read(bar, ucode_idx).data()
     } else if engine_id_mask & 0x0004 != 0 {
         regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION::read(bar, ucode_idx).data()
@@ -68,7 +68,8 @@ fn signature_reg_fuse_version_ga102(
     } else {
         dev_err!(dev, "unexpected engine_id_mask {:#x}", engine_id_mask);
         return Err(EINVAL);
-    };
+    }
+    .into();
 
     // TODO[NUMM]: replace with `last_set_bit` once it lands.
     Ok(u16::BITS - reg_fuse_version.leading_zeros())
drivers/gpu/nova-core/falcon/sec2.rs +6 -7
index b57d362e576a..5d836e2d17dd 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.
drivers/gpu/nova-core/fb/hal/ga100.rs +5 -4
index e0acc41aa7cd..acf46ad0dba1 100644
@@ -1,6 +1,9 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    num::Bounded,
+    prelude::*, //
+};
 
 use crate::{
     driver::Bar0,
@@ -20,9 +23,7 @@ pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) -> u64 {
 
 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)
+        .set_adr_63_40(Bounded::from_expr(addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI).cast())
         .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
drivers/gpu/nova-core/gpu.rs +14 -10
index 629c9d2dc994..556b2454b5a6 100644
@@ -4,6 +4,7 @@
     device,
     devres::Devres,
     fmt,
+    num::Bounded,
     pci,
     prelude::*,
     sync::Arc, //
@@ -135,11 +136,11 @@ pub(crate) enum Architecture {
     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 +149,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(),
         }
     }
 }
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
index 3991ccc0c10f..60a1b0fecf62 100644
@@ -476,7 +476,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)
+            .set_address(0u32)
             .write(bar);
     }
 
drivers/gpu/nova-core/regs.rs +133 -132

442 lines not on this page · raw message

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

721 lines not on this page · raw message

Signature · 1 line
2.52.0
Tested-by on the v2 series
#24 lore raw
In reply to Alexandre Courbot
Quoted 43 lines · Alexandre Courbot

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,
- Extended documentation,
- Doccomments now build and run,
- Supports visibility and different storage sizes.

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. Third patch adds another convenience method to obtain a bool from single-bit Boundeds.

Patch 4 adds the register! macro. Since it falls under rust/kernel/io it is covered by the corresponding MAINTAINERS entry so I refrained from adding one just for this file, especially since the bitfield-related parts will eventually move and what remains is very tightly related to I/O.

The last patch illustrates 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.

Previous work to extract the macros was done in the partially-merged [1]. The current series can be considered a reboot with more features and the bitfield! macro being postponed.

Quoted 7 lines

This patchset is based on driver-core-next.

Note that it also need rust-fixes to avoid an unused_unsafe warning.

[1] https://lore.kernel.org/all/[email protected]/

I gave this v2 a try on top of my 6.19.0-rc3 and it compiles now using rustc 1.81.0. I adapted my aarch64 timer TMU test using register!() and it works as expected. With this:

Many thanks!

Dirk