fs_info->fs_devices->latest_bdev = next_device->bdev;
 }
 
+/*
+ * Return btrfs_fs_devices::num_devices excluding the device that's being
+ * currently replaced.
+ */
+static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
+{
+       u64 num_devices = fs_info->fs_devices->num_devices;
+
+       btrfs_dev_replace_read_lock(&fs_info->dev_replace);
+       if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
+               ASSERT(num_devices > 1);
+               num_devices--;
+       }
+       btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
+
+       return num_devices;
+}
+
 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
                u64 devid)
 {
 
        mutex_lock(&uuid_mutex);
 
-       num_devices = fs_devices->num_devices;
-       btrfs_dev_replace_read_lock(&fs_info->dev_replace);
-       if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
-               ASSERT(num_devices > 1);
-               num_devices--;
-       }
-       btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
+       num_devices = btrfs_num_devices(fs_info);
 
        ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
        if (ret)
                }
        }
 
-       num_devices = fs_info->fs_devices->num_devices;
-       btrfs_dev_replace_read_lock(&fs_info->dev_replace);
-       if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
-               ASSERT(num_devices > 1);
-               num_devices--;
-       }
-       btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
+       num_devices = btrfs_num_devices(fs_info);
+
        allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
        if (num_devices > 1)
                allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);