Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Copyright (C) STRATO AG 2012.  All rights reserved.
0004  */
0005 
0006 #include <linux/sched.h>
0007 #include <linux/bio.h>
0008 #include <linux/slab.h>
0009 #include <linux/blkdev.h>
0010 #include <linux/kthread.h>
0011 #include <linux/math64.h>
0012 #include "misc.h"
0013 #include "ctree.h"
0014 #include "extent_map.h"
0015 #include "disk-io.h"
0016 #include "transaction.h"
0017 #include "print-tree.h"
0018 #include "volumes.h"
0019 #include "async-thread.h"
0020 #include "check-integrity.h"
0021 #include "rcu-string.h"
0022 #include "dev-replace.h"
0023 #include "sysfs.h"
0024 #include "zoned.h"
0025 #include "block-group.h"
0026 
0027 /*
0028  * Device replace overview
0029  *
0030  * [Objective]
0031  * To copy all extents (both new and on-disk) from source device to target
0032  * device, while still keeping the filesystem read-write.
0033  *
0034  * [Method]
0035  * There are two main methods involved:
0036  *
0037  * - Write duplication
0038  *
0039  *   All new writes will be written to both target and source devices, so even
0040  *   if replace gets canceled, sources device still contains up-to-date data.
0041  *
0042  *   Location:      handle_ops_on_dev_replace() from __btrfs_map_block()
0043  *   Start:     btrfs_dev_replace_start()
0044  *   End:       btrfs_dev_replace_finishing()
0045  *   Content:       Latest data/metadata
0046  *
0047  * - Copy existing extents
0048  *
0049  *   This happens by re-using scrub facility, as scrub also iterates through
0050  *   existing extents from commit root.
0051  *
0052  *   Location:      scrub_write_block_to_dev_replace() from
0053  *              scrub_block_complete()
0054  *   Content:       Data/meta from commit root.
0055  *
0056  * Due to the content difference, we need to avoid nocow write when dev-replace
0057  * is happening.  This is done by marking the block group read-only and waiting
0058  * for NOCOW writes.
0059  *
0060  * After replace is done, the finishing part is done by swapping the target and
0061  * source devices.
0062  *
0063  *   Location:      btrfs_dev_replace_update_device_in_mapping_tree() from
0064  *              btrfs_dev_replace_finishing()
0065  */
0066 
0067 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
0068                        int scrub_ret);
0069 static int btrfs_dev_replace_kthread(void *data);
0070 
0071 int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
0072 {
0073     struct btrfs_dev_lookup_args args = { .devid = BTRFS_DEV_REPLACE_DEVID };
0074     struct btrfs_key key;
0075     struct btrfs_root *dev_root = fs_info->dev_root;
0076     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
0077     struct extent_buffer *eb;
0078     int slot;
0079     int ret = 0;
0080     struct btrfs_path *path = NULL;
0081     int item_size;
0082     struct btrfs_dev_replace_item *ptr;
0083     u64 src_devid;
0084 
0085     if (!dev_root)
0086         return 0;
0087 
0088     path = btrfs_alloc_path();
0089     if (!path) {
0090         ret = -ENOMEM;
0091         goto out;
0092     }
0093 
0094     key.objectid = 0;
0095     key.type = BTRFS_DEV_REPLACE_KEY;
0096     key.offset = 0;
0097     ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
0098     if (ret) {
0099 no_valid_dev_replace_entry_found:
0100         /*
0101          * We don't have a replace item or it's corrupted.  If there is
0102          * a replace target, fail the mount.
0103          */
0104         if (btrfs_find_device(fs_info->fs_devices, &args)) {
0105             btrfs_err(fs_info,
0106             "found replace target device without a valid replace item");
0107             ret = -EUCLEAN;
0108             goto out;
0109         }
0110         ret = 0;
0111         dev_replace->replace_state =
0112             BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
0113         dev_replace->cont_reading_from_srcdev_mode =
0114             BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
0115         dev_replace->time_started = 0;
0116         dev_replace->time_stopped = 0;
0117         atomic64_set(&dev_replace->num_write_errors, 0);
0118         atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
0119         dev_replace->cursor_left = 0;
0120         dev_replace->committed_cursor_left = 0;
0121         dev_replace->cursor_left_last_write_of_item = 0;
0122         dev_replace->cursor_right = 0;
0123         dev_replace->srcdev = NULL;
0124         dev_replace->tgtdev = NULL;
0125         dev_replace->is_valid = 0;
0126         dev_replace->item_needs_writeback = 0;
0127         goto out;
0128     }
0129     slot = path->slots[0];
0130     eb = path->nodes[0];
0131     item_size = btrfs_item_size(eb, slot);
0132     ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item);
0133 
0134     if (item_size != sizeof(struct btrfs_dev_replace_item)) {
0135         btrfs_warn(fs_info,
0136             "dev_replace entry found has unexpected size, ignore entry");
0137         goto no_valid_dev_replace_entry_found;
0138     }
0139 
0140     src_devid = btrfs_dev_replace_src_devid(eb, ptr);
0141     dev_replace->cont_reading_from_srcdev_mode =
0142         btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
0143     dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
0144     dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
0145     dev_replace->time_stopped =
0146         btrfs_dev_replace_time_stopped(eb, ptr);
0147     atomic64_set(&dev_replace->num_write_errors,
0148              btrfs_dev_replace_num_write_errors(eb, ptr));
0149     atomic64_set(&dev_replace->num_uncorrectable_read_errors,
0150              btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr));
0151     dev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr);
0152     dev_replace->committed_cursor_left = dev_replace->cursor_left;
0153     dev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left;
0154     dev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr);
0155     dev_replace->is_valid = 1;
0156 
0157     dev_replace->item_needs_writeback = 0;
0158     switch (dev_replace->replace_state) {
0159     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
0160     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
0161     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
0162         /*
0163          * We don't have an active replace item but if there is a
0164          * replace target, fail the mount.
0165          */
0166         if (btrfs_find_device(fs_info->fs_devices, &args)) {
0167             btrfs_err(fs_info,
0168 "replace without active item, run 'device scan --forget' on the target device");
0169             ret = -EUCLEAN;
0170         } else {
0171             dev_replace->srcdev = NULL;
0172             dev_replace->tgtdev = NULL;
0173         }
0174         break;
0175     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
0176     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
0177         dev_replace->tgtdev = btrfs_find_device(fs_info->fs_devices, &args);
0178         args.devid = src_devid;
0179         dev_replace->srcdev = btrfs_find_device(fs_info->fs_devices, &args);
0180 
0181         /*
0182          * allow 'btrfs dev replace_cancel' if src/tgt device is
0183          * missing
0184          */
0185         if (!dev_replace->srcdev &&
0186             !btrfs_test_opt(fs_info, DEGRADED)) {
0187             ret = -EIO;
0188             btrfs_warn(fs_info,
0189                "cannot mount because device replace operation is ongoing and");
0190             btrfs_warn(fs_info,
0191                "srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
0192                src_devid);
0193         }
0194         if (!dev_replace->tgtdev &&
0195             !btrfs_test_opt(fs_info, DEGRADED)) {
0196             ret = -EIO;
0197             btrfs_warn(fs_info,
0198                "cannot mount because device replace operation is ongoing and");
0199             btrfs_warn(fs_info,
0200                "tgtdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
0201                 BTRFS_DEV_REPLACE_DEVID);
0202         }
0203         if (dev_replace->tgtdev) {
0204             if (dev_replace->srcdev) {
0205                 dev_replace->tgtdev->total_bytes =
0206                     dev_replace->srcdev->total_bytes;
0207                 dev_replace->tgtdev->disk_total_bytes =
0208                     dev_replace->srcdev->disk_total_bytes;
0209                 dev_replace->tgtdev->commit_total_bytes =
0210                     dev_replace->srcdev->commit_total_bytes;
0211                 dev_replace->tgtdev->bytes_used =
0212                     dev_replace->srcdev->bytes_used;
0213                 dev_replace->tgtdev->commit_bytes_used =
0214                     dev_replace->srcdev->commit_bytes_used;
0215             }
0216             set_bit(BTRFS_DEV_STATE_REPLACE_TGT,
0217                 &dev_replace->tgtdev->dev_state);
0218 
0219             WARN_ON(fs_info->fs_devices->rw_devices == 0);
0220             dev_replace->tgtdev->io_width = fs_info->sectorsize;
0221             dev_replace->tgtdev->io_align = fs_info->sectorsize;
0222             dev_replace->tgtdev->sector_size = fs_info->sectorsize;
0223             dev_replace->tgtdev->fs_info = fs_info;
0224             set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
0225                 &dev_replace->tgtdev->dev_state);
0226         }
0227         break;
0228     }
0229 
0230 out:
0231     btrfs_free_path(path);
0232     return ret;
0233 }
0234 
0235 /*
0236  * Initialize a new device for device replace target from a given source dev
0237  * and path.
0238  *
0239  * Return 0 and new device in @device_out, otherwise return < 0
0240  */
0241 static int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
0242                   const char *device_path,
0243                   struct btrfs_device *srcdev,
0244                   struct btrfs_device **device_out)
0245 {
0246     struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
0247     struct btrfs_device *device;
0248     struct block_device *bdev;
0249     struct rcu_string *name;
0250     u64 devid = BTRFS_DEV_REPLACE_DEVID;
0251     int ret = 0;
0252 
0253     *device_out = NULL;
0254     if (srcdev->fs_devices->seeding) {
0255         btrfs_err(fs_info, "the filesystem is a seed filesystem!");
0256         return -EINVAL;
0257     }
0258 
0259     bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
0260                   fs_info->bdev_holder);
0261     if (IS_ERR(bdev)) {
0262         btrfs_err(fs_info, "target device %s is invalid!", device_path);
0263         return PTR_ERR(bdev);
0264     }
0265 
0266     if (!btrfs_check_device_zone_type(fs_info, bdev)) {
0267         btrfs_err(fs_info,
0268         "dev-replace: zoned type of target device mismatch with filesystem");
0269         ret = -EINVAL;
0270         goto error;
0271     }
0272 
0273     sync_blockdev(bdev);
0274 
0275     list_for_each_entry(device, &fs_devices->devices, dev_list) {
0276         if (device->bdev == bdev) {
0277             btrfs_err(fs_info,
0278                   "target device is in the filesystem!");
0279             ret = -EEXIST;
0280             goto error;
0281         }
0282     }
0283 
0284 
0285     if (bdev_nr_bytes(bdev) < btrfs_device_get_total_bytes(srcdev)) {
0286         btrfs_err(fs_info,
0287               "target device is smaller than source device!");
0288         ret = -EINVAL;
0289         goto error;
0290     }
0291 
0292 
0293     device = btrfs_alloc_device(NULL, &devid, NULL);
0294     if (IS_ERR(device)) {
0295         ret = PTR_ERR(device);
0296         goto error;
0297     }
0298 
0299     name = rcu_string_strdup(device_path, GFP_KERNEL);
0300     if (!name) {
0301         btrfs_free_device(device);
0302         ret = -ENOMEM;
0303         goto error;
0304     }
0305     rcu_assign_pointer(device->name, name);
0306     ret = lookup_bdev(device_path, &device->devt);
0307     if (ret)
0308         goto error;
0309 
0310     set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
0311     device->generation = 0;
0312     device->io_width = fs_info->sectorsize;
0313     device->io_align = fs_info->sectorsize;
0314     device->sector_size = fs_info->sectorsize;
0315     device->total_bytes = btrfs_device_get_total_bytes(srcdev);
0316     device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
0317     device->bytes_used = btrfs_device_get_bytes_used(srcdev);
0318     device->commit_total_bytes = srcdev->commit_total_bytes;
0319     device->commit_bytes_used = device->bytes_used;
0320     device->fs_info = fs_info;
0321     device->bdev = bdev;
0322     set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
0323     set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
0324     device->mode = FMODE_EXCL;
0325     device->dev_stats_valid = 1;
0326     set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
0327     device->fs_devices = fs_devices;
0328 
0329     ret = btrfs_get_dev_zone_info(device, false);
0330     if (ret)
0331         goto error;
0332 
0333     mutex_lock(&fs_devices->device_list_mutex);
0334     list_add(&device->dev_list, &fs_devices->devices);
0335     fs_devices->num_devices++;
0336     fs_devices->open_devices++;
0337     mutex_unlock(&fs_devices->device_list_mutex);
0338 
0339     *device_out = device;
0340     return 0;
0341 
0342 error:
0343     blkdev_put(bdev, FMODE_EXCL);
0344     return ret;
0345 }
0346 
0347 /*
0348  * called from commit_transaction. Writes changed device replace state to
0349  * disk.
0350  */
0351 int btrfs_run_dev_replace(struct btrfs_trans_handle *trans)
0352 {
0353     struct btrfs_fs_info *fs_info = trans->fs_info;
0354     int ret;
0355     struct btrfs_root *dev_root = fs_info->dev_root;
0356     struct btrfs_path *path;
0357     struct btrfs_key key;
0358     struct extent_buffer *eb;
0359     struct btrfs_dev_replace_item *ptr;
0360     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
0361 
0362     down_read(&dev_replace->rwsem);
0363     if (!dev_replace->is_valid ||
0364         !dev_replace->item_needs_writeback) {
0365         up_read(&dev_replace->rwsem);
0366         return 0;
0367     }
0368     up_read(&dev_replace->rwsem);
0369 
0370     key.objectid = 0;
0371     key.type = BTRFS_DEV_REPLACE_KEY;
0372     key.offset = 0;
0373 
0374     path = btrfs_alloc_path();
0375     if (!path) {
0376         ret = -ENOMEM;
0377         goto out;
0378     }
0379     ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
0380     if (ret < 0) {
0381         btrfs_warn(fs_info,
0382                "error %d while searching for dev_replace item!",
0383                ret);
0384         goto out;
0385     }
0386 
0387     if (ret == 0 &&
0388         btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
0389         /*
0390          * need to delete old one and insert a new one.
0391          * Since no attempt is made to recover any old state, if the
0392          * dev_replace state is 'running', the data on the target
0393          * drive is lost.
0394          * It would be possible to recover the state: just make sure
0395          * that the beginning of the item is never changed and always
0396          * contains all the essential information. Then read this
0397          * minimal set of information and use it as a base for the
0398          * new state.
0399          */
0400         ret = btrfs_del_item(trans, dev_root, path);
0401         if (ret != 0) {
0402             btrfs_warn(fs_info,
0403                    "delete too small dev_replace item failed %d!",
0404                    ret);
0405             goto out;
0406         }
0407         ret = 1;
0408     }
0409 
0410     if (ret == 1) {
0411         /* need to insert a new item */
0412         btrfs_release_path(path);
0413         ret = btrfs_insert_empty_item(trans, dev_root, path,
0414                           &key, sizeof(*ptr));
0415         if (ret < 0) {
0416             btrfs_warn(fs_info,
0417                    "insert dev_replace item failed %d!", ret);
0418             goto out;
0419         }
0420     }
0421 
0422     eb = path->nodes[0];
0423     ptr = btrfs_item_ptr(eb, path->slots[0],
0424                  struct btrfs_dev_replace_item);
0425 
0426     down_write(&dev_replace->rwsem);
0427     if (dev_replace->srcdev)
0428         btrfs_set_dev_replace_src_devid(eb, ptr,
0429             dev_replace->srcdev->devid);
0430     else
0431         btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
0432     btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
0433         dev_replace->cont_reading_from_srcdev_mode);
0434     btrfs_set_dev_replace_replace_state(eb, ptr,
0435         dev_replace->replace_state);
0436     btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
0437     btrfs_set_dev_replace_time_stopped(eb, ptr, dev_replace->time_stopped);
0438     btrfs_set_dev_replace_num_write_errors(eb, ptr,
0439         atomic64_read(&dev_replace->num_write_errors));
0440     btrfs_set_dev_replace_num_uncorrectable_read_errors(eb, ptr,
0441         atomic64_read(&dev_replace->num_uncorrectable_read_errors));
0442     dev_replace->cursor_left_last_write_of_item =
0443         dev_replace->cursor_left;
0444     btrfs_set_dev_replace_cursor_left(eb, ptr,
0445         dev_replace->cursor_left_last_write_of_item);
0446     btrfs_set_dev_replace_cursor_right(eb, ptr,
0447         dev_replace->cursor_right);
0448     dev_replace->item_needs_writeback = 0;
0449     up_write(&dev_replace->rwsem);
0450 
0451     btrfs_mark_buffer_dirty(eb);
0452 
0453 out:
0454     btrfs_free_path(path);
0455 
0456     return ret;
0457 }
0458 
0459 static char* btrfs_dev_name(struct btrfs_device *device)
0460 {
0461     if (!device || test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
0462         return "<missing disk>";
0463     else
0464         return rcu_str_deref(device->name);
0465 }
0466 
0467 static int mark_block_group_to_copy(struct btrfs_fs_info *fs_info,
0468                     struct btrfs_device *src_dev)
0469 {
0470     struct btrfs_path *path;
0471     struct btrfs_key key;
0472     struct btrfs_key found_key;
0473     struct btrfs_root *root = fs_info->dev_root;
0474     struct btrfs_dev_extent *dev_extent = NULL;
0475     struct btrfs_block_group *cache;
0476     struct btrfs_trans_handle *trans;
0477     int iter_ret = 0;
0478     int ret = 0;
0479     u64 chunk_offset;
0480 
0481     /* Do not use "to_copy" on non zoned filesystem for now */
0482     if (!btrfs_is_zoned(fs_info))
0483         return 0;
0484 
0485     mutex_lock(&fs_info->chunk_mutex);
0486 
0487     /* Ensure we don't have pending new block group */
0488     spin_lock(&fs_info->trans_lock);
0489     while (fs_info->running_transaction &&
0490            !list_empty(&fs_info->running_transaction->dev_update_list)) {
0491         spin_unlock(&fs_info->trans_lock);
0492         mutex_unlock(&fs_info->chunk_mutex);
0493         trans = btrfs_attach_transaction(root);
0494         if (IS_ERR(trans)) {
0495             ret = PTR_ERR(trans);
0496             mutex_lock(&fs_info->chunk_mutex);
0497             if (ret == -ENOENT) {
0498                 spin_lock(&fs_info->trans_lock);
0499                 continue;
0500             } else {
0501                 goto unlock;
0502             }
0503         }
0504 
0505         ret = btrfs_commit_transaction(trans);
0506         mutex_lock(&fs_info->chunk_mutex);
0507         if (ret)
0508             goto unlock;
0509 
0510         spin_lock(&fs_info->trans_lock);
0511     }
0512     spin_unlock(&fs_info->trans_lock);
0513 
0514     path = btrfs_alloc_path();
0515     if (!path) {
0516         ret = -ENOMEM;
0517         goto unlock;
0518     }
0519 
0520     path->reada = READA_FORWARD;
0521     path->search_commit_root = 1;
0522     path->skip_locking = 1;
0523 
0524     key.objectid = src_dev->devid;
0525     key.type = BTRFS_DEV_EXTENT_KEY;
0526     key.offset = 0;
0527 
0528     btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
0529         struct extent_buffer *leaf = path->nodes[0];
0530 
0531         if (found_key.objectid != src_dev->devid)
0532             break;
0533 
0534         if (found_key.type != BTRFS_DEV_EXTENT_KEY)
0535             break;
0536 
0537         if (found_key.offset < key.offset)
0538             break;
0539 
0540         dev_extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
0541 
0542         chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dev_extent);
0543 
0544         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
0545         if (!cache)
0546             continue;
0547 
0548         spin_lock(&cache->lock);
0549         cache->to_copy = 1;
0550         spin_unlock(&cache->lock);
0551 
0552         btrfs_put_block_group(cache);
0553     }
0554     if (iter_ret < 0)
0555         ret = iter_ret;
0556 
0557     btrfs_free_path(path);
0558 unlock:
0559     mutex_unlock(&fs_info->chunk_mutex);
0560 
0561     return ret;
0562 }
0563 
0564 bool btrfs_finish_block_group_to_copy(struct btrfs_device *srcdev,
0565                       struct btrfs_block_group *cache,
0566                       u64 physical)
0567 {
0568     struct btrfs_fs_info *fs_info = cache->fs_info;
0569     struct extent_map *em;
0570     struct map_lookup *map;
0571     u64 chunk_offset = cache->start;
0572     int num_extents, cur_extent;
0573     int i;
0574 
0575     /* Do not use "to_copy" on non zoned filesystem for now */
0576     if (!btrfs_is_zoned(fs_info))
0577         return true;
0578 
0579     spin_lock(&cache->lock);
0580     if (cache->removed) {
0581         spin_unlock(&cache->lock);
0582         return true;
0583     }
0584     spin_unlock(&cache->lock);
0585 
0586     em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
0587     ASSERT(!IS_ERR(em));
0588     map = em->map_lookup;
0589 
0590     num_extents = 0;
0591     cur_extent = 0;
0592     for (i = 0; i < map->num_stripes; i++) {
0593         /* We have more device extent to copy */
0594         if (srcdev != map->stripes[i].dev)
0595             continue;
0596 
0597         num_extents++;
0598         if (physical == map->stripes[i].physical)
0599             cur_extent = i;
0600     }
0601 
0602     free_extent_map(em);
0603 
0604     if (num_extents > 1 && cur_extent < num_extents - 1) {
0605         /*
0606          * Has more stripes on this device. Keep this block group
0607          * readonly until we finish all the stripes.
0608          */
0609         return false;
0610     }
0611 
0612     /* Last stripe on this device */
0613     spin_lock(&cache->lock);
0614     cache->to_copy = 0;
0615     spin_unlock(&cache->lock);
0616 
0617     return true;
0618 }
0619 
0620 static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
0621         const char *tgtdev_name, u64 srcdevid, const char *srcdev_name,
0622         int read_src)
0623 {
0624     struct btrfs_root *root = fs_info->dev_root;
0625     struct btrfs_trans_handle *trans;
0626     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
0627     int ret;
0628     struct btrfs_device *tgt_device = NULL;
0629     struct btrfs_device *src_device = NULL;
0630 
0631     src_device = btrfs_find_device_by_devspec(fs_info, srcdevid,
0632                           srcdev_name);
0633     if (IS_ERR(src_device))
0634         return PTR_ERR(src_device);
0635 
0636     if (btrfs_pinned_by_swapfile(fs_info, src_device)) {
0637         btrfs_warn_in_rcu(fs_info,
0638       "cannot replace device %s (devid %llu) due to active swapfile",
0639             btrfs_dev_name(src_device), src_device->devid);
0640         return -ETXTBSY;
0641     }
0642 
0643     /*
0644      * Here we commit the transaction to make sure commit_total_bytes
0645      * of all the devices are updated.
0646      */
0647     trans = btrfs_attach_transaction(root);
0648     if (!IS_ERR(trans)) {
0649         ret = btrfs_commit_transaction(trans);
0650         if (ret)
0651             return ret;
0652     } else if (PTR_ERR(trans) != -ENOENT) {
0653         return PTR_ERR(trans);
0654     }
0655 
0656     ret = btrfs_init_dev_replace_tgtdev(fs_info, tgtdev_name,
0657                         src_device, &tgt_device);
0658     if (ret)
0659         return ret;
0660 
0661     ret = mark_block_group_to_copy(fs_info, src_device);
0662     if (ret)
0663         return ret;
0664 
0665     down_write(&dev_replace->rwsem);
0666     switch (dev_replace->replace_state) {
0667     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
0668     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
0669     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
0670         break;
0671     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
0672     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
0673         ASSERT(0);
0674         ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED;
0675         up_write(&dev_replace->rwsem);
0676         goto leave;
0677     }
0678 
0679     dev_replace->cont_reading_from_srcdev_mode = read_src;
0680     dev_replace->srcdev = src_device;
0681     dev_replace->tgtdev = tgt_device;
0682 
0683     btrfs_info_in_rcu(fs_info,
0684               "dev_replace from %s (devid %llu) to %s started",
0685               btrfs_dev_name(src_device),
0686               src_device->devid,
0687               rcu_str_deref(tgt_device->name));
0688 
0689     /*
0690      * from now on, the writes to the srcdev are all duplicated to
0691      * go to the tgtdev as well (refer to btrfs_map_block()).
0692      */
0693     dev_replace->replace_state = BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
0694     dev_replace->time_started = ktime_get_real_seconds();
0695     dev_replace->cursor_left = 0;
0696     dev_replace->committed_cursor_left = 0;
0697     dev_replace->cursor_left_last_write_of_item = 0;
0698     dev_replace->cursor_right = 0;
0699     dev_replace->is_valid = 1;
0700     dev_replace->item_needs_writeback = 1;
0701     atomic64_set(&dev_replace->num_write_errors, 0);
0702     atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
0703     up_write(&dev_replace->rwsem);
0704 
0705     ret = btrfs_sysfs_add_device(tgt_device);
0706     if (ret)
0707         btrfs_err(fs_info, "kobj add dev failed %d", ret);
0708 
0709     btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
0710 
0711     /*
0712      * Commit dev_replace state and reserve 1 item for it.
0713      * This is crucial to ensure we won't miss copying extents for new block
0714      * groups that are allocated after we started the device replace, and
0715      * must be done after setting up the device replace state.
0716      */
0717     trans = btrfs_start_transaction(root, 1);
0718     if (IS_ERR(trans)) {
0719         ret = PTR_ERR(trans);
0720         down_write(&dev_replace->rwsem);
0721         dev_replace->replace_state =
0722             BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
0723         dev_replace->srcdev = NULL;
0724         dev_replace->tgtdev = NULL;
0725         up_write(&dev_replace->rwsem);
0726         goto leave;
0727     }
0728 
0729     ret = btrfs_commit_transaction(trans);
0730     WARN_ON(ret);
0731 
0732     /* the disk copy procedure reuses the scrub code */
0733     ret = btrfs_scrub_dev(fs_info, src_device->devid, 0,
0734                   btrfs_device_get_total_bytes(src_device),
0735                   &dev_replace->scrub_progress, 0, 1);
0736 
0737     ret = btrfs_dev_replace_finishing(fs_info, ret);
0738     if (ret == -EINPROGRESS)
0739         ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS;
0740 
0741     return ret;
0742 
0743 leave:
0744     btrfs_destroy_dev_replace_tgtdev(tgt_device);
0745     return ret;
0746 }
0747 
0748 int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
0749                 struct btrfs_ioctl_dev_replace_args *args)
0750 {
0751     int ret;
0752 
0753     switch (args->start.cont_reading_from_srcdev_mode) {
0754     case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
0755     case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
0756         break;
0757     default:
0758         return -EINVAL;
0759     }
0760 
0761     if ((args->start.srcdevid == 0 && args->start.srcdev_name[0] == '\0') ||
0762         args->start.tgtdev_name[0] == '\0')
0763         return -EINVAL;
0764 
0765     ret = btrfs_dev_replace_start(fs_info, args->start.tgtdev_name,
0766                     args->start.srcdevid,
0767                     args->start.srcdev_name,
0768                     args->start.cont_reading_from_srcdev_mode);
0769     args->result = ret;
0770     /* don't warn if EINPROGRESS, someone else might be running scrub */
0771     if (ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS ||
0772         ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR)
0773         return 0;
0774 
0775     return ret;
0776 }
0777 
0778 /*
0779  * blocked until all in-flight bios operations are finished.
0780  */
0781 static void btrfs_rm_dev_replace_blocked(struct btrfs_fs_info *fs_info)
0782 {
0783     set_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
0784     wait_event(fs_info->dev_replace.replace_wait, !percpu_counter_sum(
0785            &fs_info->dev_replace.bio_counter));
0786 }
0787 
0788 /*
0789  * we have removed target device, it is safe to allow new bios request.
0790  */
0791 static void btrfs_rm_dev_replace_unblocked(struct btrfs_fs_info *fs_info)
0792 {
0793     clear_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
0794     wake_up(&fs_info->dev_replace.replace_wait);
0795 }
0796 
0797 /*
0798  * When finishing the device replace, before swapping the source device with the
0799  * target device we must update the chunk allocation state in the target device,
0800  * as it is empty because replace works by directly copying the chunks and not
0801  * through the normal chunk allocation path.
0802  */
0803 static int btrfs_set_target_alloc_state(struct btrfs_device *srcdev,
0804                     struct btrfs_device *tgtdev)
0805 {
0806     struct extent_state *cached_state = NULL;
0807     u64 start = 0;
0808     u64 found_start;
0809     u64 found_end;
0810     int ret = 0;
0811 
0812     lockdep_assert_held(&srcdev->fs_info->chunk_mutex);
0813 
0814     while (!find_first_extent_bit(&srcdev->alloc_state, start,
0815                       &found_start, &found_end,
0816                       CHUNK_ALLOCATED, &cached_state)) {
0817         ret = set_extent_bits(&tgtdev->alloc_state, found_start,
0818                       found_end, CHUNK_ALLOCATED);
0819         if (ret)
0820             break;
0821         start = found_end + 1;
0822     }
0823 
0824     free_extent_state(cached_state);
0825     return ret;
0826 }
0827 
0828 static void btrfs_dev_replace_update_device_in_mapping_tree(
0829                         struct btrfs_fs_info *fs_info,
0830                         struct btrfs_device *srcdev,
0831                         struct btrfs_device *tgtdev)
0832 {
0833     struct extent_map_tree *em_tree = &fs_info->mapping_tree;
0834     struct extent_map *em;
0835     struct map_lookup *map;
0836     u64 start = 0;
0837     int i;
0838 
0839     write_lock(&em_tree->lock);
0840     do {
0841         em = lookup_extent_mapping(em_tree, start, (u64)-1);
0842         if (!em)
0843             break;
0844         map = em->map_lookup;
0845         for (i = 0; i < map->num_stripes; i++)
0846             if (srcdev == map->stripes[i].dev)
0847                 map->stripes[i].dev = tgtdev;
0848         start = em->start + em->len;
0849         free_extent_map(em);
0850     } while (start);
0851     write_unlock(&em_tree->lock);
0852 }
0853 
0854 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
0855                        int scrub_ret)
0856 {
0857     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
0858     struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
0859     struct btrfs_device *tgt_device;
0860     struct btrfs_device *src_device;
0861     struct btrfs_root *root = fs_info->tree_root;
0862     u8 uuid_tmp[BTRFS_UUID_SIZE];
0863     struct btrfs_trans_handle *trans;
0864     int ret = 0;
0865 
0866     /* don't allow cancel or unmount to disturb the finishing procedure */
0867     mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
0868 
0869     down_read(&dev_replace->rwsem);
0870     /* was the operation canceled, or is it finished? */
0871     if (dev_replace->replace_state !=
0872         BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED) {
0873         up_read(&dev_replace->rwsem);
0874         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
0875         return 0;
0876     }
0877 
0878     tgt_device = dev_replace->tgtdev;
0879     src_device = dev_replace->srcdev;
0880     up_read(&dev_replace->rwsem);
0881 
0882     /*
0883      * flush all outstanding I/O and inode extent mappings before the
0884      * copy operation is declared as being finished
0885      */
0886     ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
0887     if (ret) {
0888         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
0889         return ret;
0890     }
0891     btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
0892 
0893     /*
0894      * We have to use this loop approach because at this point src_device
0895      * has to be available for transaction commit to complete, yet new
0896      * chunks shouldn't be allocated on the device.
0897      */
0898     while (1) {
0899         trans = btrfs_start_transaction(root, 0);
0900         if (IS_ERR(trans)) {
0901             mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
0902             return PTR_ERR(trans);
0903         }
0904         ret = btrfs_commit_transaction(trans);
0905         WARN_ON(ret);
0906 
0907         /* Prevent write_all_supers() during the finishing procedure */
0908         mutex_lock(&fs_devices->device_list_mutex);
0909         /* Prevent new chunks being allocated on the source device */
0910         mutex_lock(&fs_info->chunk_mutex);
0911 
0912         if (!list_empty(&src_device->post_commit_list)) {
0913             mutex_unlock(&fs_devices->device_list_mutex);
0914             mutex_unlock(&fs_info->chunk_mutex);
0915         } else {
0916             break;
0917         }
0918     }
0919 
0920     down_write(&dev_replace->rwsem);
0921     dev_replace->replace_state =
0922         scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
0923               : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
0924     dev_replace->tgtdev = NULL;
0925     dev_replace->srcdev = NULL;
0926     dev_replace->time_stopped = ktime_get_real_seconds();
0927     dev_replace->item_needs_writeback = 1;
0928 
0929     /*
0930      * Update allocation state in the new device and replace the old device
0931      * with the new one in the mapping tree.
0932      */
0933     if (!scrub_ret) {
0934         scrub_ret = btrfs_set_target_alloc_state(src_device, tgt_device);
0935         if (scrub_ret)
0936             goto error;
0937         btrfs_dev_replace_update_device_in_mapping_tree(fs_info,
0938                                 src_device,
0939                                 tgt_device);
0940     } else {
0941         if (scrub_ret != -ECANCELED)
0942             btrfs_err_in_rcu(fs_info,
0943                  "btrfs_scrub_dev(%s, %llu, %s) failed %d",
0944                  btrfs_dev_name(src_device),
0945                  src_device->devid,
0946                  rcu_str_deref(tgt_device->name), scrub_ret);
0947 error:
0948         up_write(&dev_replace->rwsem);
0949         mutex_unlock(&fs_info->chunk_mutex);
0950         mutex_unlock(&fs_devices->device_list_mutex);
0951         btrfs_rm_dev_replace_blocked(fs_info);
0952         if (tgt_device)
0953             btrfs_destroy_dev_replace_tgtdev(tgt_device);
0954         btrfs_rm_dev_replace_unblocked(fs_info);
0955         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
0956 
0957         return scrub_ret;
0958     }
0959 
0960     btrfs_info_in_rcu(fs_info,
0961               "dev_replace from %s (devid %llu) to %s finished",
0962               btrfs_dev_name(src_device),
0963               src_device->devid,
0964               rcu_str_deref(tgt_device->name));
0965     clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &tgt_device->dev_state);
0966     tgt_device->devid = src_device->devid;
0967     src_device->devid = BTRFS_DEV_REPLACE_DEVID;
0968     memcpy(uuid_tmp, tgt_device->uuid, sizeof(uuid_tmp));
0969     memcpy(tgt_device->uuid, src_device->uuid, sizeof(tgt_device->uuid));
0970     memcpy(src_device->uuid, uuid_tmp, sizeof(src_device->uuid));
0971     btrfs_device_set_total_bytes(tgt_device, src_device->total_bytes);
0972     btrfs_device_set_disk_total_bytes(tgt_device,
0973                       src_device->disk_total_bytes);
0974     btrfs_device_set_bytes_used(tgt_device, src_device->bytes_used);
0975     tgt_device->commit_bytes_used = src_device->bytes_used;
0976 
0977     btrfs_assign_next_active_device(src_device, tgt_device);
0978 
0979     list_add(&tgt_device->dev_alloc_list, &fs_devices->alloc_list);
0980     fs_devices->rw_devices++;
0981 
0982     up_write(&dev_replace->rwsem);
0983     btrfs_rm_dev_replace_blocked(fs_info);
0984 
0985     btrfs_rm_dev_replace_remove_srcdev(src_device);
0986 
0987     btrfs_rm_dev_replace_unblocked(fs_info);
0988 
0989     /*
0990      * Increment dev_stats_ccnt so that btrfs_run_dev_stats() will
0991      * update on-disk dev stats value during commit transaction
0992      */
0993     atomic_inc(&tgt_device->dev_stats_ccnt);
0994 
0995     /*
0996      * this is again a consistent state where no dev_replace procedure
0997      * is running, the target device is part of the filesystem, the
0998      * source device is not part of the filesystem anymore and its 1st
0999      * superblock is scratched out so that it is no longer marked to
1000      * belong to this filesystem.
1001      */
1002     mutex_unlock(&fs_info->chunk_mutex);
1003     mutex_unlock(&fs_devices->device_list_mutex);
1004 
1005     /* replace the sysfs entry */
1006     btrfs_sysfs_remove_device(src_device);
1007     btrfs_sysfs_update_devid(tgt_device);
1008     if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &src_device->dev_state))
1009         btrfs_scratch_superblocks(fs_info, src_device->bdev,
1010                       src_device->name->str);
1011 
1012     /* write back the superblocks */
1013     trans = btrfs_start_transaction(root, 0);
1014     if (!IS_ERR(trans))
1015         btrfs_commit_transaction(trans);
1016 
1017     mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1018 
1019     btrfs_rm_dev_replace_free_srcdev(src_device);
1020 
1021     return 0;
1022 }
1023 
1024 /*
1025  * Read progress of device replace status according to the state and last
1026  * stored position. The value format is the same as for
1027  * btrfs_dev_replace::progress_1000
1028  */
1029 static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info)
1030 {
1031     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1032     u64 ret = 0;
1033 
1034     switch (dev_replace->replace_state) {
1035     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1036     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1037         ret = 0;
1038         break;
1039     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1040         ret = 1000;
1041         break;
1042     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1043     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1044         ret = div64_u64(dev_replace->cursor_left,
1045                 div_u64(btrfs_device_get_total_bytes(
1046                         dev_replace->srcdev), 1000));
1047         break;
1048     }
1049 
1050     return ret;
1051 }
1052 
1053 void btrfs_dev_replace_status(struct btrfs_fs_info *fs_info,
1054                   struct btrfs_ioctl_dev_replace_args *args)
1055 {
1056     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1057 
1058     down_read(&dev_replace->rwsem);
1059     /* even if !dev_replace_is_valid, the values are good enough for
1060      * the replace_status ioctl */
1061     args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1062     args->status.replace_state = dev_replace->replace_state;
1063     args->status.time_started = dev_replace->time_started;
1064     args->status.time_stopped = dev_replace->time_stopped;
1065     args->status.num_write_errors =
1066         atomic64_read(&dev_replace->num_write_errors);
1067     args->status.num_uncorrectable_read_errors =
1068         atomic64_read(&dev_replace->num_uncorrectable_read_errors);
1069     args->status.progress_1000 = btrfs_dev_replace_progress(fs_info);
1070     up_read(&dev_replace->rwsem);
1071 }
1072 
1073 int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
1074 {
1075     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1076     struct btrfs_device *tgt_device = NULL;
1077     struct btrfs_device *src_device = NULL;
1078     struct btrfs_trans_handle *trans;
1079     struct btrfs_root *root = fs_info->tree_root;
1080     int result;
1081     int ret;
1082 
1083     if (sb_rdonly(fs_info->sb))
1084         return -EROFS;
1085 
1086     mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
1087     down_write(&dev_replace->rwsem);
1088     switch (dev_replace->replace_state) {
1089     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1090     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1091     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1092         result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
1093         up_write(&dev_replace->rwsem);
1094         break;
1095     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1096         tgt_device = dev_replace->tgtdev;
1097         src_device = dev_replace->srcdev;
1098         up_write(&dev_replace->rwsem);
1099         ret = btrfs_scrub_cancel(fs_info);
1100         if (ret < 0) {
1101             result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
1102         } else {
1103             result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1104             /*
1105              * btrfs_dev_replace_finishing() will handle the
1106              * cleanup part
1107              */
1108             btrfs_info_in_rcu(fs_info,
1109                 "dev_replace from %s (devid %llu) to %s canceled",
1110                 btrfs_dev_name(src_device), src_device->devid,
1111                 btrfs_dev_name(tgt_device));
1112         }
1113         break;
1114     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1115         /*
1116          * Scrub doing the replace isn't running so we need to do the
1117          * cleanup step of btrfs_dev_replace_finishing() here
1118          */
1119         result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1120         tgt_device = dev_replace->tgtdev;
1121         src_device = dev_replace->srcdev;
1122         dev_replace->tgtdev = NULL;
1123         dev_replace->srcdev = NULL;
1124         dev_replace->replace_state =
1125                 BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED;
1126         dev_replace->time_stopped = ktime_get_real_seconds();
1127         dev_replace->item_needs_writeback = 1;
1128 
1129         up_write(&dev_replace->rwsem);
1130 
1131         /* Scrub for replace must not be running in suspended state */
1132         btrfs_scrub_cancel(fs_info);
1133 
1134         trans = btrfs_start_transaction(root, 0);
1135         if (IS_ERR(trans)) {
1136             mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1137             return PTR_ERR(trans);
1138         }
1139         ret = btrfs_commit_transaction(trans);
1140         WARN_ON(ret);
1141 
1142         btrfs_info_in_rcu(fs_info,
1143         "suspended dev_replace from %s (devid %llu) to %s canceled",
1144             btrfs_dev_name(src_device), src_device->devid,
1145             btrfs_dev_name(tgt_device));
1146 
1147         if (tgt_device)
1148             btrfs_destroy_dev_replace_tgtdev(tgt_device);
1149         break;
1150     default:
1151         up_write(&dev_replace->rwsem);
1152         result = -EINVAL;
1153     }
1154 
1155     mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1156     return result;
1157 }
1158 
1159 void btrfs_dev_replace_suspend_for_unmount(struct btrfs_fs_info *fs_info)
1160 {
1161     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1162 
1163     mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
1164     down_write(&dev_replace->rwsem);
1165 
1166     switch (dev_replace->replace_state) {
1167     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1168     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1169     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1170     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1171         break;
1172     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1173         dev_replace->replace_state =
1174             BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1175         dev_replace->time_stopped = ktime_get_real_seconds();
1176         dev_replace->item_needs_writeback = 1;
1177         btrfs_info(fs_info, "suspending dev_replace for unmount");
1178         break;
1179     }
1180 
1181     up_write(&dev_replace->rwsem);
1182     mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1183 }
1184 
1185 /* resume dev_replace procedure that was interrupted by unmount */
1186 int btrfs_resume_dev_replace_async(struct btrfs_fs_info *fs_info)
1187 {
1188     struct task_struct *task;
1189     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1190 
1191     down_write(&dev_replace->rwsem);
1192 
1193     switch (dev_replace->replace_state) {
1194     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1195     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1196     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1197         up_write(&dev_replace->rwsem);
1198         return 0;
1199     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1200         break;
1201     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1202         dev_replace->replace_state =
1203             BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
1204         break;
1205     }
1206     if (!dev_replace->tgtdev || !dev_replace->tgtdev->bdev) {
1207         btrfs_info(fs_info,
1208                "cannot continue dev_replace, tgtdev is missing");
1209         btrfs_info(fs_info,
1210                "you may cancel the operation after 'mount -o degraded'");
1211         dev_replace->replace_state =
1212                     BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1213         up_write(&dev_replace->rwsem);
1214         return 0;
1215     }
1216     up_write(&dev_replace->rwsem);
1217 
1218     /*
1219      * This could collide with a paused balance, but the exclusive op logic
1220      * should never allow both to start and pause. We don't want to allow
1221      * dev-replace to start anyway.
1222      */
1223     if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
1224         down_write(&dev_replace->rwsem);
1225         dev_replace->replace_state =
1226                     BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1227         up_write(&dev_replace->rwsem);
1228         btrfs_info(fs_info,
1229         "cannot resume dev-replace, other exclusive operation running");
1230         return 0;
1231     }
1232 
1233     task = kthread_run(btrfs_dev_replace_kthread, fs_info, "btrfs-devrepl");
1234     return PTR_ERR_OR_ZERO(task);
1235 }
1236 
1237 static int btrfs_dev_replace_kthread(void *data)
1238 {
1239     struct btrfs_fs_info *fs_info = data;
1240     struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1241     u64 progress;
1242     int ret;
1243 
1244     progress = btrfs_dev_replace_progress(fs_info);
1245     progress = div_u64(progress, 10);
1246     btrfs_info_in_rcu(fs_info,
1247         "continuing dev_replace from %s (devid %llu) to target %s @%u%%",
1248         btrfs_dev_name(dev_replace->srcdev),
1249         dev_replace->srcdev->devid,
1250         btrfs_dev_name(dev_replace->tgtdev),
1251         (unsigned int)progress);
1252 
1253     ret = btrfs_scrub_dev(fs_info, dev_replace->srcdev->devid,
1254                   dev_replace->committed_cursor_left,
1255                   btrfs_device_get_total_bytes(dev_replace->srcdev),
1256                   &dev_replace->scrub_progress, 0, 1);
1257     ret = btrfs_dev_replace_finishing(fs_info, ret);
1258     WARN_ON(ret && ret != -ECANCELED);
1259 
1260     btrfs_exclop_finish(fs_info);
1261     return 0;
1262 }
1263 
1264 int __pure btrfs_dev_replace_is_ongoing(struct btrfs_dev_replace *dev_replace)
1265 {
1266     if (!dev_replace->is_valid)
1267         return 0;
1268 
1269     switch (dev_replace->replace_state) {
1270     case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1271     case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1272     case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1273         return 0;
1274     case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1275     case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1276         /*
1277          * return true even if tgtdev is missing (this is
1278          * something that can happen if the dev_replace
1279          * procedure is suspended by an umount and then
1280          * the tgtdev is missing (or "btrfs dev scan") was
1281          * not called and the filesystem is remounted
1282          * in degraded state. This does not stop the
1283          * dev_replace procedure. It needs to be canceled
1284          * manually if the cancellation is wanted.
1285          */
1286         break;
1287     }
1288     return 1;
1289 }
1290 
1291 void btrfs_bio_counter_inc_noblocked(struct btrfs_fs_info *fs_info)
1292 {
1293     percpu_counter_inc(&fs_info->dev_replace.bio_counter);
1294 }
1295 
1296 void btrfs_bio_counter_sub(struct btrfs_fs_info *fs_info, s64 amount)
1297 {
1298     percpu_counter_sub(&fs_info->dev_replace.bio_counter, amount);
1299     cond_wake_up_nomb(&fs_info->dev_replace.replace_wait);
1300 }
1301 
1302 void btrfs_bio_counter_inc_blocked(struct btrfs_fs_info *fs_info)
1303 {
1304     while (1) {
1305         percpu_counter_inc(&fs_info->dev_replace.bio_counter);
1306         if (likely(!test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1307                      &fs_info->fs_state)))
1308             break;
1309 
1310         btrfs_bio_counter_dec(fs_info);
1311         wait_event(fs_info->dev_replace.replace_wait,
1312                !test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1313                      &fs_info->fs_state));
1314     }
1315 }