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