[PATCH v3 2/3] block: rust: add `discard_granularity` option to `GenDiskBuilder`

From: Vitaly Wool

Date: Fri Dec 04 2026 - 06:43:46 EST


From: Igor Belousov <igor.b@xxxxxxxxx>

Allow Rust block drivers to set the discard granularity of their disks.
It defaults to the physical block size, which is too small for drivers
that can only deallocate larger units: the block layer splits discards
larger than the maximum discard size at multiples of the granularity,
so with a granularity smaller than the driver's unit, a split can fall
in the middle of a unit that neither part then covers in full.

Signed-off-by: Igor Belousov <igor.b@xxxxxxxxx>
Signed-off-by: Vitaly Wool <vitaly.wool@xxxxxxxxxxx>
---
rust/kernel/block/mq/gen_disk.rs | 13 +++++++++++++
1 file changed, 13 insertions(+)

diff --git a/rust/kernel/block/mq/gen_disk.rs b/rust/kernel/block/mq/gen_disk.rs
index 6c25b86558f4..a6480dbf603e 100644
--- a/rust/kernel/block/mq/gen_disk.rs
+++ b/rust/kernel/block/mq/gen_disk.rs
@@ -50,6 +50,7 @@ pub struct GenDiskBuilder<T> {
physical_block_size: u32,
capacity_sectors: u64,
max_hw_discard_sectors: u32,
+ discard_granularity: u32,
#[cfg(CONFIG_BLK_DEV_ZONED)]
zoned: bool,
#[cfg(CONFIG_BLK_DEV_ZONED)]
@@ -72,6 +73,7 @@ fn default() -> Self {
physical_block_size: bindings::PAGE_SIZE as u32,
capacity_sectors: 0,
max_hw_discard_sectors: 0,
+ discard_granularity: 0,
#[cfg(CONFIG_BLK_DEV_ZONED)]
zoned: false,
#[cfg(CONFIG_BLK_DEV_ZONED)]
@@ -154,6 +156,16 @@ pub fn max_hw_discard_sectors(mut self, max_hw_discard_sectors: u32) -> Self {
self
}

+ /// Set the discard granularity of the device to be built, in bytes: the
+ /// smallest unit the device can deallocate. The block layer splits large
+ /// discards at multiples of it.
+ ///
+ /// Setting 0 (default) here makes it the physical block size.
+ pub fn discard_granularity(mut self, granularity: u32) -> Self {
+ self.discard_granularity = granularity;
+ self
+ }
+
/// Mark this device as a zoned block device.
#[cfg(CONFIG_BLK_DEV_ZONED)]
pub fn zoned(mut self, enable: bool) -> Self {
@@ -226,6 +238,7 @@ pub fn build(
lim.logical_block_size = self.logical_block_size;
lim.physical_block_size = self.physical_block_size;
lim.max_hw_discard_sectors = self.max_hw_discard_sectors;
+ lim.discard_granularity = self.discard_granularity;
lim.max_sectors = self.max_sectors;
lim.virt_boundary_mask = self.virt_boundary_mask;
lim.dma_alignment = self.dma_alignment;
--
2.39.5