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
9f618b59ff51ccefadc45c66ab4e88beffacf2be)
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;