Skip to contentSkip to conversation

rust: bitfield: add conversions to Bounded of matching width

PATCH Applied Alexandre Courbot 6 participants 8 messages Nov 27 – Dec 2

Subsystems (5)
lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

PATCH 1/1 rust: bitfield: add conversions to Bounded of matching width

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

---
 drivers/gpu/drm/tyr/regs.rs | 30 +++++------------
 rust/kernel/bitfield.rs     | 82 ++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 89 insertions(+), 23 deletions(-)
drivers/gpu/drm/tyr/regs.rs +8 -22
index 69c901afb28f..0392869adc5a 100644
@@ -1150,20 +1150,6 @@ struct MMU_MEMATTR_STAGE1(u8) {
             }
         }
 
-        impl TryFrom<Bounded<u64, 8>> for MMU_MEMATTR_STAGE1 {
-            type Error = Error;
-
-            fn try_from(val: Bounded<u64, 8>) -> Result<Self, Self::Error> {
-                Ok(Self::from_raw(val.get() as u8))
-            }
-        }
-
-        impl From<MMU_MEMATTR_STAGE1> for Bounded<u64, 8> {
-            fn from(val: MMU_MEMATTR_STAGE1) -> Self {
-                Bounded::try_new(u64::from(val.into_raw())).unwrap()
-            }
-        }
-
         register! {
             base: TyrRegisters;
 
@@ -1172,14 +1158,14 @@ fn from(val: MMU_MEMATTR_STAGE1) -> Self {
             /// Each address space can configure up to 8 different memory attribute profiles.
             /// Each attribute profile follows the MMU_MEMATTR_STAGE1 layout.
             pub(crate) MEMATTR(u64)[MAX_AS, stride = STRIDE] @ 0x2408 {
-                7:0     attribute0 ?=> MMU_MEMATTR_STAGE1;
-                15:8    attribute1 ?=> MMU_MEMATTR_STAGE1;
-                23:16   attribute2 ?=> MMU_MEMATTR_STAGE1;
-                31:24   attribute3 ?=> MMU_MEMATTR_STAGE1;
-                39:32   attribute4 ?=> MMU_MEMATTR_STAGE1;
-                47:40   attribute5 ?=> MMU_MEMATTR_STAGE1;
-                55:48   attribute6 ?=> MMU_MEMATTR_STAGE1;
-                63:56   attribute7 ?=> MMU_MEMATTR_STAGE1;
+                7:0     attribute0 => MMU_MEMATTR_STAGE1;
+                15:8    attribute1 => MMU_MEMATTR_STAGE1;
+                23:16   attribute2 => MMU_MEMATTR_STAGE1;
+                31:24   attribute3 => MMU_MEMATTR_STAGE1;
+                39:32   attribute4 => MMU_MEMATTR_STAGE1;
+                47:40   attribute5 => MMU_MEMATTR_STAGE1;
+                55:48   attribute6 => MMU_MEMATTR_STAGE1;
+                63:56   attribute7 => MMU_MEMATTR_STAGE1;
             }
 
             // MEMATTR is a logical 64-bit register, but it is laid out in hardware as two
rust/kernel/bitfield.rs +81 -1

112 lines not on this page · raw message

---
base-commit: abfb640b2374e26de8ff81d488c39d8254db538e
change-id: 20261127-bitfield-conversions-e5a6b02f0ac4

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
reviewer Reviewed-by on v1 1/1
#2 lore raw
In reply to Alexandre Courbot
Quoted 19 lines · Alexandre Courbot

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }
Quoted 6 lines

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

Quoted 4 lines
---
 drivers/gpu/drm/tyr/regs.rs | 30 +++++------------
 rust/kernel/bitfield.rs     | 82 ++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 89 insertions(+), 23 deletions(-)
Reviewed-by on v1 1/1
#3 lore raw
In reply to Alexandre Courbot
Quoted 19 lines · Alexandre Courbot

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }
Quoted 6 lines

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

Quoted 182 lines
---
 drivers/gpu/drm/tyr/regs.rs | 30 +++++------------
 rust/kernel/bitfield.rs     | 82 ++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 89 insertions(+), 23 deletions(-)
drivers/gpu/drm/tyr/regs.rs +8 -22
index 69c901afb28f..0392869adc5a 100644
@@ -1150,20 +1150,6 @@ struct MMU_MEMATTR_STAGE1(u8) {
             }
         }
 
-        impl TryFrom<Bounded<u64, 8>> for MMU_MEMATTR_STAGE1 {
-            type Error = Error;
-
-            fn try_from(val: Bounded<u64, 8>) -> Result<Self, Self::Error> {
-                Ok(Self::from_raw(val.get() as u8))
-            }
-        }
-
-        impl From<MMU_MEMATTR_STAGE1> for Bounded<u64, 8> {
-            fn from(val: MMU_MEMATTR_STAGE1) -> Self {
-                Bounded::try_new(u64::from(val.into_raw())).unwrap()
-            }
-        }
-
         register! {
             base: TyrRegisters;
 
@@ -1172,14 +1158,14 @@ fn from(val: MMU_MEMATTR_STAGE1) -> Self {
             /// Each address space can configure up to 8 different memory attribute profiles.
             /// Each attribute profile follows the MMU_MEMATTR_STAGE1 layout.
             pub(crate) MEMATTR(u64)[MAX_AS, stride = STRIDE] @ 0x2408 {
-                7:0     attribute0 ?=> MMU_MEMATTR_STAGE1;
-                15:8    attribute1 ?=> MMU_MEMATTR_STAGE1;
-                23:16   attribute2 ?=> MMU_MEMATTR_STAGE1;
-                31:24   attribute3 ?=> MMU_MEMATTR_STAGE1;
-                39:32   attribute4 ?=> MMU_MEMATTR_STAGE1;
-                47:40   attribute5 ?=> MMU_MEMATTR_STAGE1;
-                55:48   attribute6 ?=> MMU_MEMATTR_STAGE1;
-                63:56   attribute7 ?=> MMU_MEMATTR_STAGE1;
+                7:0     attribute0 => MMU_MEMATTR_STAGE1;
+                15:8    attribute1 => MMU_MEMATTR_STAGE1;
+                23:16   attribute2 => MMU_MEMATTR_STAGE1;
+                31:24   attribute3 => MMU_MEMATTR_STAGE1;
+                39:32   attribute4 => MMU_MEMATTR_STAGE1;
+                47:40   attribute5 => MMU_MEMATTR_STAGE1;
+                55:48   attribute6 => MMU_MEMATTR_STAGE1;
+                63:56   attribute7 => MMU_MEMATTR_STAGE1;
             }
 
             // MEMATTR is a logical 64-bit register, but it is laid out in hardware as two
rust/kernel/bitfield.rs +81 -2
index 8d7d78175336..f53001a41731 100644
@@ -78,7 +78,8 @@
 //! every value assigned to a field. This ensures that data is never accidentally truncated.
 //!
 //! The macro generates the bitfield type, [`From`] and [`Into`] implementations for its storage
-//! type, as well as [`Debug`] and [`Zeroable`](pin_init::Zeroable) implementations.
+//! type and for any [`Bounded`] with the same number of bits as its storage type, as well as
+//! [`Debug`] and [`Zeroable`](pin_init::Zeroable) implementations.
 //!
 //! For each field, it also generates:
 //!
@@ -249,6 +250,37 @@
 //! assert_eq!(Config::from(0b11).mode(), Err(3));
 //! ```
 //!
+//! ## Nested bitfields
+//!
+//! A bitfield type can be converted from and into any [`Bounded`] with exactly as many bits as
+//! its storage type. Thus, it can be used with `=>` as the type of a field of the same width in
+//! another bitfield:
+//!
+//! ```rust
+//! use kernel::bitfield;
+//!
+//! bitfield! {
+//!     pub struct Version(u8) {
+//!         7:4 major;
+//!         3:0 minor;
+//!     }
+//! }
+//!
+//! bitfield! {
+//!     pub struct Id(u16) {
+//!         15:8 vendor;
+//!         7:0 version => Version;
+//!     }
+//! }
+//!
+//! let id = Id::from_raw(0x10_42);
+//! assert_eq!(id.version().major(), 0x4);
+//! assert_eq!(id.version().minor(), 0x2);
+//!
+//! let id = id.with_version(Version::zeroed().with_const_major::<0x1>());
+//! assert_eq!(id.into_raw(), 0x10_10);
+//! ```
+//!
 //! # Bits outside of declared fields
 //!
 //! Bits of the storage type that are not part of any declared field are preserved by the setter
@@ -346,6 +378,31 @@ fn from(val: $storage) -> $name {
             }
         }
 
+        // Conversions from/to any `Bounded` with the exact same width as `$storage`, to allow
+        // infallible nested bitfields.
+
+        impl<T> ::core::convert::From<$crate::num::Bounded<T, { <$storage>::BITS }>> for $name
+        where
+            T: $crate::num::Integer,
+            $storage: ::core::convert::From<$crate::num::Bounded<T, { <$storage>::BITS }>>,
+        {
+            #[inline(always)]
+            fn from(val: $crate::num::Bounded<T, { <$storage>::BITS }>) -> $name {
+                Self::from_raw(val.into())
+            }
+        }
+
+        impl<T> ::core::convert::From<$name> for $crate::num::Bounded<T, { <$storage>::BITS }>
+        where
+            T: $crate::num::Integer,
+            Self: ::core::convert::From<$storage>,
+        {
+            #[inline(always)]
+            fn from(val: $name) -> Self {
+                val.into_raw().into()
+            }
+        }
+
         // SAFETY: `$name` is transparent over `$storage` and `$storage` has no interior mutability.
         unsafe impl $crate::mem::AsRepr for $name {
             // Normalize `$storage` to the canonical repr type in case it is signed.
@@ -653,6 +710,14 @@ struct TestU8(u8) {
         }
     }
 
+    bitfield! {
+        struct TestNested(u32) {
+            31:16     field_31_16 => TestU16;
+            15:8      field_15_8;
+            7:0       field_7_0 => TestU8;
+        }
+    }
+
     // Single and multi-bit fields basic access.
     #[test]
     fn test_basic_access() {
@@ -770,6 +835,21 @@ fn test_fallible_conversion() {
         assert_eq!(TestU64::from_raw(raw).field_15_12(), Err(0x7));
     }
 
+    // `=>` conversion from/to another bitfield with the same width as the field.
+    #[test]
+    fn test_nested_bitfield() {
+        let val = TestNested::from_raw(0x42AB_00AF);
+        assert_eq!(val.field_31_16(), TestU16::from_raw(0x42AB));
+        assert_eq!(val.field_31_16().field_15_8(), 0x42);
+        assert_eq!(val.field_7_0(), TestU8::from_raw(0xAF));
+        assert_eq!(val.field_7_0().field_7_4(), 0xA);
+
+        let val = val
+            .with_field_31_16(TestU16::zeroed().with_const_field_3_1::<0x5>())
+            .with_field_7_0(TestU8::zeroed().with_field_0(true));
+        assert_eq!(val.into_raw(), 0x000A_0001);
+    }
+
     // Test that setting an overlapping field affects the overlapped one as expected.
     #[test]
     fn test_overlapping_fields() {
 
---

base-commit: abfb640b2374e26de8ff81d488c39d8254db538e
change-id: 20261127-bitfield-conversions-e5a6b02f0ac4

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
maintainer Applied
#4 lore raw
In reply to Alexandre Courbot
Quoted 20 lines · On Fri, 27 Nov 2026 21:05:40 +0900 Alexandre Courbot <[email protected]>…

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }
Quoted 6 lines

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

Applied to rust-next -- thanks everyone!

Cheers,
Miguel

author maintainer
#5 lore raw
Quoted 21 lines · Miguel Ojeda
Quoted 20 lines · On Fri, 27 Nov 2026 21:05:40 +0900 Alexandre Courbot <[email protected]>…

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }
Quoted 8 lines
Quoted 6 lines

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

Applied to rust-next -- thanks everyone!

Note that this is going to create a merge conflict with drm-rust-next, some of the Tyr code has been updated concurrently. It's a single one though, and taking "theirs" should solve it, so more trivial than I expected.

Which makes me think, there are more patches affecting num than I initially expected, would it help if I maintained a tree and sent you PRs, timed to avoid such conflicts when possible?

#6 lore raw
Quoted 5 lines · Alexandre Courbot

Note that this is going to create a merge conflict with drm-rust-next, some of the Tyr code has been updated concurrently. It's a single one though, and taking "theirs" should solve it, so more trivial than I expected.

Yeah, I saw that once, it should be no problem.

Quoted 3 lines

Which makes me think, there are more patches affecting num than I initially expected, would it help if I maintained a tree and sent you PRs, timed to avoid such conflicts when possible?

If you want to maintain a tree, and send PRs, then that would be very welcome! But please don't feel like you have to do it just for conflicts.

Conflicts in general are OK, and Linus prefers to see them rather than e.g. trees doing backmerges, so delaying work due to conflicts is generally not needed. And if it is me seeing the conflicts, which I think is unlikely so far given the trees I take PRs from, the same applies anyway.

(In any case, if you want the tree, then we can set it up in a moment -- I usually offer a quick call to explain how PRs usually work, but I think you have done PRs even a decade ago, so I guess you know how it all works... :) Though I guess we could take the chance to do the spreadsheet one we had pending).

Cheers,
Miguel

reviewer
#7 lore raw
In reply to Alexandre Courbot
Quoted 31 lines · Alexandre Courbot
Quoted 21 lines · Miguel Ojeda
Quoted 20 lines · On Fri, 27 Nov 2026 21:05:40 +0900 Alexandre Courbot <[email protected]>…

From/Into implementations already exist between a bitfield type and its storage type, but these are not enough to support nested bitfields, since every field is a Bounded. This resulted in some ad-hoc implementations to enable this kind of declaration:

    bitfield! {
        pub struct Version(u8) {
            7:4 major;
            3:0 minor;
        }
    }

    bitfield! {
        pub struct Id(u16) {
            15:8 vendor;
            7:0 version => Version;
        }
    }
Quoted 8 lines
Quoted 6 lines

Generate these conversions automatically through the bitfield! macro, as these tend to be useful.

Tyr had such ad-hoc implementations, so remove them to avoid conflicts.

Applied to rust-next -- thanks everyone!

Quoted 8 lines

Note that this is going to create a merge conflict with drm-rust-next, some of the Tyr code has been updated concurrently. It's a single one though, and taking "theirs" should solve it, so more trivial than I expected.

Which makes me think, there are more patches affecting num than I initially expected, would it help if I maintained a tree and sent you PRs, timed to avoid such conflicts when possible?

Do you expect continued traffic on num, or it'd quiet down a bit once the features are there and users are converted?

Best,
Gary