rust: add `bitfield!` macro
Subsystems (6)
Alexandre Courbot
maintainerv5 cover rust: add `bitfield!` macro
This is the continuation of the bitfield! macro which started alongside the register! one before being temporarily integrated into it [1].
This series extracts bitfield! from register!, adds unit tests for the new macro, and replaces the register! macro rules with the extracted version.
I have removed the nova-core patches, because the Blackwell support that has been added this cycle (and thus not visible from rust-next) introduces more uses of the Nova-local bitfield! macro that this series intended to remove. If these new uses are not updated, then nova-core won't build, thus to avoid conflicts and/or build breakages I think it is preferable to merge them during the next cycle.
This version is based on rust-next, with [2] applied.
A tree with this branch and its dependencies is available at [3].
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://github.com/Gnurou/linux/tree/b4/bitfield
---
Changes in v5:
- Squash the fixup patches into the one extracting the bitfield! macro.
- Remove the nova-core patches to avoid a conflict/build breakage on -rc1.
- Improve the unit tests per Yury's feedback:
- Use a consistent test axis where each test focuses on a single thing.
- Rename members to generic name including range for readability.
- Add test exercising try_with.
- Add test checking that unallocated bits are left untouched.
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Inline private bitfield accessor methods.
- Fully qualify types in bitfield! macro.
- Rename RUST_KERNEL_BITFIELD_KUNIT_TEST to RUST_BITFIELD_KUNIT_TEST.
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Split patch 1 into the addition of the bitfield! macro and its use in the io module.
- Mention reserved field names in bitfield!'s doccomment.
- Properly order fields in the KUnit test.
- Add a Kconfig option for building the KUnit tests.
- Document behavior on non-covered bits.
- Document support for signed fields and storage types (TL;DR: not supported).
- Move nova-core's bitfield module deletion into its own patch.
- Link to v2: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (2):
rust: extract bitfield! macro from register!
rust: io: use the bitfield! macro in register!
Joel Fernandes (1):
rust: bitfield: Add KUnit tests for bitfield
MAINTAINERS | 7 + rust/kernel/Kconfig.test | 10 + rust/kernel/bitfield.rs | 862 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/io/register.rs | 246 +------------ rust/kernel/lib.rs | 1 + 5 files changed, 882 insertions(+), 244 deletions(-)
---
base-commit: 72d33b8bfeacbfdccf2cda4650e8e002def036f8
change-id: 20260408-bitfield-6e18254f4fdc
prerequisite-message-id: [email protected]
prerequisite-patch-id: 403e34bb92b42d3f31ed972e11896d18902585e3
prerequisite-patch-id: 42ae775aa6762a9e28ff31c5f69a0b65a7b40dcc
prerequisite-patch-id: 19b3e535962348f7627ede57ea829b34abda08c7
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v5 1/3 rust: extract `bitfield!` macro from `register!`
Extract the bitfield-defining part of the register! macro into an independent macro used to define bitfield types with bounds-checked accessors.
Each field is represented as a Bounded of the appropriate bit width, ensuring field values are never silently truncated.
Fields can optionally be converted to/from custom types, either fallibly or infallibly.
Appropriate documentation is also added, and a MAINTAINERS entry created for the new module.
Two minor fixups are also applied: the private accessors are inlined, and a couple of missing fully qualified types in the macro are fixed.
--- MAINTAINERS | 7 + rust/kernel/bitfield.rs | 548 ++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 556 insertions(+)
MAINTAINERS +7 -0
@@ -23422,6 +23422,13 @@ T: git https://github.com/Rust-for-Linux/linux.git alloc-next F: rust/kernel/alloc.rs F: rust/kernel/alloc/ +RUST [BITFIELD] +M: Alexandre Courbot <[email protected]> +R: Yury Norov <[email protected]> +L: [email protected] +S: Maintained +F: rust/kernel/bitfield.rs + RUST [INTEROP] M: Joel Fernandes <[email protected]> M: Alexandre Courbot <[email protected]>
rust/kernel/bitfield.rs new file +548 -0
548 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -44,6 +44,7 @@pub mod alloc;#[cfg( CONFIG_AUXILIARY_BUS )] pub mod auxiliary; +pub mod bitfield;pub mod bitmap;pub mod bits;#[cfg( CONFIG_BLOCK )]
Signature · 1 line
2.54.0
Alexandre Courbot
maintainerPATCH v5 2/3 rust: bitfield: Add KUnit tests for bitfield
In reply to Alexandre CourbotFrom: Joel Fernandes <[email protected]>
Add KUnit tests to make sure the macro is working correctly. The unit tests are put behind the new RUST_BITFIELD_KUNIT_TEST Kconfig option.
[acourbot:
- Use a consistent test axis where each test focuses on a single thing.
- Rename members to generic name including range for readability.
- Add test exercising try_with.
- Add test checking that unallocated bits are left untouched. ]
--- rust/kernel/Kconfig.test | 10 ++ rust/kernel/bitfield.rs | 314 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 324 insertions(+)
rust/kernel/Kconfig.test +10 -0
@@ -73,4 +73,14 @@ config RUST_ATOMICS_KUNIT_TEST If unsure, say N. +config RUST_BITFIELD_KUNIT_TEST + bool "KUnit tests for the Rust `bitfield!` macro" if !KUNIT_ALL_TESTS + default KUNIT_ALL_TESTS + help + This option enables KUnit tests for the Rust `bitfield!` macro. + These are only for development and testing, not for regular + kernel use cases. + + If unsure, say N. + endif
rust/kernel/bitfield.rs +314 -0
317 lines not on this page · raw message
Signature · 1 line
2.54.0
Alexandre Courbot
maintainerRe: [PATCH v5 2/3] rust: bitfield: Add KUnit tests for bitfield
On Sat Jun 6, 2026 at 9:43 PM JST, Alexandre Courbot wrote:
<...>
rust/kernel/bitfield.rs fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kernel::fmt::Result { · line 551
Quoted 11 lines
rust/kernel/bitfield.rs +3
-0@@ -546,3 +546,317 @@ fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kernel::fmt::Result { } }; } + +#[cfg( CONFIG_RUST_BITFIELD_KUNIT_TEST )] +#[::kernel::macros::kunit_tests(kernel_bitfield)]
Looking at the other tests, this should maybe be named rust_kernel_bitfield.
Alexandre Courbot
maintainerPATCH v5 3/3 rust: io: use the `bitfield!` macro in `register!`
In reply to Alexandre CourbotReplace the local bitfield rules by the equivalent invocation of the bitfield! macro.
No functional change should be introduced as the bitfield! macro has been extracted from the rules of register!.
--- rust/kernel/io/register.rs | 246 +-------------------------------------------- 1 file changed, 2 insertions(+), 244 deletions(-)
rust/kernel/io/register.rs +2 -244
@@ -956,11 +956,10 @@ macro_rules! register { ( @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* } ) => { - $crate::register!(@bitfield_core + $crate::bitfield!(#[allow(non_camel_case_types)] - $(#[$attr] )* $vis $name $storage + $(#[$attr] )* $visstruct $name($storage) { $($fields)* } ); - $crate::register!(@bitfield_fields $vis $name $storage { $($fields)* }); };// Implementations shared by all registers types.
@@ -1016,245 +1015,4 @@ impl $crate::io::register::RegisterArray for $name {impl $crate::io::register::RelativeRegisterArray for $name {} }; - -// Defines the wrapper `$name` type and its conversions from/to the storage type. - (@bitfield_core $(#[$attr:meta])* $vis:vis $name:ident $storage:ty) => { - $(#[$attr])* - #[repr(transparent)] - #[derive(Clone, Copy, PartialEq, Eq)] - $vis struct $name { - inner: $storage, - } - - #[allow(dead_code)] - impl $name { - /// Creates a bitfield from a raw value. - #[inline(always)] - $vis const fn from_raw(value: $storage) -> Self { - Self{ inner: value } - } - - /// Turns this bitfield into its raw value. - /// - /// This is similar to the [`From`] implementation, but is shorter to invoke in - /// most cases. - #[inline(always)] - $vis const fn into_raw(self) -> $storage { - self.inner - } - } - - // SAFETY: `$storage` is `Zeroable` and `$name` is transparent. - unsafe impl ::pin_init::Zeroable for $name {} - - impl ::core::convert::From<$name> for $storage { - #[inline(always)] - fn from(val: $name) -> $storage { - val.into_raw() - } - } - - impl ::core::convert::From<$storage> for $name { - #[inline(always)] - fn from(val: $storage) -> $name { - Self::from_raw(val) - } - } - }; - - // Definitions requiring knowledge of individual fields: private and public field accessors, - // and `Debug` implementation. - (@bitfield_fields $vis:vis $name:ident $storage:ty { - $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident - $(?=> $try_into_type:ty)? - $(=> $into_type:ty)? - ; - )* - } - ) => { - #[allow(dead_code)] - impl $name { - $( - $crate::register!(@private_field_accessors $vis $name $storage : $hi:$lo $field); - $crate::register!( - @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field - $(?=> $try_into_type)? - $(=> $into_type)? - ); - )* - } - - $crate::register!(@debug $name { $($field;)* }); - }; - - // Private field accessors working with the exact `Bounded` type for the field. - ( - @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident - ) => { - ::kernel::macros::paste!( - $vis const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi; - $vis const [<$field:upper _MASK>]: $storage = - ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1); - $vis const [<$field:upper _SHIFT>]: u32 = $lo; - ); - - ::kernel::macros::paste!( - fn [<__ $field>](self) -> - ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> { - // Left shift to align the field's MSB with the storage MSB. - const ALIGN_TOP: u32 = $storage::BITS - ($hi + 1); - // Right shift to move the top-aligned field to bit 0 of the storage. - const ALIGN_BOTTOM: u32 = ALIGN_TOP + $lo; - - // Extract the field using two shifts. `Bounded::shr` produces the correctly-sized - // output type. - let val = ::kernel::num::Bounded::<$storage, { $storage::BITS }>::from( - self.inner << ALIGN_TOP - ); - val.shr::<ALIGN_BOTTOM, { $hi + 1 - $lo } >() - } - - const fn [<__with_ $field>]( - mut self, - value: ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>, - ) -> Self - { - const MASK: $storage = <$name>::[<$field:upper _MASK>]; - const SHIFT: u32 = <$name>::[<$field:upper _SHIFT>]; - - let value = value.get() << SHIFT; - self.inner = (self.inner & !MASK) | value; - - self - } - ); - }; - - // Public accessors for fields infallibly (`=>`) converted to a type. - ( - @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : - $hi:literal:$lo:literal $field:ident => $into_type:ty - ) => { - ::kernel::macros::paste!( - - $(#[doc = $doc])* - #[doc = "Returns the value of this field."] - #[inline(always)] - $vis fn $field(self) -> $into_type - { - self.[<__ $field>]().into() - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the given `value`."] - #[inline(always)] - $vis fn [<with_ $field>](self, value: $into_type) -> Self - { - self.[<__with_ $field>](value.into()) - } - - ); - }; - - // Public accessors for fields fallibly (`?=>`) converted to a type. - ( - @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : - $hi:tt:$lo:tt $field:ident ?=> $try_into_type:ty - ) => { - ::kernel::macros::paste!( - - $(#[doc = $doc])* - #[doc = "Returns the value of this field."] - #[inline(always)] - $vis fn $field(self) -> - Result< - $try_into_type, - <$try_into_type as ::core::convert::TryFrom< - ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> - >>::Error - > - { - self.[<__ $field>]().try_into() - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the given `value`."] - #[inline(always)] - $vis fn [<with_ $field>](self, value: $try_into_type) -> Self - { - self.[<__with_ $field>](value.into()) - } - - ); - }; - - // Public accessors for fields not converted to a type. - ( - @public_field_accessors $(#[doc = $doc:expr])* $vis:vis $name:ident $storage:ty : - $hi:tt:$lo:tt $field:ident - ) => { - ::kernel::macros::paste!( - - $(#[doc = $doc])* - #[doc = "Returns the value of this field."] - #[inline(always)] - $vis fn $field(self) -> - ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> - { - self.[<__ $field>]() - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the compile-time constant `VALUE`."] - #[inline(always)] - $vis const fn [<with_const_ $field>]<const VALUE: $storage>(self) -> Self { - self.[<__with_ $field>]( - ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::new::<VALUE>() - ) - } - - $(#[doc = $doc])* - #[doc = "Sets this field to the given `value`."] - #[inline(always)] - $vis fn [<with_ $field>]<T>( - self, - value: T, - ) -> Self - where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>>, - { - self.[<__with_ $field>](value.into()) - } - - $(#[doc = $doc])* - #[doc = "Tries to set this field to `value`, returning an error if it is out of range."] - #[inline(always)] - $vis fn [<try_with_ $field>]<T>( - self, - value: T, - ) -> ::kernel::error::Result<Self> - where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $lo }>, - { - Ok( - self.[<__with_ $field>]( - value.try_into_bounded().ok_or(::kernel::error::code::EOVERFLOW)? - ) - ) - } - - ); - }; - - // `Debug` implementation. - (@debug $name:ident { $($field:ident;)* }) => { - impl ::kernel::fmt::Debug for $name { - fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kernel::fmt::Result { - f.debug_struct(stringify!($name)) - .field("<raw>", &::kernel::prelude::fmt!("{:#x}", self.inner)) - $( - .field(stringify!($field), &self.$field()) - )* - .finish() - } - } - }; }
Signature · 1 line
2.54.0
Miguel Ojeda
AppliedQuoted 18 lines · Alexandre Courbot
This is the continuation of the
bitfield!macro which started alongside theregister!one before being temporarily integrated into it [1].This series extracts
bitfield!fromregister!, adds unit tests for the new macro, and replaces theregister!macro rules with the extracted version.I have removed the
nova-corepatches, because the Blackwell support that has been added this cycle (and thus not visible fromrust-next) introduces more uses of the Nova-localbitfield!macro that this series intended to remove. If these new uses are not updated, thennova-corewon't build, thus to avoid conflicts and/or build breakages I think it is preferable to merge them during the next cycle.This version is based on
rust-next, with [2] applied.
Quoted 7 lines
A tree with this branch and its dependencies is available at [3].
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://github.com/Gnurou/linux/tree/b4/bitfieldSigned-off-by Alexandre Courbot <[email protected]>
Applied to rust-next -- thanks everyone!
[ Added some more intra-doc links. - Miguel ]
[ Prefixed test suite name with rust_ as mentioned. Markdown-formatted
a few comments with Markdown. - Miguel ]
Cheers,
Miguel
Quoted 17 lines · Alexandre Courbot
This is the continuation of the
bitfield!macro which started alongside theregister!one before being temporarily integrated into it [1].This series extracts
bitfield!fromregister!, adds unit tests for the new macro, and replaces theregister!macro rules with the extracted version.I have removed the
nova-corepatches, because the Blackwell support that has been added this cycle (and thus not visible fromrust-next) introduces more uses of the Nova-localbitfield!macro that this series intended to remove. If these new uses are not updated, thennova-corewon't build, thus to avoid conflicts and/or build breakages I think it is preferable to merge them during the next cycle.This version is based on
rust-next, with [2] applied.
Quoted 7 lines
A tree with this branch and its dependencies is available at [3].
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://github.com/Gnurou/linux/tree/b4/bitfieldSigned-off-by Alexandre Courbot <[email protected]>
Thanks for the work!
Quoted 55 lines
---
Changes in v5:
- Squash the fixup patches into the one extracting thebitfield!macro.
- Remove thenova-corepatches to avoid a conflict/build breakage on -rc1.
- Improve the unit tests per Yury's feedback:
- Use a consistent test axis where each test focuses on a single thing.
- Rename members to generic name including range for readability.
- Add test exercisingtry_with.
- Add test checking that unallocated bits are left untouched.
- Link to v4: https://patch.msgid.link/[email protected]Changes in v4:
- Inline private bitfield accessor methods.
- Fully qualify types inbitfield!macro.
- RenameRUST_KERNEL_BITFIELD_KUNIT_TESTtoRUST_BITFIELD_KUNIT_TEST.
- Link to v3: https://patch.msgid.link/[email protected]Changes in v3:
- Split patch 1 into the addition of thebitfield!macro and its use in theiomodule.
- Mention reserved field names inbitfield!'s doccomment.
- Properly order fields in the KUnit test.
- Add aKconfigoption for building the KUnit tests.
- Document behavior on non-covered bits.
- Document support for signed fields and storage types (TL;DR: not supported).
- Movenova-core'sbitfieldmodule deletion into its own patch.
- Link to v2: https://patch.msgid.link/[email protected]---
Alexandre Courbot (2):
rust: extractbitfield!macro fromregister!
rust: io: use thebitfield!macro inregister!Joel Fernandes (1):
rust: bitfield: Add KUnit tests for bitfieldMAINTAINERS | 7 + rust/kernel/Kconfig.test | 10 + rust/kernel/bitfield.rs | 862 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/io/register.rs | 246 +------------ rust/kernel/lib.rs | 1 + 5 files changed, 882 insertions(+), 244 deletions(-)---
base-commit:72d33b8bfeacbfdccf2cda4650e8e002def036f8
change-id: 20260408-bitfield-6e18254f4fdc
prerequisite-message-id: [email protected]
prerequisite-patch-id:403e34bb92b42d3f31ed972e11896d18902585e3
prerequisite-patch-id:42ae775aa6762a9e28ff31c5f69a0b65a7b40dcc
prerequisite-patch-id:19b3e535962348f7627ede57ea829b34abda08c7Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Quoted 4 lines · Yury Norov
Thanks for the work!
Reviewed-by Yury Norov <[email protected]>
Given you are the R: and it was just a day in next, I decided to rebase to add the tag.
Thanks for taking a look!
Cheers,
Miguel