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