rust: Add support for reserving of ranges of IDs
Subsystems (6)
v5 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 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 (5):
rust: bitmap: use function-level cfg on kunit test
rust: bitmap: restrict bitmap length to at most i32::MAX
rust: bitmap: add contiguous area operations
rust: id_pool: add contiguous area allocation
gpu: nova-core: add ChannelIdPool
drivers/gpu/nova-core/gpu.rs | 2 + drivers/gpu/nova-core/gpu/channel.rs | 180 +++++++++++++++++++ rust/kernel/bitmap.rs | 329 +++++++++++++++++++++++++++++++---- rust/kernel/id_pool.rs | 69 ++++++++ 4 files changed, 545 insertions(+), 35 deletions(-)
---
base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
change-id: 20260608-chid-18fa943c6d6c
Best regards,
Signature · 1 line
Eliot Courtney <[email protected]>
PATCH v5 1/5 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
Re: [PATCH v5 1/5] rust: bitmap: use function-level cfg on kunit test
Quoted 5 lines · Eliot Courtney
Since commit
c652dc44192d("rust: kunit: allowcfgontests"), we no longer need this workaround.Reviewed-by Alice Ryhl <[email protected]>Signed-off-by Eliot Courtney <[email protected]>
Quoted 47 lines
--- 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 · 2 lines
-- 2.55.0
PATCH v5 2/5 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.
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 | 68 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 21 deletions(-)
rust/kernel/bitmap.rs +47 -21
@@ -17,24 +17,57 @@/// # Invariants /// /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. +/// Must not be longer than `i32::MAX` bits. #[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 +84,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 +141,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 +440,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
Re: [PATCH v5 2/5] rust: bitmap: restrict bitmap length to at most i32::MAX
Quoted 9 lines · Eliot Courtney
It is currently possible to construct a non-
BitmapVecbackedBitmapusingBitmap::from_rawthat is larger thani32::MAX, and it is not part of the unsafe requirements. Restricting all bitmaps (even non-BitmapVecbacked ones) to a maximum size ofi32::MAXsimplifies a few things and matchesBitmapVec::MAX_LEN.Add that requirement to the unsafe requirements on
Bitmap::from_rawandBitmap::from_raw_mut, and to the invariants onBitmap.
Quoted 6 lines
This also fixes u32 casts truncating in
copy_and_extend, which could otherwise lead to OOB writes.Fixes 11eca92a2cae ("rust: add bitmap API.")Signed-off-by Eliot Courtney <[email protected]>
Quoted 134 lines
--- rust/kernel/bitmap.rs | 68 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 21 deletions(-)rust/kernel/bitmap.rs +47
-21@@ -17,24 +17,57 @@/// # Invariants /// /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. +/// Must not be longer than `i32::MAX` bits. #[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 +84,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 +141,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 +440,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 · 2 lines
-- 2.55.0
PATCH v5 3/5 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 | 236 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+)
rust/kernel/bitmap.rs +236 -0
@@ -10,6 +10,7 @@use crate ::bindings;#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] use crate ::pr_err; +use crate ::ptr::Alignment ;use core::ptr::NonNull ;/// Represents a C bitmap. Wraps underlying C bitmap API.
@@ -523,6 +524,139 @@ 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: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).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)?; + +// 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}; +/// use kernel::bitmap::BitmapVec; +/// use kernel::ptr::Alignment; +/// +/// let mut b = BitmapVec::new(64, GFP_KERNEL)?; +/// let unaligned = Alignment::new::<1>(); +/// +/// assert_eq!(Some(0), b.next_zero_area(0, 8, unaligned)); +/// b.set(0, 5); +/// assert_eq!(Some(5), b.next_zero_area(0, 8, unaligned)); +/// assert_eq!(Some(8), b.next_zero_area(0, 8, Alignment::new::<8>())); +/// assert_eq!(None, b.next_zero_area(0, 65, unaligned)); +/// # Ok::<(), AllocError>(()) +/// ``` +#[inline] +pub fn next_zero_area (&self, start:usize , nbits: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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits), + 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 , nbitsas 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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits), + 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 , nbitsas i32 ) }; + } }#[cfg( CONFIG_RUST_BITMAP_KUNIT_TEST )]
@@ -640,4 +774,106 @@ 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 )?; +let unaligned =Alignment ::new ::<1 >(); + +assert_eq! (Some (0 ), b.next_zero_area (0 ,5 , unaligned)); + b.set (0 ,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 ,5 , unaligned)); +assert_eq! (Some (8 ), b.next_zero_area (0 ,5 ,Alignment ::new ::<8 >())); + + b.set (8 ,8 );// Now contains {[0, 5), [8, 16)}. +assert_eq! (Some (16 ), b.next_zero_area (0 ,4 ,Alignment ::new ::<16 >())); +assert_eq! (Some (16 ), b.next_zero_area (0 ,4 , unaligned)); + + b.clear (0 ,5 );// Now contains {[8, 16)}. +assert_eq! (Some (0 ), b.next_zero_area (0 ,5 , unaligned)); +assert_eq! (Some (8 ), b.next_bit (0 )); +assert_eq! (Some (15 ), b.last_bit ()); + + b.clear (16 ,0 );// Zero-length in-bounds clears are no-ops. +assert_eq! (Some (8 ), b.next_bit (0 )); +assert_eq! (Some (15 ), b.last_bit ()); + +// A zero-length request returns the first aligned position at or +// after the next zero bit, even if that position's own bit is set. +assert_eq! (Some (1 ), b.next_zero_area (1 ,0 , unaligned)); +assert_eq! (Some (8 ), b.next_zero_area (1 ,0 ,Alignment ::new ::<8 >())); + + b.set (60 ,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 ,40 , unaligned)); +assert_eq! (Some (70 ), b.next_zero_area (0 ,45 , unaligned)); + + b.clear (62 ,6 );// Now contains {[8, 16), [60, 62), [68, 70)}. +assert_eq! (Some (62 ), b.next_zero_area (60 ,6 , unaligned)); +assert_eq! (Some (61 ), b.next_bit (61 )); +assert_eq! (Some (69 ), b.last_bit ()); + + b.set (64 ,0 );// Zero-length in-bounds sets are no-ops. +assert_eq! (Some (62 ), b.next_zero_bit (62 )); +Ok (()) + } + +#[test] +fn bitmap_area_exhaustion () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (64 ,GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); + +assert_eq! (None , b.next_zero_area (0 ,65 , unaligned)); +assert_eq! (None , b.next_zero_area (0 ,usize ::MAX , unaligned)); +assert_eq! (None , b.next_zero_area (1 ,usize ::MAX , unaligned)); + + b.set_bit (0 );// Now contains {[0, 1)}. +assert_eq! (None , b.next_zero_area (0 ,usize ::MAX , unaligned)); + + b.set (0 ,61 );// Now contains {[0, 61)}. +assert_eq! (None , b.next_zero_area (0 ,4 , unaligned)); +assert_eq! (Some (61 ), b.next_zero_area (0 ,3 , unaligned)); +assert_eq! (None , b.next_zero_area (0 ,1 ,Alignment ::new ::<64 >())); +Ok (()) + } + +#[test] +fn bitmap_area_off () ->Result <(),AllocError > { +let mut b =BitmapVec ::new (64 ,GFP_KERNEL )?; +let align8 =Alignment ::new ::<8 >(); + + b.set (0 ,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 ,8 , align8,1 )); +assert_eq! (Some (5 ), b.next_zero_area_off (0 ,8 , align8,3 )); + +// A zero offset behaves like next_zero_area(). +assert_eq! ( + b.next_zero_area (0 ,8 , align8), + b.next_zero_area_off (0 ,8 , align8,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 ,4 ); + b.set (62 ,8 ); + b.set (usize::MAX ,0 ); + b.clear (usize::MAX ,0 ); + b.clear (2048 ,8 ); +assert_eq! (None , b.next_bit (0 )); +assert_eq! (None , b.next_zero_area (64 ,1 ,Alignment ::new ::<1 >())); +Ok (()) + } }
Signature · 1 line
2.55.0
Re: [PATCH v5 3/5] rust: bitmap: add contiguous area operations
Quoted 46 lines · Eliot Courtney
Add 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_HARDENEDis on.Add tests demonstrating the edge cases.
Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/bitmap.rs | 236 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+)rust/kernel/bitmap.rs +19
-0@@ -10,6 +10,7 @@use crate ::bindings;#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] use crate ::pr_err; +use crate ::ptr::Alignment ;use core::ptr::NonNull ;/// Represents a C bitmap. Wraps underlying C bitmap API. @@ -523,6 +524,139 @@ 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:usize , + align: Alignment,
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 554
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ align_offset: usize, + ) -> Option<usize> { +bitmap_assert! ( + start < self.len (), +"`start` must be < {}, was {}" , + self.len (), + start + ); + +let nr = u32::try_from (nbits).ok ()?;
What about nbits == 0? In C, this is a undef, and thus in the current rust implementation. Maybe make it NonZero?
The same question about align and align_offset.
Quoted 70 lines
rust/kernel/bitmap.rs +70
-0+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)?; + +// 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}; +/// use kernel::bitmap::BitmapVec; +/// use kernel::ptr::Alignment; +/// +/// let mut b = BitmapVec::new(64, GFP_KERNEL)?; +/// let unaligned = Alignment::new::<1>(); +/// +/// assert_eq!(Some(0), b.next_zero_area(0, 8, unaligned)); +/// b.set(0, 5); +/// assert_eq!(Some(5), b.next_zero_area(0, 8, unaligned)); +/// assert_eq!(Some(8), b.next_zero_area(0, 8, Alignment::new::<8>())); +/// assert_eq!(None, b.next_zero_area(0, 65, unaligned)); +/// # Ok::<(), AllocError>(()) +/// ``` +#[inline] +pub fn next_zero_area (&self, start:usize , nbits: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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits)
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 634
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ .is_some_and(|end| end <= self.len()), + "Area `start..start + nbits` ({}..{}) must be within bounds {}", + start, + start.saturating_add(nbits), + 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 , nbitsas i32 ) }; + }
In the case of bitmap_set/clear(), nbits == 0 makes it a no-op, and guarantees that the pointer is not dereferenced. So, no undefined behavior. But in rust case, I believe, it should be a stronger policy.
I'd add an assertion, at least, or better make it NonZero.
Thanks,
Yury
Quoted 26 lines
rust/kernel/bitmap.rs +25
-0+ +/// 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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits), + 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 , nbitsas i32 ) }; + } }
Re: [PATCH v5 3/5] rust: bitmap: add contiguous area operations
Quoted 61 lines · Yury Norov
Quoted 46 lines · Eliot Courtney
Add 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_HARDENEDis on.Add tests demonstrating the edge cases.
Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/bitmap.rs | 236 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+)rust/kernel/bitmap.rs +19
-0@@ -10,6 +10,7 @@use crate ::bindings;#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] use crate ::pr_err; +use crate ::ptr::Alignment ;use core::ptr::NonNull ;/// Represents a C bitmap. Wraps underlying C bitmap API. @@ -523,6 +524,139 @@ 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:usize , + align: Alignment,rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 554
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ align_offset: usize, + ) -> Option<usize> { +bitmap_assert! ( + start < self.len (), +"`start` must be < {}, was {}" , + self.len (), + start + ); + +let nr = u32::try_from (nbits).ok ()?;What about nbits == 0? In C, this is a undef, and thus in the current rust implementation. Maybe make it NonZero?
Quoted 1 line
The same question about align and
align_offset.
NonZero sounds good to me for nbits. For align, it's already guaranteed to be at least 1. For align_offset, passing 0 is normal and valid (and we need to for implementing next_zero_area just below)
Quoted 86 lines
Quoted 71 lines
rust/kernel/bitmap.rs +70
-0+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)?; + +// 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}; +/// use kernel::bitmap::BitmapVec; +/// use kernel::ptr::Alignment; +/// +/// let mut b = BitmapVec::new(64, GFP_KERNEL)?; +/// let unaligned = Alignment::new::<1>(); +/// +/// assert_eq!(Some(0), b.next_zero_area(0, 8, unaligned)); +/// b.set(0, 5); +/// assert_eq!(Some(5), b.next_zero_area(0, 8, unaligned)); +/// assert_eq!(Some(8), b.next_zero_area(0, 8, Alignment::new::<8>())); +/// assert_eq!(None, b.next_zero_area(0, 65, unaligned)); +/// # Ok::<(), AllocError>(()) +/// ``` +#[inline] +pub fn next_zero_area (&self, start:usize , nbits: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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits)rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 634
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ .is_some_and(|end| end <= self.len()), + "Area `start..start + nbits` ({}..{}) must be within bounds {}", + start, + start.saturating_add(nbits), + 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 , nbitsas i32 ) }; + }In the case of bitmap_set/clear(), nbits == 0 makes it a no-op, and guarantees that the pointer is not dereferenced. So, no undefined behavior. But in rust case, I believe, it should be a stronger policy.
Quoted 4 lines
I'd add an assertion, at least, or better make it NonZero.
Thanks,
Yury
Yeah, NonZero sounds good to me here too. Thanks!
Quoted 27 lines
Quoted 27 lines
rust/kernel/bitmap.rs +25
-0+ +/// 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:usize ) { +bitmap_assert_return! ( + start + .checked_add (nbits) + .is_some_and (|end| end <= self.len ()), +"Area `start..start + nbits` ({}..{}) must be within bounds {}" , + start, + start.saturating_add (nbits), + 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 , nbitsas i32 ) }; + } }
PATCH v5 4/5 rust: id_pool: add contiguous area allocation
In reply to Eliot CourtneyAdd support for contiguous area allocation. Add a new type, UnusedArea, following the same pattern as UnusedId.
--- rust/kernel/id_pool.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)
rust/kernel/id_pool.rs +69 -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,33 @@ pub fn find_unused_id(&mut self, offset: usize) -> Option<UnusedId<'_>> {pub fn release_id (&mut self, id:usize ) { self.map.clear_bit (id); } + +/// Finds a contiguous area of `count` unused IDs at or after `offset`. +/// +/// The start of the returned area is a multiple of `align`. +/// +/// Returns an [`UnusedArea`] upon success, or [`None`] if no such area could be found. +#[inline] +#[must_use] +pub fn find_unused_area ( + &mut self, + offset:usize , + count:NonZero <usize >, + align:Alignment , + ) ->Option <UnusedArea <'_>> { +let start = self.map.next_zero_area (offset, count.get (), align)?; +// INVARIANT: `next_zero_area()` returns None or a start with `start + count <= map.len()`. +Some (UnusedArea { + range: start..start + count.get (), + pool: self, + }) + } + +/// Releases a contiguous area of IDs. +#[inline] +pub fn release_area (&mut self, range: &Range <usize >) { + self.map.clear (range.start, range.len ()); + } }/// Represents an unused id in an [`IdPool`].
@@ -287,6 +320,42 @@ pub fn acquire(self) -> usize { } } +/// Represents an unused, contiguous area of IDs in an [`IdPool`]. +/// +/// # Invariants +/// +/// `range.start <= range.end <= pool.map.len()`. +#[must_use = "the ID range is not reserved unless acquired" ] +pub struct UnusedArea <'pool> { + range:Range <usize >, + pool: &'poolmut IdPool , +} + +impl <'pool>UnusedArea <'pool> { +/// Returns the unused ID range. +/// +/// Be aware that the area has not yet been acquired in the pool. The +/// [`acquire`] method must be called to prevent others from taking it. +/// +/// [`acquire`]: UnusedArea::acquire() +#[inline] +#[must_use] +pub fn range (&self) ->Range <usize > { + self.range.clone () + } + +/// Acquires the area. +/// +/// Returns the now-reserved ID range. +#[inline] +pub fn acquire (self) ->Range <usize > { +let Self { range, pool } = self; +// By the type invariants, the range is within bounds. + pool.map.set (range.start, range.end - range.start); + range + } +} +impl Default for IdPool {#[inline] fn default () ->Self {
Signature · 1 line
2.55.0
Re: [PATCH v5 4/5] rust: id_pool: add contiguous area allocation
Quoted 65 lines · Eliot Courtney
Add support for contiguous area allocation. Add a new type,
UnusedArea, following the same pattern asUnusedId.Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/id_pool.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)rust/kernel/id_pool.rs +33
-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,33 @@ pub fn find_unused_id(&mut self, offset: usize) -> Option<UnusedId<'_>> {pub fn release_id (&mut self, id:usize ) { self.map.clear_bit (id); } + +/// Finds a contiguous area of `count` unused IDs at or after `offset`. +/// +/// The start of the returned area is a multiple of `align`. +/// +/// Returns an [`UnusedArea`] upon success, or [`None`] if no such area could be found. +#[inline] +#[must_use] +pub fn find_unused_area ( + &mut self, + offset:usize , + count:NonZero <usize >, + align:Alignment , + ) ->Option <UnusedArea <'_>> { +let start = self.map.next_zero_area (offset, count.get (), align)?; +// INVARIANT: `next_zero_area()` returns None or a start with `start + count <= map.len()`. +Some (UnusedArea { + range: start..start + count.get (), + pool: self, + }) + } + +/// Releases a contiguous area of IDs. +#[inline] +pub fn release_area (&mut self, range: &Range <usize >) { + self.map.clear (range.start, range.len ()); + } }/// Represents an unused id in an [`IdPool`]. @@ -287,6 +320,42 @@ pub fn acquire(self) -> usize { } }
rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 332
Quoted 10 lines
rust/kernel/id_pool.rs +10
-0+/// Represents an unused, contiguous area of IDs in an [`IdPool`]. +/// +/// # Invariants +/// +/// `range.start <= range.end <= pool.map.len()`. +#[must_use = "the ID range is not reserved unless acquired" ] +pub struct UnusedArea <'pool> { + range:Range <usize >, + pool: &'poolmut IdPool , +}
So, the compilation message refers the "ID range", not the UnusedArea. To me, this 'unused' language is confusing. What should I do with the area that I just allocated? Drop the 'unused' one and create the 'used'?
Can you rename it to id_range please? Then the API would look more consistent, at least to me.
rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 340
Quoted 8 lines
rust/kernel/id_pool.rs +8
-0+ +impl <'pool>UnusedArea <'pool> { +/// Returns the unused ID range. +/// +/// Be aware that the area has not yet been acquired in the pool. The +/// [`acquire`] method must be called to prevent others from taking it. +/// +/// [`acquire`]: UnusedArea::acquire()
So maybe implement the find_acquire() method? In the caller you serialize it with:
let mut ids = self.inner.lock();
Is it possible to pass this down to the suggested find_acquire()? In my experience, having non-atomic sequence of find + acquire that requires the external locking is the recipe for troubles.
Quoted 5 lines
rust/kernel/id_pool.rs +5
-0+#[inline] +#[must_use] +pub fn range (&self) ->Range <usize > { + self.range.clone () + }
rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 355
Quoted 10 lines
rust/kernel/id_pool.rs +10
-0+ +/// Acquires the area. +/// +/// Returns the now-reserved ID range. +#[inline] +pub fn acquire (self) ->Range <usize > { +let Self { range, pool } = self; +// By the type invariants, the range is within bounds. + pool.map.set (range.start, range.end - range.start); + range
From hierarchy perspective, the UnusedArea wraps the Range, and passing the Range to the higher layer breaks the hierarchy. If you follow my suggestion, the hierarchy will be enforced stricter:
ChannelIdRange -> IdRange-> Range
instead of
ChannelIdArea -> UnusedArea-> Range
|
-> RangeOr I misunderstand the concept of the UnusedArea?
Quoted 9 lines
rust/kernel/id_pool.rs +3
-0+ } +} +impl Default for IdPool {#[inline] fn default () ->Self {Signature · 2 lines
-- 2.55.0
Re: [PATCH v5 4/5] rust: id_pool: add contiguous area allocation
Quoted 81 lines · Yury Norov
Quoted 65 lines · Eliot Courtney
Add support for contiguous area allocation. Add a new type,
UnusedArea, following the same pattern asUnusedId.Signed-off-by Eliot Courtney <[email protected]>--- rust/kernel/id_pool.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)rust/kernel/id_pool.rs +33
-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,33 @@ pub fn find_unused_id(&mut self, offset: usize) -> Option<UnusedId<'_>> {pub fn release_id (&mut self, id:usize ) { self.map.clear_bit (id); } + +/// Finds a contiguous area of `count` unused IDs at or after `offset`. +/// +/// The start of the returned area is a multiple of `align`. +/// +/// Returns an [`UnusedArea`] upon success, or [`None`] if no such area could be found. +#[inline] +#[must_use] +pub fn find_unused_area ( + &mut self, + offset:usize , + count:NonZero <usize >, + align:Alignment , + ) ->Option <UnusedArea <'_>> { +let start = self.map.next_zero_area (offset, count.get (), align)?; +// INVARIANT: `next_zero_area()` returns None or a start with `start + count <= map.len()`. +Some (UnusedArea { + range: start..start + count.get (), + pool: self, + }) + } + +/// Releases a contiguous area of IDs. +#[inline] +pub fn release_area (&mut self, range: &Range <usize >) { + self.map.clear (range.start, range.len ()); + } }/// Represents an unused id in an [`IdPool`]. @@ -287,6 +320,42 @@ pub fn acquire(self) -> usize { } }rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 332
Quoted 10 lines
rust/kernel/id_pool.rs +10
-0+/// Represents an unused, contiguous area of IDs in an [`IdPool`]. +/// +/// # Invariants +/// +/// `range.start <= range.end <= pool.map.len()`. +#[must_use = "the ID range is not reserved unless acquired" ] +pub struct UnusedArea <'pool> { + range:Range <usize >, + pool: &'poolmut IdPool , +}So, the compilation message refers the "ID range", not the UnusedArea. To me, this 'unused' language is confusing. What should I do with the area that I just allocated? Drop the 'unused' one and create the 'used'?
Quoted 2 lines
Can you rename it to
id_rangeplease? Then the API would look more consistent, at least to me.
tl;dr: I will remove UnusedArea according to your suggestion
UnusedArea here mirrors the design of UnusedId, which first finds the unused ID then lets you actually set it whenever you want (first introduced in f523d110a63b ("rust: id_pool: do not immediately acquire new ids")). According to f523d110a63b, the reason for this design is to allow some fallible operations once you know the ID you are getting before committing to actually allocating it. So UnusedArea just follows the existing design for this API. But, we don't need this intermediate fallible operation behaviour right now, so I think it's ok to get rid of it.
Quoted 13 lines
rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 340
Quoted 9 lines
rust/kernel/id_pool.rs +8
-0+ +impl <'pool>UnusedArea <'pool> { +/// Returns the unused ID range. +/// +/// Be aware that the area has not yet been acquired in the pool. The +/// [`acquire`] method must be called to prevent others from taking it. +/// +/// [`acquire`]: UnusedArea::acquire() So maybe implement the
find_acquire()method? In the caller you serialize it with:
Quoted 5 lines
let mut ids = self.inner.lock();Is it possible to pass this down to the suggested
find_acquire()? In my experience, having non-atomic sequence of find + acquire that requires the external locking is the recipe for troubles.
In this case, since we stash a mutable reference to IdPool in UnusedArea (just like UnusedId), it's not possible to hit any non-atomic find/acquire issues. The compiler will statically prevent you from being able to allocate anything else in the IdPool as long as the UnusedArea is alive. That is, it's always valid to acquire an UnusedArea (or UnusedId). In this case IMO it is more flexible to let the caller decide how it will do the locking (and that's the existing design for allocating single IDs here), since it can e.g. control the granularity. Or maybe it really exists in a single threaded context and doesn't need locking whatsoever (i.e. can get a mutable ref to IdPool without locking).
Quoted 40 lines
Quoted 6 lines
rust/kernel/id_pool.rs +5
-0+#[inline] +#[must_use] +pub fn range (&self) ->Range <usize > { + self.range.clone () + }rust/kernel/id_pool.rs pub fn acquire(self) -> usize { · line 355
Quoted 10 lines
rust/kernel/id_pool.rs +10
-0+ +/// Acquires the area. +/// +/// Returns the now-reserved ID range. +#[inline] +pub fn acquire (self) ->Range <usize > { +let Self { range, pool } = self; +// By the type invariants, the range is within bounds. + pool.map.set (range.start, range.end - range.start); + rangeFrom hierarchy perspective, the UnusedArea wraps the Range, and passing the Range to the higher layer breaks the hierarchy. If you follow my suggestion, the hierarchy will be enforced stricter:
ChannelIdRange -> IdRange-> Rangeinstead of
ChannelIdArea -> UnusedArea-> Range | -> RangeOr I misunderstand the concept of the UnusedArea?
Quoted 9 lines
rust/kernel/id_pool.rs +3
-0+ } +} +impl Default for IdPool {#[inline] fn default () ->Self {Signature · 2 lines
-- 2.55.0
PATCH v5 5/5 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 | 180 +++++++++++++++++++++++++++++++++++ 2 files changed, 182 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 +180 -0
180 lines not on this page · raw message
Signature · 1 line
2.55.0
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 76 lines · Eliot Courtney
Add
ChannelIdPoolwhich adds automatic tracking and releasing of channel IDs on top ofIdPool. 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
IdPoolis 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 reimplementsbitmap_find_next_zero_area()) [2]. It is also faster than maple tree [3].Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/gpu.rs | 2 + drivers/gpu/nova-core/gpu/channel.rs | 180 +++++++++++++++++++++++++++++++++++ 2 files changed, 182 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 +35
-0@@ -0,0 +1,180 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Channel ID allocation. + +use core::{ + num::NonZero , + ops::{ +Deref , +Range ,// + },// +}; + +use kernel::{ + id_pool::IdPool , + prelude::*, + ptr::Alignment , + sync::{ + new_mutex, +Mutex ,// + },// +}; + +/// Pool for tracking reservations of channel IDs. +#[pin_data] +pub (crate )struct ChannelIdPool { +#[pin] + inner:Mutex <IdPool >, + num_chids:usize , +} + +impl ChannelIdPool { +/// Creates a pool managing `num_chids` channel IDs. +pub (crate )fn new (num_chids:usize ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self {
drivers/gpu/nova-core/gpu/channel.rs line 45
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+ inner <- new_mutex!(IdPool::with_capacity(num_chids, GFP_KERNEL)?), + num_chids, + }) + } + +/// Reserves a contiguous area of `count` channel IDs starting at a multiple of `align`, +/// returning a guard that releases the area on drop. +pub (crate )fn alloc_area ( + &self, + count: NonZero<usize>,
OK, here you use NonZero. Please do that in the lowest layer.
drivers/gpu/nova-core/gpu/channel.rs line 51
Quoted 6 lines
drivers/gpu/nova-core/gpu/channel.rs new file +6
-0+ align: Alignment, + ) -> Result<ChannelIdArea<'_>> { +let mut ids = self.inner.lock (); +let area = ids.find_unused_area (0 , count, align).ok_or (ENOSPC )?; + +// If the pool is small, the backing bitmap may be rounded up to a larger size.
Not sure I understand this language. Your ID pool is a fixed-size. Or do you mean something else?
Quoted 47 lines
drivers/gpu/nova-core/gpu/channel.rs new file +47
-0+if area.range ().end > self.num_chids { +return Err (ENOSPC ); + } +Ok (ChannelIdArea { + pool: self, + range: area.acquire (), + }) + } +} + +/// A reserved contiguous area of channel IDs. +/// +/// Releases the whole area back to its [`ChannelIdPool`] when dropped. Releasing locks a +/// sleeping [`Mutex`], so the area must be dropped in a context that is allowed to sleep. +#[must_use = "the channel ID area is released immediately when unused" ] +pub (crate )struct ChannelIdArea <'a> { + pool: &'aChannelIdPool , + range:Range <usize >, +} + +impl Drop for ChannelIdArea <'_> { +fn drop (&mut self) { + self.pool.inner.lock ().release_area (&self.range); + } +} + +impl Deref for ChannelIdArea <'_> { +type Target =Range <usize >; + +fn deref (&self) -> &Self ::Target { + &self.range + } +} + +#[kunit_tests(nova_core_channel)] +mod tests { +use super ::*; + +const fn nz <const N :usize >() ->NonZero <usize > { +const {NonZero ::new (N ).unwrap () } + } + +#[test] +fn chid_area () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (2048 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); +
drivers/gpu/nova-core/gpu/channel.rs line 108
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+let first = pool.alloc_area (nz ::<48 >(), unaligned)?; +assert_eq! (0 , first.start); +assert_eq! (48 , first.len ()); +assert_eq! (48 , first.end); + +let second = pool.alloc_area (nz ::<48 >(), unaligned)?; +assert! (first.end <= second.start || second.end <= first.start); + +let first_start = first.start; +drop (first);
You test the drop() only once. Can you add more tests? At least, make sure that 2 allocs followed by 2 drops ends up with an empty pool.
Quoted 4 lines
drivers/gpu/nova-core/gpu/channel.rs new file +4
-0+assert_eq! (first_start, pool.alloc_area (nz ::<48 >(), unaligned)?.start); +Ok (()) + } +
drivers/gpu/nova-core/gpu/channel.rs line 122
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+#[test] +fn chid_bounded_by_num_chids () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (4 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); + + { +let a = pool.alloc_area (nz ::<1 >(), unaligned)?; +let b = pool.alloc_area (nz ::<1 >(), unaligned)?; +let c = pool.alloc_area (nz ::<1 >(), unaligned)?; +let d = pool.alloc_area (nz ::<1 >(), unaligned)?;
OK, here your alloc_area() means the find + alloc, and it returns a Range - not area.
To me it looks like the intermediate UnusedArea layer is excessive. If you just do find + alloc in this pool.alloc_area(), you seemingly don't need the UnusedArea.
Can you try without it, please?
Quoted 34 lines
drivers/gpu/nova-core/gpu/channel.rs new file +34
-0+assert_eq! (0 , a.start); +assert_eq! (1 , b.start); +assert_eq! (2 , c.start); +assert_eq! (3 , d.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<1 >(), unaligned).map (|_| ()) + ); + } + +assert_eq! (0 , pool.alloc_area (nz ::<4 >(), unaligned)?.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<5 >(), unaligned).map (|_| ()) + ); + +let head = pool.alloc_area (nz ::<3 >(), unaligned)?; +assert_eq! (0 , head.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<2 >(), unaligned).map (|_| ()) + ); +assert_eq! (3 , pool.alloc_area (nz ::<1 >(), unaligned)?.start); +Ok (()) + } + +#[test] +fn chid_area_aligned () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (16 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); +let align4 =Alignment ::new ::<4 >(); + +// Alloc 0 so the first fit for the next area is unaligned. +let pad = pool.alloc_area (nz ::<1 >(), unaligned)?;
drivers/gpu/nova-core/gpu/channel.rs line 166
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+assert_eq! (0 , pad.start); + +let a = pool.alloc_area (nz ::<4 >(), align4)?; +assert_eq! (4 , a.start); + +// The area skipped over by the aligned allocation should still be available. +let b = pool.alloc_area (nz ::<1 >(), unaligned)?; +assert_eq! (1 , b.start); + +let c = pool.alloc_area (nz ::<8 >(),Alignment ::new ::<8 >())?;
Is it possible to make it somehow simpler:
let c = pool.alloc_area(8, 8)?;
All the parameters checking must be a part of implementations, not the interface.
We had a very similar discussion in the bitfields implementation thread, and many people in CC list of this thread spent quite a long time to find a way from:
let color = Rgb::default()
.set_red(Bounded::<u16, _>::new::<0x10>())
.set_green(Bounded::<u16, _>::new::<0x1f>())
.set_blue(Bounded::<u16, _>::new::<0x18>());to:
let color = Rgb::default().
.set_red(0x10)
.set_green(0x1f)
.set_blue(0x18)Can you do the same here? Please refer:
Quoted 17 lines
drivers/gpu/nova-core/gpu/channel.rs new file +14
-0+assert_eq! (8 , c.start); + +// Only 2 IDs left. +assert_eq! (Err (ENOSPC ), pool.alloc_area (nz ::<4 >(), align4).map (|_| ())); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<1 >(),Alignment ::new ::<32 >()) + .map (|_| ()) + ); + +assert_eq! (2 , pool.alloc_area (nz ::<2 >(), unaligned)?.start); +Ok (()) + } +}Signature · 2 lines
-- 2.55.0
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 81 lines · Yury Norov
Quoted 80 lines · Eliot Courtney
Add
ChannelIdPoolwhich adds automatic tracking and releasing of channel IDs on top ofIdPool. 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
IdPoolis 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 reimplementsbitmap_find_next_zero_area()) [2]. It is also faster than maple tree [3].Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/gpu.rs | 2 + drivers/gpu/nova-core/gpu/channel.rs | 180 +++++++++++++++++++++++++++++++++++ 2 files changed, 182 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 +39
-0@@ -0,0 +1,180 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Channel ID allocation. + +use core::{ + num::NonZero , + ops::{ +Deref , +Range ,// + },// +}; + +use kernel::{ + id_pool::IdPool , + prelude::*, + ptr::Alignment , + sync::{ + new_mutex, +Mutex ,// + },// +}; + +/// Pool for tracking reservations of channel IDs. +#[pin_data] +pub (crate )struct ChannelIdPool { +#[pin] + inner:Mutex <IdPool >, + num_chids:usize , +} + +impl ChannelIdPool { +/// Creates a pool managing `num_chids` channel IDs. +pub (crate )fn new (num_chids:usize ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + inner <-new_mutex! (IdPool ::with_capacity (num_chids,GFP_KERNEL )?), + num_chids, + }) + }
Quoted 8 lines
drivers/gpu/nova-core/gpu/channel.rs line 45
Quoted 6 lines
drivers/gpu/nova-core/gpu/channel.rs new file +6
-0+ +/// Reserves a contiguous area of `count` channel IDs starting at a multiple of `align`, +/// returning a guard that releases the area on drop. +pub (crate )fn alloc_area ( + &self, + count: NonZero<usize>,OK, here you use NonZero. Please do that in the lowest layer.
Will do~
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs line 51
Quoted 7 lines
drivers/gpu/nova-core/gpu/channel.rs new file +6
-0+ align: Alignment, + ) -> Result<ChannelIdArea<'_>> { +let mut ids = self.inner.lock (); +let area = ids.find_unused_area (0 , count, align).ok_or (ENOSPC )?; + +// If the pool is small, the backing bitmap may be rounded up to a larger size. Not sure I understand this language. Your ID pool is a fixed-size. Or do you mean something else?
Yeah this is a little confusing. The reason this exists is because IdPool::with_capacity will round up the size to BitmapVec::MAX_INLINE_LEN. For binder, there isn't a natural limit to the ID space IIUC so it's not a problem there.
Anyway, in this case, IdPool can return an area that is outside of the original capacity you gave to IdPool::with_capacity, hence this check. But, I had a closer look at IdPool::with_capacity, and I can't see a good reason for why it's doing this adjusting to a min of BitmapVec::MAX_INLINE_LEN. So let me try to instead remove that behaviour.
Quoted 53 lines
Quoted 53 lines
drivers/gpu/nova-core/gpu/channel.rs new file +52
-0+if area.range ().end > self.num_chids { +return Err (ENOSPC ); + } +Ok (ChannelIdArea { + pool: self, + range: area.acquire (), + }) + } +} + +/// A reserved contiguous area of channel IDs. +/// +/// Releases the whole area back to its [`ChannelIdPool`] when dropped. Releasing locks a +/// sleeping [`Mutex`], so the area must be dropped in a context that is allowed to sleep. +#[must_use = "the channel ID area is released immediately when unused" ] +pub (crate )struct ChannelIdArea <'a> { + pool: &'aChannelIdPool , + range:Range <usize >, +} + +impl Drop for ChannelIdArea <'_> { +fn drop (&mut self) { + self.pool.inner.lock ().release_area (&self.range); + } +} + +impl Deref for ChannelIdArea <'_> { +type Target =Range <usize >; + +fn deref (&self) -> &Self ::Target { + &self.range + } +} + +#[kunit_tests(nova_core_channel)] +mod tests { +use super ::*; + +const fn nz <const N :usize >() ->NonZero <usize > { +const {NonZero ::new (N ).unwrap () } + } + +#[test] +fn chid_area () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (2048 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); + +let first = pool.alloc_area (nz ::<48 >(), unaligned)?; +assert_eq! (0 , first.start); +assert_eq! (48 , first.len ()); +assert_eq! (48 , first.end); +
Quoted 8 lines
drivers/gpu/nova-core/gpu/channel.rs line 108
Quoted 5 lines
drivers/gpu/nova-core/gpu/channel.rs new file +5
-0+let second = pool.alloc_area (nz ::<48 >(), unaligned)?; +assert! (first.end <= second.start || second.end <= first.start); + +let first_start = first.start; +drop (first);You test the
drop()only once. Can you add more tests? At least, make sure that 2 allocs followed by 2 drops ends up with an empty pool.
Yerp good idea. Thanks!
Quoted 19 lines
Quoted 5 lines
drivers/gpu/nova-core/gpu/channel.rs new file +4
-0+assert_eq! (first_start, pool.alloc_area (nz ::<48 >(), unaligned)?.start); +Ok (()) + } +drivers/gpu/nova-core/gpu/channel.rs line 122
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+#[test] +fn chid_bounded_by_num_chids () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (4 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); + + { +let a = pool.alloc_area (nz ::<1 >(), unaligned)?; +let b = pool.alloc_area (nz ::<1 >(), unaligned)?; +let c = pool.alloc_area (nz ::<1 >(), unaligned)?; +let d = pool.alloc_area (nz ::<1 >(), unaligned)?;OK, here your
alloc_area()means the find + alloc, and it returns a Range - not area.
Quoted 5 lines
To me it looks like the intermediate UnusedArea layer is excessive. If you just do find + alloc in this
pool.alloc_area(), you seemingly don't need the UnusedArea.Can you try without it, please?
Yes, you're correct that UnusedArea layer isn't strictly required. We are using it once to handle the case when IdPool gives us back something that is outside of what we originally requested. But we could also handle this just by bitmap setting the range num_chids..pool.capacity() on creation of ChannelIdPool, runtime checking num_chids >= BitmapVec::MAX_INLINE_LEN, or changing IdPool to always create a bitmap of the specified capacity (this is what I'll do unless someone knows a good reason not to).
Quoted 65 lines
Quoted 35 lines
drivers/gpu/nova-core/gpu/channel.rs new file +34
-0+assert_eq! (0 , a.start); +assert_eq! (1 , b.start); +assert_eq! (2 , c.start); +assert_eq! (3 , d.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<1 >(), unaligned).map (|_| ()) + ); + } + +assert_eq! (0 , pool.alloc_area (nz ::<4 >(), unaligned)?.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<5 >(), unaligned).map (|_| ()) + ); + +let head = pool.alloc_area (nz ::<3 >(), unaligned)?; +assert_eq! (0 , head.start); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<2 >(), unaligned).map (|_| ()) + ); +assert_eq! (3 , pool.alloc_area (nz ::<1 >(), unaligned)?.start); +Ok (()) + } + +#[test] +fn chid_area_aligned () ->Result { +let pool =KBox ::pin_init (ChannelIdPool ::new (16 ),GFP_KERNEL )?; +let unaligned =Alignment ::new ::<1 >(); +let align4 =Alignment ::new ::<4 >(); + +// Alloc 0 so the first fit for the next area is unaligned. +let pad = pool.alloc_area (nz ::<1 >(), unaligned)?;drivers/gpu/nova-core/gpu/channel.rs line 166
Quoted 10 lines
drivers/gpu/nova-core/gpu/channel.rs new file +10
-0+assert_eq! (0 , pad.start); + +let a = pool.alloc_area (nz ::<4 >(), align4)?; +assert_eq! (4 , a.start); + +// The area skipped over by the aligned allocation should still be available. +let b = pool.alloc_area (nz ::<1 >(), unaligned)?; +assert_eq! (1 , b.start); + +let c = pool.alloc_area (nz ::<8 >(),Alignment ::new ::<8 >())?;Is it possible to make it somehow simpler:
let c = pool.alloc_area(8, 8)?;All the parameters checking must be a part of implementations, not the interface.
We had a very similar discussion in the bitfields implementation thread, and many people in CC list of this thread spent quite a long time to find a way from:
let color = Rgb::default() .set_red(Bounded::<u16, _>::new::<0x10>()) .set_green(Bounded::<u16, _>::new::<0x1f>()) .set_blue(Bounded::<u16, _>::new::<0x18>());to:
Quoted 8 lines
let color = Rgb::default(). .set_red(0x10) .set_green(0x1f) .set_blue(0x18)Can you do the same here? Please refer:
I think that taking NonZero and Alignment here obviates the need for checking the parameters, since they have their own guarantees (and Alice recommended using Alignment on Bitmap too for this reason IIUC). Maybe I am misundertanding but we spent a few iterations here adding Alignment and NonZero on various parameters -- do you mean just making ChannelIdPool::alloc_area work with a plain integer syntax? It's possible to just take plain integers here and check, but I don't think it's necessarily better.
W.r.t. the bitfield stuff, yeah I agree that was a good call since that syntax was very verbose, and IIUC that was resolved by having e.g. with_const_red::<0x10>(). The analogous change here would be to provide const generic args, e.g. alloc_area_const::<size, align>() which could be plain integers. But, in practice the arguments to alloc_area are going to be runtime values (outside of tests) that the caller has strictly more info about. Having the separate types (NonZero, Alignment) also makes easier to not mix up the order. I can't think of a way to remove this verbosity without just passing plain integer runtime values, which IMO is not great.
Quoted 18 lines
Quoted 18 lines
drivers/gpu/nova-core/gpu/channel.rs new file +14
-0+assert_eq! (8 , c.start); + +// Only 2 IDs left. +assert_eq! (Err (ENOSPC ), pool.alloc_area (nz ::<4 >(), align4).map (|_| ())); +assert_eq! ( +Err (ENOSPC ), + pool.alloc_area (nz ::<1 >(),Alignment ::new ::<32 >()) + .map (|_| ()) + ); + +assert_eq! (2 , pool.alloc_area (nz ::<2 >(), unaligned)?.start); +Ok (()) + } +}Signature · 2 lines
-- 2.55.0
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 2 lines · Eliot Courtney
Quoted 1 line · Yury Norov
On Wed, Aug 12, 2026 at 05:51:25PM +0900, Eliot Courtney wrote:
...
Quoted 39 lines
Quoted 21 lines
Quoted 1 line
+ let c =
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;Is it possible to make it somehow simpler:
let c = pool.alloc_area(8, 8)?;All the parameters checking must be a part of implementations, not the interface.
We had a very similar discussion in the bitfields implementation thread, and many people in CC list of this thread spent quite a long time to find a way from:
let color = Rgb::default() .set_red(Bounded::<u16, _>::new::<0x10>()) .set_green(Bounded::<u16, _>::new::<0x1f>()) .set_blue(Bounded::<u16, _>::new::<0x18>());to:
Quoted 8 lines
let color = Rgb::default(). .set_red(0x10) .set_green(0x1f) .set_blue(0x18)Can you do the same here? Please refer:
I think that taking NonZero and Alignment here obviates the need for checking the parameters, since they have their own guarantees (and Alice recommended using Alignment on
Bitmaptoo for this reason IIUC). Maybe I am misundertanding but we spent a few iterations here addingAlignmentandNonZeroon various parameters -- do you mean just makingChannelIdPool::alloc_areawork with a plain integer syntax? It's possible to just take plain integers here and check, but I don't think it's necessarily better.
Quoted 10 lines
W.r.t. the bitfield stuff, yeah I agree that was a good call since that syntax was very verbose, and IIUC that was resolved by having e.g. with_const_red::<0x10>(). The analogous change here would be to provide const generic args, e.g. alloc_area_const::<size, align>() which could be plain integers. But, in practice the arguments to
alloc_areaare going to be runtime values (outside of tests) that the caller has strictly more info about. Having the separate types (NonZero, Alignment) also makes easier to not mix up the order. I can't think of a way to remove this verbosity without just passing plain integer runtime values, which IMO is not great.
pub(crate) fn alloc_area(
&self,
count: usize,
align: usize,
) -> Result<ChannelIdArea<'_>> {
let count = NonZero::new(count).ok_or(EINVAL)?;
let align = Alignment::new_checked(align).ok_or(EINVAL)?; let mut ids = self.inner.lock();
let area = ids.find_unused_area(0, count, align).ok_or(ENOSPC)?;
// If the pool is small, the backing bitmap may be rounded up to a larger size.
if area.range().end > self.num_chids {
return Err(ENOSPC);
}
Ok(ChannelIdArea {
pool: self,
range: area.acquire(),
})}
let area = pool.alloc_area(8, 4)?;
See the difference? You still check the parameters, but don't make it the part of interface.
And from practical perspective, your users simply call the function, not tinkering around your 'safety measures'.
In the next version, if you drop the intermediate UnusedArea layer, you may want to do a C-like check instead of creating new types, because here you'll directly call C function. And it's completely OK.
Not OK is complicating interfaces and life of your users.
Thanks,
Yury
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 2 lines · Yury Norov
Not OK is complicating interfaces and life of your users.
No, we don't want to introduce interfaces with unconstrained integers, especially so when we have already types that express what we want.
In other words, we don't want to introduce impossible states and error paths that aren't needed -- we want to rule them out statically. That is the point of all of what we are doing with Rust.
The unconstrained interface you are proposing is actually the complicated one, because it means now you have to provide more documentation about both the allowed input values and the new error cases. Not only that, you have to provide more tests for all that. And you have to duplicate information that types like Alignment already explain if you click on them.
And on the callee side, similarly, if someone already has e.g. an Alignment, then we don't want users to be forced to convert back to an unconstrained integer just to call the function that requires an alignment to begin with.
Now, if a function is truly something that we want to call with e.g. integer literals all the time, then maybe it is worth a workaround -- but those cases are rare, and even then it is likely to just be a wrapper to the normal interface.
Cheers,
Miguel
Danilo Krummrich
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Yury NorovQuoted 20 lines · Yury Norov
pub(crate) fn alloc_area( &self, count: usize, align: usize, ) -> Result<ChannelIdArea<'_>> { let count = NonZero::new(count).ok_or(EINVAL)?; let align = Alignment::new_checked(align).ok_or(EINVAL)?;let mut ids = self.inner.lock(); let area = ids.find_unused_area(0, count, align).ok_or(ENOSPC)?; // If the pool is small, the backing bitmap may be rounded up to a larger size. if area.range().end > self.num_chids { return Err(ENOSPC); } Ok(ChannelIdArea { pool: self, range: area.acquire(), })
Quoted 6 lines
}
let area = pool.alloc_area(8, 4)?;See the difference? You still check the parameters, but don't make it the part of interface.
Miguel already replied to this, so just briefly adding to this.
We usually want the arguments to already carry the invariants we require. If we make the arguments unconstrained, we may end up in situations where we already have types that provide certain guarantees about value constraints and yet we have to give up on them because the API takes unconstrained arguments and revalidates.
The code from Eliot does actually already takes advantage of this. In
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;
both arguments are already validated at compile time, whereas with unconstrained arguments we're left with a runtime check.
Yes, nz() does not actually validate it statically, but it easily could (and probably should).
Gary Guo
reviewerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 36 lines · Danilo Krummrich
Quoted 20 lines · Yury Norov
pub(crate) fn alloc_area( &self, count: usize, align: usize, ) -> Result<ChannelIdArea<'_>> { let count = NonZero::new(count).ok_or(EINVAL)?; let align = Alignment::new_checked(align).ok_or(EINVAL)?;let mut ids = self.inner.lock(); let area = ids.find_unused_area(0, count, align).ok_or(ENOSPC)?; // If the pool is small, the backing bitmap may be rounded up to a larger size. if area.range().end > self.num_chids { return Err(ENOSPC); } Ok(ChannelIdArea { pool: self, range: area.acquire(), })Quoted 6 lines
}
let area = pool.alloc_area(8, 4)?;See the difference? You still check the parameters, but don't make it the part of interface.
Miguel already replied to this, so just briefly adding to this.
We usually want the arguments to already carry the invariants we require. If we make the arguments unconstrained, we may end up in situations where we already have types that provide certain guarantees about value constraints and yet we have to give up on them because the API takes unconstrained arguments and revalidates.
Quoted 3 lines
The code from Eliot does actually already takes advantage of this. In
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;
I have to say this looks quite ugly, compared to just .alloc_area(8, 8). In this case I'd go with something aesthetically better...
While keeping invariants with types is generally good, for primitives I'm never a big fan of NonZero and Bounded... The turbofishes are just ugly and they are must harder to use compared to raw primitives without typing a lot of symbols.
Best,
Gary
Quoted 6 lines
both arguments are already validated at compile time, whereas with unconstrained arguments we're left with a runtime check.
Yes,
nz()does not actually validate it statically, but it easily could (and probably should).
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 2 lines · Gary Guo
Quoted 1 line · Danilo Krummrich
On Thu Aug 13, 2026 at 8:32 PM CEST, Yury Norov wrote:
...
Quoted 6 lines
Quoted 3 lines
The code from Eliot does actually already takes advantage of this. In
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;I have to say this looks quite ugly, compared to just
.alloc_area(8, 8). In this case I'd go with something aesthetically better...
In addition to aesthetics, a practical concern is that there is a higher cognitive load to both reading and writing the longer form, above. Perhaps that is just the price one must pay.
However, for primitive types, I am hearing (even from Miguel) that there might be a way to get the static checking *and* an easier interface.
Here's hoping you all can find a way to do that. :)
Quoted 5 lines
While keeping invariants with types is generally good, for primitives I'm never a big fan of
NonZeroandBounded... The turbofishes are just ugly and they are must harder to use compared to raw primitives without typing a lot of symbols.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 15 lines · John Hubbard
Quoted 2 lines · Gary Guo
Quoted 1 line · Danilo Krummrich
On Thu Aug 13, 2026 at 8:32 PM CEST, Yury Norov wrote:
...
Quoted 6 lines
Quoted 3 lines
The code from Eliot does actually already takes advantage of this. In
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;I have to say this looks quite ugly, compared to just
.alloc_area(8, 8). In this case I'd go with something aesthetically better...In addition to aesthetics, a practical concern is that there is a higher cognitive load to both reading and writing the longer form, above. Perhaps that is just the price one must pay.
Quoted 5 lines
However, for primitive types, I am hearing (even from Miguel) that there might be a way to get the static checking *and* an easier interface.
Here's hoping you all can find a way to do that. :)
There's a nice postfix macro proposal:
computation().macro!().method().another_macro!()
https://github.com/rust-lang/rfcs/pull/2442
That would solve the problem. But it doesn't move since 2024. I recall it was mentioned in the bitfields discussion, but maybe it's a false memory...
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 16 lines · Yury Norov
Quoted 15 lines · John Hubbard
Quoted 2 lines · Gary Guo
Quoted 1 line · Danilo Krummrich
On Thu Aug 13, 2026 at 8:32 PM CEST, Yury Norov wrote:
...
Quoted 6 lines
Quoted 3 lines
The code from Eliot does actually already takes advantage of this. In
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;I have to say this looks quite ugly, compared to just
.alloc_area(8, 8). In this case I'd go with something aesthetically better...In addition to aesthetics, a practical concern is that there is a higher cognitive load to both reading and writing the longer form, above. Perhaps that is just the price one must pay.
Quoted 5 lines
Quoted 5 lines
However, for primitive types, I am hearing (even from Miguel) that there might be a way to get the static checking *and* an easier interface.
Here's hoping you all can find a way to do that. :)
On second thought, we haven't talked about what the callers look like here, and .alloc_area(8, 8) could simply force the mess back into the call sites.
Quoted 10 lines
There's a nice postfix macro proposal:
computation().macro!().method().another_macro!()
https://github.com/rust-lang/rfcs/pull/2442
That would solve the problem. But it doesn't move since 2024. I recall it was mentioned in the bitfields discussion, but maybe it's a false memory...
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Danilo KrummrichQuoted 38 lines · Danilo Krummrich
Quoted 20 lines · Yury Norov
pub(crate) fn alloc_area( &self, count: usize, align: usize, ) -> Result<ChannelIdArea<'_>> { let count = NonZero::new(count).ok_or(EINVAL)?; let align = Alignment::new_checked(align).ok_or(EINVAL)?;let mut ids = self.inner.lock(); let area = ids.find_unused_area(0, count, align).ok_or(ENOSPC)?; // If the pool is small, the backing bitmap may be rounded up to a larger size. if area.range().end > self.num_chids { return Err(ENOSPC); } Ok(ChannelIdArea { pool: self, range: area.acquire(), })Quoted 6 lines
}
let area = pool.alloc_area(8, 4)?;See the difference? You still check the parameters, but don't make it the part of interface.
Miguel already replied to this, so just briefly adding to this.
We usually want the arguments to already carry the invariants we require. If we make the arguments unconstrained, we may end up in situations where we already have types that provide certain guarantees about value constraints and yet we have to give up on them because the API takes unconstrained arguments and revalidates.
The code from Eliot does actually already takes advantage of this. In
Quoted 7 lines
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;both arguments are already validated at compile time, whereas with unconstrained arguments we're left with a runtime check.
Yes,
nz()does not actually validate it statically, but it easily could (and probably should).
Alright, I'm not against the static checks, and I don't insist on my version. My complain is about readability and unnecessary complexity for end user.
let's find a way to convert this beast:
pool.alloc_area(nz::<8>(), alignment::new::<8>())?;
to something more readable, ideally:
pool.alloc_area(8, 8)?;
We were able to do this for bitfields, and I don't think we should give up here.
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 53 lines · Yury Norov
Quoted 38 lines · Danilo Krummrich
Quoted 20 lines · Yury Norov
pub(crate) fn alloc_area( &self, count: usize, align: usize, ) -> Result<ChannelIdArea<'_>> { let count = NonZero::new(count).ok_or(EINVAL)?; let align = Alignment::new_checked(align).ok_or(EINVAL)?;let mut ids = self.inner.lock(); let area = ids.find_unused_area(0, count, align).ok_or(ENOSPC)?; // If the pool is small, the backing bitmap may be rounded up to a larger size. if area.range().end > self.num_chids { return Err(ENOSPC); } Ok(ChannelIdArea { pool: self, range: area.acquire(), })Quoted 6 lines
}
let area = pool.alloc_area(8, 4)?;See the difference? You still check the parameters, but don't make it the part of interface.
Miguel already replied to this, so just briefly adding to this.
We usually want the arguments to already carry the invariants we require. If we make the arguments unconstrained, we may end up in situations where we already have types that provide certain guarantees about value constraints and yet we have to give up on them because the API takes unconstrained arguments and revalidates.
The code from Eliot does actually already takes advantage of this. In
Quoted 7 lines
pool.alloc_area(nz::<8>(), Alignment::new::<8>())?;both arguments are already validated at compile time, whereas with unconstrained arguments we're left with a runtime check.
Yes,
nz()does not actually validate it statically, but it easily could (and probably should).Alright, I'm not against the static checks, and I don't insist on my version. My complain is about readability and unnecessary complexity for end user.
let's find a way to convert this beast:
Quoted 8 lines
pool.alloc_area(nz::<8>(), alignment::new::<8>())?;to something more readable, ideally:
pool.alloc_area(8, 8)?;We were able to do this for bitfields, and I don't think we should give up here.
At the moment I can think of two ideas.
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).
So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;
I actually do not like pool.alloc_area(8, 8) because you can't tell what the parameters mean. Having to write Alignment is useful, IMO.
2. The same solution for bitfield, whcih was to provide a separate const method that takes the values as const generics. That looks like this:
pool.alloc_area_const::<8, 8>()?;
That said I think this form would mostly only be used in tests.
I personally prefer option #1 because it will make NonZero easier to use for everyone (I already have a few copies of the nz::<>() function in unit tests) and because it self-describes what the parameters do. And it doesn't have any turbofish.
What do you reckon?
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 7 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).
Quoted 7 lines
So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;
Actually found that if we implement SizeConstants for Alignment then we can get Alignment::SZ_4K etc almost for free.
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 11 lines · Eliot Courtney
Quoted 11 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
Quoted 6 lines
Quoted 3 lines
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;Actually found that if we implement SizeConstants for Alignment then we can get
Alignment::SZ_4Ketc almost for free.
Then maybe pass SZ_4K directly, and allow the alloc_area() to calculate the alignment:
pool.alloc_area(nz!(8), SZ_4K)?;
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 16 lines · Yury Norov
Quoted 15 lines · Eliot Courtney
Quoted 14 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;
Quoted 7 lines
Quoted 2 lines
Actually found that if we implement SizeConstants for Alignment then we can get
Alignment::SZ_4Ketc almost for free.Then maybe pass
SZ_4Kdirectly, and allow thealloc_area()to calculate the alignment:pool.alloc_area(nz!(8), SZ_4K)?;
Even worse, you can advertise the function like: allocate a contiguous set of channel IDs enough to represent XXX bytes of memory with YYY alignment. And that way, you'll be able to do:
pool.alloc_area(SZ_8K, SZ_4K)?;
If my understanding of the function is right, it would be a clear improvement, because the user now doesn't think about ID channels pool as a set of bits, but an abstraction over the memory access technique, which it really is.
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 29 lines · Yury Norov
Quoted 16 lines · Yury Norov
Quoted 15 lines · Eliot Courtney
Quoted 14 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;Quoted 7 lines
Quoted 2 lines
Actually found that if we implement SizeConstants for Alignment then we can get
Alignment::SZ_4Ketc almost for free.Then maybe pass
SZ_4Kdirectly, and allow thealloc_area()to calculate the alignment:pool.alloc_area(nz!(8), SZ_4K)?;Even worse, you can advertise the function like: allocate a contiguous set of channel IDs enough to represent XXX bytes of memory with YYY alignment. And that way, you'll be able to do:
Quoted 6 lines
pool.alloc_area(SZ_8K, SZ_4K)?;If my understanding of the function is right, it would be a clear improvement, because the user now doesn't think about ID channels pool as a set of bits, but an abstraction over the memory access technique, which it really is.
If we pass SZ_4K directly, we are back to using plain integers, which is not what we should be doing for rust interfaces according to Miguel. Let me send a new version of this with my Alignment constants + nz! macro idea, IMO it helps with the verbosity.
I don't quite understand your point about memory access. The purpose here is just to be an allocator of IDs, not memory - it's just that we have some contiguousness and alignment requirements of the IDs themselves. The values we're passing in just represent numbers of channels and constraints on those. I think that callers will naturally want to allocate a particular number of channels, not a specific amount of memory that corresponds to some number of channels in some way (e.g. USERD?). On pre-Blackwell, OpenRM makes channel ID area reservations for vGPU power of two number of channels and and places them so the base channel ID is aligned to the number of channels. Sorry if I have misunderstood your point. Maybe we should rename alloc_area to reserve_ids or something like that if it would make it clearer?
Gary Guo
reviewerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 37 lines · Eliot Courtney
Quoted 29 lines · Yury Norov
Quoted 16 lines · Yury Norov
Quoted 15 lines · Eliot Courtney
Quoted 14 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;Quoted 7 lines
Quoted 2 lines
Actually found that if we implement SizeConstants for Alignment then we can get
Alignment::SZ_4Ketc almost for free.Then maybe pass
SZ_4Kdirectly, and allow thealloc_area()to calculate the alignment:pool.alloc_area(nz!(8), SZ_4K)?;Even worse, you can advertise the function like: allocate a contiguous set of channel IDs enough to represent XXX bytes of memory with YYY alignment. And that way, you'll be able to do:
Quoted 6 lines
pool.alloc_area(SZ_8K, SZ_4K)?;If my understanding of the function is right, it would be a clear improvement, because the user now doesn't think about ID channels pool as a set of bits, but an abstraction over the memory access technique, which it really is.
Quoted 4 lines
If we pass
SZ_4Kdirectly, we are back to using plain integers, which is not what we should be doing for rust interfaces according to Miguel. Let me send a new version of this with my Alignment constants + nz! macro idea, IMO it helps with the verbosity.
I'm still not convinced with the nz! idea. Having to have a macro invocation for each call is excessive.
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 2 lines · Gary Guo
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Probably, but in contrast to ZST allocations it wouldn't be very useful, so we'd silently succeed on something that never was a reasonable argument in the first palce.
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 7 lines · Danilo Krummrich
Quoted 2 lines · Gary Guo
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Probably, but in contrast to ZST allocations it wouldn't be very useful, so we'd silently succeed on something that never was a reasonable argument in the first palce.
Yeah I agree that supporting a generalised zero sized alloc is in some ways conceptually nicer, but I also can't see any good reason why you would want to do it, it sounds like a bug. That's also why in the latest version I made IdPool also not allow a zero capacity [1] (incidentally required to not have to change the grow code to avoid trying to double a zero capacity thing every time).
Tbh, I feel that NonZero (and Alignment) is hard to use currently because of these ergonomics issues. But I reckon they're useful, so I like the idea of trying to making them easier to use. Maybe you can make an argument to not use NonZero here, but what about all the other times we will want to use it?
Danilo Krummrich
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 9 lines · Eliot Courtney
Quoted 7 lines · Danilo Krummrich
Quoted 2 lines · Gary Guo
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Probably, but in contrast to ZST allocations it wouldn't be very useful, so we'd silently succeed on something that never was a reasonable argument in the first palce.
Quoted 6 lines
Yeah I agree that supporting a generalised zero sized alloc is in some ways conceptually nicer, but I also can't see any good reason why you would want to do it, it sounds like a bug. That's also why in the latest version I made IdPool also not allow a zero capacity [1] (incidentally required to not have to change the grow code to avoid trying to double a zero capacity thing every time).
(I assume this is more a reply to Gary?)
Quoted 5 lines
Tbh, I feel that NonZero (and Alignment) is hard to use currently because of these ergonomics issues. But I reckon they're useful, so I like the idea of trying to making them easier to use. Maybe you can make an argument to not use NonZero here, but what about all the other times we will want to use it?
Personally, I don't see the argument for not using NonZero (or Alignment); the invariants required by the API are expressed very well by those types.
I also don't see a reason to step back from using those types for this API. If we'd do so it would question all the other new types we have over primitives carrying certain invariants to a certain extend as well.
I understand the ergonomics concern, and I also see that for compile time evaluation turbofish syntax is not that popular, but this can be improved.
The fundamental value remains that it nicely separates the invariants callers need to uphold about certain arguments from the API itself. It makes the code more maintainable (e.g. we don't need 10 different variants of a function depending on whether the value is a compile time, build time or run time value) and it makes the code more readable and robust (e.g. the semantic meaning of arguments is very obvious and confusing arguments becomes almost impossible).
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 10 lines · Danilo Krummrich
Quoted 9 lines · Eliot Courtney
Quoted 7 lines · Danilo Krummrich
Quoted 2 lines · Gary Guo
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Probably, but in contrast to ZST allocations it wouldn't be very useful, so we'd silently succeed on something that never was a reasonable argument in the first palce.
Quoted 8 lines
Quoted 6 lines
Yeah I agree that supporting a generalised zero sized alloc is in some ways conceptually nicer, but I also can't see any good reason why you would want to do it, it sounds like a bug. That's also why in the latest version I made IdPool also not allow a zero capacity [1] (incidentally required to not have to change the grow code to avoid trying to double a zero capacity thing every time).
(I assume this is more a reply to Gary?)
Yes, and so was the below too kinda. Sorry for the confusion.
Quoted 23 lines
Quoted 6 lines
Tbh, I feel that NonZero (and Alignment) is hard to use currently because of these ergonomics issues. But I reckon they're useful, so I like the idea of trying to making them easier to use. Maybe you can make an argument to not use NonZero here, but what about all the other times we will want to use it?
Personally, I don't see the argument for not using NonZero (or Alignment); the invariants required by the API are expressed very well by those types.
I also don't see a reason to step back from using those types for this API. If we'd do so it would question all the other new types we have over primitives carrying certain invariants to a certain extend as well.
I understand the ergonomics concern, and I also see that for compile time evaluation turbofish syntax is not that popular, but this can be improved.
The fundamental value remains that it nicely separates the invariants callers need to uphold about certain arguments from the API itself. It makes the code more maintainable (e.g. we don't need 10 different variants of a function depending on whether the value is a compile time, build time or run time value) and it makes the code more readable and robust (e.g. the semantic meaning of arguments is very obvious and confusing arguments becomes almost impossible).
Gary Guo
reviewerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Danilo KrummrichQuoted 25 lines · Danilo Krummrich
Quoted 9 lines · Eliot Courtney
Quoted 7 lines · Danilo Krummrich
Quoted 2 lines · Gary Guo
IMO we can just support zero-sized allocation by always succeeding, similar to how ZST allocation is handled in memory allocation.
Probably, but in contrast to ZST allocations it wouldn't be very useful, so we'd silently succeed on something that never was a reasonable argument in the first palce.
Quoted 6 lines
Yeah I agree that supporting a generalised zero sized alloc is in some ways conceptually nicer, but I also can't see any good reason why you would want to do it, it sounds like a bug. That's also why in the latest version I made IdPool also not allow a zero capacity [1] (incidentally required to not have to change the grow code to avoid trying to double a zero capacity thing every time).
(I assume this is more a reply to Gary?)
Quoted 5 lines
Tbh, I feel that NonZero (and Alignment) is hard to use currently because of these ergonomics issues. But I reckon they're useful, so I like the idea of trying to making them easier to use. Maybe you can make an argument to not use NonZero here, but what about all the other times we will want to use it?
Quoted 6 lines
Personally, I don't see the argument for not using NonZero (or Alignment); the invariants required by the API are expressed very well by those types.
I also don't see a reason to step back from using those types for this API. If we'd do so it would question all the other new types we have over primitives carrying certain invariants to a certain extend as well.
I think there is an distinction between semantic differences vs just range restrictions. Consider the other cases where we use new types:
* flags: very natural as you don't even need to mention raw literals.
* units: for things that semantically carry a unit, writing things like Delta::new_jiffies(...) is quite natural, just like writing "2 seconds"
* addresses: things like dma addresses naturally fit in new types because you don't need to write literals for them.
Now, with NonZero or Bounded, we are doing none of that. The only thing here is that there is a range restriction. Other than the value restriction themselves, they carry no other semantic meanings. How you interpret these types still fully depend on the API that accepts them. Therefore, it is very common that you'd be using these with literals, and it becomes an ergnomic pain.
If Rust pattern types become available in the future and you can write
fn alloc_area(&self, count: usize is 1..)
then I'd fully support adding that annotation to functions. Personally I value ergnomics higher than possibility of misuse if latter can be easily mitigated otherwise (in this case, by WARN_ON or just support zero-sized alloc).
Best,
Gary
Quoted 10 lines
I understand the ergonomics concern, and I also see that for compile time evaluation turbofish syntax is not that popular, but this can be improved.
The fundamental value remains that it nicely separates the invariants callers need to uphold about certain arguments from the API itself. It makes the code more maintainable (e.g. we don't need 10 different variants of a function depending on whether the value is a compile time, build time or run time value) and it makes the code more readable and robust (e.g. the semantic meaning of arguments is very obvious and confusing arguments becomes almost impossible).
Danilo Krummrich
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 5 lines · Gary Guo
Now, with
NonZeroorBounded, we are doing none of that. The only thing here is that there is a range restriction. Other than the value restriction themselves, they carry no other semantic meanings. How you interpret these types still fully depend on the API that accepts them. Therefore, it is very common that you'd be using these with literals, and it becomes an ergnomic pain.
I agree that NonZero and Bounded are on the weaker end of the argument. But there's still the flexibility argument.
The API itself, i.e. alloc_area(), does not need to bother with how the value is checked. I.e. is it a runtime check, compile or build time check, or is it even unchecked (or panicking) because we can derive the invariant from another type.
Quoted 3 lines
Personally I value ergnomics higher than possibility of misuse if latter can be easily mitigated otherwise (in this case, by
WARN_ONor just support zero-sized alloc).
Both is not a mitigation IMO.
WARN_ON() is does not prevent misuse of the API in the first place and in case the value comes from userspace even introduces a vulnerability.
Making zero a valid argument simply ignores the problem or just moves it elsewhere, e.g. where the caller has to validate the returned type instead, i.e. the ChannelIdArea. IOW, we'd remove the invariant ChannelIdArea carries.
Burak Emir
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 8 lines · Danilo Krummrich
Quoted 5 lines · Gary Guo
Now, with
NonZeroorBounded, we are doing none of that. The only thing here is that there is a range restriction. Other than the value restriction themselves, they carry no other semantic meanings. How you interpret these types still fully depend on the API that accepts them. Therefore, it is very common that you'd be using these with literals, and it becomes an ergnomic pain.
Quoted 7 lines
I agree that NonZero and Bounded are on the weaker end of the argument. But there's still the flexibility argument.
The API itself, i.e.
alloc_area(), does not need to bother with how the value is checked. I.e. is it a runtime check, compile or build time check, or is it even unchecked (or panicking) because we can derive the invariant from another type.
To add a minor point to this, if rustc could figure out that a suitable non-zero number literal can be treated as NonZero<usize>, we'd not need a macro and it would all be very ergonomic...
cheers,
- Burak
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 4 lines · Burak Emir
To add a minor point to this, if rustc could figure out that a suitable non-zero number literal can be treated as NonZero<usize>, we'd not need a macro and it would all be very ergonomic...
Yeah, that and/or 1nz literals could be nice. It may be a bit niche, though; and we would like good ergonomics for our own custom types too.
Nevertheless, I will ask upstream Rust in our next meeting about
https://github.com/rust-lang/rust/issues/69329.
I added it to https://github.com/Rust-for-Linux/linux/issues/354 as well.
Cheers,
Miguel
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Danilo KrummrichQuoted 18 lines · Danilo Krummrich
Quoted 5 lines · Gary Guo
Now, with
NonZeroorBounded, we are doing none of that. The only thing here is that there is a range restriction. Other than the value restriction themselves, they carry no other semantic meanings. How you interpret these types still fully depend on the API that accepts them. Therefore, it is very common that you'd be using these with literals, and it becomes an ergnomic pain.I agree that NonZero and Bounded are on the weaker end of the argument. But there's still the flexibility argument.
The API itself, i.e.
alloc_area(), does not need to bother with how the value is checked. I.e. is it a runtime check, compile or build time check, or is it even unchecked (or panicking) because we can derive the invariant from another type.Quoted 3 lines
Personally I value ergnomics higher than possibility of misuse if latter can be easily mitigated otherwise (in this case, by
WARN_ONor just support zero-sized alloc).
Quoted 8 lines
Both is not a mitigation IMO.
WARN_ON()is does not prevent misuse of the API in the first place and in case the value comes from userspace even introduces a vulnerability.Making zero a valid argument simply ignores the problem or just moves it elsewhere, e.g. where the caller has to validate the returned type instead, i.e. the ChannelIdArea. IOW, we'd remove the invariant ChannelIdArea carries.
Let's get back to roots, maybe?
The kernel functions don't check parameters, with the very few exceptions, because the kernel trusts itself.
What are those exceptions?
1. strnlen(char *s, unsigned count). Here the 'count' hard-stops traversing the array 's' in case it's not null-terminated. Why? Because c-string is the bad data structure, and it's a very common, very well known vulnerability of C strings to have them not null-terminated. It brings tons of troubles, that's why.
GENMASK(hi, lo) falls into the same category, for example. People always think of it as GENMASK(lo, hi). Bad design...
2. FIELD_PREP(mask, val) checks mask for being dense and wide enough to fit the val. It's a very basic operation, has 0 cost and implemented at compile time. In fact, FIELD_PREP() is a compile-time macro. The corresponding run-time field_prep() doesn't check for any consistency.
3. int pin_user_pages_fast(...)
{
if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
return -EINVAL;
return gup_fast_fallback(start, nr_pages, gup_flags, pages);}
It's not a validator per se, like nr_pages == 0. It's rather a consistency checker.
I don't think that alloc(size, align) matches one of the above. The underlying bitmap is not as bad as C string, the alloc_area() is not a compile-time macro, and NonZero<0>() doesn't look like a complex cross-validation.
From maintenance perspective, I don't think it's even possible to pass 0 into the alloc_area(), so that it slips through the reviewers attention. NonZero<0>() is a pure complication for absolutely no reason.
Again, any kernel API trusts it's caller. It holds for assembler, for C, and I don't see any reason why it shouldn't hold for Rust.
Rust is more restrictive to undefined behavior. Having that in mind, we may want to prevent the known undef. But that should never become a part of the API. And undef isn't the case for alloc(0) - instead of making non-zero 'size' a part of API contract, we must make the function behavior well defined for this case. kmalloc(0), for example, returns ZERO_SIZE_PTR. The pool.alloc_area(0) may return None, and probably trigger some warning.
The underlying bitmap_find_next_zero_area_of(0) doesn't behave well, so Rust wrapper should take care of it. pool.alloc_area() doesn't call the C function directly, it calls the wrapper. The problem must be already resolved at this level.
Thanks,
Yury
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
Quoted 3 lines · Yury Norov
Again, any kernel API trusts it's caller. It holds for assembler, for C, and I don't see any reason why it shouldn't hold for Rust.
Because the more you trust callers, the more complexity you are adding to keep everything dancing in sync, and thus the more perfect you have to be on every subsequent patch that modifies any code.
So this is all about not having to trust callers as much as possible -- the point of using Rust in the kernel is to prevent mistakes using the stronger type system.
And preventing mistakes is not just about memory safety. That is, even if f(0) is not UB, we still want to consider whether it is worth using the type system to prevent such an input.
In other words, yes, restricting inputs to functions as much as possible allows us to convert certain functions from unsafe to safe ones, but it doesn't mean we have to stop there: we use the type system to prevent other mistakes too.
We can even have types that do not restrict in any way the inputs value-wise, i.e. they may be pure wrappers of a primitive integer, to prevent mishandling such as passing the wrong kind of unit or mixing up two parameters.
Now, particular cases may or may not be worth it, but the general principle stands.
Cheers,
Miguel
Danilo Krummrich
maintainerRe: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Yury NorovQuoted 2 lines · Yury Norov
Again, any kernel API trusts it's caller. It holds for assembler, for C, and I don't see any reason why it shouldn't hold for Rust.
This argument is misleading in this context, because it is conflating "trusting the caller" with "trusting the value".
The kernel's APIs generally do trust the caller (and even that does not always hold), but they do not necessarily trust the arguments passed by a caller; this entirely depends on the API contract.
And this makes a lot of sense; sometimes values originate from untrusted sources, such as userspace.
But even if there is a clearly expressed API contract for the bounds of a value, kernel APIs regularly do still check their validity.
For instance, do_mmap() does return -EINVAL if !len, despite the documentation (*1) even saying:
@len: The length of the mapping. Will be page-aligned and must be at
least 1 page in size.
In this case one reason is layering, the len argument *may* originate from userspace, but it does not always originate from userspace (i.e. an untrusted source).
So, if we'd write do_mmap() in Rust, it would be a perfect candidate for len being NonZero.
This way there's only a single do_mmap() function, that doesn't need to bother with a runtime check for len, because the argument already holds that invariant.
The way the invariant is obtained depends on the call site. If the value comes from userspace, you do a fallible check
let len = NonZero::new(len).ok_or(EINVAL)?;
If the value is known at compile time you can instead call
let len = nz!(PAGE_SIZE);
which is checked at compile time.
Maybe you also already got a NonZero value from a different API that already obtained the non-zero invariant that you just pass through.
It nicely separates the code that validates the value from the user of the value, where the user of the value is only interested in the required invariant, but not how the invariant is obtained.
IOW, do_mmap() does not care (and should not care) how the caller ensures that len != 0.
Quoted 3 lines
And undef isn't the case for alloc(0) - instead of making non-zero 'size' a part of API contract, we must make the function behavior well defined for this case.
We should only do this if the return value does not depend on an argument's invariant, in which case no invariant is needed in the first place.
Quoted 2 lines
kmalloc(0), for example, returns
ZERO_SIZE_PTR. Thepool.alloc_area(0)may return None, and probably trigger some warning.
That's because ZERO_SIZE_PTR *is* a useful return value that adds real value (even more useful in Rust with ZST). It does for instance allow you to write:
items = kmalloc_array(n, sizeof(*items), GFP_KERNEL); if (!items) return -ENOMEM; for (i = 0; i < n; i++) process(items[i]); kfree(items);
However, reserve_ids() is not like kmalloc(), a ChannelIdArea with a zero range isn't useful at all.
And returning Result<Option<ChannelIdArea>> is not useful either, as it would move the validation through NonZero (which you want to avoid) back to the user now having to validate the Option instead, which, for obvious reasons, is worse given that it is actually an error condition: there's nothing optional here, it's just that the input argument was wrong, so Ok(None) is even misleading.
(*1) do_mmap()
I think the documentation is slighly misleading, since it says "must be at least 1 page in size", but the actual requirement is non-zero. It's just that anything that is not page aligned is rounded up, so any 0 < len < PAGE_SIZE ends up at PAGE_SIZE too.
Re: [PATCH v5 5/5] gpu: nova-core: add ChannelIdPool
In reply to Eliot CourtneyQuoted 37 lines · Eliot Courtney
Quoted 29 lines · Yury Norov
Quoted 16 lines · Yury Norov
Quoted 15 lines · Eliot Courtney
Quoted 14 lines
1. Provide a nz! macro to create constant non-zero things. Provide some constants for common alignments
Potentially, we could use
build_assert! for cases it is provably non-zero but not a literal (although tbh not sure this is a good idea - at least not do this initially).So either: nz!: const { NonZero::new(value).unwrap() }, or, nz!: some build assert gated construction of NonZero. A general nz! macro could also help ergonomics for other use cases too.
That looks like this:
pool.alloc_area(nz!(8), Alignment::AL_8)?;Quoted 7 lines
Quoted 2 lines
Actually found that if we implement SizeConstants for Alignment then we can get
Alignment::SZ_4Ketc almost for free.Then maybe pass
SZ_4Kdirectly, and allow thealloc_area()to calculate the alignment:pool.alloc_area(nz!(8), SZ_4K)?;Even worse, you can advertise the function like: allocate a contiguous set of channel IDs enough to represent XXX bytes of memory with YYY alignment. And that way, you'll be able to do:
Quoted 6 lines
pool.alloc_area(SZ_8K, SZ_4K)?;If my understanding of the function is right, it would be a clear improvement, because the user now doesn't think about ID channels pool as a set of bits, but an abstraction over the memory access technique, which it really is.
Quoted 4 lines
If we pass
SZ_4Kdirectly, we are back to using plain integers, which is not what we should be doing for rust interfaces according to Miguel. Let me send a new version of this with my Alignment constants + nz! macro idea, IMO it helps with the verbosity.
I meant that if you have 8-bit alignment and granularity, you can create your own enum and pass it as parameter. But it's valid for pre-blackwell channel allocations only, so not applicable in general.
Quoted 1 line
I don't quite understand your point about memory access.
Neither me. Scratch that. It was a hallucination, maybe somehow related to the 1st day of flu. :)
Quoted 4 lines
The purpose
here is just to be an allocator of IDs, not memory - it's just that we have some contiguousness and alignment requirements of the IDs themselves. The values we're passing in just represent numbers of
Quoted 8 lines
channels and constraints on those. I think that callers will naturally want to allocate a particular number of channels, not a specific amount of memory that corresponds to some number of channels in some way (e.g. USERD?). On pre-Blackwell, OpenRM makes channel ID area reservations for vGPU power of two number of channels and and places them so the base channel ID is aligned to the number of channels. Sorry if I have misunderstood your point. Maybe we should rename
alloc_areatoreserve_idsor something like that if it would make it clearer?
Yes, reserve_ids() sounds better because the parent structure is named ChannelIdPool.