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