rust: bounded integer types and use in register macro
Subsystems (5)
Alexandre Courbot
maintainercover rust: bounded integer types and use in register macro
This is a RFC/PoC for an idea I submitted a bit earlier [1] regarding how to handle truncated bits in the register/bitfield macro field setters.
Currently, the register macro allows to define fields that are shorter than the primitive type used to set them. For instance, in the following register:
register!(NV_PFALCON_FALCON_DMATRFBASE1 @ PFalconBase[0x00000128] {
8:0 base as u16;
});The base field is 9 bits long, but is set using the following setter method:
fn set_base(self, value: u16) -> Self
which discards bits of value higher than 9 without any error or warning if some happen to be set. And so you happily start a DMA transfer from the wrong base address...
While this behavior is not UB, this can also be a source of bugs. Several ideas have been submitted to not let these unnoticed, including making the register setters fallible, or panicking or printing a warning whenever extra bits are discarded [2]. These solutions are either too risky (like panicking), or add extra code and checks on what can be a critical path as registers are commonly accessed in interrupt handlers.
In pure Rust fashion, we would prefer to guarantee at compile-time, whenever possible, that no bits are discarded when setting register fields with a non-round number of bits.
This PoC proposes a possible solution for that. It introduces a new BoundedInt type that wraps a primitive integer type and, using a const generic, limits the number of bits that can actually be used within it. This is similar in spirit to NonZero or Alignment in that it provides a static guarantee that the value it contains is limited to a certain subset of the possible values of its primitive type.
Instances of BoundedInt can be constructed infallibly when the compiler is able to guarantee that the passed value fits within the allowed bounds, or fallibly using try_from(primitive).
This type is then used by the register/bitfield macros to let the fields getter and (more importantly) setter methods work with the exact number of bits they can handle. For instance, the above method would become:
fn set_base(self, value: BoundedInt<u32, 9>) -> Self
which guarantees that no bits are ever discarded by the setter, since the type of value carries an invariant that only the 9 lowest bits can ever be set.
It is then the responsibility of the caller to build the adequate BoundedInt, which very often can be done infallibly, but all the cases that require a fallible operation are cases that the caller should have checked anyway (lest you beam out the wrong memory region on your DMA transfer!).
As mentioned, this is a short and early PoC. The BoundedInt type is minimal, and defined only for u32 (as this is the type currently used by the register macro). It should be defined for all relevant types using a macro, and extended to support more operations.
Also, instead of replacing the current getter/setter methods of the register macro, this RFC adds two new ones suffixed with _bounded to demonstrate the use of this new type, and change a couple of setter call sites in nova-core's falcon.rs to showcase sites that can be statically constructed, and a few that need to be dynamically checked.
Note that this is not designed to replace the other feature of the register macro ensuring we are in control of all our bits, namely the conversion of the field from/to enum types with only valid values. Both features can happily work together (and the enum is preferred when applicable).
Another side effect of adopting this would be that the bitfield definitions could be simplified, since their type can now be automatically inferred. This means that
8:0 base as u16;
could become simply
8:0 base;
And the getter/setters would work with a BoundedInt<u32, 9> (provided the bitfield type is backed by a u32).
This is very early work, but feedback would be welcome. I expected this to be more constraining to use, but so far the disruption to user code looks minimal, and always justified when it occurs.
I intuitively suspect that such bounded integer types could also be useful outside of bitfields. If other use-cases come to mind, please let me know! :)
For convenience, this PoC is based on drm-rust-next. If we decide to proceed with it, we would do it after the patchset extracting and moving the bitfield logic [3] lands, as the two would conflict heavily.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/T/#mcbf44a779389c3664d885224ca422130b4cec5a9
[3] https://lore.kernel.org/rust-for-linux/[email protected]/T/
To: Joel Fernandes <[email protected]>
To: Yury Norov <[email protected]>
To: Danilo Krummrich <[email protected]>
To: Miguel Ojeda <[email protected]>
Cc: [email protected]
Cc: [email protected]
---
Alexandre Courbot (2):
rust: kernel: add bounded integer types
gpu: nova-core: demonstrate use of BoundedInt
drivers/gpu/nova-core/falcon.rs | 14 ++-- drivers/gpu/nova-core/regs/macros.rs | 34 ++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 120 +++++++++++++++++++++++++++++++++++ 4 files changed, 164 insertions(+), 5 deletions(-)
---
base-commit: 299eb32863e584cfff7c6b667c3e92ae7d4d2bf9
change-id: 20251001-bounded_ints-1d0457d9ae26
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerRFC PATCH 1/2 rust: kernel: add bounded integer types
Add the BoundedInt type, which restricts the number of bits allowed to be used in a given integer value. This is useful to carry guarantees when setting bitfields.
--- rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -101,6 +101,7 @@pub mod mm;#[cfg( CONFIG_NET )] pub mod net; +pub mod num;pub mod of;#[cfg( CONFIG_PM_OPP )] pub mod opp;
rust/kernel/num.rs new file +120 -0
120 lines not on this page · raw message
Signature · 1 line
2.51.0
Alexandre Courbot
maintainerRFC PATCH 2/2 gpu: nova-core: demonstrate use of BoundedInt
In reply to Alexandre CourbotAugment the register macro with two new bounded setter and getter methods, and showcase how they can be used in the driver.
--- drivers/gpu/nova-core/falcon.rs | 14 +++++++++----- drivers/gpu/nova-core/regs/macros.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/falcon.rs +9 -5
@@ -6,6 +6,7 @@use hal::FalconHal ;use kernel::device;use kernel::dma::DmaAddress ; +use kernel::num::BoundedInt ;use kernel::prelude::*;use kernel::sync::aref::ARef ;use kernel::time::Delta ;
@@ -488,24 +489,27 @@ fn dma_wr<F: FalconFirmware<Target = E>>(// Set up the base source DMA address. regs::NV_PFALCON_FALCON_DMATRFBASE ::default () - .set_base ((dma_start >>8 )as u32 ) + .set_base_bounded (BoundedInt ::new ((dma_start >>8 )as u32 )) .write (bar, &E ::ID ); regs::NV_PFALCON_FALCON_DMATRFBASE1 ::default () - .set_base ((dma_start >>40 )as u16 ) + .set_base_bounded (BoundedInt ::try_from ((dma_start >>40 )as u32 )?) .write (bar, &E ::ID ); +let r = regs::NV_PFALCON_FALCON_DMATRFBASE ::read (bar, &E ::ID ).base_bounded (); +pr_info! ("BASE: {:x}\n" , r); +let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::default () .set_size (DmaTrfCmdSize ::Size256B ) .set_imem (target_mem ==FalconMem ::Imem ) - .set_sec (if sec {1 }else {0 }); + .set_sec_bounded (BoundedInt ::new (if sec {1 }else {0 }));for posin (0 ..num_transfers).map (|i| i *DMA_LEN ) {// Perform a transfer of size `DMA_LEN`. regs::NV_PFALCON_FALCON_DMATRFMOFFS ::default () - .set_offs (load_offsets.dst_start + pos) + .set_offs_bounded (BoundedInt ::try_from (load_offsets.dst_start + pos)?) .write (bar, &E ::ID ); regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::default () - .set_offs (src_start + pos) + .set_offs_bounded (BoundedInt ::new (src_start + pos)) .write (bar, &E ::ID ); cmd.write (bar, &E ::ID );
drivers/gpu/nova-core/regs/macros.rs +34 -0
@@ -565,6 +565,40 @@ pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self { self } ); + + ::kernel::macros::paste!( +pub (crate )fn [<$field_bounded >](self) -> + ::kernel::num::BoundedInt <u32 , { $hi +1 - $lo }> { +const MASK :u32 = $name::[<$field:upper _MASK>]; +const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; +// Ensure the returned type has the same width as the field. + ::kernel::static_assert!( +MASK >>SHIFT == ::kernel::num::BoundedInt ::<u32 , { $hi +1 - $lo }>::MASK + ); + +let field = ((self.0 &MASK ) >>SHIFT ); + + ::kernel::num::BoundedInt ::<u32 , { $hi +1 - $lo }>::new (field) + } + +pub (crate )fn [<set_ $field_bounded >]( +mut self, + value: ::kernel::num::BoundedInt <u32 , { $hi +1 - $lo }> + ) ->Self { +const MASK :u32 = $name::[<$field:upper _MASK>]; +const SHIFT :u32 = $name::[<$field:upper_SHIFT >]; +// Ensure the returned type has the same width as the field. + ::kernel::static_assert!( +MASK >>SHIFT == ::kernel::num::BoundedInt ::<u32 , { $hi +1 - $lo }>::MASK + ); + +let value = (value.get () <<SHIFT ) &MASK ; + self.0 = (self.0 & !MASK ) | value; + + self + } + ); + };// Generates the `Debug` implementation for `$name`.
Signature · 1 line
2.51.0
Hi Alex,
Nice!
Quoted 3 lines · Alexandre Courbot
For convenience, this PoC is based on drm-rust-next. If we decide to proceed with it, we would do it after the patchset extracting and moving the bitfield logic [3] lands, as the two would conflict heavily.
I would strongly prefer this as well, to avoid conflicts. On initial look, this seems to be in the right direction and solves the pain points we were seeing.
- .set_sec(if sec { 1 } else { 0 });
+ .set_sec_bounded(BoundedInt::new(if sec { 1 } else { 0 }));
Here, I would prefer if we did not add _bounded, since the idea is to solve the problems in the macro's setters itself (make it infallible, not panicking etc). So we can just modify those?
Also, BoundedInt sounds like a good name to me IMO.
Also, since TryFrom trait is implemented in the first patch, then in nova we can just do the following?
.set_foo(value.try_into()?);
That's slightly simpler to read than:
.set_foo(BoundedInt::try_from(value)?);
And closer to the old syntax of
.set_foo(value); // used to truncate
But I don't feel strongly about not using the full form version.
thanks,
- Joel
Alexandre Courbot
maintainerQuoted 15 lines · Joel Fernandes
Hi Alex,
Nice!
Quoted 3 lines · Alexandre Courbot
For convenience, this PoC is based on drm-rust-next. If we decide to proceed with it, we would do it after the patchset extracting and moving the bitfield logic [3] lands, as the two would conflict heavily.
I would strongly prefer this as well, to avoid conflicts. On initial look, this seems to be in the right direction and solves the pain points we were seeing.
(quoted diff) +1
-1- .set_sec(if sec { 1 } else { 0 }); + .set_sec_bounded(BoundedInt::new(if sec { 1 } else { 0 }));
Quoted 3 lines
Here, I would prefer if we did not add
_bounded, since the idea is to solve the problems in the macro's setters itself (make it infallible, not panicking etc). So we can just modify those?
Oh absolutely, the and goal is to replace the existing accessors. For this RFC I went the lazy way and added new ones, otherwise I would have had to update more call sites in nova-core.
Quoted 6 lines
Also, BoundedInt sounds like a good name to me IMO.
Also, since TryFrom trait is implemented in the first patch, then in nova we can just do the following?
.set_foo(value.try_into()?);
Yes! That does work indeed and is more concise. And we can also make things less verbose on the caller side by adding a new generic setter in the form of:
fn try_set_field<T: TryInto<BoundedInt<..>>(self, value:T) -> Result
This setter could try to perform the conversion itself and return an error as needed, and the caller would just need to call e.g.
.try_set_foo(value)?;
instead of building the BoundedInt themselves.
There are also many other improvements that can be done, like having fields with a round number of bits be represented by the relevant primitive directly instead of a BoundedInt, but that will requires some more macro magic.
Quoted 20 lines · Alexandre Courbot
Quoted 15 lines · Joel Fernandes
Hi Alex,
Nice!
Quoted 4 lines · Alexandre Courbot
For convenience, this PoC is based on drm-rust-next. If we decide to proceed with it, we would do it after the patchset extracting and moving the bitfield logic [3] lands, as the two would conflict heavily.
I would strongly prefer this as well, to avoid conflicts. On initial look, this seems to be in the right direction and solves the pain points we were seeing.
(quoted diff) +1
-1- .set_sec(if sec { 1 } else { 0 }); + .set_sec_bounded(BoundedInt::new(if sec { 1 } else { 0 }));
Quoted 7 lines
Quoted 3 lines
Here, I would prefer if we did not add
_bounded, since the idea is to solve the problems in the macro's setters itself (make it infallible, not panicking etc). So we can just modify those?Oh absolutely, the and goal is to replace the existing accessors. For this RFC I went the lazy way and added new ones, otherwise I would have had to update more call sites in nova-core.
Ack.
Quoted 12 lines
Quoted 7 lines
Also, BoundedInt sounds like a good name to me IMO.
Also, since TryFrom trait is implemented in the first patch, then in nova we can just do the following?
.set_foo(value.try_into()?);Yes! That does work indeed and is more concise. And we can also make things less verbose on the caller side by adding a new generic setter in the form of:
Quoted 8 lines
fn try_set_field<T: TryInto<BoundedInt<..>>(self, value:T) -> ResultThis setter could try to perform the conversion itself and return an error as needed, and the caller would just need to call e.g.
.try_set_foo(value)?;instead of building the BoundedInt themselves.
Ack, this would be a great addition too, we should do it IMO.
Thanks!
- Joel
Quoted 6 lines
There are also many other improvements that can be done, like having fields with a round number of bits be represented by the relevant primitive directly instead of a BoundedInt, but that will requires some more macro magic.