Skip to content

Commit 057495c

Browse files
maharmstonekdave
authored andcommitted
btrfs: hold block group reference during entire move_existing_remap()
There is a potential use-after-free in move_existing_remap(): we're calling btrfs_put_block_group() on dest_bg, then passing it to btrfs_add_block_group_free_space() a few lines later. Fix this by getting the BG at the start of the function and putting it near the end. This also means we're not doing a lookup twice for the same thing. Reported-by: Chris Mason <clm@fb.com> Link: https://lore.kernel.org/linux-btrfs/20260125123908.2096548-1-clm@meta.com/ Fixes: bbea42d ("btrfs: move existing remaps before relocating block group") Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com> Signed-off-by: Mark Harmstone <mark@harmstone.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
1 parent 5118130 commit 057495c

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

fs/btrfs/relocation.c

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4185,6 +4185,8 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
41854185
dest_addr = ins.objectid;
41864186
dest_length = ins.offset;
41874187

4188+
dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
4189+
41884190
if (!is_data && !IS_ALIGNED(dest_length, fs_info->nodesize)) {
41894191
u64 new_length = ALIGN_DOWN(dest_length, fs_info->nodesize);
41904192

@@ -4295,15 +4297,12 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
42954297
if (unlikely(ret))
42964298
goto end;
42974299

4298-
dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
4299-
43004300
adjust_block_group_remap_bytes(trans, dest_bg, dest_length);
43014301

43024302
mutex_lock(&dest_bg->free_space_lock);
43034303
bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
43044304
&dest_bg->runtime_flags);
43054305
mutex_unlock(&dest_bg->free_space_lock);
4306-
btrfs_put_block_group(dest_bg);
43074306

43084307
if (bg_needs_free_space) {
43094308
ret = btrfs_add_block_group_free_space(trans, dest_bg);
@@ -4333,13 +4332,13 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
43334332
btrfs_end_transaction(trans);
43344333
}
43354334
} else {
4336-
dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
43374335
btrfs_free_reserved_bytes(dest_bg, dest_length, 0);
4338-
btrfs_put_block_group(dest_bg);
43394336

43404337
ret = btrfs_commit_transaction(trans);
43414338
}
43424339

4340+
btrfs_put_block_group(dest_bg);
4341+
43434342
return ret;
43444343
}
43454344

0 commit comments

Comments
 (0)