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