rust: add `register!` macro
Subsystems (8)
Alexandre Courbot
maintainerv4 cover rust: add `register!` macro
Add an improved version of nova-core's register! macro to the kernel crate for all drivers to use.
This is not a direct move from nova-core, but rather a new introduction to facilitate code review and introduce features that are missing in the nova-core versions. Differences notably include:
- Use of Bounded to prevent any data truncation when manipulating bitfields,
- Much better syntax (thanks to Gary for all the suggestions!)
- Extended documentation,
- Doccomments now build and run,
- Supports visibility and different storage sizes.
The bitfield! macro of nova-core has for the moment been wrapped into register!, as a set of private rules, to allow register! to be merged first while bitfield! undergoes review during the next cycle. Thus, some of the code from v1 (including bitfield!'s doccomments and Kunit tests) are kept for later.
Another notable difference is that I have removed the Default implementation for registers and instead implement Zeroable to provide a start value. I have deemed this preferable because implementing Default for a register requires that each of its field types also implements it, which is quite constraining and doesn't always makes sense (for instance, what is the default architecture for a family of chips?). Fields for which zero is not a valid value must implement the fallible getter anyway, so we are not at risk of undefined behavior, and Default can always be implemented on a per-case basis.
In order to avoid the ugly Bounded::<type, _>::new() syntax when setting constant field values, this revision adds an alternative const field setter named with_. Setters to not follow the most idiomatic Rust naming conventions, so their names are open to discussion.
The first patch enables the generic_arg_infer feature, which is required for generic type inference and used in subsequent patches. This feature is stable since rustc 1.89.
The second patch adds shr and shl methods to Bounded. These were suggested by Alice during LPC as a way to avoid the use of the controversial Bounded::from_expr in both the bitfield macro and the Nova code. Third patch adds another convenience method to obtain a bool from single-bit Boundeds, fourth patch a const accessor to the interval value of a Bounded, that is useful for making register setter methods const.
Patch 5 adds the register! macro. Since it falls under rust/kernel/io it is covered by the corresponding MAINTAINERS entry so I refrained from adding one just for this file, especially since the bitfield-related parts will eventually move and what remains is very tightly related to I/O.
Patch 6 updates the Rust PCI sample driver to use the register!, as per its TODO item.
The last patch illustrates more largely how this macro is used by converting nova-core to use it, and removing the local implementation. This patch is to be merged one cycle after the other patches.
Previous work to extract the macros was done in the partially-merged [1]. The current series can be considered a reboot with more features and the bitfield! macro being postponed.
This patchset is based on driver-core-next.
Note that it also need rust-fixes to avoid an unused_unsafe warning.
[1] https://lore.kernel.org/all/[email protected]/
---
Changes in v4:
- Add with_ const field setter methods (removing the need to call Bounded::new for constant field values).
- Add into_inner const method for Bounded.
- Add from_raw and const zeroed method to create initial register values.
- More documentation improvements.
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Sort the Rust features list alphabetically.
- Rebase on top of latest driver-core-next including the new Io trait.
- Allow several registers to be defined from the same macro invocation.
- Remove references to bitfield! macro.
- Fix doccomment of shr and shl.
- Use + syntax for relative register offsets.
- Move register arrays size and stride to after the backing type declaration.
- Use regular doccomments to document registers and fields (thanks Gary!).
- Remove Default implementation and implement the more predictable Zeroable instead.
- Improve doccomments a bit.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Remove bitfield! and put its rules into register! to give it more time to get reviewed.
- Allow output type larger than strictly required for shr and shl on Bounded.
- Enable the generic_arg_infer feature, required for rustc < 1.89.
- Link to v1: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (7):
rust: enable the generic_arg_infer feature
rust: num: add shr and shl methods to Bounded
rust: num: add as_bool method to Bounded<_, 1>
rust: num: add into_inner method to Bounded
rust: io: add register! macro
sample: rust: pci: use register! macro
[FOR REFERENCE] gpu: nova-core: use the kernel register! macro
drivers/gpu/nova-core/falcon.rs | 175 ++-- drivers/gpu/nova-core/falcon/gsp.rs | 12 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 15 +- drivers/gpu/nova-core/falcon/sec2.rs | 13 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 17 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 2 +- drivers/gpu/nova-core/gpu.rs | 31 +- drivers/gpu/nova-core/gsp/cmdq.rs | 4 +- drivers/gpu/nova-core/regs.rs | 494 ++++++----- drivers/gpu/nova-core/regs/macros.rs | 739 ----------------- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 +++++++++++++++++++++++++++++ rust/kernel/lib.rs | 3 + rust/kernel/num/bounded.rs | 79 ++ samples/rust/rust_driver_pci.rs | 23 +- scripts/Makefile.build | 3 +- 16 files changed, 1787 insertions(+), 1111 deletions(-)
---
base-commit: 7c60d964fbb100103730db9560f5594c1c4fc844
change-id: 20260117-register-ccaba1d21713
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v4 1/7 rust: enable the `generic_arg_infer` feature
This feature is stable since 1.89, and used in subsequent patches.
--- rust/kernel/lib.rs | 3 +++ scripts/Makefile.build | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-)
rust/kernel/lib.rs +3 -0
@@ -37,6 +37,9 @@#![feature(const_ptr_write)] #![feature(const_refs_to_cell)] // +// Stable since Rust 1.89.0. +#![feature(generic_arg_infer)] +// // Expected to become stable. #![feature(arbitrary_self_types)] //
scripts/Makefile.build +2 -1
@@ -312,12 +312,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # - Stable since Rust 1.82.0: `feature(asm_const)`, # `feature(offset_of_nested)`, `feature(raw_ref_op)`. # - Stable since Rust 1.87.0: `feature(asm_goto)`. +# - Stable since Rust 1.89.0: `feature(generic_arg_infer)`. # - Expected to become stable: `feature(arbitrary_self_types)`. # - To be determined: `feature(used_with_arg)`. # # Please see https://github.com/Rust-for-Linux/linux/issues/2 for details on # the unstable features in use. -rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg +rust_allowed_features := asm_const,asm_goto,arbitrary_self_types,generic_arg_infer,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree
Signature · 1 line
2.52.0
Alexandre Courbot
maintainerPATCH v4 2/7 rust: num: add `shr` and `shl` methods to `Bounded`
In reply to Alexandre CourbotShifting a Bounded left or right changes the number of bits required to represent the value. Add methods that perform the shift and return a Bounded with the appropriately adjusted bit width.
These methods are particularly useful for bitfield extraction.
--- rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+)
rust/kernel/num/bounded.rs +42 -0
@@ -470,6 +470,48 @@ pub fn cast<U>(self) -> Bounded<U, N>// `N` bits, and with the same signedness. Bounded ::__new (value) } + +/// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N - SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 16>::new::<0xff00>(); +/// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff); +/// ``` +pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES >=N -SHIFT ) } + +// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES == N - SHIFT`. +unsafe {Bounded ::__new (self.0 >>SHIFT ) } + } + +/// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= +/// N + SHIFT`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 8>::new::<0xff>(); +/// let v_shifted: Bounded::<u32, 16> = v.shl::<8, _>(); +/// +/// assert_eq!(v_shifted.get(), 0xff00); +/// ``` +pub fn shl <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const {assert! (RES >=N +SHIFT ) } + +// SAFETY: We shift the value left by `SHIFT`, augmenting the number of bits needed to +// represent the shifted value by as much, and just asserted that `RES == N + SHIFT`. +unsafe {Bounded ::__new (self.0 <<SHIFT ) } + } }impl <T ,const N :u32 >Deref for Bounded <T ,N >
Signature · 1 line
2.52.0
Re: [PATCH v4 2/7] rust: num: add `shr` and `shl` methods to `Bounded`
Quoted 11 lines · Alexandre Courbot
Shifting a
Boundedleft or right changes the number of bits required to represent the value. Add methods that perform the shift and return aBoundedwith the appropriately adjusted bit width.These methods are particularly useful for bitfield extraction.
Suggested-by Alice Ryhl <[email protected]>Reviewed-by Alice Ryhl <[email protected]>Tested-by Dirk Behme <[email protected]>Acked-by Miguel Ojeda <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>
Quoted 3 lines
--- rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+)
Alexandre Courbot
maintainerPATCH v4 3/7 rust: num: add `as_bool` method to `Bounded<_, 1>`
In reply to Alexandre CourbotSingle-bit numbers are typically treated as booleans. There is an Into<bool> implementation for those, but invoking it from contexts that lack type expectations is not always convenient.
Add an as_bool method as a simpler shortcut.
--- rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
rust/kernel/num/bounded.rs +21 -0
@@ -1098,3 +1098,24 @@ fn from(value: bool) -> Self {Self ::__new (T ::from (value)) } } + +impl <T >Bounded <T ,1 > +where +T :Integer +Zeroable , +{ +/// Returns the value of this [`Bounded`] as a [`bool`]. +/// +/// This is a shorter way of writing `bool::from(self)`. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// assert_eq!(Bounded::<u8, 1>::new::<0>().as_bool(), false); +/// assert_eq!(Bounded::<u8, 1>::new::<1>().as_bool(), true); +/// ``` +pub fn as_bool (self) ->bool { + self.into () + } +}
Signature · 1 line
2.52.0
Alexandre Courbot
maintainerPATCH v4 4/7 rust: num: add `into_inner` method to `Bounded`
In reply to Alexandre CourbotThis is useful to access the inner value in const contexts.
--- rust/kernel/num/bounded.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
rust/kernel/num/bounded.rs +16 -0
@@ -388,6 +388,22 @@ pub fn get(self) -> T { *self.deref () } +/// Returns the wrapped value as the backing type. +/// +/// This is a const-friendly variant of [`Self::get`] that can be used in const contexts. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// const V: u32 = Bounded::<u32, 4>::new::<7>().into_inner(); +/// assert_eq!(V, 7u32); +/// ``` +pub const fn into_inner (self) ->T { + self.0 + } +/// Increases the number of bits usable for `self`. /// /// This operation cannot fail.
Signature · 1 line
2.52.0
Gary Guo
reviewerRe: [PATCH v4 4/7] rust: num: add `into_inner` method to `Bounded`
Quoted 20 lines · Alexandre Courbot
This is useful to access the inner value in const contexts.
Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/num/bounded.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)rust/kernel/num/bounded.rs +5
-0@@ -388,6 +388,22 @@ pub fn get(self) -> T { *self.deref () } +/// Returns the wrapped value as the backing type. +/// +/// This is a const-friendly variant of [`Self::get`] that can be used in const contexts. +/// +/// # Examples
rust/kernel/num/bounded.rs pub fn get(self) -> T { · line 405
Quoted 10 lines
rust/kernel/num/bounded.rs +10
-0+/// +/// ``` +/// use kernel::num::Bounded; +/// +/// const V: u32 = Bounded::<u32, 4>::new::<7>().into_inner(); +/// assert_eq!(V, 7u32); +/// ``` +pub const fn into_inner (self) ->T { + self.0 + }
This is... just get.
You can implement it (with the fits_with_in check) in the same manner as the const new.
Best,
Gary
Quoted 4 lines
rust/kernel/num/bounded.rs +1
-0+/// Increases the number of bits usable for `self`. /// /// This operation cannot fail.
Alexandre Courbot
maintainerRe: [PATCH v4 4/7] rust: num: add `into_inner` method to `Bounded`
Quoted 34 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
This is useful to access the inner value in const contexts.
Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/num/bounded.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)rust/kernel/num/bounded.rs +5
-0@@ -388,6 +388,22 @@ pub fn get(self) -> T { *self.deref () } +/// Returns the wrapped value as the backing type. +/// +/// This is a const-friendly variant of [`Self::get`] that can be used in const contexts. +/// +/// # Examples rust/kernel/num/bounded.rs pub fn get(self) -> T { · line 405
Quoted 10 lines
rust/kernel/num/bounded.rs +10
-0+/// +/// ``` +/// use kernel::num::Bounded; +/// +/// const V: u32 = Bounded::<u32, 4>::new::<7>().into_inner(); +/// assert_eq!(V, 7u32); +/// ``` +pub const fn into_inner (self) ->T { + self.0 + }This is... just
get.
Quoted 2 lines
You can implement it (with the
fits_with_incheck) in the same manner as the const new.
But unfortunately doing so also prevents get from being called from generic code, which is a must-have. Or am I misunderstanding your suggestion?
Gary Guo
reviewerRe: [PATCH v4 4/7] rust: num: add `into_inner` method to `Bounded`
Quoted 35 lines · Alexandre Courbot
Quoted 34 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
This is useful to access the inner value in const contexts.
Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/num/bounded.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)rust/kernel/num/bounded.rs +5
-0@@ -388,6 +388,22 @@ pub fn get(self) -> T { *self.deref () } +/// Returns the wrapped value as the backing type. +/// +/// This is a const-friendly variant of [`Self::get`] that can be used in const contexts. +/// +/// # Examples rust/kernel/num/bounded.rs pub fn get(self) -> T { · line 405
Quoted 10 lines
rust/kernel/num/bounded.rs +10
-0+/// +/// ``` +/// use kernel::num::Bounded; +/// +/// const V: u32 = Bounded::<u32, 4>::new::<7>().into_inner(); +/// assert_eq!(V, 7u32); +/// ``` +pub const fn into_inner (self) ->T { + self.0 + }This is... just
get.
Quoted 6 lines
Quoted 2 lines
You can implement it (with the
fits_with_incheck) in the same manner as the const new.But unfortunately doing so also prevents
getfrom being called from generic code, which is a must-have. Or am I misunderstanding your suggestion?
Can you remove the fits_with_in check then and just provide self.0 in get then?
If the assume is really important, then we should at least name this get_const (or const_get) to indicate that this is a limitation caused by const eval, not a completely different method as the name would otherwise suggest.
Best,
Gary
Alexandre Courbot
maintainerRe: [PATCH v4 4/7] rust: num: add `into_inner` method to `Bounded`
Quoted 43 lines · Gary Guo
Quoted 35 lines · Alexandre Courbot
Quoted 34 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
This is useful to access the inner value in const contexts.
Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/num/bounded.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)rust/kernel/num/bounded.rs +5
-0@@ -388,6 +388,22 @@ pub fn get(self) -> T { *self.deref () } +/// Returns the wrapped value as the backing type. +/// +/// This is a const-friendly variant of [`Self::get`] that can be used in const contexts. +/// +/// # Examples rust/kernel/num/bounded.rs pub fn get(self) -> T { · line 405
Quoted 10 lines
rust/kernel/num/bounded.rs +10
-0+/// +/// ``` +/// use kernel::num::Bounded; +/// +/// const V: u32 = Bounded::<u32, 4>::new::<7>().into_inner(); +/// assert_eq!(V, 7u32); +/// ``` +pub const fn into_inner (self) ->T { + self.0 + }This is... just
get.Quoted 6 lines
Quoted 2 lines
You can implement it (with the
fits_with_incheck) in the same manner as the const new.But unfortunately doing so also prevents
getfrom being called from generic code, which is a must-have. Or am I misunderstanding your suggestion?
Quoted 6 lines
Can you remove the
fits_with_incheck then and just provideself.0ingetthen?If the assume is really important, then we should at least name this
get_const(orconst_get) to indicate that this is a limitation caused by const eval, not a completely different method as the name would otherwise suggest.
You're right, we should just do that. The benefits of the invariant check are negligible at best, and being able to access the value in const context is more important. Furthermore, one can always use the Deref implementation if they need the potential optimization brought by checking the invariant.
Alexandre Courbot
maintainerPATCH v4 5/7 rust: io: add `register!` macro
In reply to Alexandre CourbotAdd a macro for defining hardware register types with I/O accessors.
Each register field is represented as a Bounded of the appropriate bit width, ensuring field values are never silently truncated.
Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)
rust/kernel/io.rs +1 -0
@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;
rust/kernel/io/register.rs new file +1287 -0
1,287 lines not on this page · raw message
Signature · 1 line
2.52.0
Re: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 1 line · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
...
rust/kernel/io/register.rs line 160
Quoted 3 lines
rust/kernel/io/register.rs new file +3
-0+/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register
OK, this still looks like a naming problem that we don't need to create. Let's just pick either "set_" or "with_" as a prefix (it seems that "with_" has won out, in the v3 discussion thread), and then add "const", so that the name doesn't require explanation.
...
rust/kernel/io/register.rs line 186
Quoted 7 lines
rust/kernel/io/register.rs new file +7
-0+/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id())
See, that is just not obvious at all, why it's different. That's why you had to write a couple of comments.
.with_const_major_revision(), on the other hand, keeps the pattern clear and obvious. No comments necessary.
nova-core doesn't even use the const_ settors yet at all, according to my quick read of the (very helpful) [PATCH FOR REFERENCE v4 7/7]. So clearly it is a bit rare, and the extra characters won't come into play in daily life.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 23 lines · John Hubbard
Quoted 1 line · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
...
rust/kernel/io/register.rs line 160
Quoted 3 lines
rust/kernel/io/register.rs new file +3
-0+/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register OK, this still looks like a naming problem that we don't need to create. Let's just pick either "
set_" or "with_" as a prefix (it seems that "with_" has won out, in the v3 discussion thread), and then add "const", so that the name doesn't require explanation....
rust/kernel/io/register.rs line 186
Quoted 7 lines
rust/kernel/io/register.rs new file +7
-0+/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id()) See, that is just not obvious at all, why it's different. That's why you had to write a couple of comments.
Quoted 7 lines
.with_const_major_revision(), on the other hand, keeps the pattern clear and obvious. No comments necessary.
nova-core doesn't even use the
const_settors yet at all, according to my quick read of the (very helpful) [PATCH FOR REFERENCE v4 7/7]. So clearly it is a bit rare, and the extra characters won't come into play in daily life.
I completely agree with John here, let us please not create a confusing API. I would much rather use a bounded! macro to create bounded values and pass those to a single unified setter, making it a unified API for both constants and runtime values. Let us not use const generics just for the sake of it or create special const APIs that no one but examples use!!!
For example, instead of having separate set_/with_ prefixes, we could have:
boot0
.with_major_revision(bounded!(u8, 3))
.with_minor_revision(bounded!(u8, 10))
.with_vendor_id(obtain_vendor_id())This keeps the syntax clean while still providing compile-time bounds checking for constants. A single unified setter API is way cleaner and less confusing than having set_ for runtime and with_<N>() for compile-time values.
Is there some reason why this will not work?
Signature · 1 line
Joel Fernandes
Alexandre Courbot
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 24 lines · Joel Fernandes
Quoted 23 lines · John Hubbard
Quoted 1 line · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
...
rust/kernel/io/register.rs line 160
Quoted 3 lines
rust/kernel/io/register.rs new file +3
-0+/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register OK, this still looks like a naming problem that we don't need to create. Let's just pick either "
set_" or "with_" as a prefix (it seems that "with_" has won out, in the v3 discussion thread), and then add "const", so that the name doesn't require explanation....
rust/kernel/io/register.rs line 186
Quoted 7 lines
rust/kernel/io/register.rs new file +7
-0+/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id()) See, that is just not obvious at all, why it's different. That's why you had to write a couple of comments.
Quoted 7 lines
Quoted 7 lines
.with_const_major_revision(), on the other hand, keeps the pattern clear and obvious. No comments necessary.
nova-core doesn't even use the
const_settors yet at all, according to my quick read of the (very helpful) [PATCH FOR REFERENCE v4 7/7]. So clearly it is a bit rare, and the extra characters won't come into play in daily life.
Great, if everyone agrees on with/with_const then this is definitely idiomatic and clear (and not too verbose).
I'll respin tomorrow unless there is new input.
Quoted 14 lines
I completely agree with John here, let us please not create a confusing API. I would much rather use a bounded! macro to create bounded values and pass those to a single unified setter, making it a unified API for both constants and runtime values. Let us not use const generics just for the sake of it or create special const APIs that no one but examples use!!!
For example, instead of having separate set_/with_ prefixes, we could have:
boot0 .with_major_revision(bounded!(u8, 3)) .with_minor_revision(bounded!(u8, 10)) .with_vendor_id(obtain_vendor_id())
Quoted 6 lines
This keeps the syntax clean while still providing compile-time bounds checking for constants. A single unified setter API is way cleaner and less confusing than having
set_for runtime and with_<N>() for compile-time values.Is there some reason why this will not work?
So these setters are really part of the bitfield! API. Bitfields are, at the end of the day, just integers which we will very likely want to declare constants of out of individual const field values. This can only be done by using const methods, and a const Bounded needs to validate its constraints at build time, which requires the Bounded::new::<VALUE>() constructor, and by transition similarly-shaped setters to set fields at const time.
Re: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 7 lines · Alexandre Courbot
So these setters are really part of the
bitfield!API. Bitfields are, at the end of the day, just integers which we will very likely want to declare constants of out of individual const field values. This can only be done by using const methods, and a constBoundedneeds to validate its constraints at build time, which requires theBounded::new::<VALUE>()constructor, and by transition similarly-shaped setters to set fields at const time.
I think you run into that issue because the setter requires to do .into() to do the bounded conversion.
If we accept Bounded type in the setter directly instead, it should allow to keep the API simple. The advantage is it keeps the API naming simple. with_<field>() which accepts Bounded type, that's the contract. The trade off is the call-site can be a bit more icky but I wonder how much of an issue that really is (it really depends on usage).
I wrote a simple program to confirm the same function will work for both const and non-const parameters. Actually the caller does not even need to specific the bounded int size at the call site, it gets inferred. So we don't even need a bounded! macro.
struct Bounded<const BITS: u32>(u32);
impl<const BITS: u32> Bounded<BITS> {
pub const fn new<const VAL: u32>() -> Self { Self(VAL) }
pub fn try_new(val: u32) -> Result<Self, Error> { Ok(Self(val)) }
}struct Reg(u32);
impl Reg {
pub const fn with_foo(self, b: Bounded<4>) -> Self { Self(b.0) }
}fn bar() -> Result {
const C: Reg = Reg(0).with_foo(Bounded::new::<7>()); // const
let r = Reg(0).with_foo(Bounded::try_new(9)?); // runtime
println!("{} {}", C.0, r.0);
Ok(())
}This is clean IMO. Additionally, bounded! and bounded_expr! could be provided to build the bounded types.
Thoughts?
--
Joel Fernandes
Alexandre Courbot
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 11 lines · Joel Fernandes
Quoted 7 lines · Alexandre Courbot
So these setters are really part of the
bitfield!API. Bitfields are, at the end of the day, just integers which we will very likely want to declare constants of out of individual const field values. This can only be done by using const methods, and a constBoundedneeds to validate its constraints at build time, which requires theBounded::new::<VALUE>()constructor, and by transition similarly-shaped setters to set fields at const time.I think you run into that issue because the setter requires to do
.into()to do the bounded conversion.
Precisely. Without that conversion, the public field setter could just forward to the private one, which is const.
Quoted 6 lines
If we accept Bounded type in the setter directly instead, it should allow to keep the API simple. The advantage is it keeps the API naming simple. with_<field>() which accepts Bounded type, that's the contract. The trade off is the call-site can be a bit more icky but I wonder how much of an issue that really is (it really depends on usage).
I have tried converting the current macro to this idea, and this results in quite a few .into() calls. Notably, I find the following a bit (pun intended) annoying:
r.with_start(true.into())
start is a 1-bit bitfield, so it should accept a boolean, but here we cannot pass it directly.
So I am not sure that I prefer this over the current generic argument. In any case, this exercice has revealed that even if we adopt this idea, the issue won't be entirely solved because of the => and ?=> field conversions.
For such fields, performing an into() or try_into() is mandatory, as that's how the argument is converted to the Bounded internally. So pursuing const-purity at the moment is futile anyway, at least until we get const trait methods.
Which leaves the original problem: how do we avoid invoking the awkward Bounded constructor for const field values. And AFAICT, taking the Bounded directly still requires us to build it, which requires us to specify the backing type explicitly as that's the only way for the compiler to know which constructor to call. So in terms of API convenience I guess the with_/with_const_ combo remains the best bet for now.
Quoted 7 lines
I wrote a simple program to confirm the same function will work for both const and non-const parameters. Actually the caller does not even need to specific the bounded int size at the call site, it gets inferred. So we don't even need a bounded! macro.
struct Bounded<const BITS: u32>(u32);
For this example yes, because you have hardcoded the Bounded to be 32 bits, but I have tested this against the version in the kernel and it still requires the fully-specified constructor.
Gary Guo
reviewerRe: [PATCH v4 5/7] rust: io: add `register!` macro
In reply to Alexandre CourbotQuoted 64 lines · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
Each register field is represented as a
Boundedof the appropriate bit width, ensuring field values are never silently truncated.Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)rust/kernel/io.rs +1
-0@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;rust/kernel/io/register.rs new file +28
-0@@ -0,0 +1,1287 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A macro to define register layout and accessors. +//! +//! A single register typically includes several fields, which are accessed through a combination +//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because +//! not all possible field values are necessarily valid. +//! +//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a +//! dedicated type for each register. Each such type comes with its own field accessors that can +//! return an error if a field's value is invalid. +//! +//! [`register!`]: kernel::register! + +use core::ops::Deref ; + +use crate ::io::{ +IoCapable , +IoKnownSize ,// +}; + +/// 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 > {
rust/kernel/io/register.rs line 38
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// Base address to which register offsets are added. +const BASE :usize ; +} + +/// Trait providing I/O read/write operations for register storage types. +/// +/// This trait is implemented for all integer types on which I/O can be performed, allowing the +/// `register!` macro to generate appropriate I/O accessor methods based on the register's storage +/// type. +pub trait RegisterIo :Sized {
Is this trait intended for public usage or just internal detail of register!() macro?
If it's the former, then we should probably just put the method into IoCapable and allow generic-read in Io. If it's the latter, let's #[doc(hidden)] this so it won't get abused.
rust/kernel/io/register.rs line 43
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+/// Read a value from the given offset in the I/O region. +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >;
I think generally Deref bound shouldn't be exposed to user. What smart pointers are involved here, and can we implement forwarding impls of Io?
Quoted 59 lines
rust/kernel/io/register.rs new file +59
-0+ +/// Write a value to the given offset in the I/O region. +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >; +} + +impl RegisterIo for u8 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read8 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write8 (self, offset) + } +} + +impl RegisterIo for u16 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read16 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write16 (self, offset) + } +} + +impl RegisterIo for u32 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read32 (offset) + } + +#[inline(always)]
rust/kernel/io/register.rs line 112
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write32 (self, offset) + } +} + +#[cfg( CONFIG_64BIT )]
This cfg should be removed.
Quoted 355 lines
rust/kernel/io/register.rs new file +355
-0+impl RegisterIo for u64 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read64 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write64 (self, offset) + } +} + +/// Defines a dedicated type for a register, including getter and setter methods for its fields and +/// methods to read and write it from an [`Io`] region. +/// +/// Example: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Basic information about the chip. +/// pub BOOT_0(u32) @ 0x00000100 { +/// /// Vendor ID. +/// 15:8 vendor_id; +/// /// Major revision of the chip. +/// 7:4 major_revision; +/// /// Minor revision of the chip. +/// 3:0 minor_revision; +/// } +/// } +/// ``` +/// +/// This defines a `BOOT_0` type which can be read from or written to offset `0x100` of an `Io` +/// region. For instance, `minor_revision` consists of the 4 least significant bits of the +/// register. +/// +/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register +/// value. +/// +/// ```no_run +/// use kernel::register; +/// use kernel::num::Bounded; +/// +/// # register! { +/// # pub BOOT_0(u32) @ 0x00000100 { +/// # 15:8 vendor_id; +/// # 7:4 major_revision; +/// # 3:0 minor_revision; +/// # } +/// # } +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// # fn obtain_vendor_id() -> u8 { 0xff } +/// // Read from the register's defined offset (0x100). +/// let boot0 = BOOT_0::read(&bar); +/// pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.minor_revision().get()); +/// +/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id()) +/// .write(&bar); +/// +/// // Or, just read and update the register in a single step. +/// BOOT_0::update(&bar, |r| r +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// .set_vendor_id(obtain_vendor_id()) +/// ); +/// +/// // Constant values can also be built using the const setters. +/// const V: BOOT_0 = BOOT_0::zeroed() +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>(); +/// # } +/// ``` +/// +/// Fields can also be transparently converted from/to an arbitrary type by using the bitfield `=>` +/// and `?=>` syntaxes. +/// +/// If present, doccomments above register or fields definitions are added to the relevant item +/// they document (the register type itself, or the field's setter and getter methods). +/// +/// Note that multiple registers can be defined in a single `register!` invocation. This can be +/// useful to group related registers together. +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// pub BOOT_0(u8) @ 0x00000100 { +/// 7:4 major_revision; +/// 3:0 minor_revision; +/// } +/// +/// pub BOOT_1(u8) @ 0x00000101 { +/// 7:5 num_threads; +/// 4:0 num_cores; +/// } +/// }; +/// ``` +/// +/// It is possible to create an alias of an existing register with new field definitions by using +/// the `=> ALIAS` syntax. This is useful for cases where a register's interpretation depends on +/// the context: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Scratch register. +/// pub SCRATCH(u32) @ 0x00000200 { +/// /// Raw value. +/// 31:0 value; +/// } +/// +/// /// Boot status of the firmware. +/// pub SCRATCH_BOOT_STATUS(u32) => SCRATCH { +/// /// Whether the firmware has completed booting. +/// 0:0 completed; +/// } +/// } +/// ``` +/// +/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also +/// providing its own `completed` field. +/// +/// ## Relative registers +/// +/// A register can be defined as being accessible from a fixed offset of a provided base. For +/// instance, imagine the following I/O space: +/// +/// ```text +/// +-----------------------------+ +/// | ... | +/// | | +/// 0x100--->+------------CPU0-------------+ +/// | | +/// 0x110--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// | | +/// | | +/// 0x200--->+------------CPU1-------------+ +/// | | +/// 0x210--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// +-----------------------------+ +/// ``` +/// +/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O +/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define +/// them twice and would prefer a way to select which one to use from a single definition +/// +/// This can be done using the `Base + Offset` syntax when specifying the register's address. +/// +/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the +/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for +/// this register needs to implement `RegisterBase<Base>`. Here is the above example translated +/// into code: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// // Type used to identify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`. +/// register! { +/// /// CPU core control. +/// pub CPU_CTL(u32) @ CpuCtlBase + 0x10 { +/// /// Start the CPU core. +/// 0:0 start; +/// } +/// } +/// +/// // The `read`, `write` and `update` methods of relative registers take an extra `base` argument +/// // that is used to resolve its final address by adding its `BASE` to the offset of the +/// // register. +/// +/// // Start `CPU0`. +/// CPU_CTL::update(&bar, &CPU0, |r| r.set_start(true)); +/// +/// // Start `CPU1`. +/// CPU_CTL::update(&bar, &CPU1, |r| r.set_start(true)); +/// +/// // Aliases can also be defined for relative register. +/// register! { +/// /// Alias to CPU core control. +/// pub CPU_CTL_ALIAS(u32) => CpuCtlBase + CPU_CTL { +/// /// Start the aliased CPU core. +/// 1:1 alias_start; +/// } +/// } +/// +/// // Start the aliased `CPU0`. +/// CPU_CTL_ALIAS::update(&bar, &CPU0, |r| r.set_alias_start(true)); +/// # } +/// ``` +/// +/// ## Arrays of registers +/// +/// Some I/O areas contain consecutive registers that can be interpreted in the same way. These +/// areas can be defined as an array of identical registers, allowing them to be accessed by index +/// with compile-time or runtime bound checking. Simply specify their size inside `[` and `]` +/// brackets, and add an `idx` parameter to their `read`, `write` and `update` methods: +/// +/// ```no_run +/// use kernel::register; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Array of 64 consecutive registers with the same layout starting at offset `0x80`. +/// register! { +/// /// Scratch registers. +/// pub SCRATCH(u32)[64] @ 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// // Read scratch register 0, i.e. I/O address `0x80`. +/// let scratch_0 = SCRATCH::read(&bar, 0).value(); +/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`. +/// let scratch_15 = SCRATCH::read(&bar, 15).value(); +/// +/// // This is out of bounds and won't build. +/// // let scratch_128 = SCRATCH::read(&bar, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime index returns an error if it is out-of-bounds. +/// let some_scratch = SCRATCH::try_read(&bar, scratch_idx)?.value(); +/// +/// // Alias to a particular register in an array. +/// // Here `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Firmware exit status code. +/// pub FIRMWARE_STATUS(u32) => SCRATCH[8] { +/// 7:0 status; +/// } +/// } +/// let status = FIRMWARE_STATUS::read(&bar).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ 0x000000c0 { +/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ 0x000000c4 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// ## Relative arrays of registers +/// +/// Combining the two features described in the sections above, arrays of registers accessible from +/// a base can also be defined: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Type used as parameter of `RegisterBase` to specify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// // 64 per-cpu scratch registers, arranged as a contiguous array. +/// register! { +/// /// Per-CPU scratch registers. +/// pub CPU_SCRATCH(u32)[64] @ CpuCtlBase + 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// let cpu0_scratch_0 = CPU_SCRATCH::read(&bar, &Cpu0, 0).value(); +/// let cpu1_scratch_15 = CPU_SCRATCH::read(&bar, &Cpu1, 15).value(); +/// +/// // This won't build. +/// // let cpu0_scratch_128 = CPU_SCRATCH::read(&bar, &Cpu0, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime value returns an error if it is out-of-bounds. +/// let cpu0_some_scratch = CPU_SCRATCH::try_read(&bar, &Cpu0, scratch_idx)?.value(); +/// +/// // `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Per-CPU firmware exit status code. +/// pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase + CPU_SCRATCH[8] { +/// 7:0 status;
rust/kernel/io/register.rs line 477
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// } +/// } +/// let cpu0_status = CPU_FIRMWARE_STATUS::read(&bar, &Cpu0).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub CPU_SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ CpuCtlBase + 0x00000d00 {
I discussed this with Alex off-list and we agree that this'll better be
pub CPU_SCRATCH_INTERLEAVED_0(u32)[u16, stride = 8] @ CpuCtlBase + 0x00000d00
spelling the full intention out rather than have a special syntax, as this isn't the common case.
Quoted 12 lines
rust/kernel/io/register.rs new file +12
-0+/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub CPU_SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ CpuCtlBase + 0x00000d04 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// [`Io`]: kernel::io::Io
rust/kernel/io/register.rs line 499
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+#[macro_export] +macro_rules! register { +// Entry point for the macro, allowing multiple registers to be defined in one call. +// It matches all possible register declaration patterns to dispatch them to corresponding +// `@reg` rule that defines a single register. + ( + $( + $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + $([ $size:expr $(; $stride:expr)? ])? $(@ $offset:literal)? + $(@ $base:ident + $base_offset:literal)?
Does $(@ $($base:ident +)? $offset:literal)? not work?
rust/kernel/io/register.rs line 505
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+ $(=> $alias:ident $(+ $alias_offset:ident)? $([$alias_idx:expr])? )? + { $($fields:tt)* } + )* + ) => { + $( + ::kernel::register!(
$crate::register!()
Quoted 43 lines
rust/kernel/io/register.rs new file +43
-0+ @reg $(#[$attr])* $vis $name ($storage) $([$size $(; $stride)?])? + $(@ $offset)? + $(@ $base + $base_offset)? + $(=> $alias $(+ $alias_offset)? $([$alias_idx])? )? + { $($fields)* } + ); + )* + }; + +// All the rules below are private helpers. + +// Creates a register at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $offset); + }; + +// Creates an alias register of fixed offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET ); + }; + +// Creates a register at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $base:ident + $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $offset ); + };
rust/kernel/io/register.rs line 558
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ +// Creates an alias register of relative offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $base:ident + $alias:ident + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $alias::OFFSET );
Would this generate error messages if $name and $alias are of different base, or would such case be a bug but silently compiles?
Quoted 114 lines
rust/kernel/io/register.rs new file +114
-0+ }; + +// Creates an array of registers at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + [ $size:expr ; $stride:expr ] @ $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_array $name($storage) [ $size ; $stride ] @ $offset); + }; + +// Shortcut for contiguous array of registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of array of registers `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident [ $idx:expr ] + { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET + $idx * $alias::STRIDE ); + }; + +// Creates an array of registers at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative_array $name($storage) [ $size ; $stride ] @ $base + $offset + ); + }; + +// Shortcut for contiguous array of relative registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $base + $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of relative array of registers `alias` with its own +// fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + => $base:ident + $alias:ident [ $idx:expr ] { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative $name($storage) @ $base + $alias::OFFSET + $idx * $alias::STRIDE + ); + }; + +// Generates the bitfield for the register. +// +// `#[allow(non_camel_case_types)]` is added since register names typically use SCREAMING_CASE. + ( + @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } + ) => { + ::kernel::register!(@bitfield_core +#[allow(non_camel_case_types)] + $(#[$attr] )* $vis $name $storage + ); + ::kernel::register!(@bitfield_fields $vis $name $storage { $($fields)* }); + }; + +// Generates the IO accessors for a fixed offset register. + (@io_fixed $name:ident ($storage:ty) @ $offset:expr) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from its address in `io`. +#[inline(always)] +pub fn read <T ,I >(io: &T ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +Self (<$storageas $crate::io::register::RegisterIo >::read (io,Self ::OFFSET )) + } + +/// Write the value contained in `self` to the register address in `io`. +#[inline(always)] +pub fn write <T ,I >(self, io: &T )where +T : ::core::ops::Deref <Target =I >,
rust/kernel/io/register.rs line 682
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable<$storage>, + { + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io,Self ::OFFSET ) + } + +/// Read the register from its address in `io` and run `f` on its value to obtain a new +/// value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions.
Given the non-atomicity, how much value does it provide compared to having the user write read and write themselves? I feel that people reading the code may assume the atomicity without reading docs if they see FOO::update, while it's less likely that they do so if they read FOO::read(io).with_bar(baz).write(io).
Quoted 358 lines
rust/kernel/io/register.rs new file +358
-0+#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io)); + reg.write (io); + } + } + }; + +// Generates the IO accessors for a relative offset register. + (@io_relative $name:ident ($storage:ty) @ $base:ident + $offset:expr ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the register's offset to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it, then run `f` on its value to obtain a new value to +/// write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base)); + reg.write (io, base); + } + } + }; + +// Generates the IO accessors for an array of registers. + (@io_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] @ $offset:literal) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from its address in `io`. +#[inline(always)] +pub fn read <T ,I >( + io: &T , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +#[inline(always)] +pub fn write <T ,I >( + self, + io: &T , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, idx)); + reg.write (io, idx); + } + +/// Read the array register at index `idx` from its address in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I >( + io: &T , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I >( + self, + io: &T , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (self.write (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, idx, f)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + } + }; + +// Generates the IO accessors for an array of relative registers. + ( + @io_relative_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal + ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base, idx)); + reg.write (io, base, idx); + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I ,B >( + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I ,B >( + self, + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (self.write (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, base, idx, f)) + }else { +Err (::kernel::error::code::EINVAL )
rust/kernel/io/register.rs line 1050
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ } + } + } + }; + +// Defines the wrapper `$name` type and its conversions from/to the storage type. + (@bitfield_core $(#[$attr:meta])* $vis:vis $name:ident $storage:ty) => { + $(#[$attr])* + #[repr(transparent)] + #[derive(Clone, Copy, PartialEq, Eq)]
You can derive Zeroable and save you an unsafe impl.
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+ $vis struct $name($storage); + +#[allow(dead_code)] +impl $name { +/// Creates a bitfield from a raw value.
rust/kernel/io/register.rs line 1065
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ $vis const fn from_raw(value: $storage) -> Self { +Self (value) + } + +/// Creates a zeroed bitfield value. +/// +/// This is a const alternative to the `Zeroable::zeroed()` trait method. + $vis const fn zeroed() -> Self { +Self (0 ) + }
All types that impl Zeroable automatically have the ::zeroed() fn provided via the trait.
Quoted 47 lines
rust/kernel/io/register.rs new file +47
-0+ +/// Returns the raw value of this bitfield. +/// +/// This is similar to the [`From`] implementation, but is shorter to invoke in +/// most cases. + $vis const fn as_raw(self) -> $storage { + self.0 + } + } + +// SAFETY: `$storage` is `Zeroable` and `$name` is transparent. +unsafe impl ::pin_init::Zeroable for $name {} + +impl ::core::convert::From <$name>for $storage { +fn from (val: $name) -> $storage { + val.as_raw () + } + } + +impl ::core::convert::From <$storage>for $name { +fn from (val: $storage) -> $name { +Self ::from_raw (val) + } + } + }; + +// Definitions requiring knowledge of individual fields: private and public field accessors, +// and `Debug` implementation. + (@bitfield_fields $vis:vis $name:ident $storage:ty { + $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident + $(?=> $try_into_type:ty)? + $(=> $into_type:ty)? + ; + )* + } + ) => { + #[allow(dead_code)] + impl $name { + $( + ::kernel::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); + ::kernel::register!( + @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field + $(?=> $try_into_type)? + $(=> $into_type)? + ); + )* + }
rust/kernel/io/register.rs line 1122
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ + ::kernel::register!(@debug $name { $($field;)* }); + }; + +// Private field accessors working with the correct `Bounded` type for the field. + ( + @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident + ) => { + ::kernel::macros::paste!( + $visconst [<$field:upper_RANGE >]: ::core::ops::RangeInclusive <u8 > = $lo..=$hi;
Is this used by anything?
Best,
Gary
Quoted 165 lines
rust/kernel/io/register.rs new file +165
-0+ $vis const [<$field:upper _MASK>]: $storage = + ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1); + $vis const [<$field:upper _SHIFT>]: u32 = $lo; + ); + + ::kernel::macros::paste!( + fn [<__ $field>](self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> { + // Left shift to align the field's MSB with the storage MSB. + const ALIGN_TOP: u32 = $storage::BITS - ($hi + 1); + // Right shift to move the top-aligned field to bit 0 of the storage. + const ALIGN_BOTTOM: u32 = ALIGN_TOP + $lo; + + // Extract the field using two shifts. `Bounded::shr` produces the correctly-sized + // output type. + let val = ::kernel::num::Bounded::<$storage, { $storage::BITS }>::from( + self.0 << ALIGN_TOP + ); + val.shr::<ALIGN_BOTTOM, { $hi + 1 - $lo } >() + } + + const fn [<__set_ $field>]( + mut self, + value: ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>, + ) -> Self + { + const MASK: $storage = $name::[<$field:upper _MASK>]; + const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; + + let value = value.into_inner() << SHIFT; + self.0 = (self.0 & !MASK) | value; + + self + } + ); + }; + + // Public accessors for fields infallibly (`=>`) converted to a type. + ( + @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : + $hi:literal:$lo:literal $field:ident => $into_type:ty + ) => { + ::kernel::macros::paste!( + + $(#[doc = $doc])* + #[doc = "Returns the value of this field."] + #[inline(always)] + $vis fn $field(self) -> $into_type + { + self.[<__ $field>]().into() + } + + $(#[doc = $doc])* + #[doc = "Sets this field to the given `value`."] + #[inline(always)] + $vis fn [<set_ $field>](self, value: $into_type) -> Self + { + self.[<__set_ $field>](value.into()) + } + + ); + }; + + // Public accessors for fields fallibly (`?=>`) converted to a type. + ( + @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : + $hi:tt:$lo:tt $field:ident ?=> $try_into_type:ty + ) => { + ::kernel::macros::paste!( + + $(#[doc = $doc])* + #[doc = "Returns the value of this field."] + #[inline(always)] + $vis fn $field(self) -> + Result< + $try_into_type, + <$try_into_type as ::core::convert::TryFrom< + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> + >>::Error + > + { + self.[<__ $field>]().try_into() + } + + $(#[doc = $doc])* + #[doc = "Sets this field to the given `value`."] + #[inline(always)] + $vis fn [<set_ $field>](self, value: $try_into_type) -> Self + { + self.[<__set_ $field>](value.into()) + } + + ); + }; + + // Public accessors for fields not converted to a type. + ( + @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : + $hi:tt:$lo:tt $field:ident + ) => { + ::kernel::macros::paste!( + + $(#[doc = $doc])* + #[doc = "Returns the value of this field."] + #[inline(always)] + $vis fn $field(self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> + { + self.[<__ $field>]() + } + + $(#[doc = $doc])* + #[doc = "Sets this field to the compile-time constant `VALUE`."] + #[inline(always)] + $vis const fn [<with_ $field>]<const VALUE: $storage>(self) -> Self { + self.[<__set_ $field>]( + ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::new::<VALUE>() + ) + } + + $(#[doc = $doc])* + #[doc = "Sets this field to the given `value`."] + #[inline(always)] + $vis fn [<set_ $field>]<T>( + self, + value: T, + ) -> Self + where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>>, + { + self.[<__set_ $field>](value.into()) + } + + $(#[doc = $doc])* + #[doc = "Tries to set this field to `value`, returning an error if it is out of range."] + #[inline(always)] + $vis fn [<try_set_ $field>]<T>( + self, + value: T, + ) -> ::kernel::error::Result<Self> + where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $lo }>, + { + Ok( + self.[<__set_ $field>]( + value.try_into_bounded().ok_or(::kernel::error::code::EOVERFLOW)? + ) + ) + } + + ); + }; + + // `Debug` implementation. + (@debug $name:ident { $($field:ident;)* }) => { + impl ::kernel::fmt::Debug for $name { + fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kernel::fmt::Result { + f.debug_struct(stringify!($name)) + .field("<raw>", &::kernel::prelude::fmt!("{:#x}", self.0)) + $( + .field(stringify!($field), &self.$field()) + )* + .finish() + } + } + }; +}
Alexandre Courbot
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 79 lines · Gary Guo
Quoted 64 lines · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
Each register field is represented as a
Boundedof the appropriate bit width, ensuring field values are never silently truncated.Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)rust/kernel/io.rs +1
-0@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;rust/kernel/io/register.rs new file +28
-0@@ -0,0 +1,1287 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A macro to define register layout and accessors. +//! +//! A single register typically includes several fields, which are accessed through a combination +//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because +//! not all possible field values are necessarily valid. +//! +//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a +//! dedicated type for each register. Each such type comes with its own field accessors that can +//! return an error if a field's value is invalid. +//! +//! [`register!`]: kernel::register! + +use core::ops::Deref ; + +use crate ::io::{ +IoCapable , +IoKnownSize ,// +}; + +/// 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 > {rust/kernel/io/register.rs line 38
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// Base address to which register offsets are added. +const BASE :usize ; +} + +/// Trait providing I/O read/write operations for register storage types. +/// +/// This trait is implemented for all integer types on which I/O can be performed, allowing the +/// `register!` macro to generate appropriate I/O accessor methods based on the register's storage +/// type. +pub trait RegisterIo :Sized {Is this trait intended for public usage or just internal detail of
register!()macro?
Quoted 3 lines
If it's the former, then we should probably just put the method into
IoCapableand allow generic-read in Io. If it's the latter, let's#[doc(hidden)]this so it won't get abused.
It is an internal detail of register!() and not supposed to be used by anyone else.
Quoted 9 lines
rust/kernel/io/register.rs line 43
Quoted 6 lines
rust/kernel/io/register.rs new file +5
-0+/// Read a value from the given offset in the I/O region. +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >;I think generally
Derefbound shouldn't be exposed to user. What smart pointers are involved here, and can we implement forwarding impls ofIo?
Removing the requirement for Deref in the RegisterIo trait is simple - we can just call Deref in the register IO accessors.
But I suspect you mean that we should also remove it from the register accessors themselves? The problem if I remove it there is that things like Nova's Bar0 do not implement IoKnownSize and IoCapable (but rather deref to something that does), which would require all callers to do the deref op itself as deref coercion doesn't seem to be usable here.
Quoted 64 lines
Quoted 64 lines
rust/kernel/io/register.rs new file +63
-0+ +/// Write a value to the given offset in the I/O region. +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >; +} + +impl RegisterIo for u8 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read8 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write8 (self, offset) + } +} + +impl RegisterIo for u16 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read16 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write16 (self, offset) + } +} + +impl RegisterIo for u32 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read32 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >,
Quoted 8 lines
rust/kernel/io/register.rs line 112
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+ { + io.write32 (self, offset) + } +} + +#[cfg( CONFIG_64BIT )] This cfg should be removed.
Done.
Quoted 369 lines
Quoted 356 lines
rust/kernel/io/register.rs new file +355
-0+impl RegisterIo for u64 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read64 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write64 (self, offset) + } +} + +/// Defines a dedicated type for a register, including getter and setter methods for its fields and +/// methods to read and write it from an [`Io`] region. +/// +/// Example: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Basic information about the chip. +/// pub BOOT_0(u32) @ 0x00000100 { +/// /// Vendor ID. +/// 15:8 vendor_id; +/// /// Major revision of the chip. +/// 7:4 major_revision; +/// /// Minor revision of the chip. +/// 3:0 minor_revision; +/// } +/// } +/// ``` +/// +/// This defines a `BOOT_0` type which can be read from or written to offset `0x100` of an `Io` +/// region. For instance, `minor_revision` consists of the 4 least significant bits of the +/// register. +/// +/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register +/// value. +/// +/// ```no_run +/// use kernel::register; +/// use kernel::num::Bounded; +/// +/// # register! { +/// # pub BOOT_0(u32) @ 0x00000100 { +/// # 15:8 vendor_id; +/// # 7:4 major_revision; +/// # 3:0 minor_revision; +/// # } +/// # } +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// # fn obtain_vendor_id() -> u8 { 0xff } +/// // Read from the register's defined offset (0x100). +/// let boot0 = BOOT_0::read(&bar); +/// pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.minor_revision().get()); +/// +/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id()) +/// .write(&bar); +/// +/// // Or, just read and update the register in a single step. +/// BOOT_0::update(&bar, |r| r +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// .set_vendor_id(obtain_vendor_id()) +/// ); +/// +/// // Constant values can also be built using the const setters. +/// const V: BOOT_0 = BOOT_0::zeroed() +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>(); +/// # } +/// ``` +/// +/// Fields can also be transparently converted from/to an arbitrary type by using the bitfield `=>` +/// and `?=>` syntaxes. +/// +/// If present, doccomments above register or fields definitions are added to the relevant item +/// they document (the register type itself, or the field's setter and getter methods). +/// +/// Note that multiple registers can be defined in a single `register!` invocation. This can be +/// useful to group related registers together. +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// pub BOOT_0(u8) @ 0x00000100 { +/// 7:4 major_revision; +/// 3:0 minor_revision; +/// } +/// +/// pub BOOT_1(u8) @ 0x00000101 { +/// 7:5 num_threads; +/// 4:0 num_cores; +/// } +/// }; +/// ``` +/// +/// It is possible to create an alias of an existing register with new field definitions by using +/// the `=> ALIAS` syntax. This is useful for cases where a register's interpretation depends on +/// the context: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Scratch register. +/// pub SCRATCH(u32) @ 0x00000200 { +/// /// Raw value. +/// 31:0 value; +/// } +/// +/// /// Boot status of the firmware. +/// pub SCRATCH_BOOT_STATUS(u32) => SCRATCH { +/// /// Whether the firmware has completed booting. +/// 0:0 completed; +/// } +/// } +/// ``` +/// +/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also +/// providing its own `completed` field. +/// +/// ## Relative registers +/// +/// A register can be defined as being accessible from a fixed offset of a provided base. For +/// instance, imagine the following I/O space: +/// +/// ```text +/// +-----------------------------+ +/// | ... | +/// | | +/// 0x100--->+------------CPU0-------------+ +/// | | +/// 0x110--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// | | +/// | | +/// 0x200--->+------------CPU1-------------+ +/// | | +/// 0x210--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// +-----------------------------+ +/// ``` +/// +/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O +/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define +/// them twice and would prefer a way to select which one to use from a single definition +/// +/// This can be done using the `Base + Offset` syntax when specifying the register's address. +/// +/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the +/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for +/// this register needs to implement `RegisterBase<Base>`. Here is the above example translated +/// into code: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// // Type used to identify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`. +/// register! { +/// /// CPU core control. +/// pub CPU_CTL(u32) @ CpuCtlBase + 0x10 { +/// /// Start the CPU core. +/// 0:0 start; +/// } +/// } +/// +/// // The `read`, `write` and `update` methods of relative registers take an extra `base` argument +/// // that is used to resolve its final address by adding its `BASE` to the offset of the +/// // register. +/// +/// // Start `CPU0`. +/// CPU_CTL::update(&bar, &CPU0, |r| r.set_start(true)); +/// +/// // Start `CPU1`. +/// CPU_CTL::update(&bar, &CPU1, |r| r.set_start(true)); +/// +/// // Aliases can also be defined for relative register. +/// register! { +/// /// Alias to CPU core control. +/// pub CPU_CTL_ALIAS(u32) => CpuCtlBase + CPU_CTL { +/// /// Start the aliased CPU core. +/// 1:1 alias_start; +/// } +/// } +/// +/// // Start the aliased `CPU0`. +/// CPU_CTL_ALIAS::update(&bar, &CPU0, |r| r.set_alias_start(true)); +/// # } +/// ``` +/// +/// ## Arrays of registers +/// +/// Some I/O areas contain consecutive registers that can be interpreted in the same way. These +/// areas can be defined as an array of identical registers, allowing them to be accessed by index +/// with compile-time or runtime bound checking. Simply specify their size inside `[` and `]` +/// brackets, and add an `idx` parameter to their `read`, `write` and `update` methods: +/// +/// ```no_run +/// use kernel::register; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Array of 64 consecutive registers with the same layout starting at offset `0x80`. +/// register! { +/// /// Scratch registers. +/// pub SCRATCH(u32)[64] @ 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// // Read scratch register 0, i.e. I/O address `0x80`. +/// let scratch_0 = SCRATCH::read(&bar, 0).value(); +/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`. +/// let scratch_15 = SCRATCH::read(&bar, 15).value(); +/// +/// // This is out of bounds and won't build. +/// // let scratch_128 = SCRATCH::read(&bar, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime index returns an error if it is out-of-bounds. +/// let some_scratch = SCRATCH::try_read(&bar, scratch_idx)?.value(); +/// +/// // Alias to a particular register in an array. +/// // Here `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Firmware exit status code. +/// pub FIRMWARE_STATUS(u32) => SCRATCH[8] { +/// 7:0 status; +/// } +/// } +/// let status = FIRMWARE_STATUS::read(&bar).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ 0x000000c0 { +/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ 0x000000c4 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// ## Relative arrays of registers +/// +/// Combining the two features described in the sections above, arrays of registers accessible from +/// a base can also be defined: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Type used as parameter of `RegisterBase` to specify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// // 64 per-cpu scratch registers, arranged as a contiguous array. +/// register! { +/// /// Per-CPU scratch registers. +/// pub CPU_SCRATCH(u32)[64] @ CpuCtlBase + 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// let cpu0_scratch_0 = CPU_SCRATCH::read(&bar, &Cpu0, 0).value(); +/// let cpu1_scratch_15 = CPU_SCRATCH::read(&bar, &Cpu1, 15).value(); +/// +/// // This won't build. +/// // let cpu0_scratch_128 = CPU_SCRATCH::read(&bar, &Cpu0, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime value returns an error if it is out-of-bounds. +/// let cpu0_some_scratch = CPU_SCRATCH::try_read(&bar, &Cpu0, scratch_idx)?.value(); +/// +/// // `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Per-CPU firmware exit status code. +/// pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase + CPU_SCRATCH[8] { +/// 7:0 status; rust/kernel/io/register.rs line 477
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// } +/// } +/// let cpu0_status = CPU_FIRMWARE_STATUS::read(&bar, &Cpu0).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub CPU_SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ CpuCtlBase + 0x00000d00 { I discussed this with Alex off-list and we agree that this'll better be
Quoted 4 lines
pub CPU_SCRATCH_INTERLEAVED_0(u32)[u16, stride = 8] @ CpuCtlBase + 0x00000d00spelling the full intention out rather than have a special syntax, as this isn't the common case.
Implemented it and it indeed looks much better.
Quoted 17 lines
Quoted 17 lines
rust/kernel/io/register.rs new file +16
-0+/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub CPU_SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ CpuCtlBase + 0x00000d04 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// [`Io`]: kernel::io::Io +#[macro_export] +macro_rules! register { +// Entry point for the macro, allowing multiple registers to be defined in one call. +// It matches all possible register declaration patterns to dispatch them to corresponding
Quoted 8 lines
rust/kernel/io/register.rs line 499
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+// `@reg` rule that defines a single register. + ( + $( + $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + $([ $size:expr $(; $stride:expr)? ])? $(@ $offset:literal)? + $(@ $base:ident + $base_offset:literal)?Does
$(@ $($base:ident +)? $offset:literal)?not work?
It does! I was trying to match the + in the right-side expression and obviously couldn't, but it didn't occur to me to do it the other way. :)
Quoted 9 lines
rust/kernel/io/register.rs line 505
Quoted 7 lines
rust/kernel/io/register.rs new file +6
-0+ $(=> $alias:ident $(+ $alias_offset:ident)? $([$alias_idx:expr])? )? + { $($fields:tt)* } + )* + ) => { + $( + ::kernel::register!($crate::register!()
Updated throughout the file (I am not sure to understand the difference though?).
Quoted 49 lines
Quoted 49 lines
rust/kernel/io/register.rs new file +48
-0+ @reg $(#[$attr])* $vis $name ($storage) $([$size $(; $stride)?])? + $(@ $offset)? + $(@ $base + $base_offset)? + $(=> $alias $(+ $alias_offset)? $([$alias_idx])? )? + { $($fields)* } + ); + )* + }; + +// All the rules below are private helpers. + +// Creates a register at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $offset); + }; + +// Creates an alias register of fixed offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET ); + }; + +// Creates a register at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $base:ident + $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $offset ); + }; + +// Creates an alias register of relative offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $base:ident + $alias:ident + { $($fields:tt)* }
Quoted 8 lines
rust/kernel/io/register.rs line 558
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+ ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $alias::OFFSET );Would this generate error messages if $name and $alias are of different base, or would such case be a bug but silently compiles?
You would get an build error when trying to use the alias as the bases are dedicated types and the types would be incompatible.
Quoted 123 lines
Quoted 123 lines
rust/kernel/io/register.rs new file +122
-0+ }; + +// Creates an array of registers at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + [ $size:expr ; $stride:expr ] @ $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_array $name($storage) [ $size ; $stride ] @ $offset); + }; + +// Shortcut for contiguous array of registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of array of registers `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident [ $idx:expr ] + { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET + $idx * $alias::STRIDE ); + }; + +// Creates an array of registers at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative_array $name($storage) [ $size ; $stride ] @ $base + $offset + ); + }; + +// Shortcut for contiguous array of relative registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $base + $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of relative array of registers `alias` with its own +// fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + => $base:ident + $alias:ident [ $idx:expr ] { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative $name($storage) @ $base + $alias::OFFSET + $idx * $alias::STRIDE + ); + }; + +// Generates the bitfield for the register. +// +// `#[allow(non_camel_case_types)]` is added since register names typically use SCREAMING_CASE. + ( + @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } + ) => { + ::kernel::register!(@bitfield_core +#[allow(non_camel_case_types)] + $(#[$attr] )* $vis $name $storage + ); + ::kernel::register!(@bitfield_fields $vis $name $storage { $($fields)* }); + }; + +// Generates the IO accessors for a fixed offset register. + (@io_fixed $name:ident ($storage:ty) @ $offset:expr) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from its address in `io`. +#[inline(always)] +pub fn read <T ,I >(io: &T ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +Self (<$storageas $crate::io::register::RegisterIo >::read (io,Self ::OFFSET )) + } + +/// Write the value contained in `self` to the register address in `io`. +#[inline(always)] +pub fn write <T ,I >(self, io: &T )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io,Self ::OFFSET ) + } + +/// Read the register from its address in `io` and run `f` on its value to obtain a new +/// value to write back. +///
Quoted 8 lines
rust/kernel/io/register.rs line 682
Quoted 2 lines
rust/kernel/io/register.rs new file +2
-0+/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. Given the non-atomicity, how much value does it provide compared to having the user write read and write themselves? I feel that people reading the code may assume the atomicity without reading docs if they see
FOO::update, while it's less likely that they do so if they readFOO::read(io).with_bar(baz).write(io).
It is just a convenience method. I cannot pretend it is widely used, but it allows to turn multiple-step ops into one-liners.
Quoted 363 lines
Quoted 363 lines
rust/kernel/io/register.rs new file +362
-0+#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io)); + reg.write (io); + } + } + }; + +// Generates the IO accessors for a relative offset register. + (@io_relative $name:ident ($storage:ty) @ $base:ident + $offset:expr ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the register's offset to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it, then run `f` on its value to obtain a new value to +/// write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base)); + reg.write (io, base); + } + } + }; + +// Generates the IO accessors for an array of registers. + (@io_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] @ $offset:literal) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from its address in `io`. +#[inline(always)] +pub fn read <T ,I >( + io: &T , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +#[inline(always)] +pub fn write <T ,I >( + self, + io: &T , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, idx)); + reg.write (io, idx); + } + +/// Read the array register at index `idx` from its address in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I >( + io: &T , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I >( + self, + io: &T , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (self.write (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, idx, f)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + } + }; + +// Generates the IO accessors for an array of relative registers. + ( + @io_relative_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal + ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base, idx)); + reg.write (io, base, idx); + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I ,B >( + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I ,B >( + self, + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (self.write (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, base, idx, f)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + } + };
Quoted 8 lines
rust/kernel/io/register.rs line 1050
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+ +// Defines the wrapper `$name` type and its conversions from/to the storage type. + (@bitfield_core $(#[$attr:meta])* $vis:vis $name:ident $storage:ty) => { + $(#[$attr])* + #[repr(transparent)] + #[derive(Clone, Copy, PartialEq, Eq)]You can derive
Zeroableand save you an unsafe impl.
Unfortunately this happens if I try to do it:
error: no rules expected `(`
--> ../samples/rust/rust_driver_pci.rs:74:9
|
74 | / ::kernel::register! {
75 | | VENDOR_ID(u16) @ 0x0 {
76 | | 15:0 vendor_id;
... |
86 | | }
| |_________^ no rules expected this token in macro callNot quite sure why to be honest.
Quoted 11 lines
Quoted 11 lines
rust/kernel/io/register.rs new file +10
-0+ $vis struct $name($storage); + +#[allow(dead_code)] +impl $name { +/// Creates a bitfield from a raw value. + $vis const fn from_raw(value: $storage) -> Self { +Self (value) + } + +/// Creates a zeroed bitfield value.
Quoted 8 lines
rust/kernel/io/register.rs line 1065
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+/// +/// This is a const alternative to the `Zeroable::zeroed()` trait method. + $vis const fn zeroed() -> Self { +Self (0 ) + }All types that impl
Zeroableautomatically have the::zeroed()fn provided via the trait.
Yes, but that method from the trait cannot be used in const context, and zeroed is the starting point for building register values from scratch (and thus constant values).
Quoted 52 lines
Quoted 52 lines
rust/kernel/io/register.rs new file +51
-0+ +/// Returns the raw value of this bitfield. +/// +/// This is similar to the [`From`] implementation, but is shorter to invoke in +/// most cases. + $vis const fn as_raw(self) -> $storage { + self.0 + } + } + +// SAFETY: `$storage` is `Zeroable` and `$name` is transparent. +unsafe impl ::pin_init::Zeroable for $name {} + +impl ::core::convert::From <$name>for $storage { +fn from (val: $name) -> $storage { + val.as_raw () + } + } + +impl ::core::convert::From <$storage>for $name { +fn from (val: $storage) -> $name { +Self ::from_raw (val) + } + } + }; + +// Definitions requiring knowledge of individual fields: private and public field accessors, +// and `Debug` implementation. + (@bitfield_fields $vis:vis $name:ident $storage:ty { + $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident + $(?=> $try_into_type:ty)? + $(=> $into_type:ty)? + ; + )* + } + ) => { + #[allow(dead_code)] + impl $name { + $( + ::kernel::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); + ::kernel::register!( + @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field + $(?=> $try_into_type)? + $(=> $into_type)? + ); + )* + } + + ::kernel::register!(@debug $name { $($field;)* }); + }; +
Quoted 8 lines
rust/kernel/io/register.rs line 1122
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+// Private field accessors working with the correct `Bounded` type for the field. + ( + @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident + ) => { + ::kernel::macros::paste!( + $visconst [<$field:upper_RANGE >]: ::core::ops::RangeInclusive <u8 > = $lo..=$hi;Is this used by anything?
Not yet. This is intended for user code that wants to know which bits are used by a specific field. I don't mind removing it though.
Thanks for the review and ideas!
Gary Guo
reviewerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 94 lines · Alexandre Courbot
Quoted 79 lines · Gary Guo
Quoted 64 lines · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
Each register field is represented as a
Boundedof the appropriate bit width, ensuring field values are never silently truncated.Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)rust/kernel/io.rs +1
-0@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;rust/kernel/io/register.rs new file +28
-0@@ -0,0 +1,1287 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A macro to define register layout and accessors. +//! +//! A single register typically includes several fields, which are accessed through a combination +//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because +//! not all possible field values are necessarily valid. +//! +//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a +//! dedicated type for each register. Each such type comes with its own field accessors that can +//! return an error if a field's value is invalid. +//! +//! [`register!`]: kernel::register! + +use core::ops::Deref ; + +use crate ::io::{ +IoCapable , +IoKnownSize ,// +}; + +/// 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 > {rust/kernel/io/register.rs line 38
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// Base address to which register offsets are added. +const BASE :usize ; +} + +/// Trait providing I/O read/write operations for register storage types. +/// +/// This trait is implemented for all integer types on which I/O can be performed, allowing the +/// `register!` macro to generate appropriate I/O accessor methods based on the register's storage +/// type. +pub trait RegisterIo :Sized {Is this trait intended for public usage or just internal detail of
register!()macro?Quoted 3 lines
If it's the former, then we should probably just put the method into
IoCapableand allow generic-read in Io. If it's the latter, let's#[doc(hidden)]this so it won't get abused.It is an internal detail of
register!()and not supposed to be used by anyone else.Quoted 7 lines
Quoted 6 lines
rust/kernel/io/register.rs new file +5
-0+/// Read a value from the given offset in the I/O region. +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >;
Quoted 5 lines
Quoted 2 lines
I think generally
Derefbound shouldn't be exposed to user. What smart pointers are involved here, and can we implement forwarding impls ofIo?Removing the requirement for
Derefin theRegisterIotrait is simple - we can just callDerefin the register IO accessors.
The issue with Deref bound here is that now you *require* a level of indirection. If something implements Io directly, you cannot use it with the method. While &Bar is accepted, &Mmio is not because Mmio is a direct implementor of Io and not deref to it.
A Deref bound also does not help if, say, a type is Arc<Bar> which needs two level of dereffing before it is Io. For consistency I think it's best to avoid Deref call all together
Quoted 495 lines
But I suspect you mean that we should also remove it from the register accessors themselves? The problem if I remove it there is that things like Nova's
Bar0do not implementIoKnownSizeandIoCapable(but rather deref to something that does), which would require all callers to do the deref op itself as deref coercion doesn't seem to be usable here.Quoted 64 lines
Quoted 64 lines
rust/kernel/io/register.rs new file +63
-0+ +/// Write a value to the given offset in the I/O region. +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >; +} + +impl RegisterIo for u8 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read8 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write8 (self, offset) + } +} + +impl RegisterIo for u16 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read16 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write16 (self, offset) + } +} + +impl RegisterIo for u32 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read32 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >,Quoted 8 lines
rust/kernel/io/register.rs line 112
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+ { + io.write32 (self, offset) + } +} + +#[cfg( CONFIG_64BIT )] This cfg should be removed.
Done.
Quoted 369 lines
Quoted 356 lines
rust/kernel/io/register.rs new file +355
-0+impl RegisterIo for u64 { +#[inline(always)] +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.read64 (offset) + } + +#[inline(always)] +fn write <T ,I >(self, io: &T , offset:usize ) +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >, + { + io.write64 (self, offset) + } +} + +/// Defines a dedicated type for a register, including getter and setter methods for its fields and +/// methods to read and write it from an [`Io`] region. +/// +/// Example: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Basic information about the chip. +/// pub BOOT_0(u32) @ 0x00000100 { +/// /// Vendor ID. +/// 15:8 vendor_id; +/// /// Major revision of the chip. +/// 7:4 major_revision; +/// /// Minor revision of the chip. +/// 3:0 minor_revision; +/// } +/// } +/// ``` +/// +/// This defines a `BOOT_0` type which can be read from or written to offset `0x100` of an `Io` +/// region. For instance, `minor_revision` consists of the 4 least significant bits of the +/// register. +/// +/// Fields are instances of [`Bounded`](kernel::num::Bounded) and can be read by calling their +/// getter method, which is named after them. They also have setter methods prefixed with `set_` +/// for runtime values and `with_` for constant values. All setters return the updated register +/// value. +/// +/// ```no_run +/// use kernel::register; +/// use kernel::num::Bounded; +/// +/// # register! { +/// # pub BOOT_0(u32) @ 0x00000100 { +/// # 15:8 vendor_id; +/// # 7:4 major_revision; +/// # 3:0 minor_revision; +/// # } +/// # } +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// # fn obtain_vendor_id() -> u8 { 0xff } +/// // Read from the register's defined offset (0x100). +/// let boot0 = BOOT_0::read(&bar); +/// pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.minor_revision().get()); +/// +/// // Update some fields and write the new value back. +/// boot0 +/// // Constant values. +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// // Run-time value. +/// .set_vendor_id(obtain_vendor_id()) +/// .write(&bar); +/// +/// // Or, just read and update the register in a single step. +/// BOOT_0::update(&bar, |r| r +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>() +/// .set_vendor_id(obtain_vendor_id()) +/// ); +/// +/// // Constant values can also be built using the const setters. +/// const V: BOOT_0 = BOOT_0::zeroed() +/// .with_major_revision::<3>() +/// .with_minor_revision::<10>(); +/// # } +/// ``` +/// +/// Fields can also be transparently converted from/to an arbitrary type by using the bitfield `=>` +/// and `?=>` syntaxes. +/// +/// If present, doccomments above register or fields definitions are added to the relevant item +/// they document (the register type itself, or the field's setter and getter methods). +/// +/// Note that multiple registers can be defined in a single `register!` invocation. This can be +/// useful to group related registers together. +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// pub BOOT_0(u8) @ 0x00000100 { +/// 7:4 major_revision; +/// 3:0 minor_revision; +/// } +/// +/// pub BOOT_1(u8) @ 0x00000101 { +/// 7:5 num_threads; +/// 4:0 num_cores; +/// } +/// }; +/// ``` +/// +/// It is possible to create an alias of an existing register with new field definitions by using +/// the `=> ALIAS` syntax. This is useful for cases where a register's interpretation depends on +/// the context: +/// +/// ``` +/// use kernel::register; +/// +/// register! { +/// /// Scratch register. +/// pub SCRATCH(u32) @ 0x00000200 { +/// /// Raw value. +/// 31:0 value; +/// } +/// +/// /// Boot status of the firmware. +/// pub SCRATCH_BOOT_STATUS(u32) => SCRATCH { +/// /// Whether the firmware has completed booting. +/// 0:0 completed; +/// } +/// } +/// ``` +/// +/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also +/// providing its own `completed` field. +/// +/// ## Relative registers +/// +/// A register can be defined as being accessible from a fixed offset of a provided base. For +/// instance, imagine the following I/O space: +/// +/// ```text +/// +-----------------------------+ +/// | ... | +/// | | +/// 0x100--->+------------CPU0-------------+ +/// | | +/// 0x110--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// | | +/// | | +/// 0x200--->+------------CPU1-------------+ +/// | | +/// 0x210--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// +-----------------------------+ +/// ``` +/// +/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset `0x10` of their I/O +/// space segment. Since both instances of `CPU_CTL` share the same layout, we don't want to define +/// them twice and would prefer a way to select which one to use from a single definition +/// +/// This can be done using the `Base + Offset` syntax when specifying the register's address. +/// +/// `Base` is an arbitrary type (typically a ZST) to be used as a generic parameter of the +/// [`RegisterBase`] trait to provide the base as a constant, i.e. each type providing a base for +/// this register needs to implement `RegisterBase<Base>`. Here is the above example translated +/// into code: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// // Type used to identify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) { +/// // This makes `CPU_CTL` accessible from all implementors of `RegisterBase<CpuCtlBase>`. +/// register! { +/// /// CPU core control. +/// pub CPU_CTL(u32) @ CpuCtlBase + 0x10 { +/// /// Start the CPU core. +/// 0:0 start; +/// } +/// } +/// +/// // The `read`, `write` and `update` methods of relative registers take an extra `base` argument +/// // that is used to resolve its final address by adding its `BASE` to the offset of the +/// // register. +/// +/// // Start `CPU0`. +/// CPU_CTL::update(&bar, &CPU0, |r| r.set_start(true)); +/// +/// // Start `CPU1`. +/// CPU_CTL::update(&bar, &CPU1, |r| r.set_start(true)); +/// +/// // Aliases can also be defined for relative register. +/// register! { +/// /// Alias to CPU core control. +/// pub CPU_CTL_ALIAS(u32) => CpuCtlBase + CPU_CTL { +/// /// Start the aliased CPU core. +/// 1:1 alias_start; +/// } +/// } +/// +/// // Start the aliased `CPU0`. +/// CPU_CTL_ALIAS::update(&bar, &CPU0, |r| r.set_alias_start(true)); +/// # } +/// ``` +/// +/// ## Arrays of registers +/// +/// Some I/O areas contain consecutive registers that can be interpreted in the same way. These +/// areas can be defined as an array of identical registers, allowing them to be accessed by index +/// with compile-time or runtime bound checking. Simply specify their size inside `[` and `]` +/// brackets, and add an `idx` parameter to their `read`, `write` and `update` methods: +/// +/// ```no_run +/// use kernel::register; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Array of 64 consecutive registers with the same layout starting at offset `0x80`. +/// register! { +/// /// Scratch registers. +/// pub SCRATCH(u32)[64] @ 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// // Read scratch register 0, i.e. I/O address `0x80`. +/// let scratch_0 = SCRATCH::read(&bar, 0).value(); +/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`. +/// let scratch_15 = SCRATCH::read(&bar, 15).value(); +/// +/// // This is out of bounds and won't build. +/// // let scratch_128 = SCRATCH::read(&bar, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime index returns an error if it is out-of-bounds. +/// let some_scratch = SCRATCH::try_read(&bar, scratch_idx)?.value(); +/// +/// // Alias to a particular register in an array. +/// // Here `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Firmware exit status code. +/// pub FIRMWARE_STATUS(u32) => SCRATCH[8] { +/// 7:0 status; +/// } +/// } +/// let status = FIRMWARE_STATUS::read(&bar).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ 0x000000c0 { +/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ 0x000000c4 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// ## Relative arrays of registers +/// +/// Combining the two features described in the sections above, arrays of registers accessible from +/// a base can also be defined: +/// +/// ```no_run +/// use kernel::register; +/// use kernel::io::register::RegisterBase; +/// +/// # fn test<T: kernel::io::IoKnownSize + kernel::io::IoCapable<u32>>(bar: &T) +/// # -> Result<(), Error>{ +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// // Type used as parameter of `RegisterBase` to specify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase<CpuCtlBase> for Cpu0 { +/// const BASE: usize = 0x100; +/// } +/// // Singleton of `CPU0` used to identify it. +/// const CPU0: Cpu0 = Cpu0; +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase<CpuCtlBase> for Cpu1 { +/// const BASE: usize = 0x200; +/// } +/// // Singleton of `CPU1` used to identify it. +/// const CPU1: Cpu1 = Cpu1; +/// +/// // 64 per-cpu scratch registers, arranged as a contiguous array. +/// register! { +/// /// Per-CPU scratch registers. +/// pub CPU_SCRATCH(u32)[64] @ CpuCtlBase + 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// let cpu0_scratch_0 = CPU_SCRATCH::read(&bar, &Cpu0, 0).value(); +/// let cpu1_scratch_15 = CPU_SCRATCH::read(&bar, &Cpu1, 15).value(); +/// +/// // This won't build. +/// // let cpu0_scratch_128 = CPU_SCRATCH::read(&bar, &Cpu0, 128).value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx = get_scratch_idx(); +/// // Access on a runtime value returns an error if it is out-of-bounds. +/// let cpu0_some_scratch = CPU_SCRATCH::try_read(&bar, &Cpu0, scratch_idx)?.value(); +/// +/// // `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Per-CPU firmware exit status code. +/// pub CPU_FIRMWARE_STATUS(u32) => CpuCtlBase + CPU_SCRATCH[8] { +/// 7:0 status; rust/kernel/io/register.rs line 477
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// } +/// } +/// let cpu0_status = CPU_FIRMWARE_STATUS::read(&bar, &Cpu0).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 bytes, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub CPU_SCRATCH_INTERLEAVED_0(u32)[16 ; 8] @ CpuCtlBase + 0x00000d00 { I discussed this with Alex off-list and we agree that this'll better be
Quoted 4 lines
pub CPU_SCRATCH_INTERLEAVED_0(u32)[u16, stride = 8] @ CpuCtlBase + 0x00000d00spelling the full intention out rather than have a special syntax, as this isn't the common case.
Implemented it and it indeed looks much better.
Quoted 17 lines
Quoted 17 lines
rust/kernel/io/register.rs new file +16
-0+/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub CPU_SCRATCH_INTERLEAVED_1(u32)[16 ; 8] @ CpuCtlBase + 0x00000d04 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// [`Io`]: kernel::io::Io +#[macro_export] +macro_rules! register { +// Entry point for the macro, allowing multiple registers to be defined in one call. +// It matches all possible register declaration patterns to dispatch them to corresponding Quoted 8 lines
rust/kernel/io/register.rs line 499
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+// `@reg` rule that defines a single register. + ( + $( + $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + $([ $size:expr $(; $stride:expr)? ])? $(@ $offset:literal)? + $(@ $base:ident + $base_offset:literal)?Does
$(@ $($base:ident +)? $offset:literal)?not work?It does! I was trying to match the
+in the right-side expression and obviously couldn't, but it didn't occur to me to do it the other way. :)Quoted 8 lines
Quoted 7 lines
rust/kernel/io/register.rs new file +6
-0+ $(=> $alias:ident $(+ $alias_offset:ident)? $([$alias_idx:expr])? )? + { $($fields:tt)* } + )* + ) => { + $( + ::kernel::register!(
Quoted 3 lines
Quoted 1 line
$crate::register!()
Updated throughout the file (I am not sure to understand the difference though?).
It'll always resolve to the correct crate.
In theory, a crate can do
extern crate kernel as shell;
extern crate foobar as kernel;and now ::kernel:: would resolve to the wrong crate. Of course, people doing this are just shooting their own foot so it's not something to worry about.
Using $crate:: also allow re-exporting of the macro without adding a direct dependency (as indirect dependencies are not visible with ::crate_name).
Neither are issue of the kernel crate, but in general it's advisable to use $crate where possible.
Quoted 581 lines
Quoted 50 lines
Quoted 50 lines
rust/kernel/io/register.rs new file +48
-0+ @reg $(#[$attr])* $vis $name ($storage) $([$size $(; $stride)?])? + $(@ $offset)? + $(@ $base + $base_offset)? + $(=> $alias $(+ $alias_offset)? $([$alias_idx])? )? + { $($fields)* } + ); + )* + }; + +// All the rules below are private helpers. + +// Creates a register at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $offset); + }; + +// Creates an alias register of fixed offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET ); + }; + +// Creates a register at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $base:ident + $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $offset ); + }; + +// Creates an alias register of relative offset register `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $base:ident + $alias:ident + { $($fields:tt)* }Quoted 8 lines
rust/kernel/io/register.rs line 558
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+ ) => { + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_relative $name($storage) @ $base + $alias::OFFSET );Would this generate error messages if $name and $alias are of different base, or would such case be a bug but silently compiles?
You would get an build error when trying to use the alias as the bases are dedicated types and the types would be incompatible.
Quoted 123 lines
Quoted 123 lines
rust/kernel/io/register.rs new file +122
-0+ }; + +// Creates an array of registers at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + [ $size:expr ; $stride:expr ] @ $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_array $name($storage) [ $size ; $stride ] @ $offset); + }; + +// Shortcut for contiguous array of registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] @ $offset:literal + { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of array of registers `alias` with its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) => $alias:ident [ $idx:expr ] + { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!(@io_fixed $name($storage) @ $alias::OFFSET + $idx * $alias::STRIDE ); + }; + +// Creates an array of registers at a relative offset from a base address provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { +static_assert! (::core::mem::size_of ::<$storage>() <= $stride); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative_array $name($storage) [ $size ; $stride ] @ $base + $offset + ); + }; + +// Shortcut for contiguous array of relative registers (stride == size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) => { + ::kernel::register!( + $(#[$attr] )* $vis $name($storage) [ $size ; ::core::mem::size_of ::<$storage>() ] + @ $base + $offset { $($fields)* } + ); + }; + +// Creates an alias of register `idx` of relative array of registers `alias` with its own +// fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + => $base:ident + $alias:ident [ $idx:expr ] { $($fields:tt)* } + ) => { +static_assert! ($idx < $alias::SIZE ); + + ::kernel::register!( + @bitfield $(#[$attr] )* $visstruct $name($storage) { $($fields)* } + ); + ::kernel::register!( + @io_relative $name($storage) @ $base + $alias::OFFSET + $idx * $alias::STRIDE + ); + }; + +// Generates the bitfield for the register. +// +// `#[allow(non_camel_case_types)]` is added since register names typically use SCREAMING_CASE. + ( + @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } + ) => { + ::kernel::register!(@bitfield_core +#[allow(non_camel_case_types)] + $(#[$attr] )* $vis $name $storage + ); + ::kernel::register!(@bitfield_fields $vis $name $storage { $($fields)* }); + }; + +// Generates the IO accessors for a fixed offset register. + (@io_fixed $name:ident ($storage:ty) @ $offset:expr) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from its address in `io`. +#[inline(always)] +pub fn read <T ,I >(io: &T ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +Self (<$storageas $crate::io::register::RegisterIo >::read (io,Self ::OFFSET )) + } + +/// Write the value contained in `self` to the register address in `io`. +#[inline(always)] +pub fn write <T ,I >(self, io: &T )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io,Self ::OFFSET ) + } + +/// Read the register from its address in `io` and run `f` on its value to obtain a new +/// value to write back. +/// Quoted 8 lines
rust/kernel/io/register.rs line 682
Quoted 2 lines
rust/kernel/io/register.rs new file +2
-0+/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. Given the non-atomicity, how much value does it provide compared to having the user write read and write themselves? I feel that people reading the code may assume the atomicity without reading docs if they see
FOO::update, while it's less likely that they do so if they readFOO::read(io).with_bar(baz).write(io).It is just a convenience method. I cannot pretend it is widely used, but it allows to turn multiple-step ops into one-liners.
Quoted 363 lines
Quoted 363 lines
rust/kernel/io/register.rs new file +362
-0+#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io)); + reg.write (io); + } + } + }; + +// Generates the IO accessors for a relative offset register. + (@io_relative $name:ident ($storage:ty) @ $base:ident + $offset:expr ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register. +pub const OFFSET :usize = $offset; + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the register's offset to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET ; + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the register from `io`, using the base address provided by `base` and adding +/// the register's offset to it, then run `f` on its value to obtain a new value to +/// write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base)); + reg.write (io, base); + } + } + }; + +// Generates the IO accessors for an array of registers. + (@io_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] @ $offset:literal) => { +#[allow(dead_code)] +impl $name { +/// Absolute offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from its address in `io`. +#[inline(always)] +pub fn read <T ,I >( + io: &T , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +#[inline(always)] +pub fn write <T ,I >( + self, + io: &T , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +build_assert! (idx <Self ::SIZE ); + +let offset =Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, idx)); + reg.write (io, idx); + } + +/// Read the array register at index `idx` from its address in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I >( + io: &T , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to the array register with index `idx` in `io`. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I >( + self, + io: &T , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, + { +if idx <Self ::SIZE { +Ok (self.write (io, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a +/// new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,F >( + io: &T , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, idx, f)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + } + }; + +// Generates the IO accessors for an array of relative registers. + ( + @io_relative_array $name:ident ($storage:ty) [ $size:expr ; $stride:expr ] + @ $base:ident + $offset:literal + ) => { +#[allow(dead_code)] +impl $name { +/// Relative offset of the register array. +pub const OFFSET :usize = $offset; +/// Number of elements in the array of registers. +pub const SIZE :usize = $size; +/// Number of bytes separating each element of the array of registers. +pub const STRIDE :usize = $stride; + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +#[inline(always)] +pub fn read <T ,I ,B >( + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize , + ) ->Self where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + +Self (<$storageas $crate::io::register::RegisterIo >::read (io, offset)) + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +#[inline(always)] +pub fn write <T ,I ,B >( + self, + io: &T , +#[allow(unused_variables)] + base: &B , + idx:usize + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +build_assert! (idx <Self ::SIZE ); + +let offset = <B as $crate::io::register::RegisterBase <$base>>::BASE + +Self ::OFFSET + (idx *Self ::STRIDE ); + + <$storageas $crate::io::register::RegisterIo >::write (self.0 , io, offset) + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io, base, idx)); + reg.write (io, base, idx); + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_read <T ,I ,B >( + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result <Self >where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (Self ::read (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Write the value contained in `self` to `io`, using the base address provided by +/// `base` and adding the offset of array register `idx` to it. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +#[inline(always)] +pub fn try_write <T ,I ,B >( + self, + io: &T , + base: &B , + idx:usize , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, + { +if idx <Self ::SIZE { +Ok (self.write (io, base, idx)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + +/// Read the array register at index `idx` from `io`, using the base address provided +/// by `base` and adding the register's offset to it, then run `f` on its value to +/// obtain a new value to write back. +/// +/// The validity of `idx` is checked at run-time, and `EINVAL` is returned if the +/// access was out-of-bounds. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions. +#[inline(always)] +pub fn try_update <T ,I ,B ,F >( + io: &T , + base: &B , + idx:usize , + f:F , + ) -> ::kernel::error::Result where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +B : $crate::io::register::RegisterBase <$base>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +if idx <Self ::SIZE { +Ok (Self ::update (io, base, idx, f)) + }else { +Err (::kernel::error::code::EINVAL ) + } + } + } + };Quoted 8 lines
rust/kernel/io/register.rs line 1050
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+ +// Defines the wrapper `$name` type and its conversions from/to the storage type. + (@bitfield_core $(#[$attr:meta])* $vis:vis $name:ident $storage:ty) => { + $(#[$attr])* + #[repr(transparent)] + #[derive(Clone, Copy, PartialEq, Eq)]You can derive
Zeroableand save you an unsafe impl.Unfortunately this happens if I try to do it:
error: no rules expected `(` --> ../samples/rust/rust_driver_pci.rs:74:9 | 74 | / ::kernel::register! { 75 | | VENDOR_ID(u16) @ 0x0 { 76 | | 15:0 vendor_id; ... | 86 | | } | |_________^ no rules expected this token in macro call
Quoted 1 line
Not quite sure why to be honest.
I'll look into this.
Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
rust/kernel/io/register.rs new file +10
-0+ $vis struct $name($storage); + +#[allow(dead_code)] +impl $name { +/// Creates a bitfield from a raw value. + $vis const fn from_raw(value: $storage) -> Self { +Self (value) + } + +/// Creates a zeroed bitfield value. Quoted 8 lines
rust/kernel/io/register.rs line 1065
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+/// +/// This is a const alternative to the `Zeroable::zeroed()` trait method. + $vis const fn zeroed() -> Self { +Self (0 ) + }All types that impl
Zeroableautomatically have the::zeroed()fn provided via the trait.
Quoted 3 lines
Yes, but that method from the trait cannot be used in const context, and
zeroedis the starting point for building register values from scratch (and thus constant values).
pin_init:::zeroed() is a const function.
Best,
Gary
Quoted 66 lines
Quoted 53 lines
Quoted 53 lines
rust/kernel/io/register.rs new file +51
-0+ +/// Returns the raw value of this bitfield. +/// +/// This is similar to the [`From`] implementation, but is shorter to invoke in +/// most cases. + $vis const fn as_raw(self) -> $storage { + self.0 + } + } + +// SAFETY: `$storage` is `Zeroable` and `$name` is transparent. +unsafe impl ::pin_init::Zeroable for $name {} + +impl ::core::convert::From <$name>for $storage { +fn from (val: $name) -> $storage { + val.as_raw () + } + } + +impl ::core::convert::From <$storage>for $name { +fn from (val: $storage) -> $name { +Self ::from_raw (val) + } + } + }; + +// Definitions requiring knowledge of individual fields: private and public field accessors, +// and `Debug` implementation. + (@bitfield_fields $vis:vis $name:ident $storage:ty { + $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident + $(?=> $try_into_type:ty)? + $(=> $into_type:ty)? + ; + )* + } + ) => { + #[allow(dead_code)] + impl $name { + $( + ::kernel::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); + ::kernel::register!( + @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field + $(?=> $try_into_type)? + $(=> $into_type)? + ); + )* + } + + ::kernel::register!(@debug $name { $($field;)* }); + }; +Quoted 8 lines
rust/kernel/io/register.rs line 1122
Quoted 6 lines
rust/kernel/io/register.rs new file +6
-0+// Private field accessors working with the correct `Bounded` type for the field. + ( + @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident + ) => { + ::kernel::macros::paste!( + $visconst [<$field:upper_RANGE >]: ::core::ops::RangeInclusive <u8 > = $lo..=$hi;Is this used by anything?
Not yet. This is intended for user code that wants to know which bits are used by a specific field. I don't mind removing it though.
Thanks for the review and ideas!
Danilo Krummrich
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 8 lines · Gary Guo
The issue with
Derefbound here is that now you *require* a level of indirection. If something implementsIodirectly, you cannot use it with the method. While&Baris accepted,&Mmiois not becauseMmiois a direct implementor ofIoand not deref to it.A
Derefbound also does not help if, say, a type isArc<Bar>which needs two level of dereffing before it is Io. For consistency I think it's best to avoidDerefcall all together
I agree with that and we will probably run into this once we start implementing the I/O traits for things like DMA memory.
We could use AsRef or a custom trait instead, but I'd rather leave this for a subsequent series, as it requires more changes. They should also be transparent to users.
Alexandre Courbot
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
In reply to Gary GuoQuoted 101 lines · Gary Guo
Quoted 94 lines · Alexandre Courbot
Quoted 79 lines · Gary Guo
Quoted 64 lines · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
Each register field is represented as a
Boundedof the appropriate bit width, ensuring field values are never silently truncated.Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)rust/kernel/io.rs +1
-0@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;rust/kernel/io/register.rs new file +28
-0@@ -0,0 +1,1287 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A macro to define register layout and accessors. +//! +//! A single register typically includes several fields, which are accessed through a combination +//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because +//! not all possible field values are necessarily valid. +//! +//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a +//! dedicated type for each register. Each such type comes with its own field accessors that can +//! return an error if a field's value is invalid. +//! +//! [`register!`]: kernel::register! + +use core::ops::Deref ; + +use crate ::io::{ +IoCapable , +IoKnownSize ,// +}; + +/// 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 > {rust/kernel/io/register.rs line 38
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// Base address to which register offsets are added. +const BASE :usize ; +} + +/// Trait providing I/O read/write operations for register storage types. +/// +/// This trait is implemented for all integer types on which I/O can be performed, allowing the +/// `register!` macro to generate appropriate I/O accessor methods based on the register's storage +/// type. +pub trait RegisterIo :Sized {Is this trait intended for public usage or just internal detail of
register!()macro?Quoted 3 lines
If it's the former, then we should probably just put the method into
IoCapableand allow generic-read in Io. If it's the latter, let's#[doc(hidden)]this so it won't get abused.It is an internal detail of
register!()and not supposed to be used by anyone else.Quoted 7 lines
Quoted 6 lines
rust/kernel/io/register.rs new file +5
-0+/// Read a value from the given offset in the I/O region. +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >;Quoted 5 lines
Quoted 2 lines
I think generally
Derefbound shouldn't be exposed to user. What smart pointers are involved here, and can we implement forwarding impls ofIo?Removing the requirement for
Derefin theRegisterIotrait is simple - we can just callDerefin the register IO accessors.
Quoted 8 lines
The issue with
Derefbound here is that now you *require* a level of indirection. If something implementsIodirectly, you cannot use it with the method. While&Baris accepted,&Mmiois not becauseMmiois a direct implementor ofIoand not deref to it.A
Derefbound also does not help if, say, a type isArc<Bar>which needs two level of dereffing before it is Io. For consistency I think it's best to avoidDerefcall all together
Do you mean that Bar should implement Io, IoKnownSize, and all the required IoCapables? That's a lot of boilerplate I'm afraid, and that would need to be repeated for all other I/O proxy types.
No, I'm starting to believe that the fundamental issue is that the register interface does its I/O backwards, and that design issue is only exacerbated by the recent I/O redesign. I.e. instead of doing
regs::NV_PMC_BOOT_0::read(bar);
We should really do
bar.read_reg::<regs::NV_PMC_BOOT_0>();
Because that way we can use deref coercion.
That's quite a big redesign though, which means I don't believe register! can make it this cycle... I'll give it a try though.
<snip>
Quoted 19 lines
Quoted 19 lines
Quoted 18 lines
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+ $vis struct $name($storage); + +#[allow(dead_code)] +impl $name { +/// Creates a bitfield from a raw value. rust/kernel/io/register.rs line 1065
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ $vis const fn from_raw(value: $storage) -> Self { +Self (value) + } + +/// Creates a zeroed bitfield value. +/// +/// This is a const alternative to the `Zeroable::zeroed()` trait method. + $vis const fn zeroed() -> Self { +Self (0 ) + }All types that impl
Zeroableautomatically have the::zeroed()fn provided via the trait.
Quoted 5 lines
Quoted 3 lines
Yes, but that method from the trait cannot be used in const context, and
zeroedis the starting point for building register values from scratch (and thus constant values).
pin_init:::zeroed()is a const function.
Ah, I thought about using Zeroable::zeroed() at first, but indeed we can use the function instead.
Strangely though, I expected to be able to do
const V: BOOT_0 = pin_init::zeroed()
and have the compiler infer the generic type, but for some reason I have to specify it explicitly:
const V: BOOT_0 = pin_init::zeroed::<BOOT_0>()
Not a big deal, but a const method would reduce this to
const V: BOOT_0 = BOOT_0::zeroed()
(for variables let v: BOOT_0 = pin_init::zeroed() works fine.)
Gary Guo
reviewerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 121 lines · Alexandre Courbot
Quoted 101 lines · Gary Guo
Quoted 94 lines · Alexandre Courbot
Quoted 79 lines · Gary Guo
Quoted 64 lines · Alexandre Courbot
Add a macro for defining hardware register types with I/O accessors.
Each register field is represented as a
Boundedof the appropriate bit width, ensuring field values are never silently truncated.Fields can optionally be converted to/from custom types, either fallibly or infallibly.
The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged.
Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/io.rs | 1 + rust/kernel/io/register.rs | 1287 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1288 insertions(+)rust/kernel/io.rs +1
-0@@ -11,6 +11,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;rust/kernel/io/register.rs new file +28
-0@@ -0,0 +1,1287 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A macro to define register layout and accessors. +//! +//! A single register typically includes several fields, which are accessed through a combination +//! of bit-shift and mask operations that introduce a class of potential mistakes, notably because +//! not all possible field values are necessarily valid. +//! +//! The [`register!`] macro in this module provides an intuitive and readable syntax for defining a +//! dedicated type for each register. Each such type comes with its own field accessors that can +//! return an error if a field's value is invalid. +//! +//! [`register!`]: kernel::register! + +use core::ops::Deref ; + +use crate ::io::{ +IoCapable , +IoKnownSize ,// +}; + +/// 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 > {rust/kernel/io/register.rs line 38
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+/// Base address to which register offsets are added. +const BASE :usize ; +} + +/// Trait providing I/O read/write operations for register storage types. +/// +/// This trait is implemented for all integer types on which I/O can be performed, allowing the +/// `register!` macro to generate appropriate I/O accessor methods based on the register's storage +/// type. +pub trait RegisterIo :Sized {Is this trait intended for public usage or just internal detail of
register!()macro?Quoted 3 lines
If it's the former, then we should probably just put the method into
IoCapableand allow generic-read in Io. If it's the latter, let's#[doc(hidden)]this so it won't get abused.It is an internal detail of
register!()and not supposed to be used by anyone else.Quoted 7 lines
Quoted 6 lines
rust/kernel/io/register.rs new file +5
-0+/// Read a value from the given offset in the I/O region. +fn read <T ,I >(io: &T , offset:usize ) ->Self +where +T :Deref <Target =I >, +I :IoKnownSize +IoCapable <Self >;Quoted 5 lines
Quoted 2 lines
I think generally
Derefbound shouldn't be exposed to user. What smart pointers are involved here, and can we implement forwarding impls ofIo?Removing the requirement for
Derefin theRegisterIotrait is simple - we can just callDerefin the register IO accessors.Quoted 8 lines
The issue with
Derefbound here is that now you *require* a level of indirection. If something implementsIodirectly, you cannot use it with the method. While&Baris accepted,&Mmiois not becauseMmiois a direct implementor ofIoand not deref to it.A
Derefbound also does not help if, say, a type isArc<Bar>which needs two level of dereffing before it is Io. For consistency I think it's best to avoidDerefcall all togetherDo you mean that
Barshould implementIo,IoKnownSize, and all the requiredIoCapables? That's a lot of boilerplate I'm afraid, and that would need to be repeated for all other I/O proxy types.No, I'm starting to believe that the fundamental issue is that the register interface does its I/O backwards, and that design issue is only exacerbated by the recent I/O redesign. I.e. instead of doing
regs::NV_PMC_BOOT_0::read(bar);
Quoted 8 lines
We should really do
bar.read_reg::<regs::NV_PMC_BOOT_0>();Because that way we can use deref coercion.
That's quite a big redesign though, which means I don't believe
register!can make it this cycle... I'll give it a try though.
Hmm, that's unfortunate, but I think this is indeed a big design change that we should iron out before merging...
I think you're right that if we put the methods on Io then all of the deref issue would just went away.
BTW, there's a tricky that would allow you to avoid turbofish in this case, i.e. you would be able to write
bar.read_reg(regs::NV_PMC_BOOT_0)
Or
bar.write_reg(regs::PV_PMC_BOOT_0, ...)
The trick is to note that the same name can present in both type and value namesapce. For example, when you define
struct Foo;
you create Foo type in type namespace and a const Foo: Foo in value namespace. Similarly
struct Foo(u32);
creates a Foo in type namespace and a fn(u32) -> Foo in value namespace. This process doesn't need to be automatic. So if you create
struct Foo { value: u32 }then you're only creating Foo in type namespace and not in value namespace. This means that you could do something like:
// Use PhantomData as example, could be other token/marker types.
const Foo: PhantomData<Foo> = PhantomData;
trait Io {
fn read_reg<Reg>(&self, _: PhantomData<Reg>) -> Reg { ... }
}
// Now no turbofish!
bar.read_reg(NV_PMC_BOOT_0)This trick is heavily used in syn, so you do input.peek(type) instead of input.peek::<Type>(), which I find quite handy.
Quoted 37 lines
<snip>
Quoted 19 lines
Quoted 19 lines
Quoted 18 lines
Quoted 5 lines
rust/kernel/io/register.rs new file +5
-0+ $vis struct $name($storage); + +#[allow(dead_code)] +impl $name { +/// Creates a bitfield from a raw value. rust/kernel/io/register.rs line 1065
Quoted 10 lines
rust/kernel/io/register.rs new file +10
-0+ $vis const fn from_raw(value: $storage) -> Self { +Self (value) + } + +/// Creates a zeroed bitfield value. +/// +/// This is a const alternative to the `Zeroable::zeroed()` trait method. + $vis const fn zeroed() -> Self { +Self (0 ) + }All types that impl
Zeroableautomatically have the::zeroed()fn provided via the trait.Quoted 5 lines
Quoted 3 lines
Yes, but that method from the trait cannot be used in const context, and
zeroedis the starting point for building register values from scratch (and thus constant values).
pin_init:::zeroed()is a const function.Ah, I thought about using
Zeroable::zeroed()at first, but indeed we can use the function instead.Strangely though, I expected to be able to do
const V:
BOOT_0=pin_init::zeroed()and have the compiler infer the generic type, but for some reason I have to specify it explicitly:
Quoted 7 lines
const V:
BOOT_0= pin_init::zeroed::<BOOT_0>()Not a big deal, but a const method would reduce this to
const V:
BOOT_0=BOOT_0::zeroed()(for variables
let v: BOOT_0 = pin_init::zeroed()works fine.)
That's strange. Do you have a MCVE for this? I can't reproduce what you described.
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 13 lines · Gary Guo
Quoted 12 lines · Alexandre Courbot
No, I'm starting to believe that the fundamental issue is that the register interface does its I/O backwards, and that design issue is only exacerbated by the recent I/O redesign. I.e. instead of doing
regs::NV_PMC_BOOT_0::read(bar);We should really do
bar.read_reg::<regs::NV_PMC_BOOT_0>();Because that way we can use deref coercion.
Quoted 8 lines
Quoted 2 lines
That's quite a big redesign though, which means I don't believe
register!can make it this cycle... I'll give it a try though.Hmm, that's unfortunate, but I think this is indeed a big design change that we should iron out before merging...
I think you're right that if we put the methods on
Iothen all of the deref issue would just went away.
I already discussed this with Alex offline and I think we should not take this direction just because of the Deref issue, as we can easily overcome this with using AsRef (or a custom trait).
Whereas the downside of bar.read_reg() is that you end up with a more inconsistent and complicated API for drivers.
For instance, with the API as is you can do things like:
register!(NV_PFALCON_FALCON_ENGINE @ PFalconBase[0x000003c0] {
0:0 reset as bool;
});
impl NV_PFALCON_FALCON_ENGINE {
pub(crate) fn reset_engine<E: FalconEngine>(bar: &Bar0) {
Self::update(bar, &E::ID, |r| r.set_reset(true));
// TIMEOUT: falcon engine should not take more than 10us to reset.
time::delay::fsleep(time::Delta::from_micros(10));
Self::update(bar, &E::ID, |r| r.set_reset(false));
}
}and then use this from the driver code like this:
impl<E: FalconEngine> FalconHal<E> for Tu102<E> {
fn do_stuff(&self, bar: &Bar0) {
//...
regs::NV_PFALCON_FALCON_ENGINE::reset_engine::<E>(bar);
//...
}
}Having to implement AsRef (or a custom trait) for the corresponding I/O backend implementations is a pretty minor inconvinience compared to the simplicity the current API provides to drivers.
Gary Guo
reviewerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 20 lines · Danilo Krummrich
Quoted 19 lines · Gary Guo
Quoted 6 lines · Alexandre Courbot
No, I'm starting to believe that the fundamental issue is that the register interface does its I/O backwards, and that design issue is only exacerbated by the recent I/O redesign. I.e. instead of doing
regs::NV_PMC_BOOT_0::read(bar);Quoted 8 lines
We should really do
bar.read_reg::<regs::NV_PMC_BOOT_0>();Because that way we can use deref coercion.
That's quite a big redesign though, which means I don't believe
register!can make it this cycle... I'll give it a try though.Hmm, that's unfortunate, but I think this is indeed a big design change that we should iron out before merging...
Quoted 6 lines
Quoted 2 lines
I think you're right that if we put the methods on
Iothen all of the deref issue would just went away.I already discussed this with Alex offline and I think we should not take this direction just because of the Deref issue, as we can easily overcome this with using AsRef (or a custom trait).
AsRef won't work for Io which is a trait, unlike Device which is a type. A custom trait might work but that's more complex than what Alex purposed.
I'm quite fond of the io.read_reg(REGISTER_REF) API suggested. It looks quite uniform with other I/O acceessor methods, except typed and with constant offsets.
Quoted 6 lines
Whereas the downside of
bar.read_reg()is that you end up with a more inconsistent and complicated API for drivers.For instance, with the API as is you can do things like:
Quoted 14 lines
register!(NV_PFALCON_FALCON_ENGINE @ PFalconBase[0x000003c0] {
0:0 reset as bool;
});
impl NV_PFALCON_FALCON_ENGINE {
pub(crate) fn reset_engine<E: FalconEngine>(bar: &Bar0) {
Self::update(bar, &E::ID, |r| r.set_reset(true));
// TIMEOUT: falcon engine should not take more than 10us to reset.
time::delay::fsleep(time::Delta::from_micros(10));
Self::update(bar, &E::ID, |r| r.set_reset(false));
}
}The only benefit of this compared to the newly proposed API is that you can use Self. It's not too bad to have (hypothetical API)
pub(crate) fn reset_engine<E: FalconEngine>(bar: &Bar0) {
bar.update_reg(NV_PFALCON_FALCON_ENGINE(&E::ID), |r| r.set_reset(true));
// TIMEOUT: falcon engine should not take more than 10us to reset.
time::delay::fsleep(time::Delta::from_micros(10));
bar.update_reg(NV_PFALCON_FALCON_ENGINE(&E::ID), |r| r.set_reset(true));
}I also think in most cases these helper function won't be implemented on the register, so you're not saving much by having the ability to refer to Self. For example, in this case you could implement it on FalconEngine.
Best,
Gary
Quoted 20 lines
and then use this from the driver code like this:
impl<E: FalconEngine> FalconHal<E> for Tu102<E> { fn do_stuff(&self, bar: &Bar0) { //... regs::NV_PFALCON_FALCON_ENGINE::reset_engine::<E>(bar); //... } }Having to implement AsRef (or a custom trait) for the corresponding I/O backend implementations is a pretty minor inconvinience compared to the simplicity the current API provides to drivers.
Danilo Krummrich
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
Quoted 2 lines · Gary Guo
AsRefwon't work forIowhich is a trait, unlikeDevicewhich is a type. A custom trait might work but that's more complex than what Alex purposed.
Are we sure about that? For instance, how do we determine the size of the I/O operation in *_reg()? How can we trust that the type passed to *_reg() is valid for an arbitrary bit pattern?
I mean, I'm not saying it's possible, but it seems that we end up with a couple of safety requirements for the base register traits.
Quoted 3 lines
I'm quite fond of the
io.read_reg(REGISTER_REF)API suggested. It looks quite uniform with other I/O acceessor methods, except typed and with constant offsets.
It's just a nit, but I find it a bit icky that we have to have something like the "_reg" suffix.
Danilo Krummrich
maintainerRe: [PATCH v4 5/7] rust: io: add `register!` macro
In reply to Gary GuoQuoted 7 lines · Gary Guo
rust/kernel/io/register.rs line 682
Quoted 5 lines · Alexandre Courbot
rust/kernel/io/register.rs new file +5
-0+/// Read the register from its address in `io` and run `f` on its value to obtain a new +/// value to write back. +/// +/// Note that this operation is not atomic. In concurrent contexts, external +/// synchronization may be required to prevent race conditions.
Quoted 5 lines
Given the non-atomicity, how much value does it provide compared to having the user write read and write themselves? I feel that people reading the code may assume the atomicity without reading docs if they see
FOO::update, while it's less likely that they do so if they readFOO::read(io).with_bar(baz).write(io).
I think update() is fine, there are no promises about atomicity for any of the I/O functions, also not for read() and write(). I.e. whether an operation is atomic or not depends on the architecture, bus and device.
We should probably document this clearly to not raise wrong expectations.
Quoted 14 lines
Quoted 14 lines
rust/kernel/io/register.rs new file +14
-0+#[inline(always)] +pub fn update <T ,I ,F >( + io: &T , + f:F , + )where +T : ::core::ops::Deref <Target =I >, +I : ::kernel::io::IoKnownSize + ::kernel::io::IoCapable <$storage>, +F : ::core::ops::FnOnce (Self ) ->Self , + { +let reg =f (Self ::read (io)); + reg.write (io); + } + } + };
Alexandre Courbot
maintainerPATCH v4 6/7 sample: rust: pci: use `register!` macro
In reply to Alexandre CourbotConvert the direct IO accesses to properly defined registers.
--- samples/rust/rust_driver_pci.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)
samples/rust/rust_driver_pci.rs +18 -5
@@ -70,24 +70,37 @@ fn testdev(index: &TestIndex, bar: &Bar0) -> Result<u32> {fn config_space (pdev: &pci::Device <Bound >) {let config = pdev.config_space (); -// TODO: use the register!() macro for defining PCI configuration space registers once it -// has been move out of nova-core. +// Some PCI configuration space registers. + ::kernel::register! { +VENDOR_ID (u16 ) @0x0 { +15 :0 vendor_id; + } + +REVISION_ID (u8 ) @0x8 { +7 :0 revision_id; + } + +BAR (u32 )[6 ] @0x10 { +31 :0 value; + } + } +dev_info! ( pdev.as_ref (),"pci-testdev config space read8 rev ID: {:x}\n" , - config.read8 (0x8 ) +REVISION_ID ::read (&&config).revision_id () );dev_info! ( pdev.as_ref (),"pci-testdev config space read16 vendor ID: {:x}\n" , - config.read16 (0 ) +VENDOR_ID ::read (&&config).vendor_id () );dev_info! ( pdev.as_ref (),"pci-testdev config space read32 BAR 0: {:x}\n" , - config.read32 (0x10 ) +BAR ::read (&&config,0 ).value () ); } }
Signature · 1 line
2.52.0
Re: [PATCH v4 6/7] sample: rust: pci: use `register!` macro
Quoted 2 lines · On Wed, 28 Jan 2026 11:37:32 +0900 Alexandre Courbot <[email protected]>…
Convert the direct IO accesses to properly defined registers.
I can see the correct value of the registers read by the sample driver from the demesg.
Additionally, Clippy was complaining about unnecssary unsafe blocks and can be fixed by: (I haven't fully gone through the code, just applied this for getting rid of the warnnings.)
rust/kernel/num/bounded.rs +0 -0
@@ -503,9 +503,7 @@ pub fn cast<U>(self) -> Bounded<U, N>pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES >
{ const { assert!(RES >= N - SHIFT) }
- // SAFETY: We shift the value right by SHIFT, reducing the
number of bits needed to
- // represent the shifted value by as much, and just asserted that
RES == N - SHIFT.
- unsafe { Bounded::__new(self.0 >> SHIFT) }
+ Bounded::__new(self.0 >> SHIFT)
}
/// Left-shifts `self` by `SHIFT` and returns the result as a
`Bounded<_, RES>`, where `RES >= @@ -524,9 +522,7 @@ pub fn shr<const
SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> { pub fn
shl<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
const { assert!(RES >= N + SHIFT) }- // SAFETY: We shift the value left by SHIFT, augmenting the
number of bits needed to
- // represent the shifted value by as much, and just asserted that
RES == N + SHIFT.
- unsafe { Bounded::__new(self.0 << SHIFT) }
+ Bounded::__new(self.0 << SHIFT)
}
}
Z.
Quoted 54 lines
Signed-off-by Alexandre Courbot <[email protected]>--- samples/rust/rust_driver_pci.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)(quoted diff) +0
-0
b/samples/rust/rust_driver_pci.rsindex4dfb8a6a4707..df2232d6b71f100644samples/rust/rust_driver_pci.rs +0
-1@@ -70,24 +70,37 @@ fn testdev(index: &TestIndex, bar: &Bar0) ->Result <u32> {fn config_space (pdev: &pci::Device <Bound >) {let config = pdev.config_space (); -// TODO: use the register!() macro for defining PCI configuration space registers once it
samples/rust/rust_driver_pci.rs +18
-4-// has been move out of nova-core. +// Some PCI configuration space registers. + ::kernel::register! { +VENDOR_ID (u16 ) @0x0 { +15 :0 vendor_id; + } + +REVISION_ID (u8 ) @0x8 { +7 :0 revision_id; + } + +BAR (u32 )[6 ] @0x10 { +31 :0 value; + } + } +dev_info! ( pdev.as_ref (),"pci-testdev config space read8 rev ID: {:x}\n" , - config.read8 (0x8 ) +REVISION_ID ::read (&&config).revision_id () );dev_info! ( pdev.as_ref (),"pci-testdev config space read16 vendor ID: {:x}\n" , - config.read16 (0 ) +VENDOR_ID ::read (&&config).vendor_id () );dev_info! ( pdev.as_ref (),"pci-testdev config space read32 BAR 0: {:x}\n" , - config.read32 (0x10 ) +BAR ::read (&&config,0 ).value () ); } }
Alexandre Courbot
maintainerRe: [PATCH v4 6/7] sample: rust: pci: use `register!` macro
Quoted 10 lines · Zhi Wang
Quoted 2 lines · On Wed, 28 Jan 2026 11:37:32 +0900 Alexandre Courbot <[email protected]>…
Convert the direct IO accesses to properly defined registers.
Tested-by Zhi Wang <[email protected]>I can see the correct value of the registers read by the sample driver from the demesg.
Thanks!
Quoted 4 lines
Additionally, Clippy was complaining about unnecssary unsafe blocks and can be fixed by: (I haven't fully gone through the code, just applied this for getting rid of the warnnings.)
This is because Bounded::__new has become unsafe in rust-next ; this is not reflected in driver-core-next yet, but won't appear in -rc1.
Gary Guo
reviewerRe: [PATCH v4 6/7] sample: rust: pci: use `register!` macro
Quoted 15 lines · Alexandre Courbot
Quoted 10 lines · Zhi Wang
Quoted 2 lines · On Wed, 28 Jan 2026 11:37:32 +0900 Alexandre Courbot <[email protected]>…
Convert the direct IO accesses to properly defined registers.
Tested-by Zhi Wang <[email protected]>I can see the correct value of the registers read by the sample driver from the demesg.
Thanks!
Quoted 1 line
Quoted 6 lines
Quoted 3 lines
Additionally, Clippy was complaining about unnecssary unsafe blocks and can be fixed by: (I haven't fully gone through the code, just applied this for getting rid of the warnnings.)
This is because
Bounded::__newhas become unsafe inrust-next; this is not reflected indriver-core-nextyet, but won't appear in -rc1.
Any reason that you send the patch based on driver-core-next, instead of linux-next? You won't have the issue if this is based on linux-next.
Best,
Gary
Alexandre Courbot
maintainerRe: [PATCH v4 6/7] sample: rust: pci: use `register!` macro
Quoted 20 lines · Gary Guo
Quoted 19 lines · Alexandre Courbot
Quoted 10 lines · Zhi Wang
Quoted 2 lines · On Wed, 28 Jan 2026 11:37:32 +0900 Alexandre Courbot <[email protected]>…
Convert the direct IO accesses to properly defined registers.
Tested-by Zhi Wang <[email protected]>I can see the correct value of the registers read by the sample driver from the demesg.
Thanks!
Quoted 4 lines
Additionally, Clippy was complaining about unnecssary unsafe blocks and can be fixed by: (I haven't fully gone through the code, just applied this for getting rid of the warnnings.)
Quoted 5 lines
Quoted 2 lines
This is because
Bounded::__newhas become unsafe inrust-next; this is not reflected indriver-core-nextyet, but won't appear in -rc1.Any reason that you send the patch based on driver-core-next, instead of linux-next? You won't have the issue if this is based on linux-next.
driver-core-next is where the patch is going to be merged, so I use that as the base for the patchset.
Danilo Krummrich
maintainerRe: [PATCH v4 6/7] sample: rust: pci: use `register!` macro
In reply to Alexandre CourbotQuoted 44 lines · Alexandre Courbot
Convert the direct IO accesses to properly defined registers.
Signed-off-by Alexandre Courbot <[email protected]>--- samples/rust/rust_driver_pci.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)samples/rust/rust_driver_pci.rs +17
-4@@ -70,24 +70,37 @@ fn testdev(index: &TestIndex, bar: &Bar0) -> Result<u32> {fn config_space (pdev: &pci::Device <Bound >) {let config = pdev.config_space (); -// TODO: use the register!() macro for defining PCI configuration space registers once it -// has been move out of nova-core. +// Some PCI configuration space registers. + ::kernel::register! { +VENDOR_ID (u16 ) @0x0 { +15 :0 vendor_id; + } + +REVISION_ID (u8 ) @0x8 { +7 :0 revision_id; + } + +BAR (u32 )[6 ] @0x10 { +31 :0 value; + } + } +dev_info! ( pdev.as_ref (),"pci-testdev config space read8 rev ID: {:x}\n" , - config.read8 (0x8 ) +REVISION_ID ::read (&&config).revision_id () );dev_info! ( pdev.as_ref (),"pci-testdev config space read16 vendor ID: {:x}\n" , - config.read16 (0 ) +VENDOR_ID ::read (&&config).vendor_id ()
samples/rust/rust_driver_pci.rs fn testdev(index: &TestIndex, bar: &Bar0) -> Result<u32> { · line 106
Quoted 10 lines
samples/rust/rust_driver_pci.rs +1
-1);dev_info! ( pdev.as_ref (),"pci-testdev config space read32 BAR 0: {:x}\n" , - config.read32 (0x10 ) +BAR ::read (&&config,0 ).value () ); } }
That's only the config space registers, can you please also convert the MMIO ones?
Alexandre Courbot
maintainerPATCH v4 7/7 gpu: nova-core: use the kernel `register!` macro
In reply to Alexandre CourbotReplace the nova-core internal register! macro by the one defined in the kernel crate and remove our own private implementations.
--- drivers/gpu/nova-core/falcon.rs | 175 +++---- drivers/gpu/nova-core/falcon/gsp.rs | 12 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 15 +- drivers/gpu/nova-core/falcon/sec2.rs | 13 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 17 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 2 +- drivers/gpu/nova-core/gpu.rs | 31 +- drivers/gpu/nova-core/gsp/cmdq.rs | 4 +- drivers/gpu/nova-core/regs.rs | 494 +++++++++++--------- drivers/gpu/nova-core/regs/macros.rs | 739 ------------------------------ 10 files changed, 397 insertions(+), 1105 deletions(-)
drivers/gpu/nova-core/falcon.rs +71 -104
@@ -9,7 +9,11 @@use kernel::{ device, dma::DmaAddress , - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::RegisterBase ,// + }, + num::Bounded , prelude::*, sync::aref::ARef , time::{
@@ -27,7 +31,6 @@ IntoSafeCast, // }, regs, - regs::macros::RegisterBase, // };pub (crate )mod gsp;
@@ -35,11 +38,11 @@pub (crate )mod sec2;// TODO[FPRI]: Replace with `ToPrimitive`. -macro_rules! impl_from_enum_to_u8 { - ($enum_type:ty) => { -impl From <$enum_type>for u8 { +macro_rules! impl_from_enum_to_bounded { + ($enum_type:ty, $length:literal) => { +impl From <$enum_type>for Bounded <u32 , $length> {fn from (value: $enum_type) ->Self { - valueas u8 +Bounded ::from_expr (valueas u32 ) } } };
@@ -47,10 +50,8 @@ fn from(value: $enum_type) -> Self {/// Revision number of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] /// register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] +#[derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] pub (crate )enum FalconCoreRev { -#[default] Rev1 =1 ,Rev2 =2 ,Rev3 =3 ,
@@ -59,16 +60,16 @@ pub(crate) enum FalconCoreRev { Rev6 = 6, Rev7 = 7, } -impl_from_enum_to_u8! (FalconCoreRev ); +impl_from_enum_to_bounded! (FalconCoreRev ,4 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconCoreRev { +impl TryFrom <Bounded <u32 ,4 >>for FalconCoreRev {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { +fn try_from (value:Bounded <u32 ,4 >) ->Result <Self > {use FalconCoreRev ::*; -let rev =match value { +let rev =match value.get () {1 =>Rev1 ,2 =>Rev2 , 3 => Rev3,
@@ -85,46 +86,38 @@ fn try_from(value: u8) -> Result<Self> {/// Revision subversion number of a falcon core, used in the /// [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] +#[derive( Debug , Copy , Clone , PartialEq , Eq , PartialOrd , Ord )] pub (crate )enum FalconCoreRevSubversion { -#[default] Subversion0 =0 ,Subversion1 =1 ,Subversion2 =2 ,Subversion3 =3 , } -impl_from_enum_to_u8! (FalconCoreRevSubversion ); +impl_from_enum_to_bounded! (FalconCoreRevSubversion ,2 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconCoreRevSubversion { -type Error =Error ; - -fn try_from (value:u8 ) ->Result <Self > { +impl From <Bounded <u32 ,2 >>for FalconCoreRevSubversion { +fn from (value:Bounded <u32 ,2 >) ->Self {use FalconCoreRevSubversion ::*; -let sub_version =match value &0b11 { +match value.get () {0 =>Subversion0 ,1 =>Subversion1 ,2 =>Subversion2 ,3 =>Subversion3 , - _ =>return Err (EINVAL ), - }; - -Ok (sub_version) +// SAFETY: `value` comes from a 2-bit `Bounded`, and we just checked all possible +// values. + _ =>unsafe { core::hint::unreachable_unchecked () }, + } } } -/// Security model of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] -/// register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone )] /// Security mode of the Falcon microprocessor. /// /// See `falcon.rst` for more details. +#[derive( Debug , Copy , Clone )] pub (crate )enum FalconSecurityModel {/// Non-Secure: runs unsigned code without privileges. -#[default] None =0 ,/// Light-Secured (LS): Runs signed code with some privileges. /// Entry into this mode is only possible from 'Heavy-secure' mode, which verifies the code's
@@ -138,16 +131,16 @@ pub(crate) enum FalconSecurityModel {/// Also known as High-Secure, Privilege Level 3 or PL3. Heavy = 3, } -impl_from_enum_to_u8! (FalconSecurityModel ); +impl_from_enum_to_bounded! (FalconSecurityModel ,2 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconSecurityModel { +impl TryFrom <Bounded <u32 ,2 >>for FalconSecurityModel {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { +fn try_from (value:Bounded <u32 ,2 >) ->Result <Self > {use FalconSecurityModel ::*; -let sec_model =match value { +let sec_model =match value.get () {0 =>None ,2 =>Light , 3 => Heavy,
@@ -160,24 +153,22 @@ fn try_from(value: u8) -> Result<Self> {/// Signing algorithm for a given firmware, used in the [`crate::regs::NV_PFALCON2_FALCON_MOD_SEL`] /// register. It is passed to the Falcon Boot ROM (BROM) as a parameter. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq )] +#[derive( Debug , Copy , Clone , PartialEq , Eq )] pub (crate )enum FalconModSelAlgo {/// AES. -#[expect(dead_code)] Aes =0 ,/// RSA3K. -#[default] Rsa3k =1 , } -impl_from_enum_to_u8! (FalconModSelAlgo ); +impl_from_enum_to_bounded! (FalconModSelAlgo ,8 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconModSelAlgo { +impl TryFrom <Bounded <u32 ,8 >>for FalconModSelAlgo {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,8 >) ->Result <Self > { +match value.get () { +0 =>Ok (FalconModSelAlgo ::Aes ),1 =>Ok (FalconModSelAlgo ::Rsa3k ), _ =>Err (EINVAL ), }
@@ -185,21 +176,19 @@ fn try_from(value: u8) -> Result<Self> { }/// Valid values for the `size` field of the [`crate::regs::NV_PFALCON_FALCON_DMATRFCMD`] register. -#[repr( u8 )] -#[derive( Debug , Default , Copy , Clone , PartialEq , Eq )] +#[derive( Debug , Copy , Clone , PartialEq , Eq )] pub (crate )enum DmaTrfCmdSize {/// 256 bytes transfer. -#[default] Size256B =0x6 , } -impl_from_enum_to_u8! (DmaTrfCmdSize ); +impl_from_enum_to_bounded! (DmaTrfCmdSize ,3 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for DmaTrfCmdSize { +impl TryFrom <Bounded <u32 ,3 >>for DmaTrfCmdSize {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,3 >) ->Result <Self > { +match value.get () {0x6 =>Ok (Self ::Size256B ), _ =>Err (EINVAL ), }
@@ -207,33 +196,24 @@ fn try_from(value: u8) -> Result<Self> { }/// Currently active core on a dual falcon/riscv (Peregrine) controller. -#[derive( Debug , Clone , Copy , PartialEq , Eq , Default )] +#[derive( Debug , Clone , Copy , PartialEq , Eq )] pub (crate )enum PeregrineCoreSelect {/// Falcon core is active. -#[default] Falcon =0 ,/// RISC-V core is active. Riscv =1 , } +impl_from_enum_to_bounded! (PeregrineCoreSelect ,1 ); -impl From <bool >for PeregrineCoreSelect { -fn from (value:bool ) ->Self { -match value { +impl From <Bounded <u32 ,1 >>for PeregrineCoreSelect { +fn from (value:Bounded <u32 ,1 >) ->Self { +match bool::from (value) {false =>PeregrineCoreSelect ::Falcon ,true =>PeregrineCoreSelect ::Riscv , } } } -impl From <PeregrineCoreSelect >for bool { -fn from (value:PeregrineCoreSelect ) ->Self { -match value { -PeregrineCoreSelect ::Falcon =>false , -PeregrineCoreSelect ::Riscv =>true , - } - } -} -/// Different types of memory present in a falcon core. #[derive( Debug , Clone , Copy , PartialEq , Eq )] pub (crate )enum FalconMem {
@@ -246,10 +226,8 @@ pub(crate) enum FalconMem {/// Defines the Framebuffer Interface (FBIF) aperture type. /// This determines the memory type for external memory access during a DMA transfer, which is /// performed by the Falcon's Framebuffer DMA (FBDMA) engine. See falcon.rst for more details. -#[derive( Debug , Clone , Default )] +#[derive( Debug , Clone )] pub (crate )enum FalconFbifTarget { -/// VRAM. -#[default] /// Local Framebuffer (GPU's VRAM memory). LocalFb =0 ,/// Coherent system memory (System DRAM).
@@ -257,14 +235,14 @@ pub(crate) enum FalconFbifTarget {/// Non-coherent system memory (System DRAM). NoncoherentSysmem = 2, } -impl_from_enum_to_u8! (FalconFbifTarget ); +impl_from_enum_to_bounded! (FalconFbifTarget ,2 );// TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom <u8 >for FalconFbifTarget { +impl TryFrom <Bounded <u32 ,2 >>for FalconFbifTarget {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -let res =match value { +fn try_from (value:Bounded <u32 ,2 >) ->Result <Self > { +let res =match value.get () {0 =>Self ::LocalFb ,1 =>Self ::CoherentSysmem , 2 => Self::NoncoherentSysmem,
@@ -276,34 +254,25 @@ fn try_from(value: u8) -> Result<Self> { }/// Type of memory addresses to use. -#[derive( Debug , Clone , Default )] +#[derive( Debug , Clone )] pub (crate )enum FalconFbifMemType {/// Virtual memory addresses. -#[default] Virtual =0 ,/// Physical memory addresses. Physical =1 , } +impl_from_enum_to_bounded! (FalconFbifMemType ,1 );/// Conversion from a single-bit register field. -impl From <bool >for FalconFbifMemType { -fn from (value:bool ) ->Self { -match value { +impl From <Bounded <u32 ,1 >>for FalconFbifMemType { +fn from (value:Bounded <u32 ,1 >) ->Self { +match bool::from (value) {false =>Self ::Virtual ,true =>Self ::Physical , } } } -impl From <FalconFbifMemType >for bool { -fn from (value:FalconFbifMemType ) ->Self { -match value { -FalconFbifMemType ::Virtual =>false , -FalconFbifMemType ::Physical =>true , - } - } -} -/// Type used to represent the `PFALCON` registers address base for a given falcon engine. pub (crate )struct PFalconBase (());
@@ -385,7 +354,7 @@ pub(crate) fn new(dev: &device::Device, chipset: Chipset) -> Result<Self> {/// Resets DMA-related registers. pub (crate )fn dma_reset (&self, bar: &Bar0 ) { regs::NV_PFALCON_FBIF_CTL ::update (bar, &E ::ID , |v| v.set_allow_phys_no_ctx (true )); - regs::NV_PFALCON_FALCON_DMACTL ::default ().write (bar, &E ::ID ); + regs::NV_PFALCON_FALCON_DMACTL ::zeroed ().write (bar, &E ::ID ); }/// Wait for memory scrubbing to complete.
@@ -431,8 +400,8 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result { self.hal.select_core (self, bar)?; self.reset_wait_mem_scrubbing (bar)?; - regs::NV_PFALCON_FALCON_RM ::default () - .set_value (regs::NV_PMC_BOOT_0 ::read (bar).into ()) + regs::NV_PFALCON_FALCON_RM ::zeroed () + .set_value (regs::NV_PMC_BOOT_0 ::read (bar).as_raw ()) .write (bar, &E ::ID );Ok (())
@@ -495,28 +464,26 @@ fn dma_wr<F: FalconFirmware<Target = E>>(// Set up the base source DMA address. - regs::NV_PFALCON_FALCON_DMATRFBASE ::default () + regs::NV_PFALCON_FALCON_DMATRFBASE ::zeroed ()// CAST: `as u32` is used on purpose since we do want to strip the upper bits, which // will be written to `NV_PFALCON_FALCON_DMATRFBASE1`. .set_base ((dma_start >>8 )as u32 ) .write (bar, &E ::ID ); - regs::NV_PFALCON_FALCON_DMATRFBASE1 ::default () -// CAST: `as u16` is used on purpose since the remaining bits are guaranteed to fit -// within a `u16`. - .set_base ((dma_start >>40 )as u16 ) + regs::NV_PFALCON_FALCON_DMATRFBASE1 ::zeroed () + .try_set_base (dma_start >>40 )? .write (bar, &E ::ID ); -let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::default () +let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::zeroed () .set_size (DmaTrfCmdSize ::Size256B ) .set_imem (target_mem ==FalconMem ::Imem ) - .set_sec (if sec {1 }else {0 }); + .set_sec (sec);for posin (0 ..num_transfers).map (|i| i *DMA_LEN ) {// Perform a transfer of size `DMA_LEN`. - regs::NV_PFALCON_FALCON_DMATRFMOFFS ::default () - .set_offs (load_offsets.dst_start + pos) + regs::NV_PFALCON_FALCON_DMATRFMOFFS ::zeroed () + .try_set_offs (load_offsets.dst_start + pos)? .write (bar, &E ::ID ); - regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::default () + regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::zeroed () .set_offs (src_start + pos) .write (bar, &E ::ID ); cmd.write (bar, &E ::ID );
@@ -549,7 +516,7 @@ pub(crate) fn dma_load<F: FalconFirmware<Target = E>>(&self, bar: &Bar0, fw: &F) self.hal.program_brom (self, bar, &fw.brom_params ())?;// Set `BootVec` to start of non-secure code. - regs::NV_PFALCON_FALCON_BOOTVEC ::default () + regs::NV_PFALCON_FALCON_BOOTVEC ::zeroed () .set_value (fw.boot_addr ()) .write (bar, &E ::ID );
@@ -572,10 +539,10 @@ pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> Result<()> {/// Start the falcon CPU. pub (crate )fn start (&self, bar: &Bar0 ) ->Result <()> {match regs::NV_PFALCON_FALCON_CPUCTL ::read (bar, &E ::ID ).alias_en () { -true => regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::default () +true => regs::NV_PFALCON_FALCON_CPUCTL_ALIAS ::zeroed () .set_startcpu (true ) .write (bar, &E ::ID ), -false => regs::NV_PFALCON_FALCON_CPUCTL ::default () +false => regs::NV_PFALCON_FALCON_CPUCTL ::zeroed () .set_startcpu (true ) .write (bar, &E ::ID ), }
@@ -586,13 +553,13 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> {/// Writes values to the mailbox registers if provided. pub (crate )fn write_mailboxes (&self, bar: &Bar0 , mbox0:Option <u32 >, mbox1:Option <u32 >) {if let Some (mbox0) = mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0 ::default () + regs::NV_PFALCON_FALCON_MAILBOX0 ::zeroed () .set_value (mbox0) .write (bar, &E ::ID ); }if let Some (mbox1) = mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1 ::default () + regs::NV_PFALCON_FALCON_MAILBOX1 ::zeroed () .set_value (mbox1) .write (bar, &E ::ID ); }
@@ -657,7 +624,7 @@ pub(crate) fn is_riscv_active(&self, bar: &Bar0) -> bool {/// Write the application version to the OS register. pub (crate )fn write_os_version (&self, bar: &Bar0 , app_version:u32 ) { - regs::NV_PFALCON_FALCON_OS ::default () + regs::NV_PFALCON_FALCON_OS ::zeroed () .set_value (app_version) .write (bar, &E ::ID ); }
drivers/gpu/nova-core/falcon/gsp.rs +6 -6
@@ -1,7 +1,10 @@// SPDX-License-Identifier: GPL-2.0 use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::RegisterBase ,// + }, prelude::*, time::Delta ,// };
@@ -14,10 +17,7 @@ PFalcon2Base, PFalconBase, // }, - regs::{ - self, - macros::RegisterBase, // - }, + regs, };/// Type specifying the `Gsp` falcon engine. Cannot be instantiated.
@@ -39,7 +39,7 @@ impl Falcon<Gsp> {/// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to /// allow GSP to signal CPU for processing new messages in message queue. pub (crate )fn clear_swgen0_intr (&self, bar: &Bar0 ) { - regs::NV_PFALCON_FALCON_IRQSCLR ::default () + regs::NV_PFALCON_FALCON_IRQSCLR ::zeroed () .set_swgen0 (true ) .write (bar, &Gsp ::ID ); }
drivers/gpu/nova-core/falcon/hal/ga102.rs +8 -7
@@ -26,7 +26,7 @@fn select_core_ga102 <E :FalconEngine >(bar: &Bar0 ) ->Result {let bcr_ctrl = regs::NV_PRISCV_RISCV_BCR_CTRL ::read (bar, &E ::ID );if bcr_ctrl.core_select () !=PeregrineCoreSelect ::Falcon { - regs::NV_PRISCV_RISCV_BCR_CTRL ::default () + regs::NV_PRISCV_RISCV_BCR_CTRL ::zeroed () .set_core_select (PeregrineCoreSelect ::Falcon ) .write (bar, &E ::ID );
@@ -59,7 +59,7 @@ fn signature_reg_fuse_version_ga102(// `ucode_idx` is guaranteed to be in the range [0..15], making the `read` calls provable valid // at build-time. -let reg_fuse_version =if engine_id_mask &0x0001 !=0 { +let reg_fuse_version:u16 =if engine_id_mask &0x0001 !=0 { regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION ::read (bar, ucode_idx).data () }else if engine_id_mask &0x0004 !=0 { regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION ::read (bar, ucode_idx).data ()
@@ -68,23 +68,24 @@ fn signature_reg_fuse_version_ga102( }else {dev_err! (dev,"unexpected engine_id_mask {:#x}" , engine_id_mask);return Err (EINVAL ); - }; + } + .into ();// TODO[NUMM]: replace with `last_set_bit` once it lands. Ok (u16::BITS - reg_fuse_version.leading_zeros ()) }fn program_brom_ga102 <E :FalconEngine >(bar: &Bar0 , params: &FalconBromParams ) ->Result { - regs::NV_PFALCON2_FALCON_BROM_PARAADDR ::default () + regs::NV_PFALCON2_FALCON_BROM_PARAADDR ::zeroed () .set_value (params.pkc_data_offset) .write (bar, &E ::ID ,0 ); - regs::NV_PFALCON2_FALCON_BROM_ENGIDMASK ::default () + regs::NV_PFALCON2_FALCON_BROM_ENGIDMASK ::zeroed () .set_value (u32::from (params.engine_id_mask)) .write (bar, &E ::ID ); - regs::NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID ::default () + regs::NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID ::zeroed () .set_ucode_id (params.ucode_id) .write (bar, &E ::ID ); - regs::NV_PFALCON2_FALCON_MOD_SEL ::default () + regs::NV_PFALCON2_FALCON_MOD_SEL ::zeroed () .set_algo (FalconModSelAlgo ::Rsa3k ) .write (bar, &E ::ID );
drivers/gpu/nova-core/falcon/sec2.rs +6 -7
@@ -1,12 +1,11 @@// SPDX-License-Identifier: GPL-2.0 -use crate ::{ - falcon::{ -FalconEngine , -PFalcon2Base , -PFalconBase ,// - }, - regs::macros::RegisterBase , +use kernel::io::register::RegisterBase ; + +use crate ::falcon::{ +FalconEngine , +PFalcon2Base , +PFalconBase ,// };/// Type specifying the `Sec2` falcon engine. Cannot be instantiated.
drivers/gpu/nova-core/fb/hal/ga100.rs +11 -6
@@ -1,6 +1,9 @@// SPDX-License-Identifier: GPL-2.0 -use kernel::prelude::*; +use kernel::{ + num::Bounded , + prelude::*,// +};use crate ::{ driver::Bar0 ,
@@ -19,12 +22,14 @@ pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) -> u64 { }pub (super )fn write_sysmem_flush_page_ga100 (bar: &Bar0 , addr:u64 ) { - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ::default () -// CAST: `as u32` is used on purpose since the remaining bits are guaranteed to fit within -// a `u32`. - .set_adr_63_40 ((addr >>FLUSH_SYSMEM_ADDR_SHIFT_HI )as u32 ) + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI ::zeroed () + .set_adr_63_40 ( +Bounded ::<u64 ,_ >::from (addr) + .shr ::<FLUSH_SYSMEM_ADDR_SHIFT_HI ,_ >() + .cast (), + ) .write (bar); - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::default () + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::zeroed ()// CAST: `as u32` is used on purpose since we want to strip the upper bits that have been // written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`. .set_adr_39_08 ((addr >>FLUSH_SYSMEM_ADDR_SHIFT )as u32 )
drivers/gpu/nova-core/fb/hal/tu102.rs +1 -1
@@ -21,7 +21,7 @@ pub(super) fn write_sysmem_flush_page_gm107(bar: &Bar0, addr: u64) -> Result { u32::try_from (addr >>FLUSH_SYSMEM_ADDR_SHIFT ) .map_err (|_|EINVAL ) .map (|addr| { - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::default () + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR ::zeroed () .set_adr_39_08 (addr) .write (bar) })
drivers/gpu/nova-core/gpu.rs +15 -16
@@ -4,6 +4,7 @@ device, devres::Devres, fmt, + num::Bounded, pci, prelude::*, sync::Arc, //
@@ -122,24 +123,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { }/// Enum representation of the GPU generation. -/// -/// TODO: remove the `Default` trait implementation, and the `#[default]` -/// attribute, once the register!() macro (which creates Architecture items) no -/// longer requires it for read-only fields. -#[derive(fmt:: Debug , Default , Copy , Clone )] +#[derive(fmt:: Debug , Copy , Clone )] #[repr( u8 )] pub (crate )enum Architecture { -#[default] Turing =0x16 ,Ampere =0x17 ,Ada =0x19 , } -impl TryFrom <u8 >for Architecture { +impl TryFrom <Bounded <u32 ,6 >>for Architecture {type Error =Error ; -fn try_from (value:u8 ) ->Result <Self > { -match value { +fn try_from (value:Bounded <u32 ,6 >) ->Result <Self > { +match u8::from (value) {0x16 =>Ok (Self ::Turing ),0x17 =>Ok (Self ::Ampere ),0x19 =>Ok (Self ::Ada ),
@@ -148,23 +144,26 @@ fn try_from(value: u8) -> Result<Self> { } } -impl From <Architecture >for u8 { +impl From <Architecture >for Bounded <u32 ,6 > {fn from (value:Architecture ) ->Self { -// CAST: `Architecture` is `repr(u8)`, so this cast is always lossless. - valueas u8 +match value { +Architecture ::Turing =>Bounded ::<u8 ,6 >::new ::<0x16 >().cast (), +Architecture ::Ampere =>Bounded ::<u8 ,6 >::new ::<0x17 >().cast (), +Architecture ::Ada =>Bounded ::<u8 ,6 >::new ::<0x19 >().cast (), + } } }pub (crate )struct Revision { - major:u8 , - minor:u8 , + major:Bounded <u8 ,4 >, + minor:Bounded <u8 ,4 >, }impl From <regs::NV_PMC_BOOT_42 >for Revision {fn from (boot0: regs::NV_PMC_BOOT_42 ) ->Self {Self { - major: boot0.major_revision (), - minor: boot0.minor_revision (), + major: boot0.major_revision ().cast (), + minor: boot0.minor_revision ().cast (), } } }
drivers/gpu/nova-core/gsp/cmdq.rs +2 -2
@@ -475,8 +475,8 @@ fn calculate_checksum<T: Iterator<Item = u8>>(it: T) -> u32 {/// Notifies the GSP that we have updated the command queue pointers. fn notify_gsp (bar: &Bar0 ) { - regs::NV_PGSP_QUEUE_HEAD ::default () - .set_address (0 ) + regs::NV_PGSP_QUEUE_HEAD ::zeroed () + .set_address (0u32 ) .write (bar); }
drivers/gpu/nova-core/regs.rs +277 -217
603 lines not on this page · raw message
drivers/gpu/nova-core/regs/macros.rs deleted +0 -739
739 lines not on this page · raw message
Signature · 1 line
2.52.0
Re: [PATCH FOR REFERENCE v4 7/7] gpu: nova-core: use the kernel `register!` macro
Quoted 5 lines · Alexandre Courbot
Replace the nova-core internal
register!macro by the one defined in thekernelcrate and remove our own private implementations.Tested-by Dirk Behme <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>
Quoted 12 lines
--- drivers/gpu/nova-core/falcon.rs | 175 +++---- drivers/gpu/nova-core/falcon/gsp.rs | 12 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 15 +- drivers/gpu/nova-core/falcon/sec2.rs | 13 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 17 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 2 +- drivers/gpu/nova-core/gpu.rs | 31 +- drivers/gpu/nova-core/gsp/cmdq.rs | 4 +- drivers/gpu/nova-core/regs.rs | 494 +++++++++++--------- drivers/gpu/nova-core/regs/macros.rs | 739 ------------------------------ 10 files changed, 397 insertions(+), 1105 deletions(-)
Reading through this, it does look like an across the board improvement in readability in nova-core. Great!
thanks,
Signature · 1 line
John Hubbard