Add support for contiguous area allocation. Add a new type, `UnusedArea`, following the same pattern as `UnusedId`.
Signed-off-by: Eliot Courtney <[email protected]> --- rust/kernel/id_pool.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/rust/kernel/id_pool.rs b/rust/kernel/id_pool.rs index 384753fe0e44..b471bfd97487 100644 --- a/rust/kernel/id_pool.rs +++ b/rust/kernel/id_pool.rs @@ -4,6 +4,11 @@ //! 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; @@ -240,6 +245,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`. + /// + /// `align_mask` must be `0` (no alignment) or one less than a power of two, in which case the + /// start of the returned area is a multiple of that power of two. + /// + /// 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_mask: usize, + ) -> Option<UnusedArea<'_>> { + let start = self.map.next_zero_area(offset, count.get(), align_mask)?; + 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_area(range.start, range.len()); + } } /// Represents an unused id in an [`IdPool`]. @@ -287,6 +319,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: &'pool mut 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_area(range.start, range.end - range.start); + range + } +} + impl Default for IdPool { #[inline] fn default() -> Self { -- 2.54.0
