rust: add `bitfield!` macro
Subsystems (9)
Alexandre Courbot
maintainerv3 cover rust: add `bitfield!` macro
This is the continuation of the bitfield! macro which started alongside the register! one before being temporarily integrated into it [1].
Thanks for all the feedback on v2; I believe this version addresses all of it, modulo Eliot's suggestion for more explicit range error messages. Since this is not fundamentally broken, I'd like to address this in a follow-up change to keep the series focused on the macro extraction from register!.
This version is based on today's rust-next, which happens to be 7.1-rc1. If review proves satisfying, I see several possible merge strategies, the one with the least friction being patches 1 and 2 are merged into the rust tree this cycle, followed by patches 3-5 via the I/O and DRM trees during the following cycle. This path would not require any signed tag.
[1] https://lore.kernel.org/all/[email protected]/
---
Changes in v3:
- Split patch 1 into the addition of the bitfield! macro and its use in the io module.
- Mention reserved field names in bitfield!'s doccomment.
- Properly order fields in the KUnit test.
- Add a Kconfig option for building the KUnit tests.
- Document behavior on non-covered bits.
- Document support for signed fields and storage types (TL;DR: not supported).
- Move nova-core's bitfield module deletion into its own patch.
- Link to v2: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (4):
rust: extract bitfield! macro from register!
rust: io: use the bitfield! macro in register!
gpu: nova-core: switch to kernel bitfield macro
gpu: nova-core: remove the driver-local bitfield! macro
Joel Fernandes (1):
rust: bitfield: Add KUnit tests for bitfield
MAINTAINERS | 8 + drivers/gpu/nova-core/bitfield.rs | 329 -------------- drivers/gpu/nova-core/gsp/fw.rs | 11 +- drivers/gpu/nova-core/nova_core.rs | 3 - lib/Kconfig.debug | 12 + rust/kernel/bitfield.rs | 865 +++++++++++++++++++++++++++++++++++++ rust/kernel/io/register.rs | 246 +---------- rust/kernel/lib.rs | 1 + 8 files changed, 894 insertions(+), 581 deletions(-)
---
base-commit: 254f49634ee16a731174d2ae34bc50bd5f45e731
change-id: 20260408-bitfield-6e18254f4fdc
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v3 1/5 rust: extract `bitfield!` macro from `register!`
Extract the bitfield-defining part of the register! macro into an independent macro used to define bitfield types with bounds-checked accessors.
Each 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.
Appropriate documentation is also added, and a MAINTAINERS entry created for the new module.
--- MAINTAINERS | 8 + rust/kernel/bitfield.rs | 546 ++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 555 insertions(+)
MAINTAINERS +8 -0
@@ -23377,6 +23377,14 @@ T: git https://github.com/Rust-for-Linux/linux.git alloc-next F: rust/kernel/alloc.rs F: rust/kernel/alloc/ +RUST [BITFIELD] +M: Alexandre Courbot <[email protected]> +M: Joel Fernandes <[email protected]> +R: Yury Norov <[email protected]> +L: [email protected] +S: Maintained +F: rust/kernel/bitfield.rs + RUST [INTEROP] M: Joel Fernandes <[email protected]> M: Alexandre Courbot <[email protected]>
rust/kernel/bitfield.rs new file +546 -0
546 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -44,6 +44,7 @@pub mod alloc;#[cfg( CONFIG_AUXILIARY_BUS )] pub mod auxiliary; +pub mod bitfield;pub mod bitmap;pub mod bits;#[cfg( CONFIG_BLOCK )]
Signature · 1 line
2.54.0
Gary Guo
reviewerRe: [PATCH v3 1/5] rust: extract `bitfield!` macro from `register!`
rust/kernel/bitfield.rs line 388
Quoted 13 lines · Alexandre Courbot
rust/kernel/bitfield.rs new file +13
-0+// Private field accessors working with the exact `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; + $visconst [<$field:upper _MASK>]: $storage = + ((((1 << $hi) -1 ) <<1 ) +1 ) - ((1 << $lo) -1 ); + $visconst [<$field:upper_SHIFT >]:u32 = $lo; + ); + + ::kernel::macros::paste!( +fn [<__ $field>](self) ->
This and the __with_ methods are missing inline annotations. I'm witnessing these functions showing up in the vmlinux uninlined. (To be fair, this is an existing issue because the register! macro generated onces are also showing up).
Best,
Gary
Quoted 29 lines
rust/kernel/bitfield.rs new file +29
-0+ ::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.inner << ALIGN_TOP + ); + val.shr::<ALIGN_BOTTOM, { $hi + 1 - $lo } >() + } + + const fn [<__with_ $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.get() << SHIFT; + self.inner = (self.inner & !MASK) | value; + + self + } + ); + };
Alexandre Courbot
maintainerPATCH v3 2/5 rust: bitfield: Add KUnit tests for bitfield
In reply to Alexandre CourbotFrom: Joel Fernandes <[email protected]>
Add KUNIT tests to make sure the macro is working correctly. The unit tests are put behind the new RUST_KERNEL_BITFIELD_KUNIT_TEST Kconfig option.
--- lib/Kconfig.debug | 12 ++ rust/kernel/bitfield.rs | 319 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+)
lib/Kconfig.debug +12 -0
@@ -3608,6 +3608,18 @@ config RUST_KERNEL_DOCTESTS If unsure, say N. +config RUST_KERNEL_BITFIELD_KUNIT_TEST + bool "KUnit tests for the Rust `bitfield!` macro" if !KUNIT_ALL_TESTS + depends on RUST && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds the KUnit tests for the Rust `bitfield!` macro. + + For more information on KUnit and unit tests in general please refer + to the KUnit documentation in Documentation/dev-tools/kunit/. + + If unsure, say N. + config RUST_INLINE_HELPERS bool "Inline C helpers into Rust code (EXPERIMENTAL)" depends on RUST && RUSTC_CLANG_LLVM_COMPATIBLE
rust/kernel/bitfield.rs +319 -0
322 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v3 2/5] rust: bitfield: Add KUnit tests for bitfield
Quoted 20 lines · Alexandre Courbot
From: Joel Fernandes <[email protected]>
Add KUNIT tests to make sure the macro is working correctly. The unit tests are put behind the new
RUST_KERNEL_BITFIELD_KUNIT_TESTKconfigoption.Signed-off-by Joel Fernandes <[email protected]>Co-developed-by Alexandre Courbot <[email protected]>Signed-off-by Alexandre Courbot <[email protected]>Reviewed-by Eliot Courtney <[email protected]>--- lib/Kconfig.debug | 12 ++ rust/kernel/bitfield.rs | 319 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+)lib/Kconfig.debug +0
-0
lib/Kconfig.debug config RUST_KERNEL_DOCTESTS · line 3611
Quoted 4 lines
lib/Kconfig.debug +1
-0@@ -3608,6 +3608,18 @@ config RUST_KERNEL_DOCTESTS If unsure, say N. +config RUST_KERNEL_BITFIELD_KUNIT_TEST
Those KUnit tests are all kernel unit tests. Maybe just RUST_BITFIELD_KUNIT_TEST?
lib/Kconfig.debug config RUST_KERNEL_DOCTESTS · line 3619
Quoted 8 lines
lib/Kconfig.debug +8
-0+ bool "KUnit tests for the Rust `bitfield!` macro" if !KUNIT_ALL_TESTS + depends on RUST && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds the KUnit tests for the Rust `bitfield!` macro. + + For more information on KUnit and unit tests in general please refer + to the KUnit documentation in Documentation/dev-tools/kunit/.
This sentence travels from config to config, adding no value. Maybe drop it?
lib/Kconfig.debug config RUST_KERNEL_DOCTESTS · line 3622
Quoted 2 lines
lib/Kconfig.debug +2
-0+ If unsure, say N. +
Can you build the series on top of my "rust: add Kconfig.test" series, and add this config to the rust/kernel/Kconfig.test?
It would be better, because the series creates a "Rust KUnit tests" menu, so all the tests will be in the same place in menuconfig.
Thanks,
Yury
Alexandre Courbot
maintainerPATCH v3 3/5 rust: io: use the `bitfield!` macro in `register!`
In reply to Alexandre CourbotReplace the local bitfield rules by the equivalent invocation of the bitfield! macro.
No functional change should be introduced as the bitfield! macro has been extracted from the rules of register!.
--- rust/kernel/io/register.rs | 246 +-------------------------------------------- 1 file changed, 2 insertions(+), 244 deletions(-)
rust/kernel/io/register.rs +2 -244
@@ -956,11 +956,10 @@ macro_rules! register { ( @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } ) => { - $crate::register!(@bitfield_core + $crate::bitfield!(#[allow(non_camel_case_types)] - $(#[$attr] )* $vis $name $storage + $(#[$attr] )* $visstruct $name($storage) { $($fields)* } ); - $crate::register!(@bitfield_fields $vis $name $storage { $($fields)* }); };// Implementations shared by all registers types.
@@ -1016,245 +1015,4 @@ impl $crate::io::register::RegisterArray for $name {impl $crate::io::register::RelativeRegisterArray for $name {} }; - -// 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)] - $vis struct $name { - inner: $storage, - } - - #[allow(dead_code)] - impl $name { - /// Creates a bitfield from a raw value. - #[inline(always)] - $vis const fn from_raw(value: $storage) -> Self { - Self{ inner: value } - } - - /// Turns this bitfield into its raw value. - /// - /// This is similar to the [`From`] implementation, but is shorter to invoke in - /// most cases. - #[inline(always)] - $vis const fn into_raw(self) -> $storage { - self.inner - } - } - - // SAFETY: `$storage` is `Zeroable` and `$name` is transparent. - unsafe impl ::pin_init::Zeroable for $name {} - - impl ::core::convert::From<$name> for $storage { - #[inline(always)] - fn from(val: $name) -> $storage { - val.into_raw() - } - } - - impl ::core::convert::From<$storage> for $name { - #[inline(always)] - 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 { - $( - $crate::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); - $crate::register!( - @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field - $(?=> $try_into_type)? - $(=> $into_type)? - ); - )* - } - - $crate::register!(@debug $name { $($field;)* }); - }; - - // Private field accessors working with the exact `Bounded` type for the field. - ( - @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident - ) => { - ::kernel::macros::paste!( - $vis const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi; - $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.inner << ALIGN_TOP - ); - val.shr::<ALIGN_BOTTOM, { $hi + 1 - $lo } >() - } - - const fn [<__with_ $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.get() << SHIFT; - self.inner = (self.inner & !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 [<with_ $field>](self, value: $into_type) -> Self - { - self.[<__with_ $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 [<with_ $field>](self, value: $try_into_type) -> Self - { - self.[<__with_ $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_const_ $field>]<const VALUE: $storage>(self) -> Self { - self.[<__with_ $field>]( - ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::new::<VALUE>() - ) - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the given `value`."] - #[inline(always)] - $vis fn [<with_ $field>]<T>( - self, - value: T, - ) -> Self - where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>>, - { - self.[<__with_ $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_with_ $field>]<T>( - self, - value: T, - ) -> ::kernel::error::Result<Self> - where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $lo }>, - { - Ok( - self.[<__with_ $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.inner)) - $( - .field(stringify!($field), &self.$field()) - )* - .finish() - } - } - }; }
Signature · 1 line
2.54.0
Re: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
Quoted 7 lines · Alexandre Courbot
Replace the local bitfield rules by the equivalent invocation of the
bitfield!macro.No functional change should be introduced as the
bitfield!macro has been extracted from the rules ofregister!.Signed-off-by Alexandre Courbot <[email protected]>
If it comes to another round, maybe split switching to a bitfields and getting rid of the bitfield_core? For maintainability reasons.
Quoted 271 lines
--- rust/kernel/io/register.rs | 246 +-------------------------------------------- 1 file changed, 2 insertions(+), 244 deletions(-)rust/kernel/io/register.rs +2
-244@@ -956,11 +956,10 @@ macro_rules! register { ( @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } ) => { - $crate::register!(@bitfield_core + $crate::bitfield!(#[allow(non_camel_case_types)] - $(#[$attr] )* $vis $name $storage + $(#[$attr] )* $visstruct $name($storage) { $($fields)* } ); - $crate::register!(@bitfield_fields $vis $name $storage { $($fields)* }); };// Implementations shared by all registers types. @@ -1016,245 +1015,4 @@ impl $crate::io::register::RegisterArray for $name {impl $crate::io::register::RelativeRegisterArray for $name {} }; - -// 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)] - $vis struct $name { - inner: $storage, - } - - #[allow(dead_code)] - impl $name { - /// Creates a bitfield from a raw value. - #[inline(always)] - $vis const fn from_raw(value: $storage) -> Self { - Self{ inner: value } - } - - /// Turns this bitfield into its raw value. - /// - /// This is similar to the [`From`] implementation, but is shorter to invoke in - /// most cases. - #[inline(always)] - $vis const fn into_raw(self) -> $storage { - self.inner - } - } - - // SAFETY: `$storage` is `Zeroable` and `$name` is transparent. - unsafe impl ::pin_init::Zeroable for $name {} - - impl ::core::convert::From<$name> for $storage { - #[inline(always)] - fn from(val: $name) -> $storage { - val.into_raw() - } - } - - impl ::core::convert::From<$storage> for $name { - #[inline(always)] - 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 { - $( - $crate::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); - $crate::register!( - @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field - $(?=> $try_into_type)? - $(=> $into_type)? - ); - )* - } - - $crate::register!(@debug $name { $($field;)* }); - }; - - // Private field accessors working with the exact `Bounded` type for the field. - ( - @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident - ) => { - ::kernel::macros::paste!( - $vis const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi; - $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.inner << ALIGN_TOP - ); - val.shr::<ALIGN_BOTTOM, { $hi + 1 - $lo } >() - } - - const fn [<__with_ $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.get() << SHIFT; - self.inner = (self.inner & !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 [<with_ $field>](self, value: $into_type) -> Self - { - self.[<__with_ $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 [<with_ $field>](self, value: $try_into_type) -> Self - { - self.[<__with_ $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_const_ $field>]<const VALUE: $storage>(self) -> Self { - self.[<__with_ $field>]( - ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::new::<VALUE>() - ) - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the given `value`."] - #[inline(always)] - $vis fn [<with_ $field>]<T>( - self, - value: T, - ) -> Self - where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>>, - { - self.[<__with_ $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_with_ $field>]<T>( - self, - value: T, - ) -> ::kernel::error::Result<Self> - where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $lo }>, - { - Ok( - self.[<__with_ $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.inner)) - $( - .field(stringify!($field), &self.$field()) - )* - .finish() - } - } - }; }Signature · 2 lines
-- 2.54.0
Re: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
Quoted 7 lines · Yury Norov
Quoted 6 lines · Alexandre Courbot
Replace the local bitfield rules by the equivalent invocation of the
bitfield!macro.No functional change should be introduced as the
bitfield!macro has been extracted from the rules ofregister!.
Quoted 6 lines
Quoted 1 line
Signed-off-by Alexandre Courbot <[email protected]>Acked-by Yury Norov <[email protected]>If it comes to another round, maybe split switching to a bitfields and getting rid of the
bitfield_core? For maintainability reasons.
Moreover, you do the same for the other piece of bitfields in #4 and 5.
Danilo Krummrich
maintainerRe: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
In reply to Yury NorovQuoted 2 lines · Yury Norov
If it comes to another round, maybe split switching to a bitfields and getting rid of the
bitfield_core? For maintainability reasons.
I'm happy to take it as a single patch -- the deleted rules are dead code the moment the switch happens, and the code is local to the same macro, so the intermediate state doesn't seem to add any value, or structure in terms of touching different components etc.
Did you have anything specific in mind when you mention maintainability reasons?
Re: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
Quoted 10 lines · Danilo Krummrich
Quoted 2 lines · Yury Norov
If it comes to another round, maybe split switching to a bitfields and getting rid of the
bitfield_core? For maintainability reasons.I'm happy to take it as a single patch -- the deleted rules are dead code the moment the switch happens, and the code is local to the same macro, so the intermediate state doesn't seem to add any value, or structure in terms of touching different components etc.
Did you have anything specific in mind when you mention maintainability reasons?
I only mean that if there will be weird regression found in the new implementation, it's better to be able to revert just a single patch to restore the original code with no side effects.
Just a suggestion. If you're happy with this, I'm happy as well.
Danilo Krummrich
maintainerRe: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
Quoted 10 lines · Yury Norov
Quoted 9 lines · Danilo Krummrich
Quoted 2 lines · Yury Norov
If it comes to another round, maybe split switching to a bitfields and getting rid of the
bitfield_core? For maintainability reasons.I'm happy to take it as a single patch -- the deleted rules are dead code the moment the switch happens, and the code is local to the same macro, so the intermediate state doesn't seem to add any value, or structure in terms of touching different components etc.
Quoted 5 lines
Quoted 1 line
Did you have anything specific in mind when you mention maintainability reasons?
I only mean that if there will be weird regression found in the new implementation, it's better to be able to revert just a single patch to restore the original code with no side effects.
Indeed, but by splitting it up that wouldn't be possible anymore, no?
Am I missing something?
Re: [PATCH v3 3/5] rust: io: use the `bitfield!` macro in `register!`
Quoted 13 lines · Danilo Krummrich
Quoted 12 lines · Yury Norov
Quoted 10 lines · Danilo Krummrich
Quoted 2 lines · Yury Norov
If it comes to another round, maybe split switching to a bitfields and getting rid of the
bitfield_core? For maintainability reasons.I'm happy to take it as a single patch -- the deleted rules are dead code the moment the switch happens, and the code is local to the same macro, so the intermediate state doesn't seem to add any value, or structure in terms of touching different components etc.
Did you have anything specific in mind when you mention maintainability reasons?
Quoted 7 lines
Quoted 3 lines
I only mean that if there will be weird regression found in the new implementation, it's better to be able to revert just a single patch to restore the original code with no side effects.
Indeed, but by splitting it up that wouldn't be possible anymore, no?
Am I missing something?
The thing is that you most likely will not be able to revert the patch cleanly - because the existing code evolves. The non-existing code doesn't evolve. So unless it'is moved to another file, or something like that, the revert is simpler.
Alexandre Courbot
maintainerPATCH v3 4/5 gpu: nova-core: switch to kernel bitfield macro
In reply to Alexandre CourbotReplace uses of the Nova-internal bitfield! macro with the kernel one.
--- drivers/gpu/nova-core/gsp/fw.rs | 11 ++++++----- drivers/gpu/nova-core/nova_core.rs | 3 --- 2 files changed, 6 insertions(+), 8 deletions(-)
drivers/gpu/nova-core/gsp/fw.rs +6 -5
@@ -9,6 +9,7 @@use core::ops::Range ;use kernel::{ + bitfield, dma::Coherent , prelude::*, ptr::{
@@ -728,8 +729,8 @@ unsafe impl AsBytes for MsgqRxHeader {}bitfield! {struct MsgHeaderVersion (u32 ) { -31 :24 majoras u8 ; -23 :16 minoras u8 ; +31 :24 major; +23 :16 minor; } }
@@ -738,9 +739,9 @@ impl MsgHeaderVersion {const MINOR_TOT :u8 =0 ;fn new () ->Self { -Self ::default () - .set_major (Self ::MAJOR_TOT ) - .set_minor (Self ::MINOR_TOT ) +Self ::zeroed () + .with_major (Self ::MAJOR_TOT ) + .with_minor (Self ::MINOR_TOT ) } }
drivers/gpu/nova-core/nova_core.rs +0 -3
@@ -10,9 +10,6 @@ InPlaceModule, // }; -#[macro_use] -mod bitfield; -mod driver;mod falcon;mod fb;
Signature · 1 line
2.54.0
Alexandre Courbot
maintainerPATCH v3 5/5 gpu: nova-core: remove the driver-local `bitfield!` macro
In reply to Alexandre CourbotThis module is now orphaned code replaced by a kernel-global implementation, so remove it.
--- drivers/gpu/nova-core/bitfield.rs | 329 -------------------------------------- 1 file changed, 329 deletions(-)
drivers/gpu/nova-core/bitfield.rs deleted +0 -329
@@ -1,329 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Bitfield library for Rust structures -//! -//! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro. - -/// Defines a struct with accessors to access bits within an inner unsigned integer. -/// -/// # Syntax -/// -/// ```rust -/// use nova_core::bitfield; -/// -/// #[derive(Debug, Clone, Copy, Default)] -/// enum Mode { -/// #[default] -/// Low = 0, -/// High = 1, -/// Auto = 2, -/// } -/// -/// impl TryFrom<u8> for Mode { -/// type Error = u8; -/// fn try_from(value: u8) -> Result<Self, Self::Error> { -/// match value { -/// 0 => Ok(Mode::Low), -/// 1 => Ok(Mode::High), -/// 2 => Ok(Mode::Auto), -/// _ => Err(value), -/// } -/// } -/// } -/// -/// impl From<Mode> for u8 { -/// fn from(mode: Mode) -> u8 { -/// mode as u8 -/// } -/// } -/// -/// #[derive(Debug, Clone, Copy, Default)] -/// enum State { -/// #[default] -/// Inactive = 0, -/// Active = 1, -/// } -/// -/// impl From<bool> for State { -/// fn from(value: bool) -> Self { -/// if value { State::Active } else { State::Inactive } -/// } -/// } -/// -/// impl From<State> for bool { -/// fn from(state: State) -> bool { -/// match state { -/// State::Inactive => false, -/// State::Active => true, -/// } -/// } -/// } -/// -/// bitfield! { -/// pub struct ControlReg(u32) { -/// 7:7 state as bool => State; -/// 3:0 mode as u8 ?=> Mode; -/// } -/// } -/// ``` -/// -/// This generates a struct with: -/// - Field accessors: `mode()`, `state()`, etc. -/// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern). -/// Note that the compiler will error out if the size of the setter's arg exceeds the -/// struct's storage size. -/// - Debug and Default implementations. -/// -/// Note: Field accessors and setters inherit the same visibility as the struct itself. -/// In the example above, both `mode()` and `set_mode()` methods will be `pub`. -/// -/// Fields are defined as follows: -/// -/// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or -/// `bool`. Note that `bool` fields must have a range of 1 bit. -/// - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns -/// the result. -/// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation -/// and returns the result. This is useful with fields for which not all values are valid. -macro_rules! bitfield { -// Main entry point - defines the bitfield struct with fields - ($vis:visstruct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => { -bitfield! (@core $vis $name $storage $(, $comment)? { $($fields)* }); - }; - -// All rules below are helpers. - -// Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, -// `Default`, and conversion to the value type) and field accessor methods. - (@core $vis:vis $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => { - $( -#[doc=$comment] - )? -#[repr(transparent)] -#[derive( Clone , Copy )] - $visstruct $name($storage); - -impl ::core::convert::From <$name>for $storage { -fn from (val: $name) -> $storage { - val.0 - } - } - -bitfield! (@fields_dispatcher $vis $name $storage { $($fields)* }); - }; - -// Captures the fields and passes them to all the implementers that require field information. -// -// Used to simplify the matching rules for implementers, so they don't need to match the entire -// complex fields rule even though they only make use of part of it. - (@fields_dispatcher $vis:vis $name:ident $storage:ty { - $($hi:tt:$lo:tt $field:identas $type:tt - $(?=> $try_into_type:ty)? - $(=> $into_type:ty)? - $(, $comment:literal)? - ; - )* - } - ) => { -bitfield! (@field_accessors $vis $name $storage { - $( - $hi:$lo $fieldas $type - $(?=> $try_into_type)? - $(=> $into_type)? - $(, $comment)? - ; - )* - }); -bitfield! (@debug $name { $($field;)* }); -bitfield! (@default $name { $($field;)* }); - }; - -// Defines all the field getter/setter methods for `$name`. - ( - @field_accessors $vis:vis $name:ident $storage:ty { - $($hi:tt:$lo:tt $field:identas $type:tt - $(?=> $try_into_type:ty)? - $(=> $into_type:ty)? - $(, $comment:literal)? - ; - )* - } - ) => { - $( -bitfield! (@check_field_bounds $hi:$lo $fieldas $type ); - )* - -#[allow(dead_code)] -impl $name { - $( -bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas $type - $(?=> $try_into_type)? - $(=> $into_type)? - $(, $comment)? - ; - ); - )* - } - }; - -// Boolean fields must have `$hi == $lo`. - (@check_field_bounds $hi:tt:$lo:tt $field:identas bool ) => { -#[allow(clippy::eq_op)] -const _: () = { - ::kernel::build_assert!( - $hi == $lo, -concat! ("boolean field `" ,stringify! ($field),"` covers more than one bit" ) - ); - }; - }; - -// Non-boolean fields must have `$hi >= $lo`. - (@check_field_bounds $hi:tt:$lo:tt $field:identas $type:tt) => { -#[allow(clippy::eq_op)] -const _: () = { - ::kernel::build_assert!( - $hi >= $lo, -concat! ("field `" ,stringify! ($field),"`'s MSB is smaller than its LSB" ) - ); - }; - }; - -// Catches fields defined as `bool` and convert them into a boolean value. - ( - @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:identas bool - => $into_type:ty $(, $comment:literal)?; - ) => { -bitfield! ( - @leaf_accessor $vis $name $storage, $hi:$lo $field - { |f| <$into_type>::from (f !=0 ) } -bool $into_type => $into_type $(, $comment)?; - ); - }; - -// Shortcut for fields defined as `bool` without the `=>` syntax. - ( - @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:identas bool - $(, $comment:literal)?; - ) => { -bitfield! ( - @field_accessor $vis $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?; - ); - }; - -// Catches the `?=>` syntax for non-boolean fields. - ( - @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:identas $type:tt - ?=> $try_into_type:ty $(, $comment:literal)?; - ) => { -bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field - { |f| <$try_into_type>::try_from (fas $type ) } $type $try_into_type => - ::core::result::Result < - $try_into_type, - <$try_into_typeas ::core::convert::TryFrom <$type >>::Error - > - $(, $comment)?;); - }; - -// Catches the `=>` syntax for non-boolean fields. - ( - @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:identas $type:tt - => $into_type:ty $(, $comment:literal)?; - ) => { -bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field - { |f| <$into_type>::from (fas $type ) } $type $into_type => $into_type $(, $comment)?;); - }; - -// Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax. - ( - @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:identas $type:tt - $(, $comment:literal)?; - ) => { -bitfield! ( - @field_accessor $vis $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?; - ); - }; - -// Generates the accessor methods for a single field. - ( - @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident - { $process:expr } $prim_type:tt $to_type:ty => $res_type:ty $(, $comment:literal)?; - ) => { - ::kernel::macros::paste!( -const [<$field:upper_RANGE >]: ::core::ops::RangeInclusive <u8 > = $lo..=$hi; -const [<$field:upper _MASK>]: $storage = { -// Generate mask for shifting -match ::core::mem::size_of ::<$storage>() { -1 => ::kernel::bits::genmask_u8 ($lo..=$hi)as $storage, -2 => ::kernel::bits::genmask_u16 ($lo..=$hi)as $storage, -4 => ::kernel::bits::genmask_u32 ($lo..=$hi)as $storage, -8 => ::kernel::bits::genmask_u64 ($lo..=$hi)as $storage, - _ => ::kernel::build_error!("Unsupported storage type size" ) - } - }; -const [<$field:upper_SHIFT >]:u32 = $lo; - ); - - $( -#[doc= "Returns the value of this field:" ] -#[doc=$comment] - )? -#[inline(always)] - $visfn $field(self) -> $res_type { - ::kernel::macros::paste!( -const MASK : $storage = $name::[<$field:upper _MASK>]; -const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; - ); -let field = ((self.0 &MASK ) >>SHIFT ); - - $process(field) - } - - ::kernel::macros::paste!( - $( -#[doc= "Sets the value of this field:" ] -#[doc=$comment] - )? -#[inline(always)] - $visfn [<set_ $field>](mut self, value: $to_type) ->Self { -const MASK : $storage = $name::[<$field:upper _MASK>]; -const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; -let value = ($storage::from ($prim_type::from (value)) <<SHIFT ) &MASK ; - self.0 = (self.0 & !MASK ) | value; - - self - } - ); - }; - -// Generates the `Debug` implementation for `$name`. - (@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 () - } - } - }; - -// Generates the `Default` implementation for `$name`. - (@default $name:ident { $($field:ident;)* }) => { -/// Returns a value for the bitfield where all fields are set to their default value. -impl ::core::default ::Default for $name { -fn default () ->Self { -let value =Self (Default ::default ()); - - ::kernel::macros::paste!( - $( -let value = value.[<set_ $field>](Default ::default ()); - )* - ); - - value - } - } - }; -}
Signature · 1 line
2.54.0