rust: Add support for reserving of ranges of IDs
Subsystems (10)
v8 cover rust: Add support for reserving of ranges of IDs
Add support for reserving of ranges of IDs, with a usage in nova-core for channel IDs. This entails adding bindings for the C bitmap API for ranges of bits, then users of that in IdPool, and finally a user of IdPool in nova-core, ChannelIdPool.
Channel ID tracking is needed for allotting ranges of channel IDs to vGPU guests, and later for regular host channel ID reservation. nova-core needs allocation of a contiguous sequence of IDs with a specific length and sometimes a specific alignment [1].
About the tradeoffs between different data structures:
- IDA/xarray do not support allocating a contiguous sequence of IDs (ida_alloc_range() allocates a single ID within a range, not a contiguous sequence).
- A maple tree works, but is not as good a fit. The ID space is small (limited to 2048) and aligned allocation needs an alloc_range()+erase() retry loop (plus a Mutex around it, or new mas_empty_area() bindings) that essentially reimplements bitmap_find_next_zero_area(). See the maple tree version at [2]. For 2048 IDs a bitmap is also considerably faster and smaller [3].
- The bitmap API natively supports aligned contiguous area allocation (bitmap_find_next_zero_area()).
This is based on drm-rust-next.
[1]: https://lore.kernel.org/all/[email protected]/
[2]: https://lore.kernel.org/all/[email protected]/
[3]: https://lore.kernel.org/all/[email protected]/
---
Changes in v8:
- Clarify overflow cases in patch #2 (Alex)
- Replace nz! with generalized cv! macro (Gary)
- Add cv! macro to prelude
- Split SizeConstants and adding new constants patch (Alex)
- Move alignment size constants conersions patch (Alex)
- Drop NonZero on IdPool, fix grow_request instead (Alice, Alex)
- Add shrink/grow doctests (Burak)
- Link to v7: https://patch.msgid.link/[email protected]
Changes in v7:
- Add nz! macro for compile time NonZero
- Implement SizeConstants for Alignment + add sub 1k size constants
- Use Alignment constants + nz! in this series
- Add final patch converting existing callers to use Alignment constants
- Rename alloc_area/release_area -> reserve_ids / release_ids
- Link to v6: https://patch.msgid.link/[email protected]
Changes in v6:
- Take a NonZero nbits in next_zero_area_off, set and clear (Yury)
- Remove UnusedArea, IdPool::alloc_area now allocates directly (Yury)
- Add patch: take a NonZero capacity in IdPool::with_capacity()
- Add patch: do not round the capacity up to BitmapVec::MAX_INLINE_LEN, which also removes the bounds check in ChannelIdPool::alloc_area
- Add more testing of Drop for ChannelIdPool (Yury)
- Link to v5: https://patch.msgid.link/[email protected]
Changes in v5:
- bitmap_assert! i32::MAX length for Bitmap::from_raw* (Yury)
- Only run overflow check on 32-bit (Yury)
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Add next_zero_area_off to match C code (Yury)
- Replace overflow checks to match C code in bitmap-for-next.
- Tighten Bitmap unsafe contract to disallow Bitmaps larger than i32::MAX
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Use Alignment type in id_pool and bitmap (Alice)
- Remove hang check on the basis that it's extraordinarily rare.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Collected Alice's Reviewed-by on patch 1.
- Address Yury's comments w.r.t. using __bitmap_set etc directly.
- Address Yury's comments w.r.t. following the C names
- Additionally check for an overflow case that causes a hang
- Added more info to cover letter + patch 4 w.r.t. channel ID allottment requirements
- Add align parameter to ChannelIdPool::alloc_area() plus an aligned allocation test
- Add missing INVARIANT comment when constructing UnusedArea
- Link to v1:
https://patch.msgid.link/[email protected]
---
Eliot Courtney (12):
rust: bitmap: use function-level cfg on kunit test
rust: bitmap: restrict bitmap length to at most i32::MAX
rust: num: add cv! macro to create values from constant expressions
rust: prelude: add num::cv
rust: use cv! to build Bounded values from constants
rust: sizes: add sub-1K size constants
rust: sizes: implement SizeConstants for Alignment
rust: use Alignment size constants
rust: bitmap: add contiguous area operations
rust: id_pool: add contiguous ID reservation
rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
gpu: nova-core: add ChannelIdPool
drivers/gpu/nova-core/fb.rs | 10 +- drivers/gpu/nova-core/fb/hal/gb100.rs | 3 +- drivers/gpu/nova-core/fsp.rs | 4 +- drivers/gpu/nova-core/gpu.rs | 2 + drivers/gpu/nova-core/gpu/channel.rs | 198 ++++++++++++++++++++ drivers/gpu/nova-core/gsp/fw.rs | 12 +- drivers/gpu/nova-core/num.rs | 3 +- drivers/gpu/nova-core/vbios.rs | 7 +- rust/kernel/bitfield.rs | 8 +- rust/kernel/bitmap.rs | 336 ++++++++++++++++++++++++++++++---- rust/kernel/gpu/buddy.rs | 26 +-- rust/kernel/id_pool.rs | 70 ++++++- rust/kernel/io.rs | 5 +- rust/kernel/num.rs | 88 +++++++++ rust/kernel/num/bounded.rs | 21 ++- rust/kernel/prelude.rs | 1 + rust/kernel/ptr.rs | 13 ++ rust/kernel/sizes.rs | 47 ++++- 18 files changed, 768 insertions(+), 86 deletions(-)
---
base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
change-id: 20260608-chid-18fa943c6d6c
Best regards,
Signature · 1 line
Eliot Courtney <[email protected]>
PATCH v8 1/12 rust: bitmap: use function-level cfg on kunit test
Since commit c652dc44192d ("rust: kunit: allow cfg on tests"), we no longer need this workaround.
--- rust/kernel/bitmap.rs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-)
rust/kernel/bitmap.rs +11 -14
@@ -572,24 +572,21 @@ fn bitmap_set_clear_find() -> Result<(), AllocError> { }#[test] +#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] fn owned_bitmap_out_of_bounds () ->Result <(),AllocError > { -// TODO: Kunit #[test]s do not support `cfg` yet, -// so we add it here in the body. -#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] - { -let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; - b.set_bit (2048 ); - b.set_bit_atomic (2048 ); - b.clear_bit (2048 ); - b.clear_bit_atomic (2048 ); -assert_eq! (None , b.next_bit (2048 )); -assert_eq! (None , b.next_zero_bit (2048 )); -assert_eq! (None , b.last_bit ()); - } +let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; + + b.set_bit (2048 ); + b.set_bit_atomic (2048 ); + b.clear_bit (2048 ); + b.clear_bit_atomic (2048 ); +assert_eq! (None , b.next_bit (2048 )); +assert_eq! (None , b.next_zero_bit (2048 )); +assert_eq! (None , b.last_bit ());Ok (()) } -// TODO: uncomment once kunit supports [should_panic] and `cfg`. +// TODO: uncomment once kunit supports `#[should_panic]`. // #[cfg(CONFIG_RUST_BITMAP_HARDENED)] // #[test] // #[should_panic]
Signature · 1 line
2.55.0
PATCH v8 2/12 rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Eliot CourtneyIt is currently possible to construct a non-BitmapVec backed Bitmap using Bitmap::from_raw that is larger than i32::MAX, and it is not part of the unsafe requirements. Restricting all bitmaps (even non-BitmapVec backed ones) to a maximum size of i32::MAX simplifies a few things and matches BitmapVec::MAX_LEN. For example, copy_and_extend truncates len to u32, which is wrong for > u32::MAX size. __bitmap_set and __bitmap_clear need i32 for size and u32 for start - so they can't be run on a Bitmap with a > i32::MAX size. Rather than adding runtime checks to account for the case of a non BitmapVec backed Bitmap, just include that in the requirements for Bitmap.
Add that requirement to the unsafe requirements on Bitmap::from_raw and Bitmap::from_raw_mut, and to the invariants on Bitmap.
This also fixes u32 casts truncating in copy_and_extend, which could otherwise lead to OOB writes.
--- rust/kernel/bitmap.rs | 70 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 49 insertions(+), 21 deletions(-)
rust/kernel/bitmap.rs +49 -21
@@ -17,24 +17,59 @@/// # Invariants /// /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. +/// Must not be longer than `i32::MAX` bits, so offsets and lengths used with +/// `Bitmap` functions fit in the int and unsigned int arguments of the C bitmap API. +/// This also matches [`BitmapVec::MAX_LEN`]. #[cfg_attr( CONFIG_64BIT , repr(align( 8 )))] #[cfg_attr(not( CONFIG_64BIT ), repr(align( 4 )))] pub struct Bitmap { data: [()], } +macro_rules! bitmap_assert { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +assert! ($cond, $($arg)*); + } +} + +macro_rules! bitmap_assert_return { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +assert! ($cond, $($arg)*); + +#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] +if !($cond) { +pr_err! ($($arg)*); +return + } + } +} +impl Bitmap {/// Borrows a C bitmap. /// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds `i32::MAX`. +/// /// # Safety /// /// * `ptr` holds a non-null address of an initialized array of `unsigned long` /// that is large enough to hold `nbits` bits. +/// * `nbits` must not exceed `i32::MAX`. /// * the array must not be freed for the lifetime of this [`Bitmap`] /// * concurrent access only happens through atomic operations pub unsafe fn from_raw <'a>(ptr: *const usize , nbits:usize ) -> &'aBitmap { +bitmap_assert! ( + nbits <=i32 ::MAX as usize , +"`nbits` must be <= {}, was {}" , +i32 ::MAX , + nbits + );let data: *const [()] = core::ptr::slice_from_raw_parts (ptr.cast (), nbits);// INVARIANT: `data` references an initialized array that can hold `nbits` bits. +// INVARIANT: the caller guarantees that `nbits` does not exceed `i32::MAX`. // SAFETY: // The caller guarantees that `data` (derived from `ptr` and `nbits`) // points to a valid, initialized, and appropriately sized memory region
@@ -51,15 +86,27 @@ pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap {/// Borrows a C bitmap exclusively. /// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds `i32::MAX`. +/// /// # Safety /// /// * `ptr` holds a non-null address of an initialized array of `unsigned long` /// that is large enough to hold `nbits` bits. +/// * `nbits` must not exceed `i32::MAX`. /// * the array must not be freed for the lifetime of this [`Bitmap`] /// * no concurrent access may happen. pub unsafe fn from_raw_mut <'a>(ptr: *mut usize , nbits:usize ) -> &'amut Bitmap { +bitmap_assert! ( + nbits <=i32 ::MAX as usize , +"`nbits` must be <= {}, was {}" , +i32 ::MAX , + nbits + );let data: *mut [()] = core::ptr::slice_from_raw_parts_mut (ptr.cast (), nbits);// INVARIANT: `data` references an initialized array that can hold `nbits` bits. +// INVARIANT: the caller guarantees that `nbits` does not exceed `i32::MAX`. // SAFETY: // The caller guarantees that `data` (derived from `ptr` and `nbits`) // points to a valid, initialized, and appropriately sized memory region
@@ -96,26 +143,6 @@ union BitmapRepr { ptr: NonNull<usize>, } -macro_rules! bitmap_assert { - ($cond:expr, $($arg:tt)+) => { -#[cfg( CONFIG_RUST_BITMAP_HARDENED )] -assert! ($cond, $($arg)*); - } -} - -macro_rules! bitmap_assert_return { - ($cond:expr, $($arg:tt)+) => { -#[cfg( CONFIG_RUST_BITMAP_HARDENED )] -assert! ($cond, $($arg)*); - -#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] -if !($cond) { -pr_err! ($($arg)*); -return - } - } -} -/// Represents an owned bitmap. /// /// Wraps underlying C bitmap API. See [`Bitmap`] for available
@@ -415,7 +442,8 @@ pub fn clear_bit_atomic(&self, index: usize) {#[inline] pub fn copy_and_extend (&mut self, src: &Bitmap ) {let len = core::cmp::min (src.len (), self.len ()); -// SAFETY: access to `self` and `src` is within bounds. +// SAFETY: access to `self` and `src` is within bounds. Both lengths fit in `u32` +// because a `Bitmap` is at most `i32::MAX` bits, so the casts are lossless. unsafe { bindings::bitmap_copy_and_extend ( self.as_mut_ptr(),
Signature · 1 line
2.55.0
PATCH v8 3/12 rust: num: add cv! macro to create values from constant expressions
In reply to Eliot CourtneyCurrently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait function FromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).
--- rust/kernel/num.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/num/bounded.rs | 21 ++++++++++- rust/kernel/ptr.rs | 13 +++++++ 3 files changed, 122 insertions(+), 1 deletion(-)
rust/kernel/num.rs +89 -0
@@ -2,11 +2,100 @@//! Additional numerical features for the kernel. +use crate ::const_assert;use core::ops;pub mod bounded;pub use bounded::*; +/// Creates a value from an integer constant expression, with validity checked at build time. +/// +/// This works for any type that implements [`FromConst`], with the target type inferred from +/// the context. +/// +/// # Examples +/// +/// ``` +/// use core::num::NonZero; +/// use kernel::num::Bounded; +/// use kernel::num::cv; +/// use kernel::ptr::Alignment; +/// +/// let v: NonZero<usize> = cv!(8); +/// assert_eq!(v.get(), 8); +/// +/// // Any integer constant expression works, not only literals. +/// let m: NonZero<usize> = cv!(usize::MAX); +/// assert_eq!(m.get(), usize::MAX); +/// +/// let b: Bounded<u32, 4> = cv!(15); +/// assert_eq!(b.get(), 15); +/// +/// let a: Alignment = cv!(4096); +/// assert_eq!(a.as_usize(), 4096); +/// ``` +#[macro_export] +#[doc(hidden)] +macro_rules! cv { + ($v:expr) => { + $crate::num::FromConst ::from_const ::< + { +#[allow(unused_comparisons, unused_assignments, clippy::as_underscore)] + { +let v = $v; +let r = vas i128 ; +// Pin `back` to `v`'s type so `as _` casts back to the source type. +let mut back = v; + back = ras _ ; + + ::core::assert!( + back == v && (v <0 ) == (r <0 ), +"value cannot be losslessly widened to `i128`" + ); + + r + } + }, + >() + }; +} +#[doc(inline)] +pub use cv; + +/// Types that can be created from an integer constant expression validated at build time. +// TODO: make this a `const` trait once they are stable. This will let cv! be used in const +// contexts. +pub trait FromConst :Sized { +/// Creates the value that corresponds to the constant `V`. +/// +/// Fails the build if `V` is not a valid value for `Self`. +fn from_const <const V :i128 >() ->Self ; +} + +/// Implements [`FromConst`] for [`NonZero`](core::num::NonZero). +macro_rules! impl_from_const_nonzero { + ($($type:ty)*) => { + $( +impl FromConst for core::num::NonZero <$type> { +#[inline] +fn from_const <const V :i128 >() ->Self { +const_assert! ( +V >= <$type >::MIN as i128 &&V <= <$type >::MAX as i128 , +"Constant cannot be represented by the underlying type." + ); + +const { core::num::NonZero ::new (V as $type).unwrap () } + } + } + )* + }; +} + +impl_from_const_nonzero! ( +u8 u16 u32 u64 usize +i8 i16 i32 i64 isize +); +/// Designates unsigned primitive types. pub enum Unsigned {}
rust/kernel/num/bounded.rs +20 -1
@@ -13,7 +13,10 @@ };use kernel::{ - num::Integer , + num::{ +FromConst , +Integer ,// + }, prelude::*,// };
@@ -262,6 +265,22 @@ pub const fn new<const VALUE: $type>() -> Self {unsafe {Self ::__new (VALUE ) } } } + +impl <const N :u32 >FromConst for Bounded <$type,N > { +#[inline] +fn from_const <const V :i128 >() ->Self { +const_assert! ( +V >= <$type >::MIN as i128 &&V <= <$type >::MAX as i128 , +"Constant cannot be represented by the underlying type." + ); +// Statically assert that `V` fits within the set number of bits. +const_assert! (fits_within! (V as $type , $type ,N )); + +// SAFETY: the asserts above confirmed that `V` can be represented within `N` +// bits. +unsafe {Self ::__new (V as $type) } + } + } )* }; }
rust/kernel/ptr.rs +13 -0
@@ -166,6 +166,19 @@ pub const fn mask(self) -> usize { } } +impl crate ::num::FromConst for Alignment { +#[inline] +fn from_const <const V :i128 >() ->Self { +const_assert! ( +V >0 &&V <=usize ::MAX as i128 , +"Constant cannot be represented as an Alignment." + ); + +// The unwrap fails the build if `V` is not a power of two. +const {Alignment ::new_checked (V as usize ).unwrap () } + } +} +/// Trait for items that can be aligned against an [`Alignment`]. pub trait Alignable :Sized {/// Aligns `self` down to `alignment`.
Signature · 1 line
2.55.0
PATCH v8 4/12 rust: prelude: add `num::cv`
In reply to Eliot CourtneyAdd the cv! macro to the prelude so it doesn't need to be imported explicitly to use it.
--- rust/kernel/num.rs | 1 - rust/kernel/prelude.rs | 1 + 2 files changed, 1 insertion(+), 1 deletion(-)
rust/kernel/num.rs +0 -1
@@ -18,7 +18,6 @@/// ``` /// use core::num::NonZero; /// use kernel::num::Bounded; -/// use kernel::num::cv; /// use kernel::ptr::Alignment; /// /// let v: NonZero<usize> = cv!(8);
rust/kernel/prelude.rs +1 -0
@@ -106,6 +106,7 @@ Result, // }, init::InPlaceInit, + num::cv, pr_alert, pr_crit, pr_debug,
Signature · 1 line
2.55.0
PATCH v8 5/12 rust: use cv! to build Bounded values from constants
In reply to Eliot CourtneyThere are some locations which use Bounded::new() which can use the new cv! macro, so convert them.
--- drivers/gpu/nova-core/num.rs | 3 +-- rust/kernel/bitfield.rs | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-)
drivers/gpu/nova-core/num.rs +1 -2
@@ -240,8 +240,7 @@ macro_rules! bounded_enum {impl core::convert::From <$enum_type>for kernel::num::Bounded <$width, $length> {fn from (value: $enum_type) ->Self {match value { - $($enum_type::$variant => - kernel::num::Bounded::<$width, _>::new::<{ $value }>()),* + $($enum_type::$variant => kernel::num::cv!($value)),* } } }
rust/kernel/bitfield.rs +4 -4
@@ -21,7 +21,7 @@//! } //! //! // Valid value for the `blue` field. -//! let blue = Bounded::<u16, 5>::new::<0x18>(); +//! let blue: Bounded<u16, 5> = cv!(0x18); //! //! // Setters can be chained. Values ranges are checked at compile-time. //! let color = Rgb::zeroed()
@@ -229,9 +229,9 @@//! impl From<Mode> for Bounded<u32, 2> { //! fn from(m: Mode) -> Self { //! match m { -//! Mode::Low => Bounded::<u32, _>::new::<0>(), -//! Mode::High => Bounded::<u32, _>::new::<1>(), -//! Mode::Auto => Bounded::<u32, _>::new::<2>(), +//! Mode::Low => cv!(0), +//! Mode::High => cv!(1), +//! Mode::Auto => cv!(2), //! } //! } //! }
Signature · 1 line
2.55.0
PATCH v8 6/12 rust: sizes: add sub-1K size constants
In reply to Eliot CourtneyAdd some more size constants, mirroring include/linux/sizes.h. This is useful for making Alignment implement SizeConstants in a following patch, because these are more common alignment values.
--- rust/kernel/sizes.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
rust/kernel/sizes.rs +20 -0
@@ -35,6 +35,26 @@macro_rules! define_sizes { ($($type:ty),* $(,)?) => {define_sizes! (@internal [$($type ),*] +/// `0x0000_0001`. +SZ_1 , +/// `0x0000_0002`. +SZ_2 , +/// `0x0000_0004`. +SZ_4 , +/// `0x0000_0008`. +SZ_8 , +/// `0x0000_0010`. +SZ_16 , +/// `0x0000_0020`. +SZ_32 , +/// `0x0000_0040`. +SZ_64 , +/// `0x0000_0080`. +SZ_128 , +/// `0x0000_0100`. +SZ_256 , +/// `0x0000_0200`. +SZ_512 ,/// `0x0000_0400`. SZ_1K ,/// `0x0000_0800`.
Signature · 1 line
2.55.0
PATCH v8 7/12 rust: sizes: implement SizeConstants for Alignment
In reply to Eliot CourtneyCurrently, constructing an alignment is quite verbose:
Alignment::new::<8>()
It's unfortunate because it disincentivizes using it at interface boundaries. Implement SizeConstants for Alignment so we can write e.g. Alignment::SZ_8 instead.
--- rust/kernel/sizes.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-)
rust/kernel/sizes.rs +26 -1
@@ -13,6 +13,11 @@//! these constants as [`u64`] (or [`u32`]) rather than [`usize`], because //! device address spaces are sized independently of the CPU pointer width. //! +//! The trait is also implemented for [`Alignment`], providing each size as a +//! compile-time validated alignment. +//! +//! [`Alignment`]: crate::ptr::Alignment +//! //! # Examples //! //! ```
@@ -105,6 +110,7 @@ macro_rules! define_sizes { (@internal [$($type:ty),*] $($names_and_metas:tt)*) => { define_sizes!(@consts_and_trait $($names_and_metas)*); define_sizes!(@impls [$($type),*] $($names_and_metas)*); + define_sizes!(@impl_alignment $($names_and_metas)*); }; (@consts_and_trait $($(#[$meta:meta])* $name:ident,)*) => {
@@ -119,13 +125,22 @@ macro_rules! define_sizes {/// choose the width that matches their hardware. All `SZ_*` values fit /// in a [`u32`], so all implementations are lossless. /// +/// Also implemented for [`Alignment`], providing each size as a +/// compile-time validated alignment. +/// +/// [`Alignment`]: crate::ptr::Alignment +/// /// # Examples /// /// ``` -/// use kernel::sizes::SizeConstants; +/// use kernel::{ +/// ptr::Alignment, +/// sizes::SizeConstants, // +/// }; /// /// let gpu_heap = 14 * u64::SZ_1M; /// let mmio_window = u32::SZ_16M; +/// let page_align = Alignment::SZ_4K; /// ``` pub trait SizeConstants { $(
@@ -137,6 +152,16 @@ pub trait SizeConstants { (@impls [] $($(#[$meta:meta])* $name:ident,)*) => {}; + (@impl_alignment $($(#[$meta:meta])* $name:ident,)*) => { + impl SizeConstants for crate::ptr::Alignment { + $( + $(#[$meta])* + // A non-power-of-two constant will fail the build here if used. + const $name: Self = crate::ptr::Alignment::new::<{ self::$name }>(); + )* + } + }; + (@impls [$first:ty $(, $rest:ty)*] $($(#[$meta:meta])* $name:ident,)*) => { impl SizeConstants for $first { $(
Signature · 1 line
2.55.0
PATCH v8 8/12 rust: use Alignment size constants
In reply to Eliot CourtneyUse SizeConstants for Alignment that are implemented now.
--- drivers/gpu/nova-core/fb.rs | 10 +++++----- drivers/gpu/nova-core/fb/hal/gb100.rs | 3 +-- drivers/gpu/nova-core/fsp.rs | 4 ++-- drivers/gpu/nova-core/gsp/fw.rs | 12 +++--------- drivers/gpu/nova-core/vbios.rs | 7 +++++-- rust/kernel/gpu/buddy.rs | 26 +++++++++++++------------- rust/kernel/io.rs | 5 +++-- 7 files changed, 32 insertions(+), 35 deletions(-)
drivers/gpu/nova-core/fb.rs +5 -5
@@ -219,7 +219,7 @@ pub(crate) fn new( };let frts = { -const FRTS_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_128K >(); +const FRTS_DOWN_ALIGN :Alignment =Alignment ::SZ_128K ;let frts_size:u64 = hal.frts_size ();let frts_base = vga_workspace.start.align_down (FRTS_DOWN_ALIGN ) - frts_size;
@@ -227,7 +227,7 @@ pub(crate) fn new( };let boot = { -const BOOTLOADER_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_4K >(); +const BOOTLOADER_DOWN_ALIGN :Alignment =Alignment ::SZ_4K ;let bootloader_size = u64::from_safe_cast (gsp_fw.bootloader.ucode.size ());let bootloader_base = (frts.start - bootloader_size).align_down (BOOTLOADER_DOWN_ALIGN );
@@ -235,7 +235,7 @@ pub(crate) fn new( };let elf = { -const ELF_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_64K >(); +const ELF_DOWN_ALIGN :Alignment =Alignment ::SZ_64K ;let elf_size = u64::from_safe_cast (gsp_fw.size);let elf_addr = (boot.start - elf_size).align_down (ELF_DOWN_ALIGN );
@@ -245,7 +245,7 @@ pub(crate) fn new(let (vf_partition_count, wpr2_heap_size) =wpr2_heap_params (chipset, vgpu_state, fb.end)?;let wpr2_heap = { -const WPR2_HEAP_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_1M >(); +const WPR2_HEAP_DOWN_ALIGN :Alignment =Alignment ::SZ_1M ;let wpr2_heap_addr = elf .start .checked_sub (wpr2_heap_size)
@@ -256,7 +256,7 @@ pub(crate) fn new( };let wpr2 = { -const WPR2_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_1M >(); +const WPR2_DOWN_ALIGN :Alignment =Alignment ::SZ_1M ;let wpr2_addr = (wpr2_heap.start - u64::from_safe_cast (size_of ::<gsp::GspFwWprMeta >())) .align_down (WPR2_DOWN_ALIGN );
drivers/gpu/nova-core/fb/hal/gb100.rs +1 -2
@@ -82,8 +82,7 @@ fn write_sysmem_flush_page_gb100(bar: Bar0<'_>, addr: Bounded<u64, 52>) {// This PMU reservation size is r570-specific. pub (super )const fn pmu_reserved_size_gb100 () ->u32 { -usize_into_u32 ::<{const_align_up (SZ_8M +SZ_16M +SZ_4K ,Alignment ::new ::<SZ_128K >()).unwrap () }>( - ) +usize_into_u32 ::<{const_align_up (SZ_8M +SZ_16M +SZ_4K ,Alignment ::SZ_128K ).unwrap () }>() }impl FbHal for Gb100 {
drivers/gpu/nova-core/fsp.rs +2 -2
@@ -17,7 +17,7 @@ Alignable, Alignment, // }, - sizes::SZ_2M, + sizes::SizeConstants, time::Delta, transmute::{AsBytes ,
@@ -257,7 +257,7 @@ fn frts_vidmem_offset(hal: &dyn hal::FspHal, fb_info: &FbSizes) -> Result<u64> {if fb_info.pmu_reserved_size !=0 { offset = (offset + u64::from (fb_info.pmu_reserved_size))// The 2 MiB alignment is r570-specific. - .align_up (Alignment ::new ::<SZ_2M >()) + .align_up (Alignment ::SZ_2M ) .ok_or (EINVAL )?; }
drivers/gpu/nova-core/gsp/fw.rs +3 -9
@@ -25,10 +25,7 @@ Alignment, KnownSize, // }, - sizes::{ - SizeConstants, - SZ_128K, // - }, + sizes::SizeConstants, transmute::{AsBytes ,FromBytes ,//
@@ -63,7 +60,7 @@enum GspFwHeapParams {}/// Minimum required alignment for the GSP heap. -const GSP_HEAP_ALIGNMENT :Alignment =Alignment ::new ::<{1 <<20 }>(); +const GSP_HEAP_ALIGNMENT :Alignment =Alignment ::SZ_1M ;impl GspFwHeapParams {/// Returns the amount of GSP-RM heap memory used during GSP-RM boot and initialization (up to
@@ -209,10 +206,7 @@ pub(crate) fn from_ranges<'a>( bootBinOffset: ranges.boot.start, frtsOffset: ranges.frts.start, frtsSize: ranges.frts.len(), - gspFwWprEnd: ranges - .vga_workspace - .start - .align_down(Alignment::new::<SZ_128K>()), + gspFwWprEnd: ranges.vga_workspace.start.align_down(Alignment::SZ_128K), gspFwHeapVfPartitionCount: ranges.vf_partition_count, fbSize: ranges.fb.len(), vgaWorkspaceOffset: ranges.vga_workspace.start,
drivers/gpu/nova-core/vbios.rs +5 -2
@@ -11,7 +11,10 @@ Alignment, // }, register, - sizes::SZ_4K, + sizes::{ + SizeConstants, + SZ_4K, // + }, sync::aref::ARef, };
@@ -282,7 +285,7 @@ fn next(&mut self) -> Option<Self::Item> {// Advance to next image (aligned to 512 bytes). self.current_offset += image_size; - self.current_offset = self.current_offset.align_up (Alignment ::new ::<512 >())?; + self.current_offset = self.current_offset.align_up (Alignment ::SZ_512 )?;Some (Ok (full_image)) }
rust/kernel/gpu/buddy.rs +13 -13
@@ -31,11 +31,11 @@//! let buddy = GpuBuddy::new(GpuBuddyParams { //! base_offset: 0, //! size: SZ_1G as u64, -//! chunk_size: Alignment::new::<SZ_4K>(), +//! chunk_size: Alignment::SZ_4K, //! })?; //! //! assert_eq!(buddy.size(), SZ_1G as u64); -//! assert_eq!(buddy.chunk_size(), Alignment::new::<SZ_4K>()); +//! assert_eq!(buddy.chunk_size(), Alignment::SZ_4K); //! let initial_free = buddy.avail(); //! //! // Allocate 16MB. Block lands at the top of the address range.
@@ -43,7 +43,7 @@//! buddy.alloc_blocks( //! GpuBuddyAllocMode::Simple, //! SZ_16M as u64, -//! Alignment::new::<SZ_16M>(), +//! Alignment::SZ_16M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -74,14 +74,14 @@//! # let buddy = GpuBuddy::new(GpuBuddyParams { //! # base_offset: 0, //! # size: SZ_1G as u64, -//! # chunk_size: Alignment::new::<SZ_4K>(), +//! # chunk_size: Alignment::SZ_4K, //! # })?; //! # let initial_free = buddy.avail(); //! let topdown = KBox::pin_init( //! buddy.alloc_blocks( //! GpuBuddyAllocMode::TopDown, //! SZ_16M as u64, -//! Alignment::new::<SZ_16M>(), +//! Alignment::SZ_16M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -114,7 +114,7 @@//! # let buddy = GpuBuddy::new(GpuBuddyParams { //! # base_offset: 0, //! # size: SZ_1G as u64, -//! # chunk_size: Alignment::new::<SZ_4K>(), +//! # chunk_size: Alignment::SZ_4K, //! # })?; //! # let initial_free = buddy.avail(); //! // Create fragmentation by allocating 4MB blocks at [0,4M) and [8M,12M).
@@ -122,7 +122,7 @@//! buddy.alloc_blocks( //! GpuBuddyAllocMode::Range(0..SZ_4M as u64), //! SZ_4M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -133,7 +133,7 @@//! buddy.alloc_blocks( //! GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64), //! SZ_4M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -145,7 +145,7 @@//! buddy.alloc_blocks( //! GpuBuddyAllocMode::Range(0..SZ_16M as u64), //! SZ_8M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -178,14 +178,14 @@//! let small = GpuBuddy::new(GpuBuddyParams { //! base_offset: 0, //! size: SZ_16M as u64, -//! chunk_size: Alignment::new::<SZ_4K>(), +//! chunk_size: Alignment::SZ_4K, //! })?; //! //! let _hole1 = KBox::pin_init( //! small.alloc_blocks( //! GpuBuddyAllocMode::Range(0..SZ_4M as u64), //! SZ_4M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -195,7 +195,7 @@//! small.alloc_blocks( //! GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64), //! SZ_4M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlags::default(), //! ), //! GFP_KERNEL,
@@ -206,7 +206,7 @@//! small.alloc_blocks( //! GpuBuddyAllocMode::Simple, //! SZ_8M as u64, -//! Alignment::new::<SZ_4M>(), +//! Alignment::SZ_4M, //! GpuBuddyAllocFlag::Contiguous, //! ), //! GFP_KERNEL,
rust/kernel/io.rs +3 -2
@@ -15,7 +15,8 @@ ptr::{ Alignment, KnownSize, // - }, // + }, + sizes::SizeConstants, // };pub mod mem;
@@ -85,7 +86,7 @@ pub fn ptr_try_from_raw_parts_mut(base: *mut u8, size: usize) -> Result<*mut Selimpl <const SIZE :usize >KnownSize for Region <SIZE > {const MIN_SIZE :usize =SIZE ;// Alignment of 4 is the most common; different base types can be added once required. -const MIN_ALIGN :Alignment =Alignment ::new ::<4 >(); +const MIN_ALIGN :Alignment =Alignment ::SZ_4 ;#[inline(always)] fn size (p: *const Self ) ->usize {
Signature · 1 line
2.55.0
PATCH v8 9/12 rust: bitmap: add contiguous area operations
In reply to Eliot CourtneyAdd bindings for area operations on bitmaps. Each one is made safe by adding some extra checks compared to the underlying C code (for example, checking bounds) and with additional checks to catch likely erroneous usage if CONFIG_RUST_BITMAP_HARDENED is on.
Add tests demonstrating the edge cases.
--- rust/kernel/bitmap.rs | 241 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 239 insertions(+), 2 deletions(-)
rust/kernel/bitmap.rs +239 -2
@@ -10,7 +10,11 @@use crate ::bindings;#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] use crate ::pr_err; -use core::ptr::NonNull ; +use crate ::ptr::Alignment ; +use core::{ + num::NonZero , + ptr::NonNull ,// +};/// Represents a C bitmap. Wraps underlying C bitmap API. ///
@@ -525,13 +529,159 @@ pub fn next_zero_bit(&self, start: usize) -> Option<usize> {Some (index) } } + +/// Finds a contiguous area of `nbits` zero bits at or after `start`, where the area plus +/// `align_offset` is aligned to `align`. +/// +/// Returns the bit index of the start of the area, or [`None`] if no such area fitting in +/// the bitmap exists. +/// +/// The returned index plus `align_offset` is a multiple of `align`. +/// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `start` is out of bounds. +#[inline] +pub fn next_zero_area_off ( + &self, + start:usize , + nbits:NonZero <usize >, + align:Alignment , + align_offset:usize , + ) ->Option <usize > { +bitmap_assert! ( + start < self.len (), +"`start` must be < {}, was {}" , + self.len (), + start + ); + +let nr = u32::try_from (nbits.get ()).ok ()?; +let align_mask = align.as_usize () -1 ; + +// The C alignment and end arithmetic must not overflow, or it can read out of bounds. +// Overflow is only possible on 32-bit. +#[cfg(not( CONFIG_64BIT ))] + align_mask + .checked_add (self.len ())? + .checked_add (nbits.get ())?; + +// SAFETY: `bitmap_find_next_zero_area_off` is safe to use with an out of bounds `start` +// value and, given the overflow check above, never reads beyond `self.len()` bits. +let index =unsafe { + bindings::bitmap_find_next_zero_area_off ( + self.as_ptr ().cast_mut (), + self.len (), + start, + nr, + align_mask, + align_offset, + ) + }; + + (index < self.len ()).then_some (index) + } + +/// Finds a contiguous area of `nbits` zero bits at or after `start`, aligned to `align`. +/// +/// Returns the bit index of the start of the area, or [`None`] if no such area fitting in +/// the bitmap exists. +/// +/// The returned index is a multiple of `align`. +/// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `start` is out of bounds. +/// +/// # Examples +/// +/// ``` +/// use kernel::{ +/// alloc::{AllocError, flags::GFP_KERNEL}, +/// bitmap::BitmapVec, +/// ptr::Alignment, +/// sizes::SizeConstants, // +/// }; +/// +/// let mut b = BitmapVec::new(64, GFP_KERNEL)?; +/// +/// assert_eq!(Some(0), b.next_zero_area(0, cv!(8), Alignment::SZ_1)); +/// b.set(0, cv!(5)); +/// assert_eq!(Some(5), b.next_zero_area(0, cv!(8), Alignment::SZ_1)); +/// assert_eq!(Some(8), b.next_zero_area(0, cv!(8), Alignment::SZ_8)); +/// assert_eq!(None, b.next_zero_area(0, cv!(65), Alignment::SZ_1)); +/// # Ok::<(), AllocError>(()) +/// ``` +#[inline] +pub fn next_zero_area ( + &self, + start:usize , + nbits:NonZero <usize >, + align:Alignment , + ) ->Option <usize > { + self.next_zero_area_off (start, nbits, align,0 ) + } + +/// Sets a contiguous area of `nbits` bits starting at `start`. +/// +/// If CONFIG_RUST_BITMAP_HARDENED is not enabled and the area `start..start + nbits` is out of +/// bounds, does nothing. +/// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and the area `start..start + nbits` is out +/// of bounds. +#[inline] +pub fn set (&mut self, start:usize , nbits:NonZero <usize >) { +bitmap_assert_return! ( + start + .checked_add (nbits.get ()) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits.get ()), + self.len () + ); +// SAFETY: The area `start..start + nbits` is within bounds and a `Bitmap` is at most +// `i32::MAX` bits, so the casts are lossless. +unsafe { bindings::__bitmap_set (self.as_mut_ptr (), startas u32 , nbits.get ()as i32 ) }; + } + +/// Clears a contiguous area of `nbits` bits starting at `start`. +/// +/// If CONFIG_RUST_BITMAP_HARDENED is not enabled and the area `start..start + nbits` is out of +/// bounds, does nothing. +/// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and the area `start..start + nbits` is out +/// of bounds. +#[inline] +pub fn clear (&mut self, start:usize , nbits:NonZero <usize >) { +bitmap_assert_return! ( + start + .checked_add (nbits.get ()) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits.get ()), + self.len () + ); +// SAFETY: The area `start..start + nbits` is within bounds and a `Bitmap` is at most +// `i32::MAX` bits, so the casts are lossless. +unsafe { bindings::__bitmap_clear (self.as_mut_ptr (), startas u32 , nbits.get ()as i32 ) }; + } }#[cfg( CONFIG_RUST_BITMAP_KUNIT_TEST )] #[macros::kunit_tests(rust_kernel_bitmap)] mod tests {use super ::*; -use kernel::alloc::flags::GFP_KERNEL ; +use kernel::{ + alloc::flags::GFP_KERNEL , + num::cv, + sizes::SizeConstants ,// + };#[test] fn bitmap_borrow () {
@@ -642,4 +792,91 @@ fn bitmap_copy_and_extend() -> Result<(), AllocError> {assert_eq! (Some (17 ), long_bitmap.last_bit ());Ok (()) } + +#[test] +fn bitmap_area_set_clear_find () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (128 ,GFP_KERNEL )?; + +assert_eq! (Some (0 ), b.next_zero_area (0 ,cv! (5 ),Alignment ::SZ_1 )); + b.set (0 ,cv! (5 ));// Now contains {[0, 5)}. + +assert_eq! (Some (0 ), b.next_bit (0 )); +assert_eq! (Some (4 ), b.next_bit (4 )); +assert_eq! (Some (5 ), b.next_zero_bit (0 )); +assert_eq! (Some (5 ), b.next_zero_area (0 ,cv! (5 ),Alignment ::SZ_1 )); +assert_eq! (Some (8 ), b.next_zero_area (0 ,cv! (5 ),Alignment ::SZ_8 )); + + b.set (8 ,cv! (8 ));// Now contains {[0, 5), [8, 16)}. +assert_eq! (Some (16 ), b.next_zero_area (0 ,cv! (4 ),Alignment ::SZ_16 )); +assert_eq! (Some (16 ), b.next_zero_area (0 ,cv! (4 ),Alignment ::SZ_1 )); + + b.clear (0 ,cv! (5 ));// Now contains {[8, 16)}. +assert_eq! (Some (0 ), b.next_zero_area (0 ,cv! (5 ),Alignment ::SZ_1 )); +assert_eq! (Some (8 ), b.next_bit (0 )); +assert_eq! (Some (15 ), b.last_bit ()); + + b.set (60 ,cv! (10 ));// Now contains {[8, 16), [60, 70)}. +assert_eq! (Some (60 ), b.next_bit (16 )); +assert_eq! (Some (69 ), b.last_bit ()); +assert_eq! (Some (16 ), b.next_zero_area (9 ,cv! (40 ),Alignment ::SZ_1 )); +assert_eq! (Some (70 ), b.next_zero_area (0 ,cv! (45 ),Alignment ::SZ_1 )); + + b.clear (62 ,cv! (6 ));// Now contains {[8, 16), [60, 62), [68, 70)}. +assert_eq! (Some (62 ), b.next_zero_area (60 ,cv! (6 ),Alignment ::SZ_1 )); +assert_eq! (Some (61 ), b.next_bit (61 )); +assert_eq! (Some (69 ), b.last_bit ()); +Ok (()) + } + +#[test] +fn bitmap_area_exhaustion () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (64 ,GFP_KERNEL )?; + +assert_eq! (None , b.next_zero_area (0 ,cv! (65 ),Alignment ::SZ_1 )); +assert_eq! (None , b.next_zero_area (0 ,cv! (usize ::MAX ),Alignment ::SZ_1 )); +assert_eq! (None , b.next_zero_area (1 ,cv! (usize ::MAX ),Alignment ::SZ_1 )); + + b.set_bit (0 );// Now contains {[0, 1)}. +assert_eq! (None , b.next_zero_area (0 ,cv! (usize ::MAX ),Alignment ::SZ_1 )); + + b.set (0 ,cv! (61 ));// Now contains {[0, 61)}. +assert_eq! (None , b.next_zero_area (0 ,cv! (4 ),Alignment ::SZ_1 )); +assert_eq! (Some (61 ), b.next_zero_area (0 ,cv! (3 ),Alignment ::SZ_1 )); +assert_eq! (None , b.next_zero_area (0 ,cv! (1 ),Alignment ::SZ_64 )); +Ok (()) + } + +#[test] +fn bitmap_area_off () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (64 ,GFP_KERNEL )?; + + b.set (0 ,cv! (5 ));// Now contains {[0, 5)}. + +// The area plus align_offset starts at a multiple of the alignment. +assert_eq! (Some (7 ), b.next_zero_area_off (0 ,cv! (8 ),Alignment ::SZ_8 ,1 )); +assert_eq! (Some (5 ), b.next_zero_area_off (0 ,cv! (8 ),Alignment ::SZ_8 ,3 )); + +// A zero offset behaves like next_zero_area(). +assert_eq! ( + b.next_zero_area (0 ,cv! (8 ),Alignment ::SZ_8 ), + b.next_zero_area_off (0 ,cv! (8 ),Alignment ::SZ_8 ,0 ) + ); +Ok (()) + } + +#[test] +#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] +fn owned_bitmap_area_out_of_bounds () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (64 ,GFP_KERNEL )?; + +// Should be ignored since out of bounds. + b.set (64 ,cv! (4 )); + b.set (62 ,cv! (8 )); + b.set (usize::MAX ,cv! (1 )); + b.clear (usize::MAX ,cv! (1 )); + b.clear (2048 ,cv! (8 )); +assert_eq! (None , b.next_bit (0 )); +assert_eq! (None , b.next_zero_area (64 ,cv! (1 ),Alignment ::SZ_1 )); +Ok (()) + } }
Signature · 1 line
2.55.0
PATCH v8 10/12 rust: id_pool: add contiguous ID reservation
In reply to Eliot CourtneyAdd IdPool::reserve_ids which allocates a contiguous range with the given offset, count, and alignment.
--- rust/kernel/id_pool.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+)
rust/kernel/id_pool.rs +32 -0
@@ -4,8 +4,14 @@//! Rust API for an ID pool backed by a [`BitmapVec`]. +use core::{ + num::NonZero , + ops::Range ,// +}; +use crate ::alloc::{AllocError ,Flags };use crate ::bitmap::BitmapVec ; +use crate ::ptr::Alignment ;/// Represents a dynamic ID pool backed by a [`BitmapVec`]. ///
@@ -240,6 +246,32 @@ pub fn find_unused_id(&mut self, offset: usize) -> Option<UnusedId<'_>> {pub fn release_id (&mut self, id:usize ) { self.map.clear_bit (id); } + +/// Reserves a contiguous area of `count` IDs at or after `offset`. +/// +/// The start of the returned area is a multiple of `align`. +/// +/// Returns the reserved range upon success, or [`None`] if no such area could be found. +#[inline] +#[must_use] +pub fn reserve_ids ( + &mut self, + offset:usize , + count:NonZero <usize >, + align:Alignment , + ) ->Option <Range <usize >> { +let start = self.map.next_zero_area (offset, count, align)?; + self.map.set (start, count); +Some (start..start + count.get ()) + } + +/// Releases a contiguous area of IDs. +#[inline] +pub fn release_ids (&mut self, range: &Range <usize >) { +if let Some (nbits) =NonZero ::new (range.len ()) { + self.map.clear (range.start, nbits); + } + } }/// Represents an unused id in an [`IdPool`].
Signature · 1 line
2.55.0
PATCH v8 11/12 rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
In reply to Eliot CourtneyCurrent code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.
This allows specifying a real capacity of 0, which was not previously possible. This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.
--- rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +32 -6
@@ -112,13 +112,8 @@ pub fn new() -> Self { }/// Constructs a new [`IdPool`] with space for a specific number of bits. -/// -/// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`]. -/// -/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN #[inline] pub fn with_capacity (num_ids:usize , flags:Flags ) ->Result <Self ,AllocError > { -let num_ids = usize::max (num_ids,BitmapVec ::MAX_INLINE_LEN );let map =BitmapVec ::new (num_ids, flags)?;Ok (Self { map }) }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {/// let resizer = alloc_request.realloc(GFP_KERNEL)?; /// pool.shrink(resizer); /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN); +/// +/// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further. +/// assert!(pool.shrink_request().is_none()); +/// +/// // Neither can a pool with a capacity below `MAX_INLINE_LEN`. +/// let small = IdPool::with_capacity(8, GFP_KERNEL)?; +/// assert!(small.shrink_request().is_none()); /// # Ok::<(), AllocError>(()) /// ``` #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {/// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible. /// +/// Grows to at least [`MAX_INLINE_LEN`]. /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`]. /// +/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN /// [`MAX_LEN`]: BitmapVec::MAX_LEN +/// +/// # Examples +/// +/// ``` +/// use kernel::{ +/// alloc::AllocError, +/// bitmap::BitmapVec, +/// id_pool::IdPool, // +/// }; +/// +/// // Grow goes to at least BitmapVec::MAX_INLINE_LEN. +/// let mut pool = IdPool::with_capacity(0, GFP_KERNEL)?; +/// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN); +/// +/// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN. +/// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN); +/// # Ok::<(), AllocError>(()) +/// ``` #[inline] pub fn grow_request (&self) ->Option <ReallocRequest > { -let num_ids = self.capacity () *2 ; +let num_ids = usize::max (BitmapVec ::MAX_INLINE_LEN , self.capacity () *2 );if num_ids >BitmapVec ::MAX_LEN {return None ; }
Signature · 1 line
2.55.0
PATCH v8 12/12 gpu: nova-core: add ChannelIdPool
In reply to Eliot CourtneyAdd ChannelIdPool which adds automatic tracking and releasing of channel IDs on top of IdPool. This is necessary for apportioning ranges of channel IDs to be used in e.g. vGPU.
Channel IDs are allocated as a contiguous sequence with a specific length and sometimes a specific alignment [1] for vGPU. The ID space is small (limited to 2048) and allocation is not on a hot path, so a bitmap-backed IdPool is a better fit than IDA/xarray (which allocate a single ID within a range, not a contiguous sequence) or a maple tree (where aligned allocation needs an alloc_range()+erase() retry loop that essentially reimplements bitmap_find_next_zero_area()) [2]. It is also faster than maple tree [3].
--- drivers/gpu/nova-core/gpu.rs | 2 + drivers/gpu/nova-core/gpu/channel.rs | 198 +++++++++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+)
drivers/gpu/nova-core/gpu.rs +2 -0
@@ -33,6 +33,8 @@ vgpu::VgpuManager, // }; +#[cfg_attr(not( CONFIG_KUNIT = "y" ), expect(dead_code))] +mod channel;mod hal;macro_rules! define_chipset {
drivers/gpu/nova-core/gpu/channel.rs new file +198 -0
198 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v8 02/12] rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Eliot CourtneyThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Incomplete SAFETY comments for `Bitmap::from_raw` calls in unit tests. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Incomplete SAFETY comments for Bitmap::from_raw calls in unit tests. --
commit f2871aa21f86bcf804086540b9bc1b66aba9457a
Author: Eliot Courtney <[email protected]>
rust: bitmap: restrict bitmap length to at most i32::MAX
This restricts all Bitmaps (even non-BitmapVec backed ones) to a maximum size of i32::MAX to simplify operations and match BitmapVec::MAX_LEN. It adds this requirement to the unsafe preconditions and invariants of Bitmap functions.
Quoted 4 lines
rust/kernel/bitmap.rs +0
-0
[ ... ]
Quoted 1 line
rust/kernel/bitmap.rs +0
-0@@ -17,24 +17,59 @@
[ ... ]
Quoted 5 lines
impl Bitmap { /// Borrows a C bitmap. ///rust/kernel/bitmap.rs +2
-0+/// # Panics +///
rust/kernel/bitmap.rs line 63
Quoted 10 lines
rust/kernel/bitmap.rs +3
-0+/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds `i32::MAX`. +/// /// # Safety /// /// * `ptr` holds a non-null address of an initialized array of `unsigned long` /// that is large enough to hold `nbits` bits. +/// * `nbits` must not exceed `i32::MAX`. /// * the array must not be freed for the lifetime of this [`Bitmap`] /// * concurrent access only happens through atomic operations pub unsafe fn from_raw <'a>(ptr: *const usize , nbits:usize ) -> &'aBitmap {
[Severity: Low]
Since a new safety precondition is added here, shouldn't the SAFETY comments on existing callers be updated to explain how this condition is satisfied?
For example, the test code in rust/kernel/bitmap.rs calls from_raw() but the comments only justify the array length:
rust/kernel/bitmap.rs:tests::bitmap_borrow() {
...
// SAFETY: `fake_c_bitmap` is an array of expected length.
let b = unsafe { Bitmap::from_raw(fake_bitmap.as_ptr(), fake_bitmap_len) };
...
}rust/kernel/bitmap.rs:tests::bitmap_copy() {
...
// SAFETY: `fake_c_bitmap` can be used as one-element array of expected length.
let b = unsafe { Bitmap::from_raw(core::ptr::addr_of!(fake_bitmap), 8) };
...
}Should these be updated to also mention that fake_bitmap_len and 8 do not exceed i32::MAX?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v8 11/12] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
In reply to Eliot CourtneyThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Calling `find_unused_id(0)` or `reserve_ids(0, ...)` on an `IdPool` initialized with a capacity of…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Calling find_unused_id(0) or reserve_ids(0, ...) on an IdPool initialized with a capacity of 0 triggers a kernel panic when CONFIG_RUST_BITMAP_HARDENED is enabled. --
commit c0cd93bbf9f36768f04bc377021b9e32ae0dce05
Author: Eliot Courtney <[email protected]>
rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
This commit modifies IdPool::with_capacity to stop rounding the capacity up to BitmapVec::MAX_INLINE_LEN. This allows explicitly creating pools with 0 capacity, and adjusts grow_request and shrink_request to handle the new floor.
Quoted 8 lines
rust/kernel/id_pool.rs +0
-0@@ -112,13 +112,8 @@ pub fn new() -> Self { }/// Constructs a new [`IdPool`] with space for a specific number of bits.
rust/kernel/id_pool.rs pub fn new() -> Self { · line 119
Quoted 10 lines
rust/kernel/id_pool.rs +0
-5-/// -/// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`]. -/// -/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN #[inline] pub fn with_capacity (num_ids:usize , flags:Flags ) ->Result <Self ,AllocError > { -let num_ids = usize::max (num_ids,BitmapVec ::MAX_INLINE_LEN );let map =BitmapVec ::new (num_ids, flags)?;Ok (Self { map }) }
[Severity: High]
Does allowing a capacity of 0 here introduce a kernel panic during standard allocations if CONFIG_RUST_BITMAP_HARDENED is enabled?
If a caller attempts to allocate an ID on a 0-capacity pool using patterns like pool.find_unused_id(0) or pool.reserve_ids(0, ...), the call delegates directly to the underlying bitmap without its own bounds check:
IdPool::find_unused_id() {
Some(UnusedId {
id: self.map.next_zero_bit(offset)?,
pool: self,
})
}This passes offset=0 to Bitmap::next_zero_bit(), which contains an assertion that start < self.len(). Since 0 < 0 is false on a 0-capacity pool, it panics immediately instead of gracefully returning None to prompt a grow_request().
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
[email protected]
AI reviewRe: [PATCH v8 09/12] rust: bitmap: add contiguous area operations
In reply to Eliot CourtneyThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Overly strict bounds check in `next_zero_area_off` causes unwarranted panics for valid edge…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Overly strict bounds check in next_zero_area_off causes unwarranted panics for valid edge cases when CONFIG_RUST_BITMAP_HARDENED is enabled. --
commit 9d58aea77dca5a824882cabebc4724be42a07915
Author: Eliot Courtney <[email protected]>
rust: bitmap: add contiguous area operations
This commit introduces bindings for contiguous area operations on bitmaps, specifically next_zero_area_off(), next_zero_area(), set(), and clear(). It adds safety bounds checking that can be hardened via CONFIG_RUST_BITMAP_HARDENED, along with KUnit tests for these operations.
Quoted 4 lines
rust/kernel/bitmap.rs +0
-0
[ ... ]
Quoted 20 lines
rust/kernel/bitmap.rs +16
-0@@ -525,13 +529,159 @@ pub fn next_zero_bit(&self, start: usize) -> Option<usize> {Some (index) } } + +/// Finds a contiguous area of `nbits` zero bits at or after `start`, where the area plus +/// `align_offset` is aligned to `align`. +/// +/// Returns the bit index of the start of the area, or [`None`] if no such area fitting in +/// the bitmap exists. +/// +/// The returned index plus `align_offset` is a multiple of `align`. +/// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `start` is out of bounds. +#[inline] +pub fn next_zero_area_off ( + &self, + start: usize,
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 557
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ nbits: NonZero<usize>, + align: Alignment, + align_offset: usize, + ) -> Option<usize> { +bitmap_assert! ( + start < self.len (), +"`start` must be < {}, was {}" , + self.len (), + start + );
[Severity: Medium]
When CONFIG_RUST_BITMAP_HARDENED is enabled, does this overly strict bounds check cause unwarranted panics for valid edge cases?
Calling next_zero_area_off() (or its wrapper next_zero_area()) on an empty BitmapVec (length 0) will panic immediately because 0 < 0 is false. Additionally, standard iteration loops that update start to area_start + nbits will panic on their final check if the previous area ended exactly at the bitmap boundary (start == self.len()).
The underlying C implementation bitmap_find_next_zero_area_off() safely handles start >= self.len() and returns an out-of-bounds index, which this Rust wrapper correctly turns into a None return. Could this assertion be relaxed to start <= self.len() to avoid these spurious panics?
Quoted 3 lines
rust/kernel/bitmap.rs +3
-0+ +let nr = u32::try_from (nbits.get ()).ok ()?; +let align_mask = align.as_usize () -1 ;
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Alice Ryhl
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
In reply to Eliot CourtneyQuoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).
Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>
This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rs
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8;
const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int;
const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int;
const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int;
const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int;
const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int;
const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int;
const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int;
const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int;
const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int;
const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Alice
Alexandre Courbot
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rs
Quoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8;
const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int;
const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int;
const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int;
const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int;
const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int;
const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int;
const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int;
const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int;
const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int;
const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;const_as! [1] should do the trick for this, provided you don't need to create a const NonZero.
Alexandre Courbot
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;
Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.
... but I agree it would be nice to be able to use this in const context. And there is an overlap with const_as! that becomes more obvious the more I look at it.
In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same cv! macro, with as many branches as we have types we want to initialize from a constant value? For instance:
// Does what `const_as!` currently does under the hood.
const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT));
// Calls `NonZero::new().unwrap()` under the hood.
const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE));
// Calls `Bounded::new::<{ ...}>()` under the hood.
const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in cv! per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye bye const_as's awkward =>), albeit it would have the limitations of such a semantic dispatch.
Even the name const_as! wasn't really accurate to begin with: what it really emulates is a const try_from, and we even discussed implementing it in these terms in the future.
I'm sure the idea needs more polishing but I think there's something to explore here.
Re: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.
Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Yeah I agree that const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).
I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
Alternatively, what about just directly merging them so you use cv!(5) (the non const context FromConst::from_const dispatcher in this series) or cv!(value => u8) (exactly const_as!), with the => distinguishing between the two?
So this is what would work for Alice's example (const_as! but pushed inside cv!):
``` const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT => u8); ```
When we have const traits then we could remove the => syntax I think.
Gary Guo
reviewerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 81 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
Alternatively, what about just directly merging them so you use cv!(5) (the non const context
FromConst::from_constdispatcher in this series) or cv!(value => u8) (exactlyconst_as!), with the => distinguishing between the two?
Quoted 7 lines
So this is what would work for Alice's example (
const_as! but pushed inside cv!):``` const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT => u8); ```When we have const traits then we could remove the => syntax I think.
It'd still be useful to allow explicit specification if user prefers. I think it makes sense to (ultimately) translate
cv!(val)
to
const { FromConst::from_const(val as i128) }and
cv!(val => ty)
to
const { ty::from_const(val as i128) }I think there might be some tricks possible to get it working without const trait, e.g. for Bounded and Alignment we could simply add an inherent method
#[doc(hidden)]
#[inline]
const fn __from_const(val: i128) -> Self { ... }but I'll need to think about how to make it work with core types.
Best,
Gary
Alexandre Courbot
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
In reply to Eliot CourtneyQuoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
It also has the benefit of relying less on type inference, i.e. cv!(5) requires the caller to specify the type even with a let statement, whereas you could do let v = cv!(NonZero::new(5)); and it would work as expected.
I also feel that we should be able to support const items with cv! today, which is not going to be possible with the trait-based approach, so if we switch to macro dispatch we need differentiating syntax to decide the arm.
Quoted 6 lines
Alternatively, what about just directly merging them so you use cv!(5) (the non const context
FromConst::from_constdispatcher in this series) or cv!(value => u8) (exactlyconst_as!), with the => distinguishing between the two?
Quoted 7 lines
So this is what would work for Alice's example (
const_as! but pushed inside cv!):``` const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT => u8); ```When we have const traits then we could remove the => syntax I think.
Agreed that they should be merged in any case, even if we keep the current syntax of const_as, the macro itself is hard to justify in a world where cv exists. And cv also corresponds better to the actual purpose of const_as (which is not, as I initially thought, a const as, but rather a try_from).
Gary Guo
reviewerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 82 lines · Alexandre Courbot
Quoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
Quoted 4 lines
It also has the benefit of relying less on type inference, i.e.
cv!(5)requires the caller to specify the type even with aletstatement, whereas you could dolet v = cv!(NonZero::new(5));and it would work as expected.
Even with const try_from we'd still want cv!() to avoid having to write
const { Type::try_from(...).unwrap() }I think having => syntax is great because it is a good place to *optionally* require type annotation.
For enum repr for example, I think it'd be great that
const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT);
would work directly. It might need some tricks, which I have hard time coming up as I'm not feeling very well today, but I'll give it a shot over the weekend...
Best,
Gary
Alice Ryhl
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 96 lines · Gary Guo
Quoted 82 lines · Alexandre Courbot
Quoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
Quoted 4 lines
It also has the benefit of relying less on type inference, i.e.
cv!(5)requires the caller to specify the type even with aletstatement, whereas you could dolet v = cv!(NonZero::new(5));and it would work as expected.Even with const
try_fromwe'd still wantcv!()to avoid having to writeconst { Type::try_from(...).unwrap() }I think having
=>syntax is great because it is a good place to *optionally* require type annotation.
Quoted 6 lines
For enum repr for example, I think it'd be great that
const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT);would work directly. It might need some tricks, which I have hard time coming up as I'm not feeling very well today, but I'll give it a shot over the weekend...
One could potentially define a trait with a MIN and MAX value constant, and then implement cv! like this:
1. Verify that the value lies between MIN and MAX.
2. Cast the value to uNN of the same size as the target type.
3. Transmute the uNN to the target type.
Since the trait has no methods, this works in const eval.
Alice
Re: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 107 lines · Alice Ryhl
Quoted 96 lines · Gary Guo
Quoted 82 lines · Alexandre Courbot
Quoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
Quoted 4 lines
It also has the benefit of relying less on type inference, i.e.
cv!(5)requires the caller to specify the type even with aletstatement, whereas you could dolet v = cv!(NonZero::new(5));and it would work as expected.Even with const
try_fromwe'd still wantcv!()to avoid having to writeconst { Type::try_from(...).unwrap() }I think having
=>syntax is great because it is a good place to *optionally* require type annotation.Quoted 6 lines
For enum repr for example, I think it'd be great that
const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT);would work directly. It might need some tricks, which I have hard time coming up as I'm not feeling very well today, but I'll give it a shot over the weekend...
One could potentially define a trait with a MIN and MAX value constant, and then implement cv! like this:
Quoted 7 lines
1. Verify that the value lies between MIN and MAX.
2. Cast the value to uNN of the same size as the target type.
3. Transmute the uNN to the target type.Since the trait has no methods, this works in const eval.
Alice
Using an associated const by itself appears to work - I tried this which is very similar to Alice's suggested approach above:
```
macro_rules! const_assert {
($condition:expr $(,$arg:literal)?) => {
const { ::core::assert!($condition $(,$arg)?) };
};
}
trait FromConst<const V: i128>: Sized {
const VALUE: Self;
}
macro_rules! cv {
(@widen $v:expr) => {{
#[allow(unused_comparisons, unused_assignments)]
{
let v = $v;
let r = v as i128;
let mut back = v;
back = r as _;
::core::assert!(
back == v && (v < 0) == (r < 0),
"value cannot be losslessly widened to `i128`"
);
r
}
}};
($v:expr => $t:ty) => {
<$t as FromConst<{ cv!(@widen $v) }>>::VALUE
};
($v:expr) => {
<_ as FromConst<{ cv!(@widen $v) }>>::VALUE
};
}
macro_rules! impl_from_const_int {
($($t:ty)*) => {$(
impl<const V: i128> FromConst<V> for $t {
const VALUE: Self = {
const_assert!(
V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128,
"Constant cannot be represented by the target type."
);
V as $t
};
}
impl<const V: i128> FromConst<V> for NonZero<$t> {
const VALUE: Self = {
const_assert!(
V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128,
"Constant cannot be represented by the underlying type."
);
NonZero::new(V as $t).unwrap()
};
}
)*};
}
impl_from_const_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
impl<const V: i128> FromConst<V> for Alignment {
const VALUE: Self = {
const_assert!(V > 0 && V <= usize::MAX as i128);
// The unwrap fails the build if `V` is not a power of two.
Alignment::new_checked(V as usize).unwrap()
};
}
const A: u8 = cv!(200u32);
const B: NonZero<u8> = cv!(5);
const C: Alignment = cv!(4096);
const D: u8 = cv!(200u32 => u8);
```Alexandre Courbot
maintainerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
Quoted 119 lines · Eliot Courtney
Quoted 107 lines · Alice Ryhl
Quoted 96 lines · Gary Guo
Quoted 82 lines · Alexandre Courbot
Quoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
Quoted 4 lines
It also has the benefit of relying less on type inference, i.e.
cv!(5)requires the caller to specify the type even with aletstatement, whereas you could dolet v = cv!(NonZero::new(5));and it would work as expected.Even with const
try_fromwe'd still wantcv!()to avoid having to writeconst { Type::try_from(...).unwrap() }I think having
=>syntax is great because it is a good place to *optionally* require type annotation.Quoted 6 lines
For enum repr for example, I think it'd be great that
const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT);would work directly. It might need some tricks, which I have hard time coming up as I'm not feeling very well today, but I'll give it a shot over the weekend...
One could potentially define a trait with a MIN and MAX value constant, and then implement cv! like this:
Quoted 7 lines
1. Verify that the value lies between MIN and MAX.
2. Cast the value to uNN of the same size as the target type.
3. Transmute the uNN to the target type.Since the trait has no methods, this works in const eval.
Alice
Using an associated const by itself appears to work - I tried this which is very similar to Alice's suggested approach above:
Quoted 6 lines
```
macro_rules! const_assert { ($condition:expr $(,$arg:literal)?) => { const { ::core::assert!($condition $(,$arg)?) }; }; }
Any reason this cannot use the const_assert already in the kernel crate?
Quoted 16 lines
trait FromConst<const V: i128>: Sized { const VALUE: Self; }macro_rules! cv { (@widen $v:expr) => {{ #[allow(unused_comparisons, unused_assignments)] { let v = $v; let r = v as i128; let mut back = v; back = r as _; ::core::assert!( back == v && (v < 0) == (r < 0),
Quoted 8 lines
"value cannot be losslessly widened to `i128`"
);
r
}
}};
($v:expr => $t:ty) => {
<$t as FromConst<{ cv!(@widen $v) }>>::VALUEnit for the actual posting: make sure to fully qualify cv when calling it recursively (and make sure all symbols are fully qualified).
Quoted 16 lines
}; ($v:expr) => { <_ as FromConst<{ cv!(@widen $v) }>>::VALUE }; }macro_rules! impl_from_const_int { ($($t:ty)*) => {$( impl<const V: i128> FromConst<V> for $t { const VALUE: Self = { const_assert!( V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128, "Constant cannot be represented by the target type." ); V as $t };
Quoted 8 lines
}
impl<const V: i128> FromConst<V> for NonZero<$t> {
const VALUE: Self = {
const_assert!(
V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128,
"Constant cannot be represented by the underlying type."
);Let's also have a const_assert!(V != 0, ...) to provide a better error message than "unwrap on None" if users call this with 0.
Quoted 15 lines
NonZero::new(V as $t).unwrap() }; } )*}; }impl_from_const_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
impl<const V: i128> FromConst<V> for Alignment { const VALUE: Self = { const_assert!(V > 0 && V <= usize::MAX as i128); // The unwrap fails the build if `V` is not a power of two. Alignment::new_checked(V as usize).unwrap() }; }
Quoted 5 lines
const A: u8 = cv!(200u32); const B: NonZero<u8> = cv!(5); const C: Alignment = cv!(4096); const D: u8 = cv!(200u32 => u8); ```
That looks like it could work! IIUC it even supports something like cv!(x => NonZero<u8>). The only limitation is see is that this cannot take expressions using generic parameters, but we can probably work around that.
I guess you'll want to split this out into its own series so it doesn't remain hidden within the ranges/bitmap work. Basically as a replacement for the const_as I was driving [1]. I'll recycle the const_as series to just switch to the kernel converters, and will follow-up with using cv! once it lands.
Since this is going to be a multi-cycle effort we should probably keep the legacy *_into_* functions around for now and remove them in another patch once all users are converted.
Re: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
On Fri Aug 28, 2026 at 12:40 PM JST, Alexandre Courbot wrote:
[...]
Quoted 10 lines
Quoted 9 lines
Using an associated const by itself appears to work - I tried this which is very similar to Alice's suggested approach above:
```
macro_rules! const_assert { ($condition:expr $(,$arg:literal)?) => { const { ::core::assert!($condition $(,$arg)?) }; }; }
Quoted 2 lines
Any reason this cannot use the
const_assertalready in the kernel crate?
No reason. I prototyped this in a single file so I had some misc shims. This is just me copy pasting badly.
Quoted 54 lines
Quoted 17 lines
trait FromConst<const V: i128>: Sized { const VALUE: Self; }macro_rules! cv { (@widen $v:expr) => {{ #[allow(unused_comparisons, unused_assignments)] { let v = $v; let r = v as i128; let mut back = v; back = r as _; ::core::assert!( back == v && (v < 0) == (r < 0),Quoted 8 lines
"value cannot be losslessly widened to `i128`" ); r } }}; ($v:expr => $t:ty) => { <$t as FromConst<{ cv!(@widen $v) }>>::VALUEnit for the actual posting: make sure to fully qualify
cvwhen calling it recursively (and make sure all symbols are fully qualified).Quoted 16 lines
}; ($v:expr) => { <_ as FromConst<{ cv!(@widen $v) }>>::VALUE }; }macro_rules! impl_from_const_int { ($($t:ty)*) => {$( impl<const V: i128> FromConst<V> for $t { const VALUE: Self = { const_assert!( V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128, "Constant cannot be represented by the target type." ); V as $t };Quoted 8 lines
} impl<const V: i128> FromConst<V> for NonZero<$t> { const VALUE: Self = { const_assert!( V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128, "Constant cannot be represented by the underlying type." );
Quoted 2 lines
Let's also have a
const_assert!(V != 0, ...)to provide a better error message than "unwrap on None" if users call this with 0.
Sounds good~
Quoted 22 lines
Quoted 16 lines
NonZero::new(V as $t).unwrap() }; } )*}; }impl_from_const_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
impl<const V: i128> FromConst<V> for Alignment { const VALUE: Self = { const_assert!(V > 0 && V <= usize::MAX as i128); // The unwrap fails the build if `V` is not a power of two. Alignment::new_checked(V as usize).unwrap() }; }Quoted 5 lines
const A: u8 = cv!(200u32); const B: NonZero<u8> = cv!(5); const C: Alignment = cv!(4096); const D: u8 = cv!(200u32 => u8); ```
Quoted 4 lines
That looks like it could work! IIUC it even supports something like
cv!(x => NonZero<u8>). The only limitation is see is that this cannot take expressions using generic parameters, but we can probably work around that.
Yeah agreed. One workaround is just to list each primitive type in the macro, although it doesn't work if you define a type alias or something. I think that's reasonable and not too complex. FWIW I found one potential user that would want to be able to reference generics in cv!. In drm::Device:num_ioctls: T::IOCTLS.len() as i32,
wants to be cv!(T::IOCTLS.len() => i32), which needs this.
Quoted 7 lines
I guess you'll want to split this out into its own series so it doesn't remain hidden within the ranges/bitmap work. Basically as a replacement for the
const_asI was driving [1]. I'll recycle theconst_asseries to just switch to the kernel converters, and will follow-up with usingcv!once it lands.
Quoted 5 lines
Since this is going to be a multi-cycle effort we should probably keep the legacy
*_into_*functions around for now and remove them in another patch once all users are converted.
Yes I'll split it out. Thanks!
Re: [PATCH v8 06/12] rust: sizes: add sub-1K size constants
In reply to Eliot CourtneyQuoted 5 lines · Eliot Courtney
Add some more size constants, mirroring
include/linux/sizes.h. This is useful for makingAlignmentimplementSizeConstantsin a following patch, because these are more common alignment values.Signed-off-by Eliot Courtney <[email protected]>
Re: [PATCH v8 07/12] rust: sizes: implement SizeConstants for Alignment
In reply to Eliot CourtneyQuoted 9 lines · Eliot Courtney
Currently, constructing an alignment is quite verbose:
Alignment::new::<8>()It's unfortunate because it disincentivizes using it at interface boundaries. Implement
SizeConstantsforAlignmentso we can write e.g.Alignment::SZ_8instead.
What's the context for the link? Is this a Suggested-by?
Quoted 1 line
Signed-off-by Eliot Courtney <[email protected]>
Re: [PATCH v8 07/12] rust: sizes: implement SizeConstants for Alignment
Quoted 5 lines · Alexandre Courbot
Quoted 4 lines · Eliot Courtney
Currently, constructing an alignment is quite verbose:
Alignment::new::<8>()
Quoted 7 lines
Quoted 5 lines
It's unfortunate because it disincentivizes using it at interface boundaries. Implement
SizeConstantsforAlignmentso we can write e.g.Alignment::SZ_8instead.What's the context for the link? Is this a
Suggested-by?
Was trying to show the context for the motivation for this change (verbosity). But I can remove this if this is not how you use 'Link:'.
Quoted 4 lines
Quoted 2 lines
Signed-off-by Eliot Courtney <[email protected]>Reviewed-by Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerRe: [PATCH v8 07/12] rust: sizes: implement SizeConstants for Alignment
Quoted 10 lines · Eliot Courtney
Quoted 9 lines · Alexandre Courbot
Quoted 8 lines · Eliot Courtney
Currently, constructing an alignment is quite verbose:
Alignment::new::<8>()It's unfortunate because it disincentivizes using it at interface boundaries. Implement
SizeConstantsforAlignmentso we can write e.g.Alignment::SZ_8instead.
Quoted 6 lines
Quoted 3 lines
Quoted 1 line
What's the context for the link? Is this a
Suggested-by?Was trying to show the context for the motivation for this change (verbosity). But I can remove this if this is not how you use 'Link:'.
The custom is generally to have Link: follow tags like Suggested-by or Fixes, but I guess it is also ok to keep them as general context when nothing matches.
Re: [PATCH v8 07/12] rust: sizes: implement SizeConstants for Alignment
Quoted 4 lines · Alexandre Courbot
The custom is generally to have
Link:follow tags likeSuggested-byorFixes, but I guess it is also ok to keep them as general context when nothing matches.
Yeah, normally one provides a Link tag after e.g. Suggested-by or Reported-by, but the Link tag is more general, i.e. it is meant to provide context in general.
What I suggest is using a reference like [1] from somewhere in the text to the link, so that it is clear what is the context being added for:
But sometimes that doesn't make too much sense, and so it is fine to have the Link: tag on its own too.
By the way, the commit message also has a "code span" in a new line -- I would suggest indenting it and removing the backticks:
Alignment::new::<8>()
Cheers,
Miguel
Gary Guo
reviewerRe: [PATCH v8 03/12] rust: num: add cv! macro to create values from constant expressions
In reply to Alexandre CourbotQuoted 207 lines · Alexandre Courbot
Quoted 119 lines · Eliot Courtney
Quoted 107 lines · Alice Ryhl
Quoted 96 lines · Gary Guo
Quoted 82 lines · Alexandre Courbot
Quoted 68 lines · Eliot Courtney
Quoted 60 lines · Alexandre Courbot
Quoted 33 lines · Alexandre Courbot
Quoted 20 lines · Alice Ryhl
Quoted 10 lines · Eliot Courtney
Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro
cv!(for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait functionFromConst::from_const. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax. For example,const { NonZero::new(1).unwrap() }can be written ascv!(1).Quoted 2 lines
Suggested-by Gary Guo <[email protected]>Signed-off-by Eliot Courtney <[email protected]>This doesn't work in const context, so I don't think this is a great strategy.
I would want to use it for cases like this:
drivers/android/binder/netlink.rsQuoted 11 lines
const BINDER_CMD_REPORT: u8 = kernel::uapi::BINDER_CMD_REPORT as u8; const BINDER_A_REPORT_ERROR: c_int = kernel::uapi::BINDER_A_REPORT_ERROR as c_int; const BINDER_A_REPORT_CONTEXT: c_int = kernel::uapi::BINDER_A_REPORT_CONTEXT as c_int; const BINDER_A_REPORT_FROM_PID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_PID as c_int; const BINDER_A_REPORT_FROM_TID: c_int = kernel::uapi::BINDER_A_REPORT_FROM_TID as c_int; const BINDER_A_REPORT_TO_PID: c_int = kernel::uapi::BINDER_A_REPORT_TO_PID as c_int; const BINDER_A_REPORT_TO_TID: c_int = kernel::uapi::BINDER_A_REPORT_TO_TID as c_int; const BINDER_A_REPORT_IS_REPLY: c_int = kernel::uapi::BINDER_A_REPORT_IS_REPLY as c_int; const BINDER_A_REPORT_FLAGS: c_int = kernel::uapi::BINDER_A_REPORT_FLAGS as c_int; const BINDER_A_REPORT_CODE: c_int = kernel::uapi::BINDER_A_REPORT_CODE as c_int; const BINDER_A_REPORT_DATA_SIZE: c_int = kernel::uapi::BINDER_A_REPORT_DATA_SIZE as c_int;Quoted 4 lines
const_as![1] should do the trick for this, provided you don't need to create a constNonZero.... but I agree it would be nice to be able to use this in const context. And there is an overlap with
const_as!that becomes more obvious the more I look at it.In for a penny, in for a pound of macro code as they say. Since we agreed on using macros, how about unifying both under the same
cv!macro, with as many branches as we have types we want to initialize from a constant value? For instance:// Does what `const_as!` currently does under the hood. const BINDER_CMD_REPORT: u8 = cv!(u8::from(kernel::uapi::BINDER_CMD_REPORT)); // Calls `NonZero::new().unwrap()` under the hood. const SOME_NONZERO: NonZero<u8> = cv!(NonZero::new(kernel::uapi::NONZERO_VALUE)); // Calls `Bounded::new::<{ ...}>()` under the hood. const SOME_BOUNDED: Bounded<u32, 2> = cv!(Bounded::new(kernel::uapi::SMALL_VALUE));I.e. we would have one extra matching arm in
cv!per type it handles instead of implementing a trait. The syntax of the macro would look more natural (bye byeconst_as's awkward=>), albeit it would have the limitations of such a semantic dispatch.Quoted 6 lines
Even the name
const_as!wasn't really accurate to begin with: what it really emulates is a consttry_from, and we even discussed implementing it in these terms in the future.I'm sure the idea needs more polishing but I think there's something to explore here.
Quoted 7 lines
Yeah I agree that
const_as! is similar and if we had const traits we could fully merge them and have it always work in a const context for both duties (which are really a const tryfrom as you said).I am not sure about the suggested syntax (e.g. cv!(Bounded::new(kernel::uapi::SMALL_VALUE))), since it seems very verbose.
A bit, but what I like is that it looks very close to what you would naturally write if you had const traits (minus the unwraps), so you don't have to learn a new syntax. As long as it's not *more* verbose than natural Rust, I think it's fine.
Quoted 4 lines
It also has the benefit of relying less on type inference, i.e.
cv!(5)requires the caller to specify the type even with aletstatement, whereas you could dolet v = cv!(NonZero::new(5));and it would work as expected.Even with const
try_fromwe'd still wantcv!()to avoid having to writeconst { Type::try_from(...).unwrap() }I think having
=>syntax is great because it is a good place to *optionally* require type annotation.Quoted 6 lines
For enum repr for example, I think it'd be great that
const BINDER_CMD_REPORT: u8 = cv!(kernel::uapi::BINDER_CMD_REPORT);would work directly. It might need some tricks, which I have hard time coming up as I'm not feeling very well today, but I'll give it a shot over the weekend...
One could potentially define a trait with a MIN and MAX value constant, and then implement cv! like this:
Quoted 7 lines
1. Verify that the value lies between MIN and MAX.
2. Cast the value to uNN of the same size as the target type.
3. Transmute the uNN to the target type.Since the trait has no methods, this works in const eval.
Alice
Using an associated const by itself appears to work - I tried this which is very similar to Alice's suggested approach above:
Quoted 6 lines
```
macro_rules! const_assert { ($condition:expr $(,$arg:literal)?) => { const { ::core::assert!($condition $(,$arg)?) }; }; }Any reason this cannot use the
const_assertalready in the kernel crate?Quoted 16 lines
trait FromConst<const V: i128>: Sized { const VALUE: Self; }macro_rules! cv { (@widen $v:expr) => {{ #[allow(unused_comparisons, unused_assignments)] { let v = $v; let r = v as i128; let mut back = v; back = r as _; ::core::assert!( back == v && (v < 0) == (r < 0),Quoted 8 lines
"value cannot be losslessly widened to `i128`" ); r } }}; ($v:expr => $t:ty) => { <$t as FromConst<{ cv!(@widen $v) }>>::VALUEnit for the actual posting: make sure to fully qualify
cvwhen calling it recursively (and make sure all symbols are fully qualified).Quoted 16 lines
}; ($v:expr) => { <_ as FromConst<{ cv!(@widen $v) }>>::VALUE }; }macro_rules! impl_from_const_int { ($($t:ty)*) => {$( impl<const V: i128> FromConst<V> for $t { const VALUE: Self = { const_assert!( V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128, "Constant cannot be represented by the target type." ); V as $t };Quoted 8 lines
} impl<const V: i128> FromConst<V> for NonZero<$t> { const VALUE: Self = { const_assert!( V >= <$t>::MIN as i128 && V <= <$t>::MAX as i128, "Constant cannot be represented by the underlying type." );Let's also have a
const_assert!(V != 0, ...)to provide a better error message than "unwrap on None" if users call this with 0.Quoted 15 lines
NonZero::new(V as $t).unwrap() }; } )*}; }impl_from_const_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
impl<const V: i128> FromConst<V> for Alignment { const VALUE: Self = { const_assert!(V > 0 && V <= usize::MAX as i128); // The unwrap fails the build if `V` is not a power of two. Alignment::new_checked(V as usize).unwrap() }; }Quoted 5 lines
const A: u8 = cv!(200u32); const B: NonZero<u8> = cv!(5); const C: Alignment = cv!(4096); const D: u8 = cv!(200u32 => u8); ```
Quoted 4 lines
That looks like it could work! IIUC it even supports something like
cv!(x => NonZero<u8>). The only limitation is see is that this cannot take expressions using generic parameters, but we can probably work around that.
I posted a version [1] that works with const generic parameters. It is made of dark magic, but I think it's as close to actual const trait impl that we can actually get without actually having it. I used some extra trick to make error message very good, but the code could be simplified to not rely on method resolution order if we are okay with a less perfect error message.
What I like is that the trick is pretty generalizable to anything that need const trait impl, as it does not have limitation of generic const expr or const ADT (i.e. anything that is const-evalutable can work, not just integers that does not involve generic params), as long as concrete types are present and not just T: ConstTrait (which would actually need proper const trait impl).
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Best,
Gary
Quoted 11 lines
I guess you'll want to split this out into its own series so it doesn't remain hidden within the ranges/bitmap work. Basically as a replacement for the
const_asI was driving [1]. I'll recycle theconst_asseries to just switch to the kernel converters, and will follow-up with usingcv!once it lands.Since this is going to be a multi-cycle effort we should probably keep the legacy
*_into_*functions around for now and remove them in another patch once all users are converted.
Re: [PATCH v8 11/12] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
In reply to Eliot CourtneyQuoted 9 lines · Eliot Courtney
Current code in
IdPool::with_capacityrounds the capacity up toBitmapVec::MAX_INLINE_LEN, butBitmapVec::newworks fine with values smaller than this and still uses an inline representation. Remove this behaviour.This allows specifying a real capacity of 0, which was not previously possible. This breaks
grow_requestin this case, so change it to grow to at leastBitmapVec::MAX_INLINE_LEN, mirroring the capacity floor inshrink_request.
It wasn't possible previously for a reason: allocating 0-bit bitmap is something questionable.
Quoted 48 lines
Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-)rust/kernel/id_pool.rs +11
-5@@ -112,13 +112,8 @@ pub fn new() -> Self { }/// Constructs a new [`IdPool`] with space for a specific number of bits. -/// -/// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`]. -/// -/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN #[inline] pub fn with_capacity (num_ids:usize , flags:Flags ) ->Result <Self ,AllocError > { -let num_ids = usize::max (num_ids,BitmapVec ::MAX_INLINE_LEN );let map =BitmapVec ::new (num_ids, flags)?;Ok (Self { map }) }@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {/// let resizer = alloc_request.realloc(GFP_KERNEL)?; /// pool.shrink(resizer); /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN); +/// +/// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further. +/// assert!(pool.shrink_request().is_none()); +/// +/// // Neither can a pool with a capacity below `MAX_INLINE_LEN`. +/// let small = IdPool::with_capacity(8, GFP_KERNEL)?; +/// assert!(small.shrink_request().is_none()); /// # Ok::<(), AllocError>(()) /// ``` #[inline] @@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {/// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible. /// +/// Grows to at least [`MAX_INLINE_LEN`]. /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`]. /// +/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN /// [`MAX_LEN`]: BitmapVec::MAX_LEN +/// +/// # Examples
rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 219
Quoted 10 lines
rust/kernel/id_pool.rs +10
-0+/// +/// ``` +/// use kernel::{ +/// alloc::AllocError, +/// bitmap::BitmapVec, +/// id_pool::IdPool, // +/// }; +/// +/// // Grow goes to at least BitmapVec::MAX_INLINE_LEN. +/// let mut pool = IdPool::with_capacity(0, GFP_KERNEL)?;
Please don't add explicit examples for creating ID pools with 0 capacity. It's a factual error, and should not be explicitly expressed in documentation.
Also, it looks like your 0-bit bitmamp would trigger bitmap assertion:
IdPool::find_unused_id(0)
-> Bitmap::next_zero_bit()
-> assert!(start < self.len())
-> assert!(0 < 0)
-> panic if CONFIG_RUST_BITMAP_HARDENED=yI like your version because it allows to create an arbitrary capacity for ID pool, i.e. 4 bits. Right now one can explicitly create ID pool for 4 IDs, and allocate up to MAX_INLINE_LEN from it.
But 0-bit ID pools must be prohibited.
Quoted 20 lines
rust/kernel/id_pool.rs +11
-1+/// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN); +/// +/// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN. +/// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN); +/// # Ok::<(), AllocError>(()) +/// ``` #[inline] pub fn grow_request (&self) ->Option <ReallocRequest > { -let num_ids = self.capacity () *2 ; +let num_ids = usize::max (BitmapVec ::MAX_INLINE_LEN , self.capacity () *2 );if num_ids >BitmapVec ::MAX_LEN {return None ; }Signature · 2 lines
-- 2.55.0
Alexandre Courbot
maintainerRe: [PATCH v8 11/12] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
Quoted 6 lines · Yury Norov
Quoted 5 lines · Eliot Courtney
Current code in
IdPool::with_capacityrounds the capacity up toBitmapVec::MAX_INLINE_LEN, butBitmapVec::newworks fine with values smaller than this and still uses an inline representation. Remove this behaviour.
Quoted 7 lines
Quoted 4 lines
This allows specifying a real capacity of 0, which was not previously possible. This breaks
grow_requestin this case, so change it to grow to at leastBitmapVec::MAX_INLINE_LEN, mirroring the capacity floor inshrink_request.It wasn't possible previously for a reason: allocating 0-bit bitmap is something questionable.
We had this discussion on the previous revision [1] [2] and the conclusion was that it should be supported. Let me elaborate a bit on why.
We tend to use NonZero, Bounded and other limiting types in order to guarantee that invalid values that would otherwise require runtime error checking cannot be expressed. The main benefit being that it removes error paths and simplifies the code by removing footguns.
Here disallowing 0-bit bitmaps doesn't give us that benefit, it just adds some burden on the user in that they need to build a NonZero. But a 0-bit bitmap is not intrinsically invalid - it's actually a reasonable starting point for a user that eventually wants to grow it dynamically now that grow_request can support it.
That being said, you are correct when you say below that CONFIG_RUST_BITMAP_HARDENED will make any query panic, but the problem is that the documentation of the panicking methods does not mention that behavior (although [3] addresses that). It is also not specific to a length of 0: if the bitmap had a length of, say, 4 and the user called bitmap.next_zero_bit(4), then it will panic just the same. There is nothing special about a size of 0 in that regard.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
Quoted 55 lines
Quoted 55 lines
Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-)rust/kernel/id_pool.rs +17
-5@@ -112,13 +112,8 @@ pub fn new() -> Self { }/// Constructs a new [`IdPool`] with space for a specific number of bits. -/// -/// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`]. -/// -/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN #[inline] pub fn with_capacity (num_ids:usize , flags:Flags ) ->Result <Self ,AllocError > { -let num_ids = usize::max (num_ids,BitmapVec ::MAX_INLINE_LEN );let map =BitmapVec ::new (num_ids, flags)?;Ok (Self { map }) }@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {/// let resizer = alloc_request.realloc(GFP_KERNEL)?; /// pool.shrink(resizer); /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN); +/// +/// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further. +/// assert!(pool.shrink_request().is_none()); +/// +/// // Neither can a pool with a capacity below `MAX_INLINE_LEN`. +/// let small = IdPool::with_capacity(8, GFP_KERNEL)?; +/// assert!(small.shrink_request().is_none()); /// # Ok::<(), AllocError>(()) /// ``` #[inline] @@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {/// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible. /// +/// Grows to at least [`MAX_INLINE_LEN`]. /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`]. /// +/// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN /// [`MAX_LEN`]: BitmapVec::MAX_LEN +/// +/// # Examples +/// +/// ``` +/// use kernel::{ +/// alloc::AllocError, +/// bitmap::BitmapVec, +/// id_pool::IdPool, //
Quoted 8 lines
rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 219
Quoted 4 lines
rust/kernel/id_pool.rs +4
-0+/// }; +/// +/// // Grow goes to at least BitmapVec::MAX_INLINE_LEN. +/// let mut pool = IdPool::with_capacity(0, GFP_KERNEL)?; Please don't add explicit examples for creating ID pools with 0 capacity. It's a factual error, and should not be explicitly expressed in documentation.
I tend to agree that starting with a small capacity > 0 is probably a better illustration of how to use the API.
Quoted 9 lines
Also, it looks like your 0-bit bitmamp would trigger bitmap assertion:
IdPool::find_unused_id(0)
->Bitmap::next_zero_bit()-> assert!(start < self.len()) -> assert!(0 < 0) -> panic if CONFIG_RUST_BITMAP_HARDENED=y
Quoted 5 lines
I like your version because it allows to create an arbitrary capacity for ID pool, i.e. 4 bits. Right now one can explicitly create ID pool for 4 IDs, and allocate up to
MAX_INLINE_LENfrom it.But 0-bit ID pools must be prohibited.
I really think [4] we should consider removing CONFIG_RUST_BITMAP_HARDENED, make the conditions for panicking clear in the methods documentation (set/clear bit do panic, other methods don't), and add checked variants to allow users to write more idiomatic code. Bitmaps are really just arrays of bits, we should make them work as close as possible to regular Rust arrays.
[4] https://lore.kernel.org/rust-for-linux/[email protected]/