[PATCH] btrfs: Split remaining space to discard in chunks

From: Luca Stefani
Date: Mon Sep 02 2024 - 07:43:31 EST


Per Qu Wenruo in case we have a very large disk, e.g. 8TiB device,
mostly empty although we will do the split according to our super block
locations, the last super block ends at 256G, we can submit a huge
discard for the range [256G, 8T), causing a super large delay.

We now split the space left to discard based off the max data
chunk size (10G) to solve the problem.

Reported-by: Qu Wenruo <quwenruo.btrfs@xxxxxxx>
Closes: https://lore.kernel.org/lkml/2e15214b-7e95-4e64-a899-725de12c9037@xxxxxxxxx/T/#mdfef1d8b36334a15c54cd009f6aadf49e260e105
Signed-off-by: Luca Stefani <luca.stefani.ge1@xxxxxxxxx>
---
fs/btrfs/extent-tree.c | 20 ++++++++++++++++----
1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
index feec49e6f9c8..6ad92876bca0 100644
--- a/fs/btrfs/extent-tree.c
+++ b/fs/btrfs/extent-tree.c
@@ -1239,7 +1239,7 @@ static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
u64 *discarded_bytes)
{
int j, ret = 0;
- u64 bytes_left, end;
+ u64 bytes_left, bytes_to_discard, end;
u64 aligned_start = ALIGN(start, 1 << SECTOR_SHIFT);

/* Adjust the range to be aligned to 512B sectors if necessary. */
@@ -1300,13 +1300,25 @@ static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
bytes_left = end - start;
}

- if (bytes_left) {
+ while (bytes_left) {
+ if (bytes_left > BTRFS_MAX_DATA_CHUNK_SIZE)
+ bytes_to_discard = BTRFS_MAX_DATA_CHUNK_SIZE;
+ else
+ bytes_to_discard = bytes_left;
+
ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
- bytes_left >> SECTOR_SHIFT,
+ bytes_to_discard >> SECTOR_SHIFT,
GFP_NOFS);
+
if (!ret)
- *discarded_bytes += bytes_left;
+ *discarded_bytes += bytes_to_discard;
+ else if (ret != -EOPNOTSUPP)
+ return ret;
+
+ start += bytes_to_discard;
+ bytes_left -= bytes_to_discard;
}
+
return ret;
}

--
2.46.0