Skip to contentSkip to conversation

rust: Add support for reserving of ranges of IDs

PATCH Applied Eliot Courtney 5 participants 21 messages Nov 9 – Nov 12

Subsystems (8)

v11 of 12 Applied Latest is v12 →

lore
Share & tools
lore
#0 lore raw

v11 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.

The bitmap and IdPool parts from earlier versions are in v7.4-rc1 now, and this version has the remaining patches: using the Alignment size constants, exact IdPool capacities, and 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 v11:
- Rebase on drm-rust-next (pre-reqs are merged now)
- Split patch #1 by subsystem (Danilo). Just splitting with no actual changes, so I kept the reviewed-by tags on the new patches
- Add reviewed-by tags
- Link to v10: https://patch.msgid.link/[email protected]

Changes in v10:
- Drop the patches that were applied to rust-next
- Rebase on drm-rust-next (plus pre-reqs)
- Use a capacity of 1 instead of 0 in the grow_request() example in patch #2 (Yury)
- Convert the remaining Alignment::new() users in nova-core in patch #1
- Link to v9: https://patch.msgid.link/[email protected]

Changes in v9:
- Rebase on drm-rust-next
- Moved cv! to a separate series which this now depends on
- Reference Link: tag from the text + indent code in patch #4 commit message (Miguel)
- Add reviewed-by tags
- Link to v8: https://patch.msgid.link/[email protected]

Changes in v8:
- Clarify overflow cases in patch #2 (Alex)
- Replace nz! with generalized cv! macro (Gary)
- Add cv! macro to prelude
- Split SizeConstants and adding new constants patch (Alex)
- Move alignment size constants conersions patch (Alex)
- Drop NonZero on IdPool, fix grow_request instead (Alice, Alex)
- Add shrink/grow doctests (Burak)
- Link to v7: https://patch.msgid.link/[email protected]

Changes in v7:
- Add nz! macro for compile time NonZero
- Implement SizeConstants for Alignment + add sub 1k size constants
- Use Alignment constants + nz! in this series
- Add final patch converting existing callers to use Alignment constants
- Rename alloc_area/release_area -> reserve_ids / release_ids
- Link to v6: https://patch.msgid.link/[email protected]

Changes in v6:
- Take a NonZero nbits in next_zero_area_off, set and clear (Yury)
- Remove UnusedArea, IdPool::alloc_area now allocates directly (Yury)
- Add patch: take a NonZero capacity in IdPool::with_capacity()
- Add patch: do not round the capacity up to BitmapVec::MAX_INLINE_LEN, which also removes the bounds check in ChannelIdPool::alloc_area
- Add more testing of Drop for ChannelIdPool (Yury)
- Link to v5: https://patch.msgid.link/[email protected]

Changes in v5:
- bitmap_assert! i32::MAX length for Bitmap::from_raw* (Yury)
- Only run overflow check on 32-bit (Yury)
- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- Add next_zero_area_off to match C code (Yury)
- Replace overflow checks to match C code in bitmap-for-next.
- Tighten Bitmap unsafe contract to disallow Bitmaps larger than i32::MAX
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Use Alignment type in id_pool and bitmap (Alice)
- Remove hang check on the basis that it's extraordinarily rare.
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Collected Alice's Reviewed-by on patch 1.
- Address Yury's comments w.r.t. using __bitmap_set etc directly.
- Address Yury's comments w.r.t. following the C names
- Additionally check for an overflow case that causes a hang
- Added more info to cover letter + patch 4 w.r.t. channel ID allottment requirements
- Add align parameter to ChannelIdPool::alloc_area() plus an aligned allocation test
- Add missing INVARIANT comment when constructing UnusedArea
- Link to v1:
https://patch.msgid.link/[email protected]

---
Eliot Courtney (5):
rust: io: use Alignment size constants
rust: gpu: buddy: use Alignment size constants
gpu: nova-core: use Alignment size constants
rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN
gpu: nova-core: add ChannelIdPool

 drivers/gpu/nova-core/fb.rs               |  10 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs     |   2 +-
 drivers/gpu/nova-core/fsp.rs              |   4 +-
 drivers/gpu/nova-core/gpu.rs              |   9 +-
 drivers/gpu/nova-core/gpu/channel.rs      | 198 ++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gsp/fw.rs           |  12 +-
 drivers/gpu/nova-core/mm.rs               |   2 +-
 drivers/gpu/nova-core/mm/bar_user.rs      |   7 +-
 drivers/gpu/nova-core/mm/pagetable/map.rs |   7 +-
 drivers/gpu/nova-core/mm/pramin.rs        |   6 +-
 drivers/gpu/nova-core/vbios.rs            |   7 +-
 rust/kernel/gpu/buddy.rs                  |  26 ++--
 rust/kernel/id_pool.rs                    |  38 +++++-
 rust/kernel/io.rs                         |   5 +-
 14 files changed, 279 insertions(+), 54 deletions(-)

---
base-commit: 7ecd9ee29f7bfbe9a293952fbc83c3f8bd7205dd
change-id: 20260608-chid-18fa943c6d6c

Best regards,

Signature · 1 line
Eliot Courtney <[email protected]>
#1 lore raw

PATCH v11 1/5 rust: io: use Alignment size constants

Use SizeConstants for Alignment that are implemented now.

---
 rust/kernel/io.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
rust/kernel/io.rs +3 -2
index a877df11a03e..31c6975376bf 100644
@@ -21,7 +21,8 @@
     ptr::{
         Alignment,
         KnownSize, //
-    }, //
+    },
+    sizes::SizeConstants, //
 };
 
 #[cfg(CONFIG_HAS_IOMEM)]
@@ -154,7 +155,7 @@ pub fn ptr_try_from_raw_parts_mut(base: *mut u8, size: usize) -> Result<*mut Sel
 impl<const SIZE: usize> KnownSize for Region<SIZE> {
     const MIN_SIZE: usize = SIZE;
     // Alignment of 4 is the most common; different base types can be added once required.
-    const MIN_ALIGN: Alignment = Alignment::new::<4>();
+    const MIN_ALIGN: Alignment = Alignment::SZ_4;
 
     #[inline(always)]
     fn size(p: *const Self) -> usize {
Signature · 1 line
2.56.0
#4 lore raw

PATCH v11 2/5 rust: gpu: buddy: use Alignment size constants

In reply to Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

---
 rust/kernel/gpu/buddy.rs | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
rust/kernel/gpu/buddy.rs +13 -13
index d502ada6ebbd..691bb40629d4 100644
@@ -31,11 +31,11 @@
 //! let buddy = GpuBuddy::new(GpuBuddyParams {
 //!     base_offset: 0,
 //!     size: SZ_1G as u64,
-//!     chunk_size: Alignment::new::<SZ_4K>(),
+//!     chunk_size: Alignment::SZ_4K,
 //! })?;
 //!
 //! assert_eq!(buddy.size(), SZ_1G as u64);
-//! assert_eq!(buddy.chunk_size(), Alignment::new::<SZ_4K>());
+//! assert_eq!(buddy.chunk_size(), Alignment::SZ_4K);
 //! let initial_free = buddy.avail();
 //!
 //! // Allocate 16MB. Block lands at the top of the address range.
@@ -43,7 +43,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Simple,
 //!         SZ_16M as u64,
-//!         Alignment::new::<SZ_16M>(),
+//!         Alignment::SZ_16M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -74,14 +74,14 @@
 //! # let buddy = GpuBuddy::new(GpuBuddyParams {
 //! #     base_offset: 0,
 //! #     size: SZ_1G as u64,
-//! #     chunk_size: Alignment::new::<SZ_4K>(),
+//! #     chunk_size: Alignment::SZ_4K,
 //! # })?;
 //! # let initial_free = buddy.avail();
 //! let topdown = KBox::pin_init(
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::TopDown,
 //!         SZ_16M as u64,
-//!         Alignment::new::<SZ_16M>(),
+//!         Alignment::SZ_16M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -114,7 +114,7 @@
 //! # let buddy = GpuBuddy::new(GpuBuddyParams {
 //! #     base_offset: 0,
 //! #     size: SZ_1G as u64,
-//! #     chunk_size: Alignment::new::<SZ_4K>(),
+//! #     chunk_size: Alignment::SZ_4K,
 //! # })?;
 //! # let initial_free = buddy.avail();
 //! // Create fragmentation by allocating 4MB blocks at [0,4M) and [8M,12M).
@@ -122,7 +122,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_4M as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -133,7 +133,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -145,7 +145,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_16M as u64),
 //!         SZ_8M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -178,14 +178,14 @@
 //! let small = GpuBuddy::new(GpuBuddyParams {
 //!     base_offset: 0,
 //!     size: SZ_16M as u64,
-//!     chunk_size: Alignment::new::<SZ_4K>(),
+//!     chunk_size: Alignment::SZ_4K,
 //! })?;
 //!
 //! let _hole1 = KBox::pin_init(
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_4M as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -195,7 +195,7 @@
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -206,7 +206,7 @@
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Simple,
 //!         SZ_8M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlag::Contiguous,
 //!     ),
 //!     GFP_KERNEL,
Signature · 1 line
2.56.0
#7 lore raw

PATCH v11 3/5 gpu: nova-core: use Alignment size constants

In reply to Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

---
 drivers/gpu/nova-core/fb.rs               | 10 +++++-----
 drivers/gpu/nova-core/fb/hal/gb100.rs     |  2 +-
 drivers/gpu/nova-core/fsp.rs              |  4 ++--
 drivers/gpu/nova-core/gpu.rs              |  7 ++-----
 drivers/gpu/nova-core/gsp/fw.rs           | 12 +++---------
 drivers/gpu/nova-core/mm.rs               |  2 +-
 drivers/gpu/nova-core/mm/bar_user.rs      |  7 ++++---
 drivers/gpu/nova-core/mm/pagetable/map.rs |  7 +++++--
 drivers/gpu/nova-core/mm/pramin.rs        |  6 +++---
 drivers/gpu/nova-core/vbios.rs            |  7 +++++--
 10 files changed, 31 insertions(+), 33 deletions(-)
drivers/gpu/nova-core/fb.rs +5 -5
index b0c0b8fe6008..5ceb7760c78e 100644
@@ -219,7 +219,7 @@ pub(crate) fn new(
         };
 
         let frts = {
-            const FRTS_DOWN_ALIGN: Alignment = Alignment::new::<SZ_128K>();
+            const FRTS_DOWN_ALIGN: Alignment = Alignment::SZ_128K;
             let frts_size: u64 = hal.frts_size();
             let frts_base = vga_workspace.start.align_down(FRTS_DOWN_ALIGN) - frts_size;
 
@@ -227,7 +227,7 @@ pub(crate) fn new(
         };
 
         let boot = {
-            const BOOTLOADER_DOWN_ALIGN: Alignment = Alignment::new::<SZ_4K>();
+            const BOOTLOADER_DOWN_ALIGN: Alignment = Alignment::SZ_4K;
             let bootloader_size = u64::from_safe_cast(gsp_fw.bootloader.ucode.size());
             let bootloader_base = (frts.start - bootloader_size).align_down(BOOTLOADER_DOWN_ALIGN);
 
@@ -235,7 +235,7 @@ pub(crate) fn new(
         };
 
         let fw_image = {
-            const FW_IMAGE_DOWN_ALIGN: Alignment = Alignment::new::<SZ_64K>();
+            const FW_IMAGE_DOWN_ALIGN: Alignment = Alignment::SZ_64K;
             let fw_image_size = u64::from_safe_cast(gsp_fw.size());
             let fw_image_addr = (boot.start - fw_image_size).align_down(FW_IMAGE_DOWN_ALIGN);
 
@@ -245,7 +245,7 @@ pub(crate) fn new(
         let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(chipset, vgpu_state, fb.end)?;
 
         let wpr2_heap = {
-            const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::new::<SZ_1M>();
+            const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::SZ_1M;
             let wpr2_heap_addr = fw_image
                 .start
                 .checked_sub(wpr2_heap_size)
@@ -256,7 +256,7 @@ pub(crate) fn new(
         };
 
         let wpr2 = {
-            const WPR2_DOWN_ALIGN: Alignment = Alignment::new::<SZ_1M>();
+            const WPR2_DOWN_ALIGN: Alignment = Alignment::SZ_1M;
             let wpr2_addr = (wpr2_heap.start - u64::from_safe_cast(size_of::<gsp::GspFwWprMeta>()))
                 .align_down(WPR2_DOWN_ALIGN);
 
drivers/gpu/nova-core/fb/hal/gb100.rs +1 -1
index 612f70333c11..37b2ae762df4 100644
@@ -80,7 +80,7 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
 
 // This PMU reservation size is r570-specific.
 pub(super) const fn pmu_reserved_size_gb100() -> u32 {
-    cv!(const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap())
+    cv!(const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::SZ_128K).unwrap())
 }
 
 impl FbHal for Gb100 {
drivers/gpu/nova-core/fsp.rs +2 -2
index 3a4a10487f33..637a00b2c951 100644
@@ -20,7 +20,7 @@
         Alignable,
         Alignment, //
     },
-    sizes::SZ_2M,
+    sizes::SizeConstants,
     time::Delta,
     transmute::{
         AsBytes,
@@ -259,7 +259,7 @@ fn frts_vidmem_offset(hal: &dyn hal::FspHal, fb_info: &FbSizes) -> Result<u64> {
         if fb_info.pmu_reserved_size != 0 {
             offset = (offset + u64::from(fb_info.pmu_reserved_size))
                 // The 2 MiB alignment is r570-specific.
-                .align_up(Alignment::new::<SZ_2M>())
+                .align_up(Alignment::SZ_2M)
                 .ok_or(EINVAL)?;
         }
 
drivers/gpu/nova-core/gpu.rs +2 -5
index ac5305d7ff5e..d185e927233f 100644
@@ -12,10 +12,7 @@
     pci,
     prelude::*,
     ptr::Alignment,
-    sizes::{
-        SizeConstants,
-        SZ_4K, //
-    },
+    sizes::SizeConstants,
     uapi, //
 };
 
@@ -568,7 +565,7 @@ pub(crate) fn new<'a>(
                 let buddy_params = GpuBuddyParams {
                     base_offset: usable_vram.start,
                     size: usable_vram.end - usable_vram.start,
-                    chunk_size: Alignment::new::<SZ_4K>(),
+                    chunk_size: Alignment::SZ_4K,
                 };
 
                 GpuMm::new(
drivers/gpu/nova-core/gsp/fw.rs +3 -9
index 75b98f24dea1..5c216d777dff 100644
@@ -26,10 +26,7 @@
         Alignment,
         KnownSize, //
     },
-    sizes::{
-        SizeConstants,
-        SZ_128K, //
-    },
+    sizes::SizeConstants,
     transmute::{
         AsBytes,
         FromBytes, //
@@ -65,7 +62,7 @@
 enum GspFwHeapParams {}
 
 /// Minimum required alignment for the GSP heap.
-const GSP_HEAP_ALIGNMENT: Alignment = Alignment::new::<{ 1 << 20 }>();
+const GSP_HEAP_ALIGNMENT: Alignment = Alignment::SZ_1M;
 
 impl GspFwHeapParams {
     /// Returns the amount of GSP-RM heap memory used during GSP-RM boot and initialization (up to
@@ -209,10 +206,7 @@ pub(crate) fn from_ranges<'a>(
             bootBinOffset: ranges.boot.start,
             frtsOffset: ranges.frts.start,
             frtsSize: ranges.frts.len(),
-            gspFwWprEnd: ranges
-                .vga_workspace
-                .start
-                .align_down(Alignment::new::<SZ_128K>()),
+            gspFwWprEnd: ranges.vga_workspace.start.align_down(Alignment::SZ_128K),
             gspFwHeapVfPartitionCount: ranges.vf_partition_count,
             fbSize: ranges.fb.len(),
             vgaWorkspaceOffset: ranges.vga_workspace.start,
drivers/gpu/nova-core/mm.rs +1 -1
index 8a934c55169f..f53886f9ed91 100644
@@ -317,7 +317,7 @@ pub(crate) fn run(
 
         let base = usable_fb_regions.iter().find_map(|region| {
             // Tests rely on this being 8 byte aligned for checking misalignment handling.
-            let base = region.start.align_up(Alignment::new::<8>())?;
+            let base = region.start.align_up(Alignment::SZ_8)?;
             (base.checked_add(SELFTEST_SPAN)? <= region.end).then_some(base)
         });
         let Some(base) = base else {
drivers/gpu/nova-core/mm/bar_user.rs +4 -3
index 6e9384f06f43..2e8bd2a8ed91 100644
@@ -195,6 +195,7 @@ pub(crate) fn run_self_test(
         },
         ptr::Alignment,
         sizes::{
+            SizeConstants,
             SZ_16K,
             SZ_32K,
             SZ_4K,
@@ -222,7 +223,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Simple,
             SZ_4K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
@@ -299,7 +300,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Range(range_base + sz_16k..range_base + sz_16k + sz_4k),
             SZ_4K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
@@ -311,7 +312,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Range(range_base..range_base + sz_32k_4k),
             SZ_32K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
drivers/gpu/nova-core/mm/pagetable/map.rs +5 -2
index 77431c509a89..f7774b9cc972 100644
@@ -17,7 +17,10 @@
         RBTree,
         RBTreeNode, //
     },
-    sizes::SZ_4K, //
+    sizes::{
+        SizeConstants,
+        SZ_4K, //
+    }, //
 };
 
 use super::{
@@ -84,7 +87,7 @@ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<Prep
             mm.buddy().alloc_blocks(
                 GpuBuddyAllocMode::Simple,
                 SZ_4K.into_safe_cast(),
-                Alignment::new::<SZ_4K>(),
+                Alignment::SZ_4K,
                 GpuBuddyAllocFlags::default(),
             ),
             GFP_KERNEL,
drivers/gpu/nova-core/mm/pramin.rs +3 -3
index 7f89c093d591..c83b1681d241 100644
@@ -19,8 +19,8 @@
         Alignment, //
     },
     sizes::{
-        SZ_1M,
-        SZ_64K, //
+        SizeConstants,
+        SZ_1M, //
     },
 };
 
@@ -103,7 +103,7 @@ fn drop(&mut self) {
 
 impl<'gpu> Pramin<'gpu> {
     /// Alignment required by the PRAMIN window.
-    const BASE_ALIGN: Alignment = Alignment::new::<SZ_64K>();
+    const BASE_ALIGN: Alignment = Alignment::SZ_64K;
 
     /// Creates the window manager for the given VRAM region.
     pub(super) fn new(
drivers/gpu/nova-core/vbios.rs +5 -2
index 9c214b9f4dd9..a2d2d170b501 100644
@@ -11,7 +11,10 @@
         Alignment, //
     },
     register,
-    sizes::SZ_4K,
+    sizes::{
+        SizeConstants,
+        SZ_4K, //
+    },
     sync::aref::ARef,
 };
 
@@ -291,7 +294,7 @@ fn next(&mut self) -> Option<Self::Item> {
 
         // Advance to next image (aligned to 512 bytes).
         self.current_offset += image_size;
-        self.current_offset = self.current_offset.align_up(Alignment::new::<512>())?;
+        self.current_offset = self.current_offset.align_up(Alignment::SZ_512)?;
 
         Some(Ok(full_image))
     }
Signature · 1 line
2.56.0
#10 lore raw

PATCH v11 4/5 rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

In reply to Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible. This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

---
 rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +32 -6
index 92eeb7caa243..f77bd90325ff 100644
@@ -112,13 +112,8 @@ pub fn new() -> Self {
     }
 
     /// Constructs a new [`IdPool`] with space for a specific number of bits.
-    ///
-    /// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`].
-    ///
-    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     #[inline]
     pub fn with_capacity(num_ids: usize, flags: Flags) -> Result<Self, AllocError> {
-        let num_ids = usize::max(num_ids, BitmapVec::MAX_INLINE_LEN);
         let map = BitmapVec::new(num_ids, flags)?;
         Ok(Self { map })
     }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {
     /// let resizer = alloc_request.realloc(GFP_KERNEL)?;
     /// pool.shrink(resizer);
     /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further.
+    /// assert!(pool.shrink_request().is_none());
+    ///
+    /// // Neither can a pool with a capacity below `MAX_INLINE_LEN`.
+    /// let small = IdPool::with_capacity(8, GFP_KERNEL)?;
+    /// assert!(small.shrink_request().is_none());
     /// # Ok::<(), AllocError>(())
     /// ```
     #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {
 
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);
         if num_ids > BitmapVec::MAX_LEN {
             return None;
         }
Signature · 1 line
2.56.0
#18 lore raw

PATCH v11 5/5 gpu: nova-core: add ChannelIdPool

In reply to Eliot Courtney

Add ChannelIdPool which adds automatic tracking and releasing of channel IDs on top of IdPool. This is necessary for apportioning ranges of channel IDs to be used in e.g. vGPU.

Channel IDs are allocated as a contiguous sequence with a specific length and sometimes a specific alignment [1] for vGPU. The ID space is small (limited to 2048) and allocation is not on a hot path, so a bitmap-backed IdPool is a better fit than IDA/xarray (which allocate a single ID within a range, not a contiguous sequence) or a maple tree (where aligned allocation needs an alloc_range()+erase() retry loop that essentially reimplements bitmap_find_next_zero_area()) [2]. It is also faster than maple tree [3].

---
 drivers/gpu/nova-core/gpu.rs         |   2 +
 drivers/gpu/nova-core/gpu/channel.rs | 198 +++++++++++++++++++++++++++++++++++
 2 files changed, 200 insertions(+)
drivers/gpu/nova-core/gpu.rs +2 -0
index d185e927233f..90b1d24cdf00 100644
@@ -53,6 +53,8 @@
     vgpu::VgpuManager, //
 };
 
+#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))]
+mod channel;
 mod hal;
 mod regs;
 
drivers/gpu/nova-core/gpu/channel.rs new file +198 -0

198 lines not on this page · raw message

Signature · 1 line
2.56.0
maintainer Reviewed-by on v11 4/5
#11 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

Quoted 8 lines

This allows specifying a real capacity of 0, which was not previously possible. This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

reviewer
#12 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

In reply to Eliot Courtney
Quoted 74 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible. This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

---
 rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +25 -5
index 92eeb7caa243..f77bd90325ff 100644
@@ -112,13 +112,8 @@ pub fn new() -> Self {
     }
 
     /// Constructs a new [`IdPool`] with space for a specific number of bits.
-    ///
-    /// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`].
-    ///
-    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     #[inline]
     pub fn with_capacity(num_ids: usize, flags: Flags) -> Result<Self, AllocError> {
-        let num_ids = usize::max(num_ids, BitmapVec::MAX_INLINE_LEN);
         let map = BitmapVec::new(num_ids, flags)?;
         Ok(Self { map })
     }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {
     /// let resizer = alloc_request.realloc(GFP_KERNEL)?;
     /// pool.shrink(resizer);
     /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further.
+    /// assert!(pool.shrink_request().is_none());
+    ///
+    /// // Neither can a pool with a capacity below `MAX_INLINE_LEN`.
+    /// let small = IdPool::with_capacity(8, GFP_KERNEL)?;
+    /// assert!(small.shrink_request().is_none());
     /// # Ok::<(), AllocError>(())
     /// ```
     #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {
 
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///

rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 232

Quoted 10 lines
rust/kernel/id_pool.rs +7 -1
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);

It looks like your want the IdPool have a controlled capacity. However, as soon as grow_request is used, the capacity becomes uncontrolled.

It feels that this actually means that there are two use cases here: unbounded IdPool (where capacity just means the _current_ capacity) and bounded IdPool (where capacity means the _max_ capacity).

This is more similar to a difference between len() and capacity(). It feels to me that you're merrging Vec<bool> and Box<[bool]> into a single type where it shouldn't.

Best,
Gary

reviewer Reviewed-by on v11 1/5
#2 lore raw

Re: [PATCH v11 1/5] rust: io: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 3 lines
---
 rust/kernel/io.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
reviewer Reviewed-by on v11 2/5
#5 lore raw

Re: [PATCH v11 2/5] rust: gpu: buddy: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 3 lines
---
 rust/kernel/gpu/buddy.rs | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
reviewer Reviewed-by on v11 3/5
#8 lore raw

Re: [PATCH v11 3/5] gpu: nova-core: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 12 lines
---
 drivers/gpu/nova-core/fb.rs               | 10 +++++-----
 drivers/gpu/nova-core/fb/hal/gb100.rs     |  2 +-
 drivers/gpu/nova-core/fsp.rs              |  4 ++--
 drivers/gpu/nova-core/gpu.rs              |  7 ++-----
 drivers/gpu/nova-core/gsp/fw.rs           | 12 +++---------
 drivers/gpu/nova-core/mm.rs               |  2 +-
 drivers/gpu/nova-core/mm/bar_user.rs      |  7 ++++---
 drivers/gpu/nova-core/mm/pagetable/map.rs |  7 +++++--
 drivers/gpu/nova-core/mm/pramin.rs        |  6 +++---
 drivers/gpu/nova-core/vbios.rs            |  7 +++++--
 10 files changed, 31 insertions(+), 33 deletions(-)
maintainer Applied
#19 lore raw

Re: (subset) [PATCH v11 0/5] rust: Add support for reserving of ranges of IDs

In reply to Eliot Courtney
Quoted 1 line · Eliot Courtney

[PATCH v11 0/5] rust: Add support for reserving of ranges of IDs

Applied, thanks!

Branch: driver-core-testing
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git

[1/5] rust: io: use Alignment size constants

      commit: 4d1f2b176df7

The patch will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patch is in the driver-core-testing branch and will be promoted to driver-core-next after validation.

maintainer Applied
#20 lore raw

Re: (subset) [PATCH v11 0/5] rust: Add support for reserving of ranges of IDs

In reply to Eliot Courtney
Quoted 1 line · Eliot Courtney

[PATCH v11 0/5] rust: Add support for reserving of ranges of IDs

Applied, thanks!

Branch: drm-rust-next
Tree: https://gitlab.freedesktop.org/drm/rust/kernel.git

[2/5] rust: gpu: buddy: use Alignment size constants

      commit: 1937c07c9f83
[3/5] gpu: nova-core: use Alignment size constants
      commit: a7cdb17ca0d7

The patches will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patches are queued up for the upcoming merge window for the next major kernel release.

#13 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

In reply to Gary Guo
Quoted 15 lines · Gary Guo
Quoted 14 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible. This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

---

[...]

Quoted 37 lines
Quoted 23 lines
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
rust/kernel/id_pool.rs +18 -0
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///

rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 232

Quoted 10 lines
rust/kernel/id_pool.rs +7 -1
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);

It looks like your want the IdPool have a controlled capacity. However, as soon as grow_request is used, the capacity becomes uncontrolled.

Quoted 7 lines

It feels that this actually means that there are two use cases here: unbounded IdPool (where capacity just means the _current_ capacity) and bounded IdPool (where capacity means the _max_ capacity).

This is more similar to a difference between len() and capacity(). It feels to me that you're merrging Vec<bool> and Box<[bool]> into a single type where it shouldn't.

Yerp I agree there are two use cases here and this is adding the "fixed+controlled capacity" use case. But e.g. for Vec, we also have this "double use case" with push_within_capacity. So you can use Vec in both use cases as well.

The analogy would be:
Vec::len <=> # of actually allocated ids
Vec::capacity <=> # of available or allocated ids Vec::push_within_capacity <=> IdPool::find_unused_id / reserve_ids Vec::reserve <=> IdPool::grow / IdPool::grow_request Vec::shrink_to <=> IdPool::shrink / IdPool::shrink_request

Vec::push equivalent doesn't exist because neither binder's use case (needs to separate allocation) nor nova's use case (uses fixed capacity) requires a combined "reserve and push_within_capacity".

That said with this patch IdPool::with_capacity provides a guarantee of the capacity which Vec::with_capacity doesn't (altho I think it could for non-ZSTs). So I agree that there is a conceptual difference here w.r.t. "controlled" (guaranteed) capacity. The reason I did it this way is that I think that providing this extra guarantee is easy to do (removes code) without unduly complicating IdPool, plus adding to/allowing reuse of the existing common API functions.

We could consider in a follow-up to introduce a typestate, like Fixed vs Growable (defaulting to Growable) and grow/shrink is only implemented for Growable. But IMO it's overcomplicated to do this - if you don't want to grow it, just don't grow it. It's currently very hard to accidentally grow IdPool (compared to Vec where it would be far easier to mess it up if you tried to control the capacity). Perhaps if later many more things are added to IdPool then it'll then be worth to split it.

WDYT?

Reviewed-by on v11 1/5
#3 lore raw

Re: [PATCH v11 1/5] rust: io: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 31 lines
---
 rust/kernel/io.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
rust/kernel/io.rs +3 -2
index a877df11a03e..31c6975376bf 100644
@@ -21,7 +21,8 @@
     ptr::{
         Alignment,
         KnownSize, //
-    }, //
+    },
+    sizes::SizeConstants, //
 };
 
 #[cfg(CONFIG_HAS_IOMEM)]
@@ -154,7 +155,7 @@ pub fn ptr_try_from_raw_parts_mut(base: *mut u8, size: usize) -> Result<*mut Sel
 impl<const SIZE: usize> KnownSize for Region<SIZE> {
     const MIN_SIZE: usize = SIZE;
     // Alignment of 4 is the most common; different base types can be added once required.
-    const MIN_ALIGN: Alignment = Alignment::new::<4>();
+    const MIN_ALIGN: Alignment = Alignment::SZ_4;
 
     #[inline(always)]
     fn size(p: *const Self) -> usize {
Signature · 2 lines
-- 
2.56.0
Reviewed-by on v11 2/5
#6 lore raw

Re: [PATCH v11 2/5] rust: gpu: buddy: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 123 lines
---
 rust/kernel/gpu/buddy.rs | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)
rust/kernel/gpu/buddy.rs +13 -13
index d502ada6ebbd..691bb40629d4 100644
@@ -31,11 +31,11 @@
 //! let buddy = GpuBuddy::new(GpuBuddyParams {
 //!     base_offset: 0,
 //!     size: SZ_1G as u64,
-//!     chunk_size: Alignment::new::<SZ_4K>(),
+//!     chunk_size: Alignment::SZ_4K,
 //! })?;
 //!
 //! assert_eq!(buddy.size(), SZ_1G as u64);
-//! assert_eq!(buddy.chunk_size(), Alignment::new::<SZ_4K>());
+//! assert_eq!(buddy.chunk_size(), Alignment::SZ_4K);
 //! let initial_free = buddy.avail();
 //!
 //! // Allocate 16MB. Block lands at the top of the address range.
@@ -43,7 +43,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Simple,
 //!         SZ_16M as u64,
-//!         Alignment::new::<SZ_16M>(),
+//!         Alignment::SZ_16M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -74,14 +74,14 @@
 //! # let buddy = GpuBuddy::new(GpuBuddyParams {
 //! #     base_offset: 0,
 //! #     size: SZ_1G as u64,
-//! #     chunk_size: Alignment::new::<SZ_4K>(),
+//! #     chunk_size: Alignment::SZ_4K,
 //! # })?;
 //! # let initial_free = buddy.avail();
 //! let topdown = KBox::pin_init(
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::TopDown,
 //!         SZ_16M as u64,
-//!         Alignment::new::<SZ_16M>(),
+//!         Alignment::SZ_16M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -114,7 +114,7 @@
 //! # let buddy = GpuBuddy::new(GpuBuddyParams {
 //! #     base_offset: 0,
 //! #     size: SZ_1G as u64,
-//! #     chunk_size: Alignment::new::<SZ_4K>(),
+//! #     chunk_size: Alignment::SZ_4K,
 //! # })?;
 //! # let initial_free = buddy.avail();
 //! // Create fragmentation by allocating 4MB blocks at [0,4M) and [8M,12M).
@@ -122,7 +122,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_4M as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -133,7 +133,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -145,7 +145,7 @@
 //!     buddy.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_16M as u64),
 //!         SZ_8M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -178,14 +178,14 @@
 //! let small = GpuBuddy::new(GpuBuddyParams {
 //!     base_offset: 0,
 //!     size: SZ_16M as u64,
-//!     chunk_size: Alignment::new::<SZ_4K>(),
+//!     chunk_size: Alignment::SZ_4K,
 //! })?;
 //!
 //! let _hole1 = KBox::pin_init(
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(0..SZ_4M as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -195,7 +195,7 @@
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Range(SZ_8M as u64..(SZ_8M + SZ_4M) as u64),
 //!         SZ_4M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlags::default(),
 //!     ),
 //!     GFP_KERNEL,
@@ -206,7 +206,7 @@
 //!     small.alloc_blocks(
 //!         GpuBuddyAllocMode::Simple,
 //!         SZ_8M as u64,
-//!         Alignment::new::<SZ_4M>(),
+//!         Alignment::SZ_4M,
 //!         GpuBuddyAllocFlag::Contiguous,
 //!     ),
 //!     GFP_KERNEL,
Signature · 2 lines
-- 
2.56.0
Reviewed-by on v11 3/5
#9 lore raw

Re: [PATCH v11 3/5] gpu: nova-core: use Alignment size constants

In reply to Eliot Courtney
Quoted 5 lines · Eliot Courtney

Use SizeConstants for Alignment that are implemented now.

Quoted 289 lines
---
 drivers/gpu/nova-core/fb.rs               | 10 +++++-----
 drivers/gpu/nova-core/fb/hal/gb100.rs     |  2 +-
 drivers/gpu/nova-core/fsp.rs              |  4 ++--
 drivers/gpu/nova-core/gpu.rs              |  7 ++-----
 drivers/gpu/nova-core/gsp/fw.rs           | 12 +++---------
 drivers/gpu/nova-core/mm.rs               |  2 +-
 drivers/gpu/nova-core/mm/bar_user.rs      |  7 ++++---
 drivers/gpu/nova-core/mm/pagetable/map.rs |  7 +++++--
 drivers/gpu/nova-core/mm/pramin.rs        |  6 +++---
 drivers/gpu/nova-core/vbios.rs            |  7 +++++--
 10 files changed, 31 insertions(+), 33 deletions(-)
drivers/gpu/nova-core/fb.rs +5 -5
index b0c0b8fe6008..5ceb7760c78e 100644
@@ -219,7 +219,7 @@ pub(crate) fn new(
         };
 
         let frts = {
-            const FRTS_DOWN_ALIGN: Alignment = Alignment::new::<SZ_128K>();
+            const FRTS_DOWN_ALIGN: Alignment = Alignment::SZ_128K;
             let frts_size: u64 = hal.frts_size();
             let frts_base = vga_workspace.start.align_down(FRTS_DOWN_ALIGN) - frts_size;
 
@@ -227,7 +227,7 @@ pub(crate) fn new(
         };
 
         let boot = {
-            const BOOTLOADER_DOWN_ALIGN: Alignment = Alignment::new::<SZ_4K>();
+            const BOOTLOADER_DOWN_ALIGN: Alignment = Alignment::SZ_4K;
             let bootloader_size = u64::from_safe_cast(gsp_fw.bootloader.ucode.size());
             let bootloader_base = (frts.start - bootloader_size).align_down(BOOTLOADER_DOWN_ALIGN);
 
@@ -235,7 +235,7 @@ pub(crate) fn new(
         };
 
         let fw_image = {
-            const FW_IMAGE_DOWN_ALIGN: Alignment = Alignment::new::<SZ_64K>();
+            const FW_IMAGE_DOWN_ALIGN: Alignment = Alignment::SZ_64K;
             let fw_image_size = u64::from_safe_cast(gsp_fw.size());
             let fw_image_addr = (boot.start - fw_image_size).align_down(FW_IMAGE_DOWN_ALIGN);
 
@@ -245,7 +245,7 @@ pub(crate) fn new(
         let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(chipset, vgpu_state, fb.end)?;
 
         let wpr2_heap = {
-            const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::new::<SZ_1M>();
+            const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::SZ_1M;
             let wpr2_heap_addr = fw_image
                 .start
                 .checked_sub(wpr2_heap_size)
@@ -256,7 +256,7 @@ pub(crate) fn new(
         };
 
         let wpr2 = {
-            const WPR2_DOWN_ALIGN: Alignment = Alignment::new::<SZ_1M>();
+            const WPR2_DOWN_ALIGN: Alignment = Alignment::SZ_1M;
             let wpr2_addr = (wpr2_heap.start - u64::from_safe_cast(size_of::<gsp::GspFwWprMeta>()))
                 .align_down(WPR2_DOWN_ALIGN);
 
drivers/gpu/nova-core/fb/hal/gb100.rs +1 -1
index 612f70333c11..37b2ae762df4 100644
@@ -80,7 +80,7 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
 
 // This PMU reservation size is r570-specific.
 pub(super) const fn pmu_reserved_size_gb100() -> u32 {
-    cv!(const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap())
+    cv!(const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::SZ_128K).unwrap())
 }
 
 impl FbHal for Gb100 {
drivers/gpu/nova-core/fsp.rs +2 -2
index 3a4a10487f33..637a00b2c951 100644
@@ -20,7 +20,7 @@
         Alignable,
         Alignment, //
     },
-    sizes::SZ_2M,
+    sizes::SizeConstants,
     time::Delta,
     transmute::{
         AsBytes,
@@ -259,7 +259,7 @@ fn frts_vidmem_offset(hal: &dyn hal::FspHal, fb_info: &FbSizes) -> Result<u64> {
         if fb_info.pmu_reserved_size != 0 {
             offset = (offset + u64::from(fb_info.pmu_reserved_size))
                 // The 2 MiB alignment is r570-specific.
-                .align_up(Alignment::new::<SZ_2M>())
+                .align_up(Alignment::SZ_2M)
                 .ok_or(EINVAL)?;
         }
 
drivers/gpu/nova-core/gpu.rs +2 -5
index ac5305d7ff5e..d185e927233f 100644
@@ -12,10 +12,7 @@
     pci,
     prelude::*,
     ptr::Alignment,
-    sizes::{
-        SizeConstants,
-        SZ_4K, //
-    },
+    sizes::SizeConstants,
     uapi, //
 };
 
@@ -568,7 +565,7 @@ pub(crate) fn new<'a>(
                 let buddy_params = GpuBuddyParams {
                     base_offset: usable_vram.start,
                     size: usable_vram.end - usable_vram.start,
-                    chunk_size: Alignment::new::<SZ_4K>(),
+                    chunk_size: Alignment::SZ_4K,
                 };
 
                 GpuMm::new(
drivers/gpu/nova-core/gsp/fw.rs +3 -9
index 75b98f24dea1..5c216d777dff 100644
@@ -26,10 +26,7 @@
         Alignment,
         KnownSize, //
     },
-    sizes::{
-        SizeConstants,
-        SZ_128K, //
-    },
+    sizes::SizeConstants,
     transmute::{
         AsBytes,
         FromBytes, //
@@ -65,7 +62,7 @@
 enum GspFwHeapParams {}
 
 /// Minimum required alignment for the GSP heap.
-const GSP_HEAP_ALIGNMENT: Alignment = Alignment::new::<{ 1 << 20 }>();
+const GSP_HEAP_ALIGNMENT: Alignment = Alignment::SZ_1M;
 
 impl GspFwHeapParams {
     /// Returns the amount of GSP-RM heap memory used during GSP-RM boot and initialization (up to
@@ -209,10 +206,7 @@ pub(crate) fn from_ranges<'a>(
             bootBinOffset: ranges.boot.start,
             frtsOffset: ranges.frts.start,
             frtsSize: ranges.frts.len(),
-            gspFwWprEnd: ranges
-                .vga_workspace
-                .start
-                .align_down(Alignment::new::<SZ_128K>()),
+            gspFwWprEnd: ranges.vga_workspace.start.align_down(Alignment::SZ_128K),
             gspFwHeapVfPartitionCount: ranges.vf_partition_count,
             fbSize: ranges.fb.len(),
             vgaWorkspaceOffset: ranges.vga_workspace.start,
drivers/gpu/nova-core/mm.rs +1 -1
index 8a934c55169f..f53886f9ed91 100644
@@ -317,7 +317,7 @@ pub(crate) fn run(
 
         let base = usable_fb_regions.iter().find_map(|region| {
             // Tests rely on this being 8 byte aligned for checking misalignment handling.
-            let base = region.start.align_up(Alignment::new::<8>())?;
+            let base = region.start.align_up(Alignment::SZ_8)?;
             (base.checked_add(SELFTEST_SPAN)? <= region.end).then_some(base)
         });
         let Some(base) = base else {
drivers/gpu/nova-core/mm/bar_user.rs +4 -3
index 6e9384f06f43..2e8bd2a8ed91 100644
@@ -195,6 +195,7 @@ pub(crate) fn run_self_test(
         },
         ptr::Alignment,
         sizes::{
+            SizeConstants,
             SZ_16K,
             SZ_32K,
             SZ_4K,
@@ -222,7 +223,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Simple,
             SZ_4K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
@@ -299,7 +300,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Range(range_base + sz_16k..range_base + sz_16k + sz_4k),
             SZ_4K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
@@ -311,7 +312,7 @@ pub(crate) fn run_self_test(
         mm.buddy().alloc_blocks(
             GpuBuddyAllocMode::Range(range_base..range_base + sz_32k_4k),
             SZ_32K.into_safe_cast(),
-            Alignment::new::<SZ_4K>(),
+            Alignment::SZ_4K,
             GpuBuddyAllocFlags::default(),
         ),
         GFP_KERNEL,
drivers/gpu/nova-core/mm/pagetable/map.rs +5 -2
index 77431c509a89..f7774b9cc972 100644
@@ -17,7 +17,10 @@
         RBTree,
         RBTreeNode, //
     },
-    sizes::SZ_4K, //
+    sizes::{
+        SizeConstants,
+        SZ_4K, //
+    }, //
 };
 
 use super::{
@@ -84,7 +87,7 @@ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<Prep
             mm.buddy().alloc_blocks(
                 GpuBuddyAllocMode::Simple,
                 SZ_4K.into_safe_cast(),
-                Alignment::new::<SZ_4K>(),
+                Alignment::SZ_4K,
                 GpuBuddyAllocFlags::default(),
             ),
             GFP_KERNEL,
drivers/gpu/nova-core/mm/pramin.rs +3 -3
index 7f89c093d591..c83b1681d241 100644
@@ -19,8 +19,8 @@
         Alignment, //
     },
     sizes::{
-        SZ_1M,
-        SZ_64K, //
+        SizeConstants,
+        SZ_1M, //
     },
 };
 
@@ -103,7 +103,7 @@ fn drop(&mut self) {
 
 impl<'gpu> Pramin<'gpu> {
     /// Alignment required by the PRAMIN window.
-    const BASE_ALIGN: Alignment = Alignment::new::<SZ_64K>();
+    const BASE_ALIGN: Alignment = Alignment::SZ_64K;
 
     /// Creates the window manager for the given VRAM region.
     pub(super) fn new(
drivers/gpu/nova-core/vbios.rs +5 -2
index 9c214b9f4dd9..a2d2d170b501 100644
@@ -11,7 +11,10 @@
         Alignment, //
     },
     register,
-    sizes::SZ_4K,
+    sizes::{
+        SizeConstants,
+        SZ_4K, //
+    },
     sync::aref::ARef,
 };
 
@@ -291,7 +294,7 @@ fn next(&mut self) -> Option<Self::Item> {
 
         // Advance to next image (aligned to 512 bytes).
         self.current_offset += image_size;
-        self.current_offset = self.current_offset.align_up(Alignment::new::<512>())?;
+        self.current_offset = self.current_offset.align_up(Alignment::SZ_512)?;
 
         Some(Ok(full_image))
     }
Signature · 2 lines
-- 
2.56.0
#14 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

In reply to Eliot Courtney
Quoted 7 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible.

How real capacity 0 became possible? Did we eventually find a use case for it? If not, it should not be possible, and the implementation should not explicitly handle that case.

Quoted 3 lines

This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

Not the grow_request only, I believe. I recall the discussion about panic on most operations on a 0-bit pool.

Quoted 64 lines
---
 rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +25 -5
index 92eeb7caa243..f77bd90325ff 100644
@@ -112,13 +112,8 @@ pub fn new() -> Self {
     }
 
     /// Constructs a new [`IdPool`] with space for a specific number of bits.
-    ///
-    /// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`].
-    ///
-    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     #[inline]
     pub fn with_capacity(num_ids: usize, flags: Flags) -> Result<Self, AllocError> {
-        let num_ids = usize::max(num_ids, BitmapVec::MAX_INLINE_LEN);
         let map = BitmapVec::new(num_ids, flags)?;
         Ok(Self { map })
     }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {
     /// let resizer = alloc_request.realloc(GFP_KERNEL)?;
     /// pool.shrink(resizer);
     /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further.
+    /// assert!(pool.shrink_request().is_none());
+    ///
+    /// // Neither can a pool with a capacity below `MAX_INLINE_LEN`.
+    /// let small = IdPool::with_capacity(8, GFP_KERNEL)?;
+    /// assert!(small.shrink_request().is_none());
     /// # Ok::<(), AllocError>(())
     /// ```
     #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {
 
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///

rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 232

Quoted 10 lines
rust/kernel/id_pool.rs +7 -1
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);

You only need this max(...) thing to fix the behavior of 0-len bitmap. We don't have any users with the request to support them. Please don't add any extra code to handle unwanted and unsupported cases.

Thanks,
Yury

Quoted 7 lines
rust/kernel/id_pool.rs +0 -0
         if num_ids > BitmapVec::MAX_LEN {
             return None;
         }
Signature · 2 lines
-- 
2.56.0
#15 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

Quoted 13 lines · Yury Norov
Quoted 7 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible.

How real capacity 0 became possible? Did we eventually find a use case for it? If not, it should not be possible, and the implementation should not explicitly handle that case.

Quoted 6 lines
Quoted 3 lines

This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

Not the grow_request only, I believe. I recall the discussion about panic on most operations on a 0-bit pool.

You have panics on most operations of a pool of any size if accessed out of bounds. Zero size is not special.

Quoted 71 lines
Quoted 71 lines
---
 rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +31 -5
index 92eeb7caa243..f77bd90325ff 100644
@@ -112,13 +112,8 @@ pub fn new() -> Self {
     }
 
     /// Constructs a new [`IdPool`] with space for a specific number of bits.
-    ///
-    /// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`].
-    ///
-    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     #[inline]
     pub fn with_capacity(num_ids: usize, flags: Flags) -> Result<Self, AllocError> {
-        let num_ids = usize::max(num_ids, BitmapVec::MAX_INLINE_LEN);
         let map = BitmapVec::new(num_ids, flags)?;
         Ok(Self { map })
     }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {
     /// let resizer = alloc_request.realloc(GFP_KERNEL)?;
     /// pool.shrink(resizer);
     /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further.
+    /// assert!(pool.shrink_request().is_none());
+    ///
+    /// // Neither can a pool with a capacity below `MAX_INLINE_LEN`.
+    /// let small = IdPool::with_capacity(8, GFP_KERNEL)?;
+    /// assert!(small.shrink_request().is_none());
     /// # Ok::<(), AllocError>(())
     /// ```
     #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {
 
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
Quoted 8 lines

rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 232

Quoted 4 lines
rust/kernel/id_pool.rs +1 -1
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);

You only need this max(...) thing to fix the behavior of 0-len bitmap. We don't have any users with the request to support them. Please don't add any extra code to handle unwanted and unsupported cases.

No, this code is a side-effect of the pool not being rounded up to MAX_INLINE_LEN (note how the max moved from `with_capacity). It would still be there even if we did not support zero-size.

Forbidding zero-sized pools would actually require *more* code in this patch to enforce that rule, and would not allow us to remove any in exchange afaict.

#16 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

Quoted 104 lines · Alexandre Courbot
Quoted 13 lines · Yury Norov
Quoted 7 lines · Eliot Courtney

Current code in IdPool::with_capacity rounds the capacity up to BitmapVec::MAX_INLINE_LEN, but BitmapVec::new works fine with values smaller than this and still uses an inline representation. Remove this behaviour.

This allows specifying a real capacity of 0, which was not previously possible.

How real capacity 0 became possible? Did we eventually find a use case for it? If not, it should not be possible, and the implementation should not explicitly handle that case.

Quoted 6 lines
Quoted 3 lines

This breaks grow_request in this case, so change it to grow to at least BitmapVec::MAX_INLINE_LEN, mirroring the capacity floor in shrink_request.

Not the grow_request only, I believe. I recall the discussion about panic on most operations on a 0-bit pool.

You have panics on most operations of a pool of any size if accessed out of bounds. Zero size is not special.

Quoted 71 lines
Quoted 71 lines
---
 rust/kernel/id_pool.rs | 38 ++++++++++++++++++++++++++++++++------
 1 file changed, 32 insertions(+), 6 deletions(-)
rust/kernel/id_pool.rs +31 -5
index 92eeb7caa243..f77bd90325ff 100644
@@ -112,13 +112,8 @@ pub fn new() -> Self {
     }
 
     /// Constructs a new [`IdPool`] with space for a specific number of bits.
-    ///
-    /// A capacity below [`MAX_INLINE_LEN`] is adjusted to [`MAX_INLINE_LEN`].
-    ///
-    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     #[inline]
     pub fn with_capacity(num_ids: usize, flags: Flags) -> Result<Self, AllocError> {
-        let num_ids = usize::max(num_ids, BitmapVec::MAX_INLINE_LEN);
         let map = BitmapVec::new(num_ids, flags)?;
         Ok(Self { map })
     }
@@ -152,6 +147,13 @@ pub fn capacity(&self) -> usize {
     /// let resizer = alloc_request.realloc(GFP_KERNEL)?;
     /// pool.shrink(resizer);
     /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // A pool at the `MAX_INLINE_LEN` floor cannot shrink further.
+    /// assert!(pool.shrink_request().is_none());
+    ///
+    /// // Neither can a pool with a capacity below `MAX_INLINE_LEN`.
+    /// let small = IdPool::with_capacity(8, GFP_KERNEL)?;
+    /// assert!(small.shrink_request().is_none());
     /// # Ok::<(), AllocError>(())
     /// ```
     #[inline]
@@ -198,12 +200,36 @@ pub fn shrink(&mut self, mut resizer: PoolResizer) {
 
     /// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible.
     ///
+    /// Grows to at least [`MAX_INLINE_LEN`].
     /// The capacity of an [`IdPool`] cannot be grown above [`MAX_LEN`].
     ///
+    /// [`MAX_INLINE_LEN`]: BitmapVec::MAX_INLINE_LEN
     /// [`MAX_LEN`]: BitmapVec::MAX_LEN
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     alloc::AllocError,
+    ///     bitmap::BitmapVec,
+    ///     id_pool::IdPool, //
+    /// };
+    ///
+    /// // Grow goes to at least BitmapVec::MAX_INLINE_LEN.
+    /// let mut pool = IdPool::with_capacity(1, GFP_KERNEL)?;
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), BitmapVec::MAX_INLINE_LEN);
+    ///
+    /// // Grow doubles if at least BitmapVec::MAX_INLINE_LEN.
+    /// let resizer = pool.grow_request().ok_or(AllocError)?.realloc(GFP_KERNEL)?;
+    /// pool.grow(resizer);
+    /// assert_eq!(pool.capacity(), 2 * BitmapVec::MAX_INLINE_LEN);
+    /// # Ok::<(), AllocError>(())
+    /// ```
Quoted 8 lines

rust/kernel/id_pool.rs pub fn shrink(&mut self, mut resizer: PoolResizer) { · line 232

Quoted 4 lines
rust/kernel/id_pool.rs +1 -1
     #[inline]
     pub fn grow_request(&self) -> Option<ReallocRequest> {
-        let num_ids = self.capacity() * 2;
+        let num_ids = usize::max(BitmapVec::MAX_INLINE_LEN, self.capacity() * 2);

You only need this max(...) thing to fix the behavior of 0-len bitmap. We don't have any users with the request to support them. Please don't add any extra code to handle unwanted and unsupported cases.

Quoted 3 lines

No, this code is a side-effect of the pool not being rounded up to MAX_INLINE_LEN (note how the max moved from `with_capacity). It would still be there even if we did not support zero-size.

The commit message says exactly opposite:

This allows specifying a real capacity of 0, which was not previously possible.

Eliot, can you reword please? We don't have a single use-case for 0-sized bitmap, nor in C, neither in rust. If your code handles such a bitmap correctly to some extend, it's purely accidentally, and nobody should rely on it.

Quoted 3 lines

Forbidding zero-sized pools would actually require *more* code in this patch to enforce that rule, and would not allow us to remove any in exchange afaict.

I trust you here. Maybe declaring nbits in the allocation API as NonZero would help - IDK... I just want to make sure we're not bloating the implementation for unneeded and confusing functionality.

Thanks,
Yury

#17 lore raw

Re: [PATCH v11 4/5] rust: id_pool: do not round capacity up to BitmapVec::MAX_INLINE_LEN

Quoted 7 lines · Yury Norov
Quoted 3 lines

Forbidding zero-sized pools would actually require *more* code in this patch to enforce that rule, and would not allow us to remove any in exchange afaict.

I trust you here. Maybe declaring nbits in the allocation API as NonZero would help - IDK... I just want to make sure we're not bloating the implementation for unneeded and confusing functionality.

I think the current code is pretty much as simple as we can make it for our use-case.

Of course we can always tune it and even update the API if we find out it doesn't work as well as we thought, or that allowing zero-sized pools create issues. But if we forbid them preemptively we would actually be adding more complexity, which makes me think the current approach looks right.