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