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