xref: /openbmc/linux/fs/btrfs/dev-replace.c (revision bb21e302)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STRATO AG 2012.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/bio.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/kthread.h>
11 #include <linux/math64.h>
12 #include "misc.h"
13 #include "ctree.h"
14 #include "extent_map.h"
15 #include "disk-io.h"
16 #include "transaction.h"
17 #include "print-tree.h"
18 #include "volumes.h"
19 #include "async-thread.h"
20 #include "check-integrity.h"
21 #include "rcu-string.h"
22 #include "dev-replace.h"
23 #include "sysfs.h"
24 #include "zoned.h"
25 #include "block-group.h"
26 #include "fs.h"
27 #include "accessors.h"
28 #include "scrub.h"
29 
30 /*
31  * Device replace overview
32  *
33  * [Objective]
34  * To copy all extents (both new and on-disk) from source device to target
35  * device, while still keeping the filesystem read-write.
36  *
37  * [Method]
38  * There are two main methods involved:
39  *
40  * - Write duplication
41  *
42  *   All new writes will be written to both target and source devices, so even
43  *   if replace gets canceled, sources device still contains up-to-date data.
44  *
45  *   Location:		handle_ops_on_dev_replace() from __btrfs_map_block()
46  *   Start:		btrfs_dev_replace_start()
47  *   End:		btrfs_dev_replace_finishing()
48  *   Content:		Latest data/metadata
49  *
50  * - Copy existing extents
51  *
52  *   This happens by re-using scrub facility, as scrub also iterates through
53  *   existing extents from commit root.
54  *
55  *   Location:		scrub_write_block_to_dev_replace() from
56  *   			scrub_block_complete()
57  *   Content:		Data/meta from commit root.
58  *
59  * Due to the content difference, we need to avoid nocow write when dev-replace
60  * is happening.  This is done by marking the block group read-only and waiting
61  * for NOCOW writes.
62  *
63  * After replace is done, the finishing part is done by swapping the target and
64  * source devices.
65  *
66  *   Location:		btrfs_dev_replace_update_device_in_mapping_tree() from
67  *   			btrfs_dev_replace_finishing()
68  */
69 
70 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
71 				       int scrub_ret);
72 static int btrfs_dev_replace_kthread(void *data);
73 
74 int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
75 {
76 	struct btrfs_dev_lookup_args args = { .devid = BTRFS_DEV_REPLACE_DEVID };
77 	struct btrfs_key key;
78 	struct btrfs_root *dev_root = fs_info->dev_root;
79 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
80 	struct extent_buffer *eb;
81 	int slot;
82 	int ret = 0;
83 	struct btrfs_path *path = NULL;
84 	int item_size;
85 	struct btrfs_dev_replace_item *ptr;
86 	u64 src_devid;
87 
88 	if (!dev_root)
89 		return 0;
90 
91 	path = btrfs_alloc_path();
92 	if (!path) {
93 		ret = -ENOMEM;
94 		goto out;
95 	}
96 
97 	key.objectid = 0;
98 	key.type = BTRFS_DEV_REPLACE_KEY;
99 	key.offset = 0;
100 	ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
101 	if (ret) {
102 no_valid_dev_replace_entry_found:
103 		/*
104 		 * We don't have a replace item or it's corrupted.  If there is
105 		 * a replace target, fail the mount.
106 		 */
107 		if (btrfs_find_device(fs_info->fs_devices, &args)) {
108 			btrfs_err(fs_info,
109 			"found replace target device without a valid replace item");
110 			ret = -EUCLEAN;
111 			goto out;
112 		}
113 		ret = 0;
114 		dev_replace->replace_state =
115 			BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
116 		dev_replace->cont_reading_from_srcdev_mode =
117 		    BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
118 		dev_replace->time_started = 0;
119 		dev_replace->time_stopped = 0;
120 		atomic64_set(&dev_replace->num_write_errors, 0);
121 		atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
122 		dev_replace->cursor_left = 0;
123 		dev_replace->committed_cursor_left = 0;
124 		dev_replace->cursor_left_last_write_of_item = 0;
125 		dev_replace->cursor_right = 0;
126 		dev_replace->srcdev = NULL;
127 		dev_replace->tgtdev = NULL;
128 		dev_replace->is_valid = 0;
129 		dev_replace->item_needs_writeback = 0;
130 		goto out;
131 	}
132 	slot = path->slots[0];
133 	eb = path->nodes[0];
134 	item_size = btrfs_item_size(eb, slot);
135 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item);
136 
137 	if (item_size != sizeof(struct btrfs_dev_replace_item)) {
138 		btrfs_warn(fs_info,
139 			"dev_replace entry found has unexpected size, ignore entry");
140 		goto no_valid_dev_replace_entry_found;
141 	}
142 
143 	src_devid = btrfs_dev_replace_src_devid(eb, ptr);
144 	dev_replace->cont_reading_from_srcdev_mode =
145 		btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
146 	dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
147 	dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
148 	dev_replace->time_stopped =
149 		btrfs_dev_replace_time_stopped(eb, ptr);
150 	atomic64_set(&dev_replace->num_write_errors,
151 		     btrfs_dev_replace_num_write_errors(eb, ptr));
152 	atomic64_set(&dev_replace->num_uncorrectable_read_errors,
153 		     btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr));
154 	dev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr);
155 	dev_replace->committed_cursor_left = dev_replace->cursor_left;
156 	dev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left;
157 	dev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr);
158 	dev_replace->is_valid = 1;
159 
160 	dev_replace->item_needs_writeback = 0;
161 	switch (dev_replace->replace_state) {
162 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
163 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
164 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
165 		/*
166 		 * We don't have an active replace item but if there is a
167 		 * replace target, fail the mount.
168 		 */
169 		if (btrfs_find_device(fs_info->fs_devices, &args)) {
170 			btrfs_err(fs_info,
171 "replace without active item, run 'device scan --forget' on the target device");
172 			ret = -EUCLEAN;
173 		} else {
174 			dev_replace->srcdev = NULL;
175 			dev_replace->tgtdev = NULL;
176 		}
177 		break;
178 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
179 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
180 		dev_replace->tgtdev = btrfs_find_device(fs_info->fs_devices, &args);
181 		args.devid = src_devid;
182 		dev_replace->srcdev = btrfs_find_device(fs_info->fs_devices, &args);
183 
184 		/*
185 		 * allow 'btrfs dev replace_cancel' if src/tgt device is
186 		 * missing
187 		 */
188 		if (!dev_replace->srcdev &&
189 		    !btrfs_test_opt(fs_info, DEGRADED)) {
190 			ret = -EIO;
191 			btrfs_warn(fs_info,
192 			   "cannot mount because device replace operation is ongoing and");
193 			btrfs_warn(fs_info,
194 			   "srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
195 			   src_devid);
196 		}
197 		if (!dev_replace->tgtdev &&
198 		    !btrfs_test_opt(fs_info, DEGRADED)) {
199 			ret = -EIO;
200 			btrfs_warn(fs_info,
201 			   "cannot mount because device replace operation is ongoing and");
202 			btrfs_warn(fs_info,
203 			   "tgtdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
204 				BTRFS_DEV_REPLACE_DEVID);
205 		}
206 		if (dev_replace->tgtdev) {
207 			if (dev_replace->srcdev) {
208 				dev_replace->tgtdev->total_bytes =
209 					dev_replace->srcdev->total_bytes;
210 				dev_replace->tgtdev->disk_total_bytes =
211 					dev_replace->srcdev->disk_total_bytes;
212 				dev_replace->tgtdev->commit_total_bytes =
213 					dev_replace->srcdev->commit_total_bytes;
214 				dev_replace->tgtdev->bytes_used =
215 					dev_replace->srcdev->bytes_used;
216 				dev_replace->tgtdev->commit_bytes_used =
217 					dev_replace->srcdev->commit_bytes_used;
218 			}
219 			set_bit(BTRFS_DEV_STATE_REPLACE_TGT,
220 				&dev_replace->tgtdev->dev_state);
221 
222 			WARN_ON(fs_info->fs_devices->rw_devices == 0);
223 			dev_replace->tgtdev->io_width = fs_info->sectorsize;
224 			dev_replace->tgtdev->io_align = fs_info->sectorsize;
225 			dev_replace->tgtdev->sector_size = fs_info->sectorsize;
226 			dev_replace->tgtdev->fs_info = fs_info;
227 			set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
228 				&dev_replace->tgtdev->dev_state);
229 		}
230 		break;
231 	}
232 
233 out:
234 	btrfs_free_path(path);
235 	return ret;
236 }
237 
238 /*
239  * Initialize a new device for device replace target from a given source dev
240  * and path.
241  *
242  * Return 0 and new device in @device_out, otherwise return < 0
243  */
244 static int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
245 				  const char *device_path,
246 				  struct btrfs_device *srcdev,
247 				  struct btrfs_device **device_out)
248 {
249 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
250 	struct btrfs_device *device;
251 	struct block_device *bdev;
252 	u64 devid = BTRFS_DEV_REPLACE_DEVID;
253 	int ret = 0;
254 
255 	*device_out = NULL;
256 	if (srcdev->fs_devices->seeding) {
257 		btrfs_err(fs_info, "the filesystem is a seed filesystem!");
258 		return -EINVAL;
259 	}
260 
261 	bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
262 				  fs_info->bdev_holder);
263 	if (IS_ERR(bdev)) {
264 		btrfs_err(fs_info, "target device %s is invalid!", device_path);
265 		return PTR_ERR(bdev);
266 	}
267 
268 	if (!btrfs_check_device_zone_type(fs_info, bdev)) {
269 		btrfs_err(fs_info,
270 		"dev-replace: zoned type of target device mismatch with filesystem");
271 		ret = -EINVAL;
272 		goto error;
273 	}
274 
275 	sync_blockdev(bdev);
276 
277 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
278 		if (device->bdev == bdev) {
279 			btrfs_err(fs_info,
280 				  "target device is in the filesystem!");
281 			ret = -EEXIST;
282 			goto error;
283 		}
284 	}
285 
286 
287 	if (bdev_nr_bytes(bdev) < btrfs_device_get_total_bytes(srcdev)) {
288 		btrfs_err(fs_info,
289 			  "target device is smaller than source device!");
290 		ret = -EINVAL;
291 		goto error;
292 	}
293 
294 
295 	device = btrfs_alloc_device(NULL, &devid, NULL, device_path);
296 	if (IS_ERR(device)) {
297 		ret = PTR_ERR(device);
298 		goto error;
299 	}
300 
301 	ret = lookup_bdev(device_path, &device->devt);
302 	if (ret)
303 		goto error;
304 
305 	set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
306 	device->generation = 0;
307 	device->io_width = fs_info->sectorsize;
308 	device->io_align = fs_info->sectorsize;
309 	device->sector_size = fs_info->sectorsize;
310 	device->total_bytes = btrfs_device_get_total_bytes(srcdev);
311 	device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
312 	device->bytes_used = btrfs_device_get_bytes_used(srcdev);
313 	device->commit_total_bytes = srcdev->commit_total_bytes;
314 	device->commit_bytes_used = device->bytes_used;
315 	device->fs_info = fs_info;
316 	device->bdev = bdev;
317 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
318 	set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
319 	device->mode = FMODE_EXCL;
320 	device->dev_stats_valid = 1;
321 	set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
322 	device->fs_devices = fs_devices;
323 
324 	ret = btrfs_get_dev_zone_info(device, false);
325 	if (ret)
326 		goto error;
327 
328 	mutex_lock(&fs_devices->device_list_mutex);
329 	list_add(&device->dev_list, &fs_devices->devices);
330 	fs_devices->num_devices++;
331 	fs_devices->open_devices++;
332 	mutex_unlock(&fs_devices->device_list_mutex);
333 
334 	*device_out = device;
335 	return 0;
336 
337 error:
338 	blkdev_put(bdev, FMODE_EXCL);
339 	return ret;
340 }
341 
342 /*
343  * called from commit_transaction. Writes changed device replace state to
344  * disk.
345  */
346 int btrfs_run_dev_replace(struct btrfs_trans_handle *trans)
347 {
348 	struct btrfs_fs_info *fs_info = trans->fs_info;
349 	int ret;
350 	struct btrfs_root *dev_root = fs_info->dev_root;
351 	struct btrfs_path *path;
352 	struct btrfs_key key;
353 	struct extent_buffer *eb;
354 	struct btrfs_dev_replace_item *ptr;
355 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
356 
357 	down_read(&dev_replace->rwsem);
358 	if (!dev_replace->is_valid ||
359 	    !dev_replace->item_needs_writeback) {
360 		up_read(&dev_replace->rwsem);
361 		return 0;
362 	}
363 	up_read(&dev_replace->rwsem);
364 
365 	key.objectid = 0;
366 	key.type = BTRFS_DEV_REPLACE_KEY;
367 	key.offset = 0;
368 
369 	path = btrfs_alloc_path();
370 	if (!path) {
371 		ret = -ENOMEM;
372 		goto out;
373 	}
374 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
375 	if (ret < 0) {
376 		btrfs_warn(fs_info,
377 			   "error %d while searching for dev_replace item!",
378 			   ret);
379 		goto out;
380 	}
381 
382 	if (ret == 0 &&
383 	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
384 		/*
385 		 * need to delete old one and insert a new one.
386 		 * Since no attempt is made to recover any old state, if the
387 		 * dev_replace state is 'running', the data on the target
388 		 * drive is lost.
389 		 * It would be possible to recover the state: just make sure
390 		 * that the beginning of the item is never changed and always
391 		 * contains all the essential information. Then read this
392 		 * minimal set of information and use it as a base for the
393 		 * new state.
394 		 */
395 		ret = btrfs_del_item(trans, dev_root, path);
396 		if (ret != 0) {
397 			btrfs_warn(fs_info,
398 				   "delete too small dev_replace item failed %d!",
399 				   ret);
400 			goto out;
401 		}
402 		ret = 1;
403 	}
404 
405 	if (ret == 1) {
406 		/* need to insert a new item */
407 		btrfs_release_path(path);
408 		ret = btrfs_insert_empty_item(trans, dev_root, path,
409 					      &key, sizeof(*ptr));
410 		if (ret < 0) {
411 			btrfs_warn(fs_info,
412 				   "insert dev_replace item failed %d!", ret);
413 			goto out;
414 		}
415 	}
416 
417 	eb = path->nodes[0];
418 	ptr = btrfs_item_ptr(eb, path->slots[0],
419 			     struct btrfs_dev_replace_item);
420 
421 	down_write(&dev_replace->rwsem);
422 	if (dev_replace->srcdev)
423 		btrfs_set_dev_replace_src_devid(eb, ptr,
424 			dev_replace->srcdev->devid);
425 	else
426 		btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
427 	btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
428 		dev_replace->cont_reading_from_srcdev_mode);
429 	btrfs_set_dev_replace_replace_state(eb, ptr,
430 		dev_replace->replace_state);
431 	btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
432 	btrfs_set_dev_replace_time_stopped(eb, ptr, dev_replace->time_stopped);
433 	btrfs_set_dev_replace_num_write_errors(eb, ptr,
434 		atomic64_read(&dev_replace->num_write_errors));
435 	btrfs_set_dev_replace_num_uncorrectable_read_errors(eb, ptr,
436 		atomic64_read(&dev_replace->num_uncorrectable_read_errors));
437 	dev_replace->cursor_left_last_write_of_item =
438 		dev_replace->cursor_left;
439 	btrfs_set_dev_replace_cursor_left(eb, ptr,
440 		dev_replace->cursor_left_last_write_of_item);
441 	btrfs_set_dev_replace_cursor_right(eb, ptr,
442 		dev_replace->cursor_right);
443 	dev_replace->item_needs_writeback = 0;
444 	up_write(&dev_replace->rwsem);
445 
446 	btrfs_mark_buffer_dirty(eb);
447 
448 out:
449 	btrfs_free_path(path);
450 
451 	return ret;
452 }
453 
454 static char* btrfs_dev_name(struct btrfs_device *device)
455 {
456 	if (!device || test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
457 		return "<missing disk>";
458 	else
459 		return rcu_str_deref(device->name);
460 }
461 
462 static int mark_block_group_to_copy(struct btrfs_fs_info *fs_info,
463 				    struct btrfs_device *src_dev)
464 {
465 	struct btrfs_path *path;
466 	struct btrfs_key key;
467 	struct btrfs_key found_key;
468 	struct btrfs_root *root = fs_info->dev_root;
469 	struct btrfs_dev_extent *dev_extent = NULL;
470 	struct btrfs_block_group *cache;
471 	struct btrfs_trans_handle *trans;
472 	int iter_ret = 0;
473 	int ret = 0;
474 	u64 chunk_offset;
475 
476 	/* Do not use "to_copy" on non zoned filesystem for now */
477 	if (!btrfs_is_zoned(fs_info))
478 		return 0;
479 
480 	mutex_lock(&fs_info->chunk_mutex);
481 
482 	/* Ensure we don't have pending new block group */
483 	spin_lock(&fs_info->trans_lock);
484 	while (fs_info->running_transaction &&
485 	       !list_empty(&fs_info->running_transaction->dev_update_list)) {
486 		spin_unlock(&fs_info->trans_lock);
487 		mutex_unlock(&fs_info->chunk_mutex);
488 		trans = btrfs_attach_transaction(root);
489 		if (IS_ERR(trans)) {
490 			ret = PTR_ERR(trans);
491 			mutex_lock(&fs_info->chunk_mutex);
492 			if (ret == -ENOENT) {
493 				spin_lock(&fs_info->trans_lock);
494 				continue;
495 			} else {
496 				goto unlock;
497 			}
498 		}
499 
500 		ret = btrfs_commit_transaction(trans);
501 		mutex_lock(&fs_info->chunk_mutex);
502 		if (ret)
503 			goto unlock;
504 
505 		spin_lock(&fs_info->trans_lock);
506 	}
507 	spin_unlock(&fs_info->trans_lock);
508 
509 	path = btrfs_alloc_path();
510 	if (!path) {
511 		ret = -ENOMEM;
512 		goto unlock;
513 	}
514 
515 	path->reada = READA_FORWARD;
516 	path->search_commit_root = 1;
517 	path->skip_locking = 1;
518 
519 	key.objectid = src_dev->devid;
520 	key.type = BTRFS_DEV_EXTENT_KEY;
521 	key.offset = 0;
522 
523 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
524 		struct extent_buffer *leaf = path->nodes[0];
525 
526 		if (found_key.objectid != src_dev->devid)
527 			break;
528 
529 		if (found_key.type != BTRFS_DEV_EXTENT_KEY)
530 			break;
531 
532 		if (found_key.offset < key.offset)
533 			break;
534 
535 		dev_extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
536 
537 		chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dev_extent);
538 
539 		cache = btrfs_lookup_block_group(fs_info, chunk_offset);
540 		if (!cache)
541 			continue;
542 
543 		set_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
544 		btrfs_put_block_group(cache);
545 	}
546 	if (iter_ret < 0)
547 		ret = iter_ret;
548 
549 	btrfs_free_path(path);
550 unlock:
551 	mutex_unlock(&fs_info->chunk_mutex);
552 
553 	return ret;
554 }
555 
556 bool btrfs_finish_block_group_to_copy(struct btrfs_device *srcdev,
557 				      struct btrfs_block_group *cache,
558 				      u64 physical)
559 {
560 	struct btrfs_fs_info *fs_info = cache->fs_info;
561 	struct extent_map *em;
562 	struct map_lookup *map;
563 	u64 chunk_offset = cache->start;
564 	int num_extents, cur_extent;
565 	int i;
566 
567 	/* Do not use "to_copy" on non zoned filesystem for now */
568 	if (!btrfs_is_zoned(fs_info))
569 		return true;
570 
571 	spin_lock(&cache->lock);
572 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &cache->runtime_flags)) {
573 		spin_unlock(&cache->lock);
574 		return true;
575 	}
576 	spin_unlock(&cache->lock);
577 
578 	em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
579 	ASSERT(!IS_ERR(em));
580 	map = em->map_lookup;
581 
582 	num_extents = 0;
583 	cur_extent = 0;
584 	for (i = 0; i < map->num_stripes; i++) {
585 		/* We have more device extent to copy */
586 		if (srcdev != map->stripes[i].dev)
587 			continue;
588 
589 		num_extents++;
590 		if (physical == map->stripes[i].physical)
591 			cur_extent = i;
592 	}
593 
594 	free_extent_map(em);
595 
596 	if (num_extents > 1 && cur_extent < num_extents - 1) {
597 		/*
598 		 * Has more stripes on this device. Keep this block group
599 		 * readonly until we finish all the stripes.
600 		 */
601 		return false;
602 	}
603 
604 	/* Last stripe on this device */
605 	clear_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
606 
607 	return true;
608 }
609 
610 static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
611 		const char *tgtdev_name, u64 srcdevid, const char *srcdev_name,
612 		int read_src)
613 {
614 	struct btrfs_root *root = fs_info->dev_root;
615 	struct btrfs_trans_handle *trans;
616 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
617 	int ret;
618 	struct btrfs_device *tgt_device = NULL;
619 	struct btrfs_device *src_device = NULL;
620 
621 	src_device = btrfs_find_device_by_devspec(fs_info, srcdevid,
622 						  srcdev_name);
623 	if (IS_ERR(src_device))
624 		return PTR_ERR(src_device);
625 
626 	if (btrfs_pinned_by_swapfile(fs_info, src_device)) {
627 		btrfs_warn_in_rcu(fs_info,
628 	  "cannot replace device %s (devid %llu) due to active swapfile",
629 			btrfs_dev_name(src_device), src_device->devid);
630 		return -ETXTBSY;
631 	}
632 
633 	/*
634 	 * Here we commit the transaction to make sure commit_total_bytes
635 	 * of all the devices are updated.
636 	 */
637 	trans = btrfs_attach_transaction(root);
638 	if (!IS_ERR(trans)) {
639 		ret = btrfs_commit_transaction(trans);
640 		if (ret)
641 			return ret;
642 	} else if (PTR_ERR(trans) != -ENOENT) {
643 		return PTR_ERR(trans);
644 	}
645 
646 	ret = btrfs_init_dev_replace_tgtdev(fs_info, tgtdev_name,
647 					    src_device, &tgt_device);
648 	if (ret)
649 		return ret;
650 
651 	ret = mark_block_group_to_copy(fs_info, src_device);
652 	if (ret)
653 		return ret;
654 
655 	down_write(&dev_replace->rwsem);
656 	switch (dev_replace->replace_state) {
657 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
658 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
659 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
660 		break;
661 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
662 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
663 		ASSERT(0);
664 		ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED;
665 		up_write(&dev_replace->rwsem);
666 		goto leave;
667 	}
668 
669 	dev_replace->cont_reading_from_srcdev_mode = read_src;
670 	dev_replace->srcdev = src_device;
671 	dev_replace->tgtdev = tgt_device;
672 
673 	btrfs_info_in_rcu(fs_info,
674 		      "dev_replace from %s (devid %llu) to %s started",
675 		      btrfs_dev_name(src_device),
676 		      src_device->devid,
677 		      rcu_str_deref(tgt_device->name));
678 
679 	/*
680 	 * from now on, the writes to the srcdev are all duplicated to
681 	 * go to the tgtdev as well (refer to btrfs_map_block()).
682 	 */
683 	dev_replace->replace_state = BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
684 	dev_replace->time_started = ktime_get_real_seconds();
685 	dev_replace->cursor_left = 0;
686 	dev_replace->committed_cursor_left = 0;
687 	dev_replace->cursor_left_last_write_of_item = 0;
688 	dev_replace->cursor_right = 0;
689 	dev_replace->is_valid = 1;
690 	dev_replace->item_needs_writeback = 1;
691 	atomic64_set(&dev_replace->num_write_errors, 0);
692 	atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
693 	up_write(&dev_replace->rwsem);
694 
695 	ret = btrfs_sysfs_add_device(tgt_device);
696 	if (ret)
697 		btrfs_err(fs_info, "kobj add dev failed %d", ret);
698 
699 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
700 
701 	/*
702 	 * Commit dev_replace state and reserve 1 item for it.
703 	 * This is crucial to ensure we won't miss copying extents for new block
704 	 * groups that are allocated after we started the device replace, and
705 	 * must be done after setting up the device replace state.
706 	 */
707 	trans = btrfs_start_transaction(root, 1);
708 	if (IS_ERR(trans)) {
709 		ret = PTR_ERR(trans);
710 		down_write(&dev_replace->rwsem);
711 		dev_replace->replace_state =
712 			BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
713 		dev_replace->srcdev = NULL;
714 		dev_replace->tgtdev = NULL;
715 		up_write(&dev_replace->rwsem);
716 		goto leave;
717 	}
718 
719 	ret = btrfs_commit_transaction(trans);
720 	WARN_ON(ret);
721 
722 	/* the disk copy procedure reuses the scrub code */
723 	ret = btrfs_scrub_dev(fs_info, src_device->devid, 0,
724 			      btrfs_device_get_total_bytes(src_device),
725 			      &dev_replace->scrub_progress, 0, 1);
726 
727 	ret = btrfs_dev_replace_finishing(fs_info, ret);
728 	if (ret == -EINPROGRESS)
729 		ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS;
730 
731 	return ret;
732 
733 leave:
734 	btrfs_destroy_dev_replace_tgtdev(tgt_device);
735 	return ret;
736 }
737 
738 int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
739 			    struct btrfs_ioctl_dev_replace_args *args)
740 {
741 	int ret;
742 
743 	switch (args->start.cont_reading_from_srcdev_mode) {
744 	case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
745 	case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
746 		break;
747 	default:
748 		return -EINVAL;
749 	}
750 
751 	if ((args->start.srcdevid == 0 && args->start.srcdev_name[0] == '\0') ||
752 	    args->start.tgtdev_name[0] == '\0')
753 		return -EINVAL;
754 
755 	ret = btrfs_dev_replace_start(fs_info, args->start.tgtdev_name,
756 					args->start.srcdevid,
757 					args->start.srcdev_name,
758 					args->start.cont_reading_from_srcdev_mode);
759 	args->result = ret;
760 	/* don't warn if EINPROGRESS, someone else might be running scrub */
761 	if (ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS ||
762 	    ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR)
763 		return 0;
764 
765 	return ret;
766 }
767 
768 /*
769  * blocked until all in-flight bios operations are finished.
770  */
771 static void btrfs_rm_dev_replace_blocked(struct btrfs_fs_info *fs_info)
772 {
773 	set_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
774 	wait_event(fs_info->dev_replace.replace_wait, !percpu_counter_sum(
775 		   &fs_info->dev_replace.bio_counter));
776 }
777 
778 /*
779  * we have removed target device, it is safe to allow new bios request.
780  */
781 static void btrfs_rm_dev_replace_unblocked(struct btrfs_fs_info *fs_info)
782 {
783 	clear_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
784 	wake_up(&fs_info->dev_replace.replace_wait);
785 }
786 
787 /*
788  * When finishing the device replace, before swapping the source device with the
789  * target device we must update the chunk allocation state in the target device,
790  * as it is empty because replace works by directly copying the chunks and not
791  * through the normal chunk allocation path.
792  */
793 static int btrfs_set_target_alloc_state(struct btrfs_device *srcdev,
794 					struct btrfs_device *tgtdev)
795 {
796 	struct extent_state *cached_state = NULL;
797 	u64 start = 0;
798 	u64 found_start;
799 	u64 found_end;
800 	int ret = 0;
801 
802 	lockdep_assert_held(&srcdev->fs_info->chunk_mutex);
803 
804 	while (!find_first_extent_bit(&srcdev->alloc_state, start,
805 				      &found_start, &found_end,
806 				      CHUNK_ALLOCATED, &cached_state)) {
807 		ret = set_extent_bits(&tgtdev->alloc_state, found_start,
808 				      found_end, CHUNK_ALLOCATED);
809 		if (ret)
810 			break;
811 		start = found_end + 1;
812 	}
813 
814 	free_extent_state(cached_state);
815 	return ret;
816 }
817 
818 static void btrfs_dev_replace_update_device_in_mapping_tree(
819 						struct btrfs_fs_info *fs_info,
820 						struct btrfs_device *srcdev,
821 						struct btrfs_device *tgtdev)
822 {
823 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
824 	struct extent_map *em;
825 	struct map_lookup *map;
826 	u64 start = 0;
827 	int i;
828 
829 	write_lock(&em_tree->lock);
830 	do {
831 		em = lookup_extent_mapping(em_tree, start, (u64)-1);
832 		if (!em)
833 			break;
834 		map = em->map_lookup;
835 		for (i = 0; i < map->num_stripes; i++)
836 			if (srcdev == map->stripes[i].dev)
837 				map->stripes[i].dev = tgtdev;
838 		start = em->start + em->len;
839 		free_extent_map(em);
840 	} while (start);
841 	write_unlock(&em_tree->lock);
842 }
843 
844 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
845 				       int scrub_ret)
846 {
847 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
848 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
849 	struct btrfs_device *tgt_device;
850 	struct btrfs_device *src_device;
851 	struct btrfs_root *root = fs_info->tree_root;
852 	u8 uuid_tmp[BTRFS_UUID_SIZE];
853 	struct btrfs_trans_handle *trans;
854 	int ret = 0;
855 
856 	/* don't allow cancel or unmount to disturb the finishing procedure */
857 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
858 
859 	down_read(&dev_replace->rwsem);
860 	/* was the operation canceled, or is it finished? */
861 	if (dev_replace->replace_state !=
862 	    BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED) {
863 		up_read(&dev_replace->rwsem);
864 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
865 		return 0;
866 	}
867 
868 	tgt_device = dev_replace->tgtdev;
869 	src_device = dev_replace->srcdev;
870 	up_read(&dev_replace->rwsem);
871 
872 	/*
873 	 * flush all outstanding I/O and inode extent mappings before the
874 	 * copy operation is declared as being finished
875 	 */
876 	ret = btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
877 	if (ret) {
878 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
879 		return ret;
880 	}
881 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
882 
883 	/*
884 	 * We have to use this loop approach because at this point src_device
885 	 * has to be available for transaction commit to complete, yet new
886 	 * chunks shouldn't be allocated on the device.
887 	 */
888 	while (1) {
889 		trans = btrfs_start_transaction(root, 0);
890 		if (IS_ERR(trans)) {
891 			mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
892 			return PTR_ERR(trans);
893 		}
894 		ret = btrfs_commit_transaction(trans);
895 		WARN_ON(ret);
896 
897 		/* Prevent write_all_supers() during the finishing procedure */
898 		mutex_lock(&fs_devices->device_list_mutex);
899 		/* Prevent new chunks being allocated on the source device */
900 		mutex_lock(&fs_info->chunk_mutex);
901 
902 		if (!list_empty(&src_device->post_commit_list)) {
903 			mutex_unlock(&fs_devices->device_list_mutex);
904 			mutex_unlock(&fs_info->chunk_mutex);
905 		} else {
906 			break;
907 		}
908 	}
909 
910 	down_write(&dev_replace->rwsem);
911 	dev_replace->replace_state =
912 		scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
913 			  : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
914 	dev_replace->tgtdev = NULL;
915 	dev_replace->srcdev = NULL;
916 	dev_replace->time_stopped = ktime_get_real_seconds();
917 	dev_replace->item_needs_writeback = 1;
918 
919 	/*
920 	 * Update allocation state in the new device and replace the old device
921 	 * with the new one in the mapping tree.
922 	 */
923 	if (!scrub_ret) {
924 		scrub_ret = btrfs_set_target_alloc_state(src_device, tgt_device);
925 		if (scrub_ret)
926 			goto error;
927 		btrfs_dev_replace_update_device_in_mapping_tree(fs_info,
928 								src_device,
929 								tgt_device);
930 	} else {
931 		if (scrub_ret != -ECANCELED)
932 			btrfs_err_in_rcu(fs_info,
933 				 "btrfs_scrub_dev(%s, %llu, %s) failed %d",
934 				 btrfs_dev_name(src_device),
935 				 src_device->devid,
936 				 rcu_str_deref(tgt_device->name), scrub_ret);
937 error:
938 		up_write(&dev_replace->rwsem);
939 		mutex_unlock(&fs_info->chunk_mutex);
940 		mutex_unlock(&fs_devices->device_list_mutex);
941 		btrfs_rm_dev_replace_blocked(fs_info);
942 		if (tgt_device)
943 			btrfs_destroy_dev_replace_tgtdev(tgt_device);
944 		btrfs_rm_dev_replace_unblocked(fs_info);
945 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
946 
947 		return scrub_ret;
948 	}
949 
950 	btrfs_info_in_rcu(fs_info,
951 			  "dev_replace from %s (devid %llu) to %s finished",
952 			  btrfs_dev_name(src_device),
953 			  src_device->devid,
954 			  rcu_str_deref(tgt_device->name));
955 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &tgt_device->dev_state);
956 	tgt_device->devid = src_device->devid;
957 	src_device->devid = BTRFS_DEV_REPLACE_DEVID;
958 	memcpy(uuid_tmp, tgt_device->uuid, sizeof(uuid_tmp));
959 	memcpy(tgt_device->uuid, src_device->uuid, sizeof(tgt_device->uuid));
960 	memcpy(src_device->uuid, uuid_tmp, sizeof(src_device->uuid));
961 	btrfs_device_set_total_bytes(tgt_device, src_device->total_bytes);
962 	btrfs_device_set_disk_total_bytes(tgt_device,
963 					  src_device->disk_total_bytes);
964 	btrfs_device_set_bytes_used(tgt_device, src_device->bytes_used);
965 	tgt_device->commit_bytes_used = src_device->bytes_used;
966 
967 	btrfs_assign_next_active_device(src_device, tgt_device);
968 
969 	list_add(&tgt_device->dev_alloc_list, &fs_devices->alloc_list);
970 	fs_devices->rw_devices++;
971 
972 	up_write(&dev_replace->rwsem);
973 	btrfs_rm_dev_replace_blocked(fs_info);
974 
975 	btrfs_rm_dev_replace_remove_srcdev(src_device);
976 
977 	btrfs_rm_dev_replace_unblocked(fs_info);
978 
979 	/*
980 	 * Increment dev_stats_ccnt so that btrfs_run_dev_stats() will
981 	 * update on-disk dev stats value during commit transaction
982 	 */
983 	atomic_inc(&tgt_device->dev_stats_ccnt);
984 
985 	/*
986 	 * this is again a consistent state where no dev_replace procedure
987 	 * is running, the target device is part of the filesystem, the
988 	 * source device is not part of the filesystem anymore and its 1st
989 	 * superblock is scratched out so that it is no longer marked to
990 	 * belong to this filesystem.
991 	 */
992 	mutex_unlock(&fs_info->chunk_mutex);
993 	mutex_unlock(&fs_devices->device_list_mutex);
994 
995 	/* replace the sysfs entry */
996 	btrfs_sysfs_remove_device(src_device);
997 	btrfs_sysfs_update_devid(tgt_device);
998 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &src_device->dev_state))
999 		btrfs_scratch_superblocks(fs_info, src_device->bdev,
1000 					  src_device->name->str);
1001 
1002 	/* write back the superblocks */
1003 	trans = btrfs_start_transaction(root, 0);
1004 	if (!IS_ERR(trans))
1005 		btrfs_commit_transaction(trans);
1006 
1007 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1008 
1009 	btrfs_rm_dev_replace_free_srcdev(src_device);
1010 
1011 	return 0;
1012 }
1013 
1014 /*
1015  * Read progress of device replace status according to the state and last
1016  * stored position. The value format is the same as for
1017  * btrfs_dev_replace::progress_1000
1018  */
1019 static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info)
1020 {
1021 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1022 	u64 ret = 0;
1023 
1024 	switch (dev_replace->replace_state) {
1025 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1026 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1027 		ret = 0;
1028 		break;
1029 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1030 		ret = 1000;
1031 		break;
1032 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1033 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1034 		ret = div64_u64(dev_replace->cursor_left,
1035 				div_u64(btrfs_device_get_total_bytes(
1036 						dev_replace->srcdev), 1000));
1037 		break;
1038 	}
1039 
1040 	return ret;
1041 }
1042 
1043 void btrfs_dev_replace_status(struct btrfs_fs_info *fs_info,
1044 			      struct btrfs_ioctl_dev_replace_args *args)
1045 {
1046 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1047 
1048 	down_read(&dev_replace->rwsem);
1049 	/* even if !dev_replace_is_valid, the values are good enough for
1050 	 * the replace_status ioctl */
1051 	args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1052 	args->status.replace_state = dev_replace->replace_state;
1053 	args->status.time_started = dev_replace->time_started;
1054 	args->status.time_stopped = dev_replace->time_stopped;
1055 	args->status.num_write_errors =
1056 		atomic64_read(&dev_replace->num_write_errors);
1057 	args->status.num_uncorrectable_read_errors =
1058 		atomic64_read(&dev_replace->num_uncorrectable_read_errors);
1059 	args->status.progress_1000 = btrfs_dev_replace_progress(fs_info);
1060 	up_read(&dev_replace->rwsem);
1061 }
1062 
1063 int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
1064 {
1065 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1066 	struct btrfs_device *tgt_device = NULL;
1067 	struct btrfs_device *src_device = NULL;
1068 	struct btrfs_trans_handle *trans;
1069 	struct btrfs_root *root = fs_info->tree_root;
1070 	int result;
1071 	int ret;
1072 
1073 	if (sb_rdonly(fs_info->sb))
1074 		return -EROFS;
1075 
1076 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
1077 	down_write(&dev_replace->rwsem);
1078 	switch (dev_replace->replace_state) {
1079 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1080 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1081 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1082 		result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
1083 		up_write(&dev_replace->rwsem);
1084 		break;
1085 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1086 		tgt_device = dev_replace->tgtdev;
1087 		src_device = dev_replace->srcdev;
1088 		up_write(&dev_replace->rwsem);
1089 		ret = btrfs_scrub_cancel(fs_info);
1090 		if (ret < 0) {
1091 			result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
1092 		} else {
1093 			result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1094 			/*
1095 			 * btrfs_dev_replace_finishing() will handle the
1096 			 * cleanup part
1097 			 */
1098 			btrfs_info_in_rcu(fs_info,
1099 				"dev_replace from %s (devid %llu) to %s canceled",
1100 				btrfs_dev_name(src_device), src_device->devid,
1101 				btrfs_dev_name(tgt_device));
1102 		}
1103 		break;
1104 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1105 		/*
1106 		 * Scrub doing the replace isn't running so we need to do the
1107 		 * cleanup step of btrfs_dev_replace_finishing() here
1108 		 */
1109 		result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
1110 		tgt_device = dev_replace->tgtdev;
1111 		src_device = dev_replace->srcdev;
1112 		dev_replace->tgtdev = NULL;
1113 		dev_replace->srcdev = NULL;
1114 		dev_replace->replace_state =
1115 				BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED;
1116 		dev_replace->time_stopped = ktime_get_real_seconds();
1117 		dev_replace->item_needs_writeback = 1;
1118 
1119 		up_write(&dev_replace->rwsem);
1120 
1121 		/* Scrub for replace must not be running in suspended state */
1122 		btrfs_scrub_cancel(fs_info);
1123 
1124 		trans = btrfs_start_transaction(root, 0);
1125 		if (IS_ERR(trans)) {
1126 			mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1127 			return PTR_ERR(trans);
1128 		}
1129 		ret = btrfs_commit_transaction(trans);
1130 		WARN_ON(ret);
1131 
1132 		btrfs_info_in_rcu(fs_info,
1133 		"suspended dev_replace from %s (devid %llu) to %s canceled",
1134 			btrfs_dev_name(src_device), src_device->devid,
1135 			btrfs_dev_name(tgt_device));
1136 
1137 		if (tgt_device)
1138 			btrfs_destroy_dev_replace_tgtdev(tgt_device);
1139 		break;
1140 	default:
1141 		up_write(&dev_replace->rwsem);
1142 		result = -EINVAL;
1143 	}
1144 
1145 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1146 	return result;
1147 }
1148 
1149 void btrfs_dev_replace_suspend_for_unmount(struct btrfs_fs_info *fs_info)
1150 {
1151 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1152 
1153 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
1154 	down_write(&dev_replace->rwsem);
1155 
1156 	switch (dev_replace->replace_state) {
1157 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1158 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1159 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1160 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1161 		break;
1162 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1163 		dev_replace->replace_state =
1164 			BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1165 		dev_replace->time_stopped = ktime_get_real_seconds();
1166 		dev_replace->item_needs_writeback = 1;
1167 		btrfs_info(fs_info, "suspending dev_replace for unmount");
1168 		break;
1169 	}
1170 
1171 	up_write(&dev_replace->rwsem);
1172 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
1173 }
1174 
1175 /* resume dev_replace procedure that was interrupted by unmount */
1176 int btrfs_resume_dev_replace_async(struct btrfs_fs_info *fs_info)
1177 {
1178 	struct task_struct *task;
1179 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1180 
1181 	down_write(&dev_replace->rwsem);
1182 
1183 	switch (dev_replace->replace_state) {
1184 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1185 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1186 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1187 		up_write(&dev_replace->rwsem);
1188 		return 0;
1189 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1190 		break;
1191 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1192 		dev_replace->replace_state =
1193 			BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
1194 		break;
1195 	}
1196 	if (!dev_replace->tgtdev || !dev_replace->tgtdev->bdev) {
1197 		btrfs_info(fs_info,
1198 			   "cannot continue dev_replace, tgtdev is missing");
1199 		btrfs_info(fs_info,
1200 			   "you may cancel the operation after 'mount -o degraded'");
1201 		dev_replace->replace_state =
1202 					BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1203 		up_write(&dev_replace->rwsem);
1204 		return 0;
1205 	}
1206 	up_write(&dev_replace->rwsem);
1207 
1208 	/*
1209 	 * This could collide with a paused balance, but the exclusive op logic
1210 	 * should never allow both to start and pause. We don't want to allow
1211 	 * dev-replace to start anyway.
1212 	 */
1213 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_DEV_REPLACE)) {
1214 		down_write(&dev_replace->rwsem);
1215 		dev_replace->replace_state =
1216 					BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1217 		up_write(&dev_replace->rwsem);
1218 		btrfs_info(fs_info,
1219 		"cannot resume dev-replace, other exclusive operation running");
1220 		return 0;
1221 	}
1222 
1223 	task = kthread_run(btrfs_dev_replace_kthread, fs_info, "btrfs-devrepl");
1224 	return PTR_ERR_OR_ZERO(task);
1225 }
1226 
1227 static int btrfs_dev_replace_kthread(void *data)
1228 {
1229 	struct btrfs_fs_info *fs_info = data;
1230 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1231 	u64 progress;
1232 	int ret;
1233 
1234 	progress = btrfs_dev_replace_progress(fs_info);
1235 	progress = div_u64(progress, 10);
1236 	btrfs_info_in_rcu(fs_info,
1237 		"continuing dev_replace from %s (devid %llu) to target %s @%u%%",
1238 		btrfs_dev_name(dev_replace->srcdev),
1239 		dev_replace->srcdev->devid,
1240 		btrfs_dev_name(dev_replace->tgtdev),
1241 		(unsigned int)progress);
1242 
1243 	ret = btrfs_scrub_dev(fs_info, dev_replace->srcdev->devid,
1244 			      dev_replace->committed_cursor_left,
1245 			      btrfs_device_get_total_bytes(dev_replace->srcdev),
1246 			      &dev_replace->scrub_progress, 0, 1);
1247 	ret = btrfs_dev_replace_finishing(fs_info, ret);
1248 	WARN_ON(ret && ret != -ECANCELED);
1249 
1250 	btrfs_exclop_finish(fs_info);
1251 	return 0;
1252 }
1253 
1254 int __pure btrfs_dev_replace_is_ongoing(struct btrfs_dev_replace *dev_replace)
1255 {
1256 	if (!dev_replace->is_valid)
1257 		return 0;
1258 
1259 	switch (dev_replace->replace_state) {
1260 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1261 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1262 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1263 		return 0;
1264 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1265 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1266 		/*
1267 		 * return true even if tgtdev is missing (this is
1268 		 * something that can happen if the dev_replace
1269 		 * procedure is suspended by an umount and then
1270 		 * the tgtdev is missing (or "btrfs dev scan") was
1271 		 * not called and the filesystem is remounted
1272 		 * in degraded state. This does not stop the
1273 		 * dev_replace procedure. It needs to be canceled
1274 		 * manually if the cancellation is wanted.
1275 		 */
1276 		break;
1277 	}
1278 	return 1;
1279 }
1280 
1281 void btrfs_bio_counter_sub(struct btrfs_fs_info *fs_info, s64 amount)
1282 {
1283 	percpu_counter_sub(&fs_info->dev_replace.bio_counter, amount);
1284 	cond_wake_up_nomb(&fs_info->dev_replace.replace_wait);
1285 }
1286 
1287 void btrfs_bio_counter_inc_blocked(struct btrfs_fs_info *fs_info)
1288 {
1289 	while (1) {
1290 		percpu_counter_inc(&fs_info->dev_replace.bio_counter);
1291 		if (likely(!test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1292 				     &fs_info->fs_state)))
1293 			break;
1294 
1295 		btrfs_bio_counter_dec(fs_info);
1296 		wait_event(fs_info->dev_replace.replace_wait,
1297 			   !test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1298 				     &fs_info->fs_state));
1299 	}
1300 }
1301