Skip to contentSkip to conversation

btrfs: wait for RCU readers before freeing a new device

PATCH New Mai Hai Son 1 participant 1 message Sep 5 Btrfs file system

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 btrfs: wait for RCU readers before freeing a new device

btrfs_init_new_device() adds the new device to the RCU-protected fs_devices->devices list before completing the device-add operation. If a later step fails, error_sysfs removes the device with list_del_rcu() and then frees it without waiting for an RCU grace period.

A concurrent reader such as btrfs_ioctl_dev_info() may still hold the device pointer it obtained under rcu_read_lock() and dereference it after btrfs_free_device() has already freed it, triggering a KASAN slab-use-after-free report:

  BUG: KASAN: slab-use-after-free in btrfs_ioctl+0x58e4/0x5d40
  Read of size 8 at addr ffff8881176fa870 by task poc/84
  Call Trace:
   kasan_report+0xe4/0x1a0
   btrfs_ioctl+0x58e4/0x5d40
   __x64_sys_ioctl+0x121/0x1a0
   do_syscall_64+0xf7/0x5a0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  Allocated by task 81:
   btrfs_alloc_device+0xb0/0x3e0
   btrfs_init_new_device+0x4b2/0x3660
   btrfs_ioctl_add_dev+0x179/0x430
   btrfs_ioctl+0x11e0/0x5d40

  Freed by task 81:
   kfree+0x1b8/0x550
   btrfs_init_new_device+0x56b/0x3660
   btrfs_ioctl_add_dev+0x179/0x430
   btrfs_ioctl+0x11e0/0x5d40

Wait for an RCU grace period after removing the device from the list and before freeing it.

Fixes 39379faaad79 ("btrfs: revert fs_devices state on error of btrfs_init_new_device")
Assisted-by Codex:gpt-5.6
Assisted-by Claude:claude-opus-4-8
---
 fs/btrfs/volumes.c | 1 +
 1 file changed, 1 insertion(+)
fs/btrfs/volumes.c +1 -0
index 9b66eb584..af59291b7 100644
@@ -3133,6 +3133,7 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 	btrfs_update_per_profile_avail(fs_info);
 	mutex_unlock(&fs_info->chunk_mutex);
 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
+	synchronize_rcu();
 error_trans:
 	if (trans)
 		btrfs_end_transaction(trans);

base-commit: 4d7d9486c04d917265f64c55bd23b2cc4fe7749c