]> git.hungrycats.org Git - linux/commitdiff
btrfs: scrub: fix race leading to use-after-free in the scrub progress ioctl
authorFilipe Manana <fdmanana@suse.com>
Fri, 16 Oct 2026 16:53:00 +0000 (17:53 +0100)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Thu, 5 Nov 2026 04:21:56 +0000 (23:21 -0500)
If the scrub progress ioctl is called when replace is about to finish, we
have a race that can result in a use-after-free of the scrub context:

1) A scrub is finishing and is at btrfs_scrub_dev();

2) A concurrent task called the scrub progress ioctl and is in
   btrfs_scrub_progress(), where it takes the device_list_mutex and grabs
   the device. Then it starts using the device's scrub context (for a
   memcpy operation);

3) While the scrub progress ioctl task is running, the scrub task sets
   the device's scrub_ctx to NULL (acquiring fs_info->scrub_lock) and
   then calls scrub_put_ctx() against the scrub context, dropping the
   last reference and freeing the memory - while the scrub progress ioctl
   task is still using it, resulting in a use-after-free.

Fix this by changing btrfs_scrub_progress() to take fs_info->scrub_lock
before using the scrub context.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
(cherry picked from btrfs for-next commit cc1369667c11b1161ce6a09b9fd1b7680986d64b)

fs/btrfs/scrub.c

index a924eeb7a6618bf0b06257da150e69599709665f..9c43abbd1de4f281851873e0d0cddc5f8255bfb0 100644 (file)
@@ -3298,10 +3298,13 @@ int btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid,
 
        mutex_lock(&fs_info->fs_devices->device_list_mutex);
        dev = btrfs_find_device(fs_info->fs_devices, &args);
-       if (dev)
+       if (dev) {
+               mutex_lock(&fs_info->scrub_lock);
                sctx = dev->scrub_ctx;
-       if (sctx)
-               memcpy(progress, &sctx->stat, sizeof(*progress));
+               if (sctx)
+                       memcpy(progress, &sctx->stat, sizeof(*progress));
+               mutex_unlock(&fs_info->scrub_lock);
+       }
        mutex_unlock(&fs_info->fs_devices->device_list_mutex);
 
        return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV;