rust: add `num` module
Subsystems (8)
Alexandre Courbot
maintainercover rust: add `num` module
This patchset was part of the Nova FWSEC-FRTS submission [1], but has been extracted as it was not very visible there, and seems to require more discussion that the Nova code. I hope that presenting it separately will help make it converge towards something that can be merged.
The motivation for this new module is to provide numerical functions not supported (or not optimally supported for the kernel use-cases) by Rust core. One example is how kernel code often aligns addresses or length to some power-of-two. While Rust has next_multiple_of that provides the same result, it also supports non-power-of-two values and is thus not as efficient as the simple substract-and-mask operation that can be done with a power of two.
Another missing operation is last_set_bit (fls in the C code), which is again commonly used in the kernel but has no equivalent yet in Rust core.
This patchset introduces these two features available:
- A PowerOfTwo newtype for unsigned integers with align_down and align_up operations optimized for the kernel. The newtype ensures that these operations cannot be used with a non-power-of-two, which would yield an incorrect result.
- A set of last_set_bit const functions for unsigned integers types.
The last patch makes use of these features in the Nova driver, as was originally done in the patchset. It requires the v6 of the patch series
[2] to be applied.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
Changes since split from the nova-core series:
- Rename fls to last_set_bit,
- Generate per-type doctests,
- Add invariants section to PowerOfTwo.
- Do not use reference to self in PowerOfTwo methods since it implements Copy,
- Use #[derive] where possible instead of implementing traits manually,
- Remove Deref and Borrow implementations.
---
Alexandre Courbot (3):
rust: add num module with PowerOfTwo type
rust: num: add the last_set_bit operation
nova-core: use num module
Documentation/gpu/nova/core/todo.rst | 15 --- drivers/gpu/nova-core/falcon/hal/ga102.rs | 4 +- drivers/gpu/nova-core/fb.rs | 6 +- drivers/gpu/nova-core/firmware/fwsec.rs | 7 +- drivers/gpu/nova-core/vbios.rs | 4 +- rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 201 ++++++++++++++++++++++++++++++ 7 files changed, 211 insertions(+), 27 deletions(-)
---
base-commit: c7864f7ab73417e352d8d00e46d3e9e6a228c5ab
change-id: 20250620-num-9420281c02c7
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH 1/3 rust: add `num` module with `PowerOfTwo` type
Introduce the num module, featuring the PowerOfTwo unsigned wrapper that guarantees (at build-time or runtime) that a value is a power of two.
Such a property is often useful to maintain. In the context of the kernel, powers of two are often used to align addresses or sizes up and down, or to create masks. These operations are provided by this type.
It is introduced to be first used by the nova-core driver.
--- rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 163 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 164 insertions(+)
rust/kernel/lib.rs +1 -0
@@ -89,6 +89,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 +163 -0
163 lines not on this page · raw message
Signature · 1 line
2.49.0
Alexandre Courbot
maintainerPATCH 2/3 rust: num: add the `last_set_bit` operation
In reply to Alexandre CourbotAdd an equivalent to the fls (Find Last Set bit) C function to Rust unsigned types.
It is to be first used by the nova-core driver.
--- rust/kernel/num.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+)
rust/kernel/num.rs +38 -0
@@ -161,3 +161,41 @@ pub const fn align_up(self, value: $t) -> $t { }power_of_two_impl! (usize ,u8 ,u16 ,u32 ,u64 ,u128 ); + +macro_rules! impl_last_set_bit { + ($($t:ty),+) => { + $( + ::kernel::macros::paste! { +/// Last Set Bit: return the 1-based index of the last (i.e. most significant) set bit +/// in `v`. +/// +/// Equivalent to the C `fls` function. +/// +/// # Examples +/// +/// ``` +#[doc = concat! ( "use kernel::num::last_set_bit_" , stringify! ($t), ";" )] +/// +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x0), 0);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x1), 1);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x10), 5);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x1f), 5);" )] +#[doc = concat! ( +"assert_eq!(last_set_bit_" , +stringify! ($t), +"(" , +stringify! ($t), +"::MAX), " , +stringify! ($t), "::BITS);" +)] +/// ``` +#[inline(always)] +pub const fn [<last_set_bit_ $t>](v: $t) ->u32 { + $t::BITS - v.leading_zeros () + } + } + )+ + }; +} + +impl_last_set_bit! (usize ,u8 ,u16 ,u32 ,u64 ,u128 );
Signature · 1 line
2.49.0
Alexandre Courbot
maintainerPATCH 3/3 nova-core: use `num` module
In reply to Alexandre CourbotMake use of the functions available in the num module and remove the corresponding TODO items.
--- Documentation/gpu/nova/core/todo.rst | 15 --------------- drivers/gpu/nova-core/falcon/hal/ga102.rs | 4 ++-- drivers/gpu/nova-core/fb.rs | 6 +++--- drivers/gpu/nova-core/firmware/fwsec.rs | 7 ++----- drivers/gpu/nova-core/vbios.rs | 4 ++-- 5 files changed, 9 insertions(+), 27 deletions(-)
Documentation/gpu/nova/core/todo.rst +0 -15
@@ -141,21 +141,6 @@ Features desired before this happens: | Complexity: Advanced | Contact: Alexandre Courbot -Numerical operations [NUMM] ---------------------------- - -Nova uses integer operations that are not part of the standard library (or not -implemented in an optimized way for the kernel). These include: - -- Aligning up and down to a power of two, -- The "Find Last Set Bit" (`fls` function of the C part of the kernel) - operation. - -A `num` core kernel module is being designed to provide these operations. - -| Complexity: Intermediate -| Contact: Alexandre Courbot - Delay / Sleep abstractions [DLAY] ---------------------------------
drivers/gpu/nova-core/falcon/hal/ga102.rs +2 -2
@@ -4,6 +4,7 @@use core::time::Duration ;use kernel::device; +use kernel::num::last_set_bit_u32;use kernel::prelude::*;use crate ::driver::Bar0 ;
@@ -69,8 +70,7 @@ fn signature_reg_fuse_version_ga102(let reg_fuse_version = bar.read32 (reg_fuse_base + ((ucode_id -1 )as usize * core::mem::size_of ::<u32 >())); -// TODO[NUMM]: replace with `last_set_bit` once it lands. -Ok (u32::BITS - reg_fuse_version.leading_zeros ()) +Ok (last_set_bit_u32 (reg_fuse_version)) }fn program_brom_ga102 <E :FalconEngine >(bar: &Bar0 , params: &FalconBromParams ) ->Result {
drivers/gpu/nova-core/fb.rs +3 -3
@@ -2,6 +2,7 @@use core::ops::Range ; +use kernel::num::PowerOfTwo ;use kernel::prelude::*;use kernel::sizes::*;use kernel::types::ARef ;
@@ -119,10 +120,9 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0) -> Result<Self> { };let frts = { -const FRTS_DOWN_ALIGN :u64 =SZ_128K as u64 ; +const FRTS_DOWN_ALIGN :PowerOfTwo <u64 > =PowerOfTwo ::<u64 >::new (SZ_128K as u64 );const FRTS_SIZE :u64 =SZ_1M as u64 ; -// TODO[NUMM]: replace with `align_down` once it lands. -let frts_base = (vga_workspace.start & !(FRTS_DOWN_ALIGN -1 )) -FRTS_SIZE ; +let frts_base =FRTS_DOWN_ALIGN .align_down (vga_workspace.start) -FRTS_SIZE ; frts_base..frts_base +FRTS_SIZE };
drivers/gpu/nova-core/firmware/fwsec.rs +2 -5
@@ -15,6 +15,7 @@use core::ops::Deref ;use kernel::device::{self,Device }; +use kernel::num::PowerOfTwo ;use kernel::prelude::*;use kernel::transmute::FromBytes ;
@@ -218,11 +219,7 @@ fn dmem_load_params(&self) -> FalconLoadTarget {FalconLoadTarget { src_start: self.desc.imem_load_size, dst_start: self.desc.dmem_phys_base, -// TODO[NUMM]: replace with `align_up` once it lands. - len: self - .desc - .dmem_load_size - .next_multiple_of (DMEM_LOAD_SIZE_ALIGN ), + len:PowerOfTwo ::<u32 >::new (DMEM_LOAD_SIZE_ALIGN ).align_up (self.desc.dmem_load_size), } }
drivers/gpu/nova-core/vbios.rs +2 -2
@@ -8,6 +8,7 @@use core::convert::TryFrom ;use kernel::device;use kernel::error::Result ; +use kernel::num::PowerOfTwo ;use kernel::pci;use kernel::prelude::*;
@@ -175,8 +176,7 @@ fn next(&mut self) -> Option<Self::Item> {// Advance to next image (aligned to 512 bytes) self.current_offset += image_size; -// TODO[NUMM]: replace with `align_up` once it lands. - self.current_offset = self.current_offset.next_multiple_of (512 ); + self.current_offset =PowerOfTwo ::<usize >::new (512 ).align_up (self.current_offset);Some (Ok (full_image)) }
Signature · 1 line
2.49.0
Re: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
In reply to Alexandre CourbotQuoted 8 lines · Alexandre Courbot
Introduce the
nummodule, featuring thePowerOfTwounsigned wrapper that guarantees (at build-time or runtime) that a value is a power of two.Such a property is often useful to maintain. In the context of the kernel, powers of two are often used to align addresses or sizes up and down, or to create masks. These operations are provided by this type.
Before I forget: the other day in a call we discussed powers of two and I mentioned that there is Alignment in the standard library:
https://doc.rust-lang.org/std/ptr/struct.Alignment.html
"A type storing a usize which is a power of two"
So it would be nice to ask upstream the following if they have plans to stabilize it, and whether they have considered a generic PowerOfTwo<T> type like this one, rather than one just for alignment purposes (possibly with an alias or newtype for Alignment if needed).
Similarly, if they stabilize the Alignment one (only) and we end up only using our PowerOfTwo<T> for usize and those use cases, then we should consider using the upstream one (and adding any/all methods that we need).
So I will ask them the next time we meet. I have added ptr_alignment_type to our list (in the "nice to have" section).
(Apologies if this was already discussed!)
Cheers,
Miguel
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 10 lines · Miguel Ojeda
Quoted 8 lines · Alexandre Courbot
Introduce the
nummodule, featuring thePowerOfTwounsigned wrapper that guarantees (at build-time or runtime) that a value is a power of two.Such a property is often useful to maintain. In the context of the kernel, powers of two are often used to align addresses or sizes up and down, or to create masks. These operations are provided by this type.
Quoted 6 lines
Before I forget: the other day in a call we discussed powers of two and I mentioned that there is
Alignmentin the standard library:https://doc.rust-lang.org/std/ptr/struct.Alignment.html
"A type storing a
usizewhich is a power of two"
Haha, I wasn't aware of this effort, and am quite amazed by how close its API is to my own design. This is reassuring; maybe I am finally starting to grok Rust after all. ;)
Quoted 6 lines
So it would be nice to ask upstream the following if they have plans to stabilize it, and whether they have considered a generic
PowerOfTwo<T>type like this one, rather than one just for alignment purposes (possibly with an alias or newtype forAlignmentif needed).
Mmm indeed I don't quite see the fundamental difference between Alignment and PowerOfTwo, although Alignment might better capture what we are doing with our type anyway.
Quoted 5 lines
Similarly, if they stabilize the
Alignmentone (only) and we end up only using ourPowerOfTwo<T>forusizeand those use cases, then we should consider using the upstream one (and adding any/all methods that we need).
Alignment is very close to what we need, so I don't see a reason to not adopt the same name at the very least.
This reminds me that I should also check whether upstream Rust would be interested in prev_multiple_of and last_set_bit. The docs I've read for contributing looked a bit intimidating, with RFCs to write and all. Would you have a pointer for where I should start? Maybe a Zulip thread?
Quoted 5 lines
So I will ask them the next time we meet. I have added
ptr_alignment_typeto our list (in the "nice to have" section).(Apologies if this was already discussed!)
I wasn't aware of this, so thanks for bringing it up!
Alice Ryhl
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 5 lines · Alexandre Courbot
Quoted 4 lines
Similarly, if they stabilize the
Alignmentone (only) and we end up only using ourPowerOfTwo<T>forusizeand those use cases, then we should consider using the upstream one (and adding any/all methods that we need).
Quoted 7 lines
Alignmentis very close to what we need, so I don't see a reason to not adopt the same name at the very least.This reminds me that I should also check whether upstream Rust would be interested in
prev_multiple_ofandlast_set_bit. The docs I've read for contributing looked a bit intimidating, with RFCs to write and all. Would you have a pointer for where I should start? Maybe a Zulip thread?
If you want to add a new library function, the correct procedure would be opening an ACP, which is more light-weight than the RFC process:
https://std-dev-guide.rust-lang.org/development/feature-lifecycle.html
RFCs are mainly for much bigger changes.
Alice
Re: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
In reply to Alexandre CourbotQuoted 5 lines · Alexandre Courbot
This reminds me that I should also check whether upstream Rust would be interested in
prev_multiple_ofandlast_set_bit. The docs I've read for contributing looked a bit intimidating, with RFCs to write and all. Would you have a pointer for where I should start? Maybe a Zulip thread?
I would say it is actually quite straightforward compared to, say, WG14/21.
The first thing I added was a method too, to see how things worked, and I started just by sending the PR.
So I would say, go for it! :)
Cheers,
Miguel
Benno Lossin
reviewerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
In reply to Alexandre Courbotrust/kernel/num.rs line 21
Quoted 13 lines · Alexandre Courbot
rust/kernel/num.rs new file +13
-0+/// An unsigned integer which is guaranteed to be a power of 2. +/// +/// # Invariants +/// +/// The stored value is guaranteed to be a power of two. +#[derive( Debug , Clone , Copy , PartialEq , Eq , PartialOrd , Ord , Hash )] +#[repr(transparent)] +pub struct PowerOfTwo <T >(T ); + +macro_rules! power_of_two_impl { + ($($t:ty),+) => { + $( + impl PowerOfTwo<$t> {
I tried to use this type in a doctest like this:
use kernel::num::PowerOfTwo;
fn new(x: usize) -> PowerOfTwo<usize> {
PowerOfTwo::new(1 << x)
}And it doesn't compile :(
error[E0034]: multiple applicable items in scope
--> rust/doctests_kernel_generated.rs:4930:17
|
4930 | PowerOfTwo::new(1 << x)
| ^^^ multiple new found
|
= note: candidate #1 is defined in an impl for the type PowerOfTwo<u128> = note: candidate #2 is defined in an impl for the type PowerOfTwo<u16> = note: candidate #3 is defined in an impl for the type PowerOfTwo<u32> = note: candidate #4 is defined in an impl for the type PowerOfTwo<u64> = note: and 2 others
error: aborting due to 1 previous error
The problem is that the function new exists 6 times for each of the integer types. You can write PowerOfTwo::<usize>::new() instead, but that's annoying...
We probably need an Integer trait and then do
impl<I: Integer> PowerOfTwo<I> {
pub const fn new(value: I) -> Self;
}Quoted 6 lines
rust/kernel/num.rs new file +6
-0+/// Validates that `v` is a power of two at build-time, and returns it wrapped into +/// [`PowerOfTwo`]. +/// +/// A build error is triggered if `v` cannot be asserted to be a power of two. +/// +/// # Examples
rust/kernel/num.rs line 37
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(16);" )] +/// assert_eq!(v.value(), 16); +/// ``` +#[inline(always)] +pub const fn new (v: $t) ->Self { +build_assert! (v.count_ones () ==1 );
Why not v.is_power_of_two()?
Quoted 1 line
+ Self(v)
Missing // INVARIANT comment.
Quoted 17 lines
rust/kernel/num.rs new file +17
-0+ } + +/// Validates that `v` is a power of two at runtime, and returns it wrapped into +/// [`PowerOfTwo`]. +/// +/// [`None`] is returned if `v` was not a power of two. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// + #[doc = concat!( + "assert_eq!(PowerOfTwo::<", + stringify!($t), + ">::try_new(16), Some(PowerOfTwo::<", + stringify!($t),
rust/kernel/num.rs line 65
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+ ">::new(16)));" + )] +#[doc = concat! ( +"assert_eq!(PowerOfTwo::<" , +stringify! ($t), +">::try_new(15), None);" +)] +/// ``` +#[inline(always)] +pub const fn try_new (v: $t) ->Option <Self > {
Maybe new_checked is a better name, since it doesn't return a result?
Quoted 1 line
+ match
v.count_ones(){
Why not is_power_of_two()?
Quoted 1 line
+ 1 => Some(Self(v)),
Missing // INVARIANT comment.
Quoted 9 lines
rust/kernel/num.rs new file +9
-0+ _ => None, + } + } + +/// Returns the value of this instance. +/// +/// It is guaranteed to be a power of two. +/// +/// # Examples
rust/kernel/num.rs line 86
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(16);" )] +/// assert_eq!(v.value(), 16); +/// ``` +#[inline(always)] +pub const fn value (self) -> $t { + self.0
Let's add:
if !self.0.is_power_of_two() {
core::hint::unreachable_unchecked()
}
self.0Quoted 5 lines
rust/kernel/num.rs new file +5
-0+ } + +/// Returns the mask corresponding to `self.value() - 1`. +/// +/// # Examples
rust/kernel/num.rs line 101
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(0x10);" )] +/// assert_eq!(v.mask(), 0xf); +/// ``` +#[inline(always)] +pub const fn mask (self) -> $t { + self.0 .wrapping_sub (1 )
Then use self.value().wrapping_sub(1) here instead to also propagate the information.
---
Cheers,
Benno
Quoted 1 line
+ }
Re: [PATCH 2/3] rust: num: add the `last_set_bit` operation
In reply to Alexandre CourbotQuoted 6 lines · Alexandre Courbot
Add an equivalent to the
fls(Find Last Set bit) C function to Rust unsigned types.It is to be first used by the nova-core driver.
Signed-off-by Alexandre Courbot <[email protected]>
---
Cheers,
Benno
Quoted 3 lines
--- rust/kernel/num.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+)
Re: [PATCH 2/3] rust: num: add the `last_set_bit` operation
In reply to Alexandre CourbotQuoted 6 lines · Alexandre Courbot
Add an equivalent to the
fls(Find Last Set bit) C function to Rust unsigned types.It is to be first used by the nova-core driver.
Signed-off-by Alexandre Courbot <[email protected]>
Quoted 8 lines
rust/kernel/num.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+)rust/kernel/num.rs +0
-0
rust/kernel/num.rs pub const fn align_up(self, value: $t) -> $t { · line 168
Quoted 8 lines
rust/kernel/num.rs +5
-0@@ -161,3 +161,41 @@ pub const fn align_up(self, value: $t) -> $t { }power_of_two_impl! (usize ,u8 ,u16 ,u32 ,u64 ,u128 ); + +macro_rules! impl_last_set_bit { + ($($t:ty),+) => { + $( + ::kernel::macros::paste! {
I think this would read slightly nicer with the paste! invocation on the outer scope.
$(::kernel::macros::paste! {
...
})+Quoted 37 lines
rust/kernel/num.rs +33
-0+/// Last Set Bit: return the 1-based index of the last (i.e. most significant) set bit +/// in `v`. +/// +/// Equivalent to the C `fls` function. +/// +/// # Examples +/// +/// ``` +#[doc = concat! ( "use kernel::num::last_set_bit_" , stringify! ($t), ";" )] +/// +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x0), 0);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x1), 1);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x10), 5);" )] +#[doc = concat! ( "assert_eq!(last_set_bit_" , stringify! ($t), "(0x1f), 5);" )] +#[doc = concat! ( +"assert_eq!(last_set_bit_" , +stringify! ($t), +"(" , +stringify! ($t), +"::MAX), " , +stringify! ($t), "::BITS);" +)] +/// ``` +#[inline(always)] + pub const fn [<last_set_bit_ $t>](v: $t) -> u32 { + $t::BITS - v.leading_zeros () + } + } + )+ + }; +} + +impl_last_set_bit! (usize ,u8 ,u16 ,u32 ,u64 ,u128 );Signature · 2 lines
-- 2.49.0
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
In reply to Benno LossinHi Benno,
Sorry, took some time to come back to this!
Quoted 37 lines · Benno Lossin
rust/kernel/num.rs line 21
Quoted 13 lines · Alexandre Courbot
rust/kernel/num.rs new file +13
-0+/// An unsigned integer which is guaranteed to be a power of 2. +/// +/// # Invariants +/// +/// The stored value is guaranteed to be a power of two. +#[derive( Debug , Clone , Copy , PartialEq , Eq , PartialOrd , Ord , Hash )] +#[repr(transparent)] +pub struct PowerOfTwo <T >(T ); + +macro_rules! power_of_two_impl { + ($($t:ty),+) => { + $( + impl PowerOfTwo<$t> {I tried to use this type in a doctest like this:
use kernel::num::PowerOfTwo; fn new(x: usize) -> PowerOfTwo<usize> { PowerOfTwo::new(1 << x) }And it doesn't compile :(
error[E0034]: multiple applicable items in scope
-->rust/doctests_kernel_generated.rs:4930:17
|
4930 |PowerOfTwo::new(1 << x)
| ^^^ multiplenewfound
|
= note: candidate #1 is defined in an impl for the typePowerOfTwo<u128>= note: candidate #2 is defined in an impl for the typePowerOfTwo<u16>= note: candidate #3 is defined in an impl for the typePowerOfTwo<u32>= note: candidate #4 is defined in an impl for the typePowerOfTwo<u64>= note: and 2 others
Quoted 5 lines
error: aborting due to 1 previous error
The problem is that the function
newexists 6 times for each of the integer types. You can writePowerOfTwo::<usize>::new()instead, but that's annoying...
This should go away as we switch to the non-generic Alignment type thankfully.
Quoted 24 lines
We probably need an
Integertrait and then doimpl<I: Integer> PowerOfTwo<I> { pub const fn new(value: I) -> Self; }Quoted 6 lines
rust/kernel/num.rs new file +6
-0+/// Validates that `v` is a power of two at build-time, and returns it wrapped into +/// [`PowerOfTwo`]. +/// +/// A build error is triggered if `v` cannot be asserted to be a power of two. +/// +/// # Examples rust/kernel/num.rs line 37
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(16);" )] +/// assert_eq!(v.value(), 16); +/// ``` +#[inline(always)] +pub const fn new (v: $t) ->Self { +build_assert! (v.count_ones () ==1 );
Quoted 1 line
Why not
v.is_power_of_two()?
Why not indeed. :) Fixed.
Quoted 4 lines
Quoted 2 lines
+ Self(v)
Missing
// INVARIANTcomment.
Added (and in other places as well).
Quoted 29 lines
Quoted 18 lines
rust/kernel/num.rs new file +17
-0+ } + +/// Validates that `v` is a power of two at runtime, and returns it wrapped into +/// [`PowerOfTwo`]. +/// +/// [`None`] is returned if `v` was not a power of two. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// + #[doc = concat!( + "assert_eq!(PowerOfTwo::<", + stringify!($t), + ">::try_new(16), Some(PowerOfTwo::<", + stringify!($t),rust/kernel/num.rs line 65
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+ ">::new(16)));" + )] +#[doc = concat! ( +"assert_eq!(PowerOfTwo::<" , +stringify! ($t), +">::try_new(15), None);" +)] +/// ``` +#[inline(always)] +pub const fn try_new (v: $t) ->Option <Self > {
Quoted 1 line
Maybe
new_checkedis a better name, since it doesn't return a result?
Definitely.
Quoted 4 lines
Quoted 2 lines
+ match
v.count_ones(){Why not
is_power_of_two()?
Fixed, thanks.
Quoted 25 lines
Quoted 2 lines
+ 1 => Some(Self(v)),
Missing
// INVARIANTcomment.Quoted 9 lines
rust/kernel/num.rs new file +9
-0+ _ => None, + } + } + +/// Returns the value of this instance. +/// +/// It is guaranteed to be a power of two. +/// +/// # Examples rust/kernel/num.rs line 86
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(16);" )] +/// assert_eq!(v.value(), 16); +/// ``` +#[inline(always)] +pub const fn value (self) -> $t { + self.0
Quoted 6 lines
Let's add:
if !self.0.is_power_of_two() { core::hint::unreachable_unchecked() } self.0
Sure. Is it to enable compiler optimizations by making assumptions about the returned value?
Quoted 17 lines
Quoted 6 lines
rust/kernel/num.rs new file +5
-0+ } + +/// Returns the mask corresponding to `self.value() - 1`. +/// +/// # Examples rust/kernel/num.rs line 101
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(0x10);" )] +/// assert_eq!(v.mask(), 0xf); +/// ``` +#[inline(always)] +pub const fn mask (self) -> $t { + self.0 .wrapping_sub (1 )
Quoted 2 lines
Then use
self.value().wrapping_sub(1)here instead to also propagate the information.
Ack.
Benno Lossin
reviewerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 3 lines · Alexandre Courbot
Hi Benno,
Sorry, took some time to come back to this!
No worries!
Quoted 20 lines · Benno Lossin
Quoted 19 lines · Alexandre Courbot
Quoted 5 lines
rust/kernel/num.rs new file +5
-0+/// Returns the value of this instance. +/// +/// It is guaranteed to be a power of two. +/// +/// # Examples rust/kernel/num.rs line 86
Quoted 10 lines
rust/kernel/num.rs new file +10
-0+/// +/// ``` +/// use kernel::num::PowerOfTwo; +/// +#[doc = concat! ( "let v = PowerOfTwo::<" , stringify! ($t), ">::new(16);" )] +/// assert_eq!(v.value(), 16); +/// ``` +#[inline(always)] +pub const fn value (self) -> $t { + self.0 Let's add:
Quoted 7 lines
Quoted 4 lines
if !self.0.is_power_of_two() { core::hint::unreachable_unchecked() } self.0Sure. Is it to enable compiler optimizations by making assumptions about the returned value?
Exactly, it will for example turn dividing by it into a right shift and prevent a branch for the zero check.
---
Cheers,
Benno
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
In reply to Alice RyhlQuoted 14 lines · Alice Ryhl
Quoted 5 lines · Alexandre Courbot
Quoted 4 lines
Similarly, if they stabilize the
Alignmentone (only) and we end up only using ourPowerOfTwo<T>forusizeand those use cases, then we should consider using the upstream one (and adding any/all methods that we need).Quoted 7 lines
Alignmentis very close to what we need, so I don't see a reason to not adopt the same name at the very least.This reminds me that I should also check whether upstream Rust would be interested in
prev_multiple_ofandlast_set_bit. The docs I've read for contributing looked a bit intimidating, with RFCs to write and all. Would you have a pointer for where I should start? Maybe a Zulip thread?
Quoted 5 lines
If you want to add a new library function, the correct procedure would be opening an ACP, which is more light-weight than the RFC process:
https://std-dev-guide.rust-lang.org/development/feature-lifecycle.htmlRFCs are mainly for much bigger changes.
Belated thanks for the suggestion; I have finally opened an ACP for last_set_bit (and first_set_bit while we are at it):
https://github.com/rust-lang/libs-team/issues/631
I am still entangled with how to best leverage Alignment for our purposes, but think I am getting close to a v2 of this patchset.
Re: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 7 lines · Alexandre Courbot
Belated thanks for the suggestion; I have finally opened an ACP for
last_set_bit(andfirst_set_bitwhile we are at it):
https://github.com/rust-lang/libs-team/issues/631I am still entangled with how to best leverage
Alignmentfor our purposes, but think I am getting close to a v2 of this patchset.
Thanks for filling that one -- linked now from our usual lists :)
https://github.com/Rust-for-Linux/linux/issues/514
Cheers,
Miguel
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 6 lines · Miguel Ojeda
Quoted 5 lines · Alexandre Courbot
Belated thanks for the suggestion; I have finally opened an ACP for
last_set_bit(andfirst_set_bitwhile we are at it):
https://github.com/rust-lang/libs-team/issues/631
Quoted 6 lines
Quoted 2 lines
I am still entangled with how to best leverage
Alignmentfor our purposes, but think I am getting close to a v2 of this patchset.Thanks for filling that one -- linked now from our usual lists :)
https://github.com/Rust-for-Linux/linux/issues/514
We got some interesting feedback on the ACP already. I have been pointed to checked_ilog2 as an equivalent of last_set_bit, and it *does* indeed work well as a replacement - with the caveat that the name is not very natural to me (or anyone familiar with the C interface). Is this something we can live with? If we decide to go with the existing standard library method, how can we make sure that folks looking for an equivalent of fls find checked_ilog2?
Re: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 8 lines · Alexandre Courbot
We got some interesting feedback on the ACP already. I have been pointed to
checked_ilog2as an equivalent oflast_set_bit, and it *does* indeed work well as a replacement - with the caveat that the name is not very natural to me (or anyone familiar with the C interface). Is this something we can live with? If we decide to go with the existing standard library method, how can we make sure that folks looking for an equivalent offlsfindchecked_ilog2?
One option is using the doc(alias = ...) attribute, which makes it appear in the search in the rendered docs, and would show easily in greps too.
Another option is simply wrapping it in an inline(always), I guess, but I think we can just use the upstream ones, unless we want slightly different semantics.
Cheers,
Miguel
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 10 lines · Miguel Ojeda
Quoted 8 lines · Alexandre Courbot
We got some interesting feedback on the ACP already. I have been pointed to
checked_ilog2as an equivalent oflast_set_bit, and it *does* indeed work well as a replacement - with the caveat that the name is not very natural to me (or anyone familiar with the C interface). Is this something we can live with? If we decide to go with the existing standard library method, how can we make sure that folks looking for an equivalent offlsfindchecked_ilog2?
Quoted 7 lines
One option is using the
doc(alias = ...)attribute, which makes it appear in the search in the rendered docs, and would show easily in greps too.Another option is simply wrapping it in an
inline(always), I guess, but I think we can just use the upstream ones, unless we want slightly different semantics.
That would be useful - let's see what the Rust lib folks say, as you brought up that question on the ACP as well.
In any case, since we have reasonable alternatives for both fls (checked_ilog2) and ffs (NonZero::trailing_zeros), I guess this means we want to use these directly in the kernel and can drop patch 2 of this series?
Alexandre Courbot
maintainerRe: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 19 lines · Alexandre Courbot
Quoted 10 lines · Miguel Ojeda
Quoted 8 lines · Alexandre Courbot
We got some interesting feedback on the ACP already. I have been pointed to
checked_ilog2as an equivalent oflast_set_bit, and it *does* indeed work well as a replacement - with the caveat that the name is not very natural to me (or anyone familiar with the C interface). Is this something we can live with? If we decide to go with the existing standard library method, how can we make sure that folks looking for an equivalent offlsfindchecked_ilog2?Quoted 7 lines
One option is using the
doc(alias = ...)attribute, which makes it appear in the search in the rendered docs, and would show easily in greps too.Another option is simply wrapping it in an
inline(always), I guess, but I think we can just use the upstream ones, unless we want slightly different semantics.
Quoted 7 lines
That would be useful - let's see what the Rust lib folks say, as you brought up that question on the ACP as well.
In any case, since we have reasonable alternatives for both
fls(checked_ilog2) andffs(NonZero::trailing_zeros), I guess this means we want to use these directly in the kernel and can drop patch 2 of this series?
I didn't expect that, but it looks like the Rust folks want these methods after all:
https://github.com/rust-lang/libs-team/issues/631#issuecomment-3156000663
I'll proceed with sending a PR, and I guess we can have temporary implementations in the kernel as well?
Re: [PATCH 1/3] rust: add `num` module with `PowerOfTwo` type
Quoted 5 lines · Alexandre Courbot
I didn't expect that, but it looks like the Rust folks want these methods after all:
https://github.com/rust-lang/libs-team/issues/631#issuecomment-3156000663
Indeed -- and now they just got stabilized for Rust 1.97 as {highest,lowest}_one. :)
(They got implemented in Rust 1.91, so we cannot just delete our versions, but next time we bump the version, we will).
They have also stabilized isolate_{highest,lowest}_one for the same release.
Cheers,
Miguel