rust: add `register!` macro
Subsystems (8)
Alexandre Courbot
maintainerv8 cover rust: add `register!` macro
Another revision, another redesign.
This one eschews closures completely for write operations, and defaults to a two-argument write method backed by a single-argument write_val one to avoid register name repetition. The two-argument version can now be used in most cases thanks to a clever use of traits (thanks Gary!).
We went from this syntax:
bar.write_with(regs::NV_PFALCON_FALCON_DMATRFFBOFFS::of::<E>(), |r| {
r.with_offs(src_start + pos)
});to this one:
bar.write(
WithBase::of::<E>(), regs::NV_PFALCON_FALCON_DMATRFFBOFFS::zeroed().with_offs(src_start + pos),
);
While slightly more verbose, it is also much easier to read, as the location and value are properly formatted into their own line, and the confusing closure syntax is gone. Getting rid of closures also allows any register value constructor to be used, not just a set of fixed ones. The supporting code in the register module also doesn't spill on io at all.
This design also trims more generated code from the register macro:
almost everything is provided through traits and generic code, and the macro only implements the traits relevant to the register type (while also embedding the bitfield feature which will eventually move to its own macro).
The register macro documentation and top patch should give a good idea of how this is used.
This revision is based on driver-core-next as of 2026-03-09. The top patch also depends on drm-rust-next, but it is only here to illustrate how client code looks like.
A tree with this series and its dependencies is available at [1].
[1] https://github.com/Gnurou/linux/tree/b4/register
---
Changes in v8:
- Use two-arguments Io::write with a convenience single-argument Io::write_val.
- Remove the IoWrite type, all helper methods of IoLoc, and stop relying on closures to write values.
- Add traits for specifying relative and array register locations.
- Improved documentation and examples.
- Link to v7: https://patch.msgid.link/[email protected]
Changes in v7:
- Use RES + SHIFT >= N instead of RES >= N - SHIFT in Bounded::shr.
- Rename IoRef to IoLoc and all related types
accordingly.
- Use Into trait bounds in both directions on IoLoc.
- Add RFC patch allowing fixed register values to be used directly with write.
- Link to v6: https://patch.msgid.link/[email protected]
Changes in v6:
- Remove Tested-by tags as the code has considerably changed.
- Make Bounded::get const so it can be used with registers.
- Use the pin_init::zeroed() const function instead of defining our own method.
- Generalize all Io around the new IoRef and IoWrite types, and make registers use these as well.
- Use the more natural pattern of having the Io type perform the I/O access instead of the register type.
- Convert the whole PCI driver example, and not only the PCI configuration space.
- Rename Bounded::as_bool to Bounded::into_bool.
- Drop Bounded::into_inner in favor of making Bounded::get const.
- Link to v5: https://patch.msgid.link/[email protected]
Changes in v5:
- Rename all setters to with_* and with_const_*.
- Use , stride = to specify the stride of register arrays.
- Remove Deref requirement on the RegisterIo trait and make it #[doc(hidden).
- Simplify the top dispatch rule a bit.
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Add with_ const field setter methods (removing the need to call Bounded::new for constant field values).
- Add into_inner const method for Bounded.
- Add from_raw and const zeroed method to create initial register values.
- More documentation improvements.
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Sort the Rust features list alphabetically.
- Rebase on top of latest driver-core-next including the new Io trait.
- Allow several registers to be defined from the same macro invocation.
- Remove references to bitfield! macro.
- Fix doccomment of shr and shl.
- Use + syntax for relative register offsets.
- Move register arrays size and stride to after the backing type declaration.
- Use regular doccomments to document registers and fields (thanks Gary!).
- Remove Default implementation and implement the more predictable Zeroable instead.
- Improve doccomments a bit.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Remove bitfield! and put its rules into register! to give it more time to get reviewed.
- Allow output type larger than strictly required for shr and shl on Bounded.
- Enable the generic_arg_infer feature, required for rustc < 1.89.
- Link to v1: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (10):
rust: enable the generic_arg_infer feature
rust: num: add shr and shl methods to Bounded
rust: num: add into_bool method to Bounded
rust: num: make Bounded::get const
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduce IntoIoVal trait and single-argument write_val
rust: io: add register! macro
sample: rust: pci: use register! macro
[FOR REFERENCE] gpu: nova-core: use the kernel register! macro
drivers/gpu/nova-core/falcon.rs | 330 +++--- drivers/gpu/nova-core/falcon/gsp.rs | 25 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 70 +- drivers/gpu/nova-core/falcon/hal/tu102.rs | 12 +- drivers/gpu/nova-core/falcon/sec2.rs | 17 +- drivers/gpu/nova-core/fb.rs | 6 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 37 +- drivers/gpu/nova-core/fb/hal/ga102.rs | 7 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 17 +- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 16 +- drivers/gpu/nova-core/gfw.rs | 11 +- drivers/gpu/nova-core/gpu.rs | 36 +- drivers/gpu/nova-core/gsp/boot.rs | 11 +- drivers/gpu/nova-core/gsp/cmdq.rs | 9 +- drivers/gpu/nova-core/regs.rs | 612 +++++----- drivers/gpu/nova-core/regs/macros.rs | 739 ------------ rust/kernel/io.rs | 391 +++++-- rust/kernel/io/register.rs | 1190 ++++++++++++++++++++ rust/kernel/lib.rs | 3 + rust/kernel/num/bounded.rs | 70 +- samples/rust/rust_driver_pci.rs | 84 +- scripts/Makefile.build | 3 +- 22 files changed, 2319 insertions(+), 1377 deletions(-)
---
base-commit: a985880eb0f73b0d497d30dcce73e537f787b6c0
change-id: 20260117-register-ccaba1d21713
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v8 1/10 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
@@ -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
@@ -314,12 +314,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # - Stable since Rust 1.82.0: `feature(asm_const)`, # `feature(offset_of_nested)`, `feature(raw_ref_op)`. # - Stable since Rust 1.87.0: `feature(asm_goto)`. +# - Stable since Rust 1.89.0: `feature(generic_arg_infer)`. # - Expected to become stable: `feature(arbitrary_self_types)`. # - To be determined: `feature(used_with_arg)`. # # Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on # the unstable features in use. -rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg +rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,generic_arg_infer,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree
Signature · 1 line
2.53.0
Re: [PATCH v8 01/10] rust: enable the `generic_arg_infer` feature
Quoted 31 lines · Alexandre Courbot
This feature is stable since 1.89, and used in subsequent patches.
Reviewed-by Gary Guo <[email protected]>Tested-by Dirk Behme <[email protected]>Acked-by Miguel Ojeda <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/lib.rs | 3 +++ scripts/Makefile.build | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-)rust/kernel/lib.rs +3
-0@@ -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@@ -314,12 +314,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # - Stable since Rust 1.82.0: `feature(asm_const)`,
scripts/Makefile.build $(obj)/%.lst: $(obj)/%.c FORCE · line 323
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,generic_arg_infer,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg
Maybe split the line? It's already over 100 chars, and it doesn't seem to get shorter.
Quoted 6 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-treeSignature · 1 line
2.53.0
Re: [PATCH v8 01/10] rust: enable the `generic_arg_infer` feature
Quoted 3 lines · Yury Norov
Maybe split the line? It's already over 100 chars, and it doesn't seem to get shorter.
We are about to bump the minimum to Debian Stable's, 1.85, so it will become shorter at just about the right time... :)
Cheers,
Miguel
Alexandre Courbot
maintainerPATCH v8 2/10 rust: num: add `shr` and `shl` methods to `Bounded`
In reply to Alexandre CourbotShifting a Bounded left or right changes the number of bits required to represent the value. Add methods that perform the shift and return a Bounded with the appropriately adjusted bit width.
These methods are particularly useful for bitfield extraction.
--- rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+)
rust/kernel/num/bounded.rs +42 -0
@@ -473,6 +473,48 @@ pub fn cast<U>(self) -> Bounded<U, N>// `N` bits, and with the same signedness. unsafe {Bounded ::__new (value) } } + +/// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N - SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 16>::new::<0xff00>(); +/// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff); +/// ``` +pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES +SHIFT >=N ) } + +// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES >= N - SHIFT`. +unsafe {Bounded ::__new (self.0 >>SHIFT ) } + } + +/// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N + SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 8>::new::<0xff>(); +/// let v_shifted: Bounded::<u32, 16> = v.shl::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff00); +/// ``` +pub fn shl <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES >=N +SHIFT ) } + +// SAFETY: We shift the value left by `SHIFT`, augmenting the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES >= N + SHIFT`. +unsafe {Bounded ::__new (self.0 <<SHIFT ) } + } }impl <T ,const N :u32 >Deref for Bounded <T ,N >
Signature · 1 line
2.53.0
Re: [PATCH v8 02/10] rust: num: add `shr` and `shl` methods to `Bounded`
Quoted 6 lines · Alexandre Courbot
Shifting a
Boundedleft or right changes the number of bits required to represent the value. Add methods that perform the shift and return aBoundedwith the appropriately adjusted bit width.These methods are particularly useful for bitfield extraction.
Quoted 7 lines
Suggested-by Alice Ryhl <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>Reviewed-by Daniel Almeida <[email protected]>Tested-by Dirk Behme <[email protected]>Acked-by Miguel Ojeda <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>
Quoted 60 lines
--- rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+)rust/kernel/num/bounded.rs +42
-0@@ -473,6 +473,48 @@ pub fn cast<U>(self) -> Bounded<U, N>// `N` bits, and with the same signedness. unsafe {Bounded ::__new (value) } } + +/// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N - SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 16>::new::<0xff00>(); +/// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff); +/// ``` +pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES +SHIFT >=N ) } + +// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES >= N - SHIFT`. +unsafe {Bounded ::__new (self.0 >>SHIFT ) } + } + +/// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N + SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 8>::new::<0xff>(); +/// let v_shifted: Bounded::<u32, 16> = v.shl::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff00); +/// ``` +pub fn shl <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES >=N +SHIFT ) } + +// SAFETY: We shift the value left by `SHIFT`, augmenting the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES >= N + SHIFT`. +unsafe {Bounded ::__new (self.0 <<SHIFT ) } + } }impl <T ,const N :u32 >Deref for Bounded <T ,N >Signature · 2 lines
-- 2.53.0
Alexandre Courbot
maintainerPATCH v8 3/10 rust: num: add `into_bool` method to `Bounded`
In reply to Alexandre CourbotSingle-bit numbers are typically treated as booleans. There is an Into<bool> implementation for those, but invoking it from contexts that lack type expectations is not always convenient.
Add an into_bool method as a simpler shortcut.
--- rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
rust/kernel/num/bounded.rs +21 -0
@@ -1101,3 +1101,24 @@ fn from(value: bool) -> Self {unsafe {Self ::__new (T ::from (value)) } } } + +impl <T >Bounded <T ,1 > +where +T :Integer +Zeroable , +{ +/// Converts this [`Bounded`] into a [`bool`]. +/// +/// This is a shorter way of writing `bool::from(self)`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// assert_eq!(Bounded::<u8, 1>::new::<0>().into_bool(), false); +/// assert_eq!(Bounded::<u8, 1>::new::<1>().into_bool(), true); +/// ``` +pub fn into_bool (self) ->bool { + self.into () + } +}
Signature · 1 line
2.53.0
Re: [PATCH v8 03/10] rust: num: add `into_bool` method to `Bounded`
Quoted 4 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.
Quoted 8 lines
Add an
into_boolmethod as a simpler shortcut.Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Gary Guo <[email protected]>Reviewed-by Daniel Almeida <[email protected]>Tested-by Dirk Behme <[email protected]>Acked-by Miguel Ojeda <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>
Quoted 36 lines
--- rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)rust/kernel/num/bounded.rs +21
-0@@ -1101,3 +1101,24 @@ fn from(value: bool) -> Self {unsafe {Self ::__new (T ::from (value)) } } } + +impl <T >Bounded <T ,1 > +where +T :Integer +Zeroable , +{ +/// Converts this [`Bounded`] into a [`bool`]. +/// +/// This is a shorter way of writing `bool::from(self)`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// assert_eq!(Bounded::<u8, 1>::new::<0>().into_bool(), false); +/// assert_eq!(Bounded::<u8, 1>::new::<1>().into_bool(), true); +/// ``` +pub fn into_bool (self) ->bool { + self.into () + } +}Signature · 2 lines
-- 2.53.0
Alexandre Courbot
maintainerPATCH v8 4/10 rust: num: make Bounded::get const
In reply to Alexandre CourbotThere is a need to access the inner value of a Bounded in const context, notably for bitfields and registers. Remove the invariant check of Bounded::get, which allows us to make it const.
--- rust/kernel/num/bounded.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
rust/kernel/num/bounded.rs +5 -2
@@ -379,6 +379,9 @@ pub fn from_expr(expr: T) -> Self {/// Returns the wrapped value as the backing type. /// +/// This is similar to the [`Deref`] implementation, but doesn't enforce the size invariant of +/// the [`Bounded`], which might produce slightly less optimal code. +/// /// # Examples /// /// ```
@@ -387,8 +390,8 @@ pub fn from_expr(expr: T) -> Self {/// let v = Bounded::<u32, 4>::new::<7>(); /// assert_eq!(v.get(), 7u32); /// ``` -pub fn get (self) ->T { - *self.deref () +pub const fn get (self) ->T { + self.0 }/// Increases the number of bits usable for `self`.
Signature · 1 line
2.53.0
Alexandre Courbot
maintainerPATCH v8 5/10 rust: io: add IoLoc type and generic I/O accessors
In reply to Alexandre CourbotI/O accesses are defined by the following properties:
- An I/O location, which consists of a start address, a width, and a type to interpret the read value as,
- A value, which is returned for reads or provided for writes.
Introduce the IoLoc trait, which allows implementing types to fully specify an I/O location.
This allows I/O operations to be made generic through the new read and write methods.
This design will allow us to factorize the I/O code working with primitives, and to introduce ways to perform I/O with a higher degree of control through register types.
--- rust/kernel/io.rs | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+)
rust/kernel/io.rs +124 -0
@@ -173,6 +173,30 @@ pub trait IoCapable<T> {unsafe fn io_write (&self, value:T , address:usize ); } +/// Describes a given I/O location: its offset, width, and type to convert the raw value from and +/// into. +/// +/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`] (and +/// their fallible [`try_read`](Io::try_read), [`try_write`](Io::try_write) and +/// [`try_update`](Io::try_update) counterparts) to work uniformly with both raw [`usize`] offsets +/// (for primitive types like [`u32`]) and typed ones. +/// +/// An `IoLoc<T>` carries three pieces of information: +/// +/// - The offset to access (returned by [`IoLoc::offset`]), +/// - The width of the access (determined by [`IoLoc::IoType`]), +/// - The type `T` in which the raw data is returned or provided. +/// +/// `T` and `IoLoc::IoType` may differ: for instance, a typed register has `T` = the register type +/// with its bitfields, and `IoType` = its backing primitive (e.g. `u32`). +pub trait IoLoc <T > { +/// Size ([`u8`], [`u16`], etc) of the I/O performed on the returned [`offset`](IoLoc::offset). +type IoType :Into <T > +From <T >; + +/// Returns the offset of this location. +fn offset (&self) ->usize ; +} +/// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. ///
@@ -406,6 +430,106 @@ fn write64(&self, value: u64, offset: usize)// SAFETY: `address` has been validated by `io_addr_assert`. unsafe { self.io_write (value, address) } } + +/// Generic fallible read with runtime bounds check. +#[inline(always)] +fn try_read <T ,L >(&self, location:L ) ->Result <T > +where +L :IoLoc <T >, +Self :IoCapable <L ::IoType >, + { +let address = self.io_addr ::<L ::IoType >(location.offset ())?; + +// SAFETY: `address` has been validated by `io_addr`. +Ok (unsafe { self.io_read (address) }.into ()) + } + +/// Generic fallible write with runtime bounds check. +#[inline(always)] +fn try_write <T ,L >(&self, location:L , value:T ) ->Result +where +L :IoLoc <T >, +Self :IoCapable <L ::IoType >, + { +let address = self.io_addr ::<L ::IoType >(location.offset ())?; +let io_value = value.into (); + +// SAFETY: `address` has been validated by `io_addr`. +unsafe { self.io_write (io_value, address) } + +Ok (()) + } + +/// Generic fallible update with runtime bounds check. +/// +/// Caution: this does not perform any synchronization. Race conditions can occur in case of +/// concurrent access. +#[inline(always)] +fn try_update <T ,L ,F >(&self, location:L , f:F ) ->Result +where +L :IoLoc <T >, +Self :IoCapable <L ::IoType >, +F :FnOnce (T ) ->T , + { +let address = self.io_addr ::<L ::IoType >(location.offset ())?; + +// SAFETY: `address` has been validated by `io_addr`. +let value:T =unsafe { self.io_read (address) }.into (); +let io_value =f (value).into (); + +// SAFETY: `address` has been validated by `io_addr_assert`. +unsafe { self.io_write (io_value, address) } + +Ok (()) + } + +/// Generic infallible read with compile-time bounds check. +#[inline(always)] +fn read <T ,L >(&self, location:L ) ->T +where +L :IoLoc <T >, +Self :IoKnownSize +IoCapable <L ::IoType >, + { +let address = self.io_addr_assert ::<L ::IoType >(location.offset ()); + +// SAFETY: `address` has been validated by `io_addr_assert`. +unsafe { self.io_read (address) }.into () + } + +/// Generic infallible write with compile-time bounds check. +#[inline(always)] +fn write <T ,L >(&self, location:L , value:T ) +where +L :IoLoc <T >, +Self :IoKnownSize +IoCapable <L ::IoType >, + { +let address = self.io_addr_assert ::<L ::IoType >(location.offset ()); +let io_value = value.into (); + +// SAFETY: `address` has been validated by `io_addr_assert`. +unsafe { self.io_write (io_value, address) } + } + +/// Generic infallible update with compile-time bounds check. +/// +/// Caution: this does not perform any synchronization. Race conditions can occur in case of +/// concurrent access. +#[inline(always)] +fn update <T ,L ,F >(&self, location:L , f:F ) +where +L :IoLoc <T >, +Self :IoKnownSize +IoCapable <L ::IoType > +Sized , +F :FnOnce (T ) ->T , + { +let address = self.io_addr_assert ::<L ::IoType >(location.offset ()); + +// SAFETY: `address` has been validated by `io_addr_assert`. +let value:T =unsafe { self.io_read (address) }.into (); +let io_value =f (value).into (); + +// SAFETY: `address` has been validated by `io_addr_assert`. +unsafe { self.io_write (io_value, address) } + } }/// Trait for types with a known size at compile time.
Signature · 1 line
2.53.0
Danilo Krummrich
maintainerRe: [PATCH v8 05/10] rust: io: add IoLoc type and generic I/O accessors
rust/kernel/io.rs fn write64(&self, value: u64, offset: usize) · line 466
Quoted 4 lines · Alexandre Courbot
rust/kernel/io.rs +4
-0+/// Generic fallible update with runtime bounds check. +/// +/// Caution: this does not perform any synchronization. Race conditions can occur in case of +/// concurrent access.
NIT: I don't think this really comes as a surprise, so I'd make it "Note:" instead.
I'd also replace "Race conditions can occur in case of concurrent access." with something along the lines of "The caller is responsible to ensure exclusive access if required."
Quoted 2 lines
(quoted diff) +2
-0+ #[inline(always)] + fn try_update<T, L, F>(&self, location: L, f: F) -> Result
Alexandre Courbot
maintainerPATCH v8 6/10 rust: io: use generic read/write accessors for primitive accesses
In reply to Alexandre CourbotBy providing the required IoLoc implementations on usize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.
This also allows us to directly call the generic read/write/update methods with primitive types, so add examples illustrating this.
--- rust/kernel/io.rs | 199 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 131 insertions(+), 68 deletions(-)
rust/kernel/io.rs +131 -68
@@ -197,6 +197,25 @@ pub trait IoLoc<T> {fn offset (&self) ->usize ; } +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) => { + $( +impl IoLoc <$ty>for usize { +type IoType = $ty; + +fn offset (&self) ->usize { + *self + } + } + )* + } +} + +// Provide the ability to read any primitive type from a [`usize`]. +impl_usize_ioloc! (u8 ,u16 ,u32 ,u64 ); +/// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. ///
@@ -241,10 +260,7 @@ fn try_read8(&self, offset: usize) -> Result<u8> where Self: IoCapable<u8>, { -let address = self.io_addr ::<u8 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 16-bit read with runtime bounds check.
@@ -253,10 +269,7 @@ fn try_read16(&self, offset: usize) -> Result<u16> where Self: IoCapable<u16>, { -let address = self.io_addr ::<u16 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 32-bit read with runtime bounds check.
@@ -265,10 +278,7 @@ fn try_read32(&self, offset: usize) -> Result<u32> where Self: IoCapable<u32>, { -let address = self.io_addr ::<u32 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 64-bit read with runtime bounds check.
@@ -277,10 +287,7 @@ fn try_read64(&self, offset: usize) -> Result<u64> where Self: IoCapable<u64>, { -let address = self.io_addr ::<u64 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 8-bit write with runtime bounds check.
@@ -289,11 +296,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Result where Self: IoCapable<u8>, { -let address = self.io_addr ::<u8 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 16-bit write with runtime bounds check.
@@ -302,11 +305,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Result where Self: IoCapable<u16>, { -let address = self.io_addr ::<u16 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 32-bit write with runtime bounds check.
@@ -315,11 +314,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Result where Self: IoCapable<u32>, { -let address = self.io_addr ::<u32 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 64-bit write with runtime bounds check.
@@ -328,11 +323,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Result where Self: IoCapable<u64>, { -let address = self.io_addr ::<u64 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Infallible 8-bit read with compile-time bounds check.
@@ -341,10 +332,7 @@ fn read8(&self, offset: usize) -> u8 where Self: IoKnownSize + IoCapable<u8>, { -let address = self.io_addr_assert ::<u8 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 16-bit read with compile-time bounds check.
@@ -353,10 +341,7 @@ fn read16(&self, offset: usize) -> u16 where Self: IoKnownSize + IoCapable<u16>, { -let address = self.io_addr_assert ::<u16 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 32-bit read with compile-time bounds check.
@@ -365,10 +350,7 @@ fn read32(&self, offset: usize) -> u32 where Self: IoKnownSize + IoCapable<u32>, { -let address = self.io_addr_assert ::<u32 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 64-bit read with compile-time bounds check.
@@ -377,10 +359,7 @@ fn read64(&self, offset: usize) -> u64 where Self: IoKnownSize + IoCapable<u64>, { -let address = self.io_addr_assert ::<u64 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 8-bit write with compile-time bounds check.
@@ -389,10 +368,7 @@ fn write8(&self, value: u8, offset: usize) where Self: IoKnownSize + IoCapable<u8>, { -let address = self.io_addr_assert ::<u8 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 16-bit write with compile-time bounds check.
@@ -401,10 +377,7 @@ fn write16(&self, value: u16, offset: usize) where Self: IoKnownSize + IoCapable<u16>, { -let address = self.io_addr_assert ::<u16 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 32-bit write with compile-time bounds check.
@@ -413,10 +386,7 @@ fn write32(&self, value: u32, offset: usize) where Self: IoKnownSize + IoCapable<u32>, { -let address = self.io_addr_assert ::<u32 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 64-bit write with compile-time bounds check.
@@ -425,13 +395,28 @@ fn write64(&self, value: u64, offset: usize) where Self: IoKnownSize + IoCapable<u64>, { - let address = self.io_addr_assert::<u64>(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write (offset, value) }/// Generic fallible read with runtime bounds check. +/// +/// # Examples +/// +/// Read a primitive type from an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_reads(io: &Mmio) -> Result { +/// // 32-bit read from address `0x10`. +/// let v: u32 = io.try_read(0x10)?; +/// +/// // 8-bit read from address `0xfff`. +/// let v: u8 = io.try_read(0xfff)?; +/// +/// Ok(()) +/// } +/// ``` #[inline(always)] fn try_read<T, L>(&self, location: L) -> Result<T> where
@@ -445,6 +430,24 @@ fn try_read<T, L>(&self, location: L) -> Result<T> }/// Generic fallible write with runtime bounds check. +/// +/// # Examples +/// +/// Write a primitive type to an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) -> Result { +/// // 32-bit write of value `1` at address `0x10`. +/// io.try_write(0x10, 1u32)?; +/// +/// // 8-bit write of value `0xff` at address `0xfff`. +/// io.try_write(0xfff, 0xffu8)?; +/// +/// Ok(()) +/// } +/// ``` #[inline(always)] fn try_write <T ,L >(&self, location:L , value:T ) ->Result where
@@ -464,6 +467,20 @@ fn try_write<T, L>(&self, location: L, value: T) -> Result/// /// Caution: this does not perform any synchronization. Race conditions can occur in case of /// concurrent access. +/// +/// # Examples +/// +/// Read the u32 value at address `0x10`, increment it, and store the updated value back: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_update(io: &Mmio<0x1000>) -> Result { +/// io.try_update(0x10, |v: u32| { +/// v + 1 +/// }) +/// } +/// ``` #[inline(always)] fn try_update <T ,L ,F >(&self, location:L , f:F ) ->Result where
@@ -484,6 +501,22 @@ fn try_update<T, L, F>(&self, location: L, f: F) -> Result }/// Generic infallible read with compile-time bounds check. +/// +/// # Examples +/// +/// Read a primitive type from an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_reads(io: &Mmio<0x1000>) { +/// // 32-bit read from address `0x10`. +/// let v: u32 = io.read(0x10); +/// +/// // 8-bit read from the top of the I/O space. +/// let v: u8 = io.read(0xfff); +/// } +/// ``` #[inline(always)] fn read <T ,L >(&self, location:L ) ->T where
@@ -497,6 +530,22 @@ fn read<T, L>(&self, location: L) -> T }/// Generic infallible write with compile-time bounds check. +/// +/// # Examples +/// +/// Write a primitive type to an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio<0x1000>) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write(0x10, 1u32); +/// +/// // 8-bit write of value `0xff` at the top of the I/O space. +/// io.write(0xfff, 0xffu8); +/// } +/// ``` #[inline(always)] fn write <T ,L >(&self, location:L , value:T )where
@@ -514,6 +563,20 @@ fn write<T, L>(&self, location: L, value: T)/// /// Caution: this does not perform any synchronization. Race conditions can occur in case of /// concurrent access. +/// +/// # Examples +/// +/// Read the u32 value at address `0x10`, increment it, and store the updated value back: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_update(io: &Mmio<0x1000>) { +/// io.update(0x10, |v: u32| { +/// v + 1 +/// }) +/// } +/// ``` #[inline(always)] fn update <T ,L ,F >(&self, location:L , f:F )where
Signature · 1 line
2.53.0
Gary Guo
reviewerRe: [PATCH v8 06/10] rust: io: use generic read/write accessors for primitive accesses
Quoted 18 lines · Alexandre Courbot
By providing the required
IoLocimplementations onusize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.This also allows us to directly call the generic
read/write/updatemethods with primitive types, so add examples illustrating this.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 199 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 131 insertions(+), 68 deletions(-)rust/kernel/io.rs +0
-0@@ -197,6 +197,25 @@ pub trait IoLoc<T> {fn offset (&self) ->usize ;
rust/kernel/io.rs pub trait IoLoc<T> { · line 207
Quoted 10 lines
rust/kernel/io.rs +8
-0} +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) => { + $( + impl IoLoc<$ty> for usize { + type IoType = $ty; +
#[inline(always)]
the fact that this is a pointer is somewhat uneasy to me. I wonder if Clippy with its inlining tweak would cause optimisation failure here.
Could this be just fn offset(self)?
The rest LGTM.
Best,
Gary
Quoted 344 lines
rust/kernel/io.rs +123
-68+fn offset (&self) ->usize { + *self + } + } + )* + } +} + +// Provide the ability to read any primitive type from a [`usize`]. +impl_usize_ioloc! (u8 ,u16 ,u32 ,u64 ); +/// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. /// @@ -241,10 +260,7 @@ fn try_read8(&self, offset: usize) -> Result<u8> where Self: IoCapable<u8>, { -let address = self.io_addr ::<u8 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 16-bit read with runtime bounds check. @@ -253,10 +269,7 @@ fn try_read16(&self, offset: usize) -> Result<u16> where Self: IoCapable<u16>, { -let address = self.io_addr ::<u16 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 32-bit read with runtime bounds check. @@ -265,10 +278,7 @@ fn try_read32(&self, offset: usize) -> Result<u32> where Self: IoCapable<u32>, { -let address = self.io_addr ::<u32 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 64-bit read with runtime bounds check. @@ -277,10 +287,7 @@ fn try_read64(&self, offset: usize) -> Result<u64> where Self: IoCapable<u64>, { -let address = self.io_addr ::<u64 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -Ok (unsafe { self.io_read (address) }) + self.try_read (offset) }/// Fallible 8-bit write with runtime bounds check. @@ -289,11 +296,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Result where Self: IoCapable<u8>, { -let address = self.io_addr ::<u8 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 16-bit write with runtime bounds check. @@ -302,11 +305,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Result where Self: IoCapable<u16>, { -let address = self.io_addr ::<u16 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 32-bit write with runtime bounds check. @@ -315,11 +314,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Result where Self: IoCapable<u32>, { -let address = self.io_addr ::<u32 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Fallible 64-bit write with runtime bounds check. @@ -328,11 +323,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Result where Self: IoCapable<u64>, { -let address = self.io_addr ::<u64 >(offset)?; - -// SAFETY: `address` has been validated by `io_addr`. -unsafe { self.io_write (value, address) }; -Ok (()) + self.try_write (offset, value) }/// Infallible 8-bit read with compile-time bounds check. @@ -341,10 +332,7 @@ fn read8(&self, offset: usize) -> u8 where Self: IoKnownSize + IoCapable<u8>, { -let address = self.io_addr_assert ::<u8 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 16-bit read with compile-time bounds check. @@ -353,10 +341,7 @@ fn read16(&self, offset: usize) -> u16 where Self: IoKnownSize + IoCapable<u16>, { -let address = self.io_addr_assert ::<u16 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 32-bit read with compile-time bounds check. @@ -365,10 +350,7 @@ fn read32(&self, offset: usize) -> u32 where Self: IoKnownSize + IoCapable<u32>, { -let address = self.io_addr_assert ::<u32 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 64-bit read with compile-time bounds check. @@ -377,10 +359,7 @@ fn read64(&self, offset: usize) -> u64 where Self: IoKnownSize + IoCapable<u64>, { -let address = self.io_addr_assert ::<u64 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_read (address) } + self.read (offset) }/// Infallible 8-bit write with compile-time bounds check. @@ -389,10 +368,7 @@ fn write8(&self, value: u8, offset: usize) where Self: IoKnownSize + IoCapable<u8>, { -let address = self.io_addr_assert ::<u8 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 16-bit write with compile-time bounds check. @@ -401,10 +377,7 @@ fn write16(&self, value: u16, offset: usize) where Self: IoKnownSize + IoCapable<u16>, { -let address = self.io_addr_assert ::<u16 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 32-bit write with compile-time bounds check. @@ -413,10 +386,7 @@ fn write32(&self, value: u32, offset: usize) where Self: IoKnownSize + IoCapable<u32>, { -let address = self.io_addr_assert ::<u32 >(offset); - -// SAFETY: `address` has been validated by `io_addr_assert`. -unsafe { self.io_write (value, address) } + self.write (offset, value) }/// Infallible 64-bit write with compile-time bounds check. @@ -425,13 +395,28 @@ fn write64(&self, value: u64, offset: usize) where Self: IoKnownSize + IoCapable<u64>, { - let address = self.io_addr_assert::<u64>(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write (offset, value) }/// Generic fallible read with runtime bounds check. +/// +/// # Examples +/// +/// Read a primitive type from an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_reads(io: &Mmio) -> Result { +/// // 32-bit read from address `0x10`. +/// let v: u32 = io.try_read(0x10)?; +/// +/// // 8-bit read from address `0xfff`. +/// let v: u8 = io.try_read(0xfff)?; +/// +/// Ok(()) +/// } +/// ``` #[inline(always)] fn try_read<T, L>(&self, location: L) -> Result<T> where@@ -445,6 +430,24 @@ fn try_read<T, L>(&self, location: L) -> Result<T> }/// Generic fallible write with runtime bounds check. +/// +/// # Examples +/// +/// Write a primitive type to an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) -> Result { +/// // 32-bit write of value `1` at address `0x10`. +/// io.try_write(0x10, 1u32)?; +/// +/// // 8-bit write of value `0xff` at address `0xfff`. +/// io.try_write(0xfff, 0xffu8)?; +/// +/// Ok(()) +/// } +/// ``` #[inline(always)] fn try_write <T ,L >(&self, location:L , value:T ) ->Result where @@ -464,6 +467,20 @@ fn try_write<T, L>(&self, location: L, value: T) -> Result/// /// Caution: this does not perform any synchronization. Race conditions can occur in case of /// concurrent access. +/// +/// # Examples +/// +/// Read the u32 value at address `0x10`, increment it, and store the updated value back: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_update(io: &Mmio<0x1000>) -> Result { +/// io.try_update(0x10, |v: u32| { +/// v + 1 +/// }) +/// } +/// ``` #[inline(always)] fn try_update <T ,L ,F >(&self, location:L , f:F ) ->Result where @@ -484,6 +501,22 @@ fn try_update<T, L, F>(&self, location: L, f: F) -> Result }/// Generic infallible read with compile-time bounds check. +/// +/// # Examples +/// +/// Read a primitive type from an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_reads(io: &Mmio<0x1000>) { +/// // 32-bit read from address `0x10`. +/// let v: u32 = io.read(0x10); +/// +/// // 8-bit read from the top of the I/O space. +/// let v: u8 = io.read(0xfff); +/// } +/// ``` #[inline(always)] fn read <T ,L >(&self, location:L ) ->T where @@ -497,6 +530,22 @@ fn read<T, L>(&self, location: L) -> T }/// Generic infallible write with compile-time bounds check. +/// +/// # Examples +/// +/// Write a primitive type to an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio<0x1000>) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write(0x10, 1u32); +/// +/// // 8-bit write of value `0xff` at the top of the I/O space. +/// io.write(0xfff, 0xffu8); +/// } +/// ``` #[inline(always)] fn write <T ,L >(&self, location:L , value:T )where @@ -514,6 +563,20 @@ fn write<T, L>(&self, location: L, value: T)/// /// Caution: this does not perform any synchronization. Race conditions can occur in case of /// concurrent access. +/// +/// # Examples +/// +/// Read the u32 value at address `0x10`, increment it, and store the updated value back: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_update(io: &Mmio<0x1000>) { +/// io.update(0x10, |v: u32| { +/// v + 1 +/// }) +/// } +/// ``` #[inline(always)] fn update <T ,L ,F >(&self, location:L , f:F )where
Alexandre Courbot
maintainerRe: [PATCH v8 06/10] rust: io: use generic read/write accessors for primitive accesses
Quoted 32 lines · Gary Guo
Quoted 18 lines · Alexandre Courbot
By providing the required
IoLocimplementations onusize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.This also allows us to directly call the generic
read/write/updatemethods with primitive types, so add examples illustrating this.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 199 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 131 insertions(+), 68 deletions(-)rust/kernel/io.rs +0
-0@@ -197,6 +197,25 @@ pub trait IoLoc<T> {fn offset (&self) ->usize ;rust/kernel/io.rs pub trait IoLoc<T> { · line 207
Quoted 10 lines
rust/kernel/io.rs +8
-0} +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) => { + $( + impl IoLoc<$ty> for usize { + type IoType = $ty; +#[inline(always)]
Quoted 4 lines
the fact that this is a pointer is somewhat uneasy to me. I wonder if Clippy with its inlining tweak would cause optimisation failure here.
Could this be just
fn offset(self)?
Yes, this was a remnant from a previous design where I needed to either make IoLoc require Copy or use a reference here, so I opted for the latter.
With the current code though we are using IoLocs exactly one time, so we can consume self without requiring Copy.
Alexandre Courbot
maintainerRe: [PATCH v8 06/10] rust: io: use generic read/write accessors for primitive accesses
Quoted 36 lines · Alexandre Courbot
Quoted 35 lines · Gary Guo
Quoted 18 lines · Alexandre Courbot
By providing the required
IoLocimplementations onusize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.This also allows us to directly call the generic
read/write/updatemethods with primitive types, so add examples illustrating this.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 199 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 131 insertions(+), 68 deletions(-)rust/kernel/io.rs +0
-0@@ -197,6 +197,25 @@ pub trait IoLoc<T> {fn offset (&self) ->usize ;rust/kernel/io.rs pub trait IoLoc<T> { · line 207
Quoted 10 lines
rust/kernel/io.rs +8
-0} +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) => { + $( + impl IoLoc<$ty> for usize { + type IoType = $ty; +#[inline(always)]
the fact that this is a pointer is somewhat uneasy to me. I wonder if Clippy with its inlining tweak would cause optimisation failure here.
Quoted 8 lines
Quoted 1 line
Could this be just
fn offset(self)?Yes, this was a remnant from a previous design where I needed to either make
IoLocrequireCopyor use a reference here, so I opted for the latter.With the current code though we are using
IoLocs exactly one time, so we can consumeselfwithout requiringCopy.
I also guess this method should be renamed into_offset then?
Gary Guo
reviewerRe: [PATCH v8 06/10] rust: io: use generic read/write accessors for primitive accesses
Quoted 39 lines · Alexandre Courbot
Quoted 38 lines · Alexandre Courbot
Quoted 36 lines · Gary Guo
Quoted 18 lines · Alexandre Courbot
By providing the required
IoLocimplementations onusize, we can leverage the generic accessors and reduce the number of unsafe blocks in the module.This also allows us to directly call the generic
read/write/updatemethods with primitive types, so add examples illustrating this.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 199 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 131 insertions(+), 68 deletions(-)rust/kernel/io.rs +0
-0@@ -197,6 +197,25 @@ pub trait IoLoc<T> {fn offset (&self) ->usize ;rust/kernel/io.rs pub trait IoLoc<T> { · line 207
Quoted 10 lines
rust/kernel/io.rs +8
-0} +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) => { + $( + impl IoLoc<$ty> for usize { + type IoType = $ty; +#[inline(always)]
the fact that this is a pointer is somewhat uneasy to me. I wonder if Clippy with its inlining tweak would cause optimisation failure here.
Could this be just
fn offset(self)?
Quoted 8 lines
Quoted 6 lines
Yes, this was a remnant from a previous design where I needed to either make
IoLocrequireCopyor use a reference here, so I opted for the latter.With the current code though we are using
IoLocs exactly one time, so we can consumeselfwithout requiringCopy.I also guess this method should be renamed
into_offsetthen?
Calling this offset is fine, given that this is a trait method and is for I/O plumbing and not really conversion. But I'm fine with into_offset too.
Also, most of the IoLoc types would be Copy anyway (even if it's not required as a bound), neither makes a difference.
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v8 06/10] rust: io: use generic read/write accessors for primitive accesses
In reply to Alexandre Courbotrust/kernel/io.rs fn write64(&self, value: u64, offset: usize) · line 408
Quoted 8 lines · Alexandre Courbot
/// Generic fallible read with runtime bounds check.rust/kernel/io.rs +7
-0+/// +/// # Examples +/// +/// Read a primitive type from an I/O address: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio};
NIT: Please use kernel import style, here and in various other places (including other patches).
rust/kernel/io.rs fn write<T, L>(&self, location: L, value: T) · line 565
Quoted 4 lines
rust/kernel/io.rs +0
-0@@ -514,6 +563,20 @@ fn write<T, L>(&self, location: L, value: T)/// /// Caution: this does not perform any synchronization. Race conditions can occur in case of /// concurrent access.
Same as in the previous patch.
Alexandre Courbot
maintainerPATCH v8 7/10 rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
In reply to Alexandre CourbotSome I/O types, like fixed address registers, carry their location alongside their values. For these types, the regular Io::write method can lead into repeating the location information twice: once to provide the location itself, another time to build the value.
Add a new Io::write_val convenience method that takes a single argument implementing IntoIoVal, a trait that decomposes implementors into a (location, value) tuple. This allows write operations on fixed offset registers to be done while specifying their name only once.
--- rust/kernel/io.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+)
rust/kernel/io.rs +68 -0
@@ -216,6 +216,22 @@ fn offset(&self) -> usize {// Provide the ability to read any primitive type from a [`usize`]. impl_usize_ioloc! (u8 ,u16 ,u32 ,u64 ); +/// Trait implemented by items that contain both an I/O location and a value to assign to it. +/// +/// Implementors can be used with [`Io::write_val`]. +pub trait IntoIoVal <T ,L :IoLoc <T >> { +/// Consumes `self` and returns a `(location, value)` tuple describing a valid I/O write +/// operation. +fn into_io_val (self) -> (L ,T ); +} + +/// `(location, value)` tuples can be used as [`IntoIoVal`]s. +impl <T ,L :IoLoc <T >>IntoIoVal <T ,L >for (L ,T ) { +fn into_io_val (self) -> (L ,T ) { + self + } +} +/// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. ///
@@ -463,6 +479,32 @@ fn try_write<T, L>(&self, location: L, value: T) -> ResultOk (()) } +/// Generic fallible write of value bearing its location, with runtime bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) -> Result { +/// // 32-bit write of value `1` at address `0x10`. +/// io.try_write_val((0x10, 1u32)) +/// } +/// ``` +#[inline(always)] +fn try_write_val <T ,L ,V >(&self, value:V ) ->Result +where +L :IoLoc <T >, +V :IntoIoVal <T ,L >, +Self :IoCapable <L ::IoType >, + { +let (location, value) = value.into_io_val (); + + self.try_write (location, value) + } +/// Generic fallible update with runtime bounds check. /// /// Caution: this does not perform any synchronization. Race conditions can occur in case of
@@ -559,6 +601,32 @@ fn write<T, L>(&self, location: L, value: T)unsafe { self.io_write (io_value, address) } } +/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V ) +where +L :IoLoc <T >, +V :IntoIoVal <T ,L >, +Self :IoKnownSize +IoCapable <L ::IoType >, + { +let (location, value) = value.into_io_val (); + + self.write (location, value) + } +/// Generic infallible update with compile-time bounds check. /// /// Caution: this does not perform any synchronization. Race conditions can occur in case of
Signature · 1 line
2.53.0
Gary Guo
reviewerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 20 lines · Alexandre Courbot
Some I/O types, like fixed address registers, carry their location alongside their values. For these types, the regular
Io::writemethod can lead into repeating the location information twice: once to provide the location itself, another time to build the value.Add a new
Io::write_valconvenience method that takes a single argument implementingIntoIoVal, a trait that decomposes implementors into a(location, value)tuple. This allows write operations on fixed offset registers to be done while specifying their name only once.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+)rust/kernel/io.rs +0
-0
rust/kernel/io.rs fn offset(&self) -> usize { · line 222
Quoted 7 lines
rust/kernel/io.rs +4
-0@@ -216,6 +216,22 @@ fn offset(&self) -> usize {// Provide the ability to read any primitive type from a [`usize`]. impl_usize_ioloc! (u8 ,u16 ,u32 ,u64 ); +/// Trait implemented by items that contain both an I/O location and a value to assign to it. +/// +/// Implementors can be used with [`Io::write_val`]. +pub trait IntoIoVal <T ,L :IoLoc <T >> {
Is this generics instead of associative types for some reason? If so, please mention it in the commit mesasge.
rust/kernel/io.rs fn offset(&self) -> usize { · line 229
Quoted 7 lines
rust/kernel/io.rs +7
-0+/// Consumes `self` and returns a `(location, value)` tuple describing a valid I/O write +/// operation. +fn into_io_val (self) -> (L ,T ); +} + +/// `(location, value)` tuples can be used as [`IntoIoVal`]s. +impl <T ,L :IoLoc <T >>IntoIoVal <T ,L >for (L ,T ) {
Missing inline annotations.
Best,
Gary
Quoted 74 lines
rust/kernel/io.rs +57
-0+fn into_io_val (self) -> (L ,T ) { + self + } +} +/// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. /// @@ -463,6 +479,32 @@ fn try_write<T, L>(&self, location: L, value: T) -> ResultOk (()) } +/// Generic fallible write of value bearing its location, with runtime bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) -> Result { +/// // 32-bit write of value `1` at address `0x10`. +/// io.try_write_val((0x10, 1u32)) +/// } +/// ``` +#[inline(always)] +fn try_write_val <T ,L ,V >(&self, value:V ) ->Result +where +L :IoLoc <T >, +V :IntoIoVal <T ,L >, +Self :IoCapable <L ::IoType >, + { +let (location, value) = value.into_io_val (); + + self.try_write (location, value) + } +/// Generic fallible update with runtime bounds check. /// /// Caution: this does not perform any synchronization. Race conditions can occur in case of @@ -559,6 +601,32 @@ fn write<T, L>(&self, location: L, value: T)unsafe { self.io_write (io_value, address) } } +/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// +/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V ) +where +L :IoLoc <T >, +V :IntoIoVal <T ,L >, +Self :IoKnownSize +IoCapable <L ::IoType >, + { +let (location, value) = value.into_io_val (); + + self.write (location, value) + } +/// Generic infallible update with compile-time bounds check. /// /// Caution: this does not perform any synchronization. Race conditions can occur in case of
Alexandre Courbot
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 24 lines · Gary Guo
Quoted 23 lines · Alexandre Courbot
Some I/O types, like fixed address registers, carry their location alongside their values. For these types, the regular
Io::writemethod can lead into repeating the location information twice: once to provide the location itself, another time to build the value.Add a new
Io::write_valconvenience method that takes a single argument implementingIntoIoVal, a trait that decomposes implementors into a(location, value)tuple. This allows write operations on fixed offset registers to be done while specifying their name only once.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+)rust/kernel/io.rs +0
-0@@ -216,6 +216,22 @@ fn offset(&self) -> usize {// Provide the ability to read any primitive type from a [`usize`]. impl_usize_ioloc! (u8 ,u16 ,u32 ,u64 );
Quoted 7 lines
rust/kernel/io.rs fn offset(&self) -> usize { · line 222
Quoted 4 lines
rust/kernel/io.rs +4
-0+/// Trait implemented by items that contain both an I/O location and a value to assign to it. +/// +/// Implementors can be used with [`Io::write_val`]. +pub trait IntoIoVal <T ,L :IoLoc <T >> {Is this generics instead of associative types for some reason? If so, please mention it in the commit mesasge.
Associated types sound better in that situation, I don't think we can have several implementors with different returned types for the same value anyway.
Quoted 10 lines
rust/kernel/io.rs fn offset(&self) -> usize { · line 229
Quoted 8 lines
rust/kernel/io.rs +7
-0+/// Consumes `self` and returns a `(location, value)` tuple describing a valid I/O write +/// operation. +fn into_io_val (self) -> (L ,T ); +} + +/// `(location, value)` tuples can be used as [`IntoIoVal`]s. +impl <T ,L :IoLoc <T >>IntoIoVal <T ,L >for (L ,T ) {Missing inline annotations.
Fixed, thanks! (and elsewhere in this series as well)
Danilo Krummrich
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
In reply to Alexandre CourbotQuoted 6 lines · Alexandre Courbot
rust/kernel/io.rs +6
-0+/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +///
rust/kernel/io.rs fn write<T, L>(&self, location: L, value: T) · line 619
Quoted 10 lines
rust/kernel/io.rs +10
-0+/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V )
Still not super satisfied with the name write_val() plus I have some more considerations, sorry. :)
Let's look at this:
let reg = bar.read(regs::NV_PMC_BOOT_0); // Pass around, do some modifications, etc. bar.write_val(reg);
In this case read() returns an object that encodes the absolute location and value, i.e. read() pairs with write_val(), which is a bit odd.
In this example:
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // Pass around, do some modifications, etc. bar.write(WithBase::of::<E>(), reg);
read() pairs with write(), since the object returned by read() does only encode a relative location, so we have to supply the base location through the first argument of write().
Well, technically it also pairs with write_val(), as we could also pass this as tuple to write_val().
bar.write_val((WithBase::of::<E>(), reg));
However, my point is that this is a bit inconsistent and I think a user would expect something more symmetric.
For instance, let's say write() would become the single argument one, then read() could return an impl of IntoIoVal, so we would have
let reg = bar.read(regs::NV_PMC_BOOT_0); bar.write(reg); let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write(reg);
and additionally we can have
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(WithBase::of::<E>(), val);
The same goes for
let val = bar.read_val(regs::NV_PMC_BOOT_0); bar.write_val(regs::NV_PMC_BOOT_0, val);
which for complex values does not achieve anything, but makes sense for the FIFO register use-case, as val could also be a primitive, e.g. u32.
With a dynamic base, and a single field we could just do the following to support such primitives:
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(regs::NV_PFALCON_FALCON_RM::of::<E>(), val);
I think adding this symmetry should be trivial, as most of this already compiles with the current code.
Also, let's not get into a discussion whether we name on or the other write() vs. write_foo(). I just turned it around as I think with the specific name write_val() it makes more sense this way around.
But I'm perfectly happy either way as long as we find descriptive names that actually make sense.
Unfortunately, I can't really think of a good name for write_val() with its current semantics. If we flip it around as in my examples above, the _val() prefix seems fine. Maybe write_reg() and read_reg()?
Quoted 9 lines
rust/kernel/io.rs +9
-0+ where + L: IoLoc<T>, + V: IntoIoVal<T, L>, + Self: IoKnownSize + IoCapable<L::IoType>, + { +let (location, value) = value.into_io_val (); + + self.write (location, value) + }
Gary Guo
reviewerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 23 lines · Danilo Krummrich
Quoted 6 lines · Alexandre Courbot
rust/kernel/io.rs +6
-0+/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// rust/kernel/io.rs fn write<T, L>(&self, location: L, value: T) · line 619
Quoted 10 lines
rust/kernel/io.rs +10
-0+/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V )Still not super satisfied with the name
write_val()plus I have some more considerations, sorry. :)Let's look at this:
Quoted 8 lines
let reg = bar.read(regs::NV_PMC_BOOT_0); // Pass around, do some modifications, etc. bar.write_val(reg);In this case
read()returns an object that encodes the absolute location and value, i.e.read()pairs withwrite_val(), which is a bit odd.
I mean, it also pairs with bar.write(regs::NV_PMC_BOOT_0, reg), so it's not totally odd. We just need to teach that "write_val" infers the register location from value.
Quoted 21 lines
In this example:
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // Pass around, do some modifications, etc. bar.write(WithBase::of::<E>(), reg);
read()pairs withwrite(), since the object returned byread()does only encode a relative location, so we have to supply the base location through the first argument ofwrite().Well, technically it also pairs with
write_val(), as we could also pass this as tuple towrite_val().bar.write_val((WithBase::of::<E>(), reg));However, my point is that this is a bit inconsistent and I think a user would expect something more symmetric.
Quoted 8 lines
For instance, let's say
write()would become the single argument one, thenread()could return an impl of IntoIoVal, so we would havelet reg = bar.read(regs::NV_PMC_BOOT_0); bar.write(reg); let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write(reg);
How would you modify the value then? reg becomes a combined pair with both location and value, and we would start need to use a closure to mutate inner values again, which in my opinion is bad.
This would again become the IoWrite design of the last iteration which is the part that I disliked most.
Quoted 20 lines
and additionally we can have
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(WithBase::of::<E>(), val);The same goes for
let val = bar.read_val(regs::NV_PMC_BOOT_0); bar.write_val(regs::NV_PMC_BOOT_0, val);which for complex values does not achieve anything, but makes sense for the FIFO register use-case, as val could also be a primitive, e.g. u32.
With a dynamic base, and a single field we could just do the following to support such primitives:
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(regs::NV_PFALCON_FALCON_RM::of::<E>(), val);
Quoted 6 lines
I think adding this symmetry should be trivial, as most of this already compiles with the current code.
Also, let's not get into a discussion whether we name on or the other
write()vs.write_foo(). I just turned it around as I think with the specific namewrite_val()it makes more sense this way around.
To me flipping this around is the odd one. If this is flipped around then this should be named write_at, but then it becomes odd as it is the dual of read and we won't have read_at.
Best,
Gary
Quoted 17 lines
But I'm perfectly happy either way as long as we find descriptive names that actually make sense.
Unfortunately, I can't really think of a good name for
write_val()with its current semantics. If we flip it around as in my examples above, the_val()prefix seems fine. Maybewrite_reg()andread_reg()?Quoted 9 lines
rust/kernel/io.rs +9
-0+ where + L: IoLoc<T>, + V: IntoIoVal<T, L>, + Self: IoKnownSize + IoCapable<L::IoType>, + { +let (location, value) = value.into_io_val (); + + self.write (location, value) + }
Danilo Krummrich
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 26 lines · Gary Guo
Quoted 25 lines · Danilo Krummrich
Quoted 6 lines · Alexandre Courbot
rust/kernel/io.rs +6
-0+/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// rust/kernel/io.rs fn write<T, L>(&self, location: L, value: T) · line 619
Quoted 10 lines
rust/kernel/io.rs +10
-0+/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V )Still not super satisfied with the name
write_val()plus I have some more considerations, sorry. :)Let's look at this:
let reg = bar.read(regs::NV_PMC_BOOT_0);
Quoted 8 lines
Quoted 6 lines
// Pass around, do some modifications, etc. bar.write_val(reg);In this case
read()returns an object that encodes the absolute location and value, i.e.read()pairs withwrite_val(), which is a bit odd.I mean, it also pairs with
bar.write(regs::NV_PMC_BOOT_0, reg), so it's not
s/also pairs with/also works with/
Quoted 30 lines
totally odd. We just need to teach that "
write_val" infers the register location from value.Quoted 27 lines
In this example:
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // Pass around, do some modifications, etc. bar.write(WithBase::of::<E>(), reg);
read()pairs withwrite(), since the object returned byread()does only encode a relative location, so we have to supply the base location through the first argument ofwrite().Well, technically it also pairs with
write_val(), as we could also pass this as tuple towrite_val().bar.write_val((WithBase::of::<E>(), reg));However, my point is that this is a bit inconsistent and I think a user would expect something more symmetric.
For instance, let's say
write()would become the single argument one, thenread()could return an impl of IntoIoVal, so we would havelet reg = bar.read(regs::NV_PMC_BOOT_0); bar.write(reg);
Quoted 6 lines
Quoted 2 lines
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write(reg);How would you modify the value then?
regbecomes a combined pair with both location and value, and we would start need to use a closure to mutate inner values again, which in my opinion is bad.
IIUC, the return value could be a generic tuple struct with <L: IoLoc<T>, V:
IntoIoVal<T, L>> that dereferences to V?
I.e. the current write_val() already allows this:
bar.write_val((WithBase::of::<E>(), reg))
so, a corresponding read_val() - both write_val() and read_val() should really have different names - could return the same thing, just as a generic type that dereferences to self.1.
With this you could do
let reg = bar.read_reg(regs::NV_PFALCON_FALCON_RM::of::<E>()); reg.modify(); bar.write_reg(reg);
without repeating the of::<E>() part while
let val = regs::NV_PFALCON_FALCON_RM::zeroed(); // Set a couple of fields. bar.write(WithBase::of::<E>(), val);
is still possible.
Quoted 26 lines
This would again become the
IoWritedesign of the last iteration which is the part that I disliked most.Quoted 23 lines
and additionally we can have
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(WithBase::of::<E>(), val);The same goes for
let val = bar.read_val(regs::NV_PMC_BOOT_0); bar.write_val(regs::NV_PMC_BOOT_0, val);which for complex values does not achieve anything, but makes sense for the FIFO register use-case, as val could also be a primitive, e.g. u32.
With a dynamic base, and a single field we could just do the following to support such primitives:
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(regs::NV_PFALCON_FALCON_RM::of::<E>(), val);I think adding this symmetry should be trivial, as most of this already compiles with the current code.
Quoted 7 lines
Quoted 3 lines
Also, let's not get into a discussion whether we name on or the other
write()vs.write_foo(). I just turned it around as I think with the specific namewrite_val()it makes more sense this way around.To me flipping this around is the odd one. If this is flipped around then this should be named
write_at, but then it becomes odd as it is the dual ofreadand we won't haveread_at.
That's why I said I only flipped it because write_val() is an odd name for what it does currently. Please also note the below.
Quoted 16 lines
Quoted 16 lines
But I'm perfectly happy either way as long as we find descriptive names that actually make sense.
Unfortunately, I can't really think of a good name for
write_val()with its current semantics. If we flip it around as in my examples above, the_val()prefix seems fine. Maybewrite_reg()andread_reg()?Quoted 9 lines
rust/kernel/io.rs +9
-0+ where + L: IoLoc<T>, + V: IntoIoVal<T, L>, + Self: IoKnownSize + IoCapable<L::IoType>, + { +let (location, value) = value.into_io_val (); + + self.write (location, value) + }
Alexandre Courbot
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
On Wed Mar 11, 2026 at 10:25 PM JST, Danilo Krummrich wrote:
<snip>
Quoted 11 lines
IIUC, the return value could be a generic tuple struct with <L: IoLoc<T>, V:
IntoIoVal<T, L>> that dereferences to V?I.e. the current
write_val()already allows this:bar.write_val((WithBase::of::<E>(), reg))so, a corresponding
read_val()- bothwrite_val()andread_val()should really have different names - could return the same thing, just as a generic type that dereferences to self.1.
Quoted 5 lines
With this you could do
let reg = bar.read_reg(regs::NV_PFALCON_FALCON_RM::of::<E>()); reg.modify();
That's the tricky part - the register methods don't modify in-place, they return a new value. I don't see how we could avoid a closure (and mutable variables) here.
Alexandre Courbot
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
In reply to Danilo KrummrichQuoted 74 lines · Danilo Krummrich
Quoted 6 lines · Alexandre Courbot
rust/kernel/io.rs +6
-0+/// Generic infallible write of value bearing its location, with compile-time bounds check. +/// +/// # Examples +/// +/// Tuples carrying a location and a value can be used with this method: +/// rust/kernel/io.rs fn write<T, L>(&self, location: L, value: T) · line 619
Quoted 10 lines
rust/kernel/io.rs +10
-0+/// ```no_run +/// use kernel::io::{Io, Mmio}; +/// +/// fn do_writes(io: &Mmio) { +/// // 32-bit write of value `1` at address `0x10`. +/// io.write_val((0x10, 1u32)); +/// } +/// ``` +#[inline(always)] +fn write_val <T ,L ,V >(&self, value:V )Still not super satisfied with the name
write_val()plus I have some more considerations, sorry. :)Let's look at this:
let reg = bar.read(regs::NV_PMC_BOOT_0); // Pass around, do some modifications, etc. bar.write_val(reg);In this case
read()returns an object that encodes the absolute location and value, i.e.read()pairs withwrite_val(), which is a bit odd.In this example:
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // Pass around, do some modifications, etc. bar.write(WithBase::of::<E>(), reg);
read()pairs withwrite(), since the object returned byread()does only encode a relative location, so we have to supply the base location through the first argument ofwrite().Well, technically it also pairs with
write_val(), as we could also pass this as tuple towrite_val().bar.write_val((WithBase::of::<E>(), reg));However, my point is that this is a bit inconsistent and I think a user would expect something more symmetric.
For instance, let's say
write()would become the single argument one, thenread()could return an impl of IntoIoVal, so we would havelet reg = bar.read(regs::NV_PMC_BOOT_0); bar.write(reg); let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write(reg);and additionally we can have
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(WithBase::of::<E>(), val);The same goes for
let val = bar.read_val(regs::NV_PMC_BOOT_0); bar.write_val(regs::NV_PMC_BOOT_0, val);which for complex values does not achieve anything, but makes sense for the FIFO register use-case, as val could also be a primitive, e.g. u32.
Quoted 8 lines
With a dynamic base, and a single field we could just do the following to support such primitives:
let val = bar.read_val(regs::NV_PFALCON_FALCON_RM::of::<E>()); bar.write_val(regs::NV_PFALCON_FALCON_RM::of::<E>(), val);I think adding this symmetry should be trivial, as most of this already compiles with the current code.
Not quite, if I understood your idea correctly.
The new read would need to return some new type (except for fixed offset registers) that contains the corresponding IoLoc, creating overhead for the default I/O methods (so at the very least, I think they should be the ones with the suffix). Accessing the value of that new type would require some indirection, and probably the return of closures. And having two pairs of read/write methods that work eerily similarly but are marginally distinct sounds to me like it could itself become a source of confusion.
Quoted 11 lines
Also, let's not get into a discussion whether we name on or the other
write()vs.write_foo(). I just turned it around as I think with the specific namewrite_val()it makes more sense this way around.But I'm perfectly happy either way as long as we find descriptive names that actually make sense.
Unfortunately, I can't really think of a good name for
write_val()with its current semantics. If we flip it around as in my examples above, the_val()prefix seems fine. Maybewrite_reg()andread_reg()?
The fact is, there is a symmetry between read and write:
- read takes a location and returns a value,
- write takes a location and a value.
write_val is really nothing but a convenience shortcut that has technically no strong reason to exist. As Gary pointed out, the counterpart of
let reg = bar.read(regs::NV_PMC_BOOT_0);
is
bar.write(regs::NV_PMC_BOOT_0, reg);
... and we introduced write_val for those cases where the value in itself provides its location, as NV_PMC_BOOT_0 is redundant. But the above statement could also be written:
bar.write((), reg);
which is exactly the same length as the write_val equivalent - it's just that you need to remember that () can be used in this case. But if you can remember that your register type can be used with write_val, then why not this? This actually makes me doubt that write_val is needed at all, and if we get rid of it, then we have a symmetric API.
We were so focused on this single issue for the last few revisions that the single-argument write variant sounded like the only way to handle this properly, but the () use proposed by Gary actually fulfills the same role and doesn't introduce more burden when you think of it.
So why not try without write_val at first? We can always add it later if we feel the need (and the same applies to a (location, value) symmetric read/write API).
And most importantly, that way we also don't have to worry about its name. :)
Danilo Krummrich
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 4 lines · Alexandre Courbot
The fact is, there is a symmetry between
readandwrite:-
readtakes a location and returns a value,
-writetakes a location and a value.
This is not entirely true.
read() takes an absolute location and returns something that encodes the value and a relative location, where for fixed registers the relative location is equivalent to an absolute location.
write() works with both an absolute location and something that encodes the value and a relative location, or a base location and something that encodes the value and a relative location.
// `reg` encodes the value and an absolute location. let reg = bar.read(regs::NV_PMC_BOOT_0); // `reg` encodes the value and a relative location. let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // First argument is an absolute location, second argument is a type // that encodes a value and a relative location. bar.write(regs::NV_PFALCON_FALCON_RM::of::<E>(), reg); // First argument is a base location that infers the relative location // from `reg`. bar.write(WithBase::of::<E>(), reg);
And yes, I am aware that the above wording around the difference between regs::NV_PFALCON_FALCON_RM::of::<E>() and WithBase::of::<E>() is at least a bit vague technically, but my point is about how this appears to users.
In any case, the fact that you can write WithBase::of::<E>() as a location argument in the first place proves that reg is not *only* a value.
fn write<T, L>(&self, location: L, value: T) where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,
Which is the reason why L: IoLoc<T>, i.e. the relative location is on T, not on L.
So, what you could say is
- read() takes an absolute location and returns something that encodes a value and relative location
- write() takes a base location (or absolute location) and something that encodes a value and relative location
But then there is the case with fixed registers that simply do not have a base, but write() still asks for a base (or absolute) location.
Quoted 9 lines
write_valis really nothing but a convenience shortcut that has technically no strong reason to exist. As Gary pointed out, the counterpart oflet reg = bar.read(regs::NV_PMC_BOOT_0);is
bar.write(regs::NV_PMC_BOOT_0, reg);
I do not agree for the reasons mentioned above.
In this case read() returns (location + value), while write() asks for location *and* (location + value), i.e. there is no base location for fixed registers.
Quoted 5 lines
... and we introduced
write_valfor those cases where the value in itself provides its location, asNV_PMC_BOOT_0is redundant. But the above statement could also be written:bar.write((), reg);
This makes more sense, as one could argue that a fixed register still requires a base location, which is just always zero, but why would we bother users with this implementation detail?
Is this really less confusing than an additional bar.write_reg(reg) that just works with any register?
Quoted 6 lines
which is exactly the same length as the
write_valequivalent - it's just that you need to remember that()can be used in this case. But if you can remember that your register type can be used withwrite_val, then why not this? This actually makes me doubt thatwrite_valis needed at all, and if we get rid of it, then we have a symmetric API.
Still not symmetric, and I also don't think we will have a lot of fun explaining people why they have to call it as bar.write((), reg). :(
OOC, how would you explain it when the question is raised without arguing with implementation details?
Quoted 8 lines
We were so focused on this single issue for the last few revisions that the single-argument write variant sounded like the only way to handle this properly, but the
()use proposed by Gary actually fulfills the same role and doesn't introduce more burden when you think of it.So why not try without
write_valat first? We can always add it later if we feel the need (and the same applies to a(location, value)symmetric read/write API).
If you really think it's the best solution, I'm fine picking it up this way for now, but to me it still sounds like we have no solution for a very simple case that does not at least raise an eyebrow.
Quoted 2 lines
And most importantly, that way we also don't have to worry about its name. :)
Gary Guo
reviewerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 11 lines · Danilo Krummrich
Quoted 4 lines · Alexandre Courbot
The fact is, there is a symmetry between
readandwrite:-
readtakes a location and returns a value,
-writetakes a location and a value.This is not entirely true.
read()takes an absolute location and returns something that encodes the value and a relative location, where for fixed registers the relative location is equivalent to an absolute location.
The value returned by read does not encode relative location. If a primitive is returned (of course, this is not currently supported by the register! macro) for the FIFO register case, the returned integer has no location informaiton whatsoever. What encodes the relative location is the type itself.
If you just construct the value yourself without using read, you can also use write_val or bar.write(WithBase...).
Quoted 19 lines
write()works with both an absolute location and something that encodes the value and a relative location, or a base location and something that encodes the value and a relative location.// `reg` encodes the value and an absolute location. let reg = bar.read(regs::NV_PMC_BOOT_0); // `reg` encodes the value and a relative location. let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // First argument is an absolute location, second argument is a type // that encodes a value and a relative location. bar.write(regs::NV_PFALCON_FALCON_RM::of::<E>(), reg); // First argument is a base location that infers the relative location // from `reg`. bar.write(WithBase::of::<E>(), reg);
Quoted 3 lines
And yes, I am aware that the above wording around the difference between regs::NV_PFALCON_FALCON_RM::of::<E>() and WithBase::of::<E>() is at least a bit vague technically, but my point is about how this appears to users.
The latter is just a type inferred version of the former, to avoid having you to write the name twice. They're exactly the same.
Quoted 3 lines
In any case, the fact that you can write WithBase::of::<E>() as a location argument in the first place proves that
regis not *only* a value.
Not true as discussed above.
Quoted 8 lines
fn write<T, L>(&self, location: L, value: T) where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,Which is the reason why L: IoLoc<T>, i.e. the relative location is on T, not on L.
The location has nothing to do with value, just the type T.
Quoted 8 lines
So, what you could say is
-
read()takes an absolute location and returns something that encodes a value and relative location-
write()takes a base location (or absolute location) and something that encodes a value and relative location
Only location gives you the location. Value has nothing to do with locations at all. Type inference does the trick.
Best,
Gary
Quoted 60 lines
But then there is the case with fixed registers that simply do not have a base, but
write()still asks for a base (or absolute) location.Quoted 9 lines
write_valis really nothing but a convenience shortcut that has technically no strong reason to exist. As Gary pointed out, the counterpart oflet reg = bar.read(regs::NV_PMC_BOOT_0);is
bar.write(regs::NV_PMC_BOOT_0, reg);I do not agree for the reasons mentioned above.
In this case
read()returns (location + value), whilewrite()asks for location *and* (location + value), i.e. there is no base location for fixed registers.Quoted 5 lines
... and we introduced
write_valfor those cases where the value in itself provides its location, asNV_PMC_BOOT_0is redundant. But the above statement could also be written:bar.write((), reg);This makes more sense, as one could argue that a fixed register still requires a base location, which is just always zero, but why would we bother users with this implementation detail?
Is this really less confusing than an additional
bar.write_reg(reg)that just works with any register?Quoted 6 lines
which is exactly the same length as the
write_valequivalent - it's just that you need to remember that()can be used in this case. But if you can remember that your register type can be used withwrite_val, then why not this? This actually makes me doubt thatwrite_valis needed at all, and if we get rid of it, then we have a symmetric API.Still not symmetric, and I also don't think we will have a lot of fun explaining people why they have to call it as
bar.write((), reg). :(OOC, how would you explain it when the question is raised without arguing with implementation details?
Quoted 8 lines
We were so focused on this single issue for the last few revisions that the single-argument write variant sounded like the only way to handle this properly, but the
()use proposed by Gary actually fulfills the same role and doesn't introduce more burden when you think of it.So why not try without
write_valat first? We can always add it later if we feel the need (and the same applies to a(location, value)symmetric read/write API).If you really think it's the best solution, I'm fine picking it up this way for now, but to me it still sounds like we have no solution for a very simple case that does not at least raise an eyebrow.
Quoted 2 lines
And most importantly, that way we also don't have to worry about its name. :)
Danilo Krummrich
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 11 lines · Gary Guo
Quoted 8 lines · Danilo Krummrich
fn write<T, L>(&self, location: L, value: T) where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,Which is the reason why L: IoLoc<T>, i.e. the relative location is on T, not on L.
The location has nothing to do with
value, just the typeT.
(Cutting all the above, since it all boils down to the same thing.)
So, that's what I mean, the relative location is on type T (the value type), not on L (the location type), hence T can't just be an arbitrary primitive, no?
Quoted 10 lines
Quoted 7 lines
So, what you could say is
-
read()takes an absolute location and returns something that encodes a value and relative location-
write()takes a base location (or absolute location) and something that encodes a value and relative locationOnly
locationgives you the location. Value has nothing to do with locations at all. Type inference does the trick.
The value does have something to do with the relative location, as it comes from the value type. You can't pass an "independent" value whose type does not carry location information, can you?
Gary Guo
reviewerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 11 lines · Danilo Krummrich
Quoted 10 lines · Gary Guo
Quoted 8 lines · Danilo Krummrich
fn write<T, L>(&self, location: L, value: T) where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,Which is the reason why L: IoLoc<T>, i.e. the relative location is on T, not on L.
Quoted 6 lines
Quoted 1 line
The location has nothing to do with
value, just the typeT.(Cutting all the above, since it all boils down to the same thing.)
So, that's what I mean, the relative location is on type T (the value type), not on L (the location type), hence T can't just be an arbitrary primitive, no?
The location is on the trait impl of L, it just may depend on T.
For a register location, say, UART_TX, it is itself contain full information on location; the IoLoc<u8> impl of it would be just used to constrain the type so that no other types than u8 gets used.
Yes, for the case of () or WithBase, it is itself only partial information and the location is only complete with an associated type. But this is more just a type-system trick so that we can avoid spelling out the full register name.
For the write_val case for a bitfield, I would basically consider the canonical way of doing a register write is
bar.write(REGISTER_NAME, bitfield)
value. Where
bar.write((), bitfield)
or (write_val) is a nice sugar to avoid writing the name multiple times.
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
So, what you could say is
-
read()takes an absolute location and returns something that encodes a value and relative location-
write()takes a base location (or absolute location) and something that encodes a value and relative location
Quoted 6 lines
Quoted 2 lines
Only
locationgives you the location. Value has nothing to do with locations at all. Type inference does the trick.The value does have something to do with the relative location, as it comes from the value type. You can't pass an "independent" value whose type does not carry location information, can you?
You can also not pass an "independent" value to register of a different type. With my FIFO example, you cannot write
bar.write(UART_TX, 0u32)
because UART_TX: IoLoc<u8> only. It doesn't mean that the 0u32 suddenly start carrying location information.
I just view this as type system working as designed.
Best,
Gary
Alexandre Courbot
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
In reply to Danilo KrummrichQuoted 11 lines · Danilo Krummrich
Quoted 4 lines · Alexandre Courbot
The fact is, there is a symmetry between
readandwrite:-
readtakes a location and returns a value,
-writetakes a location and a value.This is not entirely true.
read()takes an absolute location and returns something that encodes the value and a relative location, where for fixed registers the relative location is equivalent to an absolute location.
Let's look at the prototype of read (inherited constraints in parentheses):
fn read<T, L>(&self, location: L) -> T
where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,
(L::IoType: Into<T> + From<T>,)It takes an absolute location and returns... something that can be converted to/from the I/O type. There is no mention of a relative location anywhere.
The very concept of a relative location is local to the register module. read doesn't care about this at all. It just so happens that register do carry that information in their type - but that's not a requirement of the read/write I/O API.
Quoted 4 lines
write()works with both an absolute location and something that encodes the value and a relative location, or a base location and something that encodes the value and a relative location.
Again, looking at the prototype for write:
fn write<T, L>(&self, location: L, value: T)
where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,
(L::IoType: Into<T> + From<T>,)
The first argument is an absolute location. The second argument is just a value - there is no requirement for any kind of partial location information.
It is true that in the case of registers, we can use the second argument to infer a generic parameter of the first that is needed to build that absolute location, which makes the first argument look as if it contained partial location information, but that's just because the *register* module defines this relationship between its own location and value types (and the compiler is nice enough to connect the dots for us). This is again not the work of the read/write I/O API.
So we really have this:
- read(location) -> value
- write(location, value)
Otherwise we couldn't use primitive types with read/write, since they don't carry any location information by themselves.
Quoted 15 lines
// `reg` encodes the value and an absolute location. let reg = bar.read(regs::NV_PMC_BOOT_0); // `reg` encodes the value and a relative location. let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // First argument is an absolute location, second argument is a type // that encodes a value and a relative location. bar.write(regs::NV_PFALCON_FALCON_RM::of::<E>(), reg); // First argument is a base location that infers the relative location // from `reg`. bar.write(WithBase::of::<E>(), reg);
Quoted 6 lines
And yes, I am aware that the above wording around the difference between regs::NV_PFALCON_FALCON_RM::of::<E>() and WithBase::of::<E>() is at least a bit vague technically, but my point is about how this appears to users.
In any case, the fact that you can write WithBase::of::<E>() as a location argument in the first place proves that
regis not *only* a value.
But that is only true in the case of registers. The I/O module can and does cover things other than registers - currently primitive values, but we might want to extend that in future (don't ask me with what, but I don't see a reason to close the possibility :)).
Quoted 39 lines
fn write<T, L>(&self, location: L, value: T) where
L: IoLoc<T>,
Self: IoKnownSize + IoCapable<L::IoType>,Which is the reason why L: IoLoc<T>, i.e. the relative location is on T, not on L.
So, what you could say is
-
read()takes an absolute location and returns something that encodes a value and relative location-
write()takes a base location (or absolute location) and something that encodes a value and relative locationBut then there is the case with fixed registers that simply do not have a base, but
write()still asks for a base (or absolute) location.Quoted 9 lines
write_valis really nothing but a convenience shortcut that has technically no strong reason to exist. As Gary pointed out, the counterpart oflet reg = bar.read(regs::NV_PMC_BOOT_0);is
bar.write(regs::NV_PMC_BOOT_0, reg);I do not agree for the reasons mentioned above.
In this case
read()returns (location + value), whilewrite()asks for location *and* (location + value), i.e. there is no base location for fixed registers.Quoted 4 lines
... and we introduced
write_valfor those cases where the value in itself provides its location, asNV_PMC_BOOT_0is redundant. But the above statement could also be written:
Quoted 8 lines
Quoted 1 line
bar.write((), reg);This makes more sense, as one could argue that a fixed register still requires a base location, which is just always zero, but why would we bother users with this implementation detail?
Is this really less confusing than an additional
bar.write_reg(reg)that just works with any register?
I don't think it is less or more confusing, in the end they are really equivalent.
What I would like to avoid is having register-specific functions spill into the io module. I mean, I am not strictly opposed to it if we reach the conclusion that it is more convenient to users - in this case we could add an impl Io block in register.rs and add a write_reg method (and possibly a read variant returning the full position information?). But if we can just use the same 2 methods everywhere, that's better IMHO.
Quoted 8 lines
Quoted 7 lines
which is exactly the same length as the
write_valequivalent - it's just that you need to remember that()can be used in this case. But if you can remember that your register type can be used withwrite_val, then why not this? This actually makes me doubt thatwrite_valis needed at all, and if we get rid of it, then we have a symmetric API.
Quoted 5 lines
Still not symmetric, and I also don't think we will have a lot of fun explaining people why they have to call it as
bar.write((), reg). :(OOC, how would you explain it when the question is raised without arguing with implementation details?
This seems to indicate that instead of a Io::write_val method in io.rs, we might need a Io::write_reg method in register.rs that is dedicated to writing unambiguous registers exclusively. How does that sound to you?
Quoted 6 lines
Quoted 6 lines
We were so focused on this single issue for the last few revisions that the single-argument write variant sounded like the only way to handle this properly, but the
()use proposed by Gary actually fulfills the same role and doesn't introduce more burden when you think of it.
Quoted 7 lines
Quoted 3 lines
So why not try without
write_valat first? We can always add it later if we feel the need (and the same applies to a(location, value)symmetric read/write API).If you really think it's the best solution, I'm fine picking it up this way for now, but to me it still sounds like we have no solution for a very simple case that does not at least raise an eyebrow.
I think the current read and write methods are going to stay the basis of I/O, so I'm pretty confident we can commit to them. They also allow to do everything we want to do with registers. So my suggestion would be to see how it goes and add functionality as we get feedback and more visibility into how the API is used.
After reading your reply I believe an Io::write_reg in register.rs could solve the problem of writing fixed offset registers without making a single-argument write part of the core I/O API (and save the trouble of finding a generic-enough name for it!). It's just not clear to me that we should add this right now - but I can of course do it in the next revision if you think the idea is good.
Danilo Krummrich
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
Quoted 9 lines · Alexandre Courbot
Quoted 6 lines · Danilo Krummrich
And yes, I am aware that the above wording around the difference between regs::NV_PFALCON_FALCON_RM::of::<E>() and WithBase::of::<E>() is at least a bit vague technically, but my point is about how this appears to users.
In any case, the fact that you can write WithBase::of::<E>() as a location argument in the first place proves that
regis not *only* a value.But that is only true in the case of registers.
Agree with this and all the above. But - and this is why I wrote "my point is about how this appears to users" - users use this API with registers only and except for the FIFO use-case, which is not implemented yet, it is obvious to users that part of the location comes from the value type.
I'm not saying that this is a problem. Actually, quite the opposite.
When I proposed the register!() macro, one of the problems I wanted to solve was that people can't read from a certain location and accidentally treat it as something semantically different.
Or in other words, if you want to read register A, you shouldn't be able to accidentally read from B and treat it as A.
Quoted 3 lines
The I/O module can and does cover things other than registers - currently primitive values, but we might want to extend that in future (don't ask me with what, but I don't see a reason to close the possibility :)).
Neither do I. :)
But, as mentioned above, we should be aware that people notice that for registers part of the location information comes from the value type (except for the FIFO case of course) and registers are the thing that people deal with most.
Other use-cases such as I/O memcpy, etc. will be accssible through other APIs, such as IoSlice, or more generally, IoView.
Having that said, my point is that considering the use-cases it also makes sense to think about how this API will be perceived.
And from this context something like bar.write((), reg) looks pretty odd.
Quoted 5 lines
Quoted 2 lines
Is this really less confusing than an additional
bar.write_reg(reg)that just works with any register?I don't think it is less or more confusing, in the end they are really equivalent.
From your point of view being an expert on the I/O and register!() implementation details, but please also consider the above.
Also, look at the Tyr patches for instance, they exclusively use write_val().
Quoted 7 lines
What I would like to avoid is having register-specific functions spill into the
iomodule. I mean, I am not strictly opposed to it if we reach the conclusion that it is more convenient to users - in this case we could add animpl Ioblock inregister.rsand add awrite_regmethod (and possibly areadvariant returning the full position information?). But if we can just use the same 2 methods everywhere, that's better IMHO.
Just leave it in the io module I'd say, register access is probably the most essential part of I/O, I think there is no need to factor it out.
Quoted 10 lines
Quoted 10 lines
Quoted 6 lines
which is exactly the same length as the
write_valequivalent - it's just that you need to remember that()can be used in this case. But if you can remember that your register type can be used withwrite_val, then why not this? This actually makes me doubt thatwrite_valis needed at all, and if we get rid of it, then we have a symmetric API.Still not symmetric, and I also don't think we will have a lot of fun explaining people why they have to call it as
bar.write((), reg). :(
Quoted 7 lines
Quoted 2 lines
OOC, how would you explain it when the question is raised without arguing with implementation details?
This seems to indicate that instead of a
Io::write_valmethod inio.rs, we might need aIo::write_regmethod inregister.rsthat is dedicated to writing unambiguous registers exclusively. How does that sound to you?
I don't see it adds any value to factor it out with an extention trait, rename to write_reg() seems fine.
Additionally, I'd like to leave it open for the future to add read_reg() method returning a generic (loc, val) tuple dereferencing to the value in case we see a repetition of the following pattern.
let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // modify reg bar.write(WithBase::of::<E>(), reg)
The reason is the same as mentioned above. In most cases drivers don't want to switch the base location between a read and a write, i.e. write the value from A to B.
The most common case is to read from A and write back to A. For instance, talking to the Tyr folks, they told me that for the array registers they will have, they will never have the case that they want to write a register value from A to B.
So, I still think it would be good to provide an option for drivers to prevent any mistakes in the first place.
Now, obviously this would require that we also provide register accessors that take a mutable reference for this to work, but that doesn't seem like a big deal.
I also don't think we have to do this now, but I'd like to have something like this in the future.
For now s/write_val/write_reg/ and we should be good to go. :)
Alexandre Courbot
maintainerRe: [PATCH v8 07/10] rust: io: introduce `IntoIoVal` trait and single-argument `write_val`
On Fri Mar 13, 2026 at 12:54 AM JST, Danilo Krummrich wrote:
<snip>
Quoted 31 lines
Quoted 10 lines
Quoted 10 lines
Quoted 6 lines
which is exactly the same length as the
write_valequivalent - it's just that you need to remember that()can be used in this case. But if you can remember that your register type can be used withwrite_val, then why not this? This actually makes me doubt thatwrite_valis needed at all, and if we get rid of it, then we have a symmetric API.Still not symmetric, and I also don't think we will have a lot of fun explaining people why they have to call it as
bar.write((), reg). :(Quoted 7 lines
Quoted 2 lines
OOC, how would you explain it when the question is raised without arguing with implementation details?
This seems to indicate that instead of a
Io::write_valmethod inio.rs, we might need aIo::write_regmethod inregister.rsthat is dedicated to writing unambiguous registers exclusively. How does that sound to you?I don't see it adds any value to factor it out with an extention trait, rename to
write_reg()seems fine.Additionally, I'd like to leave it open for the future to add
read_reg()method returning a generic (loc, val) tuple dereferencing to the value in case we see a repetition of the following pattern.let reg = bar.read(regs::NV_PFALCON_FALCON_RM::of::<E>()); // modify reg bar.write(WithBase::of::<E>(), reg)
Quoted 3 lines
The reason is the same as mentioned above. In most cases drivers don't want to switch the base location between a read and a write, i.e. write the value from A to B.
That's definitely a pattern we are seeing a lot already. I agree there is a use-case for that.
Quoted 9 lines
The most common case is to read from A and write back to A. For instance, talking to the Tyr folks, they told me that for the array registers they will have, they will never have the case that they want to write a register value from A to B.
So, I still think it would be good to provide an option for drivers to prevent any mistakes in the first place.
Quoted 6 lines
Now, obviously this would require that we also provide register accessors that take a mutable reference for this to work, but that doesn't seem like a big deal.
I also don't think we have to do this now, but I'd like to have something like this in the future.
There are several ways we can achieve this. One would be to use the macro to forward the bitfield setter methods to the containing type and return an updated one. Or, we implement Deref on the containing type, and add a set of set_<field> methods that modify the value in-place.
That way read_reg and write_reg should be symmetric and we remove another cause of typos and mistakes.
I'l start thinking about it once I post the extracted bitfield patches, as it makes it easier to look at the problem space.
Alexandre Courbot
maintainerPATCH v8 8/10 rust: io: add `register!` macro
In reply to Alexandre CourbotAdd 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 | 6 +- rust/kernel/io/register.rs | 1190 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1195 insertions(+), 1 deletion(-)
rust/kernel/io.rs +5 -1
@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;
@@ -179,7 +180,8 @@ pub trait IoCapable<T> {/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`] (and /// their fallible [`try_read`](Io::try_read), [`try_write`](Io::try_write) and /// [`try_update`](Io::try_update) counterparts) to work uniformly with both raw [`usize`] offsets -/// (for primitive types like [`u32`]) and typed ones. +/// (for primitive types like [`u32`]) and typed ones (like those generated by the [`register!`] +/// macro). /// /// An `IoLoc<T>` carries three pieces of information: ///
@@ -189,6 +191,8 @@ pub trait IoCapable<T> {/// /// `T` and `IoLoc::IoType` may differ: for instance, a typed register has `T` = the register type /// with its bitfields, and `IoType` = its backing primitive (e.g. `u32`). +/// +/// [`register!`]: kernel::register! pub trait IoLoc <T > {/// Size ([`u8`], [`u16`], etc) of the I/O performed on the returned [`offset`](IoLoc::offset). type IoType :Into <T > +From <T >;
rust/kernel/io/register.rs new file +1190 -0
1,190 lines not on this page · raw message
Signature · 1 line
2.53.0
Danilo Krummrich
maintainerRe: [PATCH v8 08/10] rust: io: add `register!` macro
rust/kernel/io/register.rs line 730
Quoted 2 lines · Alexandre Courbot
rust/kernel/io/register.rs new file +2
-0+#[macro_export] +macro_rules! register {
As discussed, maybe move some of the documentation to the module and keep the documentation on register!() itself a bit smaller focusing on how to use the macro itself.
Also, please add a pub use, re-export in rust/kernel/io.rs and refer to it as kernel::io::register.
Alexandre Courbot
maintainerPATCH v8 9/10 sample: rust: pci: use `register!` macro
In reply to Alexandre CourbotConvert the direct IO accesses to properly defined registers.
--- samples/rust/rust_driver_pci.rs | 84 +++++++++++++++++++++++++++++++---------- 1 file changed, 64 insertions(+), 20 deletions(-)
samples/rust/rust_driver_pci.rs +64 -20
@@ -8,27 +8,58 @@ device::Bound, device::Core, devres::Devres, - io::Io, + io::{ + register::Array, + Io, // + }, + num::Bounded, pci, prelude::*, + register, sync::aref::ARef, // }; -struct Regs ; +mod regs { +use super ::*; -impl Regs { -const TEST :usize =0x0 ; -const OFFSET :usize =0x4 ; -const DATA :usize =0x8 ; -const COUNT :usize =0xC ; -const END :usize =0x10 ; +register! { +pub (super )TEST (u8 ) @0x0 { +7 :0 index =>TestIndex ; + } + +pub (super )OFFSET (u32 ) @0x4 { +31 :0 offset; + } + +pub (super )DATA (u8 ) @0x8 { +7 :0 data; + } + +pub (super )COUNT (u32 ) @0xC { +31 :0 count; + } + } + +pub (super )const END :usize =0x10 ; } -type Bar0 = pci::Bar <{Regs ::END }>; +type Bar0 = pci::Bar <{ regs::END }>;#[derive( Copy , Clone , Debug )] struct TestIndex (u8 ); +impl From <Bounded <u8 ,8 >>for TestIndex { +fn from (value:Bounded <u8 ,8 >) ->Self { +Self (value.into ()) + } +} + +impl From <TestIndex >for Bounded <u8 ,8 > { +fn from (value:TestIndex ) ->Self { + value.0 .into () + } +} +impl TestIndex {const NO_EVENTFD :Self =Self (0 ); }
@@ -54,40 +85,53 @@ struct SampleDriver {impl SampleDriver {fn testdev (index: &TestIndex , bar: &Bar0 ) ->Result <u32 > {// Select the test. - bar.write8 (index.0 ,Regs ::TEST ); + bar.write_val (regs::TEST ::zeroed ().with_index (*index)); -let offset = bar.read32 (Regs ::OFFSET )as usize ; -let data = bar.read8 (Regs ::DATA ); +let offset = bar.read (regs::OFFSET ).into_raw ()as usize ; +let data = bar.read (regs::DATA ).into ();// Write `data` to `offset` to increase `count` by one. // // Note that we need `try_write8`, since `offset` can't be checked at compile-time. bar.try_write8 (data, offset)?; -Ok (bar.read32 (Regs ::COUNT )) +Ok (bar.read (regs::COUNT ).into ()) }fn config_space (pdev: &pci::Device <Bound >) {let config = pdev.config_space (); -// TODO: use the register!() macro for defining PCI configuration space registers once it -// has been move out of nova-core. +// Some PCI configuration space registers. +register! { +VENDOR_ID (u16 ) @0x0 { +15 :0 vendor_id; + } + +REVISION_ID (u8 ) @0x8 { +7 :0 revision_id; + } + +BAR (u32 )[6 ] @0x10 { +31 :0 value; + } + } +dev_info! ( pdev,"pci-testdev config space read8 rev ID: {:x}\n" , - config.read8 (0x8 ) + config.read (REVISION_ID ).revision_id () );dev_info! ( pdev,"pci-testdev config space read16 vendor ID: {:x}\n" , - config.read16 (0 ) + config.read (VENDOR_ID ).vendor_id () );dev_info! ( pdev,"pci-testdev config space read32 BAR 0: {:x}\n" , - config.read32 (0x10 ) + config.read (BAR ::at (0 )).value () ); } }
@@ -111,7 +155,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Er pdev.set_master (); Ok(try_pin_init!(Self { - bar <- pdev.iomap_region_sized::<{ Regs::END }>(0, c"rust_driver_pci"), + bar <- pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_driver_pci"), index: *info, _: { let bar = bar.access(pdev.as_ref())?;
@@ -131,7 +175,7 @@ fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> impl PinInit<Self, Erfn unbind (pdev: &pci::Device <Core >, this:Pin <&Self >) {if let Ok (bar) = this.bar.access (pdev.as_ref ()) {// Reset pci-testdev by writing a new test index. - bar.write8 (this.index.0 ,Regs ::TEST ); + bar.write_val (regs::TEST ::zeroed ().with_index (this.index)); } } }
Signature · 1 line
2.53.0
Alexandre Courbot
maintainerPATCH v8 10/10 gpu: nova-core: use the kernel `register!` macro
In reply to Alexandre CourbotReplace 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 | 330 ++++----- drivers/gpu/nova-core/falcon/gsp.rs | 25 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 70 +- drivers/gpu/nova-core/falcon/hal/tu102.rs | 12 +- drivers/gpu/nova-core/falcon/sec2.rs | 17 +- drivers/gpu/nova-core/fb.rs | 6 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 37 +- drivers/gpu/nova-core/fb/hal/ga102.rs | 7 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 17 +- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 16 +- drivers/gpu/nova-core/gfw.rs | 11 +- drivers/gpu/nova-core/gpu.rs | 36 +- drivers/gpu/nova-core/gsp/boot.rs | 11 +- drivers/gpu/nova-core/gsp/cmdq.rs | 9 +- drivers/gpu/nova-core/regs.rs | 612 +++++++++-------- drivers/gpu/nova-core/regs/macros.rs | 739 --------------------- 16 files changed, 667 insertions(+), 1288 deletions(-)
drivers/gpu/nova-core/falcon.rs +165 -165
@@ -13,7 +13,12 @@ DmaAddress, DmaMask, // }, - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::{RegisterBase, WithBase}, + Io, + }, + num::Bounded, prelude::*, sync::aref::ARef, time::Delta,
@@ -30,7 +35,6 @@ IntoSafeCast, // }, regs, - regs::macros::RegisterBase, // };pub (crate )mod gsp;
@@ -41,11 +45,11 @@pub (crate )const MEM_BLOCK_ALIGNMENT :usize =256 ;// TODO[FPRI]: Replace with `ToPrimitive`. -macro_rules! impl_from_enum_to_u8 { - ($enum_type:ty) => { -impl From <$enum_type>for u8 { +macro_rules! impl_from_enum_to_bounded { + ($enum_type:ty, $length:literal) => { +impl From <$enum_type>for Bounded <u32 , $length> {fn from (value: $enum_type) ->Self { - valueas u8 +Bounded ::from_expr (valueas u32 ) } } };
@@ -53,10 +57,8 @@ fn from(value: $enum_type) -> Self {/// Revision number of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] /// register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] +#[derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] pub (crate )enum FalconCoreRev { -#[default] Rev1 =1 ,Rev2 =2 ,Rev3 =3 ,
@@ -65,16 +67,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,
@@ -91,46 +93,38 @@ fn try_from(value: u8) -> Result<Self> {/// Revision subversion number of a falcon core, used in the /// [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] +#[derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] pub (crate )enum FalconCoreRevSubversion { -#[default] Subversion0 =0 ,Subversion1 =1 ,Subversion2 =2 ,Subversion3 =3 , } -impl_from_enum_to_u8! (FalconCoreRevSubversion ); +impl_from_enum_to_bounded! (FalconCoreRevSubversion ,2 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconCoreRevSubversion { -type Error =Error ; - -fn try_from (value:u8 ) ->Result <Self > { +impl From <Bounded <u32 ,2 >>for FalconCoreRevSubversion { +fn from (value:Bounded <u32 ,2 >) ->Self {use FalconCoreRevSubversion ::*; -let sub_version =match value &0b11 { +match value.get () {0 =>Subversion0 ,1 =>Subversion1 ,2 =>Subversion2 ,3 =>Subversion3 , - _ =>return Err (EINVAL ), - }; - -Ok (sub_version) +// SAFETY: `value` comes from a 2-bit `Bounded`, and we just checked all possible +// values. + _ =>unsafe { core::hint::unreachable_unchecked () }, + } } } -/// Security model of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] -/// register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone )] /// Security mode of the Falcon microprocessor. /// /// See `falcon.rst` for more details. +#[derive( Debug , Copy , Clone )] pub (crate )enum FalconSecurityModel {/// Non-Secure: runs unsigned code without privileges. -#[default] None =0 ,/// Light-Secured (LS): Runs signed code with some privileges. /// Entry into this mode is only possible from 'Heavy-secure' mode, which verifies the code's
@@ -144,16 +138,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,
@@ -166,24 +160,22 @@ fn try_from(value: u8) -> Result<Self> {/// Signing algorithm for a given firmware, used in the [`crate::regs::NV_PFALCON2_FALCON_MOD_SEL`] /// register. It is passed to the Falcon Boot ROM (BROM) as a parameter. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq )] +#[derive( Debug , Copy , Clone , PartialEq , Eq )] pub (crate )enum FalconModSelAlgo {/// AES. -#[expect(dead_code)] Aes =0 ,/// RSA3K. -#[default] Rsa3k =1 , } -impl_from_enum_to_u8! (FalconModSelAlgo ); +impl_from_enum_to_bounded! (FalconModSelAlgo ,8 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconModSelAlgo { +impl TryFrom <Bounded <u32 ,8 >>for FalconModSelAlgo {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,8 >) ->Result <Self > { +match value.get () { +0 =>Ok (FalconModSelAlgo ::Aes ),1 =>Ok (FalconModSelAlgo ::Rsa3k ), _ =>Err (EINVAL ), }
@@ -191,21 +183,19 @@ fn try_from(value: u8) -> Result<Self> { }/// Valid values for the `size` field of the [`crate::regs::NV_PFALCON_FALCON_DMATRFCMD`] register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq )] +#[derive( Debug , Copy , Clone , PartialEq , Eq )] pub (crate )enum DmaTrfCmdSize {/// 256 bytes transfer. -#[default] Size256B =0x6 , } -impl_from_enum_to_u8! (DmaTrfCmdSize ); +impl_from_enum_to_bounded! (DmaTrfCmdSize ,3 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for DmaTrfCmdSize { +impl TryFrom <Bounded <u32 ,3 >>for DmaTrfCmdSize {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,3 >) ->Result <Self > { +match value.get () {0x6 =>Ok (Self ::Size256B ), _ =>Err (EINVAL ), }
@@ -213,33 +203,24 @@ fn try_from(value: u8) -> Result<Self> { }/// Currently active core on a dual falcon/riscv (Peregrine) controller. -#[derive( Debug , Clone , Copy , PartialEq , Eq , Default )] +#[derive( Debug , Clone , Copy , PartialEq , Eq )] pub (crate )enum PeregrineCoreSelect {/// Falcon core is active. -#[default] Falcon =0 ,/// RISC-V core is active. Riscv =1 , } +impl_from_enum_to_bounded! (PeregrineCoreSelect ,1 ); -impl From <bool >for PeregrineCoreSelect { -fn from (value:bool ) ->Self { -match value { +impl From <Bounded <u32 ,1 >>for PeregrineCoreSelect { +fn from (value:Bounded <u32 ,1 >) ->Self { +match bool::from (value) {false =>PeregrineCoreSelect ::Falcon ,true =>PeregrineCoreSelect ::Riscv , } } } -impl From <PeregrineCoreSelect >for bool { -fn from (value:PeregrineCoreSelect ) ->Self { -match value { -PeregrineCoreSelect ::Falcon =>false , -PeregrineCoreSelect ::Riscv =>true , - } - } -} -/// Different types of memory present in a falcon core. #[derive( Debug , Clone , Copy , PartialEq , Eq )] pub (crate )enum FalconMem {
@@ -255,10 +236,8 @@ pub(crate) enum FalconMem {/// Defines the Framebuffer Interface (FBIF) aperture type. /// This determines the memory type for external memory access during a DMA transfer, which is /// performed by the Falcon's Framebuffer DMA (FBDMA) engine. See falcon.rst for more details. -#[derive( Debug , Clone , Default )] +#[derive( Debug , Clone )] pub (crate )enum FalconFbifTarget { -/// VRAM. -#[default] /// Local Framebuffer (GPU's VRAM memory). LocalFb =0 ,/// Coherent system memory (System DRAM).
@@ -266,14 +245,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,
@@ -285,34 +264,25 @@ fn try_from(value: u8) -> Result<Self> { }/// Type of memory addresses to use. -#[derive( Debug , Clone , Default )] +#[derive( Debug , Clone )] pub (crate )enum FalconFbifMemType {/// Virtual memory addresses. -#[default] Virtual =0 ,/// Physical memory addresses. Physical =1 , } +impl_from_enum_to_bounded! (FalconFbifMemType ,1 );/// Conversion from a single-bit register field. -impl From <bool >for FalconFbifMemType { -fn from (value:bool ) ->Self { -match value { +impl From <Bounded <u32 ,1 >>for FalconFbifMemType { +fn from (value:Bounded <u32 ,1 >) ->Self { +match bool::from (value) {false =>Self ::Virtual ,true =>Self ::Physical , } } } -impl From <FalconFbifMemType >for bool { -fn from (value:FalconFbifMemType ) ->Self { -match value { -FalconFbifMemType ::Virtual =>false , -FalconFbifMemType ::Physical =>true , - } - } -} -/// Type used to represent the `PFALCON` registers address base for a given falcon engine. pub (crate )struct PFalconBase (());
@@ -321,13 +291,10 @@ fn from(value: FalconFbifMemType) -> Self {/// Trait defining the parameters of a given Falcon engine. /// -/// Each engine provides one base for `PFALCON` and `PFALCON2` registers. The `ID` constant is used -/// to identify a given Falcon instance with register I/O methods. +/// Each engine provides one base for `PFALCON` and `PFALCON2` registers. pub (crate )trait FalconEngine :Send +Sync +RegisterBase <PFalconBase > +RegisterBase <PFalcon2Base > +Sized { -/// Singleton of the engine, used to identify it with register I/O methods. -const ID :Self ; }/// Represents a portion of the firmware to be loaded into a particular memory (e.g. IMEM or DMEM)
@@ -521,8 +488,14 @@ pub(crate) fn new(dev: &device::Device, chipset: Chipset) -> Result<Self> {/// Resets DMA-related registers. pub (crate )fn dma_reset (&self, bar: &Bar0 ) { - regs::NV_PFALCON_FBIF_CTL ::update (bar, &E ::ID , |v| v.set_allow_phys_no_ctx (true )); - regs::NV_PFALCON_FALCON_DMACTL ::default ().write (bar, &E ::ID ); + bar.update (regs::NV_PFALCON_FBIF_CTL ::of ::<E >(), |v| { + v.with_allow_phys_no_ctx (true ) + }); + + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMACTL ::zeroed (), + ); }/// Reset the controller, select the falcon core, and wait for memory scrubbing to complete.
@@ -531,9 +504,10 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result { self.hal.select_core (self, bar)?; self.hal.reset_wait_mem_scrubbing (bar)?; - regs::NV_PFALCON_FALCON_RM ::default () - .set_value (regs::NV_PMC_BOOT_0 ::read (bar).into ()) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_RM ::from (bar.read (regs::NV_PMC_BOOT_0 ).into_raw ()), + );Ok (()) }
@@ -551,25 +525,27 @@ fn pio_wr_imem_slice(&self, bar: &Bar0, load_offsets: FalconPioImemLoadTarget<'_return Err (EINVAL ); } - regs::NV_PFALCON_FALCON_IMEMC ::default () - .set_secure (load_offsets.secure) - .set_aincw (true ) - .set_offs (load_offsets.dst_start) - .write (bar, &E ::ID ,Self ::PIO_PORT ); + bar.write ( +WithBase ::of ::<E >().at (Self ::PIO_PORT ), + regs::NV_PFALCON_FALCON_IMEMC ::zeroed () + .with_secure (load_offsets.secure) + .with_aincw (true ) + .with_offs (load_offsets.dst_start), + );for (n, block)in load_offsets.data.chunks (MEM_BLOCK_ALIGNMENT ).enumerate () {let n = u16::try_from (n)?;let tag:u16 = load_offsets.start_tag.checked_add (n).ok_or (ERANGE )?; - regs::NV_PFALCON_FALCON_IMEMT ::default ().set_tag (tag).write ( - bar, - &E ::ID , -Self ::PIO_PORT , + bar.write ( +WithBase ::of ::<E >().at (Self ::PIO_PORT ), + regs::NV_PFALCON_FALCON_IMEMT ::zeroed ().with_tag (tag), );for wordin block.chunks_exact (4 ) {let w = [word[0 ], word[1 ], word[2 ], word[3 ]]; - regs::NV_PFALCON_FALCON_IMEMD ::default () - .set_data (u32::from_le_bytes (w)) - .write (bar, &E ::ID ,Self ::PIO_PORT ); + bar.write ( +WithBase ::of ::<E >().at (Self ::PIO_PORT ), + regs::NV_PFALCON_FALCON_IMEMD ::zeroed ().with_data (u32::from_le_bytes (w)), + ); } }
@@ -586,16 +562,19 @@ fn pio_wr_dmem_slice(&self, bar: &Bar0, load_offsets: FalconPioDmemLoadTarget<'_return Err (EINVAL ); } - regs::NV_PFALCON_FALCON_DMEMC ::default () - .set_aincw (true ) - .set_offs (load_offsets.dst_start) - .write (bar, &E ::ID ,Self ::PIO_PORT ); + bar.write ( +WithBase ::of ::<E >().at (Self ::PIO_PORT ), + regs::NV_PFALCON_FALCON_DMEMC ::zeroed () + .with_aincw (true ) + .with_offs (load_offsets.dst_start), + );for wordin load_offsets.data.chunks_exact (4 ) {let w = [word[0 ], word[1 ], word[2 ], word[3 ]]; - regs::NV_PFALCON_FALCON_DMEMD ::default () - .set_data (u32::from_le_bytes (w)) - .write (bar, &E ::ID ,Self ::PIO_PORT ); + bar.write ( +WithBase ::of ::<E >().at (Self ::PIO_PORT ), + regs::NV_PFALCON_FALCON_DMEMD ::zeroed ().with_data (u32::from_le_bytes (w)), + ); }Ok (())
@@ -607,11 +586,14 @@ pub(crate) fn pio_load<F: FalconFirmware<Target = E> + FalconPioLoadable>( bar: &Bar0, fw: &F, ) -> Result { - regs::NV_PFALCON_FBIF_CTL::read(bar, &E::ID) - .set_allow_phys_no_ctx(true) - .write(bar, &E::ID); + bar.update(regs::NV_PFALCON_FBIF_CTL::of::<E>(), |v| { + v.with_allow_phys_no_ctx (true ) + }); - regs::NV_PFALCON_FALCON_DMACTL::default().write(bar, &E::ID); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMACTL ::zeroed (), + );if let Some (imem_ns) = fw.imem_ns_load_params () { self.pio_wr_imem_slice (bar, imem_ns)?;
@@ -623,9 +605,10 @@ pub(crate) fn pio_load<F: FalconFirmware<Target = E> + FalconPioLoadable>( self.hal.program_brom (self, bar, &fw.brom_params ())?; - regs::NV_PFALCON_FALCON_BOOTVEC ::default () - .set_value (fw.boot_addr ()) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()), + );Ok (()) }
@@ -694,36 +677,42 @@ fn dma_wr(// Set up the base source DMA address. - regs::NV_PFALCON_FALCON_DMATRFBASE ::default () -// CAST: `as u32` is used on purpose since we do want to strip the upper bits, which -// will be written to `NV_PFALCON_FALCON_DMATRFBASE1`. - .set_base ((dma_start >>8 )as u32 ) - .write (bar, &E ::ID ); - regs::NV_PFALCON_FALCON_DMATRFBASE1 ::default () -// CAST: `as u16` is used on purpose since the remaining bits are guaranteed to fit -// within a `u16`. - .set_base ((dma_start >>40 )as u16 ) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFBASE ::zeroed ().with_base ( +// CAST: `as u32` is used on purpose since we do want to strip the upper bits, +// which will be written to `NV_PFALCON_FALCON_DMATRFBASE1`. + (dma_start >>8 )as u32 , + ), + ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFBASE1 ::zeroed ().try_with_base (dma_start >>40 )?, + ); -let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::default () - .set_size (DmaTrfCmdSize ::Size256B ) +let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::zeroed () + .with_size (DmaTrfCmdSize ::Size256B ) .with_falcon_mem (target_mem);for posin (0 ..num_transfers).map (|i| i *DMA_LEN ) {// Perform a transfer of size `DMA_LEN`. - regs::NV_PFALCON_FALCON_DMATRFMOFFS ::default () - .set_offs (load_offsets.dst_start + pos) - .write (bar, &E ::ID ); - regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::default () - .set_offs (src_start + pos) - .write (bar, &E ::ID ); - cmd.write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFMOFFS ::zeroed () + .try_with_offs (load_offsets.dst_start + pos)?, + ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::zeroed ().with_offs (src_start + pos), + ); + + bar.write (WithBase ::of ::<E >(), cmd);// Wait for the transfer to complete. // TIMEOUT: arbitrarily large value, no DMA transfer to the falcon's small memories // should ever take that long. read_poll_timeout ( - ||Ok (regs::NV_PFALCON_FALCON_DMATRFCMD ::read (bar, &E ::ID )), + ||Ok (bar.read (regs::NV_PFALCON_FALCON_DMATRFCMD ::of ::<E >())), |r| r.idle (),Delta ::ZERO , Delta::from_secs(2),
@@ -744,9 +733,9 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(let dma_obj =DmaObject ::from_data (dev, fw.as_slice ())?; self.dma_reset (bar); - regs::NV_PFALCON_FBIF_TRANSCFG ::update (bar, &E ::ID ,0 , |v| { - v.set_target (FalconFbifTarget ::CoherentSysmem ) - .set_mem_type (FalconFbifMemType ::Physical ) + bar.update (regs::NV_PFALCON_FBIF_TRANSCFG ::of ::<E >().at (0 ), |v| { + v.with_target (FalconFbifTarget ::CoherentSysmem ) + .with_mem_type (FalconFbifMemType ::Physical ) }); self.dma_wr(
@@ -760,9 +749,10 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>( self.hal.program_brom (self, bar, &fw.brom_params ())?;// Set `BootVec` to start of non-secure code. - regs::NV_PFALCON_FALCON_BOOTVEC ::default () - .set_value (fw.boot_addr ()) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()), + );Ok (()) }
@@ -771,7 +761,7 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(pub (crate )fn wait_till_halted (&self, bar: &Bar0 ) ->Result <()> {// TIMEOUT: arbitrarily large value, firmwares should complete in less than 2 seconds. read_poll_timeout ( - ||Ok (regs::NV_PFALCON_FALCON_CPUCTL ::read (bar, &E ::ID )), + ||Ok (bar.read (regs::NV_PFALCON_FALCON_CPUCTL ::of ::<E >())), |r| r.halted (),Delta ::ZERO , Delta::from_secs(2),
@@ -782,13 +772,18 @@ pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> Result<()> {/// Start the falcon CPU. pub (crate )fn start (&self, bar: &Bar0 ) ->Result <()> { -match regs::NV_PFALCON_FALCON_CPUCTL ::read (bar, &E ::ID ).alias_en () { -true => regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::default () - .set_startcpu (true ) - .write (bar, &E ::ID ), -false => regs::NV_PFALCON_FALCON_CPUCTL ::default () - .set_startcpu (true ) - .write (bar, &E ::ID ), +match bar + .read (regs::NV_PFALCON_FALCON_CPUCTL ::of ::<E >()) + .alias_en () + { +true => bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::zeroed ().with_startcpu (true ), + ), +false => bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_CPUCTL ::zeroed ().with_startcpu (true ), + ), }Ok (())
@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }/// Reads the value from `mbox0` register. pub (crate )fn read_mailbox0 (&self, bar: &Bar0 ) ->u32 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::read (bar, &E ::ID ).value () + bar.read (regs::NV_PFALCON_FALCON_MAILBOX0 ::of ::<E >()) + .value () }/// Reads the value from `mbox1` register. pub (crate )fn read_mailbox1 (&self, bar: &Bar0 ) ->u32 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::read (bar, &E ::ID ).value () + bar.read (regs::NV_PFALCON_FALCON_MAILBOX1 ::of ::<E >()) + .value () }/// Reads values from both mailbox registers.
@@ -881,8 +880,9 @@ pub(crate) fn load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(/// Write the application version to the OS register. pub (crate )fn write_os_version (&self, bar: &Bar0 , app_version:u32 ) { - regs::NV_PFALCON_FALCON_OS ::default () - .set_value (app_version) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_OS ::zeroed ().with_value (app_version), + ); } }
drivers/gpu/nova-core/falcon/gsp.rs +12 -13
@@ -1,7 +1,11 @@// SPDX-License-Identifier: GPL-2.0 use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::{RegisterBase ,WithBase }, +Io , + }, prelude::*, time::Delta ,// };
@@ -14,13 +18,9 @@ PFalcon2Base, PFalconBase, // }, - regs::{ - self, - macros::RegisterBase, // - }, + regs, }; -/// Type specifying the `Gsp` falcon engine. Cannot be instantiated. pub (crate )struct Gsp (());impl RegisterBase <PFalconBase >for Gsp {
@@ -31,23 +31,22 @@ impl RegisterBase<PFalcon2Base> for Gsp {const BASE :usize =0x00111000 ; } -impl FalconEngine for Gsp { -const ID :Self =Gsp (()); -} +impl FalconEngine for Gsp {}impl Falcon <Gsp > {/// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to /// allow GSP to signal CPU for processing new messages in message queue. pub (crate )fn clear_swgen0_intr (&self, bar: &Bar0 ) { - regs::NV_PFALCON_FALCON_IRQSCLR ::default () - .set_swgen0 (true ) - .write (bar, &Gsp ::ID ); + bar.write ( +WithBase ::of ::<Gsp >(), + regs::NV_PFALCON_FALCON_IRQSCLR ::zeroed ().with_swgen0 (true ), + ); }/// Checks if GSP reload/resume has completed during the boot process. pub (crate )fn check_reload_completed (&self, bar: &Bar0 , timeout:Delta ) ->Result <bool > {read_poll_timeout ( - ||Ok (regs::NV_PGC6_BSI_SECURE_SCRATCH_14 ::read (bar)), + ||Ok (bar.read (regs::NV_PGC6_BSI_SECURE_SCRATCH_14 )), |val| val.boot_stage_3_handoff (),Delta ::ZERO , timeout,
drivers/gpu/nova-core/falcon/hal/ga102.rs +42 -28
124 lines not on this page · raw message
drivers/gpu/nova-core/falcon/hal/tu102.rs +8 -4
@@ -3,7 +3,11 @@use core::marker::PhantomData ;use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::WithBase , +Io ,// + }, prelude::*, time::Delta ,// };
@@ -49,14 +53,14 @@ fn program_brom(&self, _falcon: &Falcon<E>, _bar: &Bar0, _params: &FalconBromPar }fn is_riscv_active (&self, bar: &Bar0 ) ->bool { -let cpuctl = regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS ::read (bar, &E ::ID ); - cpuctl.active_stat () + bar.read (regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS ::of ::<E >()) + .active_stat () }fn reset_wait_mem_scrubbing (&self, bar: &Bar0 ) ->Result {// TIMEOUT: memory scrubbing should complete in less than 10ms. read_poll_timeout ( - ||Ok (regs::NV_PFALCON_FALCON_DMACTL ::read (bar, &E ::ID )), + ||Ok (bar.read (regs::NV_PFALCON_FALCON_DMACTL ::of ::<E >())), |r| r.mem_scrubbing_done (),Delta ::ZERO , Delta::from_millis(10),
drivers/gpu/nova-core/falcon/sec2.rs +7 -10
@@ -1,12 +1,11 @@// SPDX-License-Identifier: GPL-2.0 -use crate ::{ - falcon::{ -FalconEngine , -PFalcon2Base , -PFalconBase ,// - }, - regs::macros::RegisterBase , +use kernel::io::register::RegisterBase ; + +use crate ::falcon::{ +FalconEngine , +PFalcon2Base , +PFalconBase ,// };/// Type specifying the `Sec2` falcon engine. Cannot be instantiated.
@@ -20,6 +19,4 @@ impl RegisterBase<PFalcon2Base> for Sec2 {const BASE :usize =0x00841000 ; } -impl FalconEngine for Sec2 { -const ID :Self =Sec2 (()); -} +impl FalconEngine for Sec2 {}
drivers/gpu/nova-core/fb.rs +5 -1
@@ -4,6 +4,7 @@use kernel::{ device, + io::Io , prelude::*, ptr::{Alignable ,
@@ -134,7 +135,10 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0, gsp_fw: &GspFirmware) -> Result<let base = fb.end -NV_PRAMIN_SIZE ;if hal.supports_display (bar) { -match regs::NV_PDISP_VGA_WORKSPACE_BASE ::read (bar).vga_workspace_addr () { +match bar + .read (regs::NV_PDISP_VGA_WORKSPACE_BASE ) + .vga_workspace_addr () + {Some (addr) => {if addr < base {const VBIOS_WORKSPACE_SIZE :u64 =usize_as_u64 (SZ_128K );
drivers/gpu/nova-core/fb/hal/ga100.rs +23 -14
@@ -1,6 +1,10 @@// SPDX-License-Identifier: GPL-2.0 -use kernel::prelude::*; +use kernel::{ + io::Io , + num::Bounded , + prelude::*,// +};use crate ::{ driver::Bar0 ,
@@ -13,26 +17,31 @@struct Ga100 ;pub (super )fn read_sysmem_flush_page_ga100 (bar: &Bar0 ) ->u64 { - u64::from (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::read (bar).adr_39_08 ()) <<FLUSH_SYSMEM_ADDR_SHIFT - | u64::from (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ::read (bar).adr_63_40 ()) + u64::from (bar.read (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ).adr_39_08 ()) <<FLUSH_SYSMEM_ADDR_SHIFT + | u64::from (bar.read (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ).adr_63_40 ()) <<FLUSH_SYSMEM_ADDR_SHIFT_HI }pub (super )fn write_sysmem_flush_page_ga100 (bar: &Bar0 , addr:u64 ) { - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ::default () -// CAST: `as u32` is used on purpose since the remaining bits are guaranteed to fit within -// a `u32`. - .set_adr_63_40 ((addr >>FLUSH_SYSMEM_ADDR_SHIFT_HI )as u32 ) - .write (bar); - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::default () -// CAST: `as u32` is used on purpose since we want to strip the upper bits that have been -// written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`. - .set_adr_39_08 ((addr >>FLUSH_SYSMEM_ADDR_SHIFT )as u32 ) - .write (bar); + bar.write_val ( + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ::zeroed ().with_adr_63_40 ( +Bounded ::<u64 ,_ >::from (addr) + .shr ::<FLUSH_SYSMEM_ADDR_SHIFT_HI ,_ >() + .cast (), + ), + ); + + bar.write_val ( + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::zeroed () +// CAST: `as u32` is used on purpose since we want to strip the upper bits that have +// been written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`. + .with_adr_39_08 ((addr >>FLUSH_SYSMEM_ADDR_SHIFT )as u32 ), + ); }pub (super )fn display_enabled_ga100 (bar: &Bar0 ) ->bool { - !regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY ::read (bar).display_disabled () + !bar.read (regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY ) + .display_disabled () }/// Shift applied to the sysmem address before it is written into
drivers/gpu/nova-core/fb/hal/ga102.rs +5 -2
@@ -1,6 +1,9 @@// SPDX-License-Identifier: GPL-2.0 -use kernel::prelude::*; +use kernel::{ + io::Io , + prelude::*,// +};use crate ::{ driver::Bar0 ,
@@ -9,7 +12,7 @@ };fn vidmem_size_ga102 (bar: &Bar0 ) ->u64 { - regs::NV_USABLE_FB_SIZE_IN_MB ::read (bar).usable_fb_size () + bar.read (regs::NV_USABLE_FB_SIZE_IN_MB ).usable_fb_size () }struct Ga102 ;
drivers/gpu/nova-core/fb/hal/tu102.rs +10 -7
@@ -1,6 +1,9 @@// SPDX-License-Identifier: GPL-2.0 -use kernel::prelude::*; +use kernel::{ + io::Io , + prelude::*,// +};use crate ::{ driver::Bar0 ,
@@ -13,7 +16,7 @@pub (super )const FLUSH_SYSMEM_ADDR_SHIFT :u32 =8 ;pub (super )fn read_sysmem_flush_page_gm107 (bar: &Bar0 ) ->u64 { - u64::from (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::read (bar).adr_39_08 ()) <<FLUSH_SYSMEM_ADDR_SHIFT + u64::from (bar.read (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ).adr_39_08 ()) <<FLUSH_SYSMEM_ADDR_SHIFT }pub (super )fn write_sysmem_flush_page_gm107 (bar: &Bar0 , addr:u64 ) ->Result {
@@ -21,18 +24,18 @@ pub(super) fn write_sysmem_flush_page_gm107(bar: &Bar0, addr: u64) -> Result { u32::try_from (addr >>FLUSH_SYSMEM_ADDR_SHIFT ) .map_err (|_|EINVAL ) .map (|addr| { - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::default () - .set_adr_39_08 (addr) - .write (bar) + bar.write_val (regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::zeroed ().with_adr_39_08 (addr)) }) }pub (super )fn display_enabled_gm107 (bar: &Bar0 ) ->bool { - !regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY ::read (bar).display_disabled () + !bar.read (regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY ) + .display_disabled () }pub (super )fn vidmem_size_gp102 (bar: &Bar0 ) ->u64 { - regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE ::read (bar).usable_fb_size () + bar.read (regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE ) + .usable_fb_size () }struct Tu102 ;
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +9 -7
@@ -12,6 +12,10 @@ self, Device, // }, + io::{ + register::WithBase, // + Io, + }, prelude::*, ptr::{Alignable ,
@@ -33,7 +37,6 @@ Falcon, FalconBromParams, FalconDmaLoadable, - FalconEngine, FalconFbifMemType, FalconFbifTarget, FalconFirmware,
@@ -288,13 +291,12 @@ pub(crate) fn run( .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware: {:?}\n", e))?;// Configure DMA index for the bootloader to fetch the FWSEC firmware from system memory. - regs::NV_PFALCON_FBIF_TRANSCFG ::try_update ( - bar, - &Gsp ::ID , - usize::from_safe_cast (self.dmem_desc.ctx_dma), + bar.try_update ( + regs::NV_PFALCON_FBIF_TRANSCFG ::of ::<Gsp >() + .at (usize::from_safe_cast (self.dmem_desc.ctx_dma)), |v| { - v.set_target (FalconFbifTarget ::CoherentSysmem ) - .set_mem_type (FalconFbifMemType ::Physical ) + v.with_target (FalconFbifTarget ::CoherentSysmem ) + .with_mem_type (FalconFbifMemType ::Physical ) }, )?;
drivers/gpu/nova-core/gfw.rs +8 -3
@@ -19,7 +19,10 @@//! Note that the devinit sequence also needs to run during suspend/resume. use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, +Io ,// + }, prelude::*, time::Delta ,// };
@@ -58,9 +61,11 @@ pub(crate) fn wait_gfw_boot_completion(bar: &Bar0) -> Result {Ok (// Check that FWSEC has lowered its protection level before reading the GFW_BOOT // status. - regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK ::read (bar) + bar.read (regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK ) .read_protection_level0 () - && regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT ::read (bar).completed (), + && bar + .read (regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT ) + .completed (), ) }, |&gfw_booted| gfw_booted,
drivers/gpu/nova-core/gpu.rs +18 -18
@@ -4,6 +4,8 @@ device, devres::Devres, fmt, + io::Io, + num::Bounded, pci, prelude::*, sync::Arc, //
@@ -129,24 +131,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }/// Enum representation of the GPU generation. -/// -/// TODO: remove the `Default` trait implementation, and the `#[default]` -/// attribute, once the register!() macro (which creates Architecture items) no -/// longer requires it for read-only fields. -#[derive(fmt:: Debug , Default , Copy , Clone )] +#[derive(fmt:: Debug , Copy , Clone )] #[repr( u8 )] pub (crate )enum Architecture { -#[default] Turing =0x16 ,Ampere =0x17 ,Ada =0x19 , } -impl TryFrom <u8 >for Architecture { +impl TryFrom <Bounded <u32 ,6 >>for Architecture {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,6 >) ->Result <Self > { +match u8::from (value) {0x16 =>Ok (Self ::Turing ),0x17 =>Ok (Self ::Ampere ),0x19 =>Ok (Self ::Ada ),
@@ -155,23 +152,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. - valueas 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 (), } } }
@@ -208,13 +208,13 @@ fn new(dev: &device::Device, bar: &Bar0) -> Result<Spec> {// from an earlier (pre-Fermi) era, and then using boot42 to precisely identify the GPU. // Somewhere in the Rubin timeframe, boot0 will no longer have space to add new GPU IDs. -let boot0 = regs::NV_PMC_BOOT_0 ::read (bar); +let boot0 = bar.read (regs::NV_PMC_BOOT_0 );if boot0.is_older_than_fermi () {return Err (ENODEV ); } -let boot42 = regs::NV_PMC_BOOT_42 ::read (bar); +let boot42 = bar.read (regs::NV_PMC_BOOT_42 );Spec ::try_from (boot42).inspect_err (|_| {dev_err! (dev,"Unsupported chipset: {}\n" , boot42); })
drivers/gpu/nova-core/gsp/boot.rs +7 -4
@@ -5,6 +5,7 @@ dma::CoherentAllocation, dma_write, io::poll::read_poll_timeout, + io::Io, pci, prelude::*, time::Delta, //
@@ -57,7 +58,7 @@ fn run_fwsec_frts( ) -> Result<()> {// Check that the WPR2 region does not already exists - if it does, we cannot run // FWSEC-FRTS until the GPU is reset. -if regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI ::read (bar).higher_bound () !=0 { +if bar.read (regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI ).higher_bound () !=0 {dev_err! ( dev,"WPR2 region already exists - GPU needs to be reset to proceed\n"
@@ -87,7 +88,9 @@ fn run_fwsec_frts( }// SCRATCH_E contains the error code for FWSEC-FRTS. -let frts_status = regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR ::read (bar).frts_err_code (); +let frts_status = bar + .read (regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR ) + .frts_err_code ();if frts_status !=0 {dev_err! ( dev,
@@ -100,8 +103,8 @@ fn run_fwsec_frts(// Check that the WPR2 region has been created as we requested. let (wpr2_lo, wpr2_hi) = ( - regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO ::read (bar).lower_bound (), - regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI ::read (bar).higher_bound (), + bar.read (regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO ).lower_bound (), + bar.read (regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI ).higher_bound (), );match (wpr2_lo, wpr2_hi) {
drivers/gpu/nova-core/gsp/cmdq.rs +5 -4
@@ -15,7 +15,10 @@ DmaAddress, // }, dma_write, - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + Io, // + }, prelude::*, sync::aref::ARef, time::Delta,
@@ -488,9 +491,7 @@ fn calculate_checksum<T: Iterator<Item = u8>>(it: T) -> u32 {/// Notifies the GSP that we have updated the command queue pointers. fn notify_gsp (bar: &Bar0 ) { - regs::NV_PGSP_QUEUE_HEAD ::default () - .set_address (0 ) - .write (bar); + bar.write_val (regs::NV_PGSP_QUEUE_HEAD ::zeroed ().with_address (0u32 )); }/// Sends `command` to the GSP.
drivers/gpu/nova-core/regs.rs +343 -269
749 lines not on this page · raw message
drivers/gpu/nova-core/regs/macros.rs deleted +0 -739
739 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 14 lines · Alexandre Courbot
drivers/gpu/nova-core/falcon.rs +4
-3@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }
drivers/gpu/nova-core/falcon.rs pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { · line 807
Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +4
-3if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }
TBH, this is quite a readability hit, the previous was much more readable IMHO.
Why doesn't the previous caller-side syntax still work?
thanks,
Signature · 1 line
Joel Fernandes
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 16 lines · Joel Fernandes
Quoted 14 lines · Alexandre Courbot
drivers/gpu/nova-core/falcon.rs +4
-3@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }
Quoted 12 lines
drivers/gpu/nova-core/falcon.rs pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { · line 807
Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +4
-3if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }TBH, this is quite a readability hit, the previous was much more readable IMHO.
Yes, I think so too, except that "WithBase::of::<E>" makes a lot more sense on-screen, than "&E::ID". The latter just looks quite random, so this part is an improvement.
Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 34 lines · John Hubbard
Quoted 16 lines · Joel Fernandes
Quoted 14 lines · Alexandre Courbot
drivers/gpu/nova-core/falcon.rs +4
-3@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }Quoted 12 lines
drivers/gpu/nova-core/falcon.rs pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { · line 807
Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +4
-3if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }TBH, this is quite a readability hit, the previous was much more readable IMHO.
Yes, I think so too, except that "WithBase::of::<E>" makes a lot more sense on-screen, than "
&E::ID". The latter just looks quite random, so this part is an improvement.
Quoted 8 lines
Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
The issue with omitting it is it still needs a constructor? so if not zeroed() it would still need ::default() I think.
Quoted 3 lines
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
yeah, also perhaps the whole thing should have a macro! to de-sugar. The patterns seem somewhat repetitive.
thanks,
--
Joel Fernandes
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
Quoted 19 lines
Quoted 6 lines
Quoted 1 line
TBH, this is quite a readability hit, the previous was much more readable IMHO.
Yes, I think so too, except that "WithBase::of::<E>" makes a lot more sense on-screen, than "
&E::ID". The latter just looks quite random, so this part is an improvement.Quoted 8 lines
Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
The issue with omitting it is it still needs a constructor? so if not
zeroed()it would still need ::default() I think.Quoted 1 line
Quoted 5 lines
Quoted 2 lines
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
yeah, also perhaps the whole thing should have a macro! to de-sugar. The patterns seem somewhat repetitive.
Yes, and actually, I don't immediately see why we have to specify both a base value and a register name, because registers have a fixed base address.
What about this instead (*very* approximately):
// set up or construct NV_PFALCON_FALCON_MAILBOX1:
let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar); reg.write(NV_PFALCON_FALCON_MAILBOX1, new_mbox1_val);
thanks,
Signature · 1 line
John Hubbard
Gary Guo
reviewerRe: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 24 lines · John Hubbard
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
Quoted 19 lines
Quoted 6 lines
Quoted 1 line
TBH, this is quite a readability hit, the previous was much more readable IMHO.
Yes, I think so too, except that "WithBase::of::<E>" makes a lot more sense on-screen, than "
&E::ID". The latter just looks quite random, so this part is an improvement.Quoted 8 lines
Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
The issue with omitting it is it still needs a constructor? so if not
zeroed()it would still need ::default() I think.Quoted 1 line
Quoted 5 lines
Quoted 5 lines
Quoted 2 lines
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
yeah, also perhaps the whole thing should have a macro! to de-sugar. The patterns seem somewhat repetitive.
Once we agreed on how bitfield macros should work, this could just be
bar.write(WithBase::of::<E>(), bitfield!(NV_PFCALON_FALCON_MAILBOX1 { value: mbox1 }))or something similar.
Or as Danilo pointed out, for the generic mailbox using bitfields isn't really meaningful, so the bitfield should eventually be removed and replaced with a direct write of primitive integer.
Quoted 10 lines
Yes, and actually, I don't immediately see why we have to specify both a base value and a register name, because registers have a fixed base address.
What about this instead (*very* approximately):
// set up or construct NV_PFALCON_FALCON_MAILBOX1: let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar);
This doesn't really make sense. What does "zeroed(&bar)" even mean? You're neither zeroing the register on the bar, nor constructing a zeroed value?
Best,
Gary
Quoted 7 lines
reg.write(NV_PFALCON_FALCON_MAILBOX1, new_mbox1_val);thanks,
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 8 lines · Gary Guo
Quoted 7 lines · John Hubbard
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
What about this instead (*very* approximately):
Quoted 7 lines
Quoted 3 lines
// set up or construct NV_PFALCON_FALCON_MAILBOX1: let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar);This doesn't really make sense. What does "
zeroed(&bar)" even mean? You're neither zeroing the register on the bar, nor constructing a zeroed value?
The idea was to separate constructing with a zeroed value, from the actual register write. I am not surprised that the syntax is All Wrong at this point, I'm just hoping to spark more ideas about how to make this clear and nice to read.
thanks,
Signature · 1 line
John Hubbard
Danilo Krummrich
maintainerRe: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 13 lines · John Hubbard
Quoted 12 lines · Gary Guo
Quoted 10 lines · John Hubbard
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
What about this instead (*very* approximately):// set up or construct NV_PFALCON_FALCON_MAILBOX1: let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar);
Quoted 8 lines
Quoted 3 lines
This doesn't really make sense. What does "
zeroed(&bar)" even mean? You're neither zeroing the register on the bar, nor constructing a zeroed value?The idea was to separate constructing with a zeroed value, from the actual register write. I am not surprised that the syntax is All Wrong at this point, I'm just hoping to spark more ideas about how to make this clear and nice to read.
This is where you would use write_val(), i.e.
// Construct with some custom constructor. let reg = regs::NV_PFALCON_FALCON_MAILBOX1::new(...); bar.write_val(reg);
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 23 lines · Danilo Krummrich
Quoted 13 lines · John Hubbard
Quoted 12 lines · Gary Guo
Quoted 10 lines · John Hubbard
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
What about this instead (*very* approximately):// set up or construct NV_PFALCON_FALCON_MAILBOX1: let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar);Quoted 8 lines
Quoted 3 lines
This doesn't really make sense. What does "
zeroed(&bar)" even mean? You're neither zeroing the register on the bar, nor constructing a zeroed value?The idea was to separate constructing with a zeroed value, from the actual register write. I am not surprised that the syntax is All Wrong at this point, I'm just hoping to spark more ideas about how to make this clear and nice to read.
Quoted 6 lines
This is where you would use
write_val(), i.e.// Construct with some custom constructor. let reg = regs::NV_PFALCON_FALCON_MAILBOX1::new(...); bar.write_val(reg);
Beautiful! That's what I wish I had written. :)
thanks,
Signature · 1 line
John Hubbard
Gary Guo
reviewerRe: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
In reply to John HubbardQuoted 13 lines · John Hubbard
Quoted 12 lines · Gary Guo
Quoted 10 lines · John Hubbard
Quoted 3 lines · Joel Fernandes
Quoted 2 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
...
What about this instead (*very* approximately):// set up or construct NV_PFALCON_FALCON_MAILBOX1: let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed(&bar);
Quoted 8 lines
Quoted 3 lines
This doesn't really make sense. What does "
zeroed(&bar)" even mean? You're neither zeroing the register on the bar, nor constructing a zeroed value?The idea was to separate constructing with a zeroed value, from the actual register write. I am not surprised that the syntax is All Wrong at this point, I'm just hoping to spark more ideas about how to make this clear and nice to read.
Separated construct and write is just
let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1);
bar.write(WithBase::of::<E>(), reg);(or bar.write_val(reg) for non-relative registers)
Best,
Gary
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
On 3/9/26 11:42 AM, Gary Guo wrote:
...
Quoted 11 lines
Quoted 4 lines
The idea was to separate constructing with a zeroed value, from the actual register write. I am not surprised that the syntax is All Wrong at this point, I'm just hoping to spark more ideas about how to make this clear and nice to read.
Separated construct and write is just
let reg = NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1); bar.write(WithBase::of::<E>(), reg);(or
bar.write_val(reg)for non-relative registers)
OK, so I think that Alex's example was sort of a worst case, because if we wrote it as you do above, it would be clearer to read.
And hopefully we can continue on to what Danilo wrote in the other thread, which makes it even simpler and clearer.
thanks,
Signature · 1 line
John Hubbard
Danilo Krummrich
maintainerRe: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
In reply to John HubbardQuoted 38 lines · John Hubbard
Quoted 16 lines · Joel Fernandes
Quoted 14 lines · Alexandre Courbot
drivers/gpu/nova-core/falcon.rs +4
-3@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }Quoted 12 lines
drivers/gpu/nova-core/falcon.rs pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { · line 807
Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +4
-3if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }TBH, this is quite a readability hit, the previous was much more readable IMHO.
Yes, I think so too, except that "WithBase::of::<E>" makes a lot more sense on-screen, than "
&E::ID". The latter just looks quite random, so this part is an improvement.Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
Quoted 7 lines
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
I think this could also just be
bar.write(regs::NV_PFALCON_FALCON_MAILBOX1::of::<E>(), mbox1);
as we would want it for FIFO-like registers.
Re: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
Quoted 12 lines · Danilo Krummrich
Quoted 11 lines · John Hubbard
Quoted 1 line · Joel Fernandes
On 3/9/2026 11:14 AM, Alexandre Courbot wrote:
Let's break down the remaining troublesome part a bit:
regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox1)
* "regs::" can be omitted with a "use" statement, right?
* ::zeroed() maybe should be the default behavior here, and then it could also be omitted?
Quoted 6 lines
Quoted 2 lines
* .with_value(mbox1) I'm sure this is necessary, but the construction is unfortunately much less clear than .write(value)! Thoughts?
I think this could also just be
bar.write(regs::NV_PFALCON_FALCON_MAILBOX1::of::<E>(), mbox1);
That would be quite nice.
Quoted 2 lines
as we would want it for FIFO-like registers.
thanks,
Signature · 1 line
John Hubbard
Alexandre Courbot
maintainerRe: [PATCH FOR REFERENCE v8 10/10] gpu: nova-core: use the kernel `register!` macro
In reply to Joel FernandesQuoted 29 lines · Joel Fernandes
Quoted 14 lines · Alexandre Courbot
drivers/gpu/nova-core/falcon.rs +4
-3@@ -797,26 +792,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () - .set_value (mbox0) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), + ); }drivers/gpu/nova-core/falcon.rs pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { · line 807
Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +4
-3if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () - .set_value (mbox1) - .write (bar, &E ::ID ); + bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), + ); } }TBH, this is quite a readability hit, the previous was much more readable IMHO.
Quoted 1 line
Why doesn't the previous caller-side syntax still work?
Looking down the discussion is looks like almost everyone found a way to work with this API that they like, but here are the reasons for the record.
The previous caller-side syntax had many problems:
* Every register must have its own ~6 (try_)read/write/update methods generated by the macro, creating a rift in how I/O is used only for registers.
* The number of arguments these methods take is dependent on the register type, which is awkward.
* The I/O type is passed as an argument, meaning we cannot use Deref coercion on it, further complicating things when we have more than one layer of indirection. For instance, it didn't work well with both Nova and the Rust PCI driver sample (one of them had to & or * its I/O type with every call).
With the current revision, there is only one site where I/O methods are defined (io.rs), to which registers cleanly integrate like any other I/O type (i.e. registers are not "special"). Deref coercion on the Io type can be used without limitation. There is much less code generated by the register macro, which has become much simpler as a result.
This syntax might require one more line here and there, but after working with it a bit I think it is actually much more readable and well-formatted than before. It makes it clear from the get go what kind of register you are accessing, and we *do* want to be meticulous when working with registers.
It looks better both on the inside and the outside, and I hold that view not as an opinion, but an objective fact. :)
Quoted 13 lines · Alexandre Courbot
Another revision, another redesign.
This one eschews closures completely for write operations, and defaults to a two-argument
writemethod backed by a single-argumentwrite_valone to avoid register name repetition. The two-argument version can now be used in most cases thanks to a clever use of traits (thanks Gary!).We went from this syntax:
bar.write_with(regs::NV_PFALCON_FALCON_DMATRFFBOFFS::of::<E>(), |r| { r.with_offs(src_start + pos) });
Quoted 8 lines
to this one:
bar.write(
WithBase::of::<E>(), regs::NV_PFALCON_FALCON_DMATRFFBOFFS::zeroed().with_offs(src_start + pos),
);While slightly more verbose, it is also much easier to read, as the
Yes, it is! Let's acknowledge the progress in readability here, even though we are still working on minor details in the other thread. :)
thanks,
Signature · 1 line
John Hubbard
Daniel Almeida
maintainerHi Alex,
We will test that on Tyr shortly. There’s a patch on the list that targeted an earlier version of the macro. We will rebase it on the current one.
At least you get one more user from the get-go.
— Daniel
Danilo Krummrich
maintainerQuoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macro
I did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have CONFIG_RUST_BUILD_ASSERT_ALLOW enabled?
Alexandre Courbot
maintainerQuoted 13 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macro
Quoted 3 lines
I did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have
CONFIG_RUST_BUILD_ASSERT_ALLOWenabled?
Nope, it is disabled and I build with Clippy so I am surprised you are getting this. Do you know which module is failing?
Danilo Krummrich
maintainerQuoted 14 lines · Alexandre Courbot
Quoted 13 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macro
Quoted 6 lines
Quoted 3 lines
I did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have
CONFIG_RUST_BUILD_ASSERT_ALLOWenabled?Nope, it is disabled and I build with Clippy so I am surprised you are getting this. Do you know which module is failing?
ERROR: modpost: "rust_build_error" [drivers/gpu/nova-core/nova_core.ko] undefined!
Alexandre Courbot
maintainerQuoted 15 lines · Danilo Krummrich
Quoted 14 lines · Alexandre Courbot
Quoted 13 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macro
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
I did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have
CONFIG_RUST_BUILD_ASSERT_ALLOWenabled?Nope, it is disabled and I build with Clippy so I am surprised you are getting this. Do you know which module is failing?
ERROR: modpost: "
rust_build_error" [drivers/gpu/nova-core/nova_core.ko] undefined!
Does it happen with the exact branch I posted?
https://github.com/Gnurou/linux/tree/b4/register
This one builds fine for me.
Gary also pointed out a few missing inlines that could potentially trigger that kind of error. But I'd be curious to try and reproduce myself if you can post your tree somewhere.
Danilo Krummrich
maintainerQuoted 20 lines · Alexandre Courbot
Quoted 19 lines · Danilo Krummrich
Quoted 18 lines · Alexandre Courbot
Quoted 16 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macroI did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have
CONFIG_RUST_BUILD_ASSERT_ALLOWenabled?
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
Nope, it is disabled and I build with Clippy so I am surprised you are getting this. Do you know which module is failing?
ERROR: modpost: "
rust_build_error" [drivers/gpu/nova-core/nova_core.ko] undefined!Does it happen with the exact branch I posted?
Yup, my HEAD is at commit 5c558172827e ("[FOR REFERENCE] gpu: nova-core: use the kernel register! macro").
Alexandre Courbot
maintainerQuoted 24 lines · Danilo Krummrich
Quoted 23 lines · Alexandre Courbot
Quoted 22 lines · Danilo Krummrich
Quoted 20 lines · Alexandre Courbot
Quoted 13 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Alexandre Courbot (10):
rust: enable thegeneric_arg_inferfeature
rust: num: addshrandshlmethods toBounded
rust: num: addinto_boolmethod toBounded
rust: num: makeBounded::getconst
rust: io: add IoLoc type and generic I/O accessors
rust: io: use generic read/write accessors for primitive accesses
rust: io: introduceIntoIoValtrait and single-argumentwrite_val
rust: io: addregister!macro
sample: rust: pci: useregister!macro
[FOR REFERENCE] gpu: nova-core: use the kernelregister!macroQuoted 3 lines
I did not look into the root cause, but fetching this patch series my build fails due to a build_assert!(). Maybe you have
CONFIG_RUST_BUILD_ASSERT_ALLOWenabled?Nope, it is disabled and I build with Clippy so I am surprised you are getting this. Do you know which module is failing?
Quoted 6 lines
Quoted 3 lines
Quoted 1 line
ERROR: modpost: "
rust_build_error" [drivers/gpu/nova-core/nova_core.ko] undefined!Does it happen with the exact branch I posted?
Yup, my HEAD is at commit
5c558172827e("[FOR REFERENCE] gpu: nova-core: use the kernelregister!macro").
I did a mistake when updating the nova-core code - changed a dynamically-checked index into a static one, and since it could not be proven at build-time it failed. Working as intended, apart from the too cryptic error message.
For the record, here is the fix:
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +4 -3
@@ -291,14 +291,15 @@ pub(crate) fn run( .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware: {:?}\n", e))?;// Configure DMA index for the bootloader to fetch the FWSEC firmware from system memory. - bar.try_update ( + bar.update ( regs::NV_PFALCON_FBIF_TRANSCFG ::of ::<Gsp >() - .at (usize::from_safe_cast (self.dmem_desc.ctx_dma)), + .try_at (usize::from_safe_cast (self.dmem_desc.ctx_dma)) + .ok_or (EINVAL )?, |v| { v.with_target (FalconFbifTarget ::CoherentSysmem ) .with_mem_type (FalconFbifMemType ::Physical ) }, - )?; + );let (mbox0, _) = falcon .boot (bar,Some (0 ),None )