rust: io: support register projections and remove relative registers
Subsystems (13)
Gary Guo
maintainerv4 cover rust: io: support register projections and remove relative registers
Currently registers work for all untyped I/O regions, which is not ideal. It allows registers defined for device A to work for another device B and there is no safeguarding at all.
Change this by requiring a base type for registers. register! can still define registers on untyped Regions, although users would need to do so explicitly and supply a concrete type.
This change makes it possible to use projection for relative registers; relative registers can be implemented by defining new types for the I/O subregions and just define registers for these subregion types like normal registers.
This actually results in more ergnomic code for users of relative registers (currently only nova-core), because non-array registers can be written to with
#[...]
struct Subregion(...);
register! {
base: MyBase;
SUBREGION: Subregion @ ...;
}
register! {
base: Subregion;
REG(u32) @ .. { .. }
}
let subregion = io_project!(bar, build: SUBREGION);
subregion.read(REG)
subregion.write_reg(reg)instead of
struct SubregionType;
struct Subregion;
impl RegisterBase<SubregionType> for Subregion {
const BASE: usize = ...;
}
register! {
REG(u32) @ Subregion + .. { .. }
}
bar.read(REG::of::<Subregion>())
bar.write(WithBase::of::<Subregion>(), reg)This also allows a lot more code sharing between I/O projection and register! macro.
The expressiveness power of Rust declarative macros is becoming limiting, so it is converted to a proc macro before new features being added to it.
---
Changes in v4:
- Rebase on 7.3-rc1.
- Many typo fixes. (Alex)
- Tweaks to transmute and AsRepr. See changelogs inline in patches.
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Convert the register! macro to syn.
- Add check to ensure register and alias share the same base. (Alex)
- Split transmute functionalities to kernel::mem. (Alex)
- Remove some stray trait bound in nova code. (Alex)
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Extract type conversion from register! to Io
- Redesign the API to be centered around regsiter projections.
* Support register projections in io_project!
* Support adding register definition without defining bitfield
* Subregions is thus unified with other registers.
- Store projected subregions in Falcon for nova.
- Link to v1: https://patch.msgid.link/[email protected]
---
Gary Guo (16):
rust: io: register: reimplement as proc macro
rust: mem: add transmute with deferred size check
rust: mem: add AsRepr and AsReprMut
rust: io: perform conversions using AsRepr
rust: io: support register projections
rust: io: register: allow explicit base type specification
gpu: nova-core: specify base type for registers
drm/tyr: specify base type for registers
samples: rust: pci: specify base type for registers
rust: io: register: make register have a typed base
rust: io: register: support fixed offset register without bitfield
gpu: nova-core: use projection for PFALCON and PFALCON2 registers
gpu: nova-core: convert hshub0 from relative register to projection
rust: io: register: remove relative registers
rust: io: register: remove Register trait and cleanup macro
rust: io: register: unify handling of register with/without bitfields
MAINTAINERS | 1 + drivers/gpu/drm/tyr/driver.rs | 1 + drivers/gpu/drm/tyr/fw.rs | 5 +- drivers/gpu/drm/tyr/regs.rs | 45 +- drivers/gpu/nova-core/driver.rs | 1 + drivers/gpu/nova-core/falcon.rs | 161 ++--- drivers/gpu/nova-core/falcon/fsp.rs | 63 +- drivers/gpu/nova-core/falcon/gsp.rs | 51 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 59 +- drivers/gpu/nova-core/falcon/hal/tu102.rs | 9 +- drivers/gpu/nova-core/falcon/sec2.rs | 37 +- drivers/gpu/nova-core/fb/hal/gb100.rs | 59 +- drivers/gpu/nova-core/fb/regs.rs | 31 +- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 18 +- drivers/gpu/nova-core/gsp/hal/tu102.rs | 7 +- drivers/gpu/nova-core/gsp/regs.rs | 9 +- drivers/gpu/nova-core/regs.rs | 115 ++-- drivers/gpu/nova-core/vbios.rs | 11 +- rust/kernel/bitfield.rs | 9 + rust/kernel/device_id.rs | 3 +- rust/kernel/io.rs | 181 +++-- rust/kernel/io/register.rs | 759 +++++---------------- rust/kernel/lib.rs | 1 + rust/kernel/mem.rs | 231 +++++++ rust/kernel/sync/atomic.rs | 4 +- rust/macros/io/mod.rs | 3 + rust/macros/io/register.rs | 296 ++++++++ rust/macros/lib.rs | 9 + samples/rust/rust_driver_pci.rs | 4 + 29 files changed, 1230 insertions(+), 953 deletions(-)
---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260721-typed_register-176eab3abee7
Best regards,
Signature · 1 line
Gary Guo <[email protected]>
Gary Guo
maintainerPATCH v4 1/16 rust: io: register: reimplement as proc macro
The existing register! macro is implemented as a declarative macro. Reimplement it as proc macro instead, with no functional changes intended.
The old implementation produces unhelpful diagnostics when things go wrong. For example, for code like
register! {
pub(crate) TESTREG(u32) {
31:0 data;
}
}which misses out the "@ offset" part of the specification, and the following error is produced:
error: no rules expected {
--> test.rs:42:5
|
42 | / register! {
43 | | pub(crate) TESTREG(u32) {
44 | | 31:0 data;
... |
100 | | }
| |_____^ no rules expected this token in macro callwhich isn't very helpful. With the proc macro implementation, the following error is produced:
error: expected @ or =>
--> tests.rs:43:33
|
43 | pub(crate) TESTREG(u32) {
| ^which is much more helpful. Apart from diagnostics, proc macro also has a benefit of not having follow-set restrictions, which makes syntax like
register!(name: ty @ offset);
possible; declarative macro will reject this as @ is not in the follow-set of "ty" metavariable kind.
--- MAINTAINERS | 1 + rust/kernel/io/register.rs | 224 +----------------------------------- rust/macros/io/mod.rs | 3 + rust/macros/io/register.rs | 276 +++++++++++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 9 ++ 5 files changed, 291 insertions(+), 222 deletions(-)
MAINTAINERS +1 -0
@@ -7494,6 +7494,7 @@ F: rust/kernel/io.rs F: rust/kernel/io/ F: rust/kernel/irq.rs F: rust/kernel/irq/ +F: rust/macros/io/ DEVICE RESOURCE MANAGEMENT HELPERS M: Hans de Goede <[email protected]>
rust/kernel/io/register.rs +2 -222
229 lines not on this page · raw message
rust/macros/io/mod.rs new file +3 -0
@@ -0,0 +1,3 @@ +// SPDX-License-Identifier: GPL-2.0 + +pub (crate )mod register;
rust/macros/io/register.rs new file +276 -0
276 lines not on this page · raw message
rust/macros/lib.rs +9 -0
@@ -19,6 +19,7 @@mod fmt;mod for_lt;mod helpers; +mod io;mod kunit;mod module;mod paste;
@@ -481,6 +482,14 @@ pub fn paste(input: TokenStream) -> TokenStream { .into() } +#[doc(hidden)] // Documented in `kernel` crate. +#[proc_macro] +pub fn register (input:TokenStream ) ->TokenStream { + io::register::register (parse_macro_input! (input)) + .unwrap_or_else (|e| e.into_compile_error ()) + .into () +} +/// Registers a KUnit test suite and its test cases using a user-space like syntax. /// /// This macro should be used on modules. If `CONFIG_KUNIT` (in `.config`) is `n`, the target module
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 01/16] rust: io: register: reimplement as proc macro
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 15 lines
The existing
register!macro is implemented as a declarative macro. Reimplement it as proc macro instead, with no functional changes intended.The old implementation produces unhelpful diagnostics when things go wrong. For example, for code like
register! { pub(crate) TESTREG(u32) { 31:0 data; } }which misses out the "@ offset" part of the specification, and the following error is produced:
Quoted 6 lines
[ ... ]
possible; declarative macro will reject this as
@is not in the follow-set of "ty" metavariable kind.Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Re: [PATCH v4 01/16] rust: io: register: reimplement as proc macro
In reply to Gary GuoOn Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
Quoted 15 lines
rust/macros/io/mod.rs new file +3
-0@@ -0,0 +1,3 @@ +// SPDX-License-Identifier: GPL-2.0 + +pub (crate )mod register;rust/macros/io/register.rs new file +0
-0
rust/macros/io/register.rs line 3
Quoted 3 lines
rust/macros/io/register.rs new file +3
-0@@ -0,0 +1,276 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Documention and usage example of the macro can be found at `rust/kernel/io/register.rs`.
s/Documention/Documentation
Quoted 24 lines
rust/macros/io/register.rs new file +24
-0+ +use proc_macro2::{ +Group , +Literal , +Span , +TokenStream ,// +}; +use quote::{ + quote, + quote_spanned,// +}; +use syn::{ + bracketed, + parenthesized, + parse::Parse , + spanned::Spanned , + token, +Attribute , +Expr , +Ident , +Path , +Result , +Token , +Type ,
rust/macros/io/register.rs line 37
Quoted 10 lines
rust/macros/io/register.rs new file +10
-0+ Visibility, // +}; + +mod kw { + syn::custom_keyword!(stride); +} + +/// Definition of a register array. +/// +/// Specify a size, and optionally a stride. Syntax is of form `[size: EXPR, $(stride = EXPR)?]`.
IIUC the syntax is actually [EXPR $(, stride = EXPR)?].
With these fixed,
Gary Guo
maintainerPATCH v4 2/16 rust: mem: add `transmute` with deferred size check
In reply to Gary GuoImplement a transmute/safe_transmute that checks size at monomorphization time instead of type-checking time. This allows more cases where we know that the size matches but this is not generically checkable.
The signature is equivalent to the unstable transmute_neo function in the standard library. A safe variant is provided to use with types implementing FromBytes and IntoBytes.
Existing users of transmute_copy to bypass size checks are converted.
---
Changes since v3:
- Renamed the methods to transmute and safe_transmute, so the name transmute_unchecked is for the completely unchecked variant instead, matching that of Rust intrinsics.
--- rust/kernel/device_id.rs | 3 +- rust/kernel/lib.rs | 1 + rust/kernel/mem.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/sync/atomic.rs | 4 +- 4 files changed, 103 insertions(+), 4 deletions(-)
rust/kernel/device_id.rs +1 -2
@@ -146,8 +146,7 @@ impl<T: RawDeviceId, const N: usize> IdArray<T, (), N> {/// If the device implements [`RawDeviceIdIndex`], consider using [`IdArray::new`] instead. pub const fn new_without_index (ids: [T ;N ]) ->Self {// SAFETY: `T` is layout-wise compatible with `T::RawType`, so is the array of them. -let raw_ids: [MaybeUninit <T ::RawType >;N ] =unsafe { core::mem::transmute_copy (&ids) }; - core::mem::forget (ids); +let raw_ids: [MaybeUninit <T ::RawType >;N ] =unsafe {crate ::mem::transmute (ids) };Self { ids: raw_ids,
rust/kernel/lib.rs +1 -0
@@ -98,6 +98,7 @@pub mod kunit;pub mod list;pub mod maple_tree; +pub mod mem;pub mod miscdevice;pub mod mm;pub mod module;
rust/kernel/mem.rs new file +99 -0
99 lines not on this page · raw message
rust/kernel/sync/atomic.rs +2 -2
@@ -140,7 +140,7 @@ pub unsafe trait AtomicAdd<Rhs = Self>: AtomicType {const fn into_repr <T :AtomicType >(v:T ) ->T ::Repr {// SAFETY: Per the safety requirement of `AtomicType`, `T` is round-trip transmutable to // `T::Repr`, therefore the transmute operation is sound. -unsafe { core::mem::transmute_copy (&v) } +unsafe {crate ::mem::transmute (v) } }/// # Safety
@@ -149,7 +149,7 @@ const fn into_repr<T: AtomicType>(v: T) -> T::Repr {#[inline(always)] const unsafe fn from_repr <T :AtomicType >(r:T ::Repr ) ->T {// SAFETY: Per the safety requirement of the function, the transmute operation is sound. -unsafe { core::mem::transmute_copy (&r) } +unsafe {crate ::mem::transmute (r) } }impl <T :AtomicType >Atomic <T > {
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 02/16] rust: mem: add `transmute` with deferred size check
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
Implement a
transmute/safe_transmutethat checks size at monomorphization time instead of type-checking time. This allows more cases where we know that the size matches but this is not generically checkable.The signature is equivalent to the unstable
transmute_neofunction in the standard library. A safe variant is provided to use with types implementingFromBytesandIntoBytes.Existing users of
transmute_copyto bypass size checks are converted.Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v4 02/16] rust: mem: add `transmute` with deferred size check
In reply to Gary GuoOn Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
Quoted 15 lines
rust/kernel/mem.rs new file +9
-0@@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Basic utilities for dealing with memory, values, and types. + +use crate ::prelude::*; + +/// Transmute between two types. +/// +/// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this
rust/kernel/mem.rs line 19
Quoted 10 lines
rust/kernel/mem.rs new file +10
-0+/// cannot be proven by the compiler. +/// +/// This is equivalent to Rust's `transmute_unchecked` intrinsics. +/// +/// # Safety +/// +/// All safety requirements of [`core::mem::transmute`] apply, plus that the size `Src` and `Dst` +/// must match. +/// +/// # Example
nit: IIUC the convention is to always use the plural Examples.
Quoted 5 lines
rust/kernel/mem.rs new file +5
-0+/// +/// This can be used when types are known to have the same size, but only at runtime. +/// ```no_run +/// # use core::any::TypeId; +/// fn to_u32<T: 'static>(v: T) -> Option<u32> {
rust/kernel/mem.rs line 34
Quoted 10 lines
rust/kernel/mem.rs new file +10
-0+/// if TypeId::of::<T>() != TypeId::of::<u32>() { +/// return None; +/// } +/// +/// // `core::mem::transmute` won't work here. +/// // SAFETY: We've checked that `T` is u32! +/// Some(unsafe { kernel::mem::transmute_unchecked(v) }) +/// } +/// +/// to_u32(1u32);
Missing closing code block here - interestingly, without it this block triggers a "function has unnecessary safety comment" warning.
With this,
Re: [PATCH v4 02/16] rust: mem: add `transmute` with deferred size check
In reply to Gary GuoReview
Quoted 3 lines · Gary Guo
(quoted diff) +2
-0+/// This can be used when types are known to have the same size, but only at runtime. +/// ```no_run
Newline between them.
Quoted 1 line
+/// // SAFETY: We've checked that
Tis u32!
u32
rust/kernel/mem.rs line 58
Quoted 3 lines
rust/kernel/mem.rs new file +3
-0+/// This is typically used in generic code where it's known that type will have the same size, but +/// the compiler cannot prove it generically. +/// ```no_run
Same.
Quoted 1 line
+ // SAFETY: transmute is safe with
IntoBytesandFromBytesbounds.
transmute
I think we could also link to the intrinsic and the _neo one, perhaps with a permalink to avoid drift if they go away, but not a big deal of course.
Cheers,
Miguel
Gary Guo
maintainerPATCH v4 3/16 rust: mem: add `AsRepr` and `AsReprMut`
In reply to Gary GuoSome API like atomics and I/O operate on primitives only; therefore other types would need to converted to these primitive first. Add two traits AsRepr and AsReprMut to indicate that the type can be turned into a primitive for these operations.
T: AsRepr means that &T can be viewed as &T::Repr and thus it needs to support transmutability in one direction. T: AsReprMut means that &mut T can be viewed as &mut T::Repr and thus it needs to support bi-directional transmutability.
To avoid duplicating implementations, all repr types are normalized to unsigned integers.
---
Changes since v3:
- Added as_repr and as_repr_mut so the name makes sense (Alex). I did not add Copy bound because it is not necessary (adding it won't simplify the implementation without also requring Self: Copy, which I don't want to add).
- Dropped round-trip transmutability as a concept, as it can be proved correct because from_repr_unchecked(into_repr(v)) is basically just move v.
Even for the AtomicType's use case where copies are made, it can still be proven by observing that from_repr_unchecked(copy into_repr(v)) is not distinguishable from from_repr_unchecked(into_repr(copy v)).
--- rust/kernel/mem.rs | 132 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+)
rust/kernel/mem.rs +132 -0
@@ -97,3 +97,135 @@ pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst {// SAFETY: transmute is safe with `IntoBytes` and `FromBytes` bounds. unsafe {transmute (val) } } + +/// Type that is layout-compatible with a primitive representation. +/// +/// # Safety +/// +/// - `Self` must have the same size and alignment as [`Self::Repr`]. +/// - `Self` can be [transmutable] to [`Self::Repr`]. +/// - Neither `Self` nor [`Self::Repr`] contains interior mutability. +/// +/// The above basically says that `&Self` can be transmuted to `&Self::Repr`. +/// +/// [transmutable]: core::mem::transmute +pub unsafe trait AsRepr :Sized { +/// Primitive representation of this type. +type Repr ; + +/// Convert from `&Self` to [`&Self::Repr`](AsRepr::Repr). +#[inline(always)] +fn as_repr (this: &Self ) -> &Self ::Repr { +// SAFETY: Per safety requirement of the trait. +unsafe { core::mem::transmute (this) } + } + +/// Convert from `Self` to [`Self::Repr`]. +#[inline(always)] +fn into_repr (this:Self ) ->Self ::Repr { +// SAFETY: Per safety requirement of the trait. +unsafe {transmute (this) } + } + +/// Convert from [`Self::Repr`] to `Self`. +/// +/// # Safety +/// +/// `repr` must be a valid bit pattern of `Self` and satisfy type-specific invariants of it. +/// +/// Alternatively, if `repr` is previously obtained using [`Self::into_repr`], and each +/// `from_repr_unchecked` should corresponds to a unique `into_repr` call, then it is safe to +/// call as well (this means that we're undoing a `into_repr` call getting the exact bytes +/// back). +/// +/// This method makes no guarantee if a `into_repr` corresponds to multiple +/// `from_repr_unchecked` (i.e. copies are made), to allow for cases where `Repr` is a pointer +/// and the user of the API wants ownership transfer. Users that want the ability to call +/// `from_repr_unchecked` after copying can require `Copy` bound explicitly. +#[inline(always)] +unsafe fn from_repr_unchecked (repr:Self ::Repr ) ->Self { +// SAFETY: Per safety requirement, `repr` is valid repr of `Self`, or it is previously from +// `into_repr`, in which case we're undoing the transmute so it is also safe. +unsafe {transmute (repr) } + } +} + +/// Type that is bi-directionally transmutable with a primitive representation. +/// +/// # Safety +/// +/// - [`Self`] must be [transmutable] from [`Self::Repr`]. +/// +/// [transmutable]: core::mem::transmute +/// [`Self::Repr`]: AsRepr::Repr +pub unsafe trait AsReprMut :AsRepr { +/// Convert from `&mut Self` to [`&mut Self::Repr`](AsRepr::Repr). +#[inline(always)] +fn as_repr_mut (this: &mut Self ) -> &mut Self ::Repr { +// SAFETY: Per safety requirement of the trait. +unsafe { core::mem::transmute (this) } + } + +/// Convert from [`Self::Repr`](AsRepr::Repr) to `Self`. +#[inline(always)] +fn from_repr (repr:Self ::Repr ) ->Self { +// SAFETY: Per safety requirement of the trait. +unsafe {transmute (repr) } + } +} + +// SAFETY: `bool` has the same size and alignment as `u8`, and Rust guarantees that `bool` has +// only two valid bit patterns: 0 (false) and 1 (true). Thus `bool` can be transmuted to `u8`. +// Neither types contain interior mutability. +unsafe impl AsRepr for bool { +type Repr =u8 ; +} + +// SAFETY: `*mut T` has the same size and alignment with `*const c_void`, and thus `*mut T` is +// transmutable to `*const c_void`. Neither types contain interior mutability. +unsafe impl <T >AsRepr for *mut T { +type Repr = *const c_void ; +} + +// SAFETY: `*mut T` is transmutable from `*const c_void`. +unsafe impl <T >AsReprMut for *mut T {} + +// SAFETY: `*const T` has the same size and alignment with `*const c_void`, and is transmutable to +// `*const c_void`. Neither types contain interior mutability. +unsafe impl <T >AsRepr for *const T { +type Repr = *const c_void ; +} + +// SAFETY: `*const T` is transmutable from `*const c_void`. +unsafe impl <T >AsReprMut for *const T {} + +macro_rules! int_impl { + ($($unsigned:ident $signed:ident ,)*) => {$( +// SAFETY: $unsigned has the same size and alignment with itself, and is transmutable to +// itself. It does not contain interior mutability. +unsafe impl AsRepr for $unsigned { +type Repr = $unsigned; + } + +// SAFETY: $unsigned is transmutable from itself. +unsafe impl AsReprMut for $unsigned {} + +// SAFETY: $signed has the same size and alignment with $unsigned, and is transmutable to it +// Neither types contain interior mutability. +unsafe impl AsRepr for $signed { +type Repr = $unsigned; + } + +// SAFETY: $signed is transmutable from $unsigned. +unsafe impl AsReprMut for $signed {} + )*}; +} + +int_impl! { +u8 i8 , +u16 i16 , +u32 i32 , +u64 i64 , +// `usize` is not normalized to particular integer for portability. +usize isize , +}
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
Some API like atomics and I/O operate on primitives only; therefore other types would need to converted to these primitive first. Add two traits
AsReprandAsReprMutto indicate that the type can be turned into a primitive for these operations.
T: AsReprmeans that&Tcan be viewed as&T::Reprand thus it needs to support transmutability in one direction.T: AsReprMutmeans that&mut Tcan be viewed as&mut T::Reprand thus it needs to support bi-directional transmutability.
Quoted 4 lines
To avoid duplicating implementations, all repr types are normalized to unsigned integers.
Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
In reply to Gary GuoOn Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
Quoted 27 lines
rust/kernel/mem.rs +27
-0+/// Type that is layout-compatible with a primitive representation. +/// +/// # Safety +/// +/// - `Self` must have the same size and alignment as [`Self::Repr`]. +/// - `Self` can be [transmutable] to [`Self::Repr`]. +/// - Neither `Self` nor [`Self::Repr`] contains interior mutability. +/// +/// The above basically says that `&Self` can be transmuted to `&Self::Repr`. +/// +/// [transmutable]: core::mem::transmute +pub unsafe trait AsRepr :Sized { +/// Primitive representation of this type. +type Repr ; + +/// Convert from `&Self` to [`&Self::Repr`](AsRepr::Repr). +#[inline(always)] +fn as_repr (this: &Self ) -> &Self ::Repr { +// SAFETY: Per safety requirement of the trait. +unsafe { core::mem::transmute (this) } + } + +/// Convert from `Self` to [`Self::Repr`]. +#[inline(always)] +fn into_repr (this:Self ) ->Self ::Repr { +// SAFETY: Per safety requirement of the trait. +unsafe {transmute (this) }
rust/kernel/mem.rs pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { · line 137
Quoted 10 lines
rust/kernel/mem.rs +10
-0+ } + +/// Convert from [`Self::Repr`] to `Self`. +/// +/// # Safety +/// +/// `repr` must be a valid bit pattern of `Self` and satisfy type-specific invariants of it. +/// +/// Alternatively, if `repr` is previously obtained using [`Self::into_repr`], and each +/// `from_repr_unchecked` should corresponds to a unique `into_repr` call, then it is safe to
nit: s/corresponds/correspond
rust/kernel/mem.rs pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { · line 142
Quoted 5 lines
rust/kernel/mem.rs +5
-0+/// call as well (this means that we're undoing a `into_repr` call getting the exact bytes +/// back). +/// +/// This method makes no guarantee if a `into_repr` corresponds to multiple +/// `from_repr_unchecked` (i.e. copies are made), to allow for cases where `Repr` is a pointer
This part doesn't parse for me; maybe it is worth rephrasing?
Something like "No guarantee is made if the result of a into_repr is passed to multiple from_repr_unchecked" reads a bit better IMHO.
<...>
Quoted 7 lines
rust/kernel/mem.rs +7
-0+// SAFETY: `*mut T` has the same size and alignment with `*const c_void`, and thus `*mut T` is +// transmutable to `*const c_void`. Neither types contain interior mutability. +unsafe impl <T >AsRepr for *mut T { +type Repr = *const c_void ; +} + +// SAFETY: `*mut T` is transmutable from `*const c_void`.
rust/kernel/mem.rs pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { · line 200
Quoted 10 lines
rust/kernel/mem.rs +10
-0+unsafe impl <T >AsReprMut for *mut T {} + +// SAFETY: `*const T` has the same size and alignment with `*const c_void`, and is transmutable to +// `*const c_void`. Neither types contain interior mutability. +unsafe impl <T >AsRepr for *const T { +type Repr = *const c_void ; +} + +// SAFETY: `*const T` is transmutable from `*const c_void`. +unsafe impl <T >AsReprMut for *const T {}
These pointer impls have no user in the series, should we wait until we have one to add them?
In any case,
Re: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
In reply to Gary GuoQuoted 2 lines · Gary Guo
+ /// Convert from
Selfto [Self::Repr].
I think [Self] etc. work too.
Quoted 1 line
+/// - [
Self] must be [transmutable] from [Self::Repr].
We say "can" in the AsRepr one -- we should be consistent.
rust/kernel/mem.rs pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { · line 178
Quoted 2 lines
rust/kernel/mem.rs +2
-0+// SAFETY: `bool` has the same size and alignment as `u8`, and Rust guarantees that `bool` has +// only two valid bit patterns: 0 (false) and 1 (true). Thus `bool` can be transmuted to `u8`.
false, true
Quoted 1 line
+ // SAFETY: $unsigned has the same size and alignment with itself, and is transmutable to
$unsigned (a few below).
Cheers,
Miguel
Gary Guo
maintainerRe: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
Quoted 5 lines · Miguel Ojeda
Quoted 2 lines · Gary Guo
+ /// Convert from
Selfto [Self::Repr].I think [
Self] etc. work too.
I'm not sure why we'd want a self link.
Best,
Gary
Quoted 16 lines
Quoted 2 lines
+/// - [
Self] must be [transmutable] from [Self::Repr].We say "can" in the
AsReprone -- we should be consistent.rust/kernel/mem.rs pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { · line 178
Quoted 2 lines
rust/kernel/mem.rs +2
-0+// SAFETY: `bool` has the same size and alignment as `u8`, and Rust guarantees that `bool` has +// only two valid bit patterns: 0 (false) and 1 (true). Thus `bool` can be transmuted to `u8`.
false,trueQuoted 1 line
+ // SAFETY: $unsigned has the same size and alignment with itself, and is transmutable to
$unsigned(a few below).Cheers,
Miguel
Re: [PATCH v4 03/16] rust: mem: add `AsRepr` and `AsReprMut`
Quoted 2 lines · Gary Guo
I'm not sure why we'd want a self link.
It is to follow the guideline about using intra-doc links on things that can be, which prevents mistakes and improves consistency, and in this case, for huge traits, it may help readers of the trait implementations section a bit.
Cheers,
Miguel
Gary Guo
maintainerPATCH v4 4/16 rust: io: perform conversions using `AsRepr`
In reply to Gary GuoFor types that are layout-compatible with an I/O capable type, we would want the ability to use them directly for I/O operations. E.g.
bitfield! {
pub struct Foo(u32) {
...
}
}
#[repr(C)]
struct Bar {
foo: Foo,
}
let mmio: Mmio<'_, Bar> = ...;
io_read!(mmio, .foo)Currently this feature is available from register!() macro but not otherwise available with io_read!, io_write!. Support this by performing conversions to I/O primitives via the AsRepr/AsReprMut trait.
This makes the IoLoc::IoType and Register::Storage redundant; thus remove them; also convert register methods to use the read_val and write_val instead.
--- rust/kernel/bitfield.rs | 9 ++++ rust/kernel/io.rs | 128 ++++++++++++++++++++++++--------------------- rust/kernel/io/register.rs | 15 ------ rust/macros/io/register.rs | 2 - 4 files changed, 78 insertions(+), 76 deletions(-)
rust/kernel/bitfield.rs +9 -0
@@ -346,6 +346,15 @@ fn from(val: $storage) -> $name {Self ::from_raw (val) } } + +// SAFETY: `$name` is transparent over `$storage` and `$storage` has no interior mutability. +unsafe impl $crate::mem::AsRepr for $name { +// Normalize `$storage` to the canonical repr type in case it is signed. +type Repr = <$storageas $crate::mem::AsRepr >::Repr ; + } + +// SAFETY: `$name` is transparent over `$storage`. +unsafe impl $crate::mem::AsReprMut for $name {} };// Definitions requiring knowledge of individual fields: private and public field accessors,
rust/kernel/io.rs +69 -59
330 lines not on this page · raw message
rust/kernel/io/register.rs +0 -15
@@ -117,9 +117,6 @@/// Trait implemented by all registers. pub trait Register :Sized { -/// Backing primitive type of the register. -type Storage :Into <Self > +From <Self >; -/// Start offset of the register. /// /// The interpretation of this offset depends on the type of the register.
@@ -135,8 +132,6 @@ impl<const SIZE: usize, T> IoLoc<Region<SIZE>, T> for () where T: FixedRegister, { - type IoType = T::Storage; - #[inline(always)] fn offset(self) -> usize {T ::OFFSET
@@ -149,8 +144,6 @@ impl<const SIZE: usize, T> IoLoc<Region<SIZE>, T> for T where T: FixedRegister, { - type IoType = T::Storage; - #[inline(always)] fn offset(self) -> usize {T ::OFFSET
@@ -174,8 +167,6 @@ impl<const SIZE: usize, T> IoLoc<Region<SIZE>, T> for FixedRegisterLoc<T> where T: FixedRegister, { - type IoType = T::Storage; - #[inline(always)] fn offset(self) -> usize {T ::OFFSET
@@ -246,8 +237,6 @@ impl<const SIZE: usize, T, B> IoLoc<Region<SIZE>, T> for RelativeRegisterLoc<T, T: RelativeRegister, B: RegisterBase<T::BaseFamily> + ?Sized, { -type IoType =T ::Storage ; -#[inline(always)] fn offset (self) ->usize {RelativeRegisterLoc ::offset (self)
@@ -289,8 +278,6 @@ impl<const SIZE: usize, T> IoLoc<Region<SIZE>, T> for RegisterArrayLoc<T> where T: RegisterArray, { - type IoType = T::Storage; - #[inline(always)] fn offset(self) -> usize {T ::OFFSET + self.0 *T ::STRIDE
@@ -377,8 +364,6 @@ impl<const SIZE: usize, T, B> IoLoc<Region<SIZE>, T> for RelativeRegisterArrayLo T: RelativeRegisterArray, B: RegisterBase<T::BaseFamily> + ?Sized, { -type IoType =T ::Storage ; -#[inline(always)] fn offset (self) ->usize { self.0 .offset () + self.1 *T ::STRIDE
rust/macros/io/register.rs +0 -2
@@ -213,8 +213,6 @@ pub(crate) fn register(def: RegDef) -> Result<TokenStream> { ); impl ::kernel::io::register::Register for #name { - type Storage = #storage; - const OFFSET: usize = #offset; } ));
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 04/16] rust: io: perform conversions using `AsRepr`
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 22 lines
For types that are layout-compatible with an I/O capable type, we would want the ability to use them directly for I/O operations. E.g.
bitfield! { pub struct Foo(u32) { ... } } #[repr(C)] struct Bar { foo: Foo, } let mmio: Mmio<'_, Bar> = ...; io_read!(mmio, .foo)Currently this feature is available from
register!()macro but not otherwise available withio_read!,io_write!. Support this by performing conversions to I/O primitives via theAsRepr/AsReprMuttrait.
Quoted 6 lines
This makes the
IoLoc::IoTypeandRegister::Storageredundant; thus remove them; also convert register methods to use theread_valandwrite_valinstead.Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Gary Guo
maintainerPATCH v4 5/16 rust: io: support register projections
In reply to Gary GuoIoLocs themselves just describe a projection from a region to a concrete register. Thus, support it in io_project macro too. Also, update methods that operate on IoLoc to use I/O projection.
Documentation of io_project! is not expanded yet as the example works better when register! type can specify base type. io_read! and io_write! gains the ability to operate on registers as corollary of the capability of io_project!. Examples are not added because read and write is still preferrably used instead.
--- rust/kernel/io.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 46 insertions(+), 10 deletions(-)
rust/kernel/io.rs +46 -10
@@ -857,8 +857,7 @@ fn try_read<T, L>(self, location: L) -> Result<T> L: IoLoc<Self::Target, T>, Self::Backend: IoCapable<<T as AsRepr>::Repr>, { -let view =io_view ::<Self ,T >(self, location.offset ())?; -Ok (view.read_val ()) +Ok (io_read! (self, try: location)) }/// Generic fallible write with runtime bounds check.
@@ -891,8 +890,7 @@ fn try_write<T, L>(self, location: L, value: T) -> Result L: IoLoc<Self::Target, T>, Self::Backend: IoCapable<<T as AsRepr>::Repr>, { -let view =io_view ::<Self ,T >(self, location.offset ())?; - view.write_val (value); +io_write! (self, try: location, value);Ok (()) }
@@ -971,7 +969,7 @@ fn try_update<T, L, F>(self, location: L, f: F) -> Result Self::Backend: IoCapable<<T as AsRepr>::Repr>, F: FnOnce(T) -> T, { -let view =io_view ::<Self ,T >(self, location.offset ())?; +let view =io_project! (self, try: location); view.write_val (f (view.read_val ()));Ok (()) }
@@ -1004,8 +1002,7 @@ fn read<T, L>(self, location: L) -> T L: IoLoc<Self::Target, T>, Self::Backend: IoCapable<<T as AsRepr>::Repr>, { -let view =io_view_assert ::<Self ,T >(self, location.offset ()); - view.read_val () +io_read! (self, build: location) }/// Generic infallible write with compile-time bounds check.
@@ -1036,8 +1033,7 @@ fn write<T, L>(self, location: L, value: T) L: IoLoc<Self::Target, T>, Self::Backend: IoCapable<<T as AsRepr>::Repr>, { -let view =io_view_assert ::<Self ,T >(self, location.offset ()); - view.write_val (value) +io_write! (self, build: location, value); }/// Generic infallible write of a fully-located register value.
@@ -1114,7 +1110,7 @@ fn update<T, L, F>(self, location: L, f: F) Self::Backend: IoCapable<<T as AsRepr>::Repr>, F: FnOnce(T) -> T, { -let view =io_view_assert ::<Self ,T >(self, location.offset ()); +let view =io_project! (self, build: location); view.write_val (f (view.read_val ())); } }
@@ -1659,6 +1655,25 @@ pub unsafe fn project_view<U: ?Sized + KnownSize>(// SAFETY: Per safety requirement. unsafe {T ::Backend ::project_view ::<T ::Target ,_ >(self.0 , ptr) } } + +#[inline(always)] +pub fn try_project_loc <U ,L >( + self, + location:L , + ) ->Result <<T ::Backend as IoBackend >::View <'a,U >> +where +L :IoLoc <T ::Target ,U >, + { +io_view ::<_ ,U >(self.0 , location.offset ()) + } + +#[inline(always)] +pub fn project_loc <U ,L >(self, location:L ) -> <T ::Backend as IoBackend >::View <'a,U > +where +L :IoLoc <T ::Target ,U >, + { +io_view_assert ::<_ ,U >(self.0 , location.offset ()) + } }/// Project an I/O type to a subview of it.
@@ -1686,6 +1701,21 @@ pub unsafe fn project_view<U: ?Sized + KnownSize>(#[macro_export] #[doc(hidden)] macro_rules! io_project { +// Register projection + ($io:expr, try: $ioloc:expr) => {{ +#[allow(unused)] +use $crate::io::IoBase as _; +let view = $crate::io::ProjectHelper ($io.as_view ()); + view.try_project_loc ($ioloc)? + }}; + ($io:expr, build: $ioloc:expr) => {{ +#[allow(unused)] +use $crate::io::IoBase as _; +let view = $crate::io::ProjectHelper ($io.as_view ()); + view.project_loc ($ioloc) + }}; + +// Field or index projection ($io:expr, $($proj:tt)*) => {{#[allow(unused)] use $crate::io::IoBase as _;
@@ -1756,6 +1786,12 @@ macro_rules! io_write { (@parse [$io:expr] [$($proj:tt)*] [[$flavor:ident: $index:expr] $($rest:tt)*]) => { $crate::io_write!(@parse [$io] [$($proj)* [$flavor: $index]] [$($rest)*]) }; + (@parse [$io:expr] [] [try: $ioloc:expr, $($rest:tt)*]) => { + $crate::io_write!(@parse [$io] [try: $ioloc] [, $($rest)*]) + }; + (@parse [$io:expr] [] [build: $ioloc:expr, $($rest:tt)*]) => { + $crate::io_write!(@parse [$io] [build: $ioloc] [, $($rest)*]) + }; ($io:expr, $($rest:tt)*) => { $crate::io_write!(@parse [$io] [] [$($rest)*]) };
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 05/16] rust: io: support register projections
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 4 lines
IoLocs themselves just describe a projection from a region to a concrete register. Thus, support it inio_projectmacro too. Also, update methods that operate onIoLocto use I/O projection.
Quoted 8 lines
Documentation of
io_project!is not expanded yet as the example works better whenregister!type can specify base type.io_read!andio_write!gains the ability to operate on registers as corollary of the capability ofio_project!. Examples are not added becausereadandwriteis still preferrably used instead.Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Gary Guo
maintainerPATCH v4 6/16 rust: io: register: allow explicit base type specification
In reply to Gary GuoCurrently registers work for all untyped I/O regions, which is not ideal. It allows registers defined for device A to work for another device B and there is no safeguarding at all.
All users of the register! macro know what type it will be operating on, and that type is consistent across the driver. Therefore, add a base parameter to register!.
Currently this parameter is unused in the generated code; it will be used when all users of register! is converted to gain the parameter.
---
Changes since v3:
- Add a dummy user of base to prevent warning on user side (this is present in v2 but I forgot to add it in v3's proc macro rewrite).
--- rust/kernel/io.rs | 4 ++++ rust/kernel/io/register.rs | 51 +++++++++++++++++++++++++++++++++++++++------- rust/macros/io/register.rs | 23 ++++++++++++++++++++- 3 files changed, 70 insertions(+), 8 deletions(-)
rust/kernel/io.rs +4 -0
@@ -909,6 +909,8 @@ fn try_write<T, L>(self, location: L, value: T) -> Result/// }; /// /// register! { +/// base: Region; +/// /// VERSION(u32) @ 0x100 { /// 15:8 major; /// 7:0 minor;
@@ -1051,6 +1053,8 @@ fn write<T, L>(self, location: L, value: T)/// }; /// /// register! { +/// base: Region<0x1000>; +/// /// VERSION(u32) @ 0x100 { /// 15:8 major; /// 7:0 minor;
rust/kernel/io/register.rs +44 -7
171 lines not on this page · raw message
rust/macros/io/register.rs +22 -1
@@ -29,6 +29,7 @@ };mod kw { + syn::custom_keyword!(base); syn::custom_keyword!(stride); }
@@ -152,22 +153,42 @@ fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> { }pub (crate )struct RegDef { +#[allow(unused)] + base:Option <Type >, regs:Vec <Reg >, }impl Parse for RegDef {fn parse (input: syn::parse::ParseStream <'_>) ->Result <Self > { +let base =if input.peek (kw::base) { +let _: kw::base = input.parse ()?; +let _:Token! [:] = input.parse ()?; +let base = input.parse ()?; +let _:Token! [;] = input.parse ()?; +Some (base) + }else { +None + };let mut regs =Vec ::new ();while !input.is_empty () { regs.push (input.parse ()?); } -Ok (RegDef { regs }) +Ok (RegDef { base, regs }) } }pub (crate )fn register (def:RegDef ) ->Result <TokenStream > {let mut outputs =TokenStream ::new (); +if let Some (base) = &def.base { + outputs.extend (quote_spanned! (base.span () => +const _: () = { +#[allow(unused)] +type Base = #base ; + }; + )); + } +for regin def.regs {let Reg { attrs,
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 06/16] rust: io: register: allow explicit base type specification
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 4 lines
Currently registers work for all untyped I/O regions, which is not ideal. It allows registers defined for device A to work for another device B and there is no safeguarding at all.
Quoted 8 lines
All users of the
register!macro know what type it will be operating on, and that type is consistent across the driver. Therefore, add abaseparameter toregister!.Currently this parameter is unused in the generated code; it will be used when all users of
register!is converted to gain the parameter.Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Re: [PATCH v4 06/16] rust: io: register: allow explicit base type specification
In reply to Gary GuoQuoted 4 lines · Gary Guo
Currently registers work for all untyped I/O regions, which is not ideal. It allows registers defined for device A to work for another device B and there is no safeguarding at all.
Quoted 8 lines
All users of the
register!macro know what type it will be operating on, and that type is consistent across the driver. Therefore, add abaseparameter toregister!.Currently this parameter is unused in the generated code; it will be used when all users of
register!is converted to gain the parameter.Signed-off-by Gary Guo <[email protected]>
With one nittynit below.
Quoted 13 lines
rust/macros/io/register.rs +1
-0@@ -29,6 +29,7 @@ };mod kw { + syn::custom_keyword!(base); syn::custom_keyword!(stride); }
rust/macros/io/register.rs fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> { · line 156
Quoted 4 lines
rust/macros/io/register.rs +1
-0@@ -152,22 +153,42 @@ fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> { }pub (crate )struct RegDef { + #[allow(unused)]
Now that the field is used, this can go away (also generally I believe we prefer to use expect to catch such cases).
Gary Guo
maintainerPATCH v4 7/16 gpu: nova-core: specify base type for registers
In reply to Gary GuoAll registers use the same base type, which is <Bar0 as IO>::Target. Thus add the base parameter to register! invocation.
--- drivers/gpu/nova-core/driver.rs | 1 + drivers/gpu/nova-core/fb/regs.rs | 12 ++++++++++++ drivers/gpu/nova-core/gsp/regs.rs | 9 ++++++++- drivers/gpu/nova-core/regs.rs | 37 ++++++++++++++++++++++++++++++++++++- drivers/gpu/nova-core/vbios.rs | 11 ++++++++++- 5 files changed, 67 insertions(+), 3 deletions(-)
drivers/gpu/nova-core/driver.rs +1 -0
@@ -37,6 +37,7 @@ pub(crate) struct NovaCore<'bound> {const BAR0_SIZE :usize =SZ_16M ;pub (crate )type Bar0 <'a> = &'a pci::Bar <'a,BAR0_SIZE >; +pub (crate )type NovaRegisters = kernel::io::Region <BAR0_SIZE >; kernel::pci_device_table!(PCI_TABLE ,
drivers/gpu/nova-core/fb/regs.rs +12 -0
@@ -5,9 +5,13 @@ sizes::SizeConstants, // }; +use crate ::driver::NovaRegisters ; +// PDISP register! { + base:NovaRegisters ; +pub (super )NV_PDISP_VGA_WORKSPACE_BASE (u32 ) @0x00625f04 {/// VGA workspace base address divided by 0x10000. 31 :8 addr;
@@ -30,6 +34,8 @@ pub(super) fn vga_workspace_addr(self) -> Option<u64> {// PFB register! { + base:NovaRegisters ; +/// Low bits of the physical system memory address used by the GPU to perform sysmembar /// operations (see [`crate::fb::SysmemFlush`]). pub (super )NV_PFB_NISO_FLUSH_SYSMEM_ADDR (u32 ) @0x00100c10 {
@@ -65,6 +71,8 @@ pub(super) fn vga_workspace_addr(self) -> Option<u64> {pub (super )struct Hshub0Base (());register! { + base:NovaRegisters ; +// GB10x sysmem flush registers, relative to the HSHUB0 base. GB10x routes sysmembar // through a primary and an EG (egress) pair that must both be programmed to the same // address. Hardware ignores bits 7:0 of each LO register. The boot path uses a fixed
@@ -87,6 +95,8 @@ pub(super) fn vga_workspace_addr(self) -> Option<u64> { }register! { + base:NovaRegisters ; +// GB20x FBHUB0 sysmem flush registers. Unlike the older // NV_PFB_NISO_FLUSH_SYSMEM_ADDR registers, which encode the address with an // 8-bit right-shift, these take the raw address split into lower and upper
@@ -101,6 +111,8 @@ pub(super) fn vga_workspace_addr(self) -> Option<u64> { }register! { + base:NovaRegisters ; +/// Low bits of the physical system memory address used by the GPU to perform /// sysmembar operations on Hopper. ///
drivers/gpu/nova-core/gsp/regs.rs +8 -1
@@ -2,11 +2,16 @@use kernel::io::register; -use crate ::regs::NV_PBUS_SW_SCRATCH ; +use crate ::{ + driver::NovaRegisters , + regs::NV_PBUS_SW_SCRATCH ,// +};// PGSP register! { + base:NovaRegisters ; +pub (super )NV_PGSP_QUEUE_HEAD (u32 ) @0x00110c00 {31 :0 address; }
@@ -15,6 +20,8 @@// PBUS register! { + base:NovaRegisters ; +/// Scratch register 0xe used as FRTS firmware error code. pub (super )NV_PBUS_SW_SCRATCH_0E_FRTS_ERR (u32 ) =>NV_PBUS_SW_SCRATCH [0xe ] {31 :16 frts_err_code;
drivers/gpu/nova-core/regs.rs +36 -1
@@ -13,7 +13,10 @@ };use crate ::{ - driver::Bar0 , + driver::{ +Bar0 , +NovaRegisters ,// + }, falcon::{DmaTrfCmdSize ,FalconCoreRev ,
@@ -37,6 +40,8 @@// PMC register! { + base:NovaRegisters ; +/// Basic revision information about the GPU. pub (crate )NV_PMC_BOOT_0 (u32 ) @0x00000000 {/// Lower bits of the architecture.
@@ -108,6 +113,8 @@ fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {// PBUS register! { + base:NovaRegisters ; +pub (crate )NV_PBUS_SW_SCRATCH (u32 )[64 ] @0x00001400 {} }
@@ -121,6 +128,8 @@ fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {// number. register! { + base:NovaRegisters ; +/// Boot Sequence Interface (BSI) register used to determine /// if GSP reload/resume has completed during the boot process. pub (crate )NV_PGC6_BSI_SECURE_SCRATCH_14 (u32 ) @0x001180f8 {
@@ -175,6 +184,8 @@ pub(crate) fn usable_fb_size(self) -> u64 {pub (crate )const NV_FUSE_OPT_FPF_SIZE :usize =16 ;register! { + base:NovaRegisters ; +pub (crate )NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION (u32 )[NV_FUSE_OPT_FPF_SIZE ] @0x00824100 {15 :0 data =>u16 ; }
@@ -191,6 +202,8 @@ pub(crate) fn usable_fb_size(self) -> u64 {// PFALCON register! { + base:NovaRegisters ; +pub (crate )NV_PFALCON_FALCON_IRQSCLR (u32 ) @PFalconBase +0x00000004 {6 :6 swgen0 =>bool ;4 :4 halt =>bool ;
@@ -392,6 +405,8 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {/* PFALCON2 */ register! { + base:NovaRegisters ; +pub (crate )NV_PFALCON2_FALCON_MOD_SEL (u32 ) @PFalcon2Base +0x00000180 {7 :0 algo ?=>FalconModSelAlgo ; }
@@ -414,6 +429,8 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {// PRISCV register! { + base:NovaRegisters ; +/// RISC-V status register for debug (Turing and GA100 only). /// Reflects current RISC-V core status. pub (crate )NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS (u32 ) @PFalcon2Base +0x00000240 {
@@ -439,6 +456,8 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {// These registers manage falcon EMEM communication queues. register! { + base:NovaRegisters ; +pub (crate )NV_PFSP_QUEUE_HEAD (u32 )[8 ] @0x008f2c00 {31 :0 address =>u32 ; }
@@ -462,9 +481,13 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {pub (crate )mod gm107 {use kernel::io::register; +use crate ::driver::NovaRegisters ; +// FUSE register! { + base:NovaRegisters ; +pub (crate )NV_FUSE_STATUS_OPT_DISPLAY (u32 ) @0x00021c04 {0 :0 display_disabled =>bool ; }
@@ -474,9 +497,13 @@ pub(crate) mod gm107 {pub (crate )mod ga100 {use kernel::io::register; +use crate ::driver::NovaRegisters ; +// FUSE register! { + base:NovaRegisters ; +pub (crate )NV_FUSE_STATUS_OPT_DISPLAY (u32 ) @0x00820c04 {0 :0 display_disabled =>bool ; }
@@ -488,9 +515,13 @@ pub(crate) mod ga100 {pub (crate )mod gh100 {use kernel::io::register; +use crate ::driver::NovaRegisters ; +// PTHERM register! { + base:NovaRegisters ; +pub (crate )NV_THERM_I2CS_SCRATCH (u32 ) @0x000200bc {31 :0 data; }
@@ -505,9 +536,13 @@ pub(crate) mod gh100 {pub (crate )mod gb202 {use kernel::io::register; +use crate ::driver::NovaRegisters ; +// PTHERM register! { + base:NovaRegisters ; +pub (crate )NV_THERM_I2CS_SCRATCH (u32 ) @0x00ad00bc {31 :0 data; }
drivers/gpu/nova-core/vbios.rs +10 -1
@@ -16,7 +16,10 @@ };use crate ::{ - driver::Bar0 , + driver::{ +Bar0 , +NovaRegisters ,// + }, firmware::{ fwsec::Bcrt30Rsa3kSignature ,FalconUCodeDesc ,
@@ -92,12 +95,16 @@ impl<'a> VbiosIterator<'a> {fn rom_offset (dev: &device::Device , bar0:Bar0 <'_>) ->Result <usize > {// IFR Header in VBIOS. register! { + base:NovaRegisters ; +NV_PBUS_IFR_FMT_FIXED0 (u32 ) @0x300000 {31 :0 signature; } }register! { + base:NovaRegisters ; +NV_PBUS_IFR_FMT_FIXED1 (u32 ) @0x300004 {30 :16 fixed_data_size;15 :8 version =>u8 ;
@@ -105,6 +112,8 @@ fn rom_offset(dev: &device::Device, bar0: Bar0<'_>) -> Result<usize> { }register! { + base:NovaRegisters ; +NV_PBUS_IFR_FMT_FIXED2 (u32 ) @0x300008 {19 :0 total_data_size; }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 07/16] gpu: nova-core: specify base type for registers
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
All registers use the same base type, which is
<Bar0 as IO>::Target. Thus add the base parameter toregister!invocation.Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Gary Guo
maintainerPATCH v4 8/16 drm/tyr: specify base type for registers
In reply to Gary GuoAll registers use the same base type, which is <IoMem as IO>::Target. Thus add the base parameter to register! invocation.
--- drivers/gpu/drm/tyr/driver.rs | 1 + drivers/gpu/drm/tyr/fw.rs | 5 ++++- drivers/gpu/drm/tyr/regs.rs | 45 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 49 insertions(+), 2 deletions(-)
drivers/gpu/drm/tyr/driver.rs +1 -0
@@ -46,6 +46,7 @@ };pub (crate )type IoMem <'a> = kernel::io::mem::IoMem <'a,SZ_2M >; +pub (crate )type TyrRegisters = kernel::io::Region <SZ_2M >;pub (crate )struct TyrDrmDriver ;
drivers/gpu/drm/tyr/fw.rs +4 -1
@@ -39,7 +39,8 @@use crate ::{ driver::{IoMem , -TyrDrmDevice ,// +TyrDrmDevice , +TyrRegisters ,// }, fw::parser::{FwParser ,
@@ -101,6 +102,8 @@ fn from(value: CacheMode) -> Self { }register! { + base:TyrRegisters ; +#[allow(non_upper_case_globals)] pub (super )SectionFlags (u32 ) @0x0 {0 :0 read =>bool ;
drivers/gpu/drm/tyr/regs.rs +44 -1
164 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 08/16] drm/tyr: specify base type for registers
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Out-of-bounds Register Definition: The `DOORBELL` register array exceeds the maximum size of its…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Out-of-bounds Register Definition: The DOORBELL register array exceeds the maximum size of its specified base type TyrRegisters.
- [Low] API Misuse: Applying base: TyrRegisters; to purely in-memory bitfields allows them to silently alias hardware MMIO registers. --
commit 1d550d1a42720086769c2c8dc9fd2f019102d497
Author: Gary Guo <[email protected]>
drm/tyr: specify base type for registers
This commit updates register definitions to specify TyrRegisters as the base type for all register! invocations.
Quoted 9 lines
drivers/gpu/drm/tyr/driver.rs +1
-0@@ -46,6 +46,7 @@ };pub (crate )type IoMem <'a> = kernel::io::mem::IoMem <'a,SZ_2M >; +pub (crate )type TyrRegisters = kernel::io::Region <SZ_2M >;
[ ... ]
drivers/gpu/drm/tyr/fw.rs fn from(value: CacheMode) -> Self { · line 109
Quoted 13 lines
drivers/gpu/drm/tyr/fw.rs +2
-0@@ -101,6 +102,8 @@ fn from(value: CacheMode) -> Self { }register! { + base:TyrRegisters ; +#[allow(non_upper_case_globals)] pub (super )SectionFlags (u32 ) @0x0 {0 :0 read =>bool ;
[Severity: Low]
Does applying an MMIO base to this firmware struct unintentionally allow it to be used in hardware I/O operations?
By specifying base: TyrRegisters; and @ 0x0, SectionFlags gains I/O traits tied to the hardware MMIO base. Since this appears to be an in-memory bitfield used for parsing firmware, should the bitfield! macro be used instead to prevent it from silently aliasing hardware registers?
[ ... ]
Quoted 4 lines
drivers/gpu/drm/tyr/regs.rs +0
-0
[ ... ]
drivers/gpu/drm/tyr/regs.rs fn from(val: MemoryType) -> Self { · line 1138
Quoted 9 lines
drivers/gpu/drm/tyr/regs.rs +2
-0@@ -1104,6 +1131,8 @@ fn from(val: MemoryType) -> Self { }register! { + base:TyrRegisters ; +/// Stage 1 memory attributes (8-bit bitfield). /// /// This is not an actual register, but a bitfield definition used by the MEMATTR
[Severity: Low]
Similar to SectionFlags above, the comment explicitly notes this is not an actual register. Does adding base: TyrRegisters; here mistakenly grant it MMIO traits and allow accidental I/O operations?
[ ... ]
drivers/gpu/drm/tyr/regs.rs pub(crate) mod doorbell_block { · line 1818
Quoted 9 lines
drivers/gpu/drm/tyr/regs.rs +2
-0@@ -1770,6 +1811,8 @@ pub(crate) mod doorbell_block {const STRIDE :usize =0x10000 ;register! { + base:TyrRegisters ; +/// Doorbell request register. Write-only. pub (crate )DOORBELL (u32 )[NUM_DOORBELLS , stride =STRIDE ] @0x80000 {/// Doorbell set. Writing 1 triggers the doorbell.
[Severity: Medium]
Does this base type provide enough address space for the entire array?
TyrRegisters is defined in driver.rs as kernel::io::Region<SZ_2M> (a 2MB limit). However, the DOORBELL array has 64 elements (NUM_DOORBELLS) with a stride of 0x10000 and starts at offset 0x80000.
Accessing higher indices in this array will exceed the 2MB limit (e.g., the maximum offset is 0x80000 + 63 * 0x10000 = 0x470000, ~4.5MB). Will this result in a build assertion failure or runtime out-of-bounds error when upper doorbell indices are accessed?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Gary Guo
maintainerPATCH v4 9/16 samples: rust: pci: specify base type for registers
In reply to Gary GuoThe register! macro is going to require explicit base type, specify it for both register! usages in PCI sample driver.
--- samples/rust/rust_driver_pci.rs | 4 ++++ 1 file changed, 4 insertions(+)
samples/rust/rust_driver_pci.rs +4 -0
@@ -23,6 +23,8 @@ mod regs {use super ::*;register! { + base: kernel::io::Region <END >; +pub (super )TEST (u8 ) @0x0 {7 :0 index =>TestIndex ; }
@@ -102,6 +104,8 @@ fn config_space(pdev: &pci::Device<Bound>) {// Some PCI configuration space registers. register! { + base: pci::Normal ; +VENDOR_ID (u16 ) @0x0 {15 :0 vendor_id; }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 09/16] samples: rust: pci: specify base type for registers
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
The
register!macro is going to require explicit base type, specify it for bothregister!usages in PCI sample driver.Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Gary Guo
maintainerPATCH v4 10/16 rust: io: register: make register have a typed base
In reply to Gary GuoPreviously register! defined registers can be used on any untyped I/O regions. With all users specifying their desired register type now, propagate the specified type and restrict I/O access only when type matches.
Also, add an io_project! example which is enabled by this change.
---
Changes since v3:
- Adopted Alex's map_err suggestion
- Moved the "const eval only" comment slightly down and updated the build_assert to just a plain assert.
--- rust/kernel/io.rs | 13 +++++++++++ rust/kernel/io/register.rs | 54 ++++++++++++++++++++++++++++++++-------------- rust/macros/io/register.rs | 45 +++++++++++++++----------------------- 3 files changed, 68 insertions(+), 44 deletions(-)
rust/kernel/io.rs +13 -0
@@ -1685,21 +1685,34 @@ pub fn project_loc<U, L>(self, location: L) -> <T::Backend as IoBackend>::View<'/// The syntax is of form `io_project!(io, proj)` where `io` is an expression to a type that /// implements [`Io`] and `proj` is a [projection specification](kernel::ptr::project!). /// +/// `io_project!` can also project to a subview of registers defined with [`register!`] macro. +/// Register projection has syntax `io_project!(io, try: REGISTER)` for fallible projection and +/// `io_project!(io, build: REGISTER)` for infallible projection. +/// /// # Examples /// /// ``` /// use kernel::io::{ /// io_project, +/// register, /// Mmio, /// }; /// #[repr(C)] /// struct MyStruct { field: u32, } /// +/// register! { +/// base: MyStruct; +/// FIELD(u32) @ 0 { +/// 31:0 val; +/// } +/// } +/// /// # fn test(mmio: Mmio<'_, [MyStruct]>) -> Result { /// // let mmio: Mmio<[MyStruct]>; /// let field: Mmio<'_, u32> = io_project!(mmio, [try: 1].field); /// let whole: Mmio<'_, MyStruct> = io_project!(mmio, [try: 2]); /// let nested: Mmio<'_, u32> = io_project!(whole, .field); +/// let reg: Mmio<'_, FIELD> = io_project!(whole, build: FIELD); /// # Ok::<(), Error>(()) } /// ``` #[macro_export]
rust/kernel/io/register.rs +38 -16
117 lines not on this page · raw message
rust/macros/io/register.rs +17 -28
84 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 10/16] rust: io: register: make register have a typed base
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
Previously
register!defined registers can be used on any untyped I/O regions. With all users specifying their desired register type now, propagate the specified type and restrict I/O access only when type matches.Also, add an
io_project!example which is enabled by this change.Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Re: [PATCH v4 10/16] rust: io: register: make register have a typed base
In reply to Gary GuoQuoted 8 lines · Gary Guo
Previously
register!defined registers can be used on any untyped I/O regions. With all users specifying their desired register type now, propagate the specified type and restrict I/O access only when type matches.Also, add an
io_project!example which is enabled by this change.Signed-off-by Gary Guo <[email protected]>
Gary Guo
maintainerPATCH v4 11/16 rust: io: register: support fixed offset register without bitfield
In reply to Gary GuoAdd a rule to allow creating IoLoc in register!() using an existing type and not create a bitfield. Add an example to demonstrate this for FIFO registers.
This rule is also going to be used to create subregions for registers; the example of doing so will be added later when relative registers are removed.
--- rust/kernel/io/register.rs | 31 +++++++++++++++++ rust/macros/io/register.rs | 84 +++++++++++++++++++++++++++++++--------------- 2 files changed, 88 insertions(+), 27 deletions(-)
rust/kernel/io/register.rs +31 -0
@@ -182,6 +182,24 @@ fn offset(self) -> usize { } } +// Provides a `IoLoc` impl that for a fixed offset. +#[doc(hidden)] +pub struct OffsetLoc <Base : ?Sized ,T >(usize ,PhantomData <(T ,Base )>); + +impl <Base : ?Sized ,T >OffsetLoc <Base ,T > { +#[inline] +pub const fn new (offset:usize ) ->Self { +Self (offset,PhantomData ) + } +} + +impl <Base : ?Sized ,T >IoLoc <Base ,T >for OffsetLoc <Base ,T > { +#[inline(always)] +fn offset (self) ->usize { + self.0 + } +} +/// Trait providing a base address to be added to the offset of a relative register to obtain /// its actual offset. ///
@@ -520,6 +538,19 @@ pub const fn element_alias_offset<Base: ?Sized, Alias: RegisterArray<Base = Base/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while providing /// its own `completed` field. /// +/// If you do not wish to have a bitfield defined, you can also create a register using an existing +/// type. +/// +/// ```no_run +/// # use kernel::io::*; +/// register! { +/// base: Region<0x1000>; +/// +/// /// UART RX register. +/// pub UART_RX: u8 @ 0x100; +/// } +/// ``` +/// /// ## Relative registers /// /// Relative registers can be instantiated several times at a relative offset of a group of bases.
rust/macros/io/register.rs +57 -27
151 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 11/16] rust: io: register: support fixed offset register without bitfield
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
Add a rule to allow creating
IoLocinregister!()using an existing type and not create a bitfield. Add an example to demonstrate this for FIFO registers.This rule is also going to be used to create subregions for registers; the example of doing so will be added later when relative registers are removed.
Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Gary Guo
maintainerPATCH v4 12/16 gpu: nova-core: use projection for PFALCON and PFALCON2 registers
In reply to Gary GuoAdd fixed size region types PFalconRegisters and PFalcon2Registers and update PFALCON and PFALCON2 registers to be fixed register on them and not relative registers on NovaRegisters.
Update Falcon struct to store projected views when constructing and access with self.pfalcon and self.pfalcon2.
---
Changes since v3:
- Add PFALCON_REGION_SIZE and PFALCON2_REGION_SIZE constants (Alex).
- Add TODO comment to remove pub(crate) of pfalcon
--- drivers/gpu/nova-core/falcon.rs | 161 +++++++++------------ drivers/gpu/nova-core/falcon/fsp.rs | 63 ++++---- drivers/gpu/nova-core/falcon/gsp.rs | 51 ++++--- drivers/gpu/nova-core/falcon/hal/ga102.rs | 59 +++----- drivers/gpu/nova-core/falcon/hal/tu102.rs | 9 +- drivers/gpu/nova-core/falcon/sec2.rs | 37 +++-- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 18 +-- drivers/gpu/nova-core/gsp/hal/tu102.rs | 7 +- drivers/gpu/nova-core/regs.rs | 92 ++++++------ 9 files changed, 239 insertions(+), 258 deletions(-)
drivers/gpu/nova-core/falcon.rs +71 -90
@@ -14,13 +14,12 @@ io::{ io_project, poll::read_poll_timeout, - register::{ - RegisterBase, -WithBase ,// - }, + register::Array,Io , +Mmio ,// }, prelude::*, + sizes::SZ_4K, time::Delta, };
@@ -165,18 +164,25 @@ pub(crate) enum FalconFbifMemType with From<Bounded<u32, 1>> { } } -/// Type used to represent the `PFALCON` registers address base for a given falcon engine. -pub (crate )struct PFalconBase (()); +const PFALCON_REGION_SIZE :usize =SZ_4K ; +const PFALCON2_REGION_SIZE :usize =SZ_4K ; -/// Type used to represent the `PFALCON2` registers address base for a given falcon engine. -pub (crate )struct PFalcon2Base (()); +/// Type used to represent the `PFALCON` registers. +#[repr(align( 4 ))] +#[derive( FromBytes , IntoBytes )] +pub (crate )struct PFalconRegisters ([u8 ;PFALCON_REGION_SIZE ]); + +/// Type used to represent the `PFALCON2` registers. +#[repr(align( 4 ))] +#[derive( FromBytes , IntoBytes )] +pub (crate )struct PFalcon2Registers ([u8 ;PFALCON2_REGION_SIZE ]);/// Trait defining the parameters of a given Falcon engine. /// /// Each engine provides one base for `PFALCON` and `PFALCON2` registers. -pub (crate )trait FalconEngine : -Send +Sync +RegisterBase <PFalconBase > +RegisterBase <PFalcon2Base > +Sized -{ +pub (crate )trait FalconEngine :Send +Sync +Sized { +fn pfalcon (io:Bar0 <'_>) ->Mmio <'_,PFalconRegisters >; +fn pfalcon2 (io:Bar0 <'_>) ->Mmio <'_,PFalcon2Registers >; }/// Represents a portion of the firmware to be loaded into a particular memory (e.g. IMEM or DMEM)
@@ -358,6 +364,9 @@ pub(crate) struct Falcon<'a, E: FalconEngine> { hal: KBox<dyn FalconHal<E>>, dev: &'a device::Device<device::Bound>, bar: Bar0<'a>, +// TODO: make private + pub(crate) pfalcon: Mmio<'a, PFalconRegisters>, + pfalcon2: Mmio<'a, PFalcon2Registers>, }impl <'a,E :FalconEngine + 'static>Falcon <'a,E > {
@@ -371,19 +380,19 @@ pub(crate) fn new( hal: hal::falcon_hal(chipset)?, dev, bar, + pfalcon: E::pfalcon(bar), + pfalcon2: E::pfalcon2(bar), }) }/// Resets DMA-related registers. pub (crate )fn dma_reset (&self) { - self.bar.update (regs::NV_PFALCON_FBIF_CTL ::of ::<E >(), |v| { + self.pfalcon.update (regs::NV_PFALCON_FBIF_CTL , |v| { v.with_allow_phys_no_ctx (true ) }); - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_DMACTL ::zeroed (), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_DMACTL ::zeroed ()); }/// Reset the controller, select the falcon core, and wait for memory scrubbing to complete.
@@ -392,10 +401,9 @@ pub(crate) fn reset(&self) -> Result { self.hal.select_core (self)?; self.hal.reset_wait_mem_scrubbing (self)?; - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_RM ::from (self.bar.read (regs::NV_PMC_BOOT_0 ).into_raw ()), - ); + self.pfalcon.write_reg (regs::NV_PFALCON_FALCON_RM ::from ( + self.bar.read (regs::NV_PMC_BOOT_0 ).into_raw (), + ));Ok (()) }
@@ -413,8 +421,8 @@ fn pio_wr_imem_slice(&self, load_offsets: FalconPioImemLoadTarget<'_>) -> Resultreturn Err (EINVAL ); } - self.bar.write ( -WithBase ::of ::<E >().at (Self ::PIO_PORT ), + self.pfalcon.write ( +Array ::at (Self ::PIO_PORT ), regs::NV_PFALCON_FALCON_IMEMC ::zeroed () .with_secure (load_offsets.secure) .with_aincw(true)
@@ -424,14 +432,14 @@ fn pio_wr_imem_slice(&self, load_offsets: FalconPioImemLoadTarget<'_>) -> Resultfor (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 )?; - self.bar.write ( -WithBase ::of ::<E >().at (Self ::PIO_PORT ), + self.pfalcon.write ( +Array ::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 ]]; - self.bar.write ( -WithBase ::of ::<E >().at (Self ::PIO_PORT ), + self.pfalcon.write ( +Array ::at (Self ::PIO_PORT ), regs::NV_PFALCON_FALCON_IMEMD ::zeroed ().with_data (u32::from_le_bytes (w)), ); }
@@ -450,8 +458,8 @@ fn pio_wr_dmem_slice(&self, load_offsets: FalconPioDmemLoadTarget<'_>) -> Resultreturn Err (EINVAL ); } - self.bar.write ( -WithBase ::of ::<E >().at (Self ::PIO_PORT ), + self.pfalcon.write ( +Array ::at (Self ::PIO_PORT ), regs::NV_PFALCON_FALCON_DMEMC ::zeroed () .with_aincw (true ) .with_offs(load_offsets.dst_start),
@@ -459,8 +467,8 @@ fn pio_wr_dmem_slice(&self, load_offsets: FalconPioDmemLoadTarget<'_>) -> Resultfor wordin load_offsets.data.chunks_exact (4 ) {let w = [word[0 ], word[1 ], word[2 ], word[3 ]]; - self.bar.write ( -WithBase ::of ::<E >().at (Self ::PIO_PORT ), + self.pfalcon.write ( +Array ::at (Self ::PIO_PORT ), regs::NV_PFALCON_FALCON_DMEMD ::zeroed ().with_data (u32::from_le_bytes (w)), ); }
@@ -473,14 +481,12 @@ pub(crate) fn pio_load<F: FalconFirmware<Target = E> + FalconPioLoadable>( &self, fw: &F, ) -> Result { - self.bar.update(regs::NV_PFALCON_FBIF_CTL::of::<E>(), |v| { + self.pfalcon.update(regs::NV_PFALCON_FBIF_CTL, |v| { v.with_allow_phys_no_ctx (true ) }); - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_DMACTL ::zeroed (), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_DMACTL ::zeroed ());if let Some (imem_ns) = fw.imem_ns_load_params () { self.pio_wr_imem_slice (imem_ns)?;
@@ -492,10 +498,8 @@ pub(crate) fn pio_load<F: FalconFirmware<Target = E> + FalconPioLoadable>( self.hal.program_brom (self, &fw.brom_params ()); - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()));Ok (()) }
@@ -547,16 +551,13 @@ fn dma_wr(// Set up the base source DMA address. - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_DMATRFBASE ::zeroed ().with_base ( + self.pfalcon + .write_reg (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_address >>8 )as u32 , - ), - ); - self.bar.write ( -WithBase ::of ::<E >(), + )); + self.pfalcon.write_reg ( regs::NV_PFALCON_FALCON_DMATRFBASE1 ::zeroed ().try_with_base (dma_address >>40 )?, );
@@ -566,23 +567,21 @@ fn dma_wr(for posin (0 ..num_transfers).map (|i| i *DMA_LEN ) {// Perform a transfer of size `DMA_LEN`. - self.bar.write ( -WithBase ::of ::<E >(), + self.pfalcon.write_reg ( regs::NV_PFALCON_FALCON_DMATRFMOFFS ::zeroed () .try_with_offs (load_offsets.dst_start + pos)?, ); - self.bar.write ( -WithBase ::of ::<E >(), + self.pfalcon.write_reg ( regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::zeroed ().with_offs (src_start + pos), ); - self.bar.write (WithBase ::of ::<E >(), cmd); + self.pfalcon.write_reg (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 (self.bar.read (regs::NV_PFALCON_FALCON_DMATRFCMD ::of ::<E >())), + ||Ok (self.pfalcon.read (regs::NV_PFALCON_FALCON_DMATRFCMD )), |r| r.idle (),Delta ::ZERO , Delta::from_secs(2),
@@ -614,8 +613,8 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) -> }; self.dma_reset (); - self.bar - .update (regs::NV_PFALCON_FBIF_TRANSCFG ::of ::<E >().at (0 ), |v| { + self.pfalcon + .update (regs::NV_PFALCON_FBIF_TRANSCFG ::at (0 ), |v| { v.with_target (FalconFbifTarget ::CoherentSysmem ) .with_mem_type (FalconFbifMemType ::Physical ) });
@@ -626,10 +625,8 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) -> self.hal.program_brom (self, &fw.brom_params ());// Set `BootVec` to start of non-secure code. - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed ().with_value (fw.boot_addr ()));Ok (()) }
@@ -638,7 +635,7 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) ->pub (crate )fn wait_till_halted (&self) ->Result <()> {// TIMEOUT: arbitrarily large value, firmwares should complete in less than 2 seconds. read_poll_timeout ( - ||Ok (self.bar.read (regs::NV_PFALCON_FALCON_CPUCTL ::of ::<E >())), + ||Ok (self.pfalcon.read (regs::NV_PFALCON_FALCON_CPUCTL )), |r| r.halted (),Delta ::ZERO , Delta::from_secs(2),
@@ -649,19 +646,13 @@ pub(crate) fn wait_till_halted(&self) -> Result<()> {/// Start the falcon CPU. pub (crate )fn start (&self) ->Result <()> { -match self - .bar - .read (regs::NV_PFALCON_FALCON_CPUCTL ::of ::<E >()) - .alias_en () - { -true => self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::zeroed ().with_startcpu (true ), - ), -false => self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_CPUCTL ::zeroed ().with_startcpu (true ), - ), +match self.pfalcon.read (regs::NV_PFALCON_FALCON_CPUCTL ).alias_en () { +true => self + .pfalcon + .write_reg (regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::zeroed ().with_startcpu (true )), +false => self + .pfalcon + .write_reg (regs::NV_PFALCON_FALCON_CPUCTL ::zeroed ().with_startcpu (true )), }Ok (())
@@ -670,32 +661,24 @@ pub(crate) fn start(&self) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed ().with_value (mbox0)); }if let Some (mbox1) = mbox1 { - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed ().with_value (mbox1)); } }/// Reads the value from `mbox0` register. pub (crate )fn read_mailbox0 (&self) ->u32 { - self.bar - .read (regs::NV_PFALCON_FALCON_MAILBOX0 ::of ::<E >()) - .value () + self.pfalcon.read (regs::NV_PFALCON_FALCON_MAILBOX0 ).value () }/// Reads the value from `mbox1` register. pub (crate )fn read_mailbox1 (&self) ->u32 { - self.bar - .read (regs::NV_PFALCON_FALCON_MAILBOX1 ::of ::<E >()) - .value () + self.pfalcon.read (regs::NV_PFALCON_FALCON_MAILBOX1 ).value () }/// Reads values from both mailbox registers.
@@ -760,9 +743,7 @@ pub(crate) fn load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw:/// Write the application version to the OS register. pub (crate )fn write_os_version (&self, app_version:u32 ) { - self.bar.write ( -WithBase ::of ::<E >(), - regs::NV_PFALCON_FALCON_OS ::zeroed ().with_value (app_version), - ); + self.pfalcon + .write_reg (regs::NV_PFALCON_FALCON_OS ::zeroed ().with_value (app_version)); } }
drivers/gpu/nova-core/falcon/fsp.rs +32 -31
107 lines not on this page · raw message
drivers/gpu/nova-core/falcon/gsp.rs +28 -23
93 lines not on this page · raw message
drivers/gpu/nova-core/falcon/hal/ga102.rs +24 -35
136 lines not on this page · raw message
drivers/gpu/nova-core/falcon/hal/tu102.rs +4 -5
@@ -5,7 +5,6 @@use kernel::{ io::{ poll::read_poll_timeout, - register::WithBase ,Io ,// }, prelude::*,
@@ -50,8 +49,8 @@ fn program_brom(&self, _falcon: &Falcon<'_, E>, _params: &FalconBromParams) {}fn is_riscv_active (&self, falcon: &Falcon <'_,E >) ->bool { falcon - .bar - .read (regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS ::of ::<E >()) + .pfalcon2 + .read (regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS ) .active_stat () }
@@ -62,7 +61,7 @@ fn is_riscv_halted(&self, _falcon: &Falcon<'_, E>) -> Result<bool> {fn reset_wait_mem_scrubbing (&self, falcon: &Falcon <'_,E >) ->Result {// TIMEOUT: memory scrubbing should complete in less than 10ms. read_poll_timeout ( - ||Ok (falcon.bar.read (regs::NV_PFALCON_FALCON_DMACTL ::of ::<E >())), + ||Ok (falcon.pfalcon.read (regs::NV_PFALCON_FALCON_DMACTL )), |r| r.mem_scrubbing_done (),Delta ::ZERO , Delta::from_millis(10),
@@ -71,7 +70,7 @@ fn reset_wait_mem_scrubbing(&self, falcon: &Falcon<'_, E>) -> Result { }fn reset_eng (&self, falcon: &Falcon <'_,E >) ->Result { - regs::NV_PFALCON_FALCON_ENGINE ::reset_engine ::<E >(falcon.bar); + regs::NV_PFALCON_FALCON_ENGINE ::reset_engine (falcon.pfalcon); self.reset_wait_mem_scrubbing (falcon)?;Ok (())
drivers/gpu/nova-core/falcon/sec2.rs +26 -11
@@ -1,22 +1,37 @@// SPDX-License-Identifier: GPL-2.0 -use kernel::io::register::RegisterBase ; +use kernel::io::{ + io_project, + register, +Mmio ,// +}; -use crate ::falcon::{ -FalconEngine , -PFalcon2Base , -PFalconBase ,// +use crate ::{ + driver::{ +Bar0 , +NovaRegisters ,// + }, + falcon::FalconEngine ,// };/// Type specifying the `Sec2` falcon engine. Cannot be instantiated. pub (crate )struct Sec2 (()); -impl RegisterBase <PFalconBase >for Sec2 { -const BASE :usize =0x00840000 ; -} +register! { + base:NovaRegisters ; -impl RegisterBase <PFalcon2Base >for Sec2 { -const BASE :usize =0x00841000 ; +PFALCON :super ::PFalconRegisters @0x00840000 ; +PFALCON2 :super ::PFalcon2Registers @0x00841000 ; } -impl FalconEngine for Sec2 {} +impl FalconEngine for Sec2 { +#[inline] +fn pfalcon (io:Bar0 <'_>) ->Mmio <'_,super ::PFalconRegisters > { +io_project! (io, build:PFALCON ) + } + +#[inline] +fn pfalcon2 (io:Bar0 <'_>) ->Mmio <'_,super ::PFalcon2Registers > { +io_project! (io, build:PFALCON2 ) + } +}
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +7 -11
@@ -12,7 +12,10 @@ Device, // }, dma::Coherent, - io::{register::WithBase, Io}, + io::{ + register::Array, + Io, // + }, prelude::*, ptr::{Alignable ,
@@ -23,7 +26,6 @@ };use crate ::{ - driver::Bar0 , falcon::{ self, gsp::Gsp ,
@@ -235,12 +237,7 @@ pub(crate) fn new(/// /// The bootloader will load the FWSEC firmware and then execute it. This function returns /// after FWSEC has reached completion. -pub (crate )fn run ( - &self, - dev: &Device <device::Bound >, - falcon: &Falcon <'_,Gsp >, - bar:Bar0 <'_>, - ) ->Result <()> { +pub (crate )fn run (&self, dev: &Device <device::Bound >, falcon: &Falcon <'_,Gsp >) ->Result <()> {// Reset falcon, load the firmware, and run it. falcon .reset ()
@@ -250,9 +247,8 @@ 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.update ( - regs::NV_PFALCON_FBIF_TRANSCFG ::of ::<Gsp >() - .try_at (usize::from_safe_cast (self.dmem_desc.ctx_dma)) + falcon.pfalcon.update ( + regs::NV_PFALCON_FBIF_TRANSCFG ::try_at (usize::from_safe_cast (self.dmem_desc.ctx_dma)) .ok_or (EINVAL )?, |v| { v.with_target (FalconFbifTarget ::CoherentSysmem )
drivers/gpu/nova-core/gsp/hal/tu102.rs +3 -4
@@ -62,12 +62,11 @@ impl FwsecUnloadFirmware {fn run ( &self, dev: &device::Device <device::Bound >, - bar:Bar0 <'_>, gsp_falcon: &Falcon <'_,GspEngine >, ) ->Result {match self {Self ::WithoutBl (fw) => fw.run (dev, gsp_falcon), -Self ::WithBl (fw) => fw.run (dev, gsp_falcon, bar), +Self ::WithBl (fw) => fw.run (dev, gsp_falcon), } } }
@@ -88,7 +87,7 @@ fn run(&self, ctx: &mut GspBootContext<'_, '_>) -> Result {// Log errors but keep going if it fails. let fwsec_sb_res = self .fwsec_sb - .run (dev, bar, ctx.gsp_falcon) + .run (dev, ctx.gsp_falcon) .inspect_err (|e|dev_err! (dev,"FWSEC-SB failed to run: {:?}\n" , e));// Remove WPR2 region if set.
@@ -168,7 +167,7 @@ fn run_fwsec_frts(if self.needs_fwsec_bootloader {let fwsec_frts_bl =FwsecFirmwareWithBl ::new (fwsec_frts, dev, chipset)?;// Load and run the bootloader, which will load FWSEC-FRTS and run it. - fwsec_frts_bl.run (dev, falcon, bar)?; + fwsec_frts_bl.run (dev, falcon)?; }else {// Load and run FWSEC-FRTS directly. fwsec_frts.run (dev, falcon)?;
drivers/gpu/nova-core/regs.rs +44 -48
277 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 8 lines
Add fixed size region types
PFalconRegistersandPFalcon2Registersand update PFALCON and PFALCON2 registers to be fixed register on them and not relative registers onNovaRegisters.Update
Falconstruct to store projected views when constructing and access withself.pfalconandself.pfalcon2.Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Re: [PATCH v4 12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers
In reply to Gary GuoQuoted 8 lines · Gary Guo
Add fixed size region types
PFalconRegistersandPFalcon2Registersand update PFALCON and PFALCON2 registers to be fixed register on them and not relative registers onNovaRegisters.Update
Falconstruct to store projected views when constructing and access withself.pfalconandself.pfalcon2.Signed-off-by Gary Guo <[email protected]>
Gary Guo
maintainerPATCH v4 13/16 gpu: nova-core: convert hshub0 from relative register to projection
In reply to Gary GuoSimilar to the PFALCON and PFALCON2 conversion, the hshub0 relative access can also be achieved cleanly with projection and a new base.
--- drivers/gpu/nova-core/fb/hal/gb100.rs | 59 +++++++++++++++++------------------ drivers/gpu/nova-core/fb/regs.rs | 21 ++++++++----- 2 files changed, 42 insertions(+), 38 deletions(-)
drivers/gpu/nova-core/fb/hal/gb100.rs +29 -30
@@ -5,11 +5,10 @@use kernel::{ io::{ - register::{ -RegisterBase , -WithBase ,// - }, -Io ,// + io_project, + register, +Io , +Mmio ,// }, num::Bounded , prelude::*,
@@ -21,7 +20,10 @@ };use crate ::{ - driver::Bar0 , + driver::{ +Bar0 , +NovaRegisters ,// + }, fb::{ hal::FbHal , regs,//
@@ -31,17 +33,26 @@struct Gb100 ; -impl RegisterBase <regs::Hshub0Base >for Gb100 { -const BASE :usize =0x0087_0000 ; +register! { + base:NovaRegisters ; + +HSHUB0 : regs::Hshub0Registers @0x0087_0000 ; +} + +#[inline] +fn hshub0 (bar:Bar0 <'_>) ->Mmio <'_, regs::Hshub0Registers > { +io_project! (bar, build:HSHUB0 ) } -fn read_sysmem_flush_page_gb100 (bar:Bar0 <'_>) ->u64 { +fn read_sysmem_flush_page_gb100 (hshub0:Mmio <'_, regs::Hshub0Registers >) ->u64 {let lo = u64::from ( - bar.read (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO ::of ::<Gb100 >()) + hshub0 + .read (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO ) .adr (), );let hi = u64::from ( - bar.read (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI ::of ::<Gb100 >()) + hshub0 + .read (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI ) .adr (), );
@@ -52,7 +63,7 @@ fn read_sysmem_flush_page_gb100(bar: Bar0<'_>) -> u64 {/// /// Both the primary and EG (egress) register pairs must be programmed to the same address, /// as required by hardware. -fn write_sysmem_flush_page_gb100 (bar:Bar0 <'_>, addr:Bounded <u64 ,52 >) { +fn write_sysmem_flush_page_gb100 (hshub0:Mmio <'_, regs::Hshub0Registers >, addr:Bounded <u64 ,52 >) {// CAST: lower 32 bits. Hardware ignores bits 7:0. let addr_lo = *addras u32 ;let addr_hi = addr.shr ::<32 ,20 >().cast ::<u32 >();
@@ -60,24 +71,12 @@ fn write_sysmem_flush_page_gb100(bar: Bar0<'_>, addr: Bounded<u64, 52>) {// Write HI first. The hardware will trigger the flush on the LO write. // Primary HSHUB pair. - bar.write ( - regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI ::of ::<Gb100 >(), - regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI ::zeroed ().with_adr (addr_hi), - ); - bar.write ( - regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO ::of ::<Gb100 >(), - regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO ::zeroed ().with_adr (addr_lo), - ); + hshub0.write_reg (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI ::zeroed ().with_adr (addr_hi)); + hshub0.write_reg (regs::NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO ::zeroed ().with_adr (addr_lo));// EG (egress) pair -- must match the primary pair. - bar.write ( - regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_HI ::of ::<Gb100 >(), - regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_HI ::zeroed ().with_adr (addr_hi), - ); - bar.write ( - regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO ::of ::<Gb100 >(), - regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO ::zeroed ().with_adr (addr_lo), - ); + hshub0.write_reg (regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_HI ::zeroed ().with_adr (addr_hi)); + hshub0.write_reg (regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO ::zeroed ().with_adr (addr_lo)); }// This PMU reservation size is r570-specific.
@@ -88,13 +87,13 @@ pub(super) const fn pmu_reserved_size_gb100() -> u32 {impl FbHal for Gb100 {fn read_sysmem_flush_page (&self, bar:Bar0 <'_>) ->u64 { -read_sysmem_flush_page_gb100 (bar) +read_sysmem_flush_page_gb100 (hshub0 (bar)) }fn write_sysmem_flush_page (&self, bar:Bar0 <'_>, addr:u64 ) ->Result {let addr =Bounded ::<u64 ,52 >::try_new (addr).ok_or (EINVAL )?; -write_sysmem_flush_page_gb100 (bar, addr); +write_sysmem_flush_page_gb100 (hshub0 (bar), addr);Ok (()) }
drivers/gpu/nova-core/fb/regs.rs +13 -8
@@ -2,7 +2,8 @@use kernel::{ io::register, - sizes::SizeConstants ,// + prelude::*, + sizes::{SizeConstants ,SZ_4K },// };use crate ::driver::NovaRegisters ;
@@ -65,31 +66,35 @@ pub(super) fn vga_workspace_addr(self) -> Option<u64> { } } -/// Base of the GB10x HSHUB0 register window (`NV_HSHUB0_PRIV_BASE` in Open RM). +const HSHUB0_REGION_SIZE :usize =SZ_4K ; + +/// The GB10x HSHUB0 register window (Base defined as `NV_HSHUB0_PRIV_BASE` in Open RM). /// /// The base is provided by the GB10x framebuffer HAL. -pub (super )struct Hshub0Base (()); +#[repr(align( 4 ))] +#[derive( FromBytes , IntoBytes )] +pub (super )struct Hshub0Registers ([u8 ;HSHUB0_REGION_SIZE ]);register! { - base:NovaRegisters ; + base:Hshub0Registers ;// GB10x sysmem flush registers, relative to the HSHUB0 base. GB10x routes sysmembar // through a primary and an EG (egress) pair that must both be programmed to the same // address. Hardware ignores bits 7:0 of each LO register. The boot path uses a fixed // HSHUB0 base, so the multiple runtime-discovered HSHUB bases are not needed here. -pub (super )NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO (u32 ) @Hshub0Base +0x00000e50 { +pub (super )NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_LO (u32 ) @0x00000e50 {31 :0 adr =>u32 ; } -pub (super )NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI (u32 ) @Hshub0Base +0x00000e54 { +pub (super )NV_PFB_HSHUB_PCIE_FLUSH_SYSMEM_ADDR_HI (u32 ) @0x00000e54 {19 :0 adr; } -pub (super )NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO (u32 ) @Hshub0Base +0x000006c0 { +pub (super )NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO (u32 ) @0x000006c0 {31 :0 adr =>u32 ; } -pub (super )NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_HI (u32 ) @Hshub0Base +0x000006c4 { +pub (super )NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_HI (u32 ) @0x000006c4 {19 :0 adr; } }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 13/16] gpu: nova-core: convert hshub0 from relative register to projection
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Nested imports are not formatted using the kernel vertical import style. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Nested imports are not formatted using the kernel vertical import style. --
commit 5f257dd4b3d5392812ee98a7773fef681ee000af
Author: Gary Guo <[email protected]>
gpu: nova-core: convert hshub0 from relative register to projection
This commit converts the hshub0 relative access to use a projection and a new base register. This brings it in line with the earlier PFALCON and PFALCON2 conversions.
[ ... ]
drivers/gpu/nova-core/fb/regs.rs line 6
Quoted 11 lines
drivers/gpu/nova-core/fb/regs.rs +2
-1@@ -2,7 +2,8 @@use kernel::{ io::register, - sizes::SizeConstants ,// + prelude::*, + sizes::{SizeConstants ,SZ_4K },//
[Severity: Low]
This isn't a bug, but should these nested imports be formatted using the kernel vertical import style?
The Rust coding guidelines generally require breaking nested imports vertically into multiple lines rather than keeping them grouped on a single line like sizes::{SizeConstants, SZ_4K} in the imports block of regs.rs.
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Alexandre Courbot
maintainerRe: [PATCH v4 13/16] gpu: nova-core: convert hshub0 from relative register to projection
In reply to Gary GuoOn Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
drivers/gpu/nova-core/fb/regs.rs line 6
Quoted 11 lines
drivers/gpu/nova-core/fb/regs.rs +2
-1@@ -2,7 +2,8 @@use kernel::{ io::register, - sizes::SizeConstants ,// + prelude::*, + sizes::{SizeConstants ,SZ_4K },//
Sashiko pointed out that misformatted import.
Gary Guo
maintainerPATCH v4 14/16 rust: io: register: remove relative registers
In reply to Gary GuoRelative registers can be better served by projection to subregion instead of ad-hoc handling in register macro. Projection composes better (e.g. it natively allows relative registers of relative registers without needing additional support).
Remove relative register support, and update the documentation to demonstrate how projection and subregions can be used to achieve this instead.
--- rust/kernel/io/register.rs | 388 ++++++--------------------------------------- rust/macros/io/register.rs | 52 ++---- 2 files changed, 61 insertions(+), 379 deletions(-)
rust/kernel/io/register.rs +52 -336
@@ -8,7 +8,7 @@//! //! Note: most of the items in this module are public so they can be referenced by the macro, but //! most are not to be used directly by users. Outside of the `register!` macro itself, the only -//! items you might want to import from this module are [`WithBase`] and [`Array`]. +//! item you might want to import from this module is [`Array`]. //! //! # Simple example //!
@@ -200,76 +200,6 @@ fn offset(self) -> usize { } } -/// Trait providing a base address to be added to the offset of a relative register to obtain -/// its actual offset. -/// -/// The `T` generic argument is used to distinguish which base to use, in case a type provides -/// several bases. It is given to the `register!` macro to restrict the use of the register to -/// implementors of this particular variant. -pub trait RegisterBase <T > { -/// Base address to which register offsets are added. -const BASE :usize ; -} - -/// Trait implemented by all registers that are relative to a base. -pub trait WithBase { -/// Family of bases applicable to this register. -type BaseFamily ; - -/// Returns the absolute location of this type when using `B` as its base. -#[inline(always)] -fn of <B :RegisterBase <Self ::BaseFamily >>() ->RelativeRegisterLoc <Self ,B > -where -Self :Register , - { -RelativeRegisterLoc ::new () - } -} - -/// Trait implemented by relative registers. -pub trait RelativeRegister :Register +WithBase {} - -/// Location of a relative register. -/// -/// This can either be an immediately accessible regular [`RelativeRegister`], or a -/// [`RelativeRegisterArray`] that needs one additional resolution through -/// [`RelativeRegisterLoc::at`]. -pub struct RelativeRegisterLoc <T :WithBase ,B : ?Sized >(PhantomData <T >,PhantomData <B >); - -impl <T ,B >RelativeRegisterLoc <T ,B > -where -T :Register +WithBase , -B :RegisterBase <T ::BaseFamily > + ?Sized , -{ -/// Returns the location of a relative register or register array. -#[inline(always)] -// We do not implement `Default` so we can be const. -#[expect(clippy::new_without_default)] -pub const fn new () ->Self { -Self (PhantomData ,PhantomData ) - } - -// Returns the absolute offset of the relative register using base `B`. -// -// This is implemented as a private const method so it can be reused by the [`IoLoc`] -// implementations of both [`RelativeRegisterLoc`] and [`RelativeRegisterArrayLoc`]. -#[inline] -const fn offset (self) ->usize { -B ::BASE +T ::OFFSET - } -} - -impl <SuperBase : ?Sized ,T ,B >IoLoc <SuperBase ,T >for RelativeRegisterLoc <T ,B > -where -T :RelativeRegister <Base =SuperBase >, -B :RegisterBase <T ::BaseFamily > + ?Sized , -{ -#[inline(always)] -fn offset (self) ->usize { -RelativeRegisterLoc ::offset (self) - } -} -/// Trait implemented by arrays of registers. pub trait RegisterArray :Register {/// Number of elements in the registers array.
@@ -332,71 +262,6 @@ fn try_at(idx: usize) -> Option<RegisterArrayLoc<Self>> } } -/// Trait implemented by arrays of relative registers. -pub trait RelativeRegisterArray :RegisterArray +WithBase {} - -/// Location of a relative array register. -pub struct RelativeRegisterArrayLoc < -T :RelativeRegisterArray , -B :RegisterBase <T ::BaseFamily > + ?Sized , ->(RelativeRegisterLoc <T ,B >,usize ); - -impl <T ,B >RelativeRegisterArrayLoc <T ,B > -where -T :RelativeRegisterArray , -B :RegisterBase <T ::BaseFamily > + ?Sized , -{ -/// Returns the location of register `T` from the base `B` at index `idx`, with build-time -/// validation. -#[inline(always)] -pub fn new (idx:usize ) ->Self { -build_assert! (idx <T ::SIZE ); - -Self (RelativeRegisterLoc ::new (), idx) - } - -/// Attempts to return the location of register `T` from the base `B` at index `idx`, with -/// runtime validation. -#[inline(always)] -pub fn try_new (idx:usize ) ->Option <Self > { -if idx <T ::SIZE { -Some (Self (RelativeRegisterLoc ::new (), idx)) - }else { -None - } - } -} - -/// Methods exclusive to [`RelativeRegisterLoc`]s created with a [`RelativeRegisterArray`]. -impl <T ,B >RelativeRegisterLoc <T ,B > -where -T :RelativeRegisterArray , -B :RegisterBase <T ::BaseFamily > + ?Sized , -{ -/// Returns the location of the register at position `idx`, with build-time validation. -#[inline(always)] -pub fn at (self, idx:usize ) ->RelativeRegisterArrayLoc <T ,B > { -RelativeRegisterArrayLoc ::new (idx) - } - -/// Returns the location of the register at position `idx`, with runtime validation. -#[inline(always)] -pub fn try_at (self, idx:usize ) ->Option <RelativeRegisterArrayLoc <T ,B >> { -RelativeRegisterArrayLoc ::try_new (idx) - } -} - -impl <SuperBase : ?Sized ,T ,B >IoLoc <SuperBase ,T >for RelativeRegisterArrayLoc <T ,B > -where -T :RelativeRegisterArray <Base =SuperBase >, -B :RegisterBase <T ::BaseFamily > + ?Sized , -{ -#[inline(always)] -fn offset (self) ->usize { - self.0 .offset () + self.1 *T ::STRIDE - } -} -/// Trait implemented by items that contain both a register value and the absolute I/O location at /// which to write it. ///
@@ -452,8 +317,7 @@ pub const fn element_alias_offset<Base: ?Sized, Alias: RegisterArray<Base = Base/// This documentation focuses on how to declare registers. See the [module-level /// documentation](mod@kernel::io::register) for examples of how to access them. /// -/// There are 4 possible kinds of registers: fixed offset registers, relative registers, arrays of -/// registers, and relative arrays of registers. +/// Registers can either be fixed offset registers or arrays of registers. /// /// ## Fixed offset registers ///
@@ -551,122 +415,6 @@ pub const fn element_alias_offset<Base: ?Sized, Alias: RegisterArray<Base = Base/// } /// ``` /// -/// ## Relative registers -/// -/// Relative registers can be instantiated several times at a relative offset of a group of bases. -/// For instance, imagine the following I/O space: -/// -/// ```text -/// +-----------------------------+ -/// | ... | -/// | | -/// 0x100--->+------------CPU0-------------+ -/// | | -/// 0x110--->+-----------------------------+ -/// | CPU_CTL | -/// +-----------------------------+ -/// | ... | -/// | | -/// | | -/// 0x200--->+------------CPU1-------------+ -/// | | -/// 0x210--->+-----------------------------+ -/// | CPU_CTL | -/// +-----------------------------+ -/// | ... | -/// +-----------------------------+ -/// ``` -/// -/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O -/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define -/// them twice and would prefer a way to select which one to use from a single definition. -/// -/// This can be done using the `Base + Offset` syntax when specifying the register's address: -/// -/// ```ignore -/// register! { -/// ... -/// pub RELATIVE_REG(u32) @ Base + 0x80 { -/// ... -/// } -/// } -/// ``` -/// -/// This creates a register with an offset of `0x80` from a given base. -/// -/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the -/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for -/// this register needs to implement `RegisterBase<Base>`. -/// -/// The location of relative registers can be built using the [`WithBase::of`] method to specify -/// its base. All relative registers implement [`WithBase`]. -/// -/// Here is the above layout translated into code: -/// -/// ```no_run -/// use kernel::{ -/// io::{ -/// register, -/// register::{ -/// RegisterBase, -/// WithBase, -/// }, -/// Io, -/// Region, -/// }, -/// }; -/// # use kernel::io::Mmio; -/// -/// // Type used to identify the base. -/// pub struct CpuCtlBase; -/// -/// // ZST describing `CPU0`. -/// struct Cpu0; -/// impl RegisterBase<CpuCtlBase> for Cpu0 { -/// const BASE: usize = 0x100; -/// } -/// -/// // ZST describing `CPU1`. -/// struct Cpu1; -/// impl RegisterBase<CpuCtlBase> for Cpu1 { -/// const BASE: usize = 0x200; -/// } -/// -/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`. -/// register! { -/// base: Region<0x1000>; -/// -/// /// CPU core control. -/// pub CPU_CTL(u32) @ CpuCtlBase + 0x10 { -/// 0:0 start; -/// } -/// } -/// -/// # fn test(io: Mmio<'_, Region<0x1000>>) { -/// // Read the status of `Cpu0`. -/// let cpu0_started = io.read(CPU_CTL::of::<Cpu0>()); -/// -/// // Stop `Cpu0`. -/// io.write(WithBase::of::<Cpu0>(), CPU_CTL::zeroed()); -/// # } -/// -/// // Aliases can also be defined for relative register. -/// register! { -/// base: Region<0x1000>; -/// -/// /// Alias to CPU core control. -/// pub CPU_CTL_ALIAS(u32) => CpuCtlBase + CPU_CTL { -/// /// Start the aliased CPU core. -/// 1:1 alias_start; -/// } -/// } -/// -/// # fn test2(io: Mmio<'_, Region<0x1000>>) { -/// // Start the aliased `CPU0`, leaving its other fields untouched. -/// io.update(CPU_CTL_ALIAS::of::<Cpu0>(), |r| r.with_alias_start(true)); -/// # } -/// ``` -/// /// ## Arrays of registers /// /// Some I/O areas contain consecutive registers that share the same field layout. These areas can
@@ -763,115 +511,83 @@ pub const fn element_alias_offset<Base: ?Sized, Alias: RegisterArray<Base = Base/// # } /// ``` /// -/// ## Relative arrays of registers +/// ## Relative registers /// -/// Combining the two features described in the sections above, arrays of registers accessible from -/// a base can also be defined: +/// There are cases where a register region is subdivided into small subregions, and you may wish to +/// have your register definition be relative to these subregions. This may be needed, for example, +/// if these subregions are instantiated several times, or you just want it for encapsulation +/// purpose. /// -/// ```ignore -/// register! { -/// ... -/// pub RELATIVE_REGISTER_ARRAY(u8)[10, stride = 4] @ Base + 0x100 { -/// ... -/// } -/// } +/// For instance, imagine the following I/O space: +/// +/// ```text +/// +-----------------------------+ +/// | ... | +/// | | +/// 0x100--->+------------CPU0-------------+ +/// | | +/// 0x110--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// | | +/// | | +/// 0x200--->+------------CPU1-------------+ +/// | | +/// 0x210--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// +-----------------------------+ /// ``` /// -/// Like relative registers, they implement the [`WithBase`] trait. However the return value of -/// [`WithBase::of`] cannot be used directly as a location and must be further specified using the -/// [`at`](RelativeRegisterLoc::at) method. +/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O +/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define +/// them twice and would prefer a way to select which one to use from a single definition. +/// +/// This can be done by defining a new type for the subregion, and then defining registers that use +/// the new type as the base: /// /// ```no_run /// use kernel::{ /// io::{ +/// io_project, /// register, -/// register::{ -/// RegisterBase, -/// WithBase, -/// }, /// Io, /// Region, /// }, /// }; /// # use kernel::io::Mmio; -/// # fn get_scratch_idx() -> usize { -/// # 0x15 -/// # } -/// -/// // Type used as parameter of `RegisterBase` to specify the base. -/// pub struct CpuCtlBase; /// -/// // ZST describing `CPU0`. -/// struct Cpu0; -/// impl RegisterBase<CpuCtlBase> for Cpu0 { -/// const BASE: usize = 0x100; -/// } +/// // Subregion type. Make sure it has adequate size and alignment. +/// #[repr(align(4))] +/// #[derive(FromBytes, IntoBytes)] +/// pub struct CpuCtl([u8; 0x100]); /// -/// // ZST describing `CPU1`. -/// struct Cpu1; -/// impl RegisterBase<CpuCtlBase> for Cpu1 { -/// const BASE: usize = 0x200; -/// } -/// -/// // 64 per-cpu scratch registers, arranged as a contiguous array. /// register! { /// base: Region<0x1000>; /// -/// /// Per-CPU scratch registers. -/// pub CPU_SCRATCH(u32)[64] @ CpuCtlBase + 0x00000080 { -/// 31:0 value; -/// } +/// // Subregions can just be defined like normal registers. +/// CPU0: CpuCtl @ 0x100; +/// CPU1: CpuCtl @ 0x200; /// } /// -/// # fn test(io: Mmio<'_, Region<0x1000>>) -> Result<(), Error> { -/// // Read scratch register 0 of CPU0. -/// let scratch = io.read(CPU_SCRATCH::of::<Cpu0>().at(0)); -/// -/// // Write the retrieved value into scratch register 15 of CPU1. -/// io.write(WithBase::of::<Cpu1>().at(15), scratch); -/// -/// // This won't build. -/// // let cpu0_scratch_128 = io.read(CPU_SCRATCH::of::<Cpu0>().at(128)).value(); -/// -/// // Runtime-obtained array index. -/// let scratch_idx = get_scratch_idx(); -/// // Access on a runtime index returns an error if it is out-of-bounds. -/// let cpu0_scratch = io.read( -/// CPU_SCRATCH::of::<Cpu0>().try_at(scratch_idx).ok_or(EINVAL)? -/// ).value(); -/// # Ok(()) -/// # } -/// -/// // Alias to `SCRATCH[8]` used to convey the firmware exit code. +/// // Then you can define new registers on the subregion. /// register! { -/// base: Region<0x1000>; +/// base: CpuCtl; /// -/// /// Per-CPU firmware exit status code. -/// pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase + CPU_SCRATCH[8] { -/// 7:0 status; +/// /// CPU core control. +/// pub CPU_CTL(u32) @ 0x10 { +/// 0:0 start; /// } /// } /// -/// // Non-contiguous relative register arrays can be defined by adding a stride parameter. -/// // Here, each of the 16 registers of the array is separated by 8 bytes, meaning that the -/// // registers of the two declarations below are interleaved. -/// register! { -/// base: Region<0x1000>; -/// -/// /// Scratch registers bank 0. -/// pub CPU_SCRATCH_INTERLEAVED_0(u32)[16, stride = 8] @ CpuCtlBase + 0x00000d00 { -/// 31:0 value; -/// } -/// -/// /// Scratch registers bank 1. -/// pub CPU_SCRATCH_INTERLEAVED_1(u32)[16, stride = 8] @ CpuCtlBase + 0x00000d04 { -/// 31:0 value; -/// } -/// } +/// # fn test(io: Mmio<'_, Region<0x1000>>) { +/// // Read the status of `Cpu0`. +/// let cpu0_started = io_project!(io, build: CPU0).read(CPU_CTL); /// -/// # fn test2(io: Mmio<'_, Region<0x1000>>) -> Result<(), Error> { -/// let cpu0_status = io.read(CPU_FIRMWARE_STATUS::of::<Cpu0>()).status(); -/// # Ok(()) +/// // Stop `Cpu0`. +/// io_project!(io, build: CPU0).write_reg(CPU_CTL::zeroed()); /// # } /// ``` #[macro_export]
rust/macros/io/register.rs +9 -43
108 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 14/16] rust: io: register: remove relative registers
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
Relative registers can be better served by projection to subregion instead of ad-hoc handling in register macro. Projection composes better (e.g. it natively allows relative registers of relative registers without needing additional support).
Remove relative register support, and update the documentation to demonstrate how projection and subregions can be used to achieve this instead.
Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Gary Guo
maintainerPATCH v4 15/16 rust: io: register: remove `Register` trait and cleanup macro
In reply to Gary GuoWith the removal of relative registers, there are only two type of registers left, fixed register and register arrays. There is not much benefit in having a common super trait for them anymore, thus remove it, and cleanup the macro rules associated with it.
--- rust/kernel/io/register.rs | 22 +++++++++++++--------- rust/macros/io/register.rs | 12 ++++++------ 2 files changed, 19 insertions(+), 15 deletions(-)
rust/kernel/io/register.rs +13 -9
@@ -121,8 +121,8 @@ io::IoLoc, // }; -/// Trait implemented by all registers. -pub trait Register :Sized { +/// Trait implemented by registers with a fixed offset. +pub trait FixedRegister :Sized {/// Base type for this register. type Base : ?Sized ;
@@ -132,9 +132,6 @@ pub trait Register: Sized {const OFFSET :usize ; } -/// Trait implemented by registers with a fixed offset. -pub trait FixedRegister :Register {} -/// Allows `()` to be used as the `location` parameter of [`Io::write`](super::Io::write) when /// passing a [`FixedRegister`] value. impl <Base : ?Sized ,T >IoLoc <Base ,T >for ()
@@ -201,7 +198,14 @@ fn offset(self) -> usize { }/// Trait implemented by arrays of registers. -pub trait RegisterArray :Register { +pub trait RegisterArray :Sized { +/// Base type for this register. +type Base : ?Sized ; + +/// Start offset of the register. +/// +/// The interpretation of this offset depends on the type of the register. +const OFFSET :usize ;/// Number of elements in the registers array. const SIZE :usize ;/// Number of bytes between the start of elements in the registers array.
@@ -267,8 +271,8 @@ fn try_at(idx: usize) -> Option<RegisterArrayLoc<Self>>/// /// Implementors can be used with [`Io::write_reg`](super::Io::write_reg). pub trait LocatedRegister <Base : ?Sized > { -/// Register value to write. -type Value :Register ; +/// Value to write. +type Value ;/// Full location information at which to write the value. type Location :IoLoc <Base ,Self ::Value >;
@@ -295,7 +299,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// This is used to enforce base matching. #[doc(hidden)] #[inline(always)] // for const eval only -pub const fn alias_offset <Base : ?Sized ,Alias :Register <Base =Base >>() ->usize { +pub const fn alias_offset <Base : ?Sized ,Alias :FixedRegister <Base =Base >>() ->usize {Alias ::OFFSET }
rust/macros/io/register.rs +6 -6
@@ -225,11 +225,6 @@ pub(crate) fn register(def: RegDef) -> Result<TokenStream> {#[allow(non_camel_case_types)] #(#attrs)* #vis struct #name(#storage) #args ); - - impl ::kernel::io::register::Register for #name { - type Base = #base; - const OFFSET: usize = #offset; - } )); }
@@ -245,7 +240,10 @@ impl ::kernel::io::register::Register for #name { ))?, None => outputs.extend(quote_spanned!(span => - impl ::kernel::io::register::FixedRegister for #name {} + impl ::kernel::io::register::FixedRegister for #name { + type Base = #base; + const OFFSET: usize = #offset; + } #(#attrs)* #vis const #name: ::kernel::io::register::FixedRegisterLoc<#name> = ::kernel::io::register::FixedRegisterLoc::<#name>::new();
@@ -268,6 +266,8 @@ impl ::kernel::io::register::FixedRegister for #name {} impl ::kernel::io::register::Array for #name {} impl ::kernel::io::register::RegisterArray for #name { + type Base = #base; + const OFFSET: usize = #offset; const SIZE: usize = #size; const STRIDE: usize = #stride; }
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 15/16] rust: io: register: remove `Register` trait and cleanup macro
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines
With the removal of relative registers, there are only two type of registers left, fixed register and register arrays. There is not much benefit in having a common super trait for them anymore, thus remove it, and cleanup the macro rules associated with it.
Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
Re: [PATCH v4 15/16] rust: io: register: remove `Register` trait and cleanup macro
In reply to Gary GuoQuoted 6 lines · Gary Guo
With the removal of relative registers, there are only two type of registers left, fixed register and register arrays. There is not much benefit in having a common super trait for them anymore, thus remove it, and cleanup the macro rules associated with it.
Signed-off-by Gary Guo <[email protected]>
My v3 Rb is missing here, so renewing it:
Gary Guo
maintainerPATCH v4 16/16 rust: io: register: unify handling of register with/without bitfields
In reply to Gary GuoMove the FixedRegister from a property of register to become a property of type. Name the new trait FixedIoLoc indicating if I/O location of a type is unique for a specific base. Thus, bitfields become just a special case of this (where type is unique because we're generating it in the register macro), and expose feature to registers without inline bitfield definition with the #[unique] attribute.
---
Changes since v3:
- Add a note that discourage #[unique] on primitives (Sashiko).
- Fix array's bitfield check to check bitfield.is_none() instead of !unique (Sashiko).
--- rust/kernel/io/register.rs | 114 +++++++++++++++++++++------------------------ rust/macros/io/register.rs | 58 ++++++++++++++--------- 2 files changed, 89 insertions(+), 83 deletions(-)
rust/kernel/io/register.rs +52 -62
@@ -121,61 +121,15 @@ io::IoLoc, // }; -/// Trait implemented by registers with a fixed offset. -pub trait FixedRegister :Sized { -/// Base type for this register. -type Base : ?Sized ; - -/// Start offset of the register. -/// -/// The interpretation of this offset depends on the type of the register. -const OFFSET :usize ; -} -/// Allows `()` to be used as the `location` parameter of [`Io::write`](super::Io::write) when -/// passing a [`FixedRegister`] value. +/// passing a [`FixedIoLoc`] value. impl <Base : ?Sized ,T >IoLoc <Base ,T >for ()where -T :FixedRegister <Base =Base >, +T :FixedIoLoc <Base >, {#[inline(always)] fn offset (self) ->usize { -T ::OFFSET - } -} - -/// A [`FixedRegister`] carries its location in its type. Thus `FixedRegister` values can be used -/// as an [`IoLoc`]. -impl <Base : ?Sized ,T >IoLoc <Base ,T >for T -where -T :FixedRegister <Base =Base >, -{ -#[inline(always)] -fn offset (self) ->usize { -T ::OFFSET - } -} - -/// Location of a fixed register. -pub struct FixedRegisterLoc <T :FixedRegister >(PhantomData <T >); - -impl <T :FixedRegister >FixedRegisterLoc <T > { -/// Returns the location of `T`. -#[inline(always)] -// We do not implement `Default` so we can be const. -#[expect(clippy::new_without_default)] -pub const fn new () ->Self { -Self (PhantomData ) - } -} - -impl <Base : ?Sized ,T >IoLoc <Base ,T >for FixedRegisterLoc <T > -where -T :FixedRegister <Base =Base >, -{ -#[inline(always)] -fn offset (self) ->usize { -T ::OFFSET +T ::LOCATION .offset () } }
@@ -188,6 +142,11 @@ impl<Base: ?Sized, T> OffsetLoc<Base, T> {pub const fn new (offset:usize ) ->Self {Self (offset,PhantomData ) } + +#[inline] +pub const fn const_offset (self) ->usize { + self.0 + } }impl <Base : ?Sized ,T >IoLoc <Base ,T >for OffsetLoc <Base ,T > {
@@ -266,6 +225,17 @@ fn try_at(idx: usize) -> Option<RegisterArrayLoc<Self>> } } +/// Trait implemented by types that indicate there is a fixed I/O location for this given type. +/// +/// Implementors can be used with [`Io::write_reg`](super::Io::write_reg). +pub trait FixedIoLoc <Base : ?Sized >:Sized { +/// Type of [`FixedIoLoc::LOCATION`]. +type Location :IoLoc <Base ,Self >; + +/// Location of this type within given base. +const LOCATION :Self ::Location ; +} +/// Trait implemented by items that contain both a register value and the absolute I/O location at /// which to write it. ///
@@ -283,26 +253,17 @@ pub trait LocatedRegister<Base: ?Sized> {impl <Base : ?Sized ,T >LocatedRegister <Base >for T where -T :FixedRegister <Base =Base >, +T :FixedIoLoc <Base >, { -type Location =FixedRegisterLoc <Self ::Value >; +type Location =T ::Location ;type Value =T ;#[inline(always)] -fn into_io_op (self) -> (FixedRegisterLoc <T >,T ) { - (FixedRegisterLoc ::new (), self) +fn into_io_op (self) -> (T ::Location ,T ) { + (T ::LOCATION , self) } } -/// Helper function for register alias implementation. -/// -/// This is used to enforce base matching. -#[doc(hidden)] -#[inline(always)] // for const eval only -pub const fn alias_offset <Base : ?Sized ,Alias :FixedRegister <Base =Base >>() ->usize { -Alias ::OFFSET -} -/// Helper function for register element alias implementation. /// /// This is used to enforce base matching and provide bounds checking.
@@ -419,6 +380,35 @@ pub const fn element_alias_offset<Base: ?Sized, Alias: RegisterArray<Base = Base/// } /// ``` /// +/// In case there is a fixed register associated with a specific type in the base, you can apply +/// `#[unique]` attribute which enables `write_reg` shorthand. This is automatically applied to +/// bitfields instantiated via the `register!` macro. +/// +/// This should only be used when types meaningfully represent a register. For example, in the +/// previous `UART_RX` example, even if only a single register is defined with `u8` type, it is a +/// bad idea to annotate it with `#[unique]`. +/// +/// ```no_run +/// # use kernel::{bitfield, io::*}; +/// +/// bitfield! { +/// pub struct Reset(u32) { +/// 0:0 reset; +/// } +/// } +/// +/// register! { +/// base: Region<0x1000>; +/// +/// pub RESET: #[unique] Reset @ 0x100; +/// } +/// +/// # fn test(mmio: Mmio<'_, Region<0x1000>>) { +/// // let mmio: Mmio<'_, Region<0x1000>>; +/// mmio.write_reg(Reset::zeroed().with_const_reset::<1>()); +/// # } +/// ``` +/// /// ## Arrays of registers /// /// Some I/O areas contain consecutive registers that share the same field layout. These areas can
rust/macros/io/register.rs +37 -21
105 lines not on this page · raw message
Signature · 1 line
2.54.0
[email protected]
AI reviewRe: [PATCH v4 16/16] rust: io: register: unify handling of register with/without bitfields
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
Move the
FixedRegisterfrom a property of register to become a property of type. Name the new traitFixedIoLocindicating if I/O location of a type is unique for a specific base. Thus, bitfields become just a special case of this (where type is unique because we're generating it in the register macro), and expose feature to registers without inline bitfield definition with the#[unique]attribute.Reviewed-by Alexandre Courbot <[email protected]>Signed-off-by Gary Guo <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Quoted 7 lines · Gary Guo
Currently registers work for all untyped I/O regions, which is not ideal. It allows registers defined for device A to work for another device B and there is no safeguarding at all.
Change this by requiring a base type for registers.
register!can still define registers on untypedRegions, although users would need to do so explicitly and supply a concrete type.
Thanks, this has come together really nicely imho.
I did a quick patch-by-patch build and tested the top of the series with Nova, which happily booted. Thus for all patches except patch 8 which I couldn't test, feel free to add my
Quoted 1 line · Gary Guo
[PATCH v4 00/16] rust: io: support register projections and remove relative registers
Applied, thanks!
Branch: topic/rust-io
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
[1/16] rust: io: register: reimplement as proc macro
commit: 63b2578517df
[ Fix typo in module-level doc comment and fix ArrayDef syntax
description to match the actual macro syntax. - Danilo ]
[2/16] rust: mem: add transmute with deferred size check
commit: 82591c20bcb3
[ Fix doc heading to use plural "Examples" and add missing closing code
block delimiter. - Danilo ]
[3/16] rust: mem: add AsRepr and AsReprMut
commit: 968f30ade612
[ Fix grammar in from_repr_unchecked() documentation and rephrase
confusing safety comment. - Danilo ]
[4/16] rust: io: perform conversions using AsRepr
commit: 1e707b76716a
[5/16] rust: io: support register projections
commit: 34b6dc471749[6/16] rust: io: register: allow explicit base type specification
commit: 70a122d5a342
[ Remove unnecessary #[allow(unused)] from the 'base' field. - Danilo ]
[7/16] gpu: nova-core: specify base type for registers
commit: a07fa2c979c1
[8/16] drm/tyr: specify base type for registers
commit: 573228e75c33
[9/16] samples: rust: pci: specify base type for registers
commit: 54b04b9fc0ea
[10/16] rust: io: register: make register have a typed base
commit: 35c21468c294
[11/16] rust: io: register: support fixed offset register without bitfield
commit: ddeaaa3a0fbb
[12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers
commit: 6d5f14077811[13/16] gpu: nova-core: convert hshub0 from relative register to projection
commit: 4a7a27bd1947
[ Split nested import into kernel vertical style. - Danilo ]
[14/16] rust: io: register: remove relative registers
commit: b6af037d9499
[15/16] rust: io: register: remove `Register` trait and cleanup macro
commit: dfec6f41d053
[16/16] rust: io: register: unify handling of register with/without bitfields
commit: 35423e8fd718The patches are in the topic/rust-io topic branch and will be merged into the corresponding target branch soon.
Danilo Krummrich
maintainerQuoted 7 lines · Danilo Krummrich
Quoted 1 line · Gary Guo
[PATCH v4 00/16] rust: io: support register projections and remove relative registers
Applied, thanks!
Branch: topic/rust-io
Tree:git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
I've pushed this to a topic branch, so 0-day can already do its thing.
Quoted 9 lines
[1/16] rust: io: register: reimplement as proc macro
commit:63b2578517df[ Fix typo in module-level doc comment and fix ArrayDef syntax
description to match the actual macro syntax. - Danilo ][2/16] rust: mem: add
transmutewith deferred size check
commit:82591c20bcb3
Quoted 8 lines
[ Fix doc heading to use plural "Examples" and add missing closing code
block delimiter. - Danilo ][3/16] rust: mem: add
AsReprandAsReprMut
commit:968f30ade612[ Fix grammar in
from_repr_unchecked()documentation and rephrase
confusing safety comment. - Danilo ]
Miguel, Boqun: Please let me know if you are fine with the two rust/kernel/mem.rs patches.
Thanks,
Danilo
Quoted 36 lines
[4/16] rust: io: perform conversions using
AsReprcommit: 1e707b76716a [5/16] rust: io: support register projections commit: 34b6dc471749[6/16] rust: io: register: allow explicit base type specification
commit:70a122d5a342[ Remove unnecessary #[allow(unused)] from the 'base' field. - Danilo ]
[7/16] gpu: nova-core: specify base type for registers
commit: a07fa2c979c1 [8/16] drm/tyr: specify base type for registers commit: 573228e75c33 [9/16] samples: rust: pci: specify base type for registers commit: 54b04b9fc0ea [10/16] rust: io: register: make register have a typed base commit: 35c21468c294 [11/16] rust: io: register: support fixed offset register without bitfield commit: ddeaaa3a0fbb [12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers commit: 6d5f14077811[13/16] gpu: nova-core: convert hshub0 from relative register to projection
commit:4a7a27bd1947[ Split nested import into kernel vertical style. - Danilo ]
[14/16] rust: io: register: remove relative registers
commit: b6af037d9499 [15/16] rust: io: register: remove `Register` trait and cleanup macro commit: dfec6f41d053 [16/16] rust: io: register: unify handling of register with/without bitfields commit: 35423e8fd718The patches are in the topic/rust-io topic branch and will be merged into the corresponding target branch soon.
Miguel Ojeda
Acked-byQuoted 3 lines · Danilo Krummrich
Miguel, Boqun: Please let me know if you are fine with the two
rust/kernel/mem.rspatches.
I see you fixed a few nits -- I pointed a few others in a couple replies.
It is nice to get a slice of the future of the standard library a bit sooner :)
Thanks!
Cheers,
Miguel
Danilo Krummrich
maintainerQuoted 1 line · Miguel Ojeda
I see you fixed a few nits -- I pointed a few others in a couple replies.
All fixed up, thanks!
Quoted 53 lines · Danilo Krummrich
Quoted 1 line · Gary Guo
[PATCH v4 00/16] rust: io: support register projections and remove relative registers
Applied, thanks!
Branch: topic/rust-io
Tree:git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git[1/16] rust: io: register: reimplement as proc macro
commit:63b2578517df[ Fix typo in module-level doc comment and fix ArrayDef syntax
description to match the actual macro syntax. - Danilo ][2/16] rust: mem: add
transmutewith deferred size check
commit:82591c20bcb3[ Fix doc heading to use plural "Examples" and add missing closing code
block delimiter. - Danilo ][3/16] rust: mem: add
AsReprandAsReprMut
commit:968f30ade612[ Fix grammar in
from_repr_unchecked()documentation and rephrase
confusing safety comment. - Danilo ][4/16] rust: io: perform conversions using
AsReprcommit: 1e707b76716a [5/16] rust: io: support register projections commit: 34b6dc471749[6/16] rust: io: register: allow explicit base type specification
commit:70a122d5a342[ Remove unnecessary #[allow(unused)] from the 'base' field. - Danilo ]
[7/16] gpu: nova-core: specify base type for registers
commit: a07fa2c979c1 [8/16] drm/tyr: specify base type for registers commit: 573228e75c33 [9/16] samples: rust: pci: specify base type for registers commit: 54b04b9fc0ea [10/16] rust: io: register: make register have a typed base commit: 35c21468c294 [11/16] rust: io: register: support fixed offset register without bitfield commit: ddeaaa3a0fbb [12/16] gpu: nova-core: use projection for PFALCON and PFALCON2 registers commit: 6d5f14077811[13/16] gpu: nova-core: convert hshub0 from relative register to projection
commit:4a7a27bd1947[ Split nested import into kernel vertical style. - Danilo ]
[14/16] rust: io: register: remove relative registers
Quoted 8 lines
commit: b6af037d9499 [15/16] rust: io: register: remove `Register` trait and cleanup macro commit: dfec6f41d053 [16/16] rust: io: register: unify handling of register with/without bitfields commit: 35423e8fd718The patches are in the topic/rust-io topic branch and will be merged into the corresponding target branch soon.
Merged into driver-core-next and drm-rust-next, thanks!