[PATCH v2] btrfs: fix use-after-free in mark_block_group_to_copy

From: Hongling Zeng

Date: Sun Aug 16 2026 - 23:35:52 EST


mark_block_group_to_copy() iterates over the commit root with
skip_locking=true. A concurrent transaction commit can swap and free
the commit root during iteration, causing use-after-free when
accessing extent buffers.

Fix by using path->need_commit_sem to protect the commit root search.

Fixes: 78ce9fc269af ("btrfs: zoned: mark block groups to copy for device-replace")
Cc: stable@xxxxxxxxxxxxxxx
Assisted-by: Codex:gpt-5.5
Signed-off-by: Hongling Zeng <zenghongling@xxxxxxxxxx>
Suggested-by: Qu Wenruo <wqu@xxxxxxxx>
---
- Use path->need_commit_sem instead of manual commit_root_sem locking
suggested by Qu Wenruo.
- Remove the unmatched manual up_read().
- Add LLM usage disclosure
---
fs/btrfs/dev-replace.c | 1 +
1 file changed, 1 insertion(+)

diff --git a/fs/btrfs/dev-replace.c b/fs/btrfs/dev-replace.c
index dc0834f920c3..0310aa3add54 100644
--- a/fs/btrfs/dev-replace.c
+++ b/fs/btrfs/dev-replace.c
@@ -494,6 +494,7 @@ static int mark_block_group_to_copy(struct btrfs_fs_info *fs_info,
path->reada = READA_FORWARD;
path->search_commit_root = true;
path->skip_locking = true;
+ path->need_commit_sem = true;

key.objectid = src_dev->devid;
key.type = BTRFS_DEV_EXTENT_KEY;
--
2.25.1