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