Skip to contentSkip to conversation

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

PATCH New Shuangpeng Bai 1 participant 1 message Aug 2

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 btrfs: zoned: fix use-after-free in btrfs_reset_unused_block_groups()

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")
---
 fs/btrfs/zoned.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/btrfs/zoned.c +3 -1
index a016cb471beb..e30b6a61c781 100644
@@ -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;
Signature · 1 line
2.43.0