xref: /openbmc/linux/fs/btrfs/dev-replace.c (revision 4546bcae)
1 /*
2  * Copyright (C) STRATO AG 2012.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 #include <linux/sched.h>
19 #include <linux/bio.h>
20 #include <linux/slab.h>
21 #include <linux/buffer_head.h>
22 #include <linux/blkdev.h>
23 #include <linux/random.h>
24 #include <linux/iocontext.h>
25 #include <linux/capability.h>
26 #include <linux/kthread.h>
27 #include <linux/math64.h>
28 #include <asm/div64.h>
29 #include "compat.h"
30 #include "ctree.h"
31 #include "extent_map.h"
32 #include "disk-io.h"
33 #include "transaction.h"
34 #include "print-tree.h"
35 #include "volumes.h"
36 #include "async-thread.h"
37 #include "check-integrity.h"
38 #include "rcu-string.h"
39 #include "dev-replace.h"
40 
41 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
42 				       int scrub_ret);
43 static void btrfs_dev_replace_update_device_in_mapping_tree(
44 						struct btrfs_fs_info *fs_info,
45 						struct btrfs_device *srcdev,
46 						struct btrfs_device *tgtdev);
47 static int btrfs_dev_replace_find_srcdev(struct btrfs_root *root, u64 srcdevid,
48 					 char *srcdev_name,
49 					 struct btrfs_device **device);
50 static u64 __btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info);
51 static int btrfs_dev_replace_kthread(void *data);
52 static int btrfs_dev_replace_continue_on_mount(struct btrfs_fs_info *fs_info);
53 
54 
55 int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
56 {
57 	struct btrfs_key key;
58 	struct btrfs_root *dev_root = fs_info->dev_root;
59 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
60 	struct extent_buffer *eb;
61 	int slot;
62 	int ret = 0;
63 	struct btrfs_path *path = NULL;
64 	int item_size;
65 	struct btrfs_dev_replace_item *ptr;
66 	u64 src_devid;
67 
68 	path = btrfs_alloc_path();
69 	if (!path) {
70 		ret = -ENOMEM;
71 		goto out;
72 	}
73 
74 	key.objectid = 0;
75 	key.type = BTRFS_DEV_REPLACE_KEY;
76 	key.offset = 0;
77 	ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
78 	if (ret) {
79 no_valid_dev_replace_entry_found:
80 		ret = 0;
81 		dev_replace->replace_state =
82 			BTRFS_DEV_REPLACE_ITEM_STATE_NEVER_STARTED;
83 		dev_replace->cont_reading_from_srcdev_mode =
84 		    BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
85 		dev_replace->replace_state = 0;
86 		dev_replace->time_started = 0;
87 		dev_replace->time_stopped = 0;
88 		atomic64_set(&dev_replace->num_write_errors, 0);
89 		atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
90 		dev_replace->cursor_left = 0;
91 		dev_replace->committed_cursor_left = 0;
92 		dev_replace->cursor_left_last_write_of_item = 0;
93 		dev_replace->cursor_right = 0;
94 		dev_replace->srcdev = NULL;
95 		dev_replace->tgtdev = NULL;
96 		dev_replace->is_valid = 0;
97 		dev_replace->item_needs_writeback = 0;
98 		goto out;
99 	}
100 	slot = path->slots[0];
101 	eb = path->nodes[0];
102 	item_size = btrfs_item_size_nr(eb, slot);
103 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item);
104 
105 	if (item_size != sizeof(struct btrfs_dev_replace_item)) {
106 		pr_warn("btrfs: dev_replace entry found has unexpected size, ignore entry\n");
107 		goto no_valid_dev_replace_entry_found;
108 	}
109 
110 	src_devid = btrfs_dev_replace_src_devid(eb, ptr);
111 	dev_replace->cont_reading_from_srcdev_mode =
112 		btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
113 	dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
114 	dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
115 	dev_replace->time_stopped =
116 		btrfs_dev_replace_time_stopped(eb, ptr);
117 	atomic64_set(&dev_replace->num_write_errors,
118 		     btrfs_dev_replace_num_write_errors(eb, ptr));
119 	atomic64_set(&dev_replace->num_uncorrectable_read_errors,
120 		     btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr));
121 	dev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr);
122 	dev_replace->committed_cursor_left = dev_replace->cursor_left;
123 	dev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left;
124 	dev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr);
125 	dev_replace->is_valid = 1;
126 
127 	dev_replace->item_needs_writeback = 0;
128 	switch (dev_replace->replace_state) {
129 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
130 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
131 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
132 		dev_replace->srcdev = NULL;
133 		dev_replace->tgtdev = NULL;
134 		break;
135 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
136 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
137 		dev_replace->srcdev = btrfs_find_device(fs_info, src_devid,
138 							NULL, NULL);
139 		dev_replace->tgtdev = btrfs_find_device(fs_info,
140 							BTRFS_DEV_REPLACE_DEVID,
141 							NULL, NULL);
142 		/*
143 		 * allow 'btrfs dev replace_cancel' if src/tgt device is
144 		 * missing
145 		 */
146 		if (!dev_replace->srcdev &&
147 		    !btrfs_test_opt(dev_root, DEGRADED)) {
148 			ret = -EIO;
149 			pr_warn("btrfs: cannot mount because device replace operation is ongoing and\n" "srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?\n",
150 				src_devid);
151 		}
152 		if (!dev_replace->tgtdev &&
153 		    !btrfs_test_opt(dev_root, DEGRADED)) {
154 			ret = -EIO;
155 			pr_warn("btrfs: cannot mount because device replace operation is ongoing and\n" "tgtdev (devid %llu) is missing, need to run btrfs dev scan?\n",
156 				BTRFS_DEV_REPLACE_DEVID);
157 		}
158 		if (dev_replace->tgtdev) {
159 			if (dev_replace->srcdev) {
160 				dev_replace->tgtdev->total_bytes =
161 					dev_replace->srcdev->total_bytes;
162 				dev_replace->tgtdev->disk_total_bytes =
163 					dev_replace->srcdev->disk_total_bytes;
164 				dev_replace->tgtdev->bytes_used =
165 					dev_replace->srcdev->bytes_used;
166 			}
167 			dev_replace->tgtdev->is_tgtdev_for_dev_replace = 1;
168 			btrfs_init_dev_replace_tgtdev_for_resume(fs_info,
169 				dev_replace->tgtdev);
170 		}
171 		break;
172 	}
173 
174 out:
175 	if (path)
176 		btrfs_free_path(path);
177 	return ret;
178 }
179 
180 /*
181  * called from commit_transaction. Writes changed device replace state to
182  * disk.
183  */
184 int btrfs_run_dev_replace(struct btrfs_trans_handle *trans,
185 			  struct btrfs_fs_info *fs_info)
186 {
187 	int ret;
188 	struct btrfs_root *dev_root = fs_info->dev_root;
189 	struct btrfs_path *path;
190 	struct btrfs_key key;
191 	struct extent_buffer *eb;
192 	struct btrfs_dev_replace_item *ptr;
193 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
194 
195 	btrfs_dev_replace_lock(dev_replace);
196 	if (!dev_replace->is_valid ||
197 	    !dev_replace->item_needs_writeback) {
198 		btrfs_dev_replace_unlock(dev_replace);
199 		return 0;
200 	}
201 	btrfs_dev_replace_unlock(dev_replace);
202 
203 	key.objectid = 0;
204 	key.type = BTRFS_DEV_REPLACE_KEY;
205 	key.offset = 0;
206 
207 	path = btrfs_alloc_path();
208 	if (!path) {
209 		ret = -ENOMEM;
210 		goto out;
211 	}
212 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
213 	if (ret < 0) {
214 		pr_warn("btrfs: error %d while searching for dev_replace item!\n",
215 			ret);
216 		goto out;
217 	}
218 
219 	if (ret == 0 &&
220 	    btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
221 		/*
222 		 * need to delete old one and insert a new one.
223 		 * Since no attempt is made to recover any old state, if the
224 		 * dev_replace state is 'running', the data on the target
225 		 * drive is lost.
226 		 * It would be possible to recover the state: just make sure
227 		 * that the beginning of the item is never changed and always
228 		 * contains all the essential information. Then read this
229 		 * minimal set of information and use it as a base for the
230 		 * new state.
231 		 */
232 		ret = btrfs_del_item(trans, dev_root, path);
233 		if (ret != 0) {
234 			pr_warn("btrfs: delete too small dev_replace item failed %d!\n",
235 				ret);
236 			goto out;
237 		}
238 		ret = 1;
239 	}
240 
241 	if (ret == 1) {
242 		/* need to insert a new item */
243 		btrfs_release_path(path);
244 		ret = btrfs_insert_empty_item(trans, dev_root, path,
245 					      &key, sizeof(*ptr));
246 		if (ret < 0) {
247 			pr_warn("btrfs: insert dev_replace item failed %d!\n",
248 				ret);
249 			goto out;
250 		}
251 	}
252 
253 	eb = path->nodes[0];
254 	ptr = btrfs_item_ptr(eb, path->slots[0],
255 			     struct btrfs_dev_replace_item);
256 
257 	btrfs_dev_replace_lock(dev_replace);
258 	if (dev_replace->srcdev)
259 		btrfs_set_dev_replace_src_devid(eb, ptr,
260 			dev_replace->srcdev->devid);
261 	else
262 		btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
263 	btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
264 		dev_replace->cont_reading_from_srcdev_mode);
265 	btrfs_set_dev_replace_replace_state(eb, ptr,
266 		dev_replace->replace_state);
267 	btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
268 	btrfs_set_dev_replace_time_stopped(eb, ptr, dev_replace->time_stopped);
269 	btrfs_set_dev_replace_num_write_errors(eb, ptr,
270 		atomic64_read(&dev_replace->num_write_errors));
271 	btrfs_set_dev_replace_num_uncorrectable_read_errors(eb, ptr,
272 		atomic64_read(&dev_replace->num_uncorrectable_read_errors));
273 	dev_replace->cursor_left_last_write_of_item =
274 		dev_replace->cursor_left;
275 	btrfs_set_dev_replace_cursor_left(eb, ptr,
276 		dev_replace->cursor_left_last_write_of_item);
277 	btrfs_set_dev_replace_cursor_right(eb, ptr,
278 		dev_replace->cursor_right);
279 	dev_replace->item_needs_writeback = 0;
280 	btrfs_dev_replace_unlock(dev_replace);
281 
282 	btrfs_mark_buffer_dirty(eb);
283 
284 out:
285 	btrfs_free_path(path);
286 
287 	return ret;
288 }
289 
290 void btrfs_after_dev_replace_commit(struct btrfs_fs_info *fs_info)
291 {
292 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
293 
294 	dev_replace->committed_cursor_left =
295 		dev_replace->cursor_left_last_write_of_item;
296 }
297 
298 int btrfs_dev_replace_start(struct btrfs_root *root,
299 			    struct btrfs_ioctl_dev_replace_args *args)
300 {
301 	struct btrfs_trans_handle *trans;
302 	struct btrfs_fs_info *fs_info = root->fs_info;
303 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
304 	int ret;
305 	struct btrfs_device *tgt_device = NULL;
306 	struct btrfs_device *src_device = NULL;
307 
308 	if (btrfs_fs_incompat(fs_info, RAID56)) {
309 		pr_warn("btrfs: dev_replace cannot yet handle RAID5/RAID6\n");
310 		return -EINVAL;
311 	}
312 
313 	switch (args->start.cont_reading_from_srcdev_mode) {
314 	case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
315 	case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
316 		break;
317 	default:
318 		return -EINVAL;
319 	}
320 
321 	if ((args->start.srcdevid == 0 && args->start.srcdev_name[0] == '\0') ||
322 	    args->start.tgtdev_name[0] == '\0')
323 		return -EINVAL;
324 
325 	mutex_lock(&fs_info->volume_mutex);
326 	ret = btrfs_init_dev_replace_tgtdev(root, args->start.tgtdev_name,
327 					    &tgt_device);
328 	if (ret) {
329 		pr_err("btrfs: target device %s is invalid!\n",
330 		       args->start.tgtdev_name);
331 		mutex_unlock(&fs_info->volume_mutex);
332 		return -EINVAL;
333 	}
334 
335 	ret = btrfs_dev_replace_find_srcdev(root, args->start.srcdevid,
336 					    args->start.srcdev_name,
337 					    &src_device);
338 	mutex_unlock(&fs_info->volume_mutex);
339 	if (ret) {
340 		ret = -EINVAL;
341 		goto leave_no_lock;
342 	}
343 
344 	if (tgt_device->total_bytes < src_device->total_bytes) {
345 		pr_err("btrfs: target device is smaller than source device!\n");
346 		ret = -EINVAL;
347 		goto leave_no_lock;
348 	}
349 
350 	btrfs_dev_replace_lock(dev_replace);
351 	switch (dev_replace->replace_state) {
352 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
353 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
354 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
355 		break;
356 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
357 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
358 		args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED;
359 		goto leave;
360 	}
361 
362 	dev_replace->cont_reading_from_srcdev_mode =
363 		args->start.cont_reading_from_srcdev_mode;
364 	WARN_ON(!src_device);
365 	dev_replace->srcdev = src_device;
366 	WARN_ON(!tgt_device);
367 	dev_replace->tgtdev = tgt_device;
368 
369 	printk_in_rcu(KERN_INFO
370 		      "btrfs: dev_replace from %s (devid %llu) to %s) started\n",
371 		      src_device->missing ? "<missing disk>" :
372 		        rcu_str_deref(src_device->name),
373 		      src_device->devid,
374 		      rcu_str_deref(tgt_device->name));
375 
376 	tgt_device->total_bytes = src_device->total_bytes;
377 	tgt_device->disk_total_bytes = src_device->disk_total_bytes;
378 	tgt_device->bytes_used = src_device->bytes_used;
379 
380 	/*
381 	 * from now on, the writes to the srcdev are all duplicated to
382 	 * go to the tgtdev as well (refer to btrfs_map_block()).
383 	 */
384 	dev_replace->replace_state = BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
385 	dev_replace->time_started = get_seconds();
386 	dev_replace->cursor_left = 0;
387 	dev_replace->committed_cursor_left = 0;
388 	dev_replace->cursor_left_last_write_of_item = 0;
389 	dev_replace->cursor_right = 0;
390 	dev_replace->is_valid = 1;
391 	dev_replace->item_needs_writeback = 1;
392 	args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
393 	btrfs_dev_replace_unlock(dev_replace);
394 
395 	btrfs_wait_all_ordered_extents(root->fs_info);
396 
397 	/* force writing the updated state information to disk */
398 	trans = btrfs_start_transaction(root, 0);
399 	if (IS_ERR(trans)) {
400 		ret = PTR_ERR(trans);
401 		btrfs_dev_replace_lock(dev_replace);
402 		goto leave;
403 	}
404 
405 	ret = btrfs_commit_transaction(trans, root);
406 	WARN_ON(ret);
407 
408 	/* the disk copy procedure reuses the scrub code */
409 	ret = btrfs_scrub_dev(fs_info, src_device->devid, 0,
410 			      src_device->total_bytes,
411 			      &dev_replace->scrub_progress, 0, 1);
412 
413 	ret = btrfs_dev_replace_finishing(root->fs_info, ret);
414 	WARN_ON(ret);
415 
416 	return 0;
417 
418 leave:
419 	dev_replace->srcdev = NULL;
420 	dev_replace->tgtdev = NULL;
421 	btrfs_dev_replace_unlock(dev_replace);
422 leave_no_lock:
423 	if (tgt_device)
424 		btrfs_destroy_dev_replace_tgtdev(fs_info, tgt_device);
425 	return ret;
426 }
427 
428 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
429 				       int scrub_ret)
430 {
431 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
432 	struct btrfs_device *tgt_device;
433 	struct btrfs_device *src_device;
434 	struct btrfs_root *root = fs_info->tree_root;
435 	u8 uuid_tmp[BTRFS_UUID_SIZE];
436 	struct btrfs_trans_handle *trans;
437 	int ret = 0;
438 
439 	/* don't allow cancel or unmount to disturb the finishing procedure */
440 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
441 
442 	btrfs_dev_replace_lock(dev_replace);
443 	/* was the operation canceled, or is it finished? */
444 	if (dev_replace->replace_state !=
445 	    BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED) {
446 		btrfs_dev_replace_unlock(dev_replace);
447 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
448 		return 0;
449 	}
450 
451 	tgt_device = dev_replace->tgtdev;
452 	src_device = dev_replace->srcdev;
453 	btrfs_dev_replace_unlock(dev_replace);
454 
455 	/* replace old device with new one in mapping tree */
456 	if (!scrub_ret)
457 		btrfs_dev_replace_update_device_in_mapping_tree(fs_info,
458 								src_device,
459 								tgt_device);
460 
461 	/*
462 	 * flush all outstanding I/O and inode extent mappings before the
463 	 * copy operation is declared as being finished
464 	 */
465 	ret = btrfs_start_all_delalloc_inodes(root->fs_info, 0);
466 	if (ret) {
467 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
468 		return ret;
469 	}
470 	btrfs_wait_all_ordered_extents(root->fs_info);
471 
472 	trans = btrfs_start_transaction(root, 0);
473 	if (IS_ERR(trans)) {
474 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
475 		return PTR_ERR(trans);
476 	}
477 	ret = btrfs_commit_transaction(trans, root);
478 	WARN_ON(ret);
479 
480 	/* keep away write_all_supers() during the finishing procedure */
481 	mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
482 	btrfs_dev_replace_lock(dev_replace);
483 	dev_replace->replace_state =
484 		scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
485 			  : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
486 	dev_replace->tgtdev = NULL;
487 	dev_replace->srcdev = NULL;
488 	dev_replace->time_stopped = get_seconds();
489 	dev_replace->item_needs_writeback = 1;
490 
491 	if (scrub_ret) {
492 		printk_in_rcu(KERN_ERR
493 			      "btrfs: btrfs_scrub_dev(%s, %llu, %s) failed %d\n",
494 			      src_device->missing ? "<missing disk>" :
495 			        rcu_str_deref(src_device->name),
496 			      src_device->devid,
497 			      rcu_str_deref(tgt_device->name), scrub_ret);
498 		btrfs_dev_replace_unlock(dev_replace);
499 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
500 		if (tgt_device)
501 			btrfs_destroy_dev_replace_tgtdev(fs_info, tgt_device);
502 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
503 
504 		return 0;
505 	}
506 
507 	printk_in_rcu(KERN_INFO
508 		      "btrfs: dev_replace from %s (devid %llu) to %s) finished\n",
509 		      src_device->missing ? "<missing disk>" :
510 		        rcu_str_deref(src_device->name),
511 		      src_device->devid,
512 		      rcu_str_deref(tgt_device->name));
513 	tgt_device->is_tgtdev_for_dev_replace = 0;
514 	tgt_device->devid = src_device->devid;
515 	src_device->devid = BTRFS_DEV_REPLACE_DEVID;
516 	tgt_device->bytes_used = src_device->bytes_used;
517 	memcpy(uuid_tmp, tgt_device->uuid, sizeof(uuid_tmp));
518 	memcpy(tgt_device->uuid, src_device->uuid, sizeof(tgt_device->uuid));
519 	memcpy(src_device->uuid, uuid_tmp, sizeof(src_device->uuid));
520 	tgt_device->total_bytes = src_device->total_bytes;
521 	tgt_device->disk_total_bytes = src_device->disk_total_bytes;
522 	tgt_device->bytes_used = src_device->bytes_used;
523 	if (fs_info->sb->s_bdev == src_device->bdev)
524 		fs_info->sb->s_bdev = tgt_device->bdev;
525 	if (fs_info->fs_devices->latest_bdev == src_device->bdev)
526 		fs_info->fs_devices->latest_bdev = tgt_device->bdev;
527 	list_add(&tgt_device->dev_alloc_list, &fs_info->fs_devices->alloc_list);
528 
529 	btrfs_rm_dev_replace_srcdev(fs_info, src_device);
530 
531 	/*
532 	 * this is again a consistent state where no dev_replace procedure
533 	 * is running, the target device is part of the filesystem, the
534 	 * source device is not part of the filesystem anymore and its 1st
535 	 * superblock is scratched out so that it is no longer marked to
536 	 * belong to this filesystem.
537 	 */
538 	btrfs_dev_replace_unlock(dev_replace);
539 	mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
540 
541 	/* write back the superblocks */
542 	trans = btrfs_start_transaction(root, 0);
543 	if (!IS_ERR(trans))
544 		btrfs_commit_transaction(trans, root);
545 
546 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
547 
548 	return 0;
549 }
550 
551 static void btrfs_dev_replace_update_device_in_mapping_tree(
552 						struct btrfs_fs_info *fs_info,
553 						struct btrfs_device *srcdev,
554 						struct btrfs_device *tgtdev)
555 {
556 	struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
557 	struct extent_map *em;
558 	struct map_lookup *map;
559 	u64 start = 0;
560 	int i;
561 
562 	write_lock(&em_tree->lock);
563 	do {
564 		em = lookup_extent_mapping(em_tree, start, (u64)-1);
565 		if (!em)
566 			break;
567 		map = (struct map_lookup *)em->bdev;
568 		for (i = 0; i < map->num_stripes; i++)
569 			if (srcdev == map->stripes[i].dev)
570 				map->stripes[i].dev = tgtdev;
571 		start = em->start + em->len;
572 		free_extent_map(em);
573 	} while (start);
574 	write_unlock(&em_tree->lock);
575 }
576 
577 static int btrfs_dev_replace_find_srcdev(struct btrfs_root *root, u64 srcdevid,
578 					 char *srcdev_name,
579 					 struct btrfs_device **device)
580 {
581 	int ret;
582 
583 	if (srcdevid) {
584 		ret = 0;
585 		*device = btrfs_find_device(root->fs_info, srcdevid, NULL,
586 					    NULL);
587 		if (!*device)
588 			ret = -ENOENT;
589 	} else {
590 		ret = btrfs_find_device_missing_or_by_path(root, srcdev_name,
591 							   device);
592 	}
593 	return ret;
594 }
595 
596 void btrfs_dev_replace_status(struct btrfs_fs_info *fs_info,
597 			      struct btrfs_ioctl_dev_replace_args *args)
598 {
599 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
600 
601 	btrfs_dev_replace_lock(dev_replace);
602 	/* even if !dev_replace_is_valid, the values are good enough for
603 	 * the replace_status ioctl */
604 	args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
605 	args->status.replace_state = dev_replace->replace_state;
606 	args->status.time_started = dev_replace->time_started;
607 	args->status.time_stopped = dev_replace->time_stopped;
608 	args->status.num_write_errors =
609 		atomic64_read(&dev_replace->num_write_errors);
610 	args->status.num_uncorrectable_read_errors =
611 		atomic64_read(&dev_replace->num_uncorrectable_read_errors);
612 	switch (dev_replace->replace_state) {
613 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
614 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
615 		args->status.progress_1000 = 0;
616 		break;
617 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
618 		args->status.progress_1000 = 1000;
619 		break;
620 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
621 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
622 		args->status.progress_1000 = div64_u64(dev_replace->cursor_left,
623 			div64_u64(dev_replace->srcdev->total_bytes, 1000));
624 		break;
625 	}
626 	btrfs_dev_replace_unlock(dev_replace);
627 }
628 
629 int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info,
630 			     struct btrfs_ioctl_dev_replace_args *args)
631 {
632 	args->result = __btrfs_dev_replace_cancel(fs_info);
633 	return 0;
634 }
635 
636 static u64 __btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
637 {
638 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
639 	struct btrfs_device *tgt_device = NULL;
640 	struct btrfs_trans_handle *trans;
641 	struct btrfs_root *root = fs_info->tree_root;
642 	u64 result;
643 	int ret;
644 
645 	if (fs_info->sb->s_flags & MS_RDONLY)
646 		return -EROFS;
647 
648 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
649 	btrfs_dev_replace_lock(dev_replace);
650 	switch (dev_replace->replace_state) {
651 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
652 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
653 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
654 		result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
655 		btrfs_dev_replace_unlock(dev_replace);
656 		goto leave;
657 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
658 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
659 		result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
660 		tgt_device = dev_replace->tgtdev;
661 		dev_replace->tgtdev = NULL;
662 		dev_replace->srcdev = NULL;
663 		break;
664 	}
665 	dev_replace->replace_state = BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED;
666 	dev_replace->time_stopped = get_seconds();
667 	dev_replace->item_needs_writeback = 1;
668 	btrfs_dev_replace_unlock(dev_replace);
669 	btrfs_scrub_cancel(fs_info);
670 
671 	trans = btrfs_start_transaction(root, 0);
672 	if (IS_ERR(trans)) {
673 		mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
674 		return PTR_ERR(trans);
675 	}
676 	ret = btrfs_commit_transaction(trans, root);
677 	WARN_ON(ret);
678 	if (tgt_device)
679 		btrfs_destroy_dev_replace_tgtdev(fs_info, tgt_device);
680 
681 leave:
682 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
683 	return result;
684 }
685 
686 void btrfs_dev_replace_suspend_for_unmount(struct btrfs_fs_info *fs_info)
687 {
688 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
689 
690 	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
691 	btrfs_dev_replace_lock(dev_replace);
692 	switch (dev_replace->replace_state) {
693 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
694 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
695 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
696 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
697 		break;
698 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
699 		dev_replace->replace_state =
700 			BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
701 		dev_replace->time_stopped = get_seconds();
702 		dev_replace->item_needs_writeback = 1;
703 		pr_info("btrfs: suspending dev_replace for unmount\n");
704 		break;
705 	}
706 
707 	btrfs_dev_replace_unlock(dev_replace);
708 	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
709 }
710 
711 /* resume dev_replace procedure that was interrupted by unmount */
712 int btrfs_resume_dev_replace_async(struct btrfs_fs_info *fs_info)
713 {
714 	struct task_struct *task;
715 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
716 
717 	btrfs_dev_replace_lock(dev_replace);
718 	switch (dev_replace->replace_state) {
719 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
720 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
721 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
722 		btrfs_dev_replace_unlock(dev_replace);
723 		return 0;
724 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
725 		break;
726 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
727 		dev_replace->replace_state =
728 			BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
729 		break;
730 	}
731 	if (!dev_replace->tgtdev || !dev_replace->tgtdev->bdev) {
732 		pr_info("btrfs: cannot continue dev_replace, tgtdev is missing\n"
733 			"btrfs: you may cancel the operation after 'mount -o degraded'\n");
734 		btrfs_dev_replace_unlock(dev_replace);
735 		return 0;
736 	}
737 	btrfs_dev_replace_unlock(dev_replace);
738 
739 	WARN_ON(atomic_xchg(
740 		&fs_info->mutually_exclusive_operation_running, 1));
741 	task = kthread_run(btrfs_dev_replace_kthread, fs_info, "btrfs-devrepl");
742 	return PTR_ERR_OR_ZERO(task);
743 }
744 
745 static int btrfs_dev_replace_kthread(void *data)
746 {
747 	struct btrfs_fs_info *fs_info = data;
748 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
749 	struct btrfs_ioctl_dev_replace_args *status_args;
750 	u64 progress;
751 
752 	status_args = kzalloc(sizeof(*status_args), GFP_NOFS);
753 	if (status_args) {
754 		btrfs_dev_replace_status(fs_info, status_args);
755 		progress = status_args->status.progress_1000;
756 		kfree(status_args);
757 		do_div(progress, 10);
758 		printk_in_rcu(KERN_INFO
759 			      "btrfs: continuing dev_replace from %s (devid %llu) to %s @%u%%\n",
760 			      dev_replace->srcdev->missing ? "<missing disk>" :
761 				rcu_str_deref(dev_replace->srcdev->name),
762 			      dev_replace->srcdev->devid,
763 			      dev_replace->tgtdev ?
764 				rcu_str_deref(dev_replace->tgtdev->name) :
765 				"<missing target disk>",
766 			      (unsigned int)progress);
767 	}
768 	btrfs_dev_replace_continue_on_mount(fs_info);
769 	atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
770 
771 	return 0;
772 }
773 
774 static int btrfs_dev_replace_continue_on_mount(struct btrfs_fs_info *fs_info)
775 {
776 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
777 	int ret;
778 
779 	ret = btrfs_scrub_dev(fs_info, dev_replace->srcdev->devid,
780 			      dev_replace->committed_cursor_left,
781 			      dev_replace->srcdev->total_bytes,
782 			      &dev_replace->scrub_progress, 0, 1);
783 	ret = btrfs_dev_replace_finishing(fs_info, ret);
784 	WARN_ON(ret);
785 	return 0;
786 }
787 
788 int btrfs_dev_replace_is_ongoing(struct btrfs_dev_replace *dev_replace)
789 {
790 	if (!dev_replace->is_valid)
791 		return 0;
792 
793 	switch (dev_replace->replace_state) {
794 	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
795 	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
796 	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
797 		return 0;
798 	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
799 	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
800 		/*
801 		 * return true even if tgtdev is missing (this is
802 		 * something that can happen if the dev_replace
803 		 * procedure is suspended by an umount and then
804 		 * the tgtdev is missing (or "btrfs dev scan") was
805 		 * not called and the the filesystem is remounted
806 		 * in degraded state. This does not stop the
807 		 * dev_replace procedure. It needs to be canceled
808 		 * manually if the cancelation is wanted.
809 		 */
810 		break;
811 	}
812 	return 1;
813 }
814 
815 void btrfs_dev_replace_lock(struct btrfs_dev_replace *dev_replace)
816 {
817 	/* the beginning is just an optimization for the typical case */
818 	if (atomic_read(&dev_replace->nesting_level) == 0) {
819 acquire_lock:
820 		/* this is not a nested case where the same thread
821 		 * is trying to acqurire the same lock twice */
822 		mutex_lock(&dev_replace->lock);
823 		mutex_lock(&dev_replace->lock_management_lock);
824 		dev_replace->lock_owner = current->pid;
825 		atomic_inc(&dev_replace->nesting_level);
826 		mutex_unlock(&dev_replace->lock_management_lock);
827 		return;
828 	}
829 
830 	mutex_lock(&dev_replace->lock_management_lock);
831 	if (atomic_read(&dev_replace->nesting_level) > 0 &&
832 	    dev_replace->lock_owner == current->pid) {
833 		WARN_ON(!mutex_is_locked(&dev_replace->lock));
834 		atomic_inc(&dev_replace->nesting_level);
835 		mutex_unlock(&dev_replace->lock_management_lock);
836 		return;
837 	}
838 
839 	mutex_unlock(&dev_replace->lock_management_lock);
840 	goto acquire_lock;
841 }
842 
843 void btrfs_dev_replace_unlock(struct btrfs_dev_replace *dev_replace)
844 {
845 	WARN_ON(!mutex_is_locked(&dev_replace->lock));
846 	mutex_lock(&dev_replace->lock_management_lock);
847 	WARN_ON(atomic_read(&dev_replace->nesting_level) < 1);
848 	WARN_ON(dev_replace->lock_owner != current->pid);
849 	atomic_dec(&dev_replace->nesting_level);
850 	if (atomic_read(&dev_replace->nesting_level) == 0) {
851 		dev_replace->lock_owner = 0;
852 		mutex_unlock(&dev_replace->lock_management_lock);
853 		mutex_unlock(&dev_replace->lock);
854 	} else {
855 		mutex_unlock(&dev_replace->lock_management_lock);
856 	}
857 }
858