[PATCH] btrfs: zoned: fix use-after-free in btrfs_reset_unused_block_groups()

From: Shuangpeng Bai

Date: Sun Aug 02 2026 - 19:28:54 EST


btrfs_mark_bg_unused() takes a block group reference when adding it to
unused_bgs. btrfs_reset_unused_block_groups() removes a selected block
group from the list and immediately drops that reference before accessing
bg->physical_map and updating the block group.

A concurrent unused block group deletion can then drop the remaining
references and free both bg and its physical_map, resulting in a
use-after-free.

Keep the unused_bgs reference as a local processing reference after
removing the block group from the list, and drop it only after the zone
reset and block group update have finished. Also release it on the error
and read-only paths.

Fixes: 453a73c3069a ("btrfs: zoned: reclaim unused zone by zone resetting")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Shuangpeng Bai <shuangpeng.kernel@xxxxxxxxx>
---
fs/btrfs/zoned.c | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/fs/btrfs/zoned.c b/fs/btrfs/zoned.c
index a016cb471beb..e30b6a61c781 100644
--- a/fs/btrfs/zoned.c
+++ b/fs/btrfs/zoned.c
@@ -3158,7 +3158,6 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num
}

list_del_init(&bg->bg_list);
- btrfs_put_block_group(bg);
spin_unlock(&fs_info->unused_bgs_lock);

/*
@@ -3182,6 +3181,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num

if (ret) {
up_read(&fs_info->dev_replace.rwsem);
+ btrfs_put_block_group(bg);
return ret;
}
}
@@ -3193,6 +3193,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num
if (bg->ro) {
spin_unlock(&bg->lock);
spin_unlock(&space_info->lock);
+ btrfs_put_block_group(bg);
continue;
}

@@ -3221,6 +3222,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num
spin_unlock(&bg->lock);
btrfs_return_free_space(space_info, reclaimed);
spin_unlock(&space_info->lock);
+ btrfs_put_block_group(bg);

if (num_bytes <= reclaimed)
break;
--
2.43.0