Introduce bitfield and move register macro to rust/kernel/
Subsystems (8)
v5 cover Introduce bitfield and move register macro to rust/kernel/
Hello!
These patches extract and enhance the bitfield support in the register macro in nova to define Rust structures with bitfields. It then moves out the bitfield support into the kenrel crate and further enhances it. This is extremely useful as it allows clean Rust structure definitions without requiring explicit masks and shifts.
See [1] example code using it.
v4 of the patches are at:
https://lore.kernel.org/all/[email protected]/
v3 of the patches are at:
https://lore.kernel.org/all/[email protected]/
v2 of the patches are at:
https://lore.kernel.org/all/[email protected]/
v1 of the patches are at:
https://lore.kernel.org/all/[email protected]/
v4->v5:
* Added 2 hardening patches to catch the misuse of the API.
* Limited access to the inner value of the struct.
* Fixed kunit tests
* Addressed feedback from lots of folks (Miguel, Alexandre, Yury, Danilo).
* Added Alex tags to most patches.
v3->v4:
* Rebased on -next.
* Added more test cases.
* Added support for fields larger than the struct
(ex, using 'as u32' for a u8 struct.)
v2->v3:
* Renamed bitstruct to bitfield.
* Various suggestions to improve code (Alex, Yury, Miguel).
* Added reviewed-by tags from Elle Rhumsaa.
* Added KUNIT tests including tests for overlap.
* Added F: maintainers file entry for new files under BITOPS.
v1->v2:
* Use build_assert in bitstruct
* Split move and enhance patches for easier review
* Move out of Nova into kernel crate for other drivers like Tyr which will use.
* Miscellaneous cosmetic improvements.
Joel Fernandes (9):
nova-core: bitfield: Move bitfield-specific code from register! into
new macro
nova-core: bitfield: Add support for different storage widths
nova-core: bitfield: Add support for custom visiblity
rust: Move register and bitfield macros out of Nova
rust: bitfield: Add a new() constructor and raw() accessor
rust: bitfield: Add KUNIT tests for bitfield
rust: bitfield: Use 'as' operator for setter type conversion
rust: bitfield: Add hardening for out of bounds access
rust: bitfield: Add hardening for undefined bits
MAINTAINERS | 7 + drivers/gpu/nova-core/falcon.rs | 2 +- drivers/gpu/nova-core/falcon/gsp.rs | 4 +- drivers/gpu/nova-core/falcon/sec2.rs | 2 +- drivers/gpu/nova-core/regs.rs | 6 +- rust/kernel/bitfield.rs | 804 ++++++++++++++++++ rust/kernel/io.rs | 1 + .../macros.rs => rust/kernel/io/register.rs | 317 +------ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 9 + 10 files changed, 870 insertions(+), 283 deletions(-) create mode 100644 rust/kernel/bitfield.rs rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (72%)
Signature · 1 line
2.34.1
PATCH v5 1/9 nova-core: bitfield: Move bitfield-specific code from register! into new macro
The bitfield-specific into new macro. This will be used to define structs with bitfields, similar to C language.
--- drivers/gpu/nova-core/bitfield.rs | 315 +++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 3 + drivers/gpu/nova-core/regs/macros.rs | 259 +--------------------- 3 files changed, 328 insertions(+), 249 deletions(-) create mode 100644 drivers/gpu/nova-core/bitfield.rs
drivers/gpu/nova-core/bitfield.rs new file +315 -0
@@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Bitfield library for Rust structures +//! +//! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro. +//! +//! # 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 u32 { +//! fn from(mode: Mode) -> u32 { +//! mode as u32 +//! } +//! } +//! +//! #[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 u32 { +//! fn from(state: State) -> u32 { +//! state as u32 +//! } +//! } +//! +//! bitfield! { +//! struct ControlReg { +//! 3:0 mode as u8 ?=> Mode; +//! 7:7 state as bool => State; +//! } +//! } +//! ``` +//! +//! This generates a struct with: +//! - Field accessors: `mode()`, `state()`, etc. +//! - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern). +//! - Debug and Default implementations. +//! +//! 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 + (struct $name:ident $(, $comment:literal)? { $($fields:tt)* }) => { +bitfield! (@core $name $(, $comment)? { $($fields)* }); + }; + +// All rules below are helpers. + +// Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, +// `Default`, `BitOr`, and conversion to the value type) and field accessor methods. + (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => { + $( +#[doc=$comment] + )? +#[repr(transparent)] +#[derive( Clone , Copy )] +pub (crate )struct $name(u32 ); + +impl ::core::ops::BitOr for $name { +type Output =Self ; + +fn bitor (self, rhs:Self ) ->Self ::Output { +Self (self.0 | rhs.0 ) + } + } + +impl ::core::convert::From <$name>for u32 { +fn from (val: $name) ->u32 { + val.0 + } + } + +bitfield! (@fields_dispatcher $name { $($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 $name:ident { + $($hi:tt:$lo:tt $field:identas $type:tt + $(?=> $try_into_type:ty)? + $(=> $into_type:ty)? + $(, $comment:literal)? + ; + )* + } + ) => { +bitfield! (@field_accessors $name { + $( + $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 $name:ident { + $($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 $name $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 $name:ident $hi:tt:$lo:tt $field:identas bool => $into_type:ty + $(, $comment:literal)?; + ) => { +bitfield! ( + @leaf_accessor $name $hi:$lo $field + { |f| <$into_type>::from (if f !=0 {true }else {false }) } + $into_type => $into_type $(, $comment)?; + ); + }; + +// Shortcut for fields defined as `bool` without the `=>` syntax. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:identas bool $(, $comment:literal)?; + ) => { +bitfield! (@field_accessor $name $hi:$lo $fieldas bool =>bool $(, $comment)?;); + }; + +// Catches the `?=>` syntax for non-boolean fields. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:identas $type:tt ?=> $try_into_type:ty + $(, $comment:literal)?; + ) => { +bitfield! (@leaf_accessor $name $hi:$lo $field + { |f| <$try_into_type>::try_from (fas $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 $name:ident $hi:tt:$lo:tt $field:identas $type:tt => $into_type:ty + $(, $comment:literal)?; + ) => { +bitfield! (@leaf_accessor $name $hi:$lo $field + { |f| <$into_type>::from (fas $type ) } $into_type => $into_type $(, $comment)?;); + }; + +// Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:identas $type:tt + $(, $comment:literal)?; + ) => { +bitfield! (@field_accessor $name $hi:$lo $fieldas $type => $type $(, $comment)?;); + }; + +// Generates the accessor methods for a single field. + ( + @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident + { $process:expr } $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>]:u32 = ((((1 << $hi) -1 ) <<1 ) +1 ) - ((1 << $lo) -1 ); +const [<$field:upper_SHIFT >]:u32 =Self ::[<$field:upper _MASK>].trailing_zeros (); + ); + + $( +#[doc= "Returns the value of this field:" ] +#[doc=$comment] + )? +#[inline(always)] +pub (crate )fn $field(self) -> $res_type { + ::kernel::macros::paste!( +const MASK :u32 = $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)] +pub (crate )fn [<set_ $field>](mut self, value: $to_type) ->Self { +const MASK :u32 = $name::[<$field:upper _MASK>]; +const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; +let value = (u32 ::from (value) <<SHIFT ) &MASK ; + self.0 = (self.0 & !MASK ) | value; + + self + } + ); + }; + +// Generates the `Debug` implementation for `$name`. + (@debug $name:ident { $($field:ident;)* }) => { +impl ::core::fmt::Debug for $name { +fn fmt (&self, f: &mut ::core::fmt::Formatter <'_>) -> ::core::fmt::Result { + f.debug_struct (stringify! ($name)) + .field ("<raw>" , &format_args! ("{:#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 { +#[allow(unused_mut)] +let mut value =Self (Default ::default ()); + + ::kernel::macros::paste!( + $( + value.[<set_ $field>](Default ::default ()); + )* + ); + + value + } + } + }; +}
drivers/gpu/nova-core/nova_core.rs +3 -0
@@ -2,6 +2,9 @@//! Nova Core GPU Driver +#[macro_use] +mod bitfield; +mod dma;mod driver;mod falcon;
drivers/gpu/nova-core/regs/macros.rs +10 -249
319 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v5 2/9 nova-core: bitfield: Add support for different storage widths
In reply to Joel FernandesPreviously, bitfields were hardcoded to use u32 as the underlying storage type. Add support for different storage types (u8, u16, u32, u64) to the bitfield macro.
New syntax is: struct Name: <type ex., u32> { ... }
--- drivers/gpu/nova-core/bitfield.rs | 210 ++++++++++++++------------- drivers/gpu/nova-core/regs/macros.rs | 16 +- 2 files changed, 119 insertions(+), 107 deletions(-)
drivers/gpu/nova-core/bitfield.rs +111 -99
@@ -3,96 +3,99 @@//! Bitfield library for Rust structures //! //! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro. -//! -//! # 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 u32 { -//! fn from(mode: Mode) -> u32 { -//! mode as u32 -//! } -//! } -//! -//! #[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 u32 { -//! fn from(state: State) -> u32 { -//! state as u32 -//! } -//! } -//! -//! bitfield! { -//! struct ControlReg { -//! 3:0 mode as u8 ?=> Mode; -//! 7:7 state as bool => State; -//! } -//! } -//! ``` -//! -//! This generates a struct with: -//! - Field accessors: `mode()`, `state()`, etc. -//! - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern). -//! - Debug and Default implementations. -//! -//! 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. -//! + +/// 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 u32 { +/// fn from(mode: Mode) -> u32 { +/// mode as u32 +/// } +/// } +/// +/// #[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 u32 { +/// fn from(state: State) -> u32 { +/// state as u32 +/// } +/// } +/// +/// bitfield! { +/// struct ControlReg(u32) { +/// 3:0 mode as u8 ?=> Mode; +/// 7:7 state as bool => State; +/// } +/// } +/// ``` +/// +/// 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. +/// +/// 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 - (struct $name:ident $(, $comment:literal)? { $($fields:tt)* }) => { -bitfield! (@core $name $(, $comment)? { $($fields)* }); + (struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => { +bitfield! (@core $name $storage $(, $comment)? { $($fields)* }); };// All rules below are helpers. // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, // `Default`, `BitOr`, and conversion to the value type) and field accessor methods. - (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => { + (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => { $(#[doc=$comment] )?#[repr(transparent)] #[derive( Clone , Copy )] -pub (crate )struct $name(u32 ); +pub (crate )struct $name($storage);impl ::core::ops::BitOr for $name {type Output =Self ;
@@ -102,20 +105,20 @@ fn bitor(self, rhs: Self) -> Self::Output { } } -impl ::core::convert::From <$name>for u32 { -fn from (val: $name) ->u32 { +impl ::core::convert::From <$name>for $storage { +fn from (val: $name) -> $storage { val.0 } } -bitfield! (@fields_dispatcher $name { $($fields)* }); +bitfield! (@fields_dispatcher $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 $name:ident { + (@fields_dispatcher $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=> $try_into_type:ty)? $(=> $into_type:ty)?
@@ -124,7 +127,7 @@ fn from(val: $name) -> u32 { )* } ) => { - bitfield!(@field_accessors $name { + bitfield!(@field_accessors $name $storage { $( $hi:$lo $field as $type $(?=> $try_into_type)?
@@ -139,7 +142,7 @@ fn from(val: $name) -> u32 {// Defines all the field getter/setter methods for `$name`. ( - @field_accessors $name:ident { + @field_accessors $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=> $try_into_type:ty)? $(=> $into_type:ty)?
@@ -155,7 +158,7 @@ fn from(val: $name) -> u32 {#[allow(dead_code)] impl $name { $( -bitfield! (@field_accessor $name $hi:$lo $fieldas $type +bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas $type $(?=> $try_into_type)? $(=> $into_type)? $(, $comment)?
@@ -189,11 +192,11 @@ impl $name {// Catches fields defined as `bool` and convert them into a boolean value. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty $(, $comment:literal)?; ) => {bitfield! ( - @leaf_accessor $name $hi:$lo $field + @leaf_accessor $name $storage, $hi:$lo $field { |f| <$into_type>::from (if f !=0 {true }else {false }) } $into_type => $into_type $(, $comment)?; );
@@ -201,17 +204,17 @@ impl $name {// Shortcut for fields defined as `bool` without the `=>` syntax. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?; + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $name $hi:$lo $fieldas bool =>bool $(, $comment)?;); +bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?;); };// Catches the `?=>` syntax for non-boolean fields. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $name $hi:$lo $field +bitfield! (@leaf_accessor $name $storage, $hi:$lo $field { |f| <$try_into_type>::try_from (fas $type ) } $try_into_type => ::core::result::Result < $try_into_type,
@@ -222,29 +225,38 @@ impl $name {// Catches the `=>` syntax for non-boolean fields. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $name $hi:$lo $field +bitfield! (@leaf_accessor $name $storage, $hi:$lo $field { |f| <$into_type>::from (fas $type ) } $into_type => $into_type $(, $comment)?;); };// Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $name $hi:$lo $fieldas $type => $type $(, $comment)?;); +bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?;); };// Generates the accessor methods for a single field. ( - @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident + @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident { $process:expr } $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>]:u32 = ((((1 << $hi) -1 ) <<1 ) +1 ) - ((1 << $lo) -1 ); +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 =Self ::[<$field:upper _MASK>].trailing_zeros (); );
@@ -255,7 +267,7 @@ impl $name {#[inline(always)] pub (crate )fn $field(self) -> $res_type { ::kernel::macros::paste!( -const MASK :u32 = $name::[<$field:upper _MASK>]; +const MASK : $storage = $name::[<$field:upper _MASK>];const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; );let field = ((self.0 &MASK ) >>SHIFT );
@@ -270,9 +282,9 @@ pub(crate) fn $field(self) -> $res_type { )?#[inline(always)] pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self { - const MASK: u32 = $name::[<$field:upper _MASK>]; + const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; -let value = (u32::from (value) <<SHIFT ) &MASK ; +let value = (<$storage>::from (value) <<SHIFT ) &MASK ; self.0 = (self.0 & !MASK ) | value; self
drivers/gpu/nova-core/regs/macros.rs +8 -8
@@ -276,25 +276,25 @@ pub(crate) trait RegisterBase<T> {macro_rules! register {// Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $offset); };// Creates an alias register of fixed offset register `alias` with its own fields. ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $alias::OFFSET ); };// Creates a register at a relative offset from a base address provider. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $offset ]); };// Creates an alias register of relative offset register `alias` with its own fields. ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $alias::OFFSET ]); };
@@ -305,7 +305,7 @@ macro_rules! register { } ) => {static_assert! (::core::mem::size_of ::<u32 >() <= $stride); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_array $name @ $offset [ $size ; $stride ]); };
@@ -326,7 +326,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) => {static_assert! (::core::mem::size_of ::<u32 >() <= $stride); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]); };
@@ -348,7 +348,7 @@ macro_rules! register { } ) => {static_assert! ($idx < $alias::SIZE ); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] ); };
@@ -357,7 +357,7 @@ macro_rules! register {// to avoid it being interpreted in place of the relative register array alias rule. ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {static_assert! ($idx < $alias::SIZE ); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE ); };
Signature · 1 line
2.34.1
Re: [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths
Quoted 5 lines · Joel Fernandes
Previously, bitfields were hardcoded to use u32 as the underlying storage type. Add support for different storage types (u8, u16, u32, u64) to the bitfield macro.
New syntax is: struct Name: <type ex., u32> { ... }
Apologies for not updating this commit message, the syntax is:
struct Name(<type ex., u32>) { ... }
thanks,
- Joel
Re: [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths
In reply to Joel FernandesQuoted 5 lines · Joel Fernandes
Previously, bitfields were hardcoded to use u32 as the underlying storage type. Add support for different storage types (u8, u16, u32, u64) to the bitfield macro.
New syntax is: struct Name: <type ex., u32> { ... }
With the to the line above mentioned in your reply,
PATCH v5 3/9 nova-core: bitfield: Add support for custom visiblity
In reply to Joel FernandesAdd support for custom visiblity to allow for users to control visibility of the structure and helpers.
--- drivers/gpu/nova-core/bitfield.rs | 49 +++++++++++++++------------- drivers/gpu/nova-core/regs/macros.rs | 16 ++++----- 2 files changed, 34 insertions(+), 31 deletions(-)
drivers/gpu/nova-core/bitfield.rs +26 -23
@@ -57,7 +57,7 @@/// } /// /// bitfield! { -/// struct ControlReg(u32) { +/// pub struct ControlReg(u32) { /// 3:0 mode as u8 ?=> Mode; /// 7:7 state as bool => State; /// }
@@ -71,6 +71,9 @@/// 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
@@ -81,21 +84,21 @@/// 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 - (struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => { -bitfield! (@core $name $storage $(, $comment)? { $($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`, `BitOr`, and conversion to the value type) and field accessor methods. - (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => { + (@core $vis:vis $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => { $(#[doc=$comment] )?#[repr(transparent)] #[derive( Clone , Copy )] -pub (crate )struct $name($storage); + $visstruct $name($storage);impl ::core::ops::BitOr for $name {type Output =Self ;
@@ -111,14 +114,14 @@ fn from(val: $name) -> $storage { } } -bitfield! (@fields_dispatcher $name $storage { $($fields)* }); +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 $name:ident $storage:ty { + (@fields_dispatcher $vis:vis $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=> $try_into_type:ty)? $(=> $into_type:ty)?
@@ -127,7 +130,7 @@ fn from(val: $name) -> $storage { )* } ) => { - bitfield!(@field_accessors $name $storage { + bitfield!(@field_accessors $vis $name $storage { $( $hi:$lo $field as $type $(?=> $try_into_type)?
@@ -142,7 +145,7 @@ fn from(val: $name) -> $storage {// Defines all the field getter/setter methods for `$name`. ( - @field_accessors $name:ident $storage:ty { + @field_accessors $vis:vis $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=> $try_into_type:ty)? $(=> $into_type:ty)?
@@ -158,7 +161,7 @@ fn from(val: $name) -> $storage {#[allow(dead_code)] impl $name { $( -bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas $type +bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas $type $(?=> $try_into_type)? $(=> $into_type)? $(, $comment)?
@@ -192,11 +195,11 @@ impl $name {// Catches fields defined as `bool` and convert them into a boolean value. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty $(, $comment:literal)?; ) => {bitfield! ( - @leaf_accessor $name $storage, $hi:$lo $field + @leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from (if f !=0 {true }else {false }) } $into_type => $into_type $(, $comment)?; );
@@ -204,17 +207,17 @@ impl $name {// Shortcut for fields defined as `bool` without the `=>` syntax. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?; + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?;); +bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?;); };// Catches the `?=>` syntax for non-boolean fields. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $name $storage, $hi:$lo $field +bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$try_into_type>::try_from (fas $type ) } $try_into_type => ::core::result::Result < $try_into_type,
@@ -225,24 +228,24 @@ impl $name {// Catches the `=>` syntax for non-boolean fields. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $name $storage, $hi:$lo $field +bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from (fas $type ) } $into_type => $into_type $(, $comment)?;); };// Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?;); +bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?;); };// Generates the accessor methods for a single field. ( - @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident + @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?; ) => { ::kernel::macros::paste!(
@@ -265,7 +268,7 @@ impl $name {#[doc=$comment] )?#[inline(always)] -pub (crate )fn $field(self) -> $res_type { + $vis fn $field(self) -> $res_type { ::kernel::macros::paste!(const MASK : $storage = $name::[<$field:upper _MASK>];const SHIFT :u32 = $name::[<$field:upper_SHIFT >];
@@ -281,7 +284,7 @@ pub(crate) fn $field(self) -> $res_type {#[doc=$comment] )?#[inline(always)] - pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self { + $vis fn [<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(value) << SHIFT) & MASK;
drivers/gpu/nova-core/regs/macros.rs +8 -8
@@ -276,25 +276,25 @@ pub(crate) trait RegisterBase<T> {macro_rules! register {// Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $offset); };// Creates an alias register of fixed offset register `alias` with its own fields. ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $alias::OFFSET ); };// Creates a register at a relative offset from a base address provider. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $offset ]); };// Creates an alias register of relative offset register `alias` with its own fields. ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $alias::OFFSET ]); };
@@ -305,7 +305,7 @@ macro_rules! register { } ) => {static_assert! (::core::mem::size_of ::<u32 >() <= $stride); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_array $name @ $offset [ $size ; $stride ]); };
@@ -326,7 +326,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) => {static_assert! (::core::mem::size_of ::<u32 >() <= $stride); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]); };
@@ -348,7 +348,7 @@ macro_rules! register { } ) => {static_assert! ($idx < $alias::SIZE ); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] ); };
@@ -357,7 +357,7 @@ macro_rules! register {// to avoid it being interpreted in place of the relative register array alias rule. ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {static_assert! ($idx < $alias::SIZE ); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); +bitfield! (pub (crate )struct $name(u32 ) $(, $comment)? { $($fields)* } );register! (@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE ); };
Signature · 1 line
2.34.1
PATCH v5 4/9 rust: Move register and bitfield macros out of Nova
In reply to Joel FernandesOut of broad need for the register and bitfield macros in Rust, move them out of nova into the kernel crate. Several usecases need them (Nova is already using these and Tyr developers said they need them).
bitfield moved into kernel crate - defines bitfields in Rust. register moved into io module - defines hardware registers and accessors.
---
MAINTAINERS | 7 +++
drivers/gpu/nova-core/falcon.rs | 2 +-
drivers/gpu/nova-core/falcon/gsp.rs | 4 +-
drivers/gpu/nova-core/falcon/sec2.rs | 2 +-
drivers/gpu/nova-core/nova_core.rs | 3 -
drivers/gpu/nova-core/regs.rs | 6 +-
.../gpu/nova-core => rust/kernel}/bitfield.rs | 27 ++++-----
rust/kernel/io.rs | 1 +
.../macros.rs => rust/kernel/io/register.rs | 58 ++++++++++---------
rust/kernel/lib.rs | 1 +
10 files changed, 61 insertions(+), 50 deletions(-)
rename {drivers/gpu/nova-core => rust/kernel}/bitfield.rs (91%)
rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (93%)MAINTAINERS +7 -0
@@ -4380,6 +4380,13 @@ F: include/linux/bitops.h F: lib/test_bitops.c F: tools/*/bitops* +BITFIELD API [RUST] +M: Joel Fernandes <[email protected]> +M: Alexandre Courbot <[email protected]> +M: Yury Norov <[email protected]> +S: Maintained +F: rust/kernel/bitfield.rs + BITOPS API BINDINGS [RUST] M: Yury Norov <[email protected]> S: Maintained
drivers/gpu/nova-core/falcon.rs +1 -1
@@ -6,6 +6,7 @@use hal::FalconHal ;use kernel::device;use kernel::dma::DmaAddress ; +use kernel::io::register::RegisterBase ;use kernel::prelude::*;use kernel::sync::aref::ARef ;use kernel::time::Delta ;
@@ -14,7 +15,6 @@use crate ::driver::Bar0 ;use crate ::gpu::Chipset ;use crate ::regs; -use crate ::regs::macros::RegisterBase ;use crate ::util;pub (crate )mod gsp;
drivers/gpu/nova-core/falcon/gsp.rs +3 -1
@@ -1,9 +1,11 @@// SPDX-License-Identifier: GPL-2.0 +use kernel::io::register::RegisterBase ; +use crate ::{ driver::Bar0 , falcon::{Falcon ,FalconEngine ,PFalcon2Base ,PFalconBase }, - regs::{self, macros::RegisterBase }, + regs::self, };/// Type specifying the `Gsp` falcon engine. Cannot be instantiated.
drivers/gpu/nova-core/falcon/sec2.rs +1 -1
@@ -1,7 +1,7 @@// SPDX-License-Identifier: GPL-2.0 use crate ::falcon::{FalconEngine ,PFalcon2Base ,PFalconBase }; -use crate ::regs::macros::RegisterBase ; +use kernel::io::register::RegisterBase ;/// Type specifying the `Sec2` falcon engine. Cannot be instantiated. pub (crate )struct Sec2 (());
drivers/gpu/nova-core/nova_core.rs +0 -3
@@ -2,9 +2,6 @@//! Nova Core GPU Driver -#[macro_use] -mod bitfield; -mod dma;mod driver;mod falcon;
drivers/gpu/nova-core/regs.rs +3 -3
@@ -4,15 +4,13 @@// but are mapped to types. #![allow(non_camel_case_types)] -#[macro_use] -pub (crate )mod macros; -use crate ::falcon::{DmaTrfCmdSize ,FalconCoreRev ,FalconCoreRevSubversion ,FalconFbifMemType ,FalconFbifTarget ,FalconModSelAlgo ,FalconSecurityModel ,PFalcon2Base ,PFalconBase ,PeregrineCoreSelect , };use crate ::gpu::{Architecture ,Chipset };use kernel::prelude::*; +use kernel::register;// PMC
@@ -331,6 +329,7 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {pub (crate )mod gm107 {// FUSE +use kernel::register;register! (NV_FUSE_STATUS_OPT_DISPLAY @0x00021c04 {0 :0 display_disabledas bool ;
@@ -339,6 +338,7 @@ pub(crate) mod gm107 {pub (crate )mod ga100 {// FUSE +use kernel::register;register! (NV_FUSE_STATUS_OPT_DISPLAY @0x00820c04 {0 :0 display_disabledas bool ;
rust/kernel/bitfield.rs renamed from drivers/gpu/nova-core/bitfield.rs +14 -13
@@ -9,7 +9,7 @@/// # Syntax /// /// ```rust -/// use nova_core::bitfield; +/// use kernel::bitfield; /// /// #[derive(Debug, Clone, Copy, Default)] /// enum Mode {
@@ -82,10 +82,11 @@/// 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_export] 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)* }); + ::kernel::bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* }); };// All rules below are helpers.
@@ -114,7 +115,7 @@ fn from(val: $name) -> $storage { } } -bitfield! (@fields_dispatcher $vis $name $storage { $($fields)* }); + ::kernel::bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* }); };// Captures the fields and passes them to all the implementers that require field information.
@@ -130,7 +131,7 @@ fn from(val: $name) -> $storage { )* } ) => { - bitfield!(@field_accessors $vis $name $storage { + ::kernel::bitfield!(@field_accessors $vis $name $storage { $( $hi:$lo $field as $type $(?=> $try_into_type)?
@@ -139,8 +140,8 @@ fn from(val: $name) -> $storage { ; )* }); -bitfield! (@debug $name { $($field;)* }); -bitfield! (@default $name { $($field;)* }); + ::kernel::bitfield!(@debug $name { $($field;)* }); + ::kernel::bitfield!(@default $name { $($field;)* }); };// Defines all the field getter/setter methods for `$name`.
@@ -155,13 +156,13 @@ fn from(val: $name) -> $storage { } ) => { $( - bitfield!(@check_field_bounds $hi:$lo $field as $type); + ::kernel::bitfield!(@check_field_bounds $hi:$lo $field as $type); )*#[allow(dead_code)] impl $name { $( -bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas $type + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $fieldas $type $(?=> $try_into_type)? $(=> $into_type)? $(, $comment)?
@@ -198,7 +199,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty $(, $comment:literal)?; ) => { -bitfield! ( + ::kernel::bitfield!( @leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from (if f !=0 {true }else {false }) } $into_type => $into_type $(, $comment)?;
@@ -209,7 +210,7 @@ impl $name { ( @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?;); + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $fieldas bool =>bool $(, $comment)?;); };// Catches the `?=>` syntax for non-boolean fields.
@@ -217,7 +218,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field + ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$try_into_type>::try_from (fas $type ) } $try_into_type => ::core::result::Result < $try_into_type,
@@ -231,7 +232,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty $(, $comment:literal)?; ) => { -bitfield! (@leaf_accessor $vis $name $storage, $hi:$lo $field + ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from (fas $type ) } $into_type => $into_type $(, $comment)?;); };
@@ -240,7 +241,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt $(, $comment:literal)?; ) => { -bitfield! (@field_accessor $vis $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?;); + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $fieldas $type => $type $(, $comment)?;); };// Generates the accessor methods for a single field.
rust/kernel/io.rs +1 -0
@@ -9,6 +9,7 @@pub mod mem;pub mod poll; +pub mod register;pub mod resource;pub use resource::Resource ;
rust/kernel/io/register.rs renamed from drivers/gpu/nova-core/regs/macros.rs +30 -28
217 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -64,6 +64,7 @@#[cfg( CONFIG_AUXILIARY_BUS )] pub mod auxiliary;pub mod bitmap; +pub mod bitfield;pub mod bits;#[cfg( CONFIG_BLOCK )] pub mod block;
Signature · 1 line
2.34.1
PATCH v5 5/9 rust: bitfield: Add a new() constructor and raw() accessor
In reply to Joel FernandesIn order to prevent the user from directly accessing/wrapping the inner value of the struct, provide a new storage type to wrap the inner value. The bitfield framework can then control access better. For instance, we can zero out undefined bits to prevent undefined behavior of bits that are not defined.
Further, we can somewhat prevent the user manipulating the bitfield's inner storage directly using .0. They can still do so by using the new bitfield storage type this patch defines, however it would not be by accident and would have to be deliberate.
--- rust/kernel/bitfield.rs | 123 +++++++++++++++++++++++++++++-------- rust/kernel/io/register.rs | 16 ++--- 2 files changed, 106 insertions(+), 33 deletions(-)
rust/kernel/bitfield.rs +98 -25
@@ -4,7 +4,33 @@//! //! 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. +/// Storage wrapper for bitfield values that prevents direct construction. +/// +/// This type wraps the underlying storage value and ensures that bitfield +/// structs can only be constructed through their `new()` method, which +/// properly masks undefined bits. +#[repr(transparent)] +#[derive( Clone , Copy )] +pub struct BitfieldInternalStorage <T :Copy > { + value:T , +} + +impl <T :Copy >BitfieldInternalStorage <T > { +/// Creates a new storage wrapper with the given value. +#[inline(always)] +pub const fn from_raw (value:T ) ->Self { +Self { value } + } + +/// Returns the underlying raw value. +#[inline(always)] +pub const fn into_raw (self) ->T { + self.value + } +} + +/// Bitfield macro definition. +/// Define a struct with accessors to access bits within an inner unsigned integer. /// /// # Syntax ///
@@ -62,9 +88,23 @@/// 7:7 state as bool => State; /// } /// } +/// +/// // Create a bitfield from a raw value - undefined bits are zeroed +/// let reg = ControlReg::new(0xDEADBEEF); +/// // Only bits 0-3 and 7 are preserved (as defined by the fields) +/// +/// // Get the raw underlying value +/// let raw_value = reg.raw(); +/// +/// // Use the builder pattern with field setters +/// let reg2 = ControlReg::default() +/// .set_mode(Mode::Auto) +/// .set_state(State::Active); /// ``` /// /// This generates a struct with: +/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits +/// - Raw accessor: `raw()` - returns the underlying raw value /// - 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
@@ -72,7 +112,7 @@/// - 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`. +/// In the example above, `new()`, `raw()`, `mode()` and `set_mode()` methods will be `pub`. /// /// Fields are defined as follows: ///
@@ -99,19 +139,19 @@ macro_rules! bitfield { )?#[repr(transparent)] #[derive( Clone , Copy )] - $vis struct $name($storage); + $vis struct $name(::kernel::bitfield::BitfieldInternalStorage<$storage>);impl ::core::ops::BitOr for $name {type Output =Self ;fn bitor (self, rhs:Self ) ->Self ::Output { -Self (self.0 | rhs.0 ) +Self ::new (self.raw () | rhs.raw ()) } }impl ::core::convert::From <$name>for $storage {fn from (val: $name) -> $storage { - val.0 + val.raw () } }
@@ -161,6 +201,53 @@ fn from(val: $name) -> $storage {#[allow(dead_code)] impl $name { +// Generate field constants to be used later + $( + ::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 =Self ::[<$field:upper _MASK>].trailing_zeros (); + ); + )* + +/// Creates a new bitfield instance from a raw value. +/// +/// This constructor zeros out all bits that are not defined by any field, +/// ensuring only valid field bits are preserved. This is to prevent UB +/// when raw() is used to retrieve undefined bits. +#[inline(always)] + $vis fn new(value: $storage) -> Self { +// Calculate mask for all defined fields +let mut mask: $storage =0 ; + $( + ::kernel::macros::paste!( + mask |=Self ::[<$field:upper _MASK>]; + ); + )* +// Zero out undefined bits and wrap in BitfieldInternalStorage +Self (::kernel::bitfield::BitfieldInternalStorage ::from_raw (value & mask)) + } + +/// Returns the raw underlying value of the bitfield. +/// +/// This provides direct access to the storage value, useful for +/// debugging or when you need to work with the raw value. +/// Bits not defined are masked at construction time. +#[inline(always)] + $vis fn raw(&self) -> $storage { + self.0 .into_raw () + } + +// Generate field accessors $( ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $fieldas $type $(?=> $try_into_type)?
@@ -249,21 +336,6 @@ impl $name { @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident { $process:expr } $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 =Self ::[<$field:upper _MASK>].trailing_zeros (); - ); - $( #[doc="Returns the value of this field:"] #[doc=$comment]
@@ -274,7 +346,7 @@ impl $name { const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; ); -let field = ((self.0 &MASK ) >>SHIFT ); +let field = ((self.raw () &MASK ) >>SHIFT ); $process(field) }
@@ -288,8 +360,9 @@ impl $name { $vis fn [<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(value) << SHIFT) & MASK; - self.0 = (self.0 & !MASK) | value; + let val = (<$storage>::from(value) << SHIFT) & MASK; + let new_val = (self.raw() & !MASK) | val; + self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val); self }
@@ -301,7 +374,7 @@ impl $name {impl ::core::fmt::Debug for $name {fn fmt (&self, f: &mut ::core::fmt::Formatter <'_>) -> ::core::fmt::Result { f.debug_struct (stringify! ($name)) - .field ("<raw>" , &format_args! ("{:#x}" , &self.0 )) + .field ("<raw>" , &format_args! ("{:#x}" , &self.raw ())) $( .field(stringify!($field), &self.$field()) )*
@@ -316,7 +389,7 @@ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {impl ::core::default::Default for $name {fn default () ->Self {#[allow(unused_mut)] -let mut value =Self (Default ::default ()); +let mut value =Self ::new (Default ::default ()); ::kernel::macros::paste!( $(
rust/kernel/io/register.rs +8 -8
@@ -374,7 +374,7 @@ impl $name {pub (crate )fn read <const SIZE :usize ,T >(io: &T ) ->Self where T : ::core::ops::Deref <Target = ::kernel::io::Io <SIZE >>, { -Self (io.read32 ($offset)) +Self ::new (io.read32 ($offset)) }/// Write the value contained in `self` to the register address in `io`.
@@ -382,7 +382,7 @@ pub(crate) fn read<const SIZE: usize, T>(io: &T) -> Self wherepub (crate )fn write <const SIZE :usize ,T >(self, io: &T )where T : ::core::ops::Deref <Target = ::kernel::io::Io <SIZE >>, { - io.write32 (self.0 , $offset) + io.write32 (self.raw (), $offset) }/// Read the register from its address in `io` and run `f` on its value to obtain a new
@@ -424,7 +424,7 @@ pub(crate) fn read<const SIZE: usize, T, B>( <B as ::kernel::io::register::RegisterBase <$base>>::BASE +OFFSET ); -Self (value) +Self ::new (value) }/// Write the value contained in `self` to `io`, using the base address provided by
@@ -442,7 +442,7 @@ pub(crate) fn write<const SIZE: usize, T, B>(const OFFSET :usize = $name::OFFSET ; io.write32 ( - self.0 , + self.raw (), <B as ::kernel::io::register::RegisterBase <$base>>::BASE +OFFSET ); }
@@ -487,7 +487,7 @@ pub(crate) fn read<const SIZE: usize, T>(let offset =Self ::OFFSET + (idx *Self ::STRIDE );let value = io.read32 (offset); -Self (value) +Self ::new (value) }/// Write the value contained in `self` to the array register with index `idx` in `io`.
@@ -503,7 +503,7 @@ pub(crate) fn write<const SIZE: usize, T>(let offset =Self ::OFFSET + (idx *Self ::STRIDE ); - io.write32 (self.0 , offset); + io.write32 (self.raw (), offset); }/// Read the array register at index `idx` in `io` and run `f` on its value to obtain a
@@ -610,7 +610,7 @@ pub(crate) fn read<const SIZE: usize, T, B>(Self ::OFFSET + (idx *Self ::STRIDE );let value = io.read32 (offset); -Self (value) +Self ::new (value) }/// Write the value contained in `self` to `io`, using the base address provided by
@@ -631,7 +631,7 @@ pub(crate) fn write<const SIZE: usize, T, B>(let offset = <B as ::kernel::io::register::RegisterBase <$base>>::BASE +Self ::OFFSET + (idx *Self ::STRIDE ); - io.write32 (self.0 , offset); + io.write32 (self.raw (), offset); }/// Read the array register at index `idx` from `io`, using the base address provided
Signature · 1 line
2.34.1
PATCH v5 6/9 rust: bitfield: Add KUNIT tests for bitfield
In reply to Joel FernandesAdd KUNIT tests to make sure the macro is working correctly.
--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)
rust/kernel/bitfield.rs +321 -0
@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 , +Normal =1 , +Device =2 , +Reserved =3 , + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + } + +impl TryFrom <u8 >for MemoryType { +type Error =u8 ; +fn try_from (value:u8 ) ->Result <Self ,Self ::Error > { +match value { +0 =>Ok (MemoryType ::Unmapped ), +1 =>Ok (MemoryType ::Normal ), +2 =>Ok (MemoryType ::Device ), +3 =>Ok (MemoryType ::Reserved ), + _ =>Err (value), + } + } + } + +impl From <MemoryType >for u64 { +fn from (mt:MemoryType ) ->u64 { + mtas u64 + } + } + +#[derive( Debug , Clone , Copy , PartialEq )] +enum Priority { +Low =0 , +Medium =1 , +High =2 , +Critical =3 , + } + +impl Default for Priority { +fn default () ->Self { +Priority ::Low + } + } + +impl From <u8 >for Priority { +fn from (value:u8 ) ->Self { +match value &0x3 { +0 =>Priority ::Low , +1 =>Priority ::Medium , +2 =>Priority ::High , + _ =>Priority ::Critical , + } + } + } + +impl From <Priority >for u16 { +fn from (p:Priority ) ->u16 { + pas u16 + } + } + +bitfield! { +struct TestPageTableEntry (u64 ) { +0 :0 presentas bool ; +1 :1 writableas bool ; +11 :9 availableas u8 ; +13 :12 mem_typeas u8 ?=>MemoryType ; +17 :14 extended_typeas u8 ?=>MemoryType ;// For testing failures +51 :12 pfnas u64 ; +51 :12 pfn_overlapas u64 ; +61 :52 available2as u16 ; + } + } + +bitfield! { +struct TestControlRegister (u16 ) { +0 :0 enableas bool ; +3 :1 modeas u8 ; +5 :4 priorityas u8 =>Priority ; +7 :4 priority_nibbleas u8 ; +15 :8 channelas u8 ; + } + } + +bitfield! { +struct TestStatusRegister (u8 ) { +0 :0 readyas bool ; +1 :1 erroras bool ; +3 :2 stateas u8 ; +7 :4 reservedas u8 ; +7 :0 full_byteas u8 ;// For entire register + } + } + +#[test] +fn test_single_bits () { +let mut pte =TestPageTableEntry ::default (); + +assert! (!pte.present ()); +assert! (!pte.writable ()); + + pte = pte.set_present (true ); +assert! (pte.present ()); + + pte = pte.set_writable (true ); +assert! (pte.writable ()); + + pte = pte.set_writable (false ); +assert! (!pte.writable ()); + +assert_eq! (pte.available (),0 ); + pte = pte.set_available (0x5 ); +assert_eq! (pte.available (),0x5 ); + } + +#[test] +fn test_range_fields () { +let mut pte =TestPageTableEntry ::default (); + + pte = pte.set_pfn (0x123456 ); +assert_eq! (pte.pfn (),0x123456 ); +// Test overlapping field reads same value +assert_eq! (pte.pfn_overlap (),0x123456 ); + + pte = pte.set_available (0x7 ); +assert_eq! (pte.available (),0x7 ); + + pte = pte.set_available2 (0x3FF ); +assert_eq! (pte.available2 (),0x3FF ); + +// Test TryFrom with ?=> for MemoryType + pte = pte.set_mem_type (MemoryType ::Device ); +assert_eq! (pte.mem_type (),Ok (MemoryType ::Device )); + + pte = pte.set_mem_type (MemoryType ::Normal ); +assert_eq! (pte.mem_type (),Ok (MemoryType ::Normal )); + +// Test all valid values for mem_type + pte = pte.set_mem_type (MemoryType ::Reserved );// Valid value: 3 +assert_eq! (pte.mem_type (),Ok (MemoryType ::Reserved )); + +// Test failure case using extended_type field which has 4 bits (0-15) +// MemoryType only handles 0-3, so values 4-15 should return Err +let mut raw = pte.raw (); +// Set bits 17:14 to 7 (invalid for MemoryType) + raw = (raw & !::kernel::bits::genmask_u64 (14 ..=17 )) | (0x7 <<14 ); +let invalid_pte =TestPageTableEntry ::new (raw); +// Should return Err with the invalid value +assert_eq! (invalid_pte.extended_type (),Err (0x7 )); + +// Test a valid value after testing invalid to ensure both cases work +// Set bits 17:14 to 2 (valid: Device) + raw = (raw & !::kernel::bits::genmask_u64 (14 ..=17 )) | (0x2 <<14 ); +let valid_pte =TestPageTableEntry ::new (raw); +assert_eq! (valid_pte.extended_type (),Ok (MemoryType ::Device )); + +let max_pfn = ::kernel::bits::genmask_u64 (0 ..=39 ); + pte = pte.set_pfn (max_pfn); +assert_eq! (pte.pfn (), max_pfn); +assert_eq! (pte.pfn_overlap (), max_pfn); + } + +#[test] +fn test_builder_pattern () { +let pte =TestPageTableEntry ::default () + .set_present (true ) + .set_writable (true ) + .set_available (0x7 ) + .set_pfn (0xABCDEF ) + .set_mem_type (MemoryType ::Reserved ) + .set_available2 (0x3FF ); + +assert! (pte.present ()); +assert! (pte.writable ()); +assert_eq! (pte.available (),0x7 ); +assert_eq! (pte.pfn (),0xABCDEF ); +assert_eq! (pte.pfn_overlap (),0xABCDEF ); +assert_eq! (pte.mem_type (),Ok (MemoryType ::Reserved )); +assert_eq! (pte.available2 (),0x3FF ); + } + +#[test] +fn test_raw_operations () { +let raw_value =0x3FF0000003123E03u64 ; + +let pte =TestPageTableEntry ::new (raw_value); +assert_eq! (pte.raw (), raw_value); + +assert! (pte.present ()); +assert! (pte.writable ()); +assert_eq! (pte.available (),0x7 ); +assert_eq! (pte.pfn (),0x3123 ); +assert_eq! (pte.pfn_overlap (),0x3123 ); +assert_eq! (pte.mem_type (),Ok (MemoryType ::Reserved )); +assert_eq! (pte.available2 (),0x3FF ); + +// Test using direct constructor syntax TestStruct(value) +let pte2 =TestPageTableEntry ::new (raw_value); +assert_eq! (pte2.raw (), raw_value); + } + +#[test] +fn test_u16_bitfield () { +let mut ctrl =TestControlRegister ::default (); + +assert! (!ctrl.enable ()); +assert_eq! (ctrl.mode (),0 ); +assert_eq! (ctrl.priority (),Priority ::Low ); +assert_eq! (ctrl.priority_nibble (),0 ); +assert_eq! (ctrl.channel (),0 ); + + ctrl = ctrl.set_enable (true ); +assert! (ctrl.enable ()); + + ctrl = ctrl.set_mode (0x5 ); +assert_eq! (ctrl.mode (),0x5 ); + +// Test From conversion with => + ctrl = ctrl.set_priority (Priority ::High ); +assert_eq! (ctrl.priority (),Priority ::High ); +assert_eq! (ctrl.priority_nibble (),0x2 );// High = 2 in bits 5:4 + + ctrl = ctrl.set_channel (0xAB ); +assert_eq! (ctrl.channel (),0xAB ); + +// Test overlapping fields + ctrl = ctrl.set_priority_nibble (0xF ); +assert_eq! (ctrl.priority_nibble (),0xF ); +assert_eq! (ctrl.priority (),Priority ::Critical );// bits 5:4 = 0x3 + +let ctrl2 =TestControlRegister ::default () + .set_enable (true ) + .set_mode (0x3 ) + .set_priority (Priority ::Medium ) + .set_channel (0x42 ); + +assert! (ctrl2.enable ()); +assert_eq! (ctrl2.mode (),0x3 ); +assert_eq! (ctrl2.priority (),Priority ::Medium ); +assert_eq! (ctrl2.channel (),0x42 ); + +let raw_value:u16 =0x4217 ; +let ctrl3 =TestControlRegister ::new (raw_value); +assert_eq! (ctrl3.raw (), raw_value); +assert! (ctrl3.enable ()); +assert_eq! (ctrl3.priority (),Priority ::Medium ); +assert_eq! (ctrl3.priority_nibble (),0x1 ); +assert_eq! (ctrl3.channel (),0x42 ); + } + +#[test] +fn test_u8_bitfield () { +let mut status =TestStatusRegister ::default (); + +assert! (!status.ready ()); +assert! (!status.error ()); +assert_eq! (status.state (),0 ); +assert_eq! (status.reserved (),0 ); +assert_eq! (status.full_byte (),0 ); + + status = status.set_ready (true ); +assert! (status.ready ()); +assert_eq! (status.full_byte (),0x01 ); + + status = status.set_error (true ); +assert! (status.error ()); +assert_eq! (status.full_byte (),0x03 ); + + status = status.set_state (0x3 ); +assert_eq! (status.state (),0x3 ); +assert_eq! (status.full_byte (),0x0F ); + + status = status.set_reserved (0xA ); +assert_eq! (status.reserved (),0xA ); +assert_eq! (status.full_byte (),0xAF ); + +// Test overlapping field + status = status.set_full_byte (0x55 ); +assert_eq! (status.full_byte (),0x55 ); +assert! (status.ready ()); +assert! (!status.error ()); +assert_eq! (status.state (),0x1 ); +assert_eq! (status.reserved (),0x5 ); + +let status2 =TestStatusRegister ::default () + .set_ready (true ) + .set_state (0x2 ) + .set_reserved (0x5 ); + +assert! (status2.ready ()); +assert! (!status2.error ()); +assert_eq! (status2.state (),0x2 ); +assert_eq! (status2.reserved (),0x5 ); +assert_eq! (status2.full_byte (),0x59 ); + +let raw_value:u8 =0x59 ; +let status3 =TestStatusRegister ::new (raw_value); +assert_eq! (status3.raw (), raw_value); +assert! (status3.ready ()); +assert! (!status3.error ()); +assert_eq! (status3.state (),0x2 ); +assert_eq! (status3.reserved (),0x5 ); +assert_eq! (status3.full_byte (),0x59 ); + +let status4 =TestStatusRegister ::new (0xFF ); +assert! (status4.ready ()); +assert! (status4.error ()); +assert_eq! (status4.state (),0x3 ); +assert_eq! (status4.reserved (),0xF ); +assert_eq! (status4.full_byte (),0xFF ); + } +}
Signature · 1 line
2.34.1
Alexandre Courbot
maintainerRe: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 24 lines · Joel Fernandes
Add KUNIT tests to make sure the macro is working correctly.
Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)rust/kernel/bitfield.rs +9
-0@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 ,
rust/kernel/bitfield.rs fn default() -> Self { · line 423
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ Normal = 1, + Device = 2, + Reserved = 3, + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + }
Tip: you can add Default to the #[derive] marker of MemoryType and mark the variant you want as default with #[default] instead of providing a full impl block:
#[derive(Debug, Default, Clone, Copy, PartialEq)]
enum MemoryType {
#[default]
Unmapped = 0,
Normal = 1,
Device = 2,
Reserved = 3,
}Quoted 93 lines
rust/kernel/bitfield.rs +93
-0+ +impl TryFrom <u8 >for MemoryType { +type Error =u8 ; +fn try_from (value:u8 ) ->Result <Self ,Self ::Error > { +match value { +0 =>Ok (MemoryType ::Unmapped ), +1 =>Ok (MemoryType ::Normal ), +2 =>Ok (MemoryType ::Device ), +3 =>Ok (MemoryType ::Reserved ), + _ =>Err (value), + } + } + } + +impl From <MemoryType >for u64 { +fn from (mt:MemoryType ) ->u64 { + mtas u64 + } + } + +#[derive( Debug , Clone , Copy , PartialEq )] +enum Priority { +Low =0 , +Medium =1 , +High =2 , +Critical =3 , + } + +impl Default for Priority { +fn default () ->Self { +Priority ::Low + } + } + +impl From <u8 >for Priority { +fn from (value:u8 ) ->Self { +match value &0x3 { +0 =>Priority ::Low , +1 =>Priority ::Medium , +2 =>Priority ::High , + _ =>Priority ::Critical , + } + } + } + +impl From <Priority >for u16 { +fn from (p:Priority ) ->u16 { + pas u16 + } + } + +bitfield! { +struct TestPageTableEntry (u64 ) { +0 :0 presentas bool ; +1 :1 writableas bool ; +11 :9 availableas u8 ; +13 :12 mem_typeas u8 ?=>MemoryType ; +17 :14 extended_typeas u8 ?=>MemoryType ;// For testing failures +51 :12 pfnas u64 ; +51 :12 pfn_overlapas u64 ; +61 :52 available2as u16 ; + } + } + +bitfield! { +struct TestControlRegister (u16 ) { +0 :0 enableas bool ; +3 :1 modeas u8 ; +5 :4 priorityas u8 =>Priority ; +7 :4 priority_nibbleas u8 ; +15 :8 channelas u8 ; + } + } + +bitfield! { +struct TestStatusRegister (u8 ) { +0 :0 readyas bool ; +1 :1 erroras bool ; +3 :2 stateas u8 ; +7 :4 reservedas u8 ; +7 :0 full_byteas u8 ;// For entire register + } + } + +#[test] +fn test_single_bits () { +let mut pte =TestPageTableEntry ::default (); + +assert! (!pte.present ()); +assert! (!pte.writable ()); + + pte = pte.set_present (true ); +assert! (pte.present ());
rust/kernel/bitfield.rs fn default() -> Self { · line 526
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ + pte = pte.set_writable (true ); +assert! (pte.writable ()); + + pte = pte.set_writable (false ); +assert! (!pte.writable ()); + +assert_eq! (pte.available (),0 ); + pte = pte.set_available (0x5 ); +assert_eq! (pte.available (),0x5 );
I'd suggest testing the actual raw value of the register on top of invoking the getter. That way you also test that:
- The right field is actually written (i.e. if the offset is off by one, the getter will return the expected result even though the bitfield has the wrong value),
- No other field has been affected.
So something like:
pte = pte.set_present(true);
assert!(pte.present());
assert(pte.into(), 0x1u64);
pte = pte.set_writable(true);
assert!(pte.writable());
assert(pte.into(), 0x3u64);It might look a bit gross, but it is ok since these are not doctests that users are going to take as a reference, so we case improve test coverage at the detriment of readability.
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 39 lines · Alexandre Courbot
Quoted 24 lines · Joel Fernandes
Add KUNIT tests to make sure the macro is working correctly.
Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)rust/kernel/bitfield.rs +9
-0@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 ,rust/kernel/bitfield.rs fn default() -> Self { · line 423
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ Normal = 1, + Device = 2, + Reserved = 3, + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + }Tip: you can add
Defaultto the#[derive]marker ofMemoryTypeand mark the variant you want as default with#[default]instead of providing a full impl block:
Quoted 8 lines
#[derive(Debug, Default, Clone, Copy, PartialEq)]
enum MemoryType {
#[default]
Unmapped = 0,
Normal = 1,
Device = 2,
Reserved = 3,
}I would alternatively recommend to provide a MemoryType::new impl with a const definition:
```rust
impl MemoryType {
pub const fn new() -> Self {
Self::Unmapped
}
}
impl Default for MemoryType {
fn default() -> Self {
Self::new()
}
}
```This pattern allows using MemoryType::new() in const contexts, while also providing the Default impl using the same default. It's somewhat of a workaround until we get const traits.
Quoted 125 lines
Quoted 93 lines
rust/kernel/bitfield.rs +93
-0+ +impl TryFrom <u8 >for MemoryType { +type Error =u8 ; +fn try_from (value:u8 ) ->Result <Self ,Self ::Error > { +match value { +0 =>Ok (MemoryType ::Unmapped ), +1 =>Ok (MemoryType ::Normal ), +2 =>Ok (MemoryType ::Device ), +3 =>Ok (MemoryType ::Reserved ), + _ =>Err (value), + } + } + } + +impl From <MemoryType >for u64 { +fn from (mt:MemoryType ) ->u64 { + mtas u64 + } + } + +#[derive( Debug , Clone , Copy , PartialEq )] +enum Priority { +Low =0 , +Medium =1 , +High =2 , +Critical =3 , + } + +impl Default for Priority { +fn default () ->Self { +Priority ::Low + } + } + +impl From <u8 >for Priority { +fn from (value:u8 ) ->Self { +match value &0x3 { +0 =>Priority ::Low , +1 =>Priority ::Medium , +2 =>Priority ::High , + _ =>Priority ::Critical , + } + } + } + +impl From <Priority >for u16 { +fn from (p:Priority ) ->u16 { + pas u16 + } + } + +bitfield! { +struct TestPageTableEntry (u64 ) { +0 :0 presentas bool ; +1 :1 writableas bool ; +11 :9 availableas u8 ; +13 :12 mem_typeas u8 ?=>MemoryType ; +17 :14 extended_typeas u8 ?=>MemoryType ;// For testing failures +51 :12 pfnas u64 ; +51 :12 pfn_overlapas u64 ; +61 :52 available2as u16 ; + } + } + +bitfield! { +struct TestControlRegister (u16 ) { +0 :0 enableas bool ; +3 :1 modeas u8 ; +5 :4 priorityas u8 =>Priority ; +7 :4 priority_nibbleas u8 ; +15 :8 channelas u8 ; + } + } + +bitfield! { +struct TestStatusRegister (u8 ) { +0 :0 readyas bool ; +1 :1 erroras bool ; +3 :2 stateas u8 ; +7 :4 reservedas u8 ; +7 :0 full_byteas u8 ;// For entire register + } + } + +#[test] +fn test_single_bits () { +let mut pte =TestPageTableEntry ::default (); + +assert! (!pte.present ()); +assert! (!pte.writable ()); + + pte = pte.set_present (true ); +assert! (pte.present ());rust/kernel/bitfield.rs fn default() -> Self { · line 526
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ + pte = pte.set_writable (true ); +assert! (pte.writable ()); + + pte = pte.set_writable (false ); +assert! (!pte.writable ()); + +assert_eq! (pte.available (),0 ); + pte = pte.set_available (0x5 ); +assert_eq! (pte.available (),0x5 );I'd suggest testing the actual raw value of the register on top of invoking the getter. That way you also test that:
- The right field is actually written (i.e. if the offset is off by one, the getter will return the expected result even though the bitfield has the wrong value),
- No other field has been affected.So something like:
pte = pte.set_present(true); assert!(pte.present()); assert(pte.into(), 0x1u64); pte = pte.set_writable(true); assert!(pte.writable()); assert(pte.into(), 0x3u64);It might look a bit gross, but it is ok since these are not doctests that users are going to take as a reference, so we case improve test coverage at the detriment of readability.
Alexandre Courbot
maintainerRe: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 69 lines · Elle Rhumsaa
Quoted 39 lines · Alexandre Courbot
Quoted 24 lines · Joel Fernandes
Add KUNIT tests to make sure the macro is working correctly.
Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)rust/kernel/bitfield.rs +9
-0@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 ,rust/kernel/bitfield.rs fn default() -> Self { · line 423
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ Normal = 1, + Device = 2, + Reserved = 3, + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + }Tip: you can add
Defaultto the#[derive]marker ofMemoryTypeand mark the variant you want as default with#[default]instead of providing a full impl block:Quoted 8 lines
#[derive(Debug, Default, Clone, Copy, PartialEq)] enum MemoryType { #[default] Unmapped = 0, Normal = 1, Device = 2, Reserved = 3, }I would alternatively recommend to provide a
MemoryType::newimpl with aconstdefinition:```rust impl MemoryType { pub const fn new() -> Self { Self::Unmapped } } impl Default for MemoryType { fn default() -> Self { Self::new() } } ```
Quoted 3 lines
This pattern allows using
MemoryType::new()inconstcontexts, while also providing theDefaultimpl using the same default. It's somewhat of a workaround until we getconsttraits.
That's an elegant pattern generally speaking, but I don't think we would benefit from using it in these unit tests.
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 69 lines · Alexandre Courbot
Quoted 68 lines · Elle Rhumsaa
Quoted 39 lines · Alexandre Courbot
Quoted 24 lines · Joel Fernandes
Add KUNIT tests to make sure the macro is working correctly.
Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)rust/kernel/bitfield.rs +9
-0@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 ,rust/kernel/bitfield.rs fn default() -> Self { · line 423
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ Normal = 1, + Device = 2, + Reserved = 3, + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + }Tip: you can add
Defaultto the#[derive]marker ofMemoryTypeand mark the variant you want as default with#[default]instead of providing a full impl block:Quoted 8 lines
#[derive(Debug, Default, Clone, Copy, PartialEq)] enum MemoryType { #[default] Unmapped = 0, Normal = 1, Device = 2, Reserved = 3, }I would alternatively recommend to provide a
MemoryType::newimpl with aconstdefinition:```rust impl MemoryType { pub const fn new() -> Self { Self::Unmapped } } impl Default for MemoryType { fn default() -> Self { Self::new() } } ```
Quoted 5 lines
Quoted 3 lines
This pattern allows using
MemoryType::new()inconstcontexts, while also providing theDefaultimpl using the same default. It's somewhat of a workaround until we getconsttraits.That's an elegant pattern generally speaking, but I don't think we would benefit from using it in these unit tests.
*facepalm* right, I lost the context that these data structures were KUNIT-specific. Please disregard.
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
In reply to Alexandre CourbotQuoted 40 lines · Alexandre Courbot
Quoted 24 lines · Joel Fernandes
Add KUNIT tests to make sure the macro is working correctly.
Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+)rust/kernel/bitfield.rs +9
-0@@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { +use core::convert::TryFrom ; + +// Enum types for testing => and ?=> conversions +#[derive( Debug , Clone , Copy , PartialEq )] +enum MemoryType { +Unmapped =0 ,rust/kernel/bitfield.rs fn default() -> Self { · line 423
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ Normal = 1, + Device = 2, + Reserved = 3, + } + +impl Default for MemoryType { +fn default () ->Self { +MemoryType ::Unmapped + } + }Tip: you can add
Defaultto the#[derive]marker ofMemoryTypeand mark the variant you want as default with#[default]instead of providing a full impl block:
Quoted 9 lines
#[derive(Debug, Default, Clone, Copy, PartialEq)]
enum MemoryType {
#[default]
Unmapped = 0,
Normal = 1,
Device = 2,
Reserved = 3,
}Good point, changed to this.
Quoted 98 lines
Quoted 98 lines
rust/kernel/bitfield.rs +98
-0+ +impl TryFrom <u8 >for MemoryType { +type Error =u8 ; +fn try_from (value:u8 ) ->Result <Self ,Self ::Error > { +match value { +0 =>Ok (MemoryType ::Unmapped ), +1 =>Ok (MemoryType ::Normal ), +2 =>Ok (MemoryType ::Device ), +3 =>Ok (MemoryType ::Reserved ), + _ =>Err (value), + } + } + } + +impl From <MemoryType >for u64 { +fn from (mt:MemoryType ) ->u64 { + mtas u64 + } + } + +#[derive( Debug , Clone , Copy , PartialEq )] +enum Priority { +Low =0 , +Medium =1 , +High =2 , +Critical =3 , + } + +impl Default for Priority { +fn default () ->Self { +Priority ::Low + } + } + +impl From <u8 >for Priority { +fn from (value:u8 ) ->Self { +match value &0x3 { +0 =>Priority ::Low , +1 =>Priority ::Medium , +2 =>Priority ::High , + _ =>Priority ::Critical , + } + } + } + +impl From <Priority >for u16 { +fn from (p:Priority ) ->u16 { + pas u16 + } + } + +bitfield! { +struct TestPageTableEntry (u64 ) { +0 :0 presentas bool ; +1 :1 writableas bool ; +11 :9 availableas u8 ; +13 :12 mem_typeas u8 ?=>MemoryType ; +17 :14 extended_typeas u8 ?=>MemoryType ;// For testing failures +51 :12 pfnas u64 ; +51 :12 pfn_overlapas u64 ; +61 :52 available2as u16 ; + } + } + +bitfield! { +struct TestControlRegister (u16 ) { +0 :0 enableas bool ; +3 :1 modeas u8 ; +5 :4 priorityas u8 =>Priority ; +7 :4 priority_nibbleas u8 ; +15 :8 channelas u8 ; + } + } + +bitfield! { +struct TestStatusRegister (u8 ) { +0 :0 readyas bool ; +1 :1 erroras bool ; +3 :2 stateas u8 ; +7 :4 reservedas u8 ; +7 :0 full_byteas u8 ;// For entire register + } + } + +#[test] +fn test_single_bits () { +let mut pte =TestPageTableEntry ::default (); + +assert! (!pte.present ()); +assert! (!pte.writable ()); + + pte = pte.set_present (true ); +assert! (pte.present ()); + + pte = pte.set_writable (true ); +assert! (pte.writable ()); + + pte = pte.set_writable (false );
Quoted 8 lines
rust/kernel/bitfield.rs fn default() -> Self { · line 526
Quoted 5 lines
rust/kernel/bitfield.rs +5
-0+assert! (!pte.writable ()); + +assert_eq! (pte.available (),0 ); + pte = pte.set_available (0x5 ); +assert_eq! (pte.available (),0x5 );I'd suggest testing the actual raw value of the register on top of invoking the getter. That way you also test that:
Sure, I am actually doing a raw check in a few other tests, but I could do so in this one as well.
Quoted 16 lines
- The right field is actually written (i.e. if the offset is off by one, the getter will return the expected result even though the bitfield has the wrong value),
- No other field has been affected.So something like:
pte = pte.set_present(true); assert!(pte.present()); assert(pte.into(), 0x1u64); pte = pte.set_writable(true); assert!(pte.writable()); assert(pte.into(), 0x3u64);
Quoted 4 lines
It might look a bit gross, but it is ok since these are not doctests that users are going to take as a reference, so we case improve test coverage at the detriment of readability.
Ack. I will add these.
Thanks for the review! (I am assuming with these changes you're Ok with me carrying your Reviewed-by tag on this patch as well, but please let me know if there is a concern.)
- Joel
Alexandre Courbot
maintainerRe: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 20 lines · Joel Fernandes
Quoted 15 lines
- The right field is actually written (i.e. if the offset is off by one, the getter will return the expected result even though the bitfield has the wrong value),
- No other field has been affected.So something like:
pte = pte.set_present(true); assert!(pte.present()); assert(pte.into(), 0x1u64); pte = pte.set_writable(true); assert!(pte.writable()); assert(pte.into(), 0x3u64);Quoted 4 lines
It might look a bit gross, but it is ok since these are not doctests that users are going to take as a reference, so we case improve test coverage at the detriment of readability.
Quoted 5 lines
Ack. I will add these.
Thanks for the review! (I am assuming with these changes you're Ok with me carrying your Reviewed-by tag on this patch as well, but please let me know if there is a concern.)
Please do not add tags that haven't been explicitly given. If we start assuming one another's stance about patches, the trust we can have in these tags is significantly reduced.
Doing so also doesn't achieve anything in terms of efficiency; if I am ok with v3 I can give my Reviewed-by on it, and the tag can be picked up along with the patch when it is applied.
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 27 lines · Alexandre Courbot
Quoted 22 lines · Joel Fernandes
Quoted 15 lines
- The right field is actually written (i.e. if the offset is off by one, the getter will return the expected result even though the bitfield has the wrong value),
- No other field has been affected.So something like:
pte = pte.set_present(true); assert!(pte.present()); assert(pte.into(), 0x1u64); pte = pte.set_writable(true); assert!(pte.writable()); assert(pte.into(), 0x3u64);Quoted 4 lines
It might look a bit gross, but it is ok since these are not doctests that users are going to take as a reference, so we case improve test coverage at the detriment of readability.
Ack. I will add these.
Quoted 7 lines
Quoted 3 lines
Thanks for the review! (I am assuming with these changes you're Ok with me carrying your Reviewed-by tag on this patch as well, but please let me know if there is a concern.)
Please do not add tags that haven't been explicitly given. If we start assuming one another's stance about patches, the trust we can have in these tags is significantly reduced.
Oh, I thought you told me you reviewed the patch privately, but consider the tag dropped.
Quoted 4 lines
Doing so also doesn't achieve anything in terms of efficiency; if I am ok with v3 I can give my Reviewed-by on it, and the tag can be picked up along with the patch when it is applied.
Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it. Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).
Anyway thank you for the review of this patch,
Joel
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 2 lines · Joel Fernandes
Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it. Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).
If they just say they are OK with a patch, that would just mean an Acked-by, not a Reviewed-by.
In any case, the documentation states those tags cannot be added without permission -- if someone gives you a tag privately, it is best that you tell them to please send it in the mailing list instead. That way there is no confusion and others (including tooling, e.g. patchwork and b4) can see it.
Thanks!
Cheers,
Miguel
Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
Quoted 11 lines · Miguel Ojeda
Quoted 2 lines · Joel Fernandes
Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it. Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).
If they just say they are OK with a patch, that would just mean an Acked-by, not a Reviewed-by.
Quoted 1 line
In any case, the documentation states those tags cannot be added
without permission -- if someone gives you a tag privately, it is best that you tell them to please send it in the mailing list instead. That way there is no confusion and others (including tooling, e.g. patchwork and b4) can see it.
Sure, certainly it goes against docs/guidelines to add a tag *without permission*. I don't think anyone disputed that? I don't think I was advocating adding RB tags randomly without consent at all - please don't get me wrong. :-)
And no doubts that publicly replying with RB tags is the best way.
cheers,
- Joel
PATCH v5 7/9 rust: bitfield: Use 'as' operator for setter type conversion
In reply to Joel FernandesThe bitfield macro's setter accesors currently uses the From trait for type conversion, which is overly restrictive and prevents use cases such as narrowing conversions (e.g., u8 struct storage size does not work with 'as u32' for the field size).
Replace 'from' with 'as' in the setter implementation to support this.
An example of such a bitfield struct is:
bitfield! {
struct TestWideFields: u8 {
3:0 nibble as u32;
7:4 high_nibble as u32;
7:0 full as u64;
}
}Note that there is already no requirement to have the total size of all the 'as <type>' fields to be <= the struct's storage width. For example, it is already possible to have a u8 sized struct, with two 'as u8' fields. So the struct's width is already independent of the total width of the 'as uXX' instances.
--- rust/kernel/bitfield.rs | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-)
rust/kernel/bitfield.rs +34 -3
@@ -107,8 +107,6 @@ pub const fn into_raw(self) -> T {/// - Raw accessor: `raw()` - returns the underlying raw value /// - 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.
@@ -360,7 +358,9 @@ impl $name { $vis fn [<set_ $field>](mut self, value: $to_type) -> Self { const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; - let val = (<$storage>::from(value) << SHIFT) & MASK; + // Here we are potentially narrowing value from a wider bit value + // to a narrower bit value. So we have to use `as` instead of `::from()`. + let val = ((value as $storage) << SHIFT) & MASK; let new_val = (self.raw() & !MASK) | val; self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
@@ -505,6 +505,15 @@ struct TestStatusRegister(u8) { } } +// For testing wide field types on narrow storage +bitfield! { +struct TestWideFields (u8 ) { +3 :0 nibbleas u32 ; +7 :4 high_nibbleas u32 ; +7 :0 fullas u64 ; + } + } +#[test] fn test_single_bits () {let mut pte =TestPageTableEntry ::default ();
@@ -722,4 +731,26 @@ fn test_u8_bitfield() {assert_eq! (status4.reserved (),0xF );assert_eq! (status4.full_byte (),0xFF ); } + +#[test] +fn test_wide_field_types () { +let mut wf =TestWideFields ::default (); + + wf = wf.set_nibble (0x0000000F_u32 ); +assert_eq! (wf.nibble (),0x0000000F_u32 ); + + wf = wf.set_high_nibble (0x00000007_u32 ); +assert_eq! (wf.high_nibble (),0x00000007_u32 ); + + wf = wf.set_full (0xBE_u64 ); +assert_eq! (wf.full (),0xBE_u64 ); +assert_eq! (wf.raw (),0xBE_u8 ); + + wf =TestWideFields ::default () + .set_nibble (0x5_u32 ) + .set_high_nibble (0xA_u32 ); +assert_eq! (wf.raw (),0xA5_u8 ); +assert_eq! (wf.nibble (),0x5_u32 ); +assert_eq! (wf.high_nibble (),0xA_u32 ); + } }
Signature · 1 line
2.34.1
PATCH v5 8/9 rust: bitfield: Add hardening for out of bounds access
In reply to Joel FernandesSimilar to bitmap.rs, add hardening to print errors or assert if the setter API is used to write out-of-bound values.
--- rust/kernel/bitfield.rs | 32 +++++++++++++++++++++++++++++++- security/Kconfig.hardening | 9 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-)
rust/kernel/bitfield.rs +31 -1
@@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T { } } +/// Assertion macro for bitfield +#[macro_export] +macro_rules! bitfield_assert { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITFIELD_HARDENED )] + ::core::assert!($cond, $($arg)*); + +#[cfg(not( CONFIG_RUST_BITFIELD_HARDENED ))] +if !($cond) { + $crate::pr_err!($($arg)+); + } + } +} +/// Bitfield macro definition. /// Define a struct with accessors to access bits within an inner unsigned integer. ///
@@ -358,9 +372,25 @@ impl $name { $vis fn [<set_ $field>](mut self, value: $to_type) -> Self { const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; + const BITS: u32 = ($hi - $lo + 1) as u32; + const MAX_VALUE: $storage = + if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 { + !0 + } else { + (1 << BITS) - 1 + }; + + // Check for overflow - value should fit within the field's bits. // Here we are potentially narrowing value from a wider bit value // to a narrower bit value. So we have to use `as` instead of `::from()`. - let val = ((value as $storage) << SHIFT) & MASK; + let raw_field_value = value as $storage; + + $crate::bitfield_assert!( + raw_field_value <= MAX_VALUE, + "value {} exceeds {} for a {} bit field", raw_field_value, MAX_VALUE, BITS + ); + + let val = (raw_field_value << SHIFT) & MASK; let new_val = (self.raw() & !MASK) | val; self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
security/Kconfig.hardening +9 -0
@@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED If unsure, say N. +config RUST_BITFIELD_HARDENED + bool "Check integrity of bitfield Rust API" + depends on RUST + help + Enables additional assertions in the Rust Bitfield API to catch + values that exceed the bitfield bounds. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENED
Signature · 1 line
2.34.1
Yury Norov
reviewerRe: [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access
Quoted 21 lines · Joel Fernandes
Similar to
bitmap.rs, add hardening to print errors or assert if the setter API is used to write out-of-bound values.Suggested-by Yury Norov <[email protected]>Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 32 +++++++++++++++++++++++++++++++- security/Kconfig.hardening | 9 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-)rust/kernel/bitfield.rs +3
-0@@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T { } } +/// Assertion macro for bitfield +#[macro_export] +macro_rules! bitfield_assert {
rust/kernel/bitfield.rs pub const fn into_raw(self) -> T { · line 44
Quoted 10 lines
rust/kernel/bitfield.rs +10
-0+ ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITFIELD_HARDENED )] + ::core::assert!($cond, $($arg)*); + +#[cfg(not( CONFIG_RUST_BITFIELD_HARDENED ))] +if !($cond) { + $crate::pr_err!($($arg)+); + } + } +}
Can you discuss performance implication? I'm OK if you decided to make the check always on, but we need to understand the cost of it.
rust/kernel/bitfield.rs impl $name { · line 377
Quoted 10 lines
rust/kernel/bitfield.rs +3
-0/// Bitfield macro definition. /// Define a struct with accessors to access bits within an inner unsigned integer. /// @@ -358,9 +372,25 @@ impl $name { $vis fn [<set_ $field>](mut self, value: $to_type) -> Self { const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; + const BITS: u32 = ($hi - $lo + 1) as u32; + const MAX_VALUE: $storage = + if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 {
If BITS > storage then it should be a compile time error. Can you elaborate under which condition this check makes sense, and is not covered with the "(1<<BITS) - 1" case?
rust/kernel/bitfield.rs impl $name { · line 385
Quoted 8 lines
rust/kernel/bitfield.rs +6
-0+ !0 + }else { + (1 <<BITS ) -1 + }; + +// Check for overflow - value should fit within the field's bits. // Here we are potentially narrowing value from a wider bit value // to a narrower bit value. So we have to use `as` instead of `::from()`.
The new comment sounds opposite to the old one: if you check for overflow, then there's no chance to "potentially narrow the value".
This "potentially" wording simply means undefined behavior.
rust/kernel/bitfield.rs impl $name { · line 391
Quoted 7 lines
rust/kernel/bitfield.rs +6
-1-let val = ((valueas $storage) <<SHIFT ) &MASK ; +let raw_field_value = valueas $storage; + + $crate::bitfield_assert!( + raw_field_value <=MAX_VALUE , +"value {} exceeds {} for a {} bit field" , raw_field_value,MAX_VALUE ,BITS + );
Can you hide all the internals in the assertion function? Like:
$crate::bitfield_set_assert!(bitfield, field, value, "your message", ...);
We don't need assertion implementation in the main function body.
rust/kernel/bitfield.rs impl $name {
Quoted 4 lines
rust/kernel/bitfield.rs +2
-0+ +let val = (raw_field_value <<SHIFT ) &MASK ;let new_val = (self.raw () & !MASK ) | val; all the internals in the assertion self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
User wants to set an inappropriate value, and you know that because you just have tested for it. But here you're accepting a definitely wrong request. This doesn't look right.
On previous rounds you said you can't fail in setter because that would break the "chain of setters" design. I understand that, but I think that it's more important to have a clear defensive API that returns an error when people do wrong things.
So please either find a way to return an error from the setter, or some other mechanism to abort erroneous request and notify the user.
This "chain of setters" thing looks weird to me as I already said. So if it messes with a clear API, just drop it.
And to that extend,
a = a.set_field1()
looks more questionable than just
a.set_field1()
because it implies an extra copy. If I do
b = a.set_field1()
would it change the content of 'a'?
Can I do just 'a.set_field1()'? There's no such an example in your test.
Is that 'a = a.set_field()' thing really a zero-cost comparing to just 'a.set_field()'? Can you ensure it holds, say, on 32-bit machine when 'a' is a 64-bit bitfield? Would it work if we decide to support bitfields larger than 64-bit, like C does?
Thanks,
Yury
Quoted 22 lines
security/Kconfig.hardening +9
-0@@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED If unsure, say N. +config RUST_BITFIELD_HARDENED + bool "Check integrity of bitfield Rust API" + depends on RUST + help + Enables additional assertions in the Rust Bitfield API to catch + values that exceed the bitfield bounds. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENEDSignature · 1 line
2.34.1
Re: [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access
Hello, Yury,
Quoted 19 lines · Yury Norov
Quoted 18 lines · Joel Fernandes
Similar to
bitmap.rs, add hardening to print errors or assert if the setter API is used to write out-of-bound values.Suggested-by Yury Norov <[email protected]>Signed-off-by Joel Fernandes <[email protected]>--- rust/kernel/bitfield.rs | 32 +++++++++++++++++++++++++++++++- security/Kconfig.hardening | 9 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-)rust/kernel/bitfield.rs +0
-0@@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T { } }
Quoted 16 lines
rust/kernel/bitfield.rs pub const fn into_raw(self) -> T { · line 44
Quoted 13 lines
rust/kernel/bitfield.rs +13
-0+/// Assertion macro for bitfield +#[macro_export] +macro_rules! bitfield_assert { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITFIELD_HARDENED )] + ::core::assert!($cond, $($arg)*); + +#[cfg(not( CONFIG_RUST_BITFIELD_HARDENED ))] +if !($cond) { + $crate::pr_err!($($arg)+); + } + } +}Can you discuss performance implication? I'm OK if you decided to make the check always on, but we need to understand the cost of it.
Sure, so the cost is zero if either CONFIG_RUST_BITFIELD_HARDENED is disabled or the value being checked is a constant. That is, the compiler eliminates the dead code. Otherwise the cost is a single shift instruction and a single conditional jump on x86. I verified this. As such, I think it is a good idea to keep the check on.
Quoted 13 lines
rust/kernel/bitfield.rs impl $name { · line 377
Quoted 11 lines
rust/kernel/bitfield.rs +3
-0/// Bitfield macro definition. /// Define a struct with accessors to access bits within an inner unsigned integer. /// @@ -358,9 +372,25 @@ impl $name { $vis fn [<set_ $field>](mut self, value: $to_type) -> Self { const MASK: $storage = $name::[<$field:upper _MASK>]; const SHIFT: u32 = $name::[<$field:upper _SHIFT>]; + const BITS: u32 = ($hi - $lo + 1) as u32; + const MAX_VALUE: $storage = + if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 {If BITS > storage then it should be a compile time error.
Yes, that case is a compile time error.
Quoted 2 lines
Can you> elaborate under which condition this check makes sense, and is not covered with the "(1<<BITS) - 1" case?
If BITS is 64, then the else should not execute, because it would become (1 <<
64) which is UB.
I am Ok with changing the condition to: "if BITS == (::core::mem::size_of::<$storage>() * 8)" considering the compiler time error, but I am also Ok with leaving it as it is.
Quoted 10 lines
rust/kernel/bitfield.rs impl $name { · line 385
Quoted 9 lines
rust/kernel/bitfield.rs +6
-0+ !0 + }else { + (1 <<BITS ) -1 + }; + +// Check for overflow - value should fit within the field's bits. // Here we are potentially narrowing value from a wider bit value // to a narrower bit value. So we have to use `as` instead of `::from()`.
Quoted 2 lines
The new comment sounds opposite to the old one: if you check for overflow, then there's no chance to "potentially narrow the value".
No, this a compile-time issue. Even if there is no overflow, you cannot use '::from()' because it will cause a compile-time error because it is narrowing potentially a wider width (like u32) to a narrower width (like u8). It is not so much about the value itself, as much as it is about the type of value.
Quoted 11 lines
This "potentially" wording simply means undefined behavior.
rust/kernel/bitfield.rs impl $name { · line 391
Quoted 7 lines
rust/kernel/bitfield.rs +6
-1-let val = ((valueas $storage) <<SHIFT ) &MASK ; +let raw_field_value = valueas $storage; + + $crate::bitfield_assert!( + raw_field_value <=MAX_VALUE , +"value {} exceeds {} for a {} bit field" , raw_field_value,MAX_VALUE ,BITS + );
Quoted 5 lines
Can you hide all the internals in the assertion function? Like:
$crate::bitfield_set_assert!(bitfield, field, value, "your message", ...);We don't need assertion implementation in the main function body.
Why? That's more unreadable IMO. Having the condition itself in the assert, clearly shows what the condition is in the context of the surrounding code. I don't think we should more macros to do asserts when we already have a macro.
Quoted 10 lines
rust/kernel/bitfield.rs impl $name {
Quoted 5 lines
rust/kernel/bitfield.rs +2
-0+ +let val = (raw_field_value <<SHIFT ) &MASK ;let new_val = (self.raw () & !MASK ) | val; all the internals in the assertion self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);User wants to set an inappropriate value, and you know that because you just have tested for it. But here you're accepting a definitely wrong request. This doesn't look right.
Quoted 7 lines
On previous rounds you said you can't fail in setter because that would break the "chain of setters" design. I understand that, but I think that it's more important to have a clear defensive API that returns an error when people do wrong things.
So please either find a way to return an error from the setter, or some other mechanism to abort erroneous request and notify the user.
There's no way to do that other than always panicking, or introducing a new API.
There's also no way to do this at compile time, because 'value' may not always
be a constant.
I see your point, but I think since we already panicking at runtime in a hardened config (or printing an error otherwise), we already have that covered right? The user is already notified and it does not go by silently. If this is really a problem, we can always panic (in other words, always keep it as hardened config?).
Quoted 3 lines
This "chain of setters" thing looks weird to me as I already said. So if it messes with a clear API, just drop it.
I don't think we can/should drop that because this library is also used by the register macro, and that uses the setter API (I just moved this code from there). Also builder pattern is a common paradigm in Rust programs and I'd say one of the key features of the bitfield macro so we should support it.
How else will you do something like:
let status2 = TestStruct::default()
.set_ready(true)
.set_state(0x2)
.set_reserved(0x5);? :-)
As an aside, you can check literature on the builder pattern as well, it keeps code super clean and readable.
Quoted 10 lines
And to that extend,
a = a.set_field1()looks more questionable than just
a.set_field1()because it implies an extra copy.
a.set_field1() on its own wont work, because the value returned (self) is discarded.
and,
a = a.set_field1()
a = a.set_field2()
a = a.set_field3()
doesn't really do multiple copies, the compiler optimizes things and eliminates copies. I verified this in the asm as well.
Quoted 10 lines
If I do
b = a.set_field1()would it change the content of 'a'?
Can I do just '
a.set_field1()'? There's no such an example in your test.
Is that 'a =a.set_field()' thing really a zero-cost comparing to just 'a.set_field()'?
You can't do that in the current implementation, it is a NO-OP. We can certainly add a new API for that, initially I was planning to do add a 'with_field*()' accessor for the builder pattern, and do the 'set_field*()' API as you mentioned.
So it would look like:
let status2 = TestStruct::default()
.with_ready(true)
.with_state(0x2)
.with_reserved(0x5);Or one could do:
let status2 = TestStruct::default();
status2.set_ready(true);
status2.set_state(0x2);
status2.set_reserved(0x5);Would that address your concern?
Quoted 1 line
Can you ensure it holds, say, on 32-bit machine when> 'a' is a 64-bit bitfield?
I don't think this is an issue. If the user writes a = a.set_fieldXX() multiple times, it will be optimized as I mentioned above. I have verified (in release builds) that the compiler does not create multiple intermediate copies.
Quoted 1 line
Would it work if we decide to support bitfields larger than 64-bit, like C does?
Certainly, the struct has the Copy trait. 'a = a.set_field()' will work for larger than 64-bit just fine, if/when we support it. I verified that as well.
thanks,
- Joel
Quoted 25 lines
Thanks,
YuryQuoted 22 lines
security/Kconfig.hardening +9
-0@@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED If unsure, say N. +config RUST_BITFIELD_HARDENED + bool "Check integrity of bitfield Rust API" + depends on RUST + help + Enables additional assertions in the Rust Bitfield API to catch + values that exceed the bitfield bounds. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENEDSignature · 1 line
2.34.1
PATCH v5 9/9 rust: bitfield: Add hardening for undefined bits
In reply to Joel FernandesWhen creating a new bitfield, it is possible that the value contains bits set. Such usage can be the result of an error in the usage of the bitfield. Print an error in regular configs, and assert in a hardened config (CONFIG_RUST_BITFIELD_HARDENED). If the design is deliberate, the user may silence these errors or assertions by defining the bitfield as reserved.
--- rust/kernel/bitfield.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
rust/kernel/bitfield.rs +19 -1
@@ -117,7 +117,9 @@ macro_rules! bitfield_assert {/// ``` /// /// This generates a struct with: -/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits +/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits. +/// If any of the bits passed are set, but not defined as a bitfield, an error is printed. +/// To silence these errors, either define all fields or initialize the bit positions to 0. /// - Raw accessor: `raw()` - returns the underlying raw value /// - Field accessors: `mode()`, `state()`, etc. /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
@@ -236,6 +238,10 @@ impl $name {/// This constructor zeros out all bits that are not defined by any field, /// ensuring only valid field bits are preserved. This is to prevent UB /// when raw() is used to retrieve undefined bits. +/// +/// If any of the bits passed are set, but not defined as a bitfield, +/// an error is printed. To silence these errors, either define all fields +/// or initialize the respective bit positions to 0. #[inline(always)] $vis fn new(value: $storage) -> Self {// Calculate mask for all defined fields
@@ -245,6 +251,18 @@ impl $name { mask |= Self::[<$field:upper _MASK>]; ); )* + +// Check if any undefined bits are set + $crate::bitfield_assert!( + (value & !mask) ==0 , +concat! ( +"Value 0x{:x} has bits set outside of defined field ranges " , +"(mask: 0x{:x}). To avoid this assertion, either define all " , +"fields or initialize unused bits to 0." + ), + value, mask + ); +// Zero out undefined bits and wrap in BitfieldInternalStorage Self (::kernel::bitfield::BitfieldInternalStorage ::from_raw (value & mask)) }
Signature · 1 line
2.34.1
Danilo Krummrich
maintainerQuoted 5 lines · Joel Fernandes
MAINTAINERS | 7 + drivers/gpu/nova-core/falcon.rs | 2 +- drivers/gpu/nova-core/falcon/gsp.rs | 4 +- drivers/gpu/nova-core/falcon/sec2.rs | 2 +- drivers/gpu/nova-core/regs.rs | 6 +-
Quoted 8 lines
rust/kernel/bitfield.rs | 804 ++++++++++++++++++ rust/kernel/io.rs | 1 + .../macros.rs => rust/kernel/io/register.rs | 317 +------ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 9 + 10 files changed, 870 insertions(+), 283 deletions(-) create mode 100644 rust/kernel/bitfield.rs rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (72%)
I think we have at least three or four potential target trees for this:
driver-core (I/O), drm-rust (Nova), bitmap / Rust.
(I don't know which tree the bitmap stuff would go through, I did not find a tree entry in the MAINTAINERS file.)
Unless someone thinks otherwise, I'd take it through the drm-rust tree once the series is ready. This should cause the least conflicts and as a bonus enable Tyr to use it right away.
Alexandre Courbot
maintainerQuoted 7 lines · Joel Fernandes
Hello!
These patches extract and enhance the bitfield support in the register macro in nova to define Rust structures with bitfields. It then moves out the bitfield support into the kenrel crate and further enhances it. This is extremely useful as it allows clean Rust structure definitions without requiring explicit masks and shifts.
The extraction and move in themselves (patches 1-4 and maybe the KUNIT one) look good to me. For the remainder, it will depend on whether the BoundedInt idea sticks or not as it changes the design in a way that makes most of these patches unneeded. In any case I think this can be worked on after the split and extraction.
Patch 5 should probably be dropped as it has the potential to clear register fields that are useful to the hardware but have no entry in the register! definition, making read-update-write updates of registers unpredictable.
Alexandre Courbot
maintainerQuoted 15 lines · Alexandre Courbot
Quoted 7 lines · Joel Fernandes
Hello!
These patches extract and enhance the bitfield support in the register macro in nova to define Rust structures with bitfields. It then moves out the bitfield support into the kenrel crate and further enhances it. This is extremely useful as it allows clean Rust structure definitions without requiring explicit masks and shifts.
The extraction and move in themselves (patches 1-4 and maybe the KUNIT one) look good to me. For the remainder, it will depend on whether the BoundedInt idea sticks or not as it changes the design in a way that makes most of these patches unneeded. In any case I think this can be worked on after the split and extraction.
Quoted 4 lines
Patch 5 should probably be dropped as it has the potential to clear register fields that are useful to the hardware but have no entry in the
register!definition, making read-update-write updates of registers unpredictable.
Ah, I forgot: please base the next revision on top of drm-rust-next as we are likely to apply it there.
Quoted 10 lines · Alexandre Courbot
Quoted 9 lines · Alexandre Courbot
Quoted 7 lines · Joel Fernandes
Hello!
These patches extract and enhance the bitfield support in the register macro in nova to define Rust structures with bitfields. It then moves out the bitfield support into the kenrel crate and further enhances it. This is extremely useful as it allows clean Rust structure definitions without requiring explicit masks and shifts.
Quoted 5 lines
Quoted 5 lines
The extraction and move in themselves (patches 1-4 and maybe the KUNIT one) look good to me. For the remainder, it will depend on whether the BoundedInt idea sticks or not as it changes the design in a way that makes most of these patches unneeded. In any case I think this can be worked on after the split and extraction.
Sure.
Quoted 8 lines
Quoted 5 lines
Patch 5 should probably be dropped as it has the potential to clear register fields that are useful to the hardware but have no entry in the
register!definition, making read-update-write updates of registers unpredictable.Ah, I forgot: please base the next revision on top of drm-rust-next as we are likely to apply it there.
Done, I rebased on top of drm-rust-next, commit: 299eb32863e5 ("gpu: nova-core:
Add base files for r570.144 firmware bindings")
I will send the v6 out shortly with just the patches to be included.
Thanks.