[<prev] [next>] [day] [month] [year] [list]
Message-Id: <20250320-registers-v2-1-d277409bcde8@nvidia.com>
Date: Thu, 20 Mar 2025 22:35:09 +0900
From: Alexandre Courbot <acourbot@...dia.com>
To: Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...nel.org>, Alice Ryhl <aliceryhl@...gle.com>,
Trevor Gross <tmgross@...ch.edu>, Danilo Krummrich <dakr@...nel.org>,
David Airlie <airlied@...il.com>, Simona Vetter <simona@...ll.ch>
Cc: linux-kernel@...r.kernel.org, rust-for-linux@...r.kernel.org,
Alexandre Courbot <acourbot@...dia.com>
Subject: [PATCH RFC v2] rust: add macros to define registers layout
Add two macros, register!() and register_rel!(), that define a given
register's layout and provide accessors for absolute or relative
offsets, respectively.
The following example (taken from the rustdoc) helps understanding how
they are used:
register!(Boot0@...0000100, "Basic revision information about the chip";
3:0 minor_rev => as u8, "minor revision of the chip";
7:4 major_rev => as u8, "major revision of the chip";
28:20 chipset => try_into Chipset, "chipset model"
);
This defines a `Boot0` type which can be read or written from offset
`0x100` of an `Io` region. It is composed of 3 fields, for instance
`minor_rev` is made of the 4 less significant bits of the register. Each
field can be accessed and modified using helper methods:
// Read from offset `0x100`.
let boot0 = Boot0::read(&bar);
pr_info!("chip revision: {}.{}", boot0.major_rev(), boot0.minor_rev());
// `Chipset::try_from` will be called with the value of the field and
// returns an error if the value is invalid.
let chipset = boot0.chipset()?;
// Update some fields and write the value back.
boot0.set_major_rev(3).set_minor_rev(10).write(&bar);
// Or just update the register value in a single step:
Boot0::alter(&bar, |r| r.set_major_rev(3).set_minor_rev(10));
Fields are made accessible using one of the following strategies:
- `as <type>` simply casts the field value to the requested type.
- `as_bit <type>` turns the field into a boolean and calls
<type>::from()` with the obtained value. To be used with single-bit
fields.
- `into <type>` calls `<type>::from()` on the value of the field. It is
expected to handle all the possible values for the bit range selected.
- `try_into <type>` calls `<type>::try_from()` on the value of the field
and returns its result.
The documentation strings are optional. If present, they will be added
to the type or the field getter and setter methods they are attached to.
Suggested-by: Danilo Krummrich <dakr@...nel.org>
Signed-off-by: Alexandre Courbot <acourbot@...dia.com>
---
I have written these initially for the nova-core driver, then it has
been suggested that they might be useful outside of it as well, so here
goes.
I have considered as suggested to turn these into a single procedural
macro, but could not even get even the basics to parse properly yet -
procedural macros are not easy to begin with, but kernel procedural
macros are also different from user-space ones, making it all the more
difficult. I will keep looking into it but wanted to post a new revision
meanwhile, since it is used by my next nova-core series revision.
The following things needs to be improved before we can remove the [RFC]
flag:
- Inner types other than `u32` need to be supported - this can probably
just be an extra parameter of the macro.
- The syntax can certainly be improved. I've tried to some with
something that makes the register layout obvious, while fitting within
the expectations of the Rust macro parser, but my lack of experience
certainly shows here.
- We probably need an option to make some fields or whole registers
read-only.
- The I/O offset and read/write methods should be optional, so the
layout part can be used for things that are not registers.
- The visibility of the helper macros is a bit of a headache - I haven't
found a way to completely hide them to the outside, so I have prefixed
them with `__` for now. Using a procedural macro should help with
that too.
Dependencies:
- [1] https://lore.kernel.org/rust-for-linux/20250318-topic-panthor-rs-genmask-v4-1-35004fca6ac5@collabora.com/
- [2] https://lore.kernel.org/rust-for-linux/20250306222336.23482-1-dakr@kernel.org/
---
Changes in v2:
- Moved to the io module.
- Rename the macros to "register!()" and "register_rel!()".
- Properly clear field in setter methods.
- Use the genmask macros from [1].
- Add "alter" and "try_alter" methods to modify a register's content
using a closure.
- Link to v1: https://lore.kernel.org/r/20250313-registers-v1-1-8d498537e8b2@nvidia.com
---
rust/kernel/io.rs | 2 +
rust/kernel/io/register.rs | 305 +++++++++++++++++++++++++++++++++++++++++++++
rust/kernel/reg.rs | 2 +
3 files changed, 309 insertions(+)
diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs
index d4a73e52e3ee68f7b558749ed0108acde92ae5fe..acecbf196be1751c9de7bc50dc47b213f9ba2362 100644
--- a/rust/kernel/io.rs
+++ b/rust/kernel/io.rs
@@ -7,6 +7,8 @@
use crate::error::{code::EINVAL, Result};
use crate::{bindings, build_assert};
+mod register;
+
/// Raw representation of an MMIO region.
///
/// By itself, the existence of an instance of this structure does not provide any guarantees that
diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs
new file mode 100644
index 0000000000000000000000000000000000000000..14eac88677f57ca92b80f50d03cee535ab685f07
--- /dev/null
+++ b/rust/kernel/io/register.rs
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Types and macros to define register layout and accessors.
+//!
+//! A single register typically includes several fields, which are accessed through a combination
+//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because
+//! not all possible field values are necessarily valid.
+//!
+//! The macros in this module allow to define, using an intruitive and readable syntax, a dedicated
+//! type for each register with its own field accessors that can return an error is a field's value
+//! is invalid. They also provide a builder type allowing to construct a register value to be
+//! written by combining valid values for its fields.
+
+/// Helper macro for the `register` macro.
+///
+/// Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, `BitOr`,
+/// and conversion to regular `u32`).
+#[macro_export]
+macro_rules! __reg_def_common {
+ ($name:ident $(, $type_comment:expr)?) => {
+ $(
+ #[doc=$type_comment]
+ )?
+ #[repr(transparent)]
+ #[derive(Clone, Copy, Default)]
+ pub(crate) struct $name(u32);
+
+ // TODO: should we display the raw hex value, then the value of all its fields?
+ impl ::core::fmt::Debug for $name {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_tuple(stringify!($name))
+ .field(&format_args!("0x{0:x}", &self.0))
+ .finish()
+ }
+ }
+
+ impl core::ops::BitOr for $name {
+ type Output = Self;
+
+ fn bitor(self, rhs: Self) -> Self::Output {
+ Self(self.0 | rhs.0)
+ }
+ }
+
+ impl From<$name> for u32 {
+ fn from(reg: $name) -> u32 {
+ reg.0
+ }
+ }
+ };
+}
+
+/// Helper macro for the `register` macro.
+///
+/// Defines the getter method for $field.
+#[macro_export]
+macro_rules! __reg_def_field_getter {
+ (
+ $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $comment:expr)?
+ ) => {
+ $(
+ #[doc=concat!("Returns the ", $comment)]
+ )?
+ #[inline]
+ pub(crate) fn $field(self) -> $( $as_type )? $( $bit_type )? $( $type )? $( core::result::Result<$try_type, <$try_type as TryFrom<u32>>::Error> )? {
+ const MASK: u32 = ::kernel::bits::genmask_u32($hi, $lo);
+ const SHIFT: u32 = MASK.trailing_zeros();
+ let field = (self.0 & MASK) >> SHIFT;
+
+ $( field as $as_type )?
+ $(
+ // TODO: it would be nice to throw a compile-time error if $hi != $lo as this means we
+ // are considering more than one bit but returning a bool...
+ <$bit_type>::from(if field != 0 { true } else { false }) as $bit_type
+ )?
+ $( <$type>::from(field) )?
+ $( <$try_type>::try_from(field) )?
+ }
+ }
+}
+
+/// Helper macro for the `register` macro.
+///
+/// Defines all the field getter methods for `$name`.
+#[macro_export]
+macro_rules! __reg_def_getters {
+ (
+ $name:ident
+ $(; $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $field_comment:expr)?)* $(;)?
+ ) => {
+ #[allow(dead_code)]
+ impl $name {
+ $(
+ ::kernel::__reg_def_field_getter!($hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)?);
+ )*
+ }
+ };
+}
+
+/// Helper macro for the `register` macro.
+///
+/// Defines the setter method for $field.
+#[macro_export]
+macro_rules! __reg_def_field_setter {
+ (
+ $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $comment:expr)?
+ ) => {
+ kernel::macros::paste! {
+ $(
+ #[doc=concat!("Sets the ", $comment)]
+ )?
+ #[inline]
+ pub(crate) fn [<set_ $field>](mut self, value: $( $as_type)? $( $bit_type )? $( $type )? $( $try_type)? ) -> Self {
+ const MASK: u32 = ::kernel::bits::genmask_u32($hi, $lo);
+ const SHIFT: u32 = MASK.trailing_zeros();
+
+ let value = ((value as u32) << SHIFT) & MASK;
+ self.0 = (self.0 & !MASK) | value;
+ self
+ }
+ }
+ };
+}
+
+/// Helper macro for the `register` macro.
+///
+/// Defines all the field setter methods for `$name`.
+#[macro_export]
+macro_rules! __reg_def_setters {
+ (
+ $name:ident
+ $(; $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $field_comment:expr)?)* $(;)?
+ ) => {
+ #[allow(dead_code)]
+ impl $name {
+ $(
+ ::kernel::__reg_def_field_setter!($hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)?);
+ )*
+ }
+ };
+}
+
+/// Defines a dedicated type for a register with an absolute offset, alongside with getter and
+/// setter methods for its fields and methods to read and write it from an `Io` region.
+///
+/// Example:
+///
+/// ```no_run
+/// register!(Boot0@...0000100, "Basic revision information about the chip";
+/// 3:0 minor_rev => as u8, "minor revision of the chip";
+/// 7:4 major_rev => as u8, "major revision of the chip";
+/// 28:20 chipset => try_into Chipset, "chipset model"
+/// );
+/// ```
+///
+/// This defines a `Boot0` type which can be read or written from offset `0x100` of an `Io` region.
+/// It is composed of 3 fields, for instance `minor_rev` is made of the 4 less significant bits of
+/// the register. Each field can be accessed and modified using helper methods:
+///
+/// ```no_run
+/// // Read from offset 0x100.
+/// let boot0 = Boot0::read(&bar);
+/// pr_info!("chip revision: {}.{}", boot0.major_rev(), boot0.minor_rev());
+///
+/// // `Chipset::try_from` will be called with the value of the field and returns an error if the
+/// // value is invalid.
+/// let chipset = boot0.chipset()?;
+///
+/// // Update some fields and write the value back.
+/// boot0.set_major_rev(3).set_minor_rev(10).write(&bar);
+///
+/// // Or just update the register value in a single step:
+/// Boot0::alter(&bar, |r| r.set_major_rev(3).set_minor_rev(10));
+/// ```
+///
+/// Fields are made accessible using one of the following strategies:
+///
+/// - `as <type>` simply casts the field value to the requested type.
+/// - `as_bit <type>` turns the field into a boolean and calls `<type>::from()` with the obtained
+/// value. To be used with single-bit fields.
+/// - `into <type>` calls `<type>::from()` on the value of the field. It is expected to handle all
+/// the possible values for the bit range selected.
+/// - `try_into <type>` calls `<type>::try_from()` on the value of the field and returns its
+/// result.
+///
+/// The documentation strings are optional. If present, they will be added to the type or the field
+/// getter and setter methods they are attached to.
+#[macro_export]
+macro_rules! register {
+ (
+ $name:ident@...fset:expr $(, $type_comment:expr)?
+ $(; $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $field_comment:expr)?)* $(;)?
+ ) => {
+ ::kernel::__reg_def_common!($name);
+
+ #[allow(dead_code)]
+ impl $name {
+ #[inline]
+ pub(crate) fn read<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(bar: &T) -> Self {
+ Self(bar.readl($offset))
+ }
+
+ #[inline]
+ pub(crate) fn write<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(self, bar: &T) {
+ bar.writel(self.0, $offset)
+ }
+
+ #[inline]
+ pub(crate) fn alter<const SIZE: usize, T: Deref<Target=Io<SIZE>>, F: FnOnce(Self) -> Self>(bar: &T, f: F) {
+ let reg = f(Self::read(bar));
+ reg.write(bar);
+ }
+ }
+
+ ::kernel::__reg_def_getters!($name; $( $hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)? );*);
+
+ ::kernel::__reg_def_setters!($name; $( $hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)? );*);
+ };
+}
+
+/// Defines a dedicated type for a register with a relative offset, alongside with getter and
+/// setter methods for its fields and methods to read and write it from an `Io` region.
+///
+/// See the documentation for [`register`] for more details. This macro works similarly to
+/// `register`, with the exception that the `read` and `write` methods take a `base` argument that
+/// is added to the offset of the register before access, and the `try_read` and `try_write`
+/// methods are added to allow access with offsets unknown at compile-time.
+#[macro_export]
+macro_rules! register_rel {
+ (
+ $name:ident@...fset:expr $(, $type_comment:expr)?
+ $(; $hi:tt:$lo:tt $field:ident
+ $(=> as $as_type:ty)?
+ $(=> as_bit $bit_type:ty)?
+ $(=> into $type:ty)?
+ $(=> try_into $try_type:ty)?
+ $(, $field_comment:expr)?)* $(;)?
+ ) => {
+ ::kernel::__reg_def_common!($name);
+
+ #[allow(dead_code)]
+ impl $name {
+ #[inline]
+ pub(crate) fn read<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(bar: &T, base: usize) -> Self {
+ Self(bar.readl(base + $offset))
+ }
+
+ #[inline]
+ pub(crate) fn write<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(self, bar: &T, base: usize) {
+ bar.writel(self.0, base + $offset)
+ }
+
+ #[inline]
+ pub(crate) fn alter<const SIZE: usize, T: Deref<Target=Io<SIZE>>, F: FnOnce(Self) -> Self>(bar: &T, base: usize, f: F) {
+ let reg = f(Self::read(bar, base));
+ reg.write(bar, base);
+ }
+
+ #[inline]
+ pub(crate) fn try_read<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(bar: &T, base: usize) -> ::kernel::error::Result<Self> {
+ bar.try_readl(base + $offset).map(Self)
+ }
+
+ #[inline]
+ pub(crate) fn try_write<const SIZE: usize, T: Deref<Target=Io<SIZE>>>(self, bar: &T, base: usize) -> ::kernel::error::Result<()> {
+ bar.try_writel(self.0, base + $offset)
+ }
+
+ #[inline]
+ pub(crate) fn try_alter<const SIZE: usize, T: Deref<Target=Io<SIZE>>, F: FnOnce(Self) -> Self>(bar: &T, base: usize, f: F) -> ::kernel::error::Result<()> {
+ let reg = f(Self::try_read(bar, base)?);
+ reg.try_write(bar, base)
+ }
+ }
+
+ ::kernel::__reg_def_getters!($name; $( $hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)? );*);
+
+ ::kernel::__reg_def_setters!($name; $( $hi:$lo $field $(=> as $as_type)? $(=> as_bit $bit_type)? $(=> into $type)? $(=> try_into $try_type)? $(, $field_comment)? );*);
+ };
+}
diff --git a/rust/kernel/reg.rs b/rust/kernel/reg.rs
new file mode 100644
index 0000000000000000000000000000000000000000..139597f9cb07c5d48bed18984ec4747f4b4f3438
--- /dev/null
+++ b/rust/kernel/reg.rs
@@ -0,0 +1,2 @@
+
+
---
base-commit: 1d53763dc16c9fc9329a4cdc14d691979d47568f
change-id: 20250313-registers-7fdcb3d926b0
prerequisite-change-id: 20241023-topic-panthor-rs-genmask-fabc573fef43:v4
prerequisite-patch-id: 182945904fd914573eed9388a559ce8a642310ef
prerequisite-message-id: <20250306222336.23482-1-dakr@...nel.org>
prerequisite-patch-id: de15c0d16727e6af2d79f88f5b67be4c06212552
prerequisite-patch-id: f8bca95d983222da29508cc6e6886e4b0f992588
prerequisite-patch-id: 1ae8f68250fb43808342285a284bcf7b572263fe
prerequisite-patch-id: fa5ce1308e1dbc71374a381537ab3978babe20a0
prerequisite-patch-id: 7225e000f745bb5fd45fc43393d801d1d9adb767
Best regards,
--
Alexandre Courbot <acourbot@...dia.com>
Powered by blists - more mailing lists