[PATCH 5/6] btrfs: retry a block group that references survive the update stage

From: Ismael Luceno

Date: Sun Nov 29 2026 - 08:40:41 EST


A reference added during the update stage can survive it. Its bytes were
not moved, and the block group keeps used bytes. Failing the balance
right away is safe, since the chunk is kept, but it throws away the work
already done for a case that is rare.

Move the leftover bytes again instead. The pass runs with a fresh data
reloc inode, because the mappings of the first pass are keyed by the same
logical offsets. Up to RELOC_MAX_LEFTOVER_PASSES extra passes are made.
If the block group still has used bytes after them, it is kept and the
balance fails with -EUCLEAN, with an error message naming the block group.

Signed-off-by: Ismael Luceno <ismael@xxxxxxxxxxx>
---
fs/btrfs/relocation.c | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)

diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index 75300c21fe06e..9bf0f9bc794c4 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
@@ -5751,6 +5751,9 @@ static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
/*
* function to relocate all extents in a block group.
*/
+/* Extra passes over a block group that a reference left behind. */
+#define RELOC_MAX_LEFTOVER_PASSES 3
+
int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
bool verbose)
{
@@ -5873,7 +5876,30 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,

btrfs_delete_unused_bgs(fs_info);
} else {
+ unsigned int pass = 0;
+
ret = do_nonremap_reloc(fs_info, verbose, rc);
+ /*
+ * A reference added during the update stage can survive it. Its
+ * bytes were not moved, so move what is left again with a fresh
+ * data inode. Only this rare case pays for another pass.
+ */
+ while (ret == -EUCLEAN && pass++ < RELOC_MAX_LEFTOVER_PASSES) {
+ iput(rc->data_inode);
+ rc->data_inode = create_reloc_inode(rc->block_group);
+ if (IS_ERR(rc->data_inode)) {
+ ret = PTR_ERR(rc->data_inode);
+ rc->data_inode = NULL;
+ break;
+ }
+ rc->stage = MOVE_DATA_EXTENTS;
+ rc->found_file_extent = false;
+ ret = do_nonremap_reloc(fs_info, verbose, rc);
+ }
+ if (ret == -EUCLEAN)
+ btrfs_err(fs_info,
+ "block group %llu kept: references still point into it after %d passes",
+ rc->block_group->start, RELOC_MAX_LEFTOVER_PASSES + 1);
}

out:
--
2.56.0