rust: Add support for reserving of ranges of IDs
Subsystems (6)
v4 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 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 | 268 +++++++++++++++++++++++++++++++++-- rust/kernel/id_pool.rs | 69 +++++++++ 4 files changed, 504 insertions(+), 15 deletions(-)
---
base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
change-id: 20260608-chid-18fa943c6d6c
Best regards,
Signature · 1 line
Eliot Courtney <[email protected]>
PATCH v4 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
PATCH v4 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 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
rust/kernel/bitmap.rs +7 -1
@@ -17,6 +17,7 @@/// # 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 {
@@ -30,11 +31,13 @@ impl Bitmap {/// /// * `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 {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
@@ -55,11 +58,13 @@ pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap {/// /// * `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 {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
@@ -415,7 +420,8 @@ pub fn clear_bit_atomic(&self, index: usize) {#[inline] pub fn copy_and_extend (&mut self, src: &Bitmap ) {let len = core::cmp::min (src.len (), self.len ()); -// SAFETY: access to `self` and `src` is within bounds. +// SAFETY: access to `self` and `src` is within bounds. Both lengths fit in `u32` +// because a `Bitmap` is at most `i32::MAX` bits, so the casts are lossless. unsafe { bindings::bitmap_copy_and_extend ( self.as_mut_ptr(),
Signature · 1 line
2.55.0
PATCH v4 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 | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+)
rust/kernel/bitmap.rs +235 -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.
@@ -503,6 +504,138 @@ 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 ()?; + +// The C alignment and end arithmetic must not overflow, or it can read out of bounds. +// Overflow is only possible on 32-bit. +let align_mask = align.as_usize () -1 ; + 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 )]
@@ -620,4 +753,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
PATCH v4 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
PATCH v4 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
[email protected]
AI reviewRe: [PATCH v4 2/5] rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Eliot CourtneyThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [High] This problem wasn't introduced by this patch, but the safe Rust API for Bitmap allows data races (Undefined Behavior). The methods set_bit_atomic and clear_bit_atomic are marked as safe and take a shared reference &self to perform atomic mutations. However, Bitmap (and BitmapVec via Deref) implements Sync, meaning &Bitmap can be shared across multiple threads. Other safe methods like next_bit, last_bit, and copy_and_extend (via the src parameter) also take &self but perform non-atomic reads. This allows safe Rust code to execute concurrent atomic writes and non-atomic reads on the same memory, violating Rust's memory model and causing Undefined Behavior (a data race). The safety comment in set_bit_atomic incorrectly states 'the caller has ensured that there is no mix of non-atomic and atomic operations', but since the method is marked safe, the compiler cannot enforce this. --
--- Patch [2]: [PATCH v4 2/5] rust: bitmap: restrict bitmap length to at most i32::MAX --- commit d989729ee19564d93c5d59130c2e1ac3974ea804
Author: Eliot Courtney <[email protected]>
rust: bitmap: restrict bitmap length to at most i32::MAX
This patch restricts the maximum size of a Bitmap to i32::MAX bits to match BitmapVec. It updates the unsafe requirements for Bitmap::from_raw and from_raw_mut to reflect this limit. It also corrects potential out-of-bounds writes in copy_and_extend caused by u32 cast truncations.
Quoted 4 lines
rust/kernel/bitmap.rs +0
-0
[ ... ]
rust/kernel/bitmap.rs pub fn clear_bit_atomic(&self, index: usize) { · line 421
Quoted 3 lines
rust/kernel/bitmap.rs +0
-0@@ -415,7 +420,8 @@ pub fn clear_bit_atomic(&self, index: usize) {#[inline] pub fn copy_and_extend (&mut self, src: &Bitmap ) {
[Severity: High]
This isn't a bug introduced by this patch, but does the safe Rust API for Bitmap allow data races?
The set_bit_atomic() and clear_bit_atomic() methods are marked as safe and take a shared reference to perform atomic mutations. However, Bitmap implements Sync, meaning it can be shared across multiple threads.
Other safe methods like next_bit(), last_bit(), and copy_and_extend() (via the src parameter here) also take a shared reference but perform non-atomic reads. This allows safe Rust code to execute concurrent atomic writes and non-atomic reads on the same memory, violating the memory model.
The safety comment in set_bit_atomic() states the caller has ensured there is no mix of non-atomic and atomic operations, but since the method is marked safe, the compiler cannot enforce this.
Could the API be updated to prevent safe code from triggering a data race?
Quoted 7 lines
rust/kernel/bitmap.rs +2
-1let 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
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v4 3/5] rust: bitmap: add contiguous area operations
In reply to Eliot CourtneyThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] The overflow check `align_mask.checked_add(self.len())?.checked_add(nbits)?` incorrectly rejects…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] The overflow check align_mask.checked_add(self.len())?.checked_add(nbits)? incorrectly rejects valid next_zero_area_off queries on 32-bit architectures when self.len() and nbits are large.
- [Medium] The assertion start < self.len() in next_zero_area_off panics if start == self.len(), which breaks iterators and empty bitmaps.
--
--- Patch [3]: [PATCH v4 3/5] rust: bitmap: add contiguous area operations --- commit cd8a17b1e3284bd61e474e6a67facb0e46c2ec8a
Author: Eliot Courtney <[email protected]>
rust: bitmap: add contiguous area operations
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_HARDENED is on. Tests demonstrating the edge cases are also included.
Quoted 4 lines
rust/kernel/bitmap.rs +0
-0
[ ... ]
Quoted 16 lines
rust/kernel/bitmap.rs +12
-0@@ -504,6 +504,138 @@ 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.
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 528
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+#[inline] +pub fn next_zero_area_off ( + &self, + start:usize , + nbits:usize , + align:Alignment , + align_offset:usize , + ) ->Option <usize > { +bitmap_assert! ( + start < self.len (),
[Severity: Medium]
Does this assertion break iterators and empty bitmaps when CONFIG_RUST_BITMAP_HARDENED is enabled?
If a caller iteratively searches for zero areas (e.g., start = area_index + nbits) and the last found area ends exactly at the bitmap boundary, the next iteration will query with start == self.len(). Also, querying an empty bitmap (self.len() == 0) with start = 0 would trigger this panic.
The underlying C function bitmap_find_next_zero_area_off() safely processes start >= size by returning size, which the Rust code gracefully transforms to None.
Could we use start <= self.len() here instead, similar to how the set() and clear() functions allow end <= self.len()?
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 539
Quoted 11 lines
rust/kernel/bitmap.rs +11
-0+ "`start` must be < {}, was {}", + self.len(), + start + ); + +let nr = u32::try_from (nbits).ok ()?; + +// The C alignment and end arithmetic must not overflow, or it can read out of bounds. +// Overflow is only possible on 32-bit. +let align_mask = align.as_usize () -1 ; + align_mask.checked_add (self.len ())?.checked_add (nbits)?;
[Severity: Medium]
Is this overflow check overly strict for 32-bit architectures?
If a caller requests a large contiguous area in a large bitmap, such as self.len() = 0x7FFFFFFF and nbits = 0x7FFFFFFF, the sum of align_mask + self.len() + nbits can exceed u32::MAX. This would cause the checked_add() chain to fail and incorrectly return None instead of executing the search.
Since we only need to prevent the C function's end = index + nr calculation from wrapping around maliciously, and we know nbits <= self.len() makes nr at most 0x7FFFFFFF, any wrap-around of index + nr on 32-bit would mathematically result in an end value strictly less than index. The C code handles end < index safely by returning index, which Rust then correctly rejects since index < self.len() is false.
Would a simpler check like "if nbits > self.len() { return None; }" be sufficient to prevent malicious wrap-around while preserving valid searches for large boundaries?
Quoted 6 lines
rust/kernel/bitmap.rs +6
-0+ +// 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(),
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v4 2/5] rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Eliot CourtneyQuoted 46 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.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]>--- rust/kernel/bitmap.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)rust/kernel/bitmap.rs +3
-0@@ -17,6 +17,7 @@/// # 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 {@@ -30,11 +31,13 @@ impl Bitmap {/// /// * `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 {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
rust/kernel/bitmap.rs pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap { · line 67
Quoted 10 lines
rust/kernel/bitmap.rs +2
-0@@ -55,11 +58,13 @@ pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap {/// /// * `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 {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`.
Can you enforce it in code, instead of comments? Maybe under CONFIG_RUST_BITMAP_HARDENED?
Quoted 16 lines
rust/kernel/bitmap.rs +2
-1// SAFETY: // The caller guarantees that `data` (derived from `ptr` and `nbits`) // points to a valid, initialized, and appropriately sized memory region @@ -415,7 +420,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
Re: [PATCH v4 3/5] rust: bitmap: add contiguous area operations
In reply to Eliot CourtneyQuoted 49 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 | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+)rust/kernel/bitmap.rs +22
-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. @@ -503,6 +504,138 @@ 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! (
rust/kernel/bitmap.rs pub fn next_zero_bit(&self, start: usize) -> Option<usize> { · line 537
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+ start < self.len(), + "`start` must be < {}, was {}", + self.len(), + start + ); + +let nr = u32::try_from (nbits).ok ()?; + +// The C alignment and end arithmetic must not overflow, or it can read out of bounds. +// Overflow is only possible on 32-bit.
That doesn't sound optimistic. Can you add a check for 32-bit case?
The rest looks good.
Thanks,
Yury
Quoted 214 lines
rust/kernel/bitmap.rs +203
-0+let align_mask = align.as_usize () -1 ; + 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 )] @@ -620,4 +753,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 · 2 lines
-- 2.55.0