xref: /openbmc/linux/fs/btrfs/volumes.c (revision 160b8e75)
1 /*
2  * Copyright (C) 2007 Oracle.  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/iocontext.h>
24 #include <linux/capability.h>
25 #include <linux/ratelimit.h>
26 #include <linux/kthread.h>
27 #include <linux/raid/pq.h>
28 #include <linux/semaphore.h>
29 #include <linux/uuid.h>
30 #include <asm/div64.h>
31 #include "ctree.h"
32 #include "extent_map.h"
33 #include "disk-io.h"
34 #include "transaction.h"
35 #include "print-tree.h"
36 #include "volumes.h"
37 #include "raid56.h"
38 #include "async-thread.h"
39 #include "check-integrity.h"
40 #include "rcu-string.h"
41 #include "math.h"
42 #include "dev-replace.h"
43 #include "sysfs.h"
44 
45 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
46 	[BTRFS_RAID_RAID10] = {
47 		.sub_stripes	= 2,
48 		.dev_stripes	= 1,
49 		.devs_max	= 0,	/* 0 == as many as possible */
50 		.devs_min	= 4,
51 		.tolerated_failures = 1,
52 		.devs_increment	= 2,
53 		.ncopies	= 2,
54 	},
55 	[BTRFS_RAID_RAID1] = {
56 		.sub_stripes	= 1,
57 		.dev_stripes	= 1,
58 		.devs_max	= 2,
59 		.devs_min	= 2,
60 		.tolerated_failures = 1,
61 		.devs_increment	= 2,
62 		.ncopies	= 2,
63 	},
64 	[BTRFS_RAID_DUP] = {
65 		.sub_stripes	= 1,
66 		.dev_stripes	= 2,
67 		.devs_max	= 1,
68 		.devs_min	= 1,
69 		.tolerated_failures = 0,
70 		.devs_increment	= 1,
71 		.ncopies	= 2,
72 	},
73 	[BTRFS_RAID_RAID0] = {
74 		.sub_stripes	= 1,
75 		.dev_stripes	= 1,
76 		.devs_max	= 0,
77 		.devs_min	= 2,
78 		.tolerated_failures = 0,
79 		.devs_increment	= 1,
80 		.ncopies	= 1,
81 	},
82 	[BTRFS_RAID_SINGLE] = {
83 		.sub_stripes	= 1,
84 		.dev_stripes	= 1,
85 		.devs_max	= 1,
86 		.devs_min	= 1,
87 		.tolerated_failures = 0,
88 		.devs_increment	= 1,
89 		.ncopies	= 1,
90 	},
91 	[BTRFS_RAID_RAID5] = {
92 		.sub_stripes	= 1,
93 		.dev_stripes	= 1,
94 		.devs_max	= 0,
95 		.devs_min	= 2,
96 		.tolerated_failures = 1,
97 		.devs_increment	= 1,
98 		.ncopies	= 2,
99 	},
100 	[BTRFS_RAID_RAID6] = {
101 		.sub_stripes	= 1,
102 		.dev_stripes	= 1,
103 		.devs_max	= 0,
104 		.devs_min	= 3,
105 		.tolerated_failures = 2,
106 		.devs_increment	= 1,
107 		.ncopies	= 3,
108 	},
109 };
110 
111 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
112 	[BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
113 	[BTRFS_RAID_RAID1]  = BTRFS_BLOCK_GROUP_RAID1,
114 	[BTRFS_RAID_DUP]    = BTRFS_BLOCK_GROUP_DUP,
115 	[BTRFS_RAID_RAID0]  = BTRFS_BLOCK_GROUP_RAID0,
116 	[BTRFS_RAID_SINGLE] = 0,
117 	[BTRFS_RAID_RAID5]  = BTRFS_BLOCK_GROUP_RAID5,
118 	[BTRFS_RAID_RAID6]  = BTRFS_BLOCK_GROUP_RAID6,
119 };
120 
121 /*
122  * Table to convert BTRFS_RAID_* to the error code if minimum number of devices
123  * condition is not met. Zero means there's no corresponding
124  * BTRFS_ERROR_DEV_*_NOT_MET value.
125  */
126 const int btrfs_raid_mindev_error[BTRFS_NR_RAID_TYPES] = {
127 	[BTRFS_RAID_RAID10] = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
128 	[BTRFS_RAID_RAID1]  = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
129 	[BTRFS_RAID_DUP]    = 0,
130 	[BTRFS_RAID_RAID0]  = 0,
131 	[BTRFS_RAID_SINGLE] = 0,
132 	[BTRFS_RAID_RAID5]  = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
133 	[BTRFS_RAID_RAID6]  = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
134 };
135 
136 static int init_first_rw_device(struct btrfs_trans_handle *trans,
137 				struct btrfs_fs_info *fs_info);
138 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
139 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
140 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
141 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
142 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
143 			     enum btrfs_map_op op,
144 			     u64 logical, u64 *length,
145 			     struct btrfs_bio **bbio_ret,
146 			     int mirror_num, int need_raid_map);
147 
148 /*
149  * Device locking
150  * ==============
151  *
152  * There are several mutexes that protect manipulation of devices and low-level
153  * structures like chunks but not block groups, extents or files
154  *
155  * uuid_mutex (global lock)
156  * ------------------------
157  * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
158  * the SCAN_DEV ioctl registration or from mount either implicitly (the first
159  * device) or requested by the device= mount option
160  *
161  * the mutex can be very coarse and can cover long-running operations
162  *
163  * protects: updates to fs_devices counters like missing devices, rw devices,
164  * seeding, structure cloning, openning/closing devices at mount/umount time
165  *
166  * global::fs_devs - add, remove, updates to the global list
167  *
168  * does not protect: manipulation of the fs_devices::devices list!
169  *
170  * btrfs_device::name - renames (write side), read is RCU
171  *
172  * fs_devices::device_list_mutex (per-fs, with RCU)
173  * ------------------------------------------------
174  * protects updates to fs_devices::devices, ie. adding and deleting
175  *
176  * simple list traversal with read-only actions can be done with RCU protection
177  *
178  * may be used to exclude some operations from running concurrently without any
179  * modifications to the list (see write_all_supers)
180  *
181  * volume_mutex
182  * ------------
183  * coarse lock owned by a mounted filesystem; used to exclude some operations
184  * that cannot run in parallel and affect the higher-level properties of the
185  * filesystem like: device add/deleting/resize/replace, or balance
186  *
187  * balance_mutex
188  * -------------
189  * protects balance structures (status, state) and context accessed from
190  * several places (internally, ioctl)
191  *
192  * chunk_mutex
193  * -----------
194  * protects chunks, adding or removing during allocation, trim or when a new
195  * device is added/removed
196  *
197  * cleaner_mutex
198  * -------------
199  * a big lock that is held by the cleaner thread and prevents running subvolume
200  * cleaning together with relocation or delayed iputs
201  *
202  *
203  * Lock nesting
204  * ============
205  *
206  * uuid_mutex
207  *   volume_mutex
208  *     device_list_mutex
209  *       chunk_mutex
210  *     balance_mutex
211  */
212 
213 DEFINE_MUTEX(uuid_mutex);
214 static LIST_HEAD(fs_uuids);
215 struct list_head *btrfs_get_fs_uuids(void)
216 {
217 	return &fs_uuids;
218 }
219 
220 /*
221  * alloc_fs_devices - allocate struct btrfs_fs_devices
222  * @fsid:	if not NULL, copy the uuid to fs_devices::fsid
223  *
224  * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
225  * The returned struct is not linked onto any lists and can be destroyed with
226  * kfree() right away.
227  */
228 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
229 {
230 	struct btrfs_fs_devices *fs_devs;
231 
232 	fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
233 	if (!fs_devs)
234 		return ERR_PTR(-ENOMEM);
235 
236 	mutex_init(&fs_devs->device_list_mutex);
237 
238 	INIT_LIST_HEAD(&fs_devs->devices);
239 	INIT_LIST_HEAD(&fs_devs->resized_devices);
240 	INIT_LIST_HEAD(&fs_devs->alloc_list);
241 	INIT_LIST_HEAD(&fs_devs->list);
242 	if (fsid)
243 		memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
244 
245 	return fs_devs;
246 }
247 
248 static void free_device(struct btrfs_device *device)
249 {
250 	rcu_string_free(device->name);
251 	bio_put(device->flush_bio);
252 	kfree(device);
253 }
254 
255 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
256 {
257 	struct btrfs_device *device;
258 	WARN_ON(fs_devices->opened);
259 	while (!list_empty(&fs_devices->devices)) {
260 		device = list_entry(fs_devices->devices.next,
261 				    struct btrfs_device, dev_list);
262 		list_del(&device->dev_list);
263 		free_device(device);
264 	}
265 	kfree(fs_devices);
266 }
267 
268 static void btrfs_kobject_uevent(struct block_device *bdev,
269 				 enum kobject_action action)
270 {
271 	int ret;
272 
273 	ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
274 	if (ret)
275 		pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
276 			action,
277 			kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
278 			&disk_to_dev(bdev->bd_disk)->kobj);
279 }
280 
281 void btrfs_cleanup_fs_uuids(void)
282 {
283 	struct btrfs_fs_devices *fs_devices;
284 
285 	while (!list_empty(&fs_uuids)) {
286 		fs_devices = list_entry(fs_uuids.next,
287 					struct btrfs_fs_devices, list);
288 		list_del(&fs_devices->list);
289 		free_fs_devices(fs_devices);
290 	}
291 }
292 
293 /*
294  * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
295  * Returned struct is not linked onto any lists and must be destroyed using
296  * free_device.
297  */
298 static struct btrfs_device *__alloc_device(void)
299 {
300 	struct btrfs_device *dev;
301 
302 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
303 	if (!dev)
304 		return ERR_PTR(-ENOMEM);
305 
306 	/*
307 	 * Preallocate a bio that's always going to be used for flushing device
308 	 * barriers and matches the device lifespan
309 	 */
310 	dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
311 	if (!dev->flush_bio) {
312 		kfree(dev);
313 		return ERR_PTR(-ENOMEM);
314 	}
315 
316 	INIT_LIST_HEAD(&dev->dev_list);
317 	INIT_LIST_HEAD(&dev->dev_alloc_list);
318 	INIT_LIST_HEAD(&dev->resized_list);
319 
320 	spin_lock_init(&dev->io_lock);
321 
322 	atomic_set(&dev->reada_in_flight, 0);
323 	atomic_set(&dev->dev_stats_ccnt, 0);
324 	btrfs_device_data_ordered_init(dev);
325 	INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
326 	INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
327 
328 	return dev;
329 }
330 
331 /*
332  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
333  * return NULL.
334  *
335  * If devid and uuid are both specified, the match must be exact, otherwise
336  * only devid is used.
337  */
338 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
339 		u64 devid, const u8 *uuid)
340 {
341 	struct list_head *head = &fs_devices->devices;
342 	struct btrfs_device *dev;
343 
344 	list_for_each_entry(dev, head, dev_list) {
345 		if (dev->devid == devid &&
346 		    (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
347 			return dev;
348 		}
349 	}
350 	return NULL;
351 }
352 
353 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
354 {
355 	struct btrfs_fs_devices *fs_devices;
356 
357 	list_for_each_entry(fs_devices, &fs_uuids, list) {
358 		if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
359 			return fs_devices;
360 	}
361 	return NULL;
362 }
363 
364 static int
365 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
366 		      int flush, struct block_device **bdev,
367 		      struct buffer_head **bh)
368 {
369 	int ret;
370 
371 	*bdev = blkdev_get_by_path(device_path, flags, holder);
372 
373 	if (IS_ERR(*bdev)) {
374 		ret = PTR_ERR(*bdev);
375 		goto error;
376 	}
377 
378 	if (flush)
379 		filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
380 	ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
381 	if (ret) {
382 		blkdev_put(*bdev, flags);
383 		goto error;
384 	}
385 	invalidate_bdev(*bdev);
386 	*bh = btrfs_read_dev_super(*bdev);
387 	if (IS_ERR(*bh)) {
388 		ret = PTR_ERR(*bh);
389 		blkdev_put(*bdev, flags);
390 		goto error;
391 	}
392 
393 	return 0;
394 
395 error:
396 	*bdev = NULL;
397 	*bh = NULL;
398 	return ret;
399 }
400 
401 static void requeue_list(struct btrfs_pending_bios *pending_bios,
402 			struct bio *head, struct bio *tail)
403 {
404 
405 	struct bio *old_head;
406 
407 	old_head = pending_bios->head;
408 	pending_bios->head = head;
409 	if (pending_bios->tail)
410 		tail->bi_next = old_head;
411 	else
412 		pending_bios->tail = tail;
413 }
414 
415 /*
416  * we try to collect pending bios for a device so we don't get a large
417  * number of procs sending bios down to the same device.  This greatly
418  * improves the schedulers ability to collect and merge the bios.
419  *
420  * But, it also turns into a long list of bios to process and that is sure
421  * to eventually make the worker thread block.  The solution here is to
422  * make some progress and then put this work struct back at the end of
423  * the list if the block device is congested.  This way, multiple devices
424  * can make progress from a single worker thread.
425  */
426 static noinline void run_scheduled_bios(struct btrfs_device *device)
427 {
428 	struct btrfs_fs_info *fs_info = device->fs_info;
429 	struct bio *pending;
430 	struct backing_dev_info *bdi;
431 	struct btrfs_pending_bios *pending_bios;
432 	struct bio *tail;
433 	struct bio *cur;
434 	int again = 0;
435 	unsigned long num_run;
436 	unsigned long batch_run = 0;
437 	unsigned long last_waited = 0;
438 	int force_reg = 0;
439 	int sync_pending = 0;
440 	struct blk_plug plug;
441 
442 	/*
443 	 * this function runs all the bios we've collected for
444 	 * a particular device.  We don't want to wander off to
445 	 * another device without first sending all of these down.
446 	 * So, setup a plug here and finish it off before we return
447 	 */
448 	blk_start_plug(&plug);
449 
450 	bdi = device->bdev->bd_bdi;
451 
452 loop:
453 	spin_lock(&device->io_lock);
454 
455 loop_lock:
456 	num_run = 0;
457 
458 	/* take all the bios off the list at once and process them
459 	 * later on (without the lock held).  But, remember the
460 	 * tail and other pointers so the bios can be properly reinserted
461 	 * into the list if we hit congestion
462 	 */
463 	if (!force_reg && device->pending_sync_bios.head) {
464 		pending_bios = &device->pending_sync_bios;
465 		force_reg = 1;
466 	} else {
467 		pending_bios = &device->pending_bios;
468 		force_reg = 0;
469 	}
470 
471 	pending = pending_bios->head;
472 	tail = pending_bios->tail;
473 	WARN_ON(pending && !tail);
474 
475 	/*
476 	 * if pending was null this time around, no bios need processing
477 	 * at all and we can stop.  Otherwise it'll loop back up again
478 	 * and do an additional check so no bios are missed.
479 	 *
480 	 * device->running_pending is used to synchronize with the
481 	 * schedule_bio code.
482 	 */
483 	if (device->pending_sync_bios.head == NULL &&
484 	    device->pending_bios.head == NULL) {
485 		again = 0;
486 		device->running_pending = 0;
487 	} else {
488 		again = 1;
489 		device->running_pending = 1;
490 	}
491 
492 	pending_bios->head = NULL;
493 	pending_bios->tail = NULL;
494 
495 	spin_unlock(&device->io_lock);
496 
497 	while (pending) {
498 
499 		rmb();
500 		/* we want to work on both lists, but do more bios on the
501 		 * sync list than the regular list
502 		 */
503 		if ((num_run > 32 &&
504 		    pending_bios != &device->pending_sync_bios &&
505 		    device->pending_sync_bios.head) ||
506 		   (num_run > 64 && pending_bios == &device->pending_sync_bios &&
507 		    device->pending_bios.head)) {
508 			spin_lock(&device->io_lock);
509 			requeue_list(pending_bios, pending, tail);
510 			goto loop_lock;
511 		}
512 
513 		cur = pending;
514 		pending = pending->bi_next;
515 		cur->bi_next = NULL;
516 
517 		BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
518 
519 		/*
520 		 * if we're doing the sync list, record that our
521 		 * plug has some sync requests on it
522 		 *
523 		 * If we're doing the regular list and there are
524 		 * sync requests sitting around, unplug before
525 		 * we add more
526 		 */
527 		if (pending_bios == &device->pending_sync_bios) {
528 			sync_pending = 1;
529 		} else if (sync_pending) {
530 			blk_finish_plug(&plug);
531 			blk_start_plug(&plug);
532 			sync_pending = 0;
533 		}
534 
535 		btrfsic_submit_bio(cur);
536 		num_run++;
537 		batch_run++;
538 
539 		cond_resched();
540 
541 		/*
542 		 * we made progress, there is more work to do and the bdi
543 		 * is now congested.  Back off and let other work structs
544 		 * run instead
545 		 */
546 		if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
547 		    fs_info->fs_devices->open_devices > 1) {
548 			struct io_context *ioc;
549 
550 			ioc = current->io_context;
551 
552 			/*
553 			 * the main goal here is that we don't want to
554 			 * block if we're going to be able to submit
555 			 * more requests without blocking.
556 			 *
557 			 * This code does two great things, it pokes into
558 			 * the elevator code from a filesystem _and_
559 			 * it makes assumptions about how batching works.
560 			 */
561 			if (ioc && ioc->nr_batch_requests > 0 &&
562 			    time_before(jiffies, ioc->last_waited + HZ/50UL) &&
563 			    (last_waited == 0 ||
564 			     ioc->last_waited == last_waited)) {
565 				/*
566 				 * we want to go through our batch of
567 				 * requests and stop.  So, we copy out
568 				 * the ioc->last_waited time and test
569 				 * against it before looping
570 				 */
571 				last_waited = ioc->last_waited;
572 				cond_resched();
573 				continue;
574 			}
575 			spin_lock(&device->io_lock);
576 			requeue_list(pending_bios, pending, tail);
577 			device->running_pending = 1;
578 
579 			spin_unlock(&device->io_lock);
580 			btrfs_queue_work(fs_info->submit_workers,
581 					 &device->work);
582 			goto done;
583 		}
584 	}
585 
586 	cond_resched();
587 	if (again)
588 		goto loop;
589 
590 	spin_lock(&device->io_lock);
591 	if (device->pending_bios.head || device->pending_sync_bios.head)
592 		goto loop_lock;
593 	spin_unlock(&device->io_lock);
594 
595 done:
596 	blk_finish_plug(&plug);
597 }
598 
599 static void pending_bios_fn(struct btrfs_work *work)
600 {
601 	struct btrfs_device *device;
602 
603 	device = container_of(work, struct btrfs_device, work);
604 	run_scheduled_bios(device);
605 }
606 
607 /*
608  *  Search and remove all stale (devices which are not mounted) devices.
609  *  When both inputs are NULL, it will search and release all stale devices.
610  *  path:	Optional. When provided will it release all unmounted devices
611  *		matching this path only.
612  *  skip_dev:	Optional. Will skip this device when searching for the stale
613  *		devices.
614  */
615 static void btrfs_free_stale_devices(const char *path,
616 				     struct btrfs_device *skip_dev)
617 {
618 	struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
619 	struct btrfs_device *dev, *tmp_dev;
620 
621 	list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, list) {
622 
623 		if (fs_devs->opened)
624 			continue;
625 
626 		list_for_each_entry_safe(dev, tmp_dev,
627 					 &fs_devs->devices, dev_list) {
628 			int not_found = 0;
629 
630 			if (skip_dev && skip_dev == dev)
631 				continue;
632 			if (path && !dev->name)
633 				continue;
634 
635 			rcu_read_lock();
636 			if (path)
637 				not_found = strcmp(rcu_str_deref(dev->name),
638 						   path);
639 			rcu_read_unlock();
640 			if (not_found)
641 				continue;
642 
643 			/* delete the stale device */
644 			if (fs_devs->num_devices == 1) {
645 				btrfs_sysfs_remove_fsid(fs_devs);
646 				list_del(&fs_devs->list);
647 				free_fs_devices(fs_devs);
648 			} else {
649 				fs_devs->num_devices--;
650 				list_del(&dev->dev_list);
651 				free_device(dev);
652 			}
653 		}
654 	}
655 }
656 
657 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
658 			struct btrfs_device *device, fmode_t flags,
659 			void *holder)
660 {
661 	struct request_queue *q;
662 	struct block_device *bdev;
663 	struct buffer_head *bh;
664 	struct btrfs_super_block *disk_super;
665 	u64 devid;
666 	int ret;
667 
668 	if (device->bdev)
669 		return -EINVAL;
670 	if (!device->name)
671 		return -EINVAL;
672 
673 	ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
674 				    &bdev, &bh);
675 	if (ret)
676 		return ret;
677 
678 	disk_super = (struct btrfs_super_block *)bh->b_data;
679 	devid = btrfs_stack_device_id(&disk_super->dev_item);
680 	if (devid != device->devid)
681 		goto error_brelse;
682 
683 	if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
684 		goto error_brelse;
685 
686 	device->generation = btrfs_super_generation(disk_super);
687 
688 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
689 		clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
690 		fs_devices->seeding = 1;
691 	} else {
692 		if (bdev_read_only(bdev))
693 			clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
694 		else
695 			set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
696 	}
697 
698 	q = bdev_get_queue(bdev);
699 	if (!blk_queue_nonrot(q))
700 		fs_devices->rotating = 1;
701 
702 	device->bdev = bdev;
703 	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
704 	device->mode = flags;
705 
706 	fs_devices->open_devices++;
707 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
708 	    device->devid != BTRFS_DEV_REPLACE_DEVID) {
709 		fs_devices->rw_devices++;
710 		list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
711 	}
712 	brelse(bh);
713 
714 	return 0;
715 
716 error_brelse:
717 	brelse(bh);
718 	blkdev_put(bdev, flags);
719 
720 	return -EINVAL;
721 }
722 
723 /*
724  * Add new device to list of registered devices
725  *
726  * Returns:
727  * device pointer which was just added or updated when successful
728  * error pointer when failed
729  */
730 static noinline struct btrfs_device *device_list_add(const char *path,
731 			   struct btrfs_super_block *disk_super)
732 {
733 	struct btrfs_device *device;
734 	struct btrfs_fs_devices *fs_devices;
735 	struct rcu_string *name;
736 	u64 found_transid = btrfs_super_generation(disk_super);
737 	u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
738 
739 	fs_devices = find_fsid(disk_super->fsid);
740 	if (!fs_devices) {
741 		fs_devices = alloc_fs_devices(disk_super->fsid);
742 		if (IS_ERR(fs_devices))
743 			return ERR_CAST(fs_devices);
744 
745 		list_add(&fs_devices->list, &fs_uuids);
746 
747 		device = NULL;
748 	} else {
749 		device = find_device(fs_devices, devid,
750 				disk_super->dev_item.uuid);
751 	}
752 
753 	if (!device) {
754 		if (fs_devices->opened)
755 			return ERR_PTR(-EBUSY);
756 
757 		device = btrfs_alloc_device(NULL, &devid,
758 					    disk_super->dev_item.uuid);
759 		if (IS_ERR(device)) {
760 			/* we can safely leave the fs_devices entry around */
761 			return device;
762 		}
763 
764 		name = rcu_string_strdup(path, GFP_NOFS);
765 		if (!name) {
766 			free_device(device);
767 			return ERR_PTR(-ENOMEM);
768 		}
769 		rcu_assign_pointer(device->name, name);
770 
771 		mutex_lock(&fs_devices->device_list_mutex);
772 		list_add_rcu(&device->dev_list, &fs_devices->devices);
773 		fs_devices->num_devices++;
774 		mutex_unlock(&fs_devices->device_list_mutex);
775 
776 		device->fs_devices = fs_devices;
777 		btrfs_free_stale_devices(path, device);
778 
779 		if (disk_super->label[0])
780 			pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
781 				disk_super->label, devid, found_transid, path);
782 		else
783 			pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
784 				disk_super->fsid, devid, found_transid, path);
785 
786 	} else if (!device->name || strcmp(device->name->str, path)) {
787 		/*
788 		 * When FS is already mounted.
789 		 * 1. If you are here and if the device->name is NULL that
790 		 *    means this device was missing at time of FS mount.
791 		 * 2. If you are here and if the device->name is different
792 		 *    from 'path' that means either
793 		 *      a. The same device disappeared and reappeared with
794 		 *         different name. or
795 		 *      b. The missing-disk-which-was-replaced, has
796 		 *         reappeared now.
797 		 *
798 		 * We must allow 1 and 2a above. But 2b would be a spurious
799 		 * and unintentional.
800 		 *
801 		 * Further in case of 1 and 2a above, the disk at 'path'
802 		 * would have missed some transaction when it was away and
803 		 * in case of 2a the stale bdev has to be updated as well.
804 		 * 2b must not be allowed at all time.
805 		 */
806 
807 		/*
808 		 * For now, we do allow update to btrfs_fs_device through the
809 		 * btrfs dev scan cli after FS has been mounted.  We're still
810 		 * tracking a problem where systems fail mount by subvolume id
811 		 * when we reject replacement on a mounted FS.
812 		 */
813 		if (!fs_devices->opened && found_transid < device->generation) {
814 			/*
815 			 * That is if the FS is _not_ mounted and if you
816 			 * are here, that means there is more than one
817 			 * disk with same uuid and devid.We keep the one
818 			 * with larger generation number or the last-in if
819 			 * generation are equal.
820 			 */
821 			return ERR_PTR(-EEXIST);
822 		}
823 
824 		name = rcu_string_strdup(path, GFP_NOFS);
825 		if (!name)
826 			return ERR_PTR(-ENOMEM);
827 		rcu_string_free(device->name);
828 		rcu_assign_pointer(device->name, name);
829 		if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
830 			fs_devices->missing_devices--;
831 			clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
832 		}
833 	}
834 
835 	/*
836 	 * Unmount does not free the btrfs_device struct but would zero
837 	 * generation along with most of the other members. So just update
838 	 * it back. We need it to pick the disk with largest generation
839 	 * (as above).
840 	 */
841 	if (!fs_devices->opened)
842 		device->generation = found_transid;
843 
844 	fs_devices->total_devices = btrfs_super_num_devices(disk_super);
845 
846 	return device;
847 }
848 
849 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
850 {
851 	struct btrfs_fs_devices *fs_devices;
852 	struct btrfs_device *device;
853 	struct btrfs_device *orig_dev;
854 
855 	fs_devices = alloc_fs_devices(orig->fsid);
856 	if (IS_ERR(fs_devices))
857 		return fs_devices;
858 
859 	mutex_lock(&orig->device_list_mutex);
860 	fs_devices->total_devices = orig->total_devices;
861 
862 	/* We have held the volume lock, it is safe to get the devices. */
863 	list_for_each_entry(orig_dev, &orig->devices, dev_list) {
864 		struct rcu_string *name;
865 
866 		device = btrfs_alloc_device(NULL, &orig_dev->devid,
867 					    orig_dev->uuid);
868 		if (IS_ERR(device))
869 			goto error;
870 
871 		/*
872 		 * This is ok to do without rcu read locked because we hold the
873 		 * uuid mutex so nothing we touch in here is going to disappear.
874 		 */
875 		if (orig_dev->name) {
876 			name = rcu_string_strdup(orig_dev->name->str,
877 					GFP_KERNEL);
878 			if (!name) {
879 				free_device(device);
880 				goto error;
881 			}
882 			rcu_assign_pointer(device->name, name);
883 		}
884 
885 		list_add(&device->dev_list, &fs_devices->devices);
886 		device->fs_devices = fs_devices;
887 		fs_devices->num_devices++;
888 	}
889 	mutex_unlock(&orig->device_list_mutex);
890 	return fs_devices;
891 error:
892 	mutex_unlock(&orig->device_list_mutex);
893 	free_fs_devices(fs_devices);
894 	return ERR_PTR(-ENOMEM);
895 }
896 
897 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
898 {
899 	struct btrfs_device *device, *next;
900 	struct btrfs_device *latest_dev = NULL;
901 
902 	mutex_lock(&uuid_mutex);
903 again:
904 	/* This is the initialized path, it is safe to release the devices. */
905 	list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
906 		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
907 							&device->dev_state)) {
908 			if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
909 			     &device->dev_state) &&
910 			     (!latest_dev ||
911 			      device->generation > latest_dev->generation)) {
912 				latest_dev = device;
913 			}
914 			continue;
915 		}
916 
917 		if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
918 			/*
919 			 * In the first step, keep the device which has
920 			 * the correct fsid and the devid that is used
921 			 * for the dev_replace procedure.
922 			 * In the second step, the dev_replace state is
923 			 * read from the device tree and it is known
924 			 * whether the procedure is really active or
925 			 * not, which means whether this device is
926 			 * used or whether it should be removed.
927 			 */
928 			if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
929 						  &device->dev_state)) {
930 				continue;
931 			}
932 		}
933 		if (device->bdev) {
934 			blkdev_put(device->bdev, device->mode);
935 			device->bdev = NULL;
936 			fs_devices->open_devices--;
937 		}
938 		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
939 			list_del_init(&device->dev_alloc_list);
940 			clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
941 			if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
942 				      &device->dev_state))
943 				fs_devices->rw_devices--;
944 		}
945 		list_del_init(&device->dev_list);
946 		fs_devices->num_devices--;
947 		free_device(device);
948 	}
949 
950 	if (fs_devices->seed) {
951 		fs_devices = fs_devices->seed;
952 		goto again;
953 	}
954 
955 	fs_devices->latest_bdev = latest_dev->bdev;
956 
957 	mutex_unlock(&uuid_mutex);
958 }
959 
960 static void free_device_rcu(struct rcu_head *head)
961 {
962 	struct btrfs_device *device;
963 
964 	device = container_of(head, struct btrfs_device, rcu);
965 	free_device(device);
966 }
967 
968 static void btrfs_close_bdev(struct btrfs_device *device)
969 {
970 	if (!device->bdev)
971 		return;
972 
973 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
974 		sync_blockdev(device->bdev);
975 		invalidate_bdev(device->bdev);
976 	}
977 
978 	blkdev_put(device->bdev, device->mode);
979 }
980 
981 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
982 {
983 	struct btrfs_fs_devices *fs_devices = device->fs_devices;
984 	struct btrfs_device *new_device;
985 	struct rcu_string *name;
986 
987 	if (device->bdev)
988 		fs_devices->open_devices--;
989 
990 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
991 	    device->devid != BTRFS_DEV_REPLACE_DEVID) {
992 		list_del_init(&device->dev_alloc_list);
993 		fs_devices->rw_devices--;
994 	}
995 
996 	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
997 		fs_devices->missing_devices--;
998 
999 	new_device = btrfs_alloc_device(NULL, &device->devid,
1000 					device->uuid);
1001 	BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1002 
1003 	/* Safe because we are under uuid_mutex */
1004 	if (device->name) {
1005 		name = rcu_string_strdup(device->name->str, GFP_NOFS);
1006 		BUG_ON(!name); /* -ENOMEM */
1007 		rcu_assign_pointer(new_device->name, name);
1008 	}
1009 
1010 	list_replace_rcu(&device->dev_list, &new_device->dev_list);
1011 	new_device->fs_devices = device->fs_devices;
1012 }
1013 
1014 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1015 {
1016 	struct btrfs_device *device, *tmp;
1017 	struct list_head pending_put;
1018 
1019 	INIT_LIST_HEAD(&pending_put);
1020 
1021 	if (--fs_devices->opened > 0)
1022 		return 0;
1023 
1024 	mutex_lock(&fs_devices->device_list_mutex);
1025 	list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1026 		btrfs_prepare_close_one_device(device);
1027 		list_add(&device->dev_list, &pending_put);
1028 	}
1029 	mutex_unlock(&fs_devices->device_list_mutex);
1030 
1031 	/*
1032 	 * btrfs_show_devname() is using the device_list_mutex,
1033 	 * sometimes call to blkdev_put() leads vfs calling
1034 	 * into this func. So do put outside of device_list_mutex,
1035 	 * as of now.
1036 	 */
1037 	while (!list_empty(&pending_put)) {
1038 		device = list_first_entry(&pending_put,
1039 				struct btrfs_device, dev_list);
1040 		list_del(&device->dev_list);
1041 		btrfs_close_bdev(device);
1042 		call_rcu(&device->rcu, free_device_rcu);
1043 	}
1044 
1045 	WARN_ON(fs_devices->open_devices);
1046 	WARN_ON(fs_devices->rw_devices);
1047 	fs_devices->opened = 0;
1048 	fs_devices->seeding = 0;
1049 
1050 	return 0;
1051 }
1052 
1053 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1054 {
1055 	struct btrfs_fs_devices *seed_devices = NULL;
1056 	int ret;
1057 
1058 	mutex_lock(&uuid_mutex);
1059 	ret = __btrfs_close_devices(fs_devices);
1060 	if (!fs_devices->opened) {
1061 		seed_devices = fs_devices->seed;
1062 		fs_devices->seed = NULL;
1063 	}
1064 	mutex_unlock(&uuid_mutex);
1065 
1066 	while (seed_devices) {
1067 		fs_devices = seed_devices;
1068 		seed_devices = fs_devices->seed;
1069 		__btrfs_close_devices(fs_devices);
1070 		free_fs_devices(fs_devices);
1071 	}
1072 	return ret;
1073 }
1074 
1075 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1076 				fmode_t flags, void *holder)
1077 {
1078 	struct list_head *head = &fs_devices->devices;
1079 	struct btrfs_device *device;
1080 	struct btrfs_device *latest_dev = NULL;
1081 	int ret = 0;
1082 
1083 	flags |= FMODE_EXCL;
1084 
1085 	list_for_each_entry(device, head, dev_list) {
1086 		/* Just open everything we can; ignore failures here */
1087 		if (btrfs_open_one_device(fs_devices, device, flags, holder))
1088 			continue;
1089 
1090 		if (!latest_dev ||
1091 		    device->generation > latest_dev->generation)
1092 			latest_dev = device;
1093 	}
1094 	if (fs_devices->open_devices == 0) {
1095 		ret = -EINVAL;
1096 		goto out;
1097 	}
1098 	fs_devices->opened = 1;
1099 	fs_devices->latest_bdev = latest_dev->bdev;
1100 	fs_devices->total_rw_bytes = 0;
1101 out:
1102 	return ret;
1103 }
1104 
1105 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1106 		       fmode_t flags, void *holder)
1107 {
1108 	int ret;
1109 
1110 	mutex_lock(&uuid_mutex);
1111 	if (fs_devices->opened) {
1112 		fs_devices->opened++;
1113 		ret = 0;
1114 	} else {
1115 		ret = __btrfs_open_devices(fs_devices, flags, holder);
1116 	}
1117 	mutex_unlock(&uuid_mutex);
1118 	return ret;
1119 }
1120 
1121 static void btrfs_release_disk_super(struct page *page)
1122 {
1123 	kunmap(page);
1124 	put_page(page);
1125 }
1126 
1127 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1128 				 struct page **page,
1129 				 struct btrfs_super_block **disk_super)
1130 {
1131 	void *p;
1132 	pgoff_t index;
1133 
1134 	/* make sure our super fits in the device */
1135 	if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1136 		return 1;
1137 
1138 	/* make sure our super fits in the page */
1139 	if (sizeof(**disk_super) > PAGE_SIZE)
1140 		return 1;
1141 
1142 	/* make sure our super doesn't straddle pages on disk */
1143 	index = bytenr >> PAGE_SHIFT;
1144 	if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1145 		return 1;
1146 
1147 	/* pull in the page with our super */
1148 	*page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1149 				   index, GFP_KERNEL);
1150 
1151 	if (IS_ERR_OR_NULL(*page))
1152 		return 1;
1153 
1154 	p = kmap(*page);
1155 
1156 	/* align our pointer to the offset of the super block */
1157 	*disk_super = p + (bytenr & ~PAGE_MASK);
1158 
1159 	if (btrfs_super_bytenr(*disk_super) != bytenr ||
1160 	    btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1161 		btrfs_release_disk_super(*page);
1162 		return 1;
1163 	}
1164 
1165 	if ((*disk_super)->label[0] &&
1166 		(*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1167 		(*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1168 
1169 	return 0;
1170 }
1171 
1172 /*
1173  * Look for a btrfs signature on a device. This may be called out of the mount path
1174  * and we are not allowed to call set_blocksize during the scan. The superblock
1175  * is read via pagecache
1176  */
1177 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1178 			  struct btrfs_fs_devices **fs_devices_ret)
1179 {
1180 	struct btrfs_super_block *disk_super;
1181 	struct btrfs_device *device;
1182 	struct block_device *bdev;
1183 	struct page *page;
1184 	int ret = 0;
1185 	u64 bytenr;
1186 
1187 	/*
1188 	 * we would like to check all the supers, but that would make
1189 	 * a btrfs mount succeed after a mkfs from a different FS.
1190 	 * So, we need to add a special mount option to scan for
1191 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1192 	 */
1193 	bytenr = btrfs_sb_offset(0);
1194 	flags |= FMODE_EXCL;
1195 	mutex_lock(&uuid_mutex);
1196 
1197 	bdev = blkdev_get_by_path(path, flags, holder);
1198 	if (IS_ERR(bdev)) {
1199 		ret = PTR_ERR(bdev);
1200 		goto error;
1201 	}
1202 
1203 	if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1204 		ret = -EINVAL;
1205 		goto error_bdev_put;
1206 	}
1207 
1208 	device = device_list_add(path, disk_super);
1209 	if (IS_ERR(device))
1210 		ret = PTR_ERR(device);
1211 	else
1212 		*fs_devices_ret = device->fs_devices;
1213 
1214 	btrfs_release_disk_super(page);
1215 
1216 error_bdev_put:
1217 	blkdev_put(bdev, flags);
1218 error:
1219 	mutex_unlock(&uuid_mutex);
1220 	return ret;
1221 }
1222 
1223 /* helper to account the used device space in the range */
1224 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1225 				   u64 end, u64 *length)
1226 {
1227 	struct btrfs_key key;
1228 	struct btrfs_root *root = device->fs_info->dev_root;
1229 	struct btrfs_dev_extent *dev_extent;
1230 	struct btrfs_path *path;
1231 	u64 extent_end;
1232 	int ret;
1233 	int slot;
1234 	struct extent_buffer *l;
1235 
1236 	*length = 0;
1237 
1238 	if (start >= device->total_bytes ||
1239 		test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1240 		return 0;
1241 
1242 	path = btrfs_alloc_path();
1243 	if (!path)
1244 		return -ENOMEM;
1245 	path->reada = READA_FORWARD;
1246 
1247 	key.objectid = device->devid;
1248 	key.offset = start;
1249 	key.type = BTRFS_DEV_EXTENT_KEY;
1250 
1251 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1252 	if (ret < 0)
1253 		goto out;
1254 	if (ret > 0) {
1255 		ret = btrfs_previous_item(root, path, key.objectid, key.type);
1256 		if (ret < 0)
1257 			goto out;
1258 	}
1259 
1260 	while (1) {
1261 		l = path->nodes[0];
1262 		slot = path->slots[0];
1263 		if (slot >= btrfs_header_nritems(l)) {
1264 			ret = btrfs_next_leaf(root, path);
1265 			if (ret == 0)
1266 				continue;
1267 			if (ret < 0)
1268 				goto out;
1269 
1270 			break;
1271 		}
1272 		btrfs_item_key_to_cpu(l, &key, slot);
1273 
1274 		if (key.objectid < device->devid)
1275 			goto next;
1276 
1277 		if (key.objectid > device->devid)
1278 			break;
1279 
1280 		if (key.type != BTRFS_DEV_EXTENT_KEY)
1281 			goto next;
1282 
1283 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1284 		extent_end = key.offset + btrfs_dev_extent_length(l,
1285 								  dev_extent);
1286 		if (key.offset <= start && extent_end > end) {
1287 			*length = end - start + 1;
1288 			break;
1289 		} else if (key.offset <= start && extent_end > start)
1290 			*length += extent_end - start;
1291 		else if (key.offset > start && extent_end <= end)
1292 			*length += extent_end - key.offset;
1293 		else if (key.offset > start && key.offset <= end) {
1294 			*length += end - key.offset + 1;
1295 			break;
1296 		} else if (key.offset > end)
1297 			break;
1298 
1299 next:
1300 		path->slots[0]++;
1301 	}
1302 	ret = 0;
1303 out:
1304 	btrfs_free_path(path);
1305 	return ret;
1306 }
1307 
1308 static int contains_pending_extent(struct btrfs_transaction *transaction,
1309 				   struct btrfs_device *device,
1310 				   u64 *start, u64 len)
1311 {
1312 	struct btrfs_fs_info *fs_info = device->fs_info;
1313 	struct extent_map *em;
1314 	struct list_head *search_list = &fs_info->pinned_chunks;
1315 	int ret = 0;
1316 	u64 physical_start = *start;
1317 
1318 	if (transaction)
1319 		search_list = &transaction->pending_chunks;
1320 again:
1321 	list_for_each_entry(em, search_list, list) {
1322 		struct map_lookup *map;
1323 		int i;
1324 
1325 		map = em->map_lookup;
1326 		for (i = 0; i < map->num_stripes; i++) {
1327 			u64 end;
1328 
1329 			if (map->stripes[i].dev != device)
1330 				continue;
1331 			if (map->stripes[i].physical >= physical_start + len ||
1332 			    map->stripes[i].physical + em->orig_block_len <=
1333 			    physical_start)
1334 				continue;
1335 			/*
1336 			 * Make sure that while processing the pinned list we do
1337 			 * not override our *start with a lower value, because
1338 			 * we can have pinned chunks that fall within this
1339 			 * device hole and that have lower physical addresses
1340 			 * than the pending chunks we processed before. If we
1341 			 * do not take this special care we can end up getting
1342 			 * 2 pending chunks that start at the same physical
1343 			 * device offsets because the end offset of a pinned
1344 			 * chunk can be equal to the start offset of some
1345 			 * pending chunk.
1346 			 */
1347 			end = map->stripes[i].physical + em->orig_block_len;
1348 			if (end > *start) {
1349 				*start = end;
1350 				ret = 1;
1351 			}
1352 		}
1353 	}
1354 	if (search_list != &fs_info->pinned_chunks) {
1355 		search_list = &fs_info->pinned_chunks;
1356 		goto again;
1357 	}
1358 
1359 	return ret;
1360 }
1361 
1362 
1363 /*
1364  * find_free_dev_extent_start - find free space in the specified device
1365  * @device:	  the device which we search the free space in
1366  * @num_bytes:	  the size of the free space that we need
1367  * @search_start: the position from which to begin the search
1368  * @start:	  store the start of the free space.
1369  * @len:	  the size of the free space. that we find, or the size
1370  *		  of the max free space if we don't find suitable free space
1371  *
1372  * this uses a pretty simple search, the expectation is that it is
1373  * called very infrequently and that a given device has a small number
1374  * of extents
1375  *
1376  * @start is used to store the start of the free space if we find. But if we
1377  * don't find suitable free space, it will be used to store the start position
1378  * of the max free space.
1379  *
1380  * @len is used to store the size of the free space that we find.
1381  * But if we don't find suitable free space, it is used to store the size of
1382  * the max free space.
1383  */
1384 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1385 			       struct btrfs_device *device, u64 num_bytes,
1386 			       u64 search_start, u64 *start, u64 *len)
1387 {
1388 	struct btrfs_fs_info *fs_info = device->fs_info;
1389 	struct btrfs_root *root = fs_info->dev_root;
1390 	struct btrfs_key key;
1391 	struct btrfs_dev_extent *dev_extent;
1392 	struct btrfs_path *path;
1393 	u64 hole_size;
1394 	u64 max_hole_start;
1395 	u64 max_hole_size;
1396 	u64 extent_end;
1397 	u64 search_end = device->total_bytes;
1398 	int ret;
1399 	int slot;
1400 	struct extent_buffer *l;
1401 
1402 	/*
1403 	 * We don't want to overwrite the superblock on the drive nor any area
1404 	 * used by the boot loader (grub for example), so we make sure to start
1405 	 * at an offset of at least 1MB.
1406 	 */
1407 	search_start = max_t(u64, search_start, SZ_1M);
1408 
1409 	path = btrfs_alloc_path();
1410 	if (!path)
1411 		return -ENOMEM;
1412 
1413 	max_hole_start = search_start;
1414 	max_hole_size = 0;
1415 
1416 again:
1417 	if (search_start >= search_end ||
1418 		test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1419 		ret = -ENOSPC;
1420 		goto out;
1421 	}
1422 
1423 	path->reada = READA_FORWARD;
1424 	path->search_commit_root = 1;
1425 	path->skip_locking = 1;
1426 
1427 	key.objectid = device->devid;
1428 	key.offset = search_start;
1429 	key.type = BTRFS_DEV_EXTENT_KEY;
1430 
1431 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1432 	if (ret < 0)
1433 		goto out;
1434 	if (ret > 0) {
1435 		ret = btrfs_previous_item(root, path, key.objectid, key.type);
1436 		if (ret < 0)
1437 			goto out;
1438 	}
1439 
1440 	while (1) {
1441 		l = path->nodes[0];
1442 		slot = path->slots[0];
1443 		if (slot >= btrfs_header_nritems(l)) {
1444 			ret = btrfs_next_leaf(root, path);
1445 			if (ret == 0)
1446 				continue;
1447 			if (ret < 0)
1448 				goto out;
1449 
1450 			break;
1451 		}
1452 		btrfs_item_key_to_cpu(l, &key, slot);
1453 
1454 		if (key.objectid < device->devid)
1455 			goto next;
1456 
1457 		if (key.objectid > device->devid)
1458 			break;
1459 
1460 		if (key.type != BTRFS_DEV_EXTENT_KEY)
1461 			goto next;
1462 
1463 		if (key.offset > search_start) {
1464 			hole_size = key.offset - search_start;
1465 
1466 			/*
1467 			 * Have to check before we set max_hole_start, otherwise
1468 			 * we could end up sending back this offset anyway.
1469 			 */
1470 			if (contains_pending_extent(transaction, device,
1471 						    &search_start,
1472 						    hole_size)) {
1473 				if (key.offset >= search_start) {
1474 					hole_size = key.offset - search_start;
1475 				} else {
1476 					WARN_ON_ONCE(1);
1477 					hole_size = 0;
1478 				}
1479 			}
1480 
1481 			if (hole_size > max_hole_size) {
1482 				max_hole_start = search_start;
1483 				max_hole_size = hole_size;
1484 			}
1485 
1486 			/*
1487 			 * If this free space is greater than which we need,
1488 			 * it must be the max free space that we have found
1489 			 * until now, so max_hole_start must point to the start
1490 			 * of this free space and the length of this free space
1491 			 * is stored in max_hole_size. Thus, we return
1492 			 * max_hole_start and max_hole_size and go back to the
1493 			 * caller.
1494 			 */
1495 			if (hole_size >= num_bytes) {
1496 				ret = 0;
1497 				goto out;
1498 			}
1499 		}
1500 
1501 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1502 		extent_end = key.offset + btrfs_dev_extent_length(l,
1503 								  dev_extent);
1504 		if (extent_end > search_start)
1505 			search_start = extent_end;
1506 next:
1507 		path->slots[0]++;
1508 		cond_resched();
1509 	}
1510 
1511 	/*
1512 	 * At this point, search_start should be the end of
1513 	 * allocated dev extents, and when shrinking the device,
1514 	 * search_end may be smaller than search_start.
1515 	 */
1516 	if (search_end > search_start) {
1517 		hole_size = search_end - search_start;
1518 
1519 		if (contains_pending_extent(transaction, device, &search_start,
1520 					    hole_size)) {
1521 			btrfs_release_path(path);
1522 			goto again;
1523 		}
1524 
1525 		if (hole_size > max_hole_size) {
1526 			max_hole_start = search_start;
1527 			max_hole_size = hole_size;
1528 		}
1529 	}
1530 
1531 	/* See above. */
1532 	if (max_hole_size < num_bytes)
1533 		ret = -ENOSPC;
1534 	else
1535 		ret = 0;
1536 
1537 out:
1538 	btrfs_free_path(path);
1539 	*start = max_hole_start;
1540 	if (len)
1541 		*len = max_hole_size;
1542 	return ret;
1543 }
1544 
1545 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1546 			 struct btrfs_device *device, u64 num_bytes,
1547 			 u64 *start, u64 *len)
1548 {
1549 	/* FIXME use last free of some kind */
1550 	return find_free_dev_extent_start(trans->transaction, device,
1551 					  num_bytes, 0, start, len);
1552 }
1553 
1554 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1555 			  struct btrfs_device *device,
1556 			  u64 start, u64 *dev_extent_len)
1557 {
1558 	struct btrfs_fs_info *fs_info = device->fs_info;
1559 	struct btrfs_root *root = fs_info->dev_root;
1560 	int ret;
1561 	struct btrfs_path *path;
1562 	struct btrfs_key key;
1563 	struct btrfs_key found_key;
1564 	struct extent_buffer *leaf = NULL;
1565 	struct btrfs_dev_extent *extent = NULL;
1566 
1567 	path = btrfs_alloc_path();
1568 	if (!path)
1569 		return -ENOMEM;
1570 
1571 	key.objectid = device->devid;
1572 	key.offset = start;
1573 	key.type = BTRFS_DEV_EXTENT_KEY;
1574 again:
1575 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1576 	if (ret > 0) {
1577 		ret = btrfs_previous_item(root, path, key.objectid,
1578 					  BTRFS_DEV_EXTENT_KEY);
1579 		if (ret)
1580 			goto out;
1581 		leaf = path->nodes[0];
1582 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1583 		extent = btrfs_item_ptr(leaf, path->slots[0],
1584 					struct btrfs_dev_extent);
1585 		BUG_ON(found_key.offset > start || found_key.offset +
1586 		       btrfs_dev_extent_length(leaf, extent) < start);
1587 		key = found_key;
1588 		btrfs_release_path(path);
1589 		goto again;
1590 	} else if (ret == 0) {
1591 		leaf = path->nodes[0];
1592 		extent = btrfs_item_ptr(leaf, path->slots[0],
1593 					struct btrfs_dev_extent);
1594 	} else {
1595 		btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1596 		goto out;
1597 	}
1598 
1599 	*dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1600 
1601 	ret = btrfs_del_item(trans, root, path);
1602 	if (ret) {
1603 		btrfs_handle_fs_error(fs_info, ret,
1604 				      "Failed to remove dev extent item");
1605 	} else {
1606 		set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1607 	}
1608 out:
1609 	btrfs_free_path(path);
1610 	return ret;
1611 }
1612 
1613 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1614 				  struct btrfs_device *device,
1615 				  u64 chunk_offset, u64 start, u64 num_bytes)
1616 {
1617 	int ret;
1618 	struct btrfs_path *path;
1619 	struct btrfs_fs_info *fs_info = device->fs_info;
1620 	struct btrfs_root *root = fs_info->dev_root;
1621 	struct btrfs_dev_extent *extent;
1622 	struct extent_buffer *leaf;
1623 	struct btrfs_key key;
1624 
1625 	WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1626 	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1627 	path = btrfs_alloc_path();
1628 	if (!path)
1629 		return -ENOMEM;
1630 
1631 	key.objectid = device->devid;
1632 	key.offset = start;
1633 	key.type = BTRFS_DEV_EXTENT_KEY;
1634 	ret = btrfs_insert_empty_item(trans, root, path, &key,
1635 				      sizeof(*extent));
1636 	if (ret)
1637 		goto out;
1638 
1639 	leaf = path->nodes[0];
1640 	extent = btrfs_item_ptr(leaf, path->slots[0],
1641 				struct btrfs_dev_extent);
1642 	btrfs_set_dev_extent_chunk_tree(leaf, extent,
1643 					BTRFS_CHUNK_TREE_OBJECTID);
1644 	btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1645 					    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1646 	btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1647 
1648 	btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1649 	btrfs_mark_buffer_dirty(leaf);
1650 out:
1651 	btrfs_free_path(path);
1652 	return ret;
1653 }
1654 
1655 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1656 {
1657 	struct extent_map_tree *em_tree;
1658 	struct extent_map *em;
1659 	struct rb_node *n;
1660 	u64 ret = 0;
1661 
1662 	em_tree = &fs_info->mapping_tree.map_tree;
1663 	read_lock(&em_tree->lock);
1664 	n = rb_last(&em_tree->map);
1665 	if (n) {
1666 		em = rb_entry(n, struct extent_map, rb_node);
1667 		ret = em->start + em->len;
1668 	}
1669 	read_unlock(&em_tree->lock);
1670 
1671 	return ret;
1672 }
1673 
1674 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1675 				    u64 *devid_ret)
1676 {
1677 	int ret;
1678 	struct btrfs_key key;
1679 	struct btrfs_key found_key;
1680 	struct btrfs_path *path;
1681 
1682 	path = btrfs_alloc_path();
1683 	if (!path)
1684 		return -ENOMEM;
1685 
1686 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1687 	key.type = BTRFS_DEV_ITEM_KEY;
1688 	key.offset = (u64)-1;
1689 
1690 	ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1691 	if (ret < 0)
1692 		goto error;
1693 
1694 	BUG_ON(ret == 0); /* Corruption */
1695 
1696 	ret = btrfs_previous_item(fs_info->chunk_root, path,
1697 				  BTRFS_DEV_ITEMS_OBJECTID,
1698 				  BTRFS_DEV_ITEM_KEY);
1699 	if (ret) {
1700 		*devid_ret = 1;
1701 	} else {
1702 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1703 				      path->slots[0]);
1704 		*devid_ret = found_key.offset + 1;
1705 	}
1706 	ret = 0;
1707 error:
1708 	btrfs_free_path(path);
1709 	return ret;
1710 }
1711 
1712 /*
1713  * the device information is stored in the chunk root
1714  * the btrfs_device struct should be fully filled in
1715  */
1716 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1717 			    struct btrfs_fs_info *fs_info,
1718 			    struct btrfs_device *device)
1719 {
1720 	struct btrfs_root *root = fs_info->chunk_root;
1721 	int ret;
1722 	struct btrfs_path *path;
1723 	struct btrfs_dev_item *dev_item;
1724 	struct extent_buffer *leaf;
1725 	struct btrfs_key key;
1726 	unsigned long ptr;
1727 
1728 	path = btrfs_alloc_path();
1729 	if (!path)
1730 		return -ENOMEM;
1731 
1732 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1733 	key.type = BTRFS_DEV_ITEM_KEY;
1734 	key.offset = device->devid;
1735 
1736 	ret = btrfs_insert_empty_item(trans, root, path, &key,
1737 				      sizeof(*dev_item));
1738 	if (ret)
1739 		goto out;
1740 
1741 	leaf = path->nodes[0];
1742 	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1743 
1744 	btrfs_set_device_id(leaf, dev_item, device->devid);
1745 	btrfs_set_device_generation(leaf, dev_item, 0);
1746 	btrfs_set_device_type(leaf, dev_item, device->type);
1747 	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1748 	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1749 	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1750 	btrfs_set_device_total_bytes(leaf, dev_item,
1751 				     btrfs_device_get_disk_total_bytes(device));
1752 	btrfs_set_device_bytes_used(leaf, dev_item,
1753 				    btrfs_device_get_bytes_used(device));
1754 	btrfs_set_device_group(leaf, dev_item, 0);
1755 	btrfs_set_device_seek_speed(leaf, dev_item, 0);
1756 	btrfs_set_device_bandwidth(leaf, dev_item, 0);
1757 	btrfs_set_device_start_offset(leaf, dev_item, 0);
1758 
1759 	ptr = btrfs_device_uuid(dev_item);
1760 	write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1761 	ptr = btrfs_device_fsid(dev_item);
1762 	write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1763 	btrfs_mark_buffer_dirty(leaf);
1764 
1765 	ret = 0;
1766 out:
1767 	btrfs_free_path(path);
1768 	return ret;
1769 }
1770 
1771 /*
1772  * Function to update ctime/mtime for a given device path.
1773  * Mainly used for ctime/mtime based probe like libblkid.
1774  */
1775 static void update_dev_time(const char *path_name)
1776 {
1777 	struct file *filp;
1778 
1779 	filp = filp_open(path_name, O_RDWR, 0);
1780 	if (IS_ERR(filp))
1781 		return;
1782 	file_update_time(filp);
1783 	filp_close(filp, NULL);
1784 }
1785 
1786 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1787 			     struct btrfs_device *device)
1788 {
1789 	struct btrfs_root *root = fs_info->chunk_root;
1790 	int ret;
1791 	struct btrfs_path *path;
1792 	struct btrfs_key key;
1793 	struct btrfs_trans_handle *trans;
1794 
1795 	path = btrfs_alloc_path();
1796 	if (!path)
1797 		return -ENOMEM;
1798 
1799 	trans = btrfs_start_transaction(root, 0);
1800 	if (IS_ERR(trans)) {
1801 		btrfs_free_path(path);
1802 		return PTR_ERR(trans);
1803 	}
1804 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1805 	key.type = BTRFS_DEV_ITEM_KEY;
1806 	key.offset = device->devid;
1807 
1808 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1809 	if (ret) {
1810 		if (ret > 0)
1811 			ret = -ENOENT;
1812 		btrfs_abort_transaction(trans, ret);
1813 		btrfs_end_transaction(trans);
1814 		goto out;
1815 	}
1816 
1817 	ret = btrfs_del_item(trans, root, path);
1818 	if (ret) {
1819 		btrfs_abort_transaction(trans, ret);
1820 		btrfs_end_transaction(trans);
1821 	}
1822 
1823 out:
1824 	btrfs_free_path(path);
1825 	if (!ret)
1826 		ret = btrfs_commit_transaction(trans);
1827 	return ret;
1828 }
1829 
1830 /*
1831  * Verify that @num_devices satisfies the RAID profile constraints in the whole
1832  * filesystem. It's up to the caller to adjust that number regarding eg. device
1833  * replace.
1834  */
1835 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1836 		u64 num_devices)
1837 {
1838 	u64 all_avail;
1839 	unsigned seq;
1840 	int i;
1841 
1842 	do {
1843 		seq = read_seqbegin(&fs_info->profiles_lock);
1844 
1845 		all_avail = fs_info->avail_data_alloc_bits |
1846 			    fs_info->avail_system_alloc_bits |
1847 			    fs_info->avail_metadata_alloc_bits;
1848 	} while (read_seqretry(&fs_info->profiles_lock, seq));
1849 
1850 	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1851 		if (!(all_avail & btrfs_raid_group[i]))
1852 			continue;
1853 
1854 		if (num_devices < btrfs_raid_array[i].devs_min) {
1855 			int ret = btrfs_raid_mindev_error[i];
1856 
1857 			if (ret)
1858 				return ret;
1859 		}
1860 	}
1861 
1862 	return 0;
1863 }
1864 
1865 static struct btrfs_device * btrfs_find_next_active_device(
1866 		struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1867 {
1868 	struct btrfs_device *next_device;
1869 
1870 	list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1871 		if (next_device != device &&
1872 		    !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1873 		    && next_device->bdev)
1874 			return next_device;
1875 	}
1876 
1877 	return NULL;
1878 }
1879 
1880 /*
1881  * Helper function to check if the given device is part of s_bdev / latest_bdev
1882  * and replace it with the provided or the next active device, in the context
1883  * where this function called, there should be always be another device (or
1884  * this_dev) which is active.
1885  */
1886 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1887 		struct btrfs_device *device, struct btrfs_device *this_dev)
1888 {
1889 	struct btrfs_device *next_device;
1890 
1891 	if (this_dev)
1892 		next_device = this_dev;
1893 	else
1894 		next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1895 								device);
1896 	ASSERT(next_device);
1897 
1898 	if (fs_info->sb->s_bdev &&
1899 			(fs_info->sb->s_bdev == device->bdev))
1900 		fs_info->sb->s_bdev = next_device->bdev;
1901 
1902 	if (fs_info->fs_devices->latest_bdev == device->bdev)
1903 		fs_info->fs_devices->latest_bdev = next_device->bdev;
1904 }
1905 
1906 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1907 		u64 devid)
1908 {
1909 	struct btrfs_device *device;
1910 	struct btrfs_fs_devices *cur_devices;
1911 	u64 num_devices;
1912 	int ret = 0;
1913 
1914 	mutex_lock(&fs_info->volume_mutex);
1915 	mutex_lock(&uuid_mutex);
1916 
1917 	num_devices = fs_info->fs_devices->num_devices;
1918 	btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1919 	if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1920 		WARN_ON(num_devices < 1);
1921 		num_devices--;
1922 	}
1923 	btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1924 
1925 	ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1926 	if (ret)
1927 		goto out;
1928 
1929 	ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1930 					   &device);
1931 	if (ret)
1932 		goto out;
1933 
1934 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1935 		ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1936 		goto out;
1937 	}
1938 
1939 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1940 	    fs_info->fs_devices->rw_devices == 1) {
1941 		ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1942 		goto out;
1943 	}
1944 
1945 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1946 		mutex_lock(&fs_info->chunk_mutex);
1947 		list_del_init(&device->dev_alloc_list);
1948 		device->fs_devices->rw_devices--;
1949 		mutex_unlock(&fs_info->chunk_mutex);
1950 	}
1951 
1952 	mutex_unlock(&uuid_mutex);
1953 	ret = btrfs_shrink_device(device, 0);
1954 	mutex_lock(&uuid_mutex);
1955 	if (ret)
1956 		goto error_undo;
1957 
1958 	/*
1959 	 * TODO: the superblock still includes this device in its num_devices
1960 	 * counter although write_all_supers() is not locked out. This
1961 	 * could give a filesystem state which requires a degraded mount.
1962 	 */
1963 	ret = btrfs_rm_dev_item(fs_info, device);
1964 	if (ret)
1965 		goto error_undo;
1966 
1967 	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1968 	btrfs_scrub_cancel_dev(fs_info, device);
1969 
1970 	/*
1971 	 * the device list mutex makes sure that we don't change
1972 	 * the device list while someone else is writing out all
1973 	 * the device supers. Whoever is writing all supers, should
1974 	 * lock the device list mutex before getting the number of
1975 	 * devices in the super block (super_copy). Conversely,
1976 	 * whoever updates the number of devices in the super block
1977 	 * (super_copy) should hold the device list mutex.
1978 	 */
1979 
1980 	cur_devices = device->fs_devices;
1981 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
1982 	list_del_rcu(&device->dev_list);
1983 
1984 	device->fs_devices->num_devices--;
1985 	device->fs_devices->total_devices--;
1986 
1987 	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1988 		device->fs_devices->missing_devices--;
1989 
1990 	btrfs_assign_next_active_device(fs_info, device, NULL);
1991 
1992 	if (device->bdev) {
1993 		device->fs_devices->open_devices--;
1994 		/* remove sysfs entry */
1995 		btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
1996 	}
1997 
1998 	num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1999 	btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2000 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2001 
2002 	/*
2003 	 * at this point, the device is zero sized and detached from
2004 	 * the devices list.  All that's left is to zero out the old
2005 	 * supers and free the device.
2006 	 */
2007 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2008 		btrfs_scratch_superblocks(device->bdev, device->name->str);
2009 
2010 	btrfs_close_bdev(device);
2011 	call_rcu(&device->rcu, free_device_rcu);
2012 
2013 	if (cur_devices->open_devices == 0) {
2014 		struct btrfs_fs_devices *fs_devices;
2015 		fs_devices = fs_info->fs_devices;
2016 		while (fs_devices) {
2017 			if (fs_devices->seed == cur_devices) {
2018 				fs_devices->seed = cur_devices->seed;
2019 				break;
2020 			}
2021 			fs_devices = fs_devices->seed;
2022 		}
2023 		cur_devices->seed = NULL;
2024 		__btrfs_close_devices(cur_devices);
2025 		free_fs_devices(cur_devices);
2026 	}
2027 
2028 out:
2029 	mutex_unlock(&uuid_mutex);
2030 	mutex_unlock(&fs_info->volume_mutex);
2031 	return ret;
2032 
2033 error_undo:
2034 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2035 		mutex_lock(&fs_info->chunk_mutex);
2036 		list_add(&device->dev_alloc_list,
2037 			 &fs_info->fs_devices->alloc_list);
2038 		device->fs_devices->rw_devices++;
2039 		mutex_unlock(&fs_info->chunk_mutex);
2040 	}
2041 	goto out;
2042 }
2043 
2044 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2045 					struct btrfs_device *srcdev)
2046 {
2047 	struct btrfs_fs_devices *fs_devices;
2048 
2049 	WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
2050 
2051 	/*
2052 	 * in case of fs with no seed, srcdev->fs_devices will point
2053 	 * to fs_devices of fs_info. However when the dev being replaced is
2054 	 * a seed dev it will point to the seed's local fs_devices. In short
2055 	 * srcdev will have its correct fs_devices in both the cases.
2056 	 */
2057 	fs_devices = srcdev->fs_devices;
2058 
2059 	list_del_rcu(&srcdev->dev_list);
2060 	list_del(&srcdev->dev_alloc_list);
2061 	fs_devices->num_devices--;
2062 	if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2063 		fs_devices->missing_devices--;
2064 
2065 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2066 		fs_devices->rw_devices--;
2067 
2068 	if (srcdev->bdev)
2069 		fs_devices->open_devices--;
2070 }
2071 
2072 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2073 				      struct btrfs_device *srcdev)
2074 {
2075 	struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2076 
2077 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2078 		/* zero out the old super if it is writable */
2079 		btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2080 	}
2081 
2082 	btrfs_close_bdev(srcdev);
2083 	call_rcu(&srcdev->rcu, free_device_rcu);
2084 
2085 	/* if this is no devs we rather delete the fs_devices */
2086 	if (!fs_devices->num_devices) {
2087 		struct btrfs_fs_devices *tmp_fs_devices;
2088 
2089 		/*
2090 		 * On a mounted FS, num_devices can't be zero unless it's a
2091 		 * seed. In case of a seed device being replaced, the replace
2092 		 * target added to the sprout FS, so there will be no more
2093 		 * device left under the seed FS.
2094 		 */
2095 		ASSERT(fs_devices->seeding);
2096 
2097 		tmp_fs_devices = fs_info->fs_devices;
2098 		while (tmp_fs_devices) {
2099 			if (tmp_fs_devices->seed == fs_devices) {
2100 				tmp_fs_devices->seed = fs_devices->seed;
2101 				break;
2102 			}
2103 			tmp_fs_devices = tmp_fs_devices->seed;
2104 		}
2105 		fs_devices->seed = NULL;
2106 		__btrfs_close_devices(fs_devices);
2107 		free_fs_devices(fs_devices);
2108 	}
2109 }
2110 
2111 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2112 				      struct btrfs_device *tgtdev)
2113 {
2114 	mutex_lock(&uuid_mutex);
2115 	WARN_ON(!tgtdev);
2116 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2117 
2118 	btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2119 
2120 	if (tgtdev->bdev)
2121 		fs_info->fs_devices->open_devices--;
2122 
2123 	fs_info->fs_devices->num_devices--;
2124 
2125 	btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2126 
2127 	list_del_rcu(&tgtdev->dev_list);
2128 
2129 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2130 	mutex_unlock(&uuid_mutex);
2131 
2132 	/*
2133 	 * The update_dev_time() with in btrfs_scratch_superblocks()
2134 	 * may lead to a call to btrfs_show_devname() which will try
2135 	 * to hold device_list_mutex. And here this device
2136 	 * is already out of device list, so we don't have to hold
2137 	 * the device_list_mutex lock.
2138 	 */
2139 	btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2140 
2141 	btrfs_close_bdev(tgtdev);
2142 	call_rcu(&tgtdev->rcu, free_device_rcu);
2143 }
2144 
2145 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2146 				     const char *device_path,
2147 				     struct btrfs_device **device)
2148 {
2149 	int ret = 0;
2150 	struct btrfs_super_block *disk_super;
2151 	u64 devid;
2152 	u8 *dev_uuid;
2153 	struct block_device *bdev;
2154 	struct buffer_head *bh;
2155 
2156 	*device = NULL;
2157 	ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2158 				    fs_info->bdev_holder, 0, &bdev, &bh);
2159 	if (ret)
2160 		return ret;
2161 	disk_super = (struct btrfs_super_block *)bh->b_data;
2162 	devid = btrfs_stack_device_id(&disk_super->dev_item);
2163 	dev_uuid = disk_super->dev_item.uuid;
2164 	*device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2165 	brelse(bh);
2166 	if (!*device)
2167 		ret = -ENOENT;
2168 	blkdev_put(bdev, FMODE_READ);
2169 	return ret;
2170 }
2171 
2172 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2173 					 const char *device_path,
2174 					 struct btrfs_device **device)
2175 {
2176 	*device = NULL;
2177 	if (strcmp(device_path, "missing") == 0) {
2178 		struct list_head *devices;
2179 		struct btrfs_device *tmp;
2180 
2181 		devices = &fs_info->fs_devices->devices;
2182 		/*
2183 		 * It is safe to read the devices since the volume_mutex
2184 		 * is held by the caller.
2185 		 */
2186 		list_for_each_entry(tmp, devices, dev_list) {
2187 			if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2188 					&tmp->dev_state) && !tmp->bdev) {
2189 				*device = tmp;
2190 				break;
2191 			}
2192 		}
2193 
2194 		if (!*device)
2195 			return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2196 
2197 		return 0;
2198 	} else {
2199 		return btrfs_find_device_by_path(fs_info, device_path, device);
2200 	}
2201 }
2202 
2203 /*
2204  * Lookup a device given by device id, or the path if the id is 0.
2205  */
2206 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2207 				 const char *devpath,
2208 				 struct btrfs_device **device)
2209 {
2210 	int ret;
2211 
2212 	if (devid) {
2213 		ret = 0;
2214 		*device = btrfs_find_device(fs_info, devid, NULL, NULL);
2215 		if (!*device)
2216 			ret = -ENOENT;
2217 	} else {
2218 		if (!devpath || !devpath[0])
2219 			return -EINVAL;
2220 
2221 		ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2222 							   device);
2223 	}
2224 	return ret;
2225 }
2226 
2227 /*
2228  * does all the dirty work required for changing file system's UUID.
2229  */
2230 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2231 {
2232 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2233 	struct btrfs_fs_devices *old_devices;
2234 	struct btrfs_fs_devices *seed_devices;
2235 	struct btrfs_super_block *disk_super = fs_info->super_copy;
2236 	struct btrfs_device *device;
2237 	u64 super_flags;
2238 
2239 	BUG_ON(!mutex_is_locked(&uuid_mutex));
2240 	if (!fs_devices->seeding)
2241 		return -EINVAL;
2242 
2243 	seed_devices = alloc_fs_devices(NULL);
2244 	if (IS_ERR(seed_devices))
2245 		return PTR_ERR(seed_devices);
2246 
2247 	old_devices = clone_fs_devices(fs_devices);
2248 	if (IS_ERR(old_devices)) {
2249 		kfree(seed_devices);
2250 		return PTR_ERR(old_devices);
2251 	}
2252 
2253 	list_add(&old_devices->list, &fs_uuids);
2254 
2255 	memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2256 	seed_devices->opened = 1;
2257 	INIT_LIST_HEAD(&seed_devices->devices);
2258 	INIT_LIST_HEAD(&seed_devices->alloc_list);
2259 	mutex_init(&seed_devices->device_list_mutex);
2260 
2261 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2262 	list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2263 			      synchronize_rcu);
2264 	list_for_each_entry(device, &seed_devices->devices, dev_list)
2265 		device->fs_devices = seed_devices;
2266 
2267 	mutex_lock(&fs_info->chunk_mutex);
2268 	list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2269 	mutex_unlock(&fs_info->chunk_mutex);
2270 
2271 	fs_devices->seeding = 0;
2272 	fs_devices->num_devices = 0;
2273 	fs_devices->open_devices = 0;
2274 	fs_devices->missing_devices = 0;
2275 	fs_devices->rotating = 0;
2276 	fs_devices->seed = seed_devices;
2277 
2278 	generate_random_uuid(fs_devices->fsid);
2279 	memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2280 	memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2281 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2282 
2283 	super_flags = btrfs_super_flags(disk_super) &
2284 		      ~BTRFS_SUPER_FLAG_SEEDING;
2285 	btrfs_set_super_flags(disk_super, super_flags);
2286 
2287 	return 0;
2288 }
2289 
2290 /*
2291  * Store the expected generation for seed devices in device items.
2292  */
2293 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2294 			       struct btrfs_fs_info *fs_info)
2295 {
2296 	struct btrfs_root *root = fs_info->chunk_root;
2297 	struct btrfs_path *path;
2298 	struct extent_buffer *leaf;
2299 	struct btrfs_dev_item *dev_item;
2300 	struct btrfs_device *device;
2301 	struct btrfs_key key;
2302 	u8 fs_uuid[BTRFS_FSID_SIZE];
2303 	u8 dev_uuid[BTRFS_UUID_SIZE];
2304 	u64 devid;
2305 	int ret;
2306 
2307 	path = btrfs_alloc_path();
2308 	if (!path)
2309 		return -ENOMEM;
2310 
2311 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2312 	key.offset = 0;
2313 	key.type = BTRFS_DEV_ITEM_KEY;
2314 
2315 	while (1) {
2316 		ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2317 		if (ret < 0)
2318 			goto error;
2319 
2320 		leaf = path->nodes[0];
2321 next_slot:
2322 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2323 			ret = btrfs_next_leaf(root, path);
2324 			if (ret > 0)
2325 				break;
2326 			if (ret < 0)
2327 				goto error;
2328 			leaf = path->nodes[0];
2329 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2330 			btrfs_release_path(path);
2331 			continue;
2332 		}
2333 
2334 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2335 		if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2336 		    key.type != BTRFS_DEV_ITEM_KEY)
2337 			break;
2338 
2339 		dev_item = btrfs_item_ptr(leaf, path->slots[0],
2340 					  struct btrfs_dev_item);
2341 		devid = btrfs_device_id(leaf, dev_item);
2342 		read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2343 				   BTRFS_UUID_SIZE);
2344 		read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2345 				   BTRFS_FSID_SIZE);
2346 		device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2347 		BUG_ON(!device); /* Logic error */
2348 
2349 		if (device->fs_devices->seeding) {
2350 			btrfs_set_device_generation(leaf, dev_item,
2351 						    device->generation);
2352 			btrfs_mark_buffer_dirty(leaf);
2353 		}
2354 
2355 		path->slots[0]++;
2356 		goto next_slot;
2357 	}
2358 	ret = 0;
2359 error:
2360 	btrfs_free_path(path);
2361 	return ret;
2362 }
2363 
2364 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2365 {
2366 	struct btrfs_root *root = fs_info->dev_root;
2367 	struct request_queue *q;
2368 	struct btrfs_trans_handle *trans;
2369 	struct btrfs_device *device;
2370 	struct block_device *bdev;
2371 	struct list_head *devices;
2372 	struct super_block *sb = fs_info->sb;
2373 	struct rcu_string *name;
2374 	u64 tmp;
2375 	int seeding_dev = 0;
2376 	int ret = 0;
2377 	bool unlocked = false;
2378 
2379 	if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2380 		return -EROFS;
2381 
2382 	bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2383 				  fs_info->bdev_holder);
2384 	if (IS_ERR(bdev))
2385 		return PTR_ERR(bdev);
2386 
2387 	if (fs_info->fs_devices->seeding) {
2388 		seeding_dev = 1;
2389 		down_write(&sb->s_umount);
2390 		mutex_lock(&uuid_mutex);
2391 	}
2392 
2393 	filemap_write_and_wait(bdev->bd_inode->i_mapping);
2394 
2395 	devices = &fs_info->fs_devices->devices;
2396 
2397 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2398 	list_for_each_entry(device, devices, dev_list) {
2399 		if (device->bdev == bdev) {
2400 			ret = -EEXIST;
2401 			mutex_unlock(
2402 				&fs_info->fs_devices->device_list_mutex);
2403 			goto error;
2404 		}
2405 	}
2406 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2407 
2408 	device = btrfs_alloc_device(fs_info, NULL, NULL);
2409 	if (IS_ERR(device)) {
2410 		/* we can safely leave the fs_devices entry around */
2411 		ret = PTR_ERR(device);
2412 		goto error;
2413 	}
2414 
2415 	name = rcu_string_strdup(device_path, GFP_KERNEL);
2416 	if (!name) {
2417 		ret = -ENOMEM;
2418 		goto error_free_device;
2419 	}
2420 	rcu_assign_pointer(device->name, name);
2421 
2422 	trans = btrfs_start_transaction(root, 0);
2423 	if (IS_ERR(trans)) {
2424 		ret = PTR_ERR(trans);
2425 		goto error_free_device;
2426 	}
2427 
2428 	q = bdev_get_queue(bdev);
2429 	set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2430 	device->generation = trans->transid;
2431 	device->io_width = fs_info->sectorsize;
2432 	device->io_align = fs_info->sectorsize;
2433 	device->sector_size = fs_info->sectorsize;
2434 	device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2435 					 fs_info->sectorsize);
2436 	device->disk_total_bytes = device->total_bytes;
2437 	device->commit_total_bytes = device->total_bytes;
2438 	device->fs_info = fs_info;
2439 	device->bdev = bdev;
2440 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2441 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2442 	device->mode = FMODE_EXCL;
2443 	device->dev_stats_valid = 1;
2444 	set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2445 
2446 	if (seeding_dev) {
2447 		sb->s_flags &= ~SB_RDONLY;
2448 		ret = btrfs_prepare_sprout(fs_info);
2449 		if (ret) {
2450 			btrfs_abort_transaction(trans, ret);
2451 			goto error_trans;
2452 		}
2453 	}
2454 
2455 	device->fs_devices = fs_info->fs_devices;
2456 
2457 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2458 	mutex_lock(&fs_info->chunk_mutex);
2459 	list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2460 	list_add(&device->dev_alloc_list,
2461 		 &fs_info->fs_devices->alloc_list);
2462 	fs_info->fs_devices->num_devices++;
2463 	fs_info->fs_devices->open_devices++;
2464 	fs_info->fs_devices->rw_devices++;
2465 	fs_info->fs_devices->total_devices++;
2466 	fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2467 
2468 	atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2469 
2470 	if (!blk_queue_nonrot(q))
2471 		fs_info->fs_devices->rotating = 1;
2472 
2473 	tmp = btrfs_super_total_bytes(fs_info->super_copy);
2474 	btrfs_set_super_total_bytes(fs_info->super_copy,
2475 		round_down(tmp + device->total_bytes, fs_info->sectorsize));
2476 
2477 	tmp = btrfs_super_num_devices(fs_info->super_copy);
2478 	btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2479 
2480 	/* add sysfs device entry */
2481 	btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2482 
2483 	/*
2484 	 * we've got more storage, clear any full flags on the space
2485 	 * infos
2486 	 */
2487 	btrfs_clear_space_info_full(fs_info);
2488 
2489 	mutex_unlock(&fs_info->chunk_mutex);
2490 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2491 
2492 	if (seeding_dev) {
2493 		mutex_lock(&fs_info->chunk_mutex);
2494 		ret = init_first_rw_device(trans, fs_info);
2495 		mutex_unlock(&fs_info->chunk_mutex);
2496 		if (ret) {
2497 			btrfs_abort_transaction(trans, ret);
2498 			goto error_sysfs;
2499 		}
2500 	}
2501 
2502 	ret = btrfs_add_dev_item(trans, fs_info, device);
2503 	if (ret) {
2504 		btrfs_abort_transaction(trans, ret);
2505 		goto error_sysfs;
2506 	}
2507 
2508 	if (seeding_dev) {
2509 		char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2510 
2511 		ret = btrfs_finish_sprout(trans, fs_info);
2512 		if (ret) {
2513 			btrfs_abort_transaction(trans, ret);
2514 			goto error_sysfs;
2515 		}
2516 
2517 		/* Sprouting would change fsid of the mounted root,
2518 		 * so rename the fsid on the sysfs
2519 		 */
2520 		snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2521 						fs_info->fsid);
2522 		if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2523 			btrfs_warn(fs_info,
2524 				   "sysfs: failed to create fsid for sprout");
2525 	}
2526 
2527 	ret = btrfs_commit_transaction(trans);
2528 
2529 	if (seeding_dev) {
2530 		mutex_unlock(&uuid_mutex);
2531 		up_write(&sb->s_umount);
2532 		unlocked = true;
2533 
2534 		if (ret) /* transaction commit */
2535 			return ret;
2536 
2537 		ret = btrfs_relocate_sys_chunks(fs_info);
2538 		if (ret < 0)
2539 			btrfs_handle_fs_error(fs_info, ret,
2540 				    "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2541 		trans = btrfs_attach_transaction(root);
2542 		if (IS_ERR(trans)) {
2543 			if (PTR_ERR(trans) == -ENOENT)
2544 				return 0;
2545 			ret = PTR_ERR(trans);
2546 			trans = NULL;
2547 			goto error_sysfs;
2548 		}
2549 		ret = btrfs_commit_transaction(trans);
2550 	}
2551 
2552 	/* Update ctime/mtime for libblkid */
2553 	update_dev_time(device_path);
2554 	return ret;
2555 
2556 error_sysfs:
2557 	btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2558 error_trans:
2559 	if (seeding_dev)
2560 		sb->s_flags |= SB_RDONLY;
2561 	if (trans)
2562 		btrfs_end_transaction(trans);
2563 error_free_device:
2564 	free_device(device);
2565 error:
2566 	blkdev_put(bdev, FMODE_EXCL);
2567 	if (seeding_dev && !unlocked) {
2568 		mutex_unlock(&uuid_mutex);
2569 		up_write(&sb->s_umount);
2570 	}
2571 	return ret;
2572 }
2573 
2574 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2575 				  const char *device_path,
2576 				  struct btrfs_device *srcdev,
2577 				  struct btrfs_device **device_out)
2578 {
2579 	struct btrfs_device *device;
2580 	struct block_device *bdev;
2581 	struct list_head *devices;
2582 	struct rcu_string *name;
2583 	u64 devid = BTRFS_DEV_REPLACE_DEVID;
2584 	int ret = 0;
2585 
2586 	*device_out = NULL;
2587 	if (fs_info->fs_devices->seeding) {
2588 		btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2589 		return -EINVAL;
2590 	}
2591 
2592 	bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2593 				  fs_info->bdev_holder);
2594 	if (IS_ERR(bdev)) {
2595 		btrfs_err(fs_info, "target device %s is invalid!", device_path);
2596 		return PTR_ERR(bdev);
2597 	}
2598 
2599 	filemap_write_and_wait(bdev->bd_inode->i_mapping);
2600 
2601 	devices = &fs_info->fs_devices->devices;
2602 	list_for_each_entry(device, devices, dev_list) {
2603 		if (device->bdev == bdev) {
2604 			btrfs_err(fs_info,
2605 				  "target device is in the filesystem!");
2606 			ret = -EEXIST;
2607 			goto error;
2608 		}
2609 	}
2610 
2611 
2612 	if (i_size_read(bdev->bd_inode) <
2613 	    btrfs_device_get_total_bytes(srcdev)) {
2614 		btrfs_err(fs_info,
2615 			  "target device is smaller than source device!");
2616 		ret = -EINVAL;
2617 		goto error;
2618 	}
2619 
2620 
2621 	device = btrfs_alloc_device(NULL, &devid, NULL);
2622 	if (IS_ERR(device)) {
2623 		ret = PTR_ERR(device);
2624 		goto error;
2625 	}
2626 
2627 	name = rcu_string_strdup(device_path, GFP_KERNEL);
2628 	if (!name) {
2629 		free_device(device);
2630 		ret = -ENOMEM;
2631 		goto error;
2632 	}
2633 	rcu_assign_pointer(device->name, name);
2634 
2635 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2636 	set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2637 	device->generation = 0;
2638 	device->io_width = fs_info->sectorsize;
2639 	device->io_align = fs_info->sectorsize;
2640 	device->sector_size = fs_info->sectorsize;
2641 	device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2642 	device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2643 	device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2644 	ASSERT(list_empty(&srcdev->resized_list));
2645 	device->commit_total_bytes = srcdev->commit_total_bytes;
2646 	device->commit_bytes_used = device->bytes_used;
2647 	device->fs_info = fs_info;
2648 	device->bdev = bdev;
2649 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2650 	set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2651 	device->mode = FMODE_EXCL;
2652 	device->dev_stats_valid = 1;
2653 	set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2654 	device->fs_devices = fs_info->fs_devices;
2655 	list_add(&device->dev_list, &fs_info->fs_devices->devices);
2656 	fs_info->fs_devices->num_devices++;
2657 	fs_info->fs_devices->open_devices++;
2658 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2659 
2660 	*device_out = device;
2661 	return ret;
2662 
2663 error:
2664 	blkdev_put(bdev, FMODE_EXCL);
2665 	return ret;
2666 }
2667 
2668 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2669 					      struct btrfs_device *tgtdev)
2670 {
2671 	u32 sectorsize = fs_info->sectorsize;
2672 
2673 	WARN_ON(fs_info->fs_devices->rw_devices == 0);
2674 	tgtdev->io_width = sectorsize;
2675 	tgtdev->io_align = sectorsize;
2676 	tgtdev->sector_size = sectorsize;
2677 	tgtdev->fs_info = fs_info;
2678 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &tgtdev->dev_state);
2679 }
2680 
2681 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2682 					struct btrfs_device *device)
2683 {
2684 	int ret;
2685 	struct btrfs_path *path;
2686 	struct btrfs_root *root = device->fs_info->chunk_root;
2687 	struct btrfs_dev_item *dev_item;
2688 	struct extent_buffer *leaf;
2689 	struct btrfs_key key;
2690 
2691 	path = btrfs_alloc_path();
2692 	if (!path)
2693 		return -ENOMEM;
2694 
2695 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2696 	key.type = BTRFS_DEV_ITEM_KEY;
2697 	key.offset = device->devid;
2698 
2699 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2700 	if (ret < 0)
2701 		goto out;
2702 
2703 	if (ret > 0) {
2704 		ret = -ENOENT;
2705 		goto out;
2706 	}
2707 
2708 	leaf = path->nodes[0];
2709 	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2710 
2711 	btrfs_set_device_id(leaf, dev_item, device->devid);
2712 	btrfs_set_device_type(leaf, dev_item, device->type);
2713 	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2714 	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2715 	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2716 	btrfs_set_device_total_bytes(leaf, dev_item,
2717 				     btrfs_device_get_disk_total_bytes(device));
2718 	btrfs_set_device_bytes_used(leaf, dev_item,
2719 				    btrfs_device_get_bytes_used(device));
2720 	btrfs_mark_buffer_dirty(leaf);
2721 
2722 out:
2723 	btrfs_free_path(path);
2724 	return ret;
2725 }
2726 
2727 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2728 		      struct btrfs_device *device, u64 new_size)
2729 {
2730 	struct btrfs_fs_info *fs_info = device->fs_info;
2731 	struct btrfs_super_block *super_copy = fs_info->super_copy;
2732 	struct btrfs_fs_devices *fs_devices;
2733 	u64 old_total;
2734 	u64 diff;
2735 
2736 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2737 		return -EACCES;
2738 
2739 	new_size = round_down(new_size, fs_info->sectorsize);
2740 
2741 	mutex_lock(&fs_info->chunk_mutex);
2742 	old_total = btrfs_super_total_bytes(super_copy);
2743 	diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2744 
2745 	if (new_size <= device->total_bytes ||
2746 	    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2747 		mutex_unlock(&fs_info->chunk_mutex);
2748 		return -EINVAL;
2749 	}
2750 
2751 	fs_devices = fs_info->fs_devices;
2752 
2753 	btrfs_set_super_total_bytes(super_copy,
2754 			round_down(old_total + diff, fs_info->sectorsize));
2755 	device->fs_devices->total_rw_bytes += diff;
2756 
2757 	btrfs_device_set_total_bytes(device, new_size);
2758 	btrfs_device_set_disk_total_bytes(device, new_size);
2759 	btrfs_clear_space_info_full(device->fs_info);
2760 	if (list_empty(&device->resized_list))
2761 		list_add_tail(&device->resized_list,
2762 			      &fs_devices->resized_devices);
2763 	mutex_unlock(&fs_info->chunk_mutex);
2764 
2765 	return btrfs_update_device(trans, device);
2766 }
2767 
2768 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2769 			    struct btrfs_fs_info *fs_info, u64 chunk_offset)
2770 {
2771 	struct btrfs_root *root = fs_info->chunk_root;
2772 	int ret;
2773 	struct btrfs_path *path;
2774 	struct btrfs_key key;
2775 
2776 	path = btrfs_alloc_path();
2777 	if (!path)
2778 		return -ENOMEM;
2779 
2780 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2781 	key.offset = chunk_offset;
2782 	key.type = BTRFS_CHUNK_ITEM_KEY;
2783 
2784 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2785 	if (ret < 0)
2786 		goto out;
2787 	else if (ret > 0) { /* Logic error or corruption */
2788 		btrfs_handle_fs_error(fs_info, -ENOENT,
2789 				      "Failed lookup while freeing chunk.");
2790 		ret = -ENOENT;
2791 		goto out;
2792 	}
2793 
2794 	ret = btrfs_del_item(trans, root, path);
2795 	if (ret < 0)
2796 		btrfs_handle_fs_error(fs_info, ret,
2797 				      "Failed to delete chunk item.");
2798 out:
2799 	btrfs_free_path(path);
2800 	return ret;
2801 }
2802 
2803 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2804 {
2805 	struct btrfs_super_block *super_copy = fs_info->super_copy;
2806 	struct btrfs_disk_key *disk_key;
2807 	struct btrfs_chunk *chunk;
2808 	u8 *ptr;
2809 	int ret = 0;
2810 	u32 num_stripes;
2811 	u32 array_size;
2812 	u32 len = 0;
2813 	u32 cur;
2814 	struct btrfs_key key;
2815 
2816 	mutex_lock(&fs_info->chunk_mutex);
2817 	array_size = btrfs_super_sys_array_size(super_copy);
2818 
2819 	ptr = super_copy->sys_chunk_array;
2820 	cur = 0;
2821 
2822 	while (cur < array_size) {
2823 		disk_key = (struct btrfs_disk_key *)ptr;
2824 		btrfs_disk_key_to_cpu(&key, disk_key);
2825 
2826 		len = sizeof(*disk_key);
2827 
2828 		if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2829 			chunk = (struct btrfs_chunk *)(ptr + len);
2830 			num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2831 			len += btrfs_chunk_item_size(num_stripes);
2832 		} else {
2833 			ret = -EIO;
2834 			break;
2835 		}
2836 		if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2837 		    key.offset == chunk_offset) {
2838 			memmove(ptr, ptr + len, array_size - (cur + len));
2839 			array_size -= len;
2840 			btrfs_set_super_sys_array_size(super_copy, array_size);
2841 		} else {
2842 			ptr += len;
2843 			cur += len;
2844 		}
2845 	}
2846 	mutex_unlock(&fs_info->chunk_mutex);
2847 	return ret;
2848 }
2849 
2850 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2851 					u64 logical, u64 length)
2852 {
2853 	struct extent_map_tree *em_tree;
2854 	struct extent_map *em;
2855 
2856 	em_tree = &fs_info->mapping_tree.map_tree;
2857 	read_lock(&em_tree->lock);
2858 	em = lookup_extent_mapping(em_tree, logical, length);
2859 	read_unlock(&em_tree->lock);
2860 
2861 	if (!em) {
2862 		btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2863 			   logical, length);
2864 		return ERR_PTR(-EINVAL);
2865 	}
2866 
2867 	if (em->start > logical || em->start + em->len < logical) {
2868 		btrfs_crit(fs_info,
2869 			   "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2870 			   logical, length, em->start, em->start + em->len);
2871 		free_extent_map(em);
2872 		return ERR_PTR(-EINVAL);
2873 	}
2874 
2875 	/* callers are responsible for dropping em's ref. */
2876 	return em;
2877 }
2878 
2879 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2880 		       struct btrfs_fs_info *fs_info, u64 chunk_offset)
2881 {
2882 	struct extent_map *em;
2883 	struct map_lookup *map;
2884 	u64 dev_extent_len = 0;
2885 	int i, ret = 0;
2886 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2887 
2888 	em = get_chunk_map(fs_info, chunk_offset, 1);
2889 	if (IS_ERR(em)) {
2890 		/*
2891 		 * This is a logic error, but we don't want to just rely on the
2892 		 * user having built with ASSERT enabled, so if ASSERT doesn't
2893 		 * do anything we still error out.
2894 		 */
2895 		ASSERT(0);
2896 		return PTR_ERR(em);
2897 	}
2898 	map = em->map_lookup;
2899 	mutex_lock(&fs_info->chunk_mutex);
2900 	check_system_chunk(trans, fs_info, map->type);
2901 	mutex_unlock(&fs_info->chunk_mutex);
2902 
2903 	/*
2904 	 * Take the device list mutex to prevent races with the final phase of
2905 	 * a device replace operation that replaces the device object associated
2906 	 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2907 	 */
2908 	mutex_lock(&fs_devices->device_list_mutex);
2909 	for (i = 0; i < map->num_stripes; i++) {
2910 		struct btrfs_device *device = map->stripes[i].dev;
2911 		ret = btrfs_free_dev_extent(trans, device,
2912 					    map->stripes[i].physical,
2913 					    &dev_extent_len);
2914 		if (ret) {
2915 			mutex_unlock(&fs_devices->device_list_mutex);
2916 			btrfs_abort_transaction(trans, ret);
2917 			goto out;
2918 		}
2919 
2920 		if (device->bytes_used > 0) {
2921 			mutex_lock(&fs_info->chunk_mutex);
2922 			btrfs_device_set_bytes_used(device,
2923 					device->bytes_used - dev_extent_len);
2924 			atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2925 			btrfs_clear_space_info_full(fs_info);
2926 			mutex_unlock(&fs_info->chunk_mutex);
2927 		}
2928 
2929 		if (map->stripes[i].dev) {
2930 			ret = btrfs_update_device(trans, map->stripes[i].dev);
2931 			if (ret) {
2932 				mutex_unlock(&fs_devices->device_list_mutex);
2933 				btrfs_abort_transaction(trans, ret);
2934 				goto out;
2935 			}
2936 		}
2937 	}
2938 	mutex_unlock(&fs_devices->device_list_mutex);
2939 
2940 	ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2941 	if (ret) {
2942 		btrfs_abort_transaction(trans, ret);
2943 		goto out;
2944 	}
2945 
2946 	trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2947 
2948 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2949 		ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2950 		if (ret) {
2951 			btrfs_abort_transaction(trans, ret);
2952 			goto out;
2953 		}
2954 	}
2955 
2956 	ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2957 	if (ret) {
2958 		btrfs_abort_transaction(trans, ret);
2959 		goto out;
2960 	}
2961 
2962 out:
2963 	/* once for us */
2964 	free_extent_map(em);
2965 	return ret;
2966 }
2967 
2968 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2969 {
2970 	struct btrfs_root *root = fs_info->chunk_root;
2971 	struct btrfs_trans_handle *trans;
2972 	int ret;
2973 
2974 	/*
2975 	 * Prevent races with automatic removal of unused block groups.
2976 	 * After we relocate and before we remove the chunk with offset
2977 	 * chunk_offset, automatic removal of the block group can kick in,
2978 	 * resulting in a failure when calling btrfs_remove_chunk() below.
2979 	 *
2980 	 * Make sure to acquire this mutex before doing a tree search (dev
2981 	 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2982 	 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2983 	 * we release the path used to search the chunk/dev tree and before
2984 	 * the current task acquires this mutex and calls us.
2985 	 */
2986 	ASSERT(mutex_is_locked(&fs_info->delete_unused_bgs_mutex));
2987 
2988 	ret = btrfs_can_relocate(fs_info, chunk_offset);
2989 	if (ret)
2990 		return -ENOSPC;
2991 
2992 	/* step one, relocate all the extents inside this chunk */
2993 	btrfs_scrub_pause(fs_info);
2994 	ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2995 	btrfs_scrub_continue(fs_info);
2996 	if (ret)
2997 		return ret;
2998 
2999 	trans = btrfs_start_trans_remove_block_group(root->fs_info,
3000 						     chunk_offset);
3001 	if (IS_ERR(trans)) {
3002 		ret = PTR_ERR(trans);
3003 		btrfs_handle_fs_error(root->fs_info, ret, NULL);
3004 		return ret;
3005 	}
3006 
3007 	/*
3008 	 * step two, delete the device extents and the
3009 	 * chunk tree entries
3010 	 */
3011 	ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3012 	btrfs_end_transaction(trans);
3013 	return ret;
3014 }
3015 
3016 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3017 {
3018 	struct btrfs_root *chunk_root = fs_info->chunk_root;
3019 	struct btrfs_path *path;
3020 	struct extent_buffer *leaf;
3021 	struct btrfs_chunk *chunk;
3022 	struct btrfs_key key;
3023 	struct btrfs_key found_key;
3024 	u64 chunk_type;
3025 	bool retried = false;
3026 	int failed = 0;
3027 	int ret;
3028 
3029 	path = btrfs_alloc_path();
3030 	if (!path)
3031 		return -ENOMEM;
3032 
3033 again:
3034 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3035 	key.offset = (u64)-1;
3036 	key.type = BTRFS_CHUNK_ITEM_KEY;
3037 
3038 	while (1) {
3039 		mutex_lock(&fs_info->delete_unused_bgs_mutex);
3040 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3041 		if (ret < 0) {
3042 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3043 			goto error;
3044 		}
3045 		BUG_ON(ret == 0); /* Corruption */
3046 
3047 		ret = btrfs_previous_item(chunk_root, path, key.objectid,
3048 					  key.type);
3049 		if (ret)
3050 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3051 		if (ret < 0)
3052 			goto error;
3053 		if (ret > 0)
3054 			break;
3055 
3056 		leaf = path->nodes[0];
3057 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3058 
3059 		chunk = btrfs_item_ptr(leaf, path->slots[0],
3060 				       struct btrfs_chunk);
3061 		chunk_type = btrfs_chunk_type(leaf, chunk);
3062 		btrfs_release_path(path);
3063 
3064 		if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3065 			ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3066 			if (ret == -ENOSPC)
3067 				failed++;
3068 			else
3069 				BUG_ON(ret);
3070 		}
3071 		mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3072 
3073 		if (found_key.offset == 0)
3074 			break;
3075 		key.offset = found_key.offset - 1;
3076 	}
3077 	ret = 0;
3078 	if (failed && !retried) {
3079 		failed = 0;
3080 		retried = true;
3081 		goto again;
3082 	} else if (WARN_ON(failed && retried)) {
3083 		ret = -ENOSPC;
3084 	}
3085 error:
3086 	btrfs_free_path(path);
3087 	return ret;
3088 }
3089 
3090 /*
3091  * return 1 : allocate a data chunk successfully,
3092  * return <0: errors during allocating a data chunk,
3093  * return 0 : no need to allocate a data chunk.
3094  */
3095 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3096 				      u64 chunk_offset)
3097 {
3098 	struct btrfs_block_group_cache *cache;
3099 	u64 bytes_used;
3100 	u64 chunk_type;
3101 
3102 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3103 	ASSERT(cache);
3104 	chunk_type = cache->flags;
3105 	btrfs_put_block_group(cache);
3106 
3107 	if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3108 		spin_lock(&fs_info->data_sinfo->lock);
3109 		bytes_used = fs_info->data_sinfo->bytes_used;
3110 		spin_unlock(&fs_info->data_sinfo->lock);
3111 
3112 		if (!bytes_used) {
3113 			struct btrfs_trans_handle *trans;
3114 			int ret;
3115 
3116 			trans =	btrfs_join_transaction(fs_info->tree_root);
3117 			if (IS_ERR(trans))
3118 				return PTR_ERR(trans);
3119 
3120 			ret = btrfs_force_chunk_alloc(trans, fs_info,
3121 						      BTRFS_BLOCK_GROUP_DATA);
3122 			btrfs_end_transaction(trans);
3123 			if (ret < 0)
3124 				return ret;
3125 
3126 			return 1;
3127 		}
3128 	}
3129 	return 0;
3130 }
3131 
3132 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3133 			       struct btrfs_balance_control *bctl)
3134 {
3135 	struct btrfs_root *root = fs_info->tree_root;
3136 	struct btrfs_trans_handle *trans;
3137 	struct btrfs_balance_item *item;
3138 	struct btrfs_disk_balance_args disk_bargs;
3139 	struct btrfs_path *path;
3140 	struct extent_buffer *leaf;
3141 	struct btrfs_key key;
3142 	int ret, err;
3143 
3144 	path = btrfs_alloc_path();
3145 	if (!path)
3146 		return -ENOMEM;
3147 
3148 	trans = btrfs_start_transaction(root, 0);
3149 	if (IS_ERR(trans)) {
3150 		btrfs_free_path(path);
3151 		return PTR_ERR(trans);
3152 	}
3153 
3154 	key.objectid = BTRFS_BALANCE_OBJECTID;
3155 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3156 	key.offset = 0;
3157 
3158 	ret = btrfs_insert_empty_item(trans, root, path, &key,
3159 				      sizeof(*item));
3160 	if (ret)
3161 		goto out;
3162 
3163 	leaf = path->nodes[0];
3164 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3165 
3166 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3167 
3168 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3169 	btrfs_set_balance_data(leaf, item, &disk_bargs);
3170 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3171 	btrfs_set_balance_meta(leaf, item, &disk_bargs);
3172 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3173 	btrfs_set_balance_sys(leaf, item, &disk_bargs);
3174 
3175 	btrfs_set_balance_flags(leaf, item, bctl->flags);
3176 
3177 	btrfs_mark_buffer_dirty(leaf);
3178 out:
3179 	btrfs_free_path(path);
3180 	err = btrfs_commit_transaction(trans);
3181 	if (err && !ret)
3182 		ret = err;
3183 	return ret;
3184 }
3185 
3186 static int del_balance_item(struct btrfs_fs_info *fs_info)
3187 {
3188 	struct btrfs_root *root = fs_info->tree_root;
3189 	struct btrfs_trans_handle *trans;
3190 	struct btrfs_path *path;
3191 	struct btrfs_key key;
3192 	int ret, err;
3193 
3194 	path = btrfs_alloc_path();
3195 	if (!path)
3196 		return -ENOMEM;
3197 
3198 	trans = btrfs_start_transaction(root, 0);
3199 	if (IS_ERR(trans)) {
3200 		btrfs_free_path(path);
3201 		return PTR_ERR(trans);
3202 	}
3203 
3204 	key.objectid = BTRFS_BALANCE_OBJECTID;
3205 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3206 	key.offset = 0;
3207 
3208 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3209 	if (ret < 0)
3210 		goto out;
3211 	if (ret > 0) {
3212 		ret = -ENOENT;
3213 		goto out;
3214 	}
3215 
3216 	ret = btrfs_del_item(trans, root, path);
3217 out:
3218 	btrfs_free_path(path);
3219 	err = btrfs_commit_transaction(trans);
3220 	if (err && !ret)
3221 		ret = err;
3222 	return ret;
3223 }
3224 
3225 /*
3226  * This is a heuristic used to reduce the number of chunks balanced on
3227  * resume after balance was interrupted.
3228  */
3229 static void update_balance_args(struct btrfs_balance_control *bctl)
3230 {
3231 	/*
3232 	 * Turn on soft mode for chunk types that were being converted.
3233 	 */
3234 	if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3235 		bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3236 	if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3237 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3238 	if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3239 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3240 
3241 	/*
3242 	 * Turn on usage filter if is not already used.  The idea is
3243 	 * that chunks that we have already balanced should be
3244 	 * reasonably full.  Don't do it for chunks that are being
3245 	 * converted - that will keep us from relocating unconverted
3246 	 * (albeit full) chunks.
3247 	 */
3248 	if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3249 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3250 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3251 		bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3252 		bctl->data.usage = 90;
3253 	}
3254 	if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3255 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3256 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3257 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3258 		bctl->sys.usage = 90;
3259 	}
3260 	if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3261 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3262 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3263 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3264 		bctl->meta.usage = 90;
3265 	}
3266 }
3267 
3268 /*
3269  * Should be called with both balance and volume mutexes held to
3270  * serialize other volume operations (add_dev/rm_dev/resize) with
3271  * restriper.  Same goes for unset_balance_control.
3272  */
3273 static void set_balance_control(struct btrfs_balance_control *bctl)
3274 {
3275 	struct btrfs_fs_info *fs_info = bctl->fs_info;
3276 
3277 	BUG_ON(fs_info->balance_ctl);
3278 
3279 	spin_lock(&fs_info->balance_lock);
3280 	fs_info->balance_ctl = bctl;
3281 	spin_unlock(&fs_info->balance_lock);
3282 }
3283 
3284 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3285 {
3286 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3287 
3288 	BUG_ON(!fs_info->balance_ctl);
3289 
3290 	spin_lock(&fs_info->balance_lock);
3291 	fs_info->balance_ctl = NULL;
3292 	spin_unlock(&fs_info->balance_lock);
3293 
3294 	kfree(bctl);
3295 }
3296 
3297 /*
3298  * Balance filters.  Return 1 if chunk should be filtered out
3299  * (should not be balanced).
3300  */
3301 static int chunk_profiles_filter(u64 chunk_type,
3302 				 struct btrfs_balance_args *bargs)
3303 {
3304 	chunk_type = chunk_to_extended(chunk_type) &
3305 				BTRFS_EXTENDED_PROFILE_MASK;
3306 
3307 	if (bargs->profiles & chunk_type)
3308 		return 0;
3309 
3310 	return 1;
3311 }
3312 
3313 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3314 			      struct btrfs_balance_args *bargs)
3315 {
3316 	struct btrfs_block_group_cache *cache;
3317 	u64 chunk_used;
3318 	u64 user_thresh_min;
3319 	u64 user_thresh_max;
3320 	int ret = 1;
3321 
3322 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3323 	chunk_used = btrfs_block_group_used(&cache->item);
3324 
3325 	if (bargs->usage_min == 0)
3326 		user_thresh_min = 0;
3327 	else
3328 		user_thresh_min = div_factor_fine(cache->key.offset,
3329 					bargs->usage_min);
3330 
3331 	if (bargs->usage_max == 0)
3332 		user_thresh_max = 1;
3333 	else if (bargs->usage_max > 100)
3334 		user_thresh_max = cache->key.offset;
3335 	else
3336 		user_thresh_max = div_factor_fine(cache->key.offset,
3337 					bargs->usage_max);
3338 
3339 	if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3340 		ret = 0;
3341 
3342 	btrfs_put_block_group(cache);
3343 	return ret;
3344 }
3345 
3346 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3347 		u64 chunk_offset, struct btrfs_balance_args *bargs)
3348 {
3349 	struct btrfs_block_group_cache *cache;
3350 	u64 chunk_used, user_thresh;
3351 	int ret = 1;
3352 
3353 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3354 	chunk_used = btrfs_block_group_used(&cache->item);
3355 
3356 	if (bargs->usage_min == 0)
3357 		user_thresh = 1;
3358 	else if (bargs->usage > 100)
3359 		user_thresh = cache->key.offset;
3360 	else
3361 		user_thresh = div_factor_fine(cache->key.offset,
3362 					      bargs->usage);
3363 
3364 	if (chunk_used < user_thresh)
3365 		ret = 0;
3366 
3367 	btrfs_put_block_group(cache);
3368 	return ret;
3369 }
3370 
3371 static int chunk_devid_filter(struct extent_buffer *leaf,
3372 			      struct btrfs_chunk *chunk,
3373 			      struct btrfs_balance_args *bargs)
3374 {
3375 	struct btrfs_stripe *stripe;
3376 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3377 	int i;
3378 
3379 	for (i = 0; i < num_stripes; i++) {
3380 		stripe = btrfs_stripe_nr(chunk, i);
3381 		if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3382 			return 0;
3383 	}
3384 
3385 	return 1;
3386 }
3387 
3388 /* [pstart, pend) */
3389 static int chunk_drange_filter(struct extent_buffer *leaf,
3390 			       struct btrfs_chunk *chunk,
3391 			       struct btrfs_balance_args *bargs)
3392 {
3393 	struct btrfs_stripe *stripe;
3394 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3395 	u64 stripe_offset;
3396 	u64 stripe_length;
3397 	int factor;
3398 	int i;
3399 
3400 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3401 		return 0;
3402 
3403 	if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3404 	     BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3405 		factor = num_stripes / 2;
3406 	} else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3407 		factor = num_stripes - 1;
3408 	} else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3409 		factor = num_stripes - 2;
3410 	} else {
3411 		factor = num_stripes;
3412 	}
3413 
3414 	for (i = 0; i < num_stripes; i++) {
3415 		stripe = btrfs_stripe_nr(chunk, i);
3416 		if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3417 			continue;
3418 
3419 		stripe_offset = btrfs_stripe_offset(leaf, stripe);
3420 		stripe_length = btrfs_chunk_length(leaf, chunk);
3421 		stripe_length = div_u64(stripe_length, factor);
3422 
3423 		if (stripe_offset < bargs->pend &&
3424 		    stripe_offset + stripe_length > bargs->pstart)
3425 			return 0;
3426 	}
3427 
3428 	return 1;
3429 }
3430 
3431 /* [vstart, vend) */
3432 static int chunk_vrange_filter(struct extent_buffer *leaf,
3433 			       struct btrfs_chunk *chunk,
3434 			       u64 chunk_offset,
3435 			       struct btrfs_balance_args *bargs)
3436 {
3437 	if (chunk_offset < bargs->vend &&
3438 	    chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3439 		/* at least part of the chunk is inside this vrange */
3440 		return 0;
3441 
3442 	return 1;
3443 }
3444 
3445 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3446 			       struct btrfs_chunk *chunk,
3447 			       struct btrfs_balance_args *bargs)
3448 {
3449 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3450 
3451 	if (bargs->stripes_min <= num_stripes
3452 			&& num_stripes <= bargs->stripes_max)
3453 		return 0;
3454 
3455 	return 1;
3456 }
3457 
3458 static int chunk_soft_convert_filter(u64 chunk_type,
3459 				     struct btrfs_balance_args *bargs)
3460 {
3461 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3462 		return 0;
3463 
3464 	chunk_type = chunk_to_extended(chunk_type) &
3465 				BTRFS_EXTENDED_PROFILE_MASK;
3466 
3467 	if (bargs->target == chunk_type)
3468 		return 1;
3469 
3470 	return 0;
3471 }
3472 
3473 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3474 				struct extent_buffer *leaf,
3475 				struct btrfs_chunk *chunk, u64 chunk_offset)
3476 {
3477 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3478 	struct btrfs_balance_args *bargs = NULL;
3479 	u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3480 
3481 	/* type filter */
3482 	if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3483 	      (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3484 		return 0;
3485 	}
3486 
3487 	if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3488 		bargs = &bctl->data;
3489 	else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3490 		bargs = &bctl->sys;
3491 	else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3492 		bargs = &bctl->meta;
3493 
3494 	/* profiles filter */
3495 	if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3496 	    chunk_profiles_filter(chunk_type, bargs)) {
3497 		return 0;
3498 	}
3499 
3500 	/* usage filter */
3501 	if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3502 	    chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3503 		return 0;
3504 	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3505 	    chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3506 		return 0;
3507 	}
3508 
3509 	/* devid filter */
3510 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3511 	    chunk_devid_filter(leaf, chunk, bargs)) {
3512 		return 0;
3513 	}
3514 
3515 	/* drange filter, makes sense only with devid filter */
3516 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3517 	    chunk_drange_filter(leaf, chunk, bargs)) {
3518 		return 0;
3519 	}
3520 
3521 	/* vrange filter */
3522 	if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3523 	    chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3524 		return 0;
3525 	}
3526 
3527 	/* stripes filter */
3528 	if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3529 	    chunk_stripes_range_filter(leaf, chunk, bargs)) {
3530 		return 0;
3531 	}
3532 
3533 	/* soft profile changing mode */
3534 	if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3535 	    chunk_soft_convert_filter(chunk_type, bargs)) {
3536 		return 0;
3537 	}
3538 
3539 	/*
3540 	 * limited by count, must be the last filter
3541 	 */
3542 	if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3543 		if (bargs->limit == 0)
3544 			return 0;
3545 		else
3546 			bargs->limit--;
3547 	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3548 		/*
3549 		 * Same logic as the 'limit' filter; the minimum cannot be
3550 		 * determined here because we do not have the global information
3551 		 * about the count of all chunks that satisfy the filters.
3552 		 */
3553 		if (bargs->limit_max == 0)
3554 			return 0;
3555 		else
3556 			bargs->limit_max--;
3557 	}
3558 
3559 	return 1;
3560 }
3561 
3562 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3563 {
3564 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3565 	struct btrfs_root *chunk_root = fs_info->chunk_root;
3566 	struct btrfs_root *dev_root = fs_info->dev_root;
3567 	struct list_head *devices;
3568 	struct btrfs_device *device;
3569 	u64 old_size;
3570 	u64 size_to_free;
3571 	u64 chunk_type;
3572 	struct btrfs_chunk *chunk;
3573 	struct btrfs_path *path = NULL;
3574 	struct btrfs_key key;
3575 	struct btrfs_key found_key;
3576 	struct btrfs_trans_handle *trans;
3577 	struct extent_buffer *leaf;
3578 	int slot;
3579 	int ret;
3580 	int enospc_errors = 0;
3581 	bool counting = true;
3582 	/* The single value limit and min/max limits use the same bytes in the */
3583 	u64 limit_data = bctl->data.limit;
3584 	u64 limit_meta = bctl->meta.limit;
3585 	u64 limit_sys = bctl->sys.limit;
3586 	u32 count_data = 0;
3587 	u32 count_meta = 0;
3588 	u32 count_sys = 0;
3589 	int chunk_reserved = 0;
3590 
3591 	/* step one make some room on all the devices */
3592 	devices = &fs_info->fs_devices->devices;
3593 	list_for_each_entry(device, devices, dev_list) {
3594 		old_size = btrfs_device_get_total_bytes(device);
3595 		size_to_free = div_factor(old_size, 1);
3596 		size_to_free = min_t(u64, size_to_free, SZ_1M);
3597 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3598 		    btrfs_device_get_total_bytes(device) -
3599 		    btrfs_device_get_bytes_used(device) > size_to_free ||
3600 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3601 			continue;
3602 
3603 		ret = btrfs_shrink_device(device, old_size - size_to_free);
3604 		if (ret == -ENOSPC)
3605 			break;
3606 		if (ret) {
3607 			/* btrfs_shrink_device never returns ret > 0 */
3608 			WARN_ON(ret > 0);
3609 			goto error;
3610 		}
3611 
3612 		trans = btrfs_start_transaction(dev_root, 0);
3613 		if (IS_ERR(trans)) {
3614 			ret = PTR_ERR(trans);
3615 			btrfs_info_in_rcu(fs_info,
3616 		 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3617 					  rcu_str_deref(device->name), ret,
3618 					  old_size, old_size - size_to_free);
3619 			goto error;
3620 		}
3621 
3622 		ret = btrfs_grow_device(trans, device, old_size);
3623 		if (ret) {
3624 			btrfs_end_transaction(trans);
3625 			/* btrfs_grow_device never returns ret > 0 */
3626 			WARN_ON(ret > 0);
3627 			btrfs_info_in_rcu(fs_info,
3628 		 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3629 					  rcu_str_deref(device->name), ret,
3630 					  old_size, old_size - size_to_free);
3631 			goto error;
3632 		}
3633 
3634 		btrfs_end_transaction(trans);
3635 	}
3636 
3637 	/* step two, relocate all the chunks */
3638 	path = btrfs_alloc_path();
3639 	if (!path) {
3640 		ret = -ENOMEM;
3641 		goto error;
3642 	}
3643 
3644 	/* zero out stat counters */
3645 	spin_lock(&fs_info->balance_lock);
3646 	memset(&bctl->stat, 0, sizeof(bctl->stat));
3647 	spin_unlock(&fs_info->balance_lock);
3648 again:
3649 	if (!counting) {
3650 		/*
3651 		 * The single value limit and min/max limits use the same bytes
3652 		 * in the
3653 		 */
3654 		bctl->data.limit = limit_data;
3655 		bctl->meta.limit = limit_meta;
3656 		bctl->sys.limit = limit_sys;
3657 	}
3658 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3659 	key.offset = (u64)-1;
3660 	key.type = BTRFS_CHUNK_ITEM_KEY;
3661 
3662 	while (1) {
3663 		if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3664 		    atomic_read(&fs_info->balance_cancel_req)) {
3665 			ret = -ECANCELED;
3666 			goto error;
3667 		}
3668 
3669 		mutex_lock(&fs_info->delete_unused_bgs_mutex);
3670 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3671 		if (ret < 0) {
3672 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3673 			goto error;
3674 		}
3675 
3676 		/*
3677 		 * this shouldn't happen, it means the last relocate
3678 		 * failed
3679 		 */
3680 		if (ret == 0)
3681 			BUG(); /* FIXME break ? */
3682 
3683 		ret = btrfs_previous_item(chunk_root, path, 0,
3684 					  BTRFS_CHUNK_ITEM_KEY);
3685 		if (ret) {
3686 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3687 			ret = 0;
3688 			break;
3689 		}
3690 
3691 		leaf = path->nodes[0];
3692 		slot = path->slots[0];
3693 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3694 
3695 		if (found_key.objectid != key.objectid) {
3696 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3697 			break;
3698 		}
3699 
3700 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3701 		chunk_type = btrfs_chunk_type(leaf, chunk);
3702 
3703 		if (!counting) {
3704 			spin_lock(&fs_info->balance_lock);
3705 			bctl->stat.considered++;
3706 			spin_unlock(&fs_info->balance_lock);
3707 		}
3708 
3709 		ret = should_balance_chunk(fs_info, leaf, chunk,
3710 					   found_key.offset);
3711 
3712 		btrfs_release_path(path);
3713 		if (!ret) {
3714 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3715 			goto loop;
3716 		}
3717 
3718 		if (counting) {
3719 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3720 			spin_lock(&fs_info->balance_lock);
3721 			bctl->stat.expected++;
3722 			spin_unlock(&fs_info->balance_lock);
3723 
3724 			if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3725 				count_data++;
3726 			else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3727 				count_sys++;
3728 			else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3729 				count_meta++;
3730 
3731 			goto loop;
3732 		}
3733 
3734 		/*
3735 		 * Apply limit_min filter, no need to check if the LIMITS
3736 		 * filter is used, limit_min is 0 by default
3737 		 */
3738 		if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3739 					count_data < bctl->data.limit_min)
3740 				|| ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3741 					count_meta < bctl->meta.limit_min)
3742 				|| ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3743 					count_sys < bctl->sys.limit_min)) {
3744 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3745 			goto loop;
3746 		}
3747 
3748 		if (!chunk_reserved) {
3749 			/*
3750 			 * We may be relocating the only data chunk we have,
3751 			 * which could potentially end up with losing data's
3752 			 * raid profile, so lets allocate an empty one in
3753 			 * advance.
3754 			 */
3755 			ret = btrfs_may_alloc_data_chunk(fs_info,
3756 							 found_key.offset);
3757 			if (ret < 0) {
3758 				mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3759 				goto error;
3760 			} else if (ret == 1) {
3761 				chunk_reserved = 1;
3762 			}
3763 		}
3764 
3765 		ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3766 		mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3767 		if (ret && ret != -ENOSPC)
3768 			goto error;
3769 		if (ret == -ENOSPC) {
3770 			enospc_errors++;
3771 		} else {
3772 			spin_lock(&fs_info->balance_lock);
3773 			bctl->stat.completed++;
3774 			spin_unlock(&fs_info->balance_lock);
3775 		}
3776 loop:
3777 		if (found_key.offset == 0)
3778 			break;
3779 		key.offset = found_key.offset - 1;
3780 	}
3781 
3782 	if (counting) {
3783 		btrfs_release_path(path);
3784 		counting = false;
3785 		goto again;
3786 	}
3787 error:
3788 	btrfs_free_path(path);
3789 	if (enospc_errors) {
3790 		btrfs_info(fs_info, "%d enospc errors during balance",
3791 			   enospc_errors);
3792 		if (!ret)
3793 			ret = -ENOSPC;
3794 	}
3795 
3796 	return ret;
3797 }
3798 
3799 /**
3800  * alloc_profile_is_valid - see if a given profile is valid and reduced
3801  * @flags: profile to validate
3802  * @extended: if true @flags is treated as an extended profile
3803  */
3804 static int alloc_profile_is_valid(u64 flags, int extended)
3805 {
3806 	u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3807 			       BTRFS_BLOCK_GROUP_PROFILE_MASK);
3808 
3809 	flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3810 
3811 	/* 1) check that all other bits are zeroed */
3812 	if (flags & ~mask)
3813 		return 0;
3814 
3815 	/* 2) see if profile is reduced */
3816 	if (flags == 0)
3817 		return !extended; /* "0" is valid for usual profiles */
3818 
3819 	/* true if exactly one bit set */
3820 	return (flags & (flags - 1)) == 0;
3821 }
3822 
3823 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3824 {
3825 	/* cancel requested || normal exit path */
3826 	return atomic_read(&fs_info->balance_cancel_req) ||
3827 		(atomic_read(&fs_info->balance_pause_req) == 0 &&
3828 		 atomic_read(&fs_info->balance_cancel_req) == 0);
3829 }
3830 
3831 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3832 {
3833 	int ret;
3834 
3835 	unset_balance_control(fs_info);
3836 	ret = del_balance_item(fs_info);
3837 	if (ret)
3838 		btrfs_handle_fs_error(fs_info, ret, NULL);
3839 
3840 	clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3841 }
3842 
3843 /* Non-zero return value signifies invalidity */
3844 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3845 		u64 allowed)
3846 {
3847 	return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3848 		(!alloc_profile_is_valid(bctl_arg->target, 1) ||
3849 		 (bctl_arg->target & ~allowed)));
3850 }
3851 
3852 /*
3853  * Should be called with both balance and volume mutexes held
3854  */
3855 int btrfs_balance(struct btrfs_balance_control *bctl,
3856 		  struct btrfs_ioctl_balance_args *bargs)
3857 {
3858 	struct btrfs_fs_info *fs_info = bctl->fs_info;
3859 	u64 meta_target, data_target;
3860 	u64 allowed;
3861 	int mixed = 0;
3862 	int ret;
3863 	u64 num_devices;
3864 	unsigned seq;
3865 
3866 	if (btrfs_fs_closing(fs_info) ||
3867 	    atomic_read(&fs_info->balance_pause_req) ||
3868 	    atomic_read(&fs_info->balance_cancel_req)) {
3869 		ret = -EINVAL;
3870 		goto out;
3871 	}
3872 
3873 	allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3874 	if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3875 		mixed = 1;
3876 
3877 	/*
3878 	 * In case of mixed groups both data and meta should be picked,
3879 	 * and identical options should be given for both of them.
3880 	 */
3881 	allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3882 	if (mixed && (bctl->flags & allowed)) {
3883 		if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3884 		    !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3885 		    memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3886 			btrfs_err(fs_info,
3887 				  "with mixed groups data and metadata balance options must be the same");
3888 			ret = -EINVAL;
3889 			goto out;
3890 		}
3891 	}
3892 
3893 	num_devices = fs_info->fs_devices->num_devices;
3894 	btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3895 	if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3896 		BUG_ON(num_devices < 1);
3897 		num_devices--;
3898 	}
3899 	btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3900 	allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3901 	if (num_devices > 1)
3902 		allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3903 	if (num_devices > 2)
3904 		allowed |= BTRFS_BLOCK_GROUP_RAID5;
3905 	if (num_devices > 3)
3906 		allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3907 			    BTRFS_BLOCK_GROUP_RAID6);
3908 	if (validate_convert_profile(&bctl->data, allowed)) {
3909 		btrfs_err(fs_info,
3910 			  "unable to start balance with target data profile %llu",
3911 			  bctl->data.target);
3912 		ret = -EINVAL;
3913 		goto out;
3914 	}
3915 	if (validate_convert_profile(&bctl->meta, allowed)) {
3916 		btrfs_err(fs_info,
3917 			  "unable to start balance with target metadata profile %llu",
3918 			  bctl->meta.target);
3919 		ret = -EINVAL;
3920 		goto out;
3921 	}
3922 	if (validate_convert_profile(&bctl->sys, allowed)) {
3923 		btrfs_err(fs_info,
3924 			  "unable to start balance with target system profile %llu",
3925 			  bctl->sys.target);
3926 		ret = -EINVAL;
3927 		goto out;
3928 	}
3929 
3930 	/* allow to reduce meta or sys integrity only if force set */
3931 	allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3932 			BTRFS_BLOCK_GROUP_RAID10 |
3933 			BTRFS_BLOCK_GROUP_RAID5 |
3934 			BTRFS_BLOCK_GROUP_RAID6;
3935 	do {
3936 		seq = read_seqbegin(&fs_info->profiles_lock);
3937 
3938 		if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3939 		     (fs_info->avail_system_alloc_bits & allowed) &&
3940 		     !(bctl->sys.target & allowed)) ||
3941 		    ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3942 		     (fs_info->avail_metadata_alloc_bits & allowed) &&
3943 		     !(bctl->meta.target & allowed))) {
3944 			if (bctl->flags & BTRFS_BALANCE_FORCE) {
3945 				btrfs_info(fs_info,
3946 					   "force reducing metadata integrity");
3947 			} else {
3948 				btrfs_err(fs_info,
3949 					  "balance will reduce metadata integrity, use force if you want this");
3950 				ret = -EINVAL;
3951 				goto out;
3952 			}
3953 		}
3954 	} while (read_seqretry(&fs_info->profiles_lock, seq));
3955 
3956 	/* if we're not converting, the target field is uninitialized */
3957 	meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3958 		bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3959 	data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3960 		bctl->data.target : fs_info->avail_data_alloc_bits;
3961 	if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3962 		btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3963 		btrfs_warn(fs_info,
3964 			   "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3965 			   meta_target, data_target);
3966 	}
3967 
3968 	ret = insert_balance_item(fs_info, bctl);
3969 	if (ret && ret != -EEXIST)
3970 		goto out;
3971 
3972 	if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3973 		BUG_ON(ret == -EEXIST);
3974 		set_balance_control(bctl);
3975 	} else {
3976 		BUG_ON(ret != -EEXIST);
3977 		spin_lock(&fs_info->balance_lock);
3978 		update_balance_args(bctl);
3979 		spin_unlock(&fs_info->balance_lock);
3980 	}
3981 
3982 	atomic_inc(&fs_info->balance_running);
3983 	mutex_unlock(&fs_info->balance_mutex);
3984 
3985 	ret = __btrfs_balance(fs_info);
3986 
3987 	mutex_lock(&fs_info->balance_mutex);
3988 	atomic_dec(&fs_info->balance_running);
3989 
3990 	if (bargs) {
3991 		memset(bargs, 0, sizeof(*bargs));
3992 		update_ioctl_balance_args(fs_info, 0, bargs);
3993 	}
3994 
3995 	if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3996 	    balance_need_close(fs_info)) {
3997 		__cancel_balance(fs_info);
3998 	}
3999 
4000 	wake_up(&fs_info->balance_wait_q);
4001 
4002 	return ret;
4003 out:
4004 	if (bctl->flags & BTRFS_BALANCE_RESUME)
4005 		__cancel_balance(fs_info);
4006 	else {
4007 		kfree(bctl);
4008 		clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4009 	}
4010 	return ret;
4011 }
4012 
4013 static int balance_kthread(void *data)
4014 {
4015 	struct btrfs_fs_info *fs_info = data;
4016 	int ret = 0;
4017 
4018 	mutex_lock(&fs_info->volume_mutex);
4019 	mutex_lock(&fs_info->balance_mutex);
4020 
4021 	if (fs_info->balance_ctl) {
4022 		btrfs_info(fs_info, "continuing balance");
4023 		ret = btrfs_balance(fs_info->balance_ctl, NULL);
4024 	}
4025 
4026 	mutex_unlock(&fs_info->balance_mutex);
4027 	mutex_unlock(&fs_info->volume_mutex);
4028 
4029 	return ret;
4030 }
4031 
4032 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4033 {
4034 	struct task_struct *tsk;
4035 
4036 	spin_lock(&fs_info->balance_lock);
4037 	if (!fs_info->balance_ctl) {
4038 		spin_unlock(&fs_info->balance_lock);
4039 		return 0;
4040 	}
4041 	spin_unlock(&fs_info->balance_lock);
4042 
4043 	if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4044 		btrfs_info(fs_info, "force skipping balance");
4045 		return 0;
4046 	}
4047 
4048 	tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4049 	return PTR_ERR_OR_ZERO(tsk);
4050 }
4051 
4052 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4053 {
4054 	struct btrfs_balance_control *bctl;
4055 	struct btrfs_balance_item *item;
4056 	struct btrfs_disk_balance_args disk_bargs;
4057 	struct btrfs_path *path;
4058 	struct extent_buffer *leaf;
4059 	struct btrfs_key key;
4060 	int ret;
4061 
4062 	path = btrfs_alloc_path();
4063 	if (!path)
4064 		return -ENOMEM;
4065 
4066 	key.objectid = BTRFS_BALANCE_OBJECTID;
4067 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
4068 	key.offset = 0;
4069 
4070 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4071 	if (ret < 0)
4072 		goto out;
4073 	if (ret > 0) { /* ret = -ENOENT; */
4074 		ret = 0;
4075 		goto out;
4076 	}
4077 
4078 	bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4079 	if (!bctl) {
4080 		ret = -ENOMEM;
4081 		goto out;
4082 	}
4083 
4084 	leaf = path->nodes[0];
4085 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4086 
4087 	bctl->fs_info = fs_info;
4088 	bctl->flags = btrfs_balance_flags(leaf, item);
4089 	bctl->flags |= BTRFS_BALANCE_RESUME;
4090 
4091 	btrfs_balance_data(leaf, item, &disk_bargs);
4092 	btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4093 	btrfs_balance_meta(leaf, item, &disk_bargs);
4094 	btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4095 	btrfs_balance_sys(leaf, item, &disk_bargs);
4096 	btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4097 
4098 	WARN_ON(test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4099 
4100 	mutex_lock(&fs_info->volume_mutex);
4101 	mutex_lock(&fs_info->balance_mutex);
4102 
4103 	set_balance_control(bctl);
4104 
4105 	mutex_unlock(&fs_info->balance_mutex);
4106 	mutex_unlock(&fs_info->volume_mutex);
4107 out:
4108 	btrfs_free_path(path);
4109 	return ret;
4110 }
4111 
4112 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4113 {
4114 	int ret = 0;
4115 
4116 	mutex_lock(&fs_info->balance_mutex);
4117 	if (!fs_info->balance_ctl) {
4118 		mutex_unlock(&fs_info->balance_mutex);
4119 		return -ENOTCONN;
4120 	}
4121 
4122 	if (atomic_read(&fs_info->balance_running)) {
4123 		atomic_inc(&fs_info->balance_pause_req);
4124 		mutex_unlock(&fs_info->balance_mutex);
4125 
4126 		wait_event(fs_info->balance_wait_q,
4127 			   atomic_read(&fs_info->balance_running) == 0);
4128 
4129 		mutex_lock(&fs_info->balance_mutex);
4130 		/* we are good with balance_ctl ripped off from under us */
4131 		BUG_ON(atomic_read(&fs_info->balance_running));
4132 		atomic_dec(&fs_info->balance_pause_req);
4133 	} else {
4134 		ret = -ENOTCONN;
4135 	}
4136 
4137 	mutex_unlock(&fs_info->balance_mutex);
4138 	return ret;
4139 }
4140 
4141 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4142 {
4143 	if (sb_rdonly(fs_info->sb))
4144 		return -EROFS;
4145 
4146 	mutex_lock(&fs_info->balance_mutex);
4147 	if (!fs_info->balance_ctl) {
4148 		mutex_unlock(&fs_info->balance_mutex);
4149 		return -ENOTCONN;
4150 	}
4151 
4152 	atomic_inc(&fs_info->balance_cancel_req);
4153 	/*
4154 	 * if we are running just wait and return, balance item is
4155 	 * deleted in btrfs_balance in this case
4156 	 */
4157 	if (atomic_read(&fs_info->balance_running)) {
4158 		mutex_unlock(&fs_info->balance_mutex);
4159 		wait_event(fs_info->balance_wait_q,
4160 			   atomic_read(&fs_info->balance_running) == 0);
4161 		mutex_lock(&fs_info->balance_mutex);
4162 	} else {
4163 		/* __cancel_balance needs volume_mutex */
4164 		mutex_unlock(&fs_info->balance_mutex);
4165 		mutex_lock(&fs_info->volume_mutex);
4166 		mutex_lock(&fs_info->balance_mutex);
4167 
4168 		if (fs_info->balance_ctl)
4169 			__cancel_balance(fs_info);
4170 
4171 		mutex_unlock(&fs_info->volume_mutex);
4172 	}
4173 
4174 	BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4175 	atomic_dec(&fs_info->balance_cancel_req);
4176 	mutex_unlock(&fs_info->balance_mutex);
4177 	return 0;
4178 }
4179 
4180 static int btrfs_uuid_scan_kthread(void *data)
4181 {
4182 	struct btrfs_fs_info *fs_info = data;
4183 	struct btrfs_root *root = fs_info->tree_root;
4184 	struct btrfs_key key;
4185 	struct btrfs_path *path = NULL;
4186 	int ret = 0;
4187 	struct extent_buffer *eb;
4188 	int slot;
4189 	struct btrfs_root_item root_item;
4190 	u32 item_size;
4191 	struct btrfs_trans_handle *trans = NULL;
4192 
4193 	path = btrfs_alloc_path();
4194 	if (!path) {
4195 		ret = -ENOMEM;
4196 		goto out;
4197 	}
4198 
4199 	key.objectid = 0;
4200 	key.type = BTRFS_ROOT_ITEM_KEY;
4201 	key.offset = 0;
4202 
4203 	while (1) {
4204 		ret = btrfs_search_forward(root, &key, path, 0);
4205 		if (ret) {
4206 			if (ret > 0)
4207 				ret = 0;
4208 			break;
4209 		}
4210 
4211 		if (key.type != BTRFS_ROOT_ITEM_KEY ||
4212 		    (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4213 		     key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4214 		    key.objectid > BTRFS_LAST_FREE_OBJECTID)
4215 			goto skip;
4216 
4217 		eb = path->nodes[0];
4218 		slot = path->slots[0];
4219 		item_size = btrfs_item_size_nr(eb, slot);
4220 		if (item_size < sizeof(root_item))
4221 			goto skip;
4222 
4223 		read_extent_buffer(eb, &root_item,
4224 				   btrfs_item_ptr_offset(eb, slot),
4225 				   (int)sizeof(root_item));
4226 		if (btrfs_root_refs(&root_item) == 0)
4227 			goto skip;
4228 
4229 		if (!btrfs_is_empty_uuid(root_item.uuid) ||
4230 		    !btrfs_is_empty_uuid(root_item.received_uuid)) {
4231 			if (trans)
4232 				goto update_tree;
4233 
4234 			btrfs_release_path(path);
4235 			/*
4236 			 * 1 - subvol uuid item
4237 			 * 1 - received_subvol uuid item
4238 			 */
4239 			trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4240 			if (IS_ERR(trans)) {
4241 				ret = PTR_ERR(trans);
4242 				break;
4243 			}
4244 			continue;
4245 		} else {
4246 			goto skip;
4247 		}
4248 update_tree:
4249 		if (!btrfs_is_empty_uuid(root_item.uuid)) {
4250 			ret = btrfs_uuid_tree_add(trans, fs_info,
4251 						  root_item.uuid,
4252 						  BTRFS_UUID_KEY_SUBVOL,
4253 						  key.objectid);
4254 			if (ret < 0) {
4255 				btrfs_warn(fs_info, "uuid_tree_add failed %d",
4256 					ret);
4257 				break;
4258 			}
4259 		}
4260 
4261 		if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4262 			ret = btrfs_uuid_tree_add(trans, fs_info,
4263 						  root_item.received_uuid,
4264 						 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4265 						  key.objectid);
4266 			if (ret < 0) {
4267 				btrfs_warn(fs_info, "uuid_tree_add failed %d",
4268 					ret);
4269 				break;
4270 			}
4271 		}
4272 
4273 skip:
4274 		if (trans) {
4275 			ret = btrfs_end_transaction(trans);
4276 			trans = NULL;
4277 			if (ret)
4278 				break;
4279 		}
4280 
4281 		btrfs_release_path(path);
4282 		if (key.offset < (u64)-1) {
4283 			key.offset++;
4284 		} else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4285 			key.offset = 0;
4286 			key.type = BTRFS_ROOT_ITEM_KEY;
4287 		} else if (key.objectid < (u64)-1) {
4288 			key.offset = 0;
4289 			key.type = BTRFS_ROOT_ITEM_KEY;
4290 			key.objectid++;
4291 		} else {
4292 			break;
4293 		}
4294 		cond_resched();
4295 	}
4296 
4297 out:
4298 	btrfs_free_path(path);
4299 	if (trans && !IS_ERR(trans))
4300 		btrfs_end_transaction(trans);
4301 	if (ret)
4302 		btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4303 	else
4304 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4305 	up(&fs_info->uuid_tree_rescan_sem);
4306 	return 0;
4307 }
4308 
4309 /*
4310  * Callback for btrfs_uuid_tree_iterate().
4311  * returns:
4312  * 0	check succeeded, the entry is not outdated.
4313  * < 0	if an error occurred.
4314  * > 0	if the check failed, which means the caller shall remove the entry.
4315  */
4316 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4317 				       u8 *uuid, u8 type, u64 subid)
4318 {
4319 	struct btrfs_key key;
4320 	int ret = 0;
4321 	struct btrfs_root *subvol_root;
4322 
4323 	if (type != BTRFS_UUID_KEY_SUBVOL &&
4324 	    type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4325 		goto out;
4326 
4327 	key.objectid = subid;
4328 	key.type = BTRFS_ROOT_ITEM_KEY;
4329 	key.offset = (u64)-1;
4330 	subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4331 	if (IS_ERR(subvol_root)) {
4332 		ret = PTR_ERR(subvol_root);
4333 		if (ret == -ENOENT)
4334 			ret = 1;
4335 		goto out;
4336 	}
4337 
4338 	switch (type) {
4339 	case BTRFS_UUID_KEY_SUBVOL:
4340 		if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4341 			ret = 1;
4342 		break;
4343 	case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4344 		if (memcmp(uuid, subvol_root->root_item.received_uuid,
4345 			   BTRFS_UUID_SIZE))
4346 			ret = 1;
4347 		break;
4348 	}
4349 
4350 out:
4351 	return ret;
4352 }
4353 
4354 static int btrfs_uuid_rescan_kthread(void *data)
4355 {
4356 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4357 	int ret;
4358 
4359 	/*
4360 	 * 1st step is to iterate through the existing UUID tree and
4361 	 * to delete all entries that contain outdated data.
4362 	 * 2nd step is to add all missing entries to the UUID tree.
4363 	 */
4364 	ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4365 	if (ret < 0) {
4366 		btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4367 		up(&fs_info->uuid_tree_rescan_sem);
4368 		return ret;
4369 	}
4370 	return btrfs_uuid_scan_kthread(data);
4371 }
4372 
4373 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4374 {
4375 	struct btrfs_trans_handle *trans;
4376 	struct btrfs_root *tree_root = fs_info->tree_root;
4377 	struct btrfs_root *uuid_root;
4378 	struct task_struct *task;
4379 	int ret;
4380 
4381 	/*
4382 	 * 1 - root node
4383 	 * 1 - root item
4384 	 */
4385 	trans = btrfs_start_transaction(tree_root, 2);
4386 	if (IS_ERR(trans))
4387 		return PTR_ERR(trans);
4388 
4389 	uuid_root = btrfs_create_tree(trans, fs_info,
4390 				      BTRFS_UUID_TREE_OBJECTID);
4391 	if (IS_ERR(uuid_root)) {
4392 		ret = PTR_ERR(uuid_root);
4393 		btrfs_abort_transaction(trans, ret);
4394 		btrfs_end_transaction(trans);
4395 		return ret;
4396 	}
4397 
4398 	fs_info->uuid_root = uuid_root;
4399 
4400 	ret = btrfs_commit_transaction(trans);
4401 	if (ret)
4402 		return ret;
4403 
4404 	down(&fs_info->uuid_tree_rescan_sem);
4405 	task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4406 	if (IS_ERR(task)) {
4407 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
4408 		btrfs_warn(fs_info, "failed to start uuid_scan task");
4409 		up(&fs_info->uuid_tree_rescan_sem);
4410 		return PTR_ERR(task);
4411 	}
4412 
4413 	return 0;
4414 }
4415 
4416 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4417 {
4418 	struct task_struct *task;
4419 
4420 	down(&fs_info->uuid_tree_rescan_sem);
4421 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4422 	if (IS_ERR(task)) {
4423 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
4424 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
4425 		up(&fs_info->uuid_tree_rescan_sem);
4426 		return PTR_ERR(task);
4427 	}
4428 
4429 	return 0;
4430 }
4431 
4432 /*
4433  * shrinking a device means finding all of the device extents past
4434  * the new size, and then following the back refs to the chunks.
4435  * The chunk relocation code actually frees the device extent
4436  */
4437 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4438 {
4439 	struct btrfs_fs_info *fs_info = device->fs_info;
4440 	struct btrfs_root *root = fs_info->dev_root;
4441 	struct btrfs_trans_handle *trans;
4442 	struct btrfs_dev_extent *dev_extent = NULL;
4443 	struct btrfs_path *path;
4444 	u64 length;
4445 	u64 chunk_offset;
4446 	int ret;
4447 	int slot;
4448 	int failed = 0;
4449 	bool retried = false;
4450 	bool checked_pending_chunks = false;
4451 	struct extent_buffer *l;
4452 	struct btrfs_key key;
4453 	struct btrfs_super_block *super_copy = fs_info->super_copy;
4454 	u64 old_total = btrfs_super_total_bytes(super_copy);
4455 	u64 old_size = btrfs_device_get_total_bytes(device);
4456 	u64 diff;
4457 
4458 	new_size = round_down(new_size, fs_info->sectorsize);
4459 	diff = round_down(old_size - new_size, fs_info->sectorsize);
4460 
4461 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4462 		return -EINVAL;
4463 
4464 	path = btrfs_alloc_path();
4465 	if (!path)
4466 		return -ENOMEM;
4467 
4468 	path->reada = READA_FORWARD;
4469 
4470 	mutex_lock(&fs_info->chunk_mutex);
4471 
4472 	btrfs_device_set_total_bytes(device, new_size);
4473 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4474 		device->fs_devices->total_rw_bytes -= diff;
4475 		atomic64_sub(diff, &fs_info->free_chunk_space);
4476 	}
4477 	mutex_unlock(&fs_info->chunk_mutex);
4478 
4479 again:
4480 	key.objectid = device->devid;
4481 	key.offset = (u64)-1;
4482 	key.type = BTRFS_DEV_EXTENT_KEY;
4483 
4484 	do {
4485 		mutex_lock(&fs_info->delete_unused_bgs_mutex);
4486 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4487 		if (ret < 0) {
4488 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4489 			goto done;
4490 		}
4491 
4492 		ret = btrfs_previous_item(root, path, 0, key.type);
4493 		if (ret)
4494 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4495 		if (ret < 0)
4496 			goto done;
4497 		if (ret) {
4498 			ret = 0;
4499 			btrfs_release_path(path);
4500 			break;
4501 		}
4502 
4503 		l = path->nodes[0];
4504 		slot = path->slots[0];
4505 		btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4506 
4507 		if (key.objectid != device->devid) {
4508 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4509 			btrfs_release_path(path);
4510 			break;
4511 		}
4512 
4513 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4514 		length = btrfs_dev_extent_length(l, dev_extent);
4515 
4516 		if (key.offset + length <= new_size) {
4517 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4518 			btrfs_release_path(path);
4519 			break;
4520 		}
4521 
4522 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4523 		btrfs_release_path(path);
4524 
4525 		/*
4526 		 * We may be relocating the only data chunk we have,
4527 		 * which could potentially end up with losing data's
4528 		 * raid profile, so lets allocate an empty one in
4529 		 * advance.
4530 		 */
4531 		ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4532 		if (ret < 0) {
4533 			mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4534 			goto done;
4535 		}
4536 
4537 		ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4538 		mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4539 		if (ret && ret != -ENOSPC)
4540 			goto done;
4541 		if (ret == -ENOSPC)
4542 			failed++;
4543 	} while (key.offset-- > 0);
4544 
4545 	if (failed && !retried) {
4546 		failed = 0;
4547 		retried = true;
4548 		goto again;
4549 	} else if (failed && retried) {
4550 		ret = -ENOSPC;
4551 		goto done;
4552 	}
4553 
4554 	/* Shrinking succeeded, else we would be at "done". */
4555 	trans = btrfs_start_transaction(root, 0);
4556 	if (IS_ERR(trans)) {
4557 		ret = PTR_ERR(trans);
4558 		goto done;
4559 	}
4560 
4561 	mutex_lock(&fs_info->chunk_mutex);
4562 
4563 	/*
4564 	 * We checked in the above loop all device extents that were already in
4565 	 * the device tree. However before we have updated the device's
4566 	 * total_bytes to the new size, we might have had chunk allocations that
4567 	 * have not complete yet (new block groups attached to transaction
4568 	 * handles), and therefore their device extents were not yet in the
4569 	 * device tree and we missed them in the loop above. So if we have any
4570 	 * pending chunk using a device extent that overlaps the device range
4571 	 * that we can not use anymore, commit the current transaction and
4572 	 * repeat the search on the device tree - this way we guarantee we will
4573 	 * not have chunks using device extents that end beyond 'new_size'.
4574 	 */
4575 	if (!checked_pending_chunks) {
4576 		u64 start = new_size;
4577 		u64 len = old_size - new_size;
4578 
4579 		if (contains_pending_extent(trans->transaction, device,
4580 					    &start, len)) {
4581 			mutex_unlock(&fs_info->chunk_mutex);
4582 			checked_pending_chunks = true;
4583 			failed = 0;
4584 			retried = false;
4585 			ret = btrfs_commit_transaction(trans);
4586 			if (ret)
4587 				goto done;
4588 			goto again;
4589 		}
4590 	}
4591 
4592 	btrfs_device_set_disk_total_bytes(device, new_size);
4593 	if (list_empty(&device->resized_list))
4594 		list_add_tail(&device->resized_list,
4595 			      &fs_info->fs_devices->resized_devices);
4596 
4597 	WARN_ON(diff > old_total);
4598 	btrfs_set_super_total_bytes(super_copy,
4599 			round_down(old_total - diff, fs_info->sectorsize));
4600 	mutex_unlock(&fs_info->chunk_mutex);
4601 
4602 	/* Now btrfs_update_device() will change the on-disk size. */
4603 	ret = btrfs_update_device(trans, device);
4604 	btrfs_end_transaction(trans);
4605 done:
4606 	btrfs_free_path(path);
4607 	if (ret) {
4608 		mutex_lock(&fs_info->chunk_mutex);
4609 		btrfs_device_set_total_bytes(device, old_size);
4610 		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4611 			device->fs_devices->total_rw_bytes += diff;
4612 		atomic64_add(diff, &fs_info->free_chunk_space);
4613 		mutex_unlock(&fs_info->chunk_mutex);
4614 	}
4615 	return ret;
4616 }
4617 
4618 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4619 			   struct btrfs_key *key,
4620 			   struct btrfs_chunk *chunk, int item_size)
4621 {
4622 	struct btrfs_super_block *super_copy = fs_info->super_copy;
4623 	struct btrfs_disk_key disk_key;
4624 	u32 array_size;
4625 	u8 *ptr;
4626 
4627 	mutex_lock(&fs_info->chunk_mutex);
4628 	array_size = btrfs_super_sys_array_size(super_copy);
4629 	if (array_size + item_size + sizeof(disk_key)
4630 			> BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4631 		mutex_unlock(&fs_info->chunk_mutex);
4632 		return -EFBIG;
4633 	}
4634 
4635 	ptr = super_copy->sys_chunk_array + array_size;
4636 	btrfs_cpu_key_to_disk(&disk_key, key);
4637 	memcpy(ptr, &disk_key, sizeof(disk_key));
4638 	ptr += sizeof(disk_key);
4639 	memcpy(ptr, chunk, item_size);
4640 	item_size += sizeof(disk_key);
4641 	btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4642 	mutex_unlock(&fs_info->chunk_mutex);
4643 
4644 	return 0;
4645 }
4646 
4647 /*
4648  * sort the devices in descending order by max_avail, total_avail
4649  */
4650 static int btrfs_cmp_device_info(const void *a, const void *b)
4651 {
4652 	const struct btrfs_device_info *di_a = a;
4653 	const struct btrfs_device_info *di_b = b;
4654 
4655 	if (di_a->max_avail > di_b->max_avail)
4656 		return -1;
4657 	if (di_a->max_avail < di_b->max_avail)
4658 		return 1;
4659 	if (di_a->total_avail > di_b->total_avail)
4660 		return -1;
4661 	if (di_a->total_avail < di_b->total_avail)
4662 		return 1;
4663 	return 0;
4664 }
4665 
4666 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4667 {
4668 	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4669 		return;
4670 
4671 	btrfs_set_fs_incompat(info, RAID56);
4672 }
4673 
4674 #define BTRFS_MAX_DEVS(r) ((BTRFS_MAX_ITEM_SIZE(r->fs_info)		\
4675 			- sizeof(struct btrfs_chunk))		\
4676 			/ sizeof(struct btrfs_stripe) + 1)
4677 
4678 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE	\
4679 				- 2 * sizeof(struct btrfs_disk_key)	\
4680 				- 2 * sizeof(struct btrfs_chunk))	\
4681 				/ sizeof(struct btrfs_stripe) + 1)
4682 
4683 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4684 			       u64 start, u64 type)
4685 {
4686 	struct btrfs_fs_info *info = trans->fs_info;
4687 	struct btrfs_fs_devices *fs_devices = info->fs_devices;
4688 	struct btrfs_device *device;
4689 	struct map_lookup *map = NULL;
4690 	struct extent_map_tree *em_tree;
4691 	struct extent_map *em;
4692 	struct btrfs_device_info *devices_info = NULL;
4693 	u64 total_avail;
4694 	int num_stripes;	/* total number of stripes to allocate */
4695 	int data_stripes;	/* number of stripes that count for
4696 				   block group size */
4697 	int sub_stripes;	/* sub_stripes info for map */
4698 	int dev_stripes;	/* stripes per dev */
4699 	int devs_max;		/* max devs to use */
4700 	int devs_min;		/* min devs needed */
4701 	int devs_increment;	/* ndevs has to be a multiple of this */
4702 	int ncopies;		/* how many copies to data has */
4703 	int ret;
4704 	u64 max_stripe_size;
4705 	u64 max_chunk_size;
4706 	u64 stripe_size;
4707 	u64 num_bytes;
4708 	int ndevs;
4709 	int i;
4710 	int j;
4711 	int index;
4712 
4713 	BUG_ON(!alloc_profile_is_valid(type, 0));
4714 
4715 	if (list_empty(&fs_devices->alloc_list))
4716 		return -ENOSPC;
4717 
4718 	index = __get_raid_index(type);
4719 
4720 	sub_stripes = btrfs_raid_array[index].sub_stripes;
4721 	dev_stripes = btrfs_raid_array[index].dev_stripes;
4722 	devs_max = btrfs_raid_array[index].devs_max;
4723 	devs_min = btrfs_raid_array[index].devs_min;
4724 	devs_increment = btrfs_raid_array[index].devs_increment;
4725 	ncopies = btrfs_raid_array[index].ncopies;
4726 
4727 	if (type & BTRFS_BLOCK_GROUP_DATA) {
4728 		max_stripe_size = SZ_1G;
4729 		max_chunk_size = 10 * max_stripe_size;
4730 		if (!devs_max)
4731 			devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4732 	} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4733 		/* for larger filesystems, use larger metadata chunks */
4734 		if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4735 			max_stripe_size = SZ_1G;
4736 		else
4737 			max_stripe_size = SZ_256M;
4738 		max_chunk_size = max_stripe_size;
4739 		if (!devs_max)
4740 			devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4741 	} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4742 		max_stripe_size = SZ_32M;
4743 		max_chunk_size = 2 * max_stripe_size;
4744 		if (!devs_max)
4745 			devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4746 	} else {
4747 		btrfs_err(info, "invalid chunk type 0x%llx requested",
4748 		       type);
4749 		BUG_ON(1);
4750 	}
4751 
4752 	/* we don't want a chunk larger than 10% of writeable space */
4753 	max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4754 			     max_chunk_size);
4755 
4756 	devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4757 			       GFP_NOFS);
4758 	if (!devices_info)
4759 		return -ENOMEM;
4760 
4761 	/*
4762 	 * in the first pass through the devices list, we gather information
4763 	 * about the available holes on each device.
4764 	 */
4765 	ndevs = 0;
4766 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4767 		u64 max_avail;
4768 		u64 dev_offset;
4769 
4770 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4771 			WARN(1, KERN_ERR
4772 			       "BTRFS: read-only device in alloc_list\n");
4773 			continue;
4774 		}
4775 
4776 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4777 					&device->dev_state) ||
4778 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4779 			continue;
4780 
4781 		if (device->total_bytes > device->bytes_used)
4782 			total_avail = device->total_bytes - device->bytes_used;
4783 		else
4784 			total_avail = 0;
4785 
4786 		/* If there is no space on this device, skip it. */
4787 		if (total_avail == 0)
4788 			continue;
4789 
4790 		ret = find_free_dev_extent(trans, device,
4791 					   max_stripe_size * dev_stripes,
4792 					   &dev_offset, &max_avail);
4793 		if (ret && ret != -ENOSPC)
4794 			goto error;
4795 
4796 		if (ret == 0)
4797 			max_avail = max_stripe_size * dev_stripes;
4798 
4799 		if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4800 			continue;
4801 
4802 		if (ndevs == fs_devices->rw_devices) {
4803 			WARN(1, "%s: found more than %llu devices\n",
4804 			     __func__, fs_devices->rw_devices);
4805 			break;
4806 		}
4807 		devices_info[ndevs].dev_offset = dev_offset;
4808 		devices_info[ndevs].max_avail = max_avail;
4809 		devices_info[ndevs].total_avail = total_avail;
4810 		devices_info[ndevs].dev = device;
4811 		++ndevs;
4812 	}
4813 
4814 	/*
4815 	 * now sort the devices by hole size / available space
4816 	 */
4817 	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4818 	     btrfs_cmp_device_info, NULL);
4819 
4820 	/* round down to number of usable stripes */
4821 	ndevs = round_down(ndevs, devs_increment);
4822 
4823 	if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4824 		ret = -ENOSPC;
4825 		goto error;
4826 	}
4827 
4828 	ndevs = min(ndevs, devs_max);
4829 
4830 	/*
4831 	 * the primary goal is to maximize the number of stripes, so use as many
4832 	 * devices as possible, even if the stripes are not maximum sized.
4833 	 */
4834 	stripe_size = devices_info[ndevs-1].max_avail;
4835 	num_stripes = ndevs * dev_stripes;
4836 
4837 	/*
4838 	 * this will have to be fixed for RAID1 and RAID10 over
4839 	 * more drives
4840 	 */
4841 	data_stripes = num_stripes / ncopies;
4842 
4843 	if (type & BTRFS_BLOCK_GROUP_RAID5)
4844 		data_stripes = num_stripes - 1;
4845 
4846 	if (type & BTRFS_BLOCK_GROUP_RAID6)
4847 		data_stripes = num_stripes - 2;
4848 
4849 	/*
4850 	 * Use the number of data stripes to figure out how big this chunk
4851 	 * is really going to be in terms of logical address space,
4852 	 * and compare that answer with the max chunk size
4853 	 */
4854 	if (stripe_size * data_stripes > max_chunk_size) {
4855 		u64 mask = (1ULL << 24) - 1;
4856 
4857 		stripe_size = div_u64(max_chunk_size, data_stripes);
4858 
4859 		/* bump the answer up to a 16MB boundary */
4860 		stripe_size = (stripe_size + mask) & ~mask;
4861 
4862 		/* but don't go higher than the limits we found
4863 		 * while searching for free extents
4864 		 */
4865 		if (stripe_size > devices_info[ndevs-1].max_avail)
4866 			stripe_size = devices_info[ndevs-1].max_avail;
4867 	}
4868 
4869 	stripe_size = div_u64(stripe_size, dev_stripes);
4870 
4871 	/* align to BTRFS_STRIPE_LEN */
4872 	stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4873 
4874 	map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4875 	if (!map) {
4876 		ret = -ENOMEM;
4877 		goto error;
4878 	}
4879 	map->num_stripes = num_stripes;
4880 
4881 	for (i = 0; i < ndevs; ++i) {
4882 		for (j = 0; j < dev_stripes; ++j) {
4883 			int s = i * dev_stripes + j;
4884 			map->stripes[s].dev = devices_info[i].dev;
4885 			map->stripes[s].physical = devices_info[i].dev_offset +
4886 						   j * stripe_size;
4887 		}
4888 	}
4889 	map->stripe_len = BTRFS_STRIPE_LEN;
4890 	map->io_align = BTRFS_STRIPE_LEN;
4891 	map->io_width = BTRFS_STRIPE_LEN;
4892 	map->type = type;
4893 	map->sub_stripes = sub_stripes;
4894 
4895 	num_bytes = stripe_size * data_stripes;
4896 
4897 	trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4898 
4899 	em = alloc_extent_map();
4900 	if (!em) {
4901 		kfree(map);
4902 		ret = -ENOMEM;
4903 		goto error;
4904 	}
4905 	set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4906 	em->map_lookup = map;
4907 	em->start = start;
4908 	em->len = num_bytes;
4909 	em->block_start = 0;
4910 	em->block_len = em->len;
4911 	em->orig_block_len = stripe_size;
4912 
4913 	em_tree = &info->mapping_tree.map_tree;
4914 	write_lock(&em_tree->lock);
4915 	ret = add_extent_mapping(em_tree, em, 0);
4916 	if (ret) {
4917 		write_unlock(&em_tree->lock);
4918 		free_extent_map(em);
4919 		goto error;
4920 	}
4921 
4922 	list_add_tail(&em->list, &trans->transaction->pending_chunks);
4923 	refcount_inc(&em->refs);
4924 	write_unlock(&em_tree->lock);
4925 
4926 	ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4927 	if (ret)
4928 		goto error_del_extent;
4929 
4930 	for (i = 0; i < map->num_stripes; i++) {
4931 		num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4932 		btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4933 	}
4934 
4935 	atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4936 
4937 	free_extent_map(em);
4938 	check_raid56_incompat_flag(info, type);
4939 
4940 	kfree(devices_info);
4941 	return 0;
4942 
4943 error_del_extent:
4944 	write_lock(&em_tree->lock);
4945 	remove_extent_mapping(em_tree, em);
4946 	write_unlock(&em_tree->lock);
4947 
4948 	/* One for our allocation */
4949 	free_extent_map(em);
4950 	/* One for the tree reference */
4951 	free_extent_map(em);
4952 	/* One for the pending_chunks list reference */
4953 	free_extent_map(em);
4954 error:
4955 	kfree(devices_info);
4956 	return ret;
4957 }
4958 
4959 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4960 				struct btrfs_fs_info *fs_info,
4961 				u64 chunk_offset, u64 chunk_size)
4962 {
4963 	struct btrfs_root *extent_root = fs_info->extent_root;
4964 	struct btrfs_root *chunk_root = fs_info->chunk_root;
4965 	struct btrfs_key key;
4966 	struct btrfs_device *device;
4967 	struct btrfs_chunk *chunk;
4968 	struct btrfs_stripe *stripe;
4969 	struct extent_map *em;
4970 	struct map_lookup *map;
4971 	size_t item_size;
4972 	u64 dev_offset;
4973 	u64 stripe_size;
4974 	int i = 0;
4975 	int ret = 0;
4976 
4977 	em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4978 	if (IS_ERR(em))
4979 		return PTR_ERR(em);
4980 
4981 	map = em->map_lookup;
4982 	item_size = btrfs_chunk_item_size(map->num_stripes);
4983 	stripe_size = em->orig_block_len;
4984 
4985 	chunk = kzalloc(item_size, GFP_NOFS);
4986 	if (!chunk) {
4987 		ret = -ENOMEM;
4988 		goto out;
4989 	}
4990 
4991 	/*
4992 	 * Take the device list mutex to prevent races with the final phase of
4993 	 * a device replace operation that replaces the device object associated
4994 	 * with the map's stripes, because the device object's id can change
4995 	 * at any time during that final phase of the device replace operation
4996 	 * (dev-replace.c:btrfs_dev_replace_finishing()).
4997 	 */
4998 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
4999 	for (i = 0; i < map->num_stripes; i++) {
5000 		device = map->stripes[i].dev;
5001 		dev_offset = map->stripes[i].physical;
5002 
5003 		ret = btrfs_update_device(trans, device);
5004 		if (ret)
5005 			break;
5006 		ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5007 					     dev_offset, stripe_size);
5008 		if (ret)
5009 			break;
5010 	}
5011 	if (ret) {
5012 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5013 		goto out;
5014 	}
5015 
5016 	stripe = &chunk->stripe;
5017 	for (i = 0; i < map->num_stripes; i++) {
5018 		device = map->stripes[i].dev;
5019 		dev_offset = map->stripes[i].physical;
5020 
5021 		btrfs_set_stack_stripe_devid(stripe, device->devid);
5022 		btrfs_set_stack_stripe_offset(stripe, dev_offset);
5023 		memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5024 		stripe++;
5025 	}
5026 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5027 
5028 	btrfs_set_stack_chunk_length(chunk, chunk_size);
5029 	btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5030 	btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5031 	btrfs_set_stack_chunk_type(chunk, map->type);
5032 	btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5033 	btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5034 	btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5035 	btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5036 	btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5037 
5038 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5039 	key.type = BTRFS_CHUNK_ITEM_KEY;
5040 	key.offset = chunk_offset;
5041 
5042 	ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5043 	if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5044 		/*
5045 		 * TODO: Cleanup of inserted chunk root in case of
5046 		 * failure.
5047 		 */
5048 		ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5049 	}
5050 
5051 out:
5052 	kfree(chunk);
5053 	free_extent_map(em);
5054 	return ret;
5055 }
5056 
5057 /*
5058  * Chunk allocation falls into two parts. The first part does works
5059  * that make the new allocated chunk useable, but not do any operation
5060  * that modifies the chunk tree. The second part does the works that
5061  * require modifying the chunk tree. This division is important for the
5062  * bootstrap process of adding storage to a seed btrfs.
5063  */
5064 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5065 		      struct btrfs_fs_info *fs_info, u64 type)
5066 {
5067 	u64 chunk_offset;
5068 
5069 	ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
5070 	chunk_offset = find_next_chunk(fs_info);
5071 	return __btrfs_alloc_chunk(trans, chunk_offset, type);
5072 }
5073 
5074 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5075 					 struct btrfs_fs_info *fs_info)
5076 {
5077 	u64 chunk_offset;
5078 	u64 sys_chunk_offset;
5079 	u64 alloc_profile;
5080 	int ret;
5081 
5082 	chunk_offset = find_next_chunk(fs_info);
5083 	alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5084 	ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5085 	if (ret)
5086 		return ret;
5087 
5088 	sys_chunk_offset = find_next_chunk(fs_info);
5089 	alloc_profile = btrfs_system_alloc_profile(fs_info);
5090 	ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5091 	return ret;
5092 }
5093 
5094 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5095 {
5096 	int max_errors;
5097 
5098 	if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5099 			 BTRFS_BLOCK_GROUP_RAID10 |
5100 			 BTRFS_BLOCK_GROUP_RAID5 |
5101 			 BTRFS_BLOCK_GROUP_DUP)) {
5102 		max_errors = 1;
5103 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5104 		max_errors = 2;
5105 	} else {
5106 		max_errors = 0;
5107 	}
5108 
5109 	return max_errors;
5110 }
5111 
5112 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5113 {
5114 	struct extent_map *em;
5115 	struct map_lookup *map;
5116 	int readonly = 0;
5117 	int miss_ndevs = 0;
5118 	int i;
5119 
5120 	em = get_chunk_map(fs_info, chunk_offset, 1);
5121 	if (IS_ERR(em))
5122 		return 1;
5123 
5124 	map = em->map_lookup;
5125 	for (i = 0; i < map->num_stripes; i++) {
5126 		if (test_bit(BTRFS_DEV_STATE_MISSING,
5127 					&map->stripes[i].dev->dev_state)) {
5128 			miss_ndevs++;
5129 			continue;
5130 		}
5131 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5132 					&map->stripes[i].dev->dev_state)) {
5133 			readonly = 1;
5134 			goto end;
5135 		}
5136 	}
5137 
5138 	/*
5139 	 * If the number of missing devices is larger than max errors,
5140 	 * we can not write the data into that chunk successfully, so
5141 	 * set it readonly.
5142 	 */
5143 	if (miss_ndevs > btrfs_chunk_max_errors(map))
5144 		readonly = 1;
5145 end:
5146 	free_extent_map(em);
5147 	return readonly;
5148 }
5149 
5150 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5151 {
5152 	extent_map_tree_init(&tree->map_tree);
5153 }
5154 
5155 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5156 {
5157 	struct extent_map *em;
5158 
5159 	while (1) {
5160 		write_lock(&tree->map_tree.lock);
5161 		em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5162 		if (em)
5163 			remove_extent_mapping(&tree->map_tree, em);
5164 		write_unlock(&tree->map_tree.lock);
5165 		if (!em)
5166 			break;
5167 		/* once for us */
5168 		free_extent_map(em);
5169 		/* once for the tree */
5170 		free_extent_map(em);
5171 	}
5172 }
5173 
5174 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5175 {
5176 	struct extent_map *em;
5177 	struct map_lookup *map;
5178 	int ret;
5179 
5180 	em = get_chunk_map(fs_info, logical, len);
5181 	if (IS_ERR(em))
5182 		/*
5183 		 * We could return errors for these cases, but that could get
5184 		 * ugly and we'd probably do the same thing which is just not do
5185 		 * anything else and exit, so return 1 so the callers don't try
5186 		 * to use other copies.
5187 		 */
5188 		return 1;
5189 
5190 	map = em->map_lookup;
5191 	if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5192 		ret = map->num_stripes;
5193 	else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5194 		ret = map->sub_stripes;
5195 	else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5196 		ret = 2;
5197 	else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5198 		/*
5199 		 * There could be two corrupted data stripes, we need
5200 		 * to loop retry in order to rebuild the correct data.
5201 		 *
5202 		 * Fail a stripe at a time on every retry except the
5203 		 * stripe under reconstruction.
5204 		 */
5205 		ret = map->num_stripes;
5206 	else
5207 		ret = 1;
5208 	free_extent_map(em);
5209 
5210 	btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5211 	if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5212 	    fs_info->dev_replace.tgtdev)
5213 		ret++;
5214 	btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5215 
5216 	return ret;
5217 }
5218 
5219 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5220 				    u64 logical)
5221 {
5222 	struct extent_map *em;
5223 	struct map_lookup *map;
5224 	unsigned long len = fs_info->sectorsize;
5225 
5226 	em = get_chunk_map(fs_info, logical, len);
5227 
5228 	if (!WARN_ON(IS_ERR(em))) {
5229 		map = em->map_lookup;
5230 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5231 			len = map->stripe_len * nr_data_stripes(map);
5232 		free_extent_map(em);
5233 	}
5234 	return len;
5235 }
5236 
5237 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5238 {
5239 	struct extent_map *em;
5240 	struct map_lookup *map;
5241 	int ret = 0;
5242 
5243 	em = get_chunk_map(fs_info, logical, len);
5244 
5245 	if(!WARN_ON(IS_ERR(em))) {
5246 		map = em->map_lookup;
5247 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5248 			ret = 1;
5249 		free_extent_map(em);
5250 	}
5251 	return ret;
5252 }
5253 
5254 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5255 			    struct map_lookup *map, int first, int num,
5256 			    int optimal, int dev_replace_is_ongoing)
5257 {
5258 	int i;
5259 	int tolerance;
5260 	struct btrfs_device *srcdev;
5261 
5262 	if (dev_replace_is_ongoing &&
5263 	    fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5264 	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5265 		srcdev = fs_info->dev_replace.srcdev;
5266 	else
5267 		srcdev = NULL;
5268 
5269 	/*
5270 	 * try to avoid the drive that is the source drive for a
5271 	 * dev-replace procedure, only choose it if no other non-missing
5272 	 * mirror is available
5273 	 */
5274 	for (tolerance = 0; tolerance < 2; tolerance++) {
5275 		if (map->stripes[optimal].dev->bdev &&
5276 		    (tolerance || map->stripes[optimal].dev != srcdev))
5277 			return optimal;
5278 		for (i = first; i < first + num; i++) {
5279 			if (map->stripes[i].dev->bdev &&
5280 			    (tolerance || map->stripes[i].dev != srcdev))
5281 				return i;
5282 		}
5283 	}
5284 
5285 	/* we couldn't find one that doesn't fail.  Just return something
5286 	 * and the io error handling code will clean up eventually
5287 	 */
5288 	return optimal;
5289 }
5290 
5291 static inline int parity_smaller(u64 a, u64 b)
5292 {
5293 	return a > b;
5294 }
5295 
5296 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5297 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5298 {
5299 	struct btrfs_bio_stripe s;
5300 	int i;
5301 	u64 l;
5302 	int again = 1;
5303 
5304 	while (again) {
5305 		again = 0;
5306 		for (i = 0; i < num_stripes - 1; i++) {
5307 			if (parity_smaller(bbio->raid_map[i],
5308 					   bbio->raid_map[i+1])) {
5309 				s = bbio->stripes[i];
5310 				l = bbio->raid_map[i];
5311 				bbio->stripes[i] = bbio->stripes[i+1];
5312 				bbio->raid_map[i] = bbio->raid_map[i+1];
5313 				bbio->stripes[i+1] = s;
5314 				bbio->raid_map[i+1] = l;
5315 
5316 				again = 1;
5317 			}
5318 		}
5319 	}
5320 }
5321 
5322 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5323 {
5324 	struct btrfs_bio *bbio = kzalloc(
5325 		 /* the size of the btrfs_bio */
5326 		sizeof(struct btrfs_bio) +
5327 		/* plus the variable array for the stripes */
5328 		sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5329 		/* plus the variable array for the tgt dev */
5330 		sizeof(int) * (real_stripes) +
5331 		/*
5332 		 * plus the raid_map, which includes both the tgt dev
5333 		 * and the stripes
5334 		 */
5335 		sizeof(u64) * (total_stripes),
5336 		GFP_NOFS|__GFP_NOFAIL);
5337 
5338 	atomic_set(&bbio->error, 0);
5339 	refcount_set(&bbio->refs, 1);
5340 
5341 	return bbio;
5342 }
5343 
5344 void btrfs_get_bbio(struct btrfs_bio *bbio)
5345 {
5346 	WARN_ON(!refcount_read(&bbio->refs));
5347 	refcount_inc(&bbio->refs);
5348 }
5349 
5350 void btrfs_put_bbio(struct btrfs_bio *bbio)
5351 {
5352 	if (!bbio)
5353 		return;
5354 	if (refcount_dec_and_test(&bbio->refs))
5355 		kfree(bbio);
5356 }
5357 
5358 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5359 /*
5360  * Please note that, discard won't be sent to target device of device
5361  * replace.
5362  */
5363 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5364 					 u64 logical, u64 length,
5365 					 struct btrfs_bio **bbio_ret)
5366 {
5367 	struct extent_map *em;
5368 	struct map_lookup *map;
5369 	struct btrfs_bio *bbio;
5370 	u64 offset;
5371 	u64 stripe_nr;
5372 	u64 stripe_nr_end;
5373 	u64 stripe_end_offset;
5374 	u64 stripe_cnt;
5375 	u64 stripe_len;
5376 	u64 stripe_offset;
5377 	u64 num_stripes;
5378 	u32 stripe_index;
5379 	u32 factor = 0;
5380 	u32 sub_stripes = 0;
5381 	u64 stripes_per_dev = 0;
5382 	u32 remaining_stripes = 0;
5383 	u32 last_stripe = 0;
5384 	int ret = 0;
5385 	int i;
5386 
5387 	/* discard always return a bbio */
5388 	ASSERT(bbio_ret);
5389 
5390 	em = get_chunk_map(fs_info, logical, length);
5391 	if (IS_ERR(em))
5392 		return PTR_ERR(em);
5393 
5394 	map = em->map_lookup;
5395 	/* we don't discard raid56 yet */
5396 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5397 		ret = -EOPNOTSUPP;
5398 		goto out;
5399 	}
5400 
5401 	offset = logical - em->start;
5402 	length = min_t(u64, em->len - offset, length);
5403 
5404 	stripe_len = map->stripe_len;
5405 	/*
5406 	 * stripe_nr counts the total number of stripes we have to stride
5407 	 * to get to this block
5408 	 */
5409 	stripe_nr = div64_u64(offset, stripe_len);
5410 
5411 	/* stripe_offset is the offset of this block in its stripe */
5412 	stripe_offset = offset - stripe_nr * stripe_len;
5413 
5414 	stripe_nr_end = round_up(offset + length, map->stripe_len);
5415 	stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5416 	stripe_cnt = stripe_nr_end - stripe_nr;
5417 	stripe_end_offset = stripe_nr_end * map->stripe_len -
5418 			    (offset + length);
5419 	/*
5420 	 * after this, stripe_nr is the number of stripes on this
5421 	 * device we have to walk to find the data, and stripe_index is
5422 	 * the number of our device in the stripe array
5423 	 */
5424 	num_stripes = 1;
5425 	stripe_index = 0;
5426 	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5427 			 BTRFS_BLOCK_GROUP_RAID10)) {
5428 		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5429 			sub_stripes = 1;
5430 		else
5431 			sub_stripes = map->sub_stripes;
5432 
5433 		factor = map->num_stripes / sub_stripes;
5434 		num_stripes = min_t(u64, map->num_stripes,
5435 				    sub_stripes * stripe_cnt);
5436 		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5437 		stripe_index *= sub_stripes;
5438 		stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5439 					      &remaining_stripes);
5440 		div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5441 		last_stripe *= sub_stripes;
5442 	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5443 				BTRFS_BLOCK_GROUP_DUP)) {
5444 		num_stripes = map->num_stripes;
5445 	} else {
5446 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5447 					&stripe_index);
5448 	}
5449 
5450 	bbio = alloc_btrfs_bio(num_stripes, 0);
5451 	if (!bbio) {
5452 		ret = -ENOMEM;
5453 		goto out;
5454 	}
5455 
5456 	for (i = 0; i < num_stripes; i++) {
5457 		bbio->stripes[i].physical =
5458 			map->stripes[stripe_index].physical +
5459 			stripe_offset + stripe_nr * map->stripe_len;
5460 		bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5461 
5462 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5463 				 BTRFS_BLOCK_GROUP_RAID10)) {
5464 			bbio->stripes[i].length = stripes_per_dev *
5465 				map->stripe_len;
5466 
5467 			if (i / sub_stripes < remaining_stripes)
5468 				bbio->stripes[i].length +=
5469 					map->stripe_len;
5470 
5471 			/*
5472 			 * Special for the first stripe and
5473 			 * the last stripe:
5474 			 *
5475 			 * |-------|...|-------|
5476 			 *     |----------|
5477 			 *    off     end_off
5478 			 */
5479 			if (i < sub_stripes)
5480 				bbio->stripes[i].length -=
5481 					stripe_offset;
5482 
5483 			if (stripe_index >= last_stripe &&
5484 			    stripe_index <= (last_stripe +
5485 					     sub_stripes - 1))
5486 				bbio->stripes[i].length -=
5487 					stripe_end_offset;
5488 
5489 			if (i == sub_stripes - 1)
5490 				stripe_offset = 0;
5491 		} else {
5492 			bbio->stripes[i].length = length;
5493 		}
5494 
5495 		stripe_index++;
5496 		if (stripe_index == map->num_stripes) {
5497 			stripe_index = 0;
5498 			stripe_nr++;
5499 		}
5500 	}
5501 
5502 	*bbio_ret = bbio;
5503 	bbio->map_type = map->type;
5504 	bbio->num_stripes = num_stripes;
5505 out:
5506 	free_extent_map(em);
5507 	return ret;
5508 }
5509 
5510 /*
5511  * In dev-replace case, for repair case (that's the only case where the mirror
5512  * is selected explicitly when calling btrfs_map_block), blocks left of the
5513  * left cursor can also be read from the target drive.
5514  *
5515  * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5516  * array of stripes.
5517  * For READ, it also needs to be supported using the same mirror number.
5518  *
5519  * If the requested block is not left of the left cursor, EIO is returned. This
5520  * can happen because btrfs_num_copies() returns one more in the dev-replace
5521  * case.
5522  */
5523 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5524 					 u64 logical, u64 length,
5525 					 u64 srcdev_devid, int *mirror_num,
5526 					 u64 *physical)
5527 {
5528 	struct btrfs_bio *bbio = NULL;
5529 	int num_stripes;
5530 	int index_srcdev = 0;
5531 	int found = 0;
5532 	u64 physical_of_found = 0;
5533 	int i;
5534 	int ret = 0;
5535 
5536 	ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5537 				logical, &length, &bbio, 0, 0);
5538 	if (ret) {
5539 		ASSERT(bbio == NULL);
5540 		return ret;
5541 	}
5542 
5543 	num_stripes = bbio->num_stripes;
5544 	if (*mirror_num > num_stripes) {
5545 		/*
5546 		 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5547 		 * that means that the requested area is not left of the left
5548 		 * cursor
5549 		 */
5550 		btrfs_put_bbio(bbio);
5551 		return -EIO;
5552 	}
5553 
5554 	/*
5555 	 * process the rest of the function using the mirror_num of the source
5556 	 * drive. Therefore look it up first.  At the end, patch the device
5557 	 * pointer to the one of the target drive.
5558 	 */
5559 	for (i = 0; i < num_stripes; i++) {
5560 		if (bbio->stripes[i].dev->devid != srcdev_devid)
5561 			continue;
5562 
5563 		/*
5564 		 * In case of DUP, in order to keep it simple, only add the
5565 		 * mirror with the lowest physical address
5566 		 */
5567 		if (found &&
5568 		    physical_of_found <= bbio->stripes[i].physical)
5569 			continue;
5570 
5571 		index_srcdev = i;
5572 		found = 1;
5573 		physical_of_found = bbio->stripes[i].physical;
5574 	}
5575 
5576 	btrfs_put_bbio(bbio);
5577 
5578 	ASSERT(found);
5579 	if (!found)
5580 		return -EIO;
5581 
5582 	*mirror_num = index_srcdev + 1;
5583 	*physical = physical_of_found;
5584 	return ret;
5585 }
5586 
5587 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5588 				      struct btrfs_bio **bbio_ret,
5589 				      struct btrfs_dev_replace *dev_replace,
5590 				      int *num_stripes_ret, int *max_errors_ret)
5591 {
5592 	struct btrfs_bio *bbio = *bbio_ret;
5593 	u64 srcdev_devid = dev_replace->srcdev->devid;
5594 	int tgtdev_indexes = 0;
5595 	int num_stripes = *num_stripes_ret;
5596 	int max_errors = *max_errors_ret;
5597 	int i;
5598 
5599 	if (op == BTRFS_MAP_WRITE) {
5600 		int index_where_to_add;
5601 
5602 		/*
5603 		 * duplicate the write operations while the dev replace
5604 		 * procedure is running. Since the copying of the old disk to
5605 		 * the new disk takes place at run time while the filesystem is
5606 		 * mounted writable, the regular write operations to the old
5607 		 * disk have to be duplicated to go to the new disk as well.
5608 		 *
5609 		 * Note that device->missing is handled by the caller, and that
5610 		 * the write to the old disk is already set up in the stripes
5611 		 * array.
5612 		 */
5613 		index_where_to_add = num_stripes;
5614 		for (i = 0; i < num_stripes; i++) {
5615 			if (bbio->stripes[i].dev->devid == srcdev_devid) {
5616 				/* write to new disk, too */
5617 				struct btrfs_bio_stripe *new =
5618 					bbio->stripes + index_where_to_add;
5619 				struct btrfs_bio_stripe *old =
5620 					bbio->stripes + i;
5621 
5622 				new->physical = old->physical;
5623 				new->length = old->length;
5624 				new->dev = dev_replace->tgtdev;
5625 				bbio->tgtdev_map[i] = index_where_to_add;
5626 				index_where_to_add++;
5627 				max_errors++;
5628 				tgtdev_indexes++;
5629 			}
5630 		}
5631 		num_stripes = index_where_to_add;
5632 	} else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5633 		int index_srcdev = 0;
5634 		int found = 0;
5635 		u64 physical_of_found = 0;
5636 
5637 		/*
5638 		 * During the dev-replace procedure, the target drive can also
5639 		 * be used to read data in case it is needed to repair a corrupt
5640 		 * block elsewhere. This is possible if the requested area is
5641 		 * left of the left cursor. In this area, the target drive is a
5642 		 * full copy of the source drive.
5643 		 */
5644 		for (i = 0; i < num_stripes; i++) {
5645 			if (bbio->stripes[i].dev->devid == srcdev_devid) {
5646 				/*
5647 				 * In case of DUP, in order to keep it simple,
5648 				 * only add the mirror with the lowest physical
5649 				 * address
5650 				 */
5651 				if (found &&
5652 				    physical_of_found <=
5653 				     bbio->stripes[i].physical)
5654 					continue;
5655 				index_srcdev = i;
5656 				found = 1;
5657 				physical_of_found = bbio->stripes[i].physical;
5658 			}
5659 		}
5660 		if (found) {
5661 			struct btrfs_bio_stripe *tgtdev_stripe =
5662 				bbio->stripes + num_stripes;
5663 
5664 			tgtdev_stripe->physical = physical_of_found;
5665 			tgtdev_stripe->length =
5666 				bbio->stripes[index_srcdev].length;
5667 			tgtdev_stripe->dev = dev_replace->tgtdev;
5668 			bbio->tgtdev_map[index_srcdev] = num_stripes;
5669 
5670 			tgtdev_indexes++;
5671 			num_stripes++;
5672 		}
5673 	}
5674 
5675 	*num_stripes_ret = num_stripes;
5676 	*max_errors_ret = max_errors;
5677 	bbio->num_tgtdevs = tgtdev_indexes;
5678 	*bbio_ret = bbio;
5679 }
5680 
5681 static bool need_full_stripe(enum btrfs_map_op op)
5682 {
5683 	return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5684 }
5685 
5686 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5687 			     enum btrfs_map_op op,
5688 			     u64 logical, u64 *length,
5689 			     struct btrfs_bio **bbio_ret,
5690 			     int mirror_num, int need_raid_map)
5691 {
5692 	struct extent_map *em;
5693 	struct map_lookup *map;
5694 	u64 offset;
5695 	u64 stripe_offset;
5696 	u64 stripe_nr;
5697 	u64 stripe_len;
5698 	u32 stripe_index;
5699 	int i;
5700 	int ret = 0;
5701 	int num_stripes;
5702 	int max_errors = 0;
5703 	int tgtdev_indexes = 0;
5704 	struct btrfs_bio *bbio = NULL;
5705 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5706 	int dev_replace_is_ongoing = 0;
5707 	int num_alloc_stripes;
5708 	int patch_the_first_stripe_for_dev_replace = 0;
5709 	u64 physical_to_patch_in_first_stripe = 0;
5710 	u64 raid56_full_stripe_start = (u64)-1;
5711 
5712 	if (op == BTRFS_MAP_DISCARD)
5713 		return __btrfs_map_block_for_discard(fs_info, logical,
5714 						     *length, bbio_ret);
5715 
5716 	em = get_chunk_map(fs_info, logical, *length);
5717 	if (IS_ERR(em))
5718 		return PTR_ERR(em);
5719 
5720 	map = em->map_lookup;
5721 	offset = logical - em->start;
5722 
5723 	stripe_len = map->stripe_len;
5724 	stripe_nr = offset;
5725 	/*
5726 	 * stripe_nr counts the total number of stripes we have to stride
5727 	 * to get to this block
5728 	 */
5729 	stripe_nr = div64_u64(stripe_nr, stripe_len);
5730 
5731 	stripe_offset = stripe_nr * stripe_len;
5732 	if (offset < stripe_offset) {
5733 		btrfs_crit(fs_info,
5734 			   "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5735 			   stripe_offset, offset, em->start, logical,
5736 			   stripe_len);
5737 		free_extent_map(em);
5738 		return -EINVAL;
5739 	}
5740 
5741 	/* stripe_offset is the offset of this block in its stripe*/
5742 	stripe_offset = offset - stripe_offset;
5743 
5744 	/* if we're here for raid56, we need to know the stripe aligned start */
5745 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5746 		unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5747 		raid56_full_stripe_start = offset;
5748 
5749 		/* allow a write of a full stripe, but make sure we don't
5750 		 * allow straddling of stripes
5751 		 */
5752 		raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5753 				full_stripe_len);
5754 		raid56_full_stripe_start *= full_stripe_len;
5755 	}
5756 
5757 	if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5758 		u64 max_len;
5759 		/* For writes to RAID[56], allow a full stripeset across all disks.
5760 		   For other RAID types and for RAID[56] reads, just allow a single
5761 		   stripe (on a single disk). */
5762 		if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5763 		    (op == BTRFS_MAP_WRITE)) {
5764 			max_len = stripe_len * nr_data_stripes(map) -
5765 				(offset - raid56_full_stripe_start);
5766 		} else {
5767 			/* we limit the length of each bio to what fits in a stripe */
5768 			max_len = stripe_len - stripe_offset;
5769 		}
5770 		*length = min_t(u64, em->len - offset, max_len);
5771 	} else {
5772 		*length = em->len - offset;
5773 	}
5774 
5775 	/* This is for when we're called from btrfs_merge_bio_hook() and all
5776 	   it cares about is the length */
5777 	if (!bbio_ret)
5778 		goto out;
5779 
5780 	btrfs_dev_replace_lock(dev_replace, 0);
5781 	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5782 	if (!dev_replace_is_ongoing)
5783 		btrfs_dev_replace_unlock(dev_replace, 0);
5784 	else
5785 		btrfs_dev_replace_set_lock_blocking(dev_replace);
5786 
5787 	if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5788 	    !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5789 		ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5790 						    dev_replace->srcdev->devid,
5791 						    &mirror_num,
5792 					    &physical_to_patch_in_first_stripe);
5793 		if (ret)
5794 			goto out;
5795 		else
5796 			patch_the_first_stripe_for_dev_replace = 1;
5797 	} else if (mirror_num > map->num_stripes) {
5798 		mirror_num = 0;
5799 	}
5800 
5801 	num_stripes = 1;
5802 	stripe_index = 0;
5803 	if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5804 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5805 				&stripe_index);
5806 		if (!need_full_stripe(op))
5807 			mirror_num = 1;
5808 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5809 		if (need_full_stripe(op))
5810 			num_stripes = map->num_stripes;
5811 		else if (mirror_num)
5812 			stripe_index = mirror_num - 1;
5813 		else {
5814 			stripe_index = find_live_mirror(fs_info, map, 0,
5815 					    map->num_stripes,
5816 					    current->pid % map->num_stripes,
5817 					    dev_replace_is_ongoing);
5818 			mirror_num = stripe_index + 1;
5819 		}
5820 
5821 	} else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5822 		if (need_full_stripe(op)) {
5823 			num_stripes = map->num_stripes;
5824 		} else if (mirror_num) {
5825 			stripe_index = mirror_num - 1;
5826 		} else {
5827 			mirror_num = 1;
5828 		}
5829 
5830 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5831 		u32 factor = map->num_stripes / map->sub_stripes;
5832 
5833 		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5834 		stripe_index *= map->sub_stripes;
5835 
5836 		if (need_full_stripe(op))
5837 			num_stripes = map->sub_stripes;
5838 		else if (mirror_num)
5839 			stripe_index += mirror_num - 1;
5840 		else {
5841 			int old_stripe_index = stripe_index;
5842 			stripe_index = find_live_mirror(fs_info, map,
5843 					      stripe_index,
5844 					      map->sub_stripes, stripe_index +
5845 					      current->pid % map->sub_stripes,
5846 					      dev_replace_is_ongoing);
5847 			mirror_num = stripe_index - old_stripe_index + 1;
5848 		}
5849 
5850 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5851 		if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5852 			/* push stripe_nr back to the start of the full stripe */
5853 			stripe_nr = div64_u64(raid56_full_stripe_start,
5854 					stripe_len * nr_data_stripes(map));
5855 
5856 			/* RAID[56] write or recovery. Return all stripes */
5857 			num_stripes = map->num_stripes;
5858 			max_errors = nr_parity_stripes(map);
5859 
5860 			*length = map->stripe_len;
5861 			stripe_index = 0;
5862 			stripe_offset = 0;
5863 		} else {
5864 			/*
5865 			 * Mirror #0 or #1 means the original data block.
5866 			 * Mirror #2 is RAID5 parity block.
5867 			 * Mirror #3 is RAID6 Q block.
5868 			 */
5869 			stripe_nr = div_u64_rem(stripe_nr,
5870 					nr_data_stripes(map), &stripe_index);
5871 			if (mirror_num > 1)
5872 				stripe_index = nr_data_stripes(map) +
5873 						mirror_num - 2;
5874 
5875 			/* We distribute the parity blocks across stripes */
5876 			div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5877 					&stripe_index);
5878 			if (!need_full_stripe(op) && mirror_num <= 1)
5879 				mirror_num = 1;
5880 		}
5881 	} else {
5882 		/*
5883 		 * after this, stripe_nr is the number of stripes on this
5884 		 * device we have to walk to find the data, and stripe_index is
5885 		 * the number of our device in the stripe array
5886 		 */
5887 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5888 				&stripe_index);
5889 		mirror_num = stripe_index + 1;
5890 	}
5891 	if (stripe_index >= map->num_stripes) {
5892 		btrfs_crit(fs_info,
5893 			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5894 			   stripe_index, map->num_stripes);
5895 		ret = -EINVAL;
5896 		goto out;
5897 	}
5898 
5899 	num_alloc_stripes = num_stripes;
5900 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5901 		if (op == BTRFS_MAP_WRITE)
5902 			num_alloc_stripes <<= 1;
5903 		if (op == BTRFS_MAP_GET_READ_MIRRORS)
5904 			num_alloc_stripes++;
5905 		tgtdev_indexes = num_stripes;
5906 	}
5907 
5908 	bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5909 	if (!bbio) {
5910 		ret = -ENOMEM;
5911 		goto out;
5912 	}
5913 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5914 		bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5915 
5916 	/* build raid_map */
5917 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5918 	    (need_full_stripe(op) || mirror_num > 1)) {
5919 		u64 tmp;
5920 		unsigned rot;
5921 
5922 		bbio->raid_map = (u64 *)((void *)bbio->stripes +
5923 				 sizeof(struct btrfs_bio_stripe) *
5924 				 num_alloc_stripes +
5925 				 sizeof(int) * tgtdev_indexes);
5926 
5927 		/* Work out the disk rotation on this stripe-set */
5928 		div_u64_rem(stripe_nr, num_stripes, &rot);
5929 
5930 		/* Fill in the logical address of each stripe */
5931 		tmp = stripe_nr * nr_data_stripes(map);
5932 		for (i = 0; i < nr_data_stripes(map); i++)
5933 			bbio->raid_map[(i+rot) % num_stripes] =
5934 				em->start + (tmp + i) * map->stripe_len;
5935 
5936 		bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5937 		if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5938 			bbio->raid_map[(i+rot+1) % num_stripes] =
5939 				RAID6_Q_STRIPE;
5940 	}
5941 
5942 
5943 	for (i = 0; i < num_stripes; i++) {
5944 		bbio->stripes[i].physical =
5945 			map->stripes[stripe_index].physical +
5946 			stripe_offset +
5947 			stripe_nr * map->stripe_len;
5948 		bbio->stripes[i].dev =
5949 			map->stripes[stripe_index].dev;
5950 		stripe_index++;
5951 	}
5952 
5953 	if (need_full_stripe(op))
5954 		max_errors = btrfs_chunk_max_errors(map);
5955 
5956 	if (bbio->raid_map)
5957 		sort_parity_stripes(bbio, num_stripes);
5958 
5959 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5960 	    need_full_stripe(op)) {
5961 		handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5962 					  &max_errors);
5963 	}
5964 
5965 	*bbio_ret = bbio;
5966 	bbio->map_type = map->type;
5967 	bbio->num_stripes = num_stripes;
5968 	bbio->max_errors = max_errors;
5969 	bbio->mirror_num = mirror_num;
5970 
5971 	/*
5972 	 * this is the case that REQ_READ && dev_replace_is_ongoing &&
5973 	 * mirror_num == num_stripes + 1 && dev_replace target drive is
5974 	 * available as a mirror
5975 	 */
5976 	if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5977 		WARN_ON(num_stripes > 1);
5978 		bbio->stripes[0].dev = dev_replace->tgtdev;
5979 		bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5980 		bbio->mirror_num = map->num_stripes + 1;
5981 	}
5982 out:
5983 	if (dev_replace_is_ongoing) {
5984 		btrfs_dev_replace_clear_lock_blocking(dev_replace);
5985 		btrfs_dev_replace_unlock(dev_replace, 0);
5986 	}
5987 	free_extent_map(em);
5988 	return ret;
5989 }
5990 
5991 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5992 		      u64 logical, u64 *length,
5993 		      struct btrfs_bio **bbio_ret, int mirror_num)
5994 {
5995 	return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5996 				 mirror_num, 0);
5997 }
5998 
5999 /* For Scrub/replace */
6000 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6001 		     u64 logical, u64 *length,
6002 		     struct btrfs_bio **bbio_ret)
6003 {
6004 	return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6005 }
6006 
6007 int btrfs_rmap_block(struct btrfs_fs_info *fs_info,
6008 		     u64 chunk_start, u64 physical, u64 devid,
6009 		     u64 **logical, int *naddrs, int *stripe_len)
6010 {
6011 	struct extent_map *em;
6012 	struct map_lookup *map;
6013 	u64 *buf;
6014 	u64 bytenr;
6015 	u64 length;
6016 	u64 stripe_nr;
6017 	u64 rmap_len;
6018 	int i, j, nr = 0;
6019 
6020 	em = get_chunk_map(fs_info, chunk_start, 1);
6021 	if (IS_ERR(em))
6022 		return -EIO;
6023 
6024 	map = em->map_lookup;
6025 	length = em->len;
6026 	rmap_len = map->stripe_len;
6027 
6028 	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6029 		length = div_u64(length, map->num_stripes / map->sub_stripes);
6030 	else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6031 		length = div_u64(length, map->num_stripes);
6032 	else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6033 		length = div_u64(length, nr_data_stripes(map));
6034 		rmap_len = map->stripe_len * nr_data_stripes(map);
6035 	}
6036 
6037 	buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6038 	BUG_ON(!buf); /* -ENOMEM */
6039 
6040 	for (i = 0; i < map->num_stripes; i++) {
6041 		if (devid && map->stripes[i].dev->devid != devid)
6042 			continue;
6043 		if (map->stripes[i].physical > physical ||
6044 		    map->stripes[i].physical + length <= physical)
6045 			continue;
6046 
6047 		stripe_nr = physical - map->stripes[i].physical;
6048 		stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6049 
6050 		if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6051 			stripe_nr = stripe_nr * map->num_stripes + i;
6052 			stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6053 		} else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6054 			stripe_nr = stripe_nr * map->num_stripes + i;
6055 		} /* else if RAID[56], multiply by nr_data_stripes().
6056 		   * Alternatively, just use rmap_len below instead of
6057 		   * map->stripe_len */
6058 
6059 		bytenr = chunk_start + stripe_nr * rmap_len;
6060 		WARN_ON(nr >= map->num_stripes);
6061 		for (j = 0; j < nr; j++) {
6062 			if (buf[j] == bytenr)
6063 				break;
6064 		}
6065 		if (j == nr) {
6066 			WARN_ON(nr >= map->num_stripes);
6067 			buf[nr++] = bytenr;
6068 		}
6069 	}
6070 
6071 	*logical = buf;
6072 	*naddrs = nr;
6073 	*stripe_len = rmap_len;
6074 
6075 	free_extent_map(em);
6076 	return 0;
6077 }
6078 
6079 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6080 {
6081 	bio->bi_private = bbio->private;
6082 	bio->bi_end_io = bbio->end_io;
6083 	bio_endio(bio);
6084 
6085 	btrfs_put_bbio(bbio);
6086 }
6087 
6088 static void btrfs_end_bio(struct bio *bio)
6089 {
6090 	struct btrfs_bio *bbio = bio->bi_private;
6091 	int is_orig_bio = 0;
6092 
6093 	if (bio->bi_status) {
6094 		atomic_inc(&bbio->error);
6095 		if (bio->bi_status == BLK_STS_IOERR ||
6096 		    bio->bi_status == BLK_STS_TARGET) {
6097 			unsigned int stripe_index =
6098 				btrfs_io_bio(bio)->stripe_index;
6099 			struct btrfs_device *dev;
6100 
6101 			BUG_ON(stripe_index >= bbio->num_stripes);
6102 			dev = bbio->stripes[stripe_index].dev;
6103 			if (dev->bdev) {
6104 				if (bio_op(bio) == REQ_OP_WRITE)
6105 					btrfs_dev_stat_inc_and_print(dev,
6106 						BTRFS_DEV_STAT_WRITE_ERRS);
6107 				else
6108 					btrfs_dev_stat_inc_and_print(dev,
6109 						BTRFS_DEV_STAT_READ_ERRS);
6110 				if (bio->bi_opf & REQ_PREFLUSH)
6111 					btrfs_dev_stat_inc_and_print(dev,
6112 						BTRFS_DEV_STAT_FLUSH_ERRS);
6113 			}
6114 		}
6115 	}
6116 
6117 	if (bio == bbio->orig_bio)
6118 		is_orig_bio = 1;
6119 
6120 	btrfs_bio_counter_dec(bbio->fs_info);
6121 
6122 	if (atomic_dec_and_test(&bbio->stripes_pending)) {
6123 		if (!is_orig_bio) {
6124 			bio_put(bio);
6125 			bio = bbio->orig_bio;
6126 		}
6127 
6128 		btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6129 		/* only send an error to the higher layers if it is
6130 		 * beyond the tolerance of the btrfs bio
6131 		 */
6132 		if (atomic_read(&bbio->error) > bbio->max_errors) {
6133 			bio->bi_status = BLK_STS_IOERR;
6134 		} else {
6135 			/*
6136 			 * this bio is actually up to date, we didn't
6137 			 * go over the max number of errors
6138 			 */
6139 			bio->bi_status = BLK_STS_OK;
6140 		}
6141 
6142 		btrfs_end_bbio(bbio, bio);
6143 	} else if (!is_orig_bio) {
6144 		bio_put(bio);
6145 	}
6146 }
6147 
6148 /*
6149  * see run_scheduled_bios for a description of why bios are collected for
6150  * async submit.
6151  *
6152  * This will add one bio to the pending list for a device and make sure
6153  * the work struct is scheduled.
6154  */
6155 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6156 					struct bio *bio)
6157 {
6158 	struct btrfs_fs_info *fs_info = device->fs_info;
6159 	int should_queue = 1;
6160 	struct btrfs_pending_bios *pending_bios;
6161 
6162 	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
6163 	    !device->bdev) {
6164 		bio_io_error(bio);
6165 		return;
6166 	}
6167 
6168 	/* don't bother with additional async steps for reads, right now */
6169 	if (bio_op(bio) == REQ_OP_READ) {
6170 		btrfsic_submit_bio(bio);
6171 		return;
6172 	}
6173 
6174 	WARN_ON(bio->bi_next);
6175 	bio->bi_next = NULL;
6176 
6177 	spin_lock(&device->io_lock);
6178 	if (op_is_sync(bio->bi_opf))
6179 		pending_bios = &device->pending_sync_bios;
6180 	else
6181 		pending_bios = &device->pending_bios;
6182 
6183 	if (pending_bios->tail)
6184 		pending_bios->tail->bi_next = bio;
6185 
6186 	pending_bios->tail = bio;
6187 	if (!pending_bios->head)
6188 		pending_bios->head = bio;
6189 	if (device->running_pending)
6190 		should_queue = 0;
6191 
6192 	spin_unlock(&device->io_lock);
6193 
6194 	if (should_queue)
6195 		btrfs_queue_work(fs_info->submit_workers, &device->work);
6196 }
6197 
6198 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6199 			      u64 physical, int dev_nr, int async)
6200 {
6201 	struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6202 	struct btrfs_fs_info *fs_info = bbio->fs_info;
6203 
6204 	bio->bi_private = bbio;
6205 	btrfs_io_bio(bio)->stripe_index = dev_nr;
6206 	bio->bi_end_io = btrfs_end_bio;
6207 	bio->bi_iter.bi_sector = physical >> 9;
6208 #ifdef DEBUG
6209 	{
6210 		struct rcu_string *name;
6211 
6212 		rcu_read_lock();
6213 		name = rcu_dereference(dev->name);
6214 		btrfs_debug(fs_info,
6215 			"btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6216 			bio_op(bio), bio->bi_opf,
6217 			(u64)bio->bi_iter.bi_sector,
6218 			(u_long)dev->bdev->bd_dev, name->str, dev->devid,
6219 			bio->bi_iter.bi_size);
6220 		rcu_read_unlock();
6221 	}
6222 #endif
6223 	bio_set_dev(bio, dev->bdev);
6224 
6225 	btrfs_bio_counter_inc_noblocked(fs_info);
6226 
6227 	if (async)
6228 		btrfs_schedule_bio(dev, bio);
6229 	else
6230 		btrfsic_submit_bio(bio);
6231 }
6232 
6233 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6234 {
6235 	atomic_inc(&bbio->error);
6236 	if (atomic_dec_and_test(&bbio->stripes_pending)) {
6237 		/* Should be the original bio. */
6238 		WARN_ON(bio != bbio->orig_bio);
6239 
6240 		btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6241 		bio->bi_iter.bi_sector = logical >> 9;
6242 		if (atomic_read(&bbio->error) > bbio->max_errors)
6243 			bio->bi_status = BLK_STS_IOERR;
6244 		else
6245 			bio->bi_status = BLK_STS_OK;
6246 		btrfs_end_bbio(bbio, bio);
6247 	}
6248 }
6249 
6250 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6251 			   int mirror_num, int async_submit)
6252 {
6253 	struct btrfs_device *dev;
6254 	struct bio *first_bio = bio;
6255 	u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6256 	u64 length = 0;
6257 	u64 map_length;
6258 	int ret;
6259 	int dev_nr;
6260 	int total_devs;
6261 	struct btrfs_bio *bbio = NULL;
6262 
6263 	length = bio->bi_iter.bi_size;
6264 	map_length = length;
6265 
6266 	btrfs_bio_counter_inc_blocked(fs_info);
6267 	ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6268 				&map_length, &bbio, mirror_num, 1);
6269 	if (ret) {
6270 		btrfs_bio_counter_dec(fs_info);
6271 		return errno_to_blk_status(ret);
6272 	}
6273 
6274 	total_devs = bbio->num_stripes;
6275 	bbio->orig_bio = first_bio;
6276 	bbio->private = first_bio->bi_private;
6277 	bbio->end_io = first_bio->bi_end_io;
6278 	bbio->fs_info = fs_info;
6279 	atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6280 
6281 	if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6282 	    ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6283 		/* In this case, map_length has been set to the length of
6284 		   a single stripe; not the whole write */
6285 		if (bio_op(bio) == REQ_OP_WRITE) {
6286 			ret = raid56_parity_write(fs_info, bio, bbio,
6287 						  map_length);
6288 		} else {
6289 			ret = raid56_parity_recover(fs_info, bio, bbio,
6290 						    map_length, mirror_num, 1);
6291 		}
6292 
6293 		btrfs_bio_counter_dec(fs_info);
6294 		return errno_to_blk_status(ret);
6295 	}
6296 
6297 	if (map_length < length) {
6298 		btrfs_crit(fs_info,
6299 			   "mapping failed logical %llu bio len %llu len %llu",
6300 			   logical, length, map_length);
6301 		BUG();
6302 	}
6303 
6304 	for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6305 		dev = bbio->stripes[dev_nr].dev;
6306 		if (!dev || !dev->bdev ||
6307 		    (bio_op(first_bio) == REQ_OP_WRITE &&
6308 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6309 			bbio_error(bbio, first_bio, logical);
6310 			continue;
6311 		}
6312 
6313 		if (dev_nr < total_devs - 1)
6314 			bio = btrfs_bio_clone(first_bio);
6315 		else
6316 			bio = first_bio;
6317 
6318 		submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6319 				  dev_nr, async_submit);
6320 	}
6321 	btrfs_bio_counter_dec(fs_info);
6322 	return BLK_STS_OK;
6323 }
6324 
6325 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6326 				       u8 *uuid, u8 *fsid)
6327 {
6328 	struct btrfs_device *device;
6329 	struct btrfs_fs_devices *cur_devices;
6330 
6331 	cur_devices = fs_info->fs_devices;
6332 	while (cur_devices) {
6333 		if (!fsid ||
6334 		    !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6335 			device = find_device(cur_devices, devid, uuid);
6336 			if (device)
6337 				return device;
6338 		}
6339 		cur_devices = cur_devices->seed;
6340 	}
6341 	return NULL;
6342 }
6343 
6344 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6345 					    u64 devid, u8 *dev_uuid)
6346 {
6347 	struct btrfs_device *device;
6348 
6349 	device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6350 	if (IS_ERR(device))
6351 		return device;
6352 
6353 	list_add(&device->dev_list, &fs_devices->devices);
6354 	device->fs_devices = fs_devices;
6355 	fs_devices->num_devices++;
6356 
6357 	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6358 	fs_devices->missing_devices++;
6359 
6360 	return device;
6361 }
6362 
6363 /**
6364  * btrfs_alloc_device - allocate struct btrfs_device
6365  * @fs_info:	used only for generating a new devid, can be NULL if
6366  *		devid is provided (i.e. @devid != NULL).
6367  * @devid:	a pointer to devid for this device.  If NULL a new devid
6368  *		is generated.
6369  * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
6370  *		is generated.
6371  *
6372  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6373  * on error.  Returned struct is not linked onto any lists and must be
6374  * destroyed with free_device.
6375  */
6376 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6377 					const u64 *devid,
6378 					const u8 *uuid)
6379 {
6380 	struct btrfs_device *dev;
6381 	u64 tmp;
6382 
6383 	if (WARN_ON(!devid && !fs_info))
6384 		return ERR_PTR(-EINVAL);
6385 
6386 	dev = __alloc_device();
6387 	if (IS_ERR(dev))
6388 		return dev;
6389 
6390 	if (devid)
6391 		tmp = *devid;
6392 	else {
6393 		int ret;
6394 
6395 		ret = find_next_devid(fs_info, &tmp);
6396 		if (ret) {
6397 			free_device(dev);
6398 			return ERR_PTR(ret);
6399 		}
6400 	}
6401 	dev->devid = tmp;
6402 
6403 	if (uuid)
6404 		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6405 	else
6406 		generate_random_uuid(dev->uuid);
6407 
6408 	btrfs_init_work(&dev->work, btrfs_submit_helper,
6409 			pending_bios_fn, NULL, NULL);
6410 
6411 	return dev;
6412 }
6413 
6414 /* Return -EIO if any error, otherwise return 0. */
6415 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6416 				   struct extent_buffer *leaf,
6417 				   struct btrfs_chunk *chunk, u64 logical)
6418 {
6419 	u64 length;
6420 	u64 stripe_len;
6421 	u16 num_stripes;
6422 	u16 sub_stripes;
6423 	u64 type;
6424 
6425 	length = btrfs_chunk_length(leaf, chunk);
6426 	stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6427 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6428 	sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6429 	type = btrfs_chunk_type(leaf, chunk);
6430 
6431 	if (!num_stripes) {
6432 		btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6433 			  num_stripes);
6434 		return -EIO;
6435 	}
6436 	if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6437 		btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6438 		return -EIO;
6439 	}
6440 	if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6441 		btrfs_err(fs_info, "invalid chunk sectorsize %u",
6442 			  btrfs_chunk_sector_size(leaf, chunk));
6443 		return -EIO;
6444 	}
6445 	if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6446 		btrfs_err(fs_info, "invalid chunk length %llu", length);
6447 		return -EIO;
6448 	}
6449 	if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6450 		btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6451 			  stripe_len);
6452 		return -EIO;
6453 	}
6454 	if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6455 	    type) {
6456 		btrfs_err(fs_info, "unrecognized chunk type: %llu",
6457 			  ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6458 			    BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6459 			  btrfs_chunk_type(leaf, chunk));
6460 		return -EIO;
6461 	}
6462 	if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6463 	    (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6464 	    (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6465 	    (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6466 	    (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6467 	    ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6468 	     num_stripes != 1)) {
6469 		btrfs_err(fs_info,
6470 			"invalid num_stripes:sub_stripes %u:%u for profile %llu",
6471 			num_stripes, sub_stripes,
6472 			type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6473 		return -EIO;
6474 	}
6475 
6476 	return 0;
6477 }
6478 
6479 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6480 					u64 devid, u8 *uuid, bool error)
6481 {
6482 	if (error)
6483 		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6484 			      devid, uuid);
6485 	else
6486 		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6487 			      devid, uuid);
6488 }
6489 
6490 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6491 			  struct extent_buffer *leaf,
6492 			  struct btrfs_chunk *chunk)
6493 {
6494 	struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6495 	struct map_lookup *map;
6496 	struct extent_map *em;
6497 	u64 logical;
6498 	u64 length;
6499 	u64 devid;
6500 	u8 uuid[BTRFS_UUID_SIZE];
6501 	int num_stripes;
6502 	int ret;
6503 	int i;
6504 
6505 	logical = key->offset;
6506 	length = btrfs_chunk_length(leaf, chunk);
6507 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6508 
6509 	ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6510 	if (ret)
6511 		return ret;
6512 
6513 	read_lock(&map_tree->map_tree.lock);
6514 	em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6515 	read_unlock(&map_tree->map_tree.lock);
6516 
6517 	/* already mapped? */
6518 	if (em && em->start <= logical && em->start + em->len > logical) {
6519 		free_extent_map(em);
6520 		return 0;
6521 	} else if (em) {
6522 		free_extent_map(em);
6523 	}
6524 
6525 	em = alloc_extent_map();
6526 	if (!em)
6527 		return -ENOMEM;
6528 	map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6529 	if (!map) {
6530 		free_extent_map(em);
6531 		return -ENOMEM;
6532 	}
6533 
6534 	set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6535 	em->map_lookup = map;
6536 	em->start = logical;
6537 	em->len = length;
6538 	em->orig_start = 0;
6539 	em->block_start = 0;
6540 	em->block_len = em->len;
6541 
6542 	map->num_stripes = num_stripes;
6543 	map->io_width = btrfs_chunk_io_width(leaf, chunk);
6544 	map->io_align = btrfs_chunk_io_align(leaf, chunk);
6545 	map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6546 	map->type = btrfs_chunk_type(leaf, chunk);
6547 	map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6548 	for (i = 0; i < num_stripes; i++) {
6549 		map->stripes[i].physical =
6550 			btrfs_stripe_offset_nr(leaf, chunk, i);
6551 		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6552 		read_extent_buffer(leaf, uuid, (unsigned long)
6553 				   btrfs_stripe_dev_uuid_nr(chunk, i),
6554 				   BTRFS_UUID_SIZE);
6555 		map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6556 							uuid, NULL);
6557 		if (!map->stripes[i].dev &&
6558 		    !btrfs_test_opt(fs_info, DEGRADED)) {
6559 			free_extent_map(em);
6560 			btrfs_report_missing_device(fs_info, devid, uuid, true);
6561 			return -ENOENT;
6562 		}
6563 		if (!map->stripes[i].dev) {
6564 			map->stripes[i].dev =
6565 				add_missing_dev(fs_info->fs_devices, devid,
6566 						uuid);
6567 			if (IS_ERR(map->stripes[i].dev)) {
6568 				free_extent_map(em);
6569 				btrfs_err(fs_info,
6570 					"failed to init missing dev %llu: %ld",
6571 					devid, PTR_ERR(map->stripes[i].dev));
6572 				return PTR_ERR(map->stripes[i].dev);
6573 			}
6574 			btrfs_report_missing_device(fs_info, devid, uuid, false);
6575 		}
6576 		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6577 				&(map->stripes[i].dev->dev_state));
6578 
6579 	}
6580 
6581 	write_lock(&map_tree->map_tree.lock);
6582 	ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6583 	write_unlock(&map_tree->map_tree.lock);
6584 	BUG_ON(ret); /* Tree corruption */
6585 	free_extent_map(em);
6586 
6587 	return 0;
6588 }
6589 
6590 static void fill_device_from_item(struct extent_buffer *leaf,
6591 				 struct btrfs_dev_item *dev_item,
6592 				 struct btrfs_device *device)
6593 {
6594 	unsigned long ptr;
6595 
6596 	device->devid = btrfs_device_id(leaf, dev_item);
6597 	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6598 	device->total_bytes = device->disk_total_bytes;
6599 	device->commit_total_bytes = device->disk_total_bytes;
6600 	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6601 	device->commit_bytes_used = device->bytes_used;
6602 	device->type = btrfs_device_type(leaf, dev_item);
6603 	device->io_align = btrfs_device_io_align(leaf, dev_item);
6604 	device->io_width = btrfs_device_io_width(leaf, dev_item);
6605 	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6606 	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6607 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6608 
6609 	ptr = btrfs_device_uuid(dev_item);
6610 	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6611 }
6612 
6613 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6614 						  u8 *fsid)
6615 {
6616 	struct btrfs_fs_devices *fs_devices;
6617 	int ret;
6618 
6619 	BUG_ON(!mutex_is_locked(&uuid_mutex));
6620 	ASSERT(fsid);
6621 
6622 	fs_devices = fs_info->fs_devices->seed;
6623 	while (fs_devices) {
6624 		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6625 			return fs_devices;
6626 
6627 		fs_devices = fs_devices->seed;
6628 	}
6629 
6630 	fs_devices = find_fsid(fsid);
6631 	if (!fs_devices) {
6632 		if (!btrfs_test_opt(fs_info, DEGRADED))
6633 			return ERR_PTR(-ENOENT);
6634 
6635 		fs_devices = alloc_fs_devices(fsid);
6636 		if (IS_ERR(fs_devices))
6637 			return fs_devices;
6638 
6639 		fs_devices->seeding = 1;
6640 		fs_devices->opened = 1;
6641 		return fs_devices;
6642 	}
6643 
6644 	fs_devices = clone_fs_devices(fs_devices);
6645 	if (IS_ERR(fs_devices))
6646 		return fs_devices;
6647 
6648 	ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6649 				   fs_info->bdev_holder);
6650 	if (ret) {
6651 		free_fs_devices(fs_devices);
6652 		fs_devices = ERR_PTR(ret);
6653 		goto out;
6654 	}
6655 
6656 	if (!fs_devices->seeding) {
6657 		__btrfs_close_devices(fs_devices);
6658 		free_fs_devices(fs_devices);
6659 		fs_devices = ERR_PTR(-EINVAL);
6660 		goto out;
6661 	}
6662 
6663 	fs_devices->seed = fs_info->fs_devices->seed;
6664 	fs_info->fs_devices->seed = fs_devices;
6665 out:
6666 	return fs_devices;
6667 }
6668 
6669 static int read_one_dev(struct btrfs_fs_info *fs_info,
6670 			struct extent_buffer *leaf,
6671 			struct btrfs_dev_item *dev_item)
6672 {
6673 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6674 	struct btrfs_device *device;
6675 	u64 devid;
6676 	int ret;
6677 	u8 fs_uuid[BTRFS_FSID_SIZE];
6678 	u8 dev_uuid[BTRFS_UUID_SIZE];
6679 
6680 	devid = btrfs_device_id(leaf, dev_item);
6681 	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6682 			   BTRFS_UUID_SIZE);
6683 	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6684 			   BTRFS_FSID_SIZE);
6685 
6686 	if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6687 		fs_devices = open_seed_devices(fs_info, fs_uuid);
6688 		if (IS_ERR(fs_devices))
6689 			return PTR_ERR(fs_devices);
6690 	}
6691 
6692 	device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6693 	if (!device) {
6694 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
6695 			btrfs_report_missing_device(fs_info, devid,
6696 							dev_uuid, true);
6697 			return -ENOENT;
6698 		}
6699 
6700 		device = add_missing_dev(fs_devices, devid, dev_uuid);
6701 		if (IS_ERR(device)) {
6702 			btrfs_err(fs_info,
6703 				"failed to add missing dev %llu: %ld",
6704 				devid, PTR_ERR(device));
6705 			return PTR_ERR(device);
6706 		}
6707 		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6708 	} else {
6709 		if (!device->bdev) {
6710 			if (!btrfs_test_opt(fs_info, DEGRADED)) {
6711 				btrfs_report_missing_device(fs_info,
6712 						devid, dev_uuid, true);
6713 				return -ENOENT;
6714 			}
6715 			btrfs_report_missing_device(fs_info, devid,
6716 							dev_uuid, false);
6717 		}
6718 
6719 		if (!device->bdev &&
6720 		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6721 			/*
6722 			 * this happens when a device that was properly setup
6723 			 * in the device info lists suddenly goes bad.
6724 			 * device->bdev is NULL, and so we have to set
6725 			 * device->missing to one here
6726 			 */
6727 			device->fs_devices->missing_devices++;
6728 			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6729 		}
6730 
6731 		/* Move the device to its own fs_devices */
6732 		if (device->fs_devices != fs_devices) {
6733 			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6734 							&device->dev_state));
6735 
6736 			list_move(&device->dev_list, &fs_devices->devices);
6737 			device->fs_devices->num_devices--;
6738 			fs_devices->num_devices++;
6739 
6740 			device->fs_devices->missing_devices--;
6741 			fs_devices->missing_devices++;
6742 
6743 			device->fs_devices = fs_devices;
6744 		}
6745 	}
6746 
6747 	if (device->fs_devices != fs_info->fs_devices) {
6748 		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6749 		if (device->generation !=
6750 		    btrfs_device_generation(leaf, dev_item))
6751 			return -EINVAL;
6752 	}
6753 
6754 	fill_device_from_item(leaf, dev_item, device);
6755 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6756 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6757 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6758 		device->fs_devices->total_rw_bytes += device->total_bytes;
6759 		atomic64_add(device->total_bytes - device->bytes_used,
6760 				&fs_info->free_chunk_space);
6761 	}
6762 	ret = 0;
6763 	return ret;
6764 }
6765 
6766 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6767 {
6768 	struct btrfs_root *root = fs_info->tree_root;
6769 	struct btrfs_super_block *super_copy = fs_info->super_copy;
6770 	struct extent_buffer *sb;
6771 	struct btrfs_disk_key *disk_key;
6772 	struct btrfs_chunk *chunk;
6773 	u8 *array_ptr;
6774 	unsigned long sb_array_offset;
6775 	int ret = 0;
6776 	u32 num_stripes;
6777 	u32 array_size;
6778 	u32 len = 0;
6779 	u32 cur_offset;
6780 	u64 type;
6781 	struct btrfs_key key;
6782 
6783 	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6784 	/*
6785 	 * This will create extent buffer of nodesize, superblock size is
6786 	 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6787 	 * overallocate but we can keep it as-is, only the first page is used.
6788 	 */
6789 	sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6790 	if (IS_ERR(sb))
6791 		return PTR_ERR(sb);
6792 	set_extent_buffer_uptodate(sb);
6793 	btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6794 	/*
6795 	 * The sb extent buffer is artificial and just used to read the system array.
6796 	 * set_extent_buffer_uptodate() call does not properly mark all it's
6797 	 * pages up-to-date when the page is larger: extent does not cover the
6798 	 * whole page and consequently check_page_uptodate does not find all
6799 	 * the page's extents up-to-date (the hole beyond sb),
6800 	 * write_extent_buffer then triggers a WARN_ON.
6801 	 *
6802 	 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6803 	 * but sb spans only this function. Add an explicit SetPageUptodate call
6804 	 * to silence the warning eg. on PowerPC 64.
6805 	 */
6806 	if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6807 		SetPageUptodate(sb->pages[0]);
6808 
6809 	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6810 	array_size = btrfs_super_sys_array_size(super_copy);
6811 
6812 	array_ptr = super_copy->sys_chunk_array;
6813 	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6814 	cur_offset = 0;
6815 
6816 	while (cur_offset < array_size) {
6817 		disk_key = (struct btrfs_disk_key *)array_ptr;
6818 		len = sizeof(*disk_key);
6819 		if (cur_offset + len > array_size)
6820 			goto out_short_read;
6821 
6822 		btrfs_disk_key_to_cpu(&key, disk_key);
6823 
6824 		array_ptr += len;
6825 		sb_array_offset += len;
6826 		cur_offset += len;
6827 
6828 		if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6829 			chunk = (struct btrfs_chunk *)sb_array_offset;
6830 			/*
6831 			 * At least one btrfs_chunk with one stripe must be
6832 			 * present, exact stripe count check comes afterwards
6833 			 */
6834 			len = btrfs_chunk_item_size(1);
6835 			if (cur_offset + len > array_size)
6836 				goto out_short_read;
6837 
6838 			num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6839 			if (!num_stripes) {
6840 				btrfs_err(fs_info,
6841 					"invalid number of stripes %u in sys_array at offset %u",
6842 					num_stripes, cur_offset);
6843 				ret = -EIO;
6844 				break;
6845 			}
6846 
6847 			type = btrfs_chunk_type(sb, chunk);
6848 			if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6849 				btrfs_err(fs_info,
6850 			    "invalid chunk type %llu in sys_array at offset %u",
6851 					type, cur_offset);
6852 				ret = -EIO;
6853 				break;
6854 			}
6855 
6856 			len = btrfs_chunk_item_size(num_stripes);
6857 			if (cur_offset + len > array_size)
6858 				goto out_short_read;
6859 
6860 			ret = read_one_chunk(fs_info, &key, sb, chunk);
6861 			if (ret)
6862 				break;
6863 		} else {
6864 			btrfs_err(fs_info,
6865 			    "unexpected item type %u in sys_array at offset %u",
6866 				  (u32)key.type, cur_offset);
6867 			ret = -EIO;
6868 			break;
6869 		}
6870 		array_ptr += len;
6871 		sb_array_offset += len;
6872 		cur_offset += len;
6873 	}
6874 	clear_extent_buffer_uptodate(sb);
6875 	free_extent_buffer_stale(sb);
6876 	return ret;
6877 
6878 out_short_read:
6879 	btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6880 			len, cur_offset);
6881 	clear_extent_buffer_uptodate(sb);
6882 	free_extent_buffer_stale(sb);
6883 	return -EIO;
6884 }
6885 
6886 /*
6887  * Check if all chunks in the fs are OK for read-write degraded mount
6888  *
6889  * If the @failing_dev is specified, it's accounted as missing.
6890  *
6891  * Return true if all chunks meet the minimal RW mount requirements.
6892  * Return false if any chunk doesn't meet the minimal RW mount requirements.
6893  */
6894 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6895 					struct btrfs_device *failing_dev)
6896 {
6897 	struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6898 	struct extent_map *em;
6899 	u64 next_start = 0;
6900 	bool ret = true;
6901 
6902 	read_lock(&map_tree->map_tree.lock);
6903 	em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6904 	read_unlock(&map_tree->map_tree.lock);
6905 	/* No chunk at all? Return false anyway */
6906 	if (!em) {
6907 		ret = false;
6908 		goto out;
6909 	}
6910 	while (em) {
6911 		struct map_lookup *map;
6912 		int missing = 0;
6913 		int max_tolerated;
6914 		int i;
6915 
6916 		map = em->map_lookup;
6917 		max_tolerated =
6918 			btrfs_get_num_tolerated_disk_barrier_failures(
6919 					map->type);
6920 		for (i = 0; i < map->num_stripes; i++) {
6921 			struct btrfs_device *dev = map->stripes[i].dev;
6922 
6923 			if (!dev || !dev->bdev ||
6924 			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6925 			    dev->last_flush_error)
6926 				missing++;
6927 			else if (failing_dev && failing_dev == dev)
6928 				missing++;
6929 		}
6930 		if (missing > max_tolerated) {
6931 			if (!failing_dev)
6932 				btrfs_warn(fs_info,
6933 	"chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6934 				   em->start, missing, max_tolerated);
6935 			free_extent_map(em);
6936 			ret = false;
6937 			goto out;
6938 		}
6939 		next_start = extent_map_end(em);
6940 		free_extent_map(em);
6941 
6942 		read_lock(&map_tree->map_tree.lock);
6943 		em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6944 					   (u64)(-1) - next_start);
6945 		read_unlock(&map_tree->map_tree.lock);
6946 	}
6947 out:
6948 	return ret;
6949 }
6950 
6951 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6952 {
6953 	struct btrfs_root *root = fs_info->chunk_root;
6954 	struct btrfs_path *path;
6955 	struct extent_buffer *leaf;
6956 	struct btrfs_key key;
6957 	struct btrfs_key found_key;
6958 	int ret;
6959 	int slot;
6960 	u64 total_dev = 0;
6961 
6962 	path = btrfs_alloc_path();
6963 	if (!path)
6964 		return -ENOMEM;
6965 
6966 	mutex_lock(&uuid_mutex);
6967 	mutex_lock(&fs_info->chunk_mutex);
6968 
6969 	/*
6970 	 * Read all device items, and then all the chunk items. All
6971 	 * device items are found before any chunk item (their object id
6972 	 * is smaller than the lowest possible object id for a chunk
6973 	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6974 	 */
6975 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6976 	key.offset = 0;
6977 	key.type = 0;
6978 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6979 	if (ret < 0)
6980 		goto error;
6981 	while (1) {
6982 		leaf = path->nodes[0];
6983 		slot = path->slots[0];
6984 		if (slot >= btrfs_header_nritems(leaf)) {
6985 			ret = btrfs_next_leaf(root, path);
6986 			if (ret == 0)
6987 				continue;
6988 			if (ret < 0)
6989 				goto error;
6990 			break;
6991 		}
6992 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
6993 		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6994 			struct btrfs_dev_item *dev_item;
6995 			dev_item = btrfs_item_ptr(leaf, slot,
6996 						  struct btrfs_dev_item);
6997 			ret = read_one_dev(fs_info, leaf, dev_item);
6998 			if (ret)
6999 				goto error;
7000 			total_dev++;
7001 		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7002 			struct btrfs_chunk *chunk;
7003 			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7004 			ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7005 			if (ret)
7006 				goto error;
7007 		}
7008 		path->slots[0]++;
7009 	}
7010 
7011 	/*
7012 	 * After loading chunk tree, we've got all device information,
7013 	 * do another round of validation checks.
7014 	 */
7015 	if (total_dev != fs_info->fs_devices->total_devices) {
7016 		btrfs_err(fs_info,
7017 	   "super_num_devices %llu mismatch with num_devices %llu found here",
7018 			  btrfs_super_num_devices(fs_info->super_copy),
7019 			  total_dev);
7020 		ret = -EINVAL;
7021 		goto error;
7022 	}
7023 	if (btrfs_super_total_bytes(fs_info->super_copy) <
7024 	    fs_info->fs_devices->total_rw_bytes) {
7025 		btrfs_err(fs_info,
7026 	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7027 			  btrfs_super_total_bytes(fs_info->super_copy),
7028 			  fs_info->fs_devices->total_rw_bytes);
7029 		ret = -EINVAL;
7030 		goto error;
7031 	}
7032 	ret = 0;
7033 error:
7034 	mutex_unlock(&fs_info->chunk_mutex);
7035 	mutex_unlock(&uuid_mutex);
7036 
7037 	btrfs_free_path(path);
7038 	return ret;
7039 }
7040 
7041 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7042 {
7043 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7044 	struct btrfs_device *device;
7045 
7046 	while (fs_devices) {
7047 		mutex_lock(&fs_devices->device_list_mutex);
7048 		list_for_each_entry(device, &fs_devices->devices, dev_list)
7049 			device->fs_info = fs_info;
7050 		mutex_unlock(&fs_devices->device_list_mutex);
7051 
7052 		fs_devices = fs_devices->seed;
7053 	}
7054 }
7055 
7056 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7057 {
7058 	int i;
7059 
7060 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7061 		btrfs_dev_stat_reset(dev, i);
7062 }
7063 
7064 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7065 {
7066 	struct btrfs_key key;
7067 	struct btrfs_key found_key;
7068 	struct btrfs_root *dev_root = fs_info->dev_root;
7069 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7070 	struct extent_buffer *eb;
7071 	int slot;
7072 	int ret = 0;
7073 	struct btrfs_device *device;
7074 	struct btrfs_path *path = NULL;
7075 	int i;
7076 
7077 	path = btrfs_alloc_path();
7078 	if (!path) {
7079 		ret = -ENOMEM;
7080 		goto out;
7081 	}
7082 
7083 	mutex_lock(&fs_devices->device_list_mutex);
7084 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7085 		int item_size;
7086 		struct btrfs_dev_stats_item *ptr;
7087 
7088 		key.objectid = BTRFS_DEV_STATS_OBJECTID;
7089 		key.type = BTRFS_PERSISTENT_ITEM_KEY;
7090 		key.offset = device->devid;
7091 		ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7092 		if (ret) {
7093 			__btrfs_reset_dev_stats(device);
7094 			device->dev_stats_valid = 1;
7095 			btrfs_release_path(path);
7096 			continue;
7097 		}
7098 		slot = path->slots[0];
7099 		eb = path->nodes[0];
7100 		btrfs_item_key_to_cpu(eb, &found_key, slot);
7101 		item_size = btrfs_item_size_nr(eb, slot);
7102 
7103 		ptr = btrfs_item_ptr(eb, slot,
7104 				     struct btrfs_dev_stats_item);
7105 
7106 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7107 			if (item_size >= (1 + i) * sizeof(__le64))
7108 				btrfs_dev_stat_set(device, i,
7109 					btrfs_dev_stats_value(eb, ptr, i));
7110 			else
7111 				btrfs_dev_stat_reset(device, i);
7112 		}
7113 
7114 		device->dev_stats_valid = 1;
7115 		btrfs_dev_stat_print_on_load(device);
7116 		btrfs_release_path(path);
7117 	}
7118 	mutex_unlock(&fs_devices->device_list_mutex);
7119 
7120 out:
7121 	btrfs_free_path(path);
7122 	return ret < 0 ? ret : 0;
7123 }
7124 
7125 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7126 				struct btrfs_fs_info *fs_info,
7127 				struct btrfs_device *device)
7128 {
7129 	struct btrfs_root *dev_root = fs_info->dev_root;
7130 	struct btrfs_path *path;
7131 	struct btrfs_key key;
7132 	struct extent_buffer *eb;
7133 	struct btrfs_dev_stats_item *ptr;
7134 	int ret;
7135 	int i;
7136 
7137 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7138 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7139 	key.offset = device->devid;
7140 
7141 	path = btrfs_alloc_path();
7142 	if (!path)
7143 		return -ENOMEM;
7144 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7145 	if (ret < 0) {
7146 		btrfs_warn_in_rcu(fs_info,
7147 			"error %d while searching for dev_stats item for device %s",
7148 			      ret, rcu_str_deref(device->name));
7149 		goto out;
7150 	}
7151 
7152 	if (ret == 0 &&
7153 	    btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7154 		/* need to delete old one and insert a new one */
7155 		ret = btrfs_del_item(trans, dev_root, path);
7156 		if (ret != 0) {
7157 			btrfs_warn_in_rcu(fs_info,
7158 				"delete too small dev_stats item for device %s failed %d",
7159 				      rcu_str_deref(device->name), ret);
7160 			goto out;
7161 		}
7162 		ret = 1;
7163 	}
7164 
7165 	if (ret == 1) {
7166 		/* need to insert a new item */
7167 		btrfs_release_path(path);
7168 		ret = btrfs_insert_empty_item(trans, dev_root, path,
7169 					      &key, sizeof(*ptr));
7170 		if (ret < 0) {
7171 			btrfs_warn_in_rcu(fs_info,
7172 				"insert dev_stats item for device %s failed %d",
7173 				rcu_str_deref(device->name), ret);
7174 			goto out;
7175 		}
7176 	}
7177 
7178 	eb = path->nodes[0];
7179 	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7180 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7181 		btrfs_set_dev_stats_value(eb, ptr, i,
7182 					  btrfs_dev_stat_read(device, i));
7183 	btrfs_mark_buffer_dirty(eb);
7184 
7185 out:
7186 	btrfs_free_path(path);
7187 	return ret;
7188 }
7189 
7190 /*
7191  * called from commit_transaction. Writes all changed device stats to disk.
7192  */
7193 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7194 			struct btrfs_fs_info *fs_info)
7195 {
7196 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7197 	struct btrfs_device *device;
7198 	int stats_cnt;
7199 	int ret = 0;
7200 
7201 	mutex_lock(&fs_devices->device_list_mutex);
7202 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7203 		stats_cnt = atomic_read(&device->dev_stats_ccnt);
7204 		if (!device->dev_stats_valid || stats_cnt == 0)
7205 			continue;
7206 
7207 
7208 		/*
7209 		 * There is a LOAD-LOAD control dependency between the value of
7210 		 * dev_stats_ccnt and updating the on-disk values which requires
7211 		 * reading the in-memory counters. Such control dependencies
7212 		 * require explicit read memory barriers.
7213 		 *
7214 		 * This memory barriers pairs with smp_mb__before_atomic in
7215 		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7216 		 * barrier implied by atomic_xchg in
7217 		 * btrfs_dev_stats_read_and_reset
7218 		 */
7219 		smp_rmb();
7220 
7221 		ret = update_dev_stat_item(trans, fs_info, device);
7222 		if (!ret)
7223 			atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7224 	}
7225 	mutex_unlock(&fs_devices->device_list_mutex);
7226 
7227 	return ret;
7228 }
7229 
7230 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7231 {
7232 	btrfs_dev_stat_inc(dev, index);
7233 	btrfs_dev_stat_print_on_error(dev);
7234 }
7235 
7236 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7237 {
7238 	if (!dev->dev_stats_valid)
7239 		return;
7240 	btrfs_err_rl_in_rcu(dev->fs_info,
7241 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7242 			   rcu_str_deref(dev->name),
7243 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7244 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7245 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7246 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7247 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7248 }
7249 
7250 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7251 {
7252 	int i;
7253 
7254 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7255 		if (btrfs_dev_stat_read(dev, i) != 0)
7256 			break;
7257 	if (i == BTRFS_DEV_STAT_VALUES_MAX)
7258 		return; /* all values == 0, suppress message */
7259 
7260 	btrfs_info_in_rcu(dev->fs_info,
7261 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7262 	       rcu_str_deref(dev->name),
7263 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7264 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7265 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7266 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7267 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7268 }
7269 
7270 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7271 			struct btrfs_ioctl_get_dev_stats *stats)
7272 {
7273 	struct btrfs_device *dev;
7274 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7275 	int i;
7276 
7277 	mutex_lock(&fs_devices->device_list_mutex);
7278 	dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7279 	mutex_unlock(&fs_devices->device_list_mutex);
7280 
7281 	if (!dev) {
7282 		btrfs_warn(fs_info, "get dev_stats failed, device not found");
7283 		return -ENODEV;
7284 	} else if (!dev->dev_stats_valid) {
7285 		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7286 		return -ENODEV;
7287 	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7288 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7289 			if (stats->nr_items > i)
7290 				stats->values[i] =
7291 					btrfs_dev_stat_read_and_reset(dev, i);
7292 			else
7293 				btrfs_dev_stat_reset(dev, i);
7294 		}
7295 	} else {
7296 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7297 			if (stats->nr_items > i)
7298 				stats->values[i] = btrfs_dev_stat_read(dev, i);
7299 	}
7300 	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7301 		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7302 	return 0;
7303 }
7304 
7305 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7306 {
7307 	struct buffer_head *bh;
7308 	struct btrfs_super_block *disk_super;
7309 	int copy_num;
7310 
7311 	if (!bdev)
7312 		return;
7313 
7314 	for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7315 		copy_num++) {
7316 
7317 		if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7318 			continue;
7319 
7320 		disk_super = (struct btrfs_super_block *)bh->b_data;
7321 
7322 		memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7323 		set_buffer_dirty(bh);
7324 		sync_dirty_buffer(bh);
7325 		brelse(bh);
7326 	}
7327 
7328 	/* Notify udev that device has changed */
7329 	btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7330 
7331 	/* Update ctime/mtime for device path for libblkid */
7332 	update_dev_time(device_path);
7333 }
7334 
7335 /*
7336  * Update the size of all devices, which is used for writing out the
7337  * super blocks.
7338  */
7339 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7340 {
7341 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7342 	struct btrfs_device *curr, *next;
7343 
7344 	if (list_empty(&fs_devices->resized_devices))
7345 		return;
7346 
7347 	mutex_lock(&fs_devices->device_list_mutex);
7348 	mutex_lock(&fs_info->chunk_mutex);
7349 	list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7350 				 resized_list) {
7351 		list_del_init(&curr->resized_list);
7352 		curr->commit_total_bytes = curr->disk_total_bytes;
7353 	}
7354 	mutex_unlock(&fs_info->chunk_mutex);
7355 	mutex_unlock(&fs_devices->device_list_mutex);
7356 }
7357 
7358 /* Must be invoked during the transaction commit */
7359 void btrfs_update_commit_device_bytes_used(struct btrfs_fs_info *fs_info,
7360 					struct btrfs_transaction *transaction)
7361 {
7362 	struct extent_map *em;
7363 	struct map_lookup *map;
7364 	struct btrfs_device *dev;
7365 	int i;
7366 
7367 	if (list_empty(&transaction->pending_chunks))
7368 		return;
7369 
7370 	/* In order to kick the device replace finish process */
7371 	mutex_lock(&fs_info->chunk_mutex);
7372 	list_for_each_entry(em, &transaction->pending_chunks, list) {
7373 		map = em->map_lookup;
7374 
7375 		for (i = 0; i < map->num_stripes; i++) {
7376 			dev = map->stripes[i].dev;
7377 			dev->commit_bytes_used = dev->bytes_used;
7378 		}
7379 	}
7380 	mutex_unlock(&fs_info->chunk_mutex);
7381 }
7382 
7383 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7384 {
7385 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7386 	while (fs_devices) {
7387 		fs_devices->fs_info = fs_info;
7388 		fs_devices = fs_devices->seed;
7389 	}
7390 }
7391 
7392 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7393 {
7394 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7395 	while (fs_devices) {
7396 		fs_devices->fs_info = NULL;
7397 		fs_devices = fs_devices->seed;
7398 	}
7399 }
7400