xref: /linux/fs/btrfs/volumes.c (revision 9383a7fdcb27142d97e65fc76f28475018980b35)
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 
2481 	/* Remove sysfs entry, including for a missing device. */
2482 	btrfs_sysfs_remove_device(device);
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 	ret = btrfs_sysfs_add_device(device);
3101 	if (ret) {
3102 		mutex_unlock(&fs_devices->device_list_mutex);
3103 		goto error_unwind_device;
3104 	}
3105 
3106 	mutex_unlock(&fs_devices->device_list_mutex);
3107 
3108 	if (seeding_dev) {
3109 		mutex_lock(&fs_info->chunk_mutex);
3110 		ret = init_first_rw_device(trans);
3111 		btrfs_update_per_profile_avail(fs_info);
3112 		mutex_unlock(&fs_info->chunk_mutex);
3113 		if (unlikely(ret)) {
3114 			btrfs_abort_transaction(trans, ret);
3115 			goto error_sysfs;
3116 		}
3117 	}
3118 
3119 	ret = btrfs_add_dev_item(trans, device);
3120 	if (unlikely(ret)) {
3121 		btrfs_abort_transaction(trans, ret);
3122 		goto error_sysfs;
3123 	}
3124 
3125 	if (seeding_dev) {
3126 		ret = btrfs_finish_sprout(trans);
3127 		if (unlikely(ret)) {
3128 			btrfs_abort_transaction(trans, ret);
3129 			goto error_sysfs;
3130 		}
3131 
3132 		/*
3133 		 * fs_devices now represents the newly sprouted filesystem and
3134 		 * its fsid has been changed by btrfs_sprout_splice().
3135 		 */
3136 		btrfs_sysfs_update_sprout_fsid(fs_devices);
3137 	}
3138 
3139 	ret = btrfs_commit_transaction(trans);
3140 
3141 	if (seeding_dev) {
3142 		mutex_unlock(&uuid_mutex);
3143 		up_write(&sb->s_umount);
3144 		locked = false;
3145 
3146 		if (ret) { /* transaction commit */
3147 			bdev_allow_freeze(file_bdev(bdev_file));
3148 			return ret;
3149 		}
3150 
3151 		ret = btrfs_relocate_sys_chunks(fs_info);
3152 		if (ret < 0)
3153 			btrfs_handle_fs_error(fs_info, ret,
3154 				    "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
3155 		trans = btrfs_attach_transaction(root);
3156 		if (IS_ERR(trans)) {
3157 			if (PTR_ERR(trans) == -ENOENT) {
3158 				bdev_allow_freeze(file_bdev(bdev_file));
3159 				return 0;
3160 			}
3161 			ret = PTR_ERR(trans);
3162 			trans = NULL;
3163 			goto error_sysfs;
3164 		}
3165 		ret = btrfs_commit_transaction(trans);
3166 	}
3167 
3168 	/*
3169 	 * Now that we have written a new super block to this device, check all
3170 	 * other fs_devices list if device_path alienates any other scanned
3171 	 * device.
3172 	 * We can ignore the return value as it typically returns -EINVAL and
3173 	 * only succeeds if the device was an alien.
3174 	 */
3175 	btrfs_forget_devices(device->devt);
3176 
3177 	/* Update ctime/mtime for blkid or udev */
3178 	update_dev_time(device_path);
3179 
3180 	bdev_allow_freeze(file_bdev(bdev_file));
3181 	return ret;
3182 
3183 error_sysfs:
3184 	btrfs_sysfs_remove_device(device);
3185 error_unwind_device:
3186 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
3187 	if (seeding_dev)
3188 		btrfs_assign_next_active_device(device, seed_devices->latest_dev);
3189 	mutex_lock(&fs_info->chunk_mutex);
3190 	if (!list_empty(&device->post_commit_list))
3191 		list_del_init(&device->post_commit_list);
3192 	list_del_rcu(&device->dev_list);
3193 	list_del(&device->dev_alloc_list);
3194 	fs_info->fs_devices->num_devices--;
3195 	fs_info->fs_devices->open_devices--;
3196 	fs_info->fs_devices->rw_devices--;
3197 	fs_info->fs_devices->total_devices--;
3198 	fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
3199 	atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
3200 	btrfs_set_super_total_bytes(fs_info->super_copy,
3201 				    orig_super_total_bytes);
3202 	btrfs_set_super_num_devices(fs_info->super_copy,
3203 				    orig_super_num_devices);
3204 	if (seeding_dev)
3205 		btrfs_rollback_sprout(fs_info, seed_devices);
3206 	btrfs_update_per_profile_avail(fs_info);
3207 	mutex_unlock(&fs_info->chunk_mutex);
3208 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3209 	synchronize_rcu();
3210 error_trans:
3211 	if (trans)
3212 		btrfs_end_transaction(trans);
3213 error_free_zone:
3214 	btrfs_destroy_dev_zone_info(device);
3215 error_free_device:
3216 	btrfs_free_device(device);
3217 error:
3218 	btrfs_release_device_allow_freeze(bdev_file);
3219 	if (locked) {
3220 		mutex_unlock(&uuid_mutex);
3221 		up_write(&sb->s_umount);
3222 	}
3223 	return ret;
3224 }
3225 
3226 int btrfs_update_device(struct btrfs_trans_handle *trans, struct btrfs_device *device)
3227 {
3228 	int ret;
3229 	BTRFS_PATH_AUTO_FREE(path);
3230 	struct btrfs_root *root = device->fs_info->chunk_root;
3231 	struct btrfs_dev_item *dev_item;
3232 	struct extent_buffer *leaf;
3233 	struct btrfs_key key;
3234 
3235 	path = btrfs_alloc_path();
3236 	if (!path)
3237 		return -ENOMEM;
3238 
3239 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3240 	key.type = BTRFS_DEV_ITEM_KEY;
3241 	key.offset = device->devid;
3242 
3243 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3244 	if (ret < 0)
3245 		return ret;
3246 
3247 	if (ret > 0)
3248 		return -ENOENT;
3249 
3250 	leaf = path->nodes[0];
3251 	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
3252 
3253 	btrfs_set_device_id(leaf, dev_item, device->devid);
3254 	btrfs_set_device_type(leaf, dev_item, device->type);
3255 	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
3256 	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
3257 	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
3258 	btrfs_set_device_total_bytes(leaf, dev_item,
3259 				     btrfs_device_get_disk_total_bytes(device));
3260 	btrfs_set_device_bytes_used(leaf, dev_item,
3261 				    btrfs_device_get_bytes_used(device));
3262 	return ret;
3263 }
3264 
3265 int btrfs_grow_device(struct btrfs_trans_handle *trans,
3266 		      struct btrfs_device *device, u64 new_size)
3267 {
3268 	struct btrfs_fs_info *fs_info = device->fs_info;
3269 	struct btrfs_super_block *super_copy = fs_info->super_copy;
3270 	u64 old_total;
3271 	u64 diff;
3272 	int ret;
3273 
3274 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
3275 		return -EACCES;
3276 
3277 	new_size = round_down(new_size, fs_info->sectorsize);
3278 
3279 	mutex_lock(&fs_info->chunk_mutex);
3280 	old_total = btrfs_super_total_bytes(super_copy);
3281 	diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
3282 
3283 	if (new_size <= device->total_bytes ||
3284 	    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
3285 		mutex_unlock(&fs_info->chunk_mutex);
3286 		return -EINVAL;
3287 	}
3288 
3289 	btrfs_set_super_total_bytes(super_copy,
3290 			round_down(old_total + diff, fs_info->sectorsize));
3291 	device->fs_devices->total_rw_bytes += diff;
3292 	atomic64_add(diff, &fs_info->free_chunk_space);
3293 
3294 	btrfs_device_set_total_bytes(device, new_size);
3295 	btrfs_device_set_disk_total_bytes(device, new_size);
3296 	btrfs_clear_space_info_full(device->fs_info);
3297 	if (list_empty(&device->post_commit_list))
3298 		list_add_tail(&device->post_commit_list,
3299 			      &trans->transaction->dev_update_list);
3300 	btrfs_update_per_profile_avail(fs_info);
3301 	mutex_unlock(&fs_info->chunk_mutex);
3302 
3303 	btrfs_reserve_chunk_metadata(trans, false);
3304 	ret = btrfs_update_device(trans, device);
3305 	btrfs_trans_release_chunk_metadata(trans);
3306 
3307 	return ret;
3308 }
3309 
3310 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3311 {
3312 	struct btrfs_fs_info *fs_info = trans->fs_info;
3313 	struct btrfs_root *root = fs_info->chunk_root;
3314 	int ret;
3315 	BTRFS_PATH_AUTO_FREE(path);
3316 	struct btrfs_key key;
3317 
3318 	path = btrfs_alloc_path();
3319 	if (!path)
3320 		return -ENOMEM;
3321 
3322 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3323 	key.type = BTRFS_CHUNK_ITEM_KEY;
3324 	key.offset = chunk_offset;
3325 
3326 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3327 	if (ret < 0)
3328 		return ret;
3329 	if (unlikely(ret > 0)) {
3330 		/* Logic error or corruption */
3331 		btrfs_err(fs_info, "failed to lookup chunk %llu when freeing",
3332 			  chunk_offset);
3333 		btrfs_abort_transaction(trans, -ENOENT);
3334 		return -EUCLEAN;
3335 	}
3336 
3337 	ret = btrfs_del_item(trans, root, path);
3338 	if (unlikely(ret < 0)) {
3339 		btrfs_err(fs_info, "failed to delete chunk %llu item", chunk_offset);
3340 		btrfs_abort_transaction(trans, ret);
3341 		return ret;
3342 	}
3343 	return ret;
3344 }
3345 
3346 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3347 {
3348 	struct btrfs_super_block *super_copy = fs_info->super_copy;
3349 	struct btrfs_disk_key *disk_key;
3350 	struct btrfs_chunk *chunk;
3351 	u8 *ptr;
3352 	int ret = 0;
3353 	u32 num_stripes;
3354 	u32 array_size;
3355 	u32 len = 0;
3356 	u32 cur;
3357 	struct btrfs_key key;
3358 
3359 	lockdep_assert_held(&fs_info->chunk_mutex);
3360 	array_size = btrfs_super_sys_array_size(super_copy);
3361 
3362 	ptr = super_copy->sys_chunk_array;
3363 	cur = 0;
3364 
3365 	while (cur < array_size) {
3366 		disk_key = (struct btrfs_disk_key *)ptr;
3367 		btrfs_disk_key_to_cpu(&key, disk_key);
3368 
3369 		len = sizeof(*disk_key);
3370 
3371 		if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3372 			chunk = (struct btrfs_chunk *)(ptr + len);
3373 			num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3374 			len += btrfs_chunk_item_size(num_stripes);
3375 		} else {
3376 			ret = -EIO;
3377 			break;
3378 		}
3379 		if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3380 		    key.offset == chunk_offset) {
3381 			memmove(ptr, ptr + len, array_size - (cur + len));
3382 			array_size -= len;
3383 			btrfs_set_super_sys_array_size(super_copy, array_size);
3384 		} else {
3385 			ptr += len;
3386 			cur += len;
3387 		}
3388 	}
3389 	return ret;
3390 }
3391 
3392 struct btrfs_chunk_map *btrfs_find_chunk_map_nolock(struct btrfs_fs_info *fs_info,
3393 						    u64 logical, u64 length)
3394 {
3395 	struct rb_node *node = fs_info->mapping_tree.rb_root.rb_node;
3396 	struct rb_node *prev = NULL;
3397 	struct rb_node *orig_prev;
3398 	struct btrfs_chunk_map *map;
3399 	struct btrfs_chunk_map *prev_map = NULL;
3400 
3401 	while (node) {
3402 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
3403 		prev = node;
3404 		prev_map = map;
3405 
3406 		if (logical < map->start) {
3407 			node = node->rb_left;
3408 		} else if (logical >= map->start + map->chunk_len) {
3409 			node = node->rb_right;
3410 		} else {
3411 			refcount_inc(&map->refs);
3412 			return map;
3413 		}
3414 	}
3415 
3416 	if (!prev)
3417 		return NULL;
3418 
3419 	orig_prev = prev;
3420 	while (prev && logical >= prev_map->start + prev_map->chunk_len) {
3421 		prev = rb_next(prev);
3422 		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3423 	}
3424 
3425 	if (!prev) {
3426 		prev = orig_prev;
3427 		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3428 		while (prev && logical < prev_map->start) {
3429 			prev = rb_prev(prev);
3430 			prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3431 		}
3432 	}
3433 
3434 	if (prev) {
3435 		u64 end = logical + length;
3436 
3437 		/*
3438 		 * Caller can pass a U64_MAX length when it wants to get any
3439 		 * chunk starting at an offset of 'logical' or higher, so deal
3440 		 * with underflow by resetting the end offset to U64_MAX.
3441 		 */
3442 		if (end < logical)
3443 			end = U64_MAX;
3444 
3445 		if (end > prev_map->start &&
3446 		    logical < prev_map->start + prev_map->chunk_len) {
3447 			refcount_inc(&prev_map->refs);
3448 			return prev_map;
3449 		}
3450 	}
3451 
3452 	return NULL;
3453 }
3454 
3455 struct btrfs_chunk_map *btrfs_find_chunk_map(struct btrfs_fs_info *fs_info,
3456 					     u64 logical, u64 length)
3457 {
3458 	struct btrfs_chunk_map *map;
3459 
3460 	read_lock(&fs_info->mapping_tree_lock);
3461 	map = btrfs_find_chunk_map_nolock(fs_info, logical, length);
3462 	read_unlock(&fs_info->mapping_tree_lock);
3463 
3464 	return map;
3465 }
3466 
3467 /*
3468  * Find the mapping containing the given logical extent.
3469  *
3470  * @logical: Logical block offset in bytes.
3471  * @length: Length of extent in bytes.
3472  *
3473  * Return: Chunk mapping or ERR_PTR.
3474  */
3475 struct btrfs_chunk_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3476 					    u64 logical, u64 length)
3477 {
3478 	struct btrfs_chunk_map *map;
3479 
3480 	map = btrfs_find_chunk_map(fs_info, logical, length);
3481 
3482 	if (unlikely(!map)) {
3483 		btrfs_crit(fs_info,
3484 			   "unable to find chunk map for logical %llu length %llu",
3485 			   logical, length);
3486 		return ERR_PTR(-EINVAL);
3487 	}
3488 
3489 	if (unlikely(map->start > logical || map->start + map->chunk_len <= logical)) {
3490 		btrfs_crit(fs_info,
3491 			   "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3492 			   logical, logical + length, map->start,
3493 			   map->start + map->chunk_len);
3494 		btrfs_free_chunk_map(map);
3495 		return ERR_PTR(-EINVAL);
3496 	}
3497 
3498 	/* Callers are responsible for dropping the reference. */
3499 	return map;
3500 }
3501 
3502 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3503 			     struct btrfs_chunk_map *map, u64 chunk_offset)
3504 {
3505 	int i;
3506 
3507 	/*
3508 	 * Removing chunk items and updating the device items in the chunks btree
3509 	 * requires holding the chunk_mutex.
3510 	 * See the comment at btrfs_chunk_alloc() for the details.
3511 	 */
3512 	lockdep_assert_held(&trans->fs_info->chunk_mutex);
3513 
3514 	for (i = 0; i < map->num_stripes; i++) {
3515 		int ret;
3516 
3517 		ret = btrfs_update_device(trans, map->stripes[i].dev);
3518 		if (ret)
3519 			return ret;
3520 	}
3521 
3522 	return btrfs_free_chunk(trans, chunk_offset);
3523 }
3524 
3525 int btrfs_remove_dev_extents(struct btrfs_trans_handle *trans, struct btrfs_chunk_map *map)
3526 {
3527 	struct btrfs_fs_info *fs_info = trans->fs_info;
3528 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3529 	u64 dev_extent_len = 0;
3530 	int i, ret = 0;
3531 
3532 	/*
3533 	 * First delete the device extent items from the devices btree.
3534 	 * We take the device_list_mutex to avoid racing with the finishing phase
3535 	 * of a device replace operation. See the comment below before acquiring
3536 	 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3537 	 * because that can result in a deadlock when deleting the device extent
3538 	 * items from the devices btree - COWing an extent buffer from the btree
3539 	 * may result in allocating a new metadata chunk, which would attempt to
3540 	 * lock again fs_info->chunk_mutex.
3541 	 */
3542 	mutex_lock(&fs_devices->device_list_mutex);
3543 	for (i = 0; i < map->num_stripes; i++) {
3544 		struct btrfs_device *device = map->stripes[i].dev;
3545 		ret = btrfs_free_dev_extent(trans, device,
3546 					    map->stripes[i].physical,
3547 					    &dev_extent_len);
3548 		if (unlikely(ret)) {
3549 			mutex_unlock(&fs_devices->device_list_mutex);
3550 			btrfs_abort_transaction(trans, ret);
3551 			return ret;
3552 		}
3553 
3554 		if (device->bytes_used > 0) {
3555 			mutex_lock(&fs_info->chunk_mutex);
3556 			btrfs_device_set_bytes_used(device,
3557 					device->bytes_used - dev_extent_len);
3558 			atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3559 			btrfs_clear_space_info_full(fs_info);
3560 
3561 			if (list_empty(&device->post_commit_list)) {
3562 				list_add_tail(&device->post_commit_list,
3563 					      &trans->transaction->dev_update_list);
3564 			}
3565 
3566 			mutex_unlock(&fs_info->chunk_mutex);
3567 		}
3568 	}
3569 	mutex_unlock(&fs_devices->device_list_mutex);
3570 
3571 	return 0;
3572 }
3573 
3574 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3575 {
3576 	struct btrfs_fs_info *fs_info = trans->fs_info;
3577 	struct btrfs_chunk_map *map;
3578 	int ret;
3579 
3580 	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3581 	if (IS_ERR(map)) {
3582 		DEBUG_WARN("errr %ld reading chunk map at offset %llu",
3583 			   PTR_ERR(map), chunk_offset);
3584 		return PTR_ERR(map);
3585 	}
3586 
3587 	ret = btrfs_remove_dev_extents(trans, map);
3588 	if (ret)
3589 		goto out;
3590 
3591 	/*
3592 	 * We acquire fs_info->chunk_mutex for 2 reasons:
3593 	 *
3594 	 * 1) Just like with the first phase of the chunk allocation, we must
3595 	 *    reserve system space, do all chunk btree updates and deletions, and
3596 	 *    update the system chunk array in the superblock while holding this
3597 	 *    mutex. This is for similar reasons as explained on the comment at
3598 	 *    the top of btrfs_chunk_alloc();
3599 	 *
3600 	 * 2) Prevent races with the final phase of a device replace operation
3601 	 *    that replaces the device object associated with the map's stripes,
3602 	 *    because the device object's id can change at any time during that
3603 	 *    final phase of the device replace operation
3604 	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3605 	 *    replaced device and then see it with an ID of
3606 	 *    BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3607 	 *    the device item, which does not exists on the chunk btree.
3608 	 *    The finishing phase of device replace acquires both the
3609 	 *    device_list_mutex and the chunk_mutex, in that order, so we are
3610 	 *    safe by just acquiring the chunk_mutex.
3611 	 */
3612 	trans->removing_chunk = true;
3613 	mutex_lock(&fs_info->chunk_mutex);
3614 
3615 	check_system_chunk(trans, map->type);
3616 
3617 	ret = remove_chunk_item(trans, map, chunk_offset);
3618 	/*
3619 	 * Normally we should not get -ENOSPC since we reserved space before
3620 	 * through the call to check_system_chunk().
3621 	 *
3622 	 * Despite our system space_info having enough free space, we may not
3623 	 * be able to allocate extents from its block groups, because all have
3624 	 * an incompatible profile, which will force us to allocate a new system
3625 	 * block group with the right profile, or right after we called
3626 	 * check_system_space() above, a scrub turned the only system block group
3627 	 * with enough free space into RO mode.
3628 	 * This is explained with more detail at do_chunk_alloc().
3629 	 *
3630 	 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3631 	 */
3632 	if (ret == -ENOSPC) {
3633 		const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3634 		struct btrfs_block_group *sys_bg;
3635 		struct btrfs_space_info *space_info;
3636 
3637 		space_info = btrfs_find_space_info(fs_info, sys_flags);
3638 		if (unlikely(!space_info)) {
3639 			ret = -EINVAL;
3640 			btrfs_abort_transaction(trans, ret);
3641 			goto out;
3642 		}
3643 
3644 		sys_bg = btrfs_create_chunk(trans, space_info, sys_flags);
3645 		if (IS_ERR(sys_bg)) {
3646 			ret = PTR_ERR(sys_bg);
3647 			btrfs_abort_transaction(trans, ret);
3648 			goto out;
3649 		}
3650 
3651 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3652 		if (unlikely(ret)) {
3653 			btrfs_abort_transaction(trans, ret);
3654 			goto out;
3655 		}
3656 
3657 		ret = remove_chunk_item(trans, map, chunk_offset);
3658 		if (unlikely(ret)) {
3659 			btrfs_abort_transaction(trans, ret);
3660 			goto out;
3661 		}
3662 	} else if (unlikely(ret)) {
3663 		btrfs_abort_transaction(trans, ret);
3664 		goto out;
3665 	}
3666 
3667 	trace_btrfs_chunk_free(fs_info, map, chunk_offset, map->chunk_len);
3668 
3669 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3670 		ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3671 		if (unlikely(ret)) {
3672 			btrfs_abort_transaction(trans, ret);
3673 			goto out;
3674 		}
3675 	}
3676 
3677 	btrfs_update_per_profile_avail(fs_info);
3678 	mutex_unlock(&fs_info->chunk_mutex);
3679 	trans->removing_chunk = false;
3680 
3681 	/*
3682 	 * We are done with chunk btree updates and deletions, so release the
3683 	 * system space we previously reserved (with check_system_chunk()).
3684 	 */
3685 	btrfs_trans_release_chunk_metadata(trans);
3686 
3687 	/* On error, btrfs_remove_block_group() aborts the transaction. */
3688 	ret = btrfs_remove_block_group(trans, map);
3689 	if (unlikely(ret))
3690 		ASSERT(BTRFS_FS_ERROR(fs_info) != 0);
3691 
3692 out:
3693 	if (trans->removing_chunk) {
3694 		mutex_unlock(&fs_info->chunk_mutex);
3695 		trans->removing_chunk = false;
3696 	}
3697 	/* once for us */
3698 	btrfs_free_chunk_map(map);
3699 	return ret;
3700 }
3701 
3702 static int btrfs_relocate_chunk_finish(struct btrfs_fs_info *fs_info,
3703 				       struct btrfs_block_group *bg)
3704 {
3705 	struct btrfs_root *root = fs_info->chunk_root;
3706 	struct btrfs_trans_handle *trans;
3707 	u64 length;
3708 	int ret;
3709 
3710 	btrfs_discard_cancel_work(&fs_info->discard_ctl, bg);
3711 	length = bg->length;
3712 	btrfs_put_block_group(bg);
3713 
3714 	/*
3715 	 * On a zoned file system, discard the whole block group, this will
3716 	 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3717 	 * resetting the zone fails, don't treat it as a fatal problem from the
3718 	 * filesystem's point of view.
3719 	 */
3720 	if (btrfs_is_zoned(fs_info)) {
3721 		ret = btrfs_discard_extent(fs_info, bg->start, length, NULL, true);
3722 		if (ret)
3723 			btrfs_info(fs_info, "failed to reset zone %llu after relocation",
3724 				   bg->start);
3725 	}
3726 
3727 	trans = btrfs_start_trans_remove_block_group(root->fs_info, bg->start);
3728 	if (IS_ERR(trans)) {
3729 		ret = PTR_ERR(trans);
3730 		btrfs_handle_fs_error(root->fs_info, ret, NULL);
3731 		return ret;
3732 	}
3733 
3734 	/* Step two, delete the device extents and the chunk tree entries. */
3735 	ret = btrfs_remove_chunk(trans, bg->start);
3736 	btrfs_end_transaction(trans);
3737 
3738 	return ret;
3739 }
3740 
3741 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool verbose)
3742 {
3743 	struct btrfs_block_group *block_group;
3744 	int ret;
3745 
3746 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3747 		btrfs_err(fs_info,
3748 			  "relocate: not supported on extent tree v2 yet");
3749 		return -EINVAL;
3750 	}
3751 
3752 	/*
3753 	 * Prevent races with automatic removal of unused block groups.
3754 	 * After we relocate and before we remove the chunk with offset
3755 	 * chunk_offset, automatic removal of the block group can kick in,
3756 	 * resulting in a failure when calling btrfs_remove_chunk() below.
3757 	 *
3758 	 * Make sure to acquire this mutex before doing a tree search (dev
3759 	 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3760 	 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3761 	 * we release the path used to search the chunk/dev tree and before
3762 	 * the current task acquires this mutex and calls us.
3763 	 */
3764 	lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3765 
3766 	/* step one, relocate all the extents inside this chunk */
3767 	btrfs_scrub_pause(fs_info);
3768 	ret = btrfs_relocate_block_group(fs_info, chunk_offset, verbose);
3769 	btrfs_scrub_continue(fs_info);
3770 	if (ret) {
3771 		/*
3772 		 * If we had a transaction abort, stop all running scrubs.
3773 		 * See transaction.c:cleanup_transaction() why we do it here.
3774 		 */
3775 		if (unlikely(BTRFS_FS_ERROR(fs_info)))
3776 			btrfs_scrub_cancel(fs_info);
3777 		return ret;
3778 	}
3779 
3780 	block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3781 	if (!block_group)
3782 		return -ENOENT;
3783 
3784 	if (should_relocate_using_remap_tree(block_group)) {
3785 		/* If we're relocating using the remap tree we're now done. */
3786 		btrfs_put_block_group(block_group);
3787 		ret = 0;
3788 	} else {
3789 		ret = btrfs_relocate_chunk_finish(fs_info, block_group);
3790 	}
3791 
3792 	return ret;
3793 }
3794 
3795 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3796 {
3797 	struct btrfs_root *chunk_root = fs_info->chunk_root;
3798 	BTRFS_PATH_AUTO_FREE(path);
3799 	struct extent_buffer *leaf;
3800 	struct btrfs_chunk *chunk;
3801 	struct btrfs_key key;
3802 	struct btrfs_key found_key;
3803 	u64 chunk_type;
3804 	bool retried = false;
3805 	int failed = 0;
3806 	int ret;
3807 
3808 	path = btrfs_alloc_path();
3809 	if (!path)
3810 		return -ENOMEM;
3811 
3812 again:
3813 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3814 	key.type = BTRFS_CHUNK_ITEM_KEY;
3815 	key.offset = (u64)-1;
3816 
3817 	while (1) {
3818 		mutex_lock(&fs_info->reclaim_bgs_lock);
3819 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3820 		if (ret < 0) {
3821 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3822 			return ret;
3823 		}
3824 		if (unlikely(ret == 0)) {
3825 			/*
3826 			 * On the first search we would find chunk tree with
3827 			 * offset -1, which is not possible. On subsequent
3828 			 * loops this would find an existing item on an invalid
3829 			 * offset (one less than the previous one, wrong
3830 			 * alignment and size).
3831 			 */
3832 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3833 			return -EUCLEAN;
3834 		}
3835 
3836 		ret = btrfs_previous_item(chunk_root, path, key.objectid,
3837 					  key.type);
3838 		if (ret)
3839 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3840 		if (ret < 0)
3841 			return ret;
3842 		if (ret > 0)
3843 			break;
3844 
3845 		leaf = path->nodes[0];
3846 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3847 
3848 		chunk = btrfs_item_ptr(leaf, path->slots[0],
3849 				       struct btrfs_chunk);
3850 		chunk_type = btrfs_chunk_type(leaf, chunk);
3851 		btrfs_release_path(path);
3852 
3853 		if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3854 			ret = btrfs_relocate_chunk(fs_info, found_key.offset,
3855 						   true);
3856 			if (ret == -ENOSPC)
3857 				failed++;
3858 			else
3859 				BUG_ON(ret);
3860 		}
3861 		mutex_unlock(&fs_info->reclaim_bgs_lock);
3862 
3863 		if (found_key.offset == 0)
3864 			break;
3865 		key.offset = found_key.offset - 1;
3866 	}
3867 	ret = 0;
3868 	if (failed && !retried) {
3869 		failed = 0;
3870 		retried = true;
3871 		goto again;
3872 	} else if (WARN_ON(failed && retried)) {
3873 		ret = -ENOSPC;
3874 	}
3875 	return ret;
3876 }
3877 
3878 /*
3879  * return 1 : allocate a data chunk successfully,
3880  * return <0: errors during allocating a data chunk,
3881  * return 0 : no need to allocate a data chunk.
3882  */
3883 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3884 				      u64 chunk_offset)
3885 {
3886 	struct btrfs_block_group *cache;
3887 	u64 bytes_used;
3888 	u64 chunk_type;
3889 
3890 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3891 	if (unlikely(!cache)) {
3892 		btrfs_err(fs_info, "balance: chunk at bytenr %llu has no corresponding block group",
3893 			  chunk_offset);
3894 		return -EUCLEAN;
3895 	}
3896 	chunk_type = cache->flags;
3897 	btrfs_put_block_group(cache);
3898 
3899 	if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3900 		return 0;
3901 
3902 	spin_lock(&fs_info->data_sinfo->lock);
3903 	bytes_used = fs_info->data_sinfo->bytes_used;
3904 	spin_unlock(&fs_info->data_sinfo->lock);
3905 
3906 	if (!bytes_used) {
3907 		struct btrfs_trans_handle *trans;
3908 		int ret;
3909 
3910 		trans =	btrfs_join_transaction(fs_info->tree_root);
3911 		if (IS_ERR(trans))
3912 			return PTR_ERR(trans);
3913 
3914 		ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3915 		btrfs_end_transaction(trans);
3916 		if (ret < 0)
3917 			return ret;
3918 		return 1;
3919 	}
3920 
3921 	return 0;
3922 }
3923 
3924 static void btrfs_disk_balance_args_to_cpu(struct btrfs_balance_args *cpu,
3925 					   const struct btrfs_disk_balance_args *disk)
3926 {
3927 	memset(cpu, 0, sizeof(*cpu));
3928 
3929 	cpu->profiles = le64_to_cpu(disk->profiles);
3930 	cpu->usage = le64_to_cpu(disk->usage);
3931 	cpu->devid = le64_to_cpu(disk->devid);
3932 	cpu->pstart = le64_to_cpu(disk->pstart);
3933 	cpu->pend = le64_to_cpu(disk->pend);
3934 	cpu->vstart = le64_to_cpu(disk->vstart);
3935 	cpu->vend = le64_to_cpu(disk->vend);
3936 	cpu->target = le64_to_cpu(disk->target);
3937 	cpu->flags = le64_to_cpu(disk->flags);
3938 	cpu->limit = le64_to_cpu(disk->limit);
3939 	cpu->stripes_min = le32_to_cpu(disk->stripes_min);
3940 	cpu->stripes_max = le32_to_cpu(disk->stripes_max);
3941 }
3942 
3943 static void btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args *disk,
3944 					   const struct btrfs_balance_args *cpu)
3945 {
3946 	memset(disk, 0, sizeof(*disk));
3947 
3948 	disk->profiles = cpu_to_le64(cpu->profiles);
3949 	disk->usage = cpu_to_le64(cpu->usage);
3950 	disk->devid = cpu_to_le64(cpu->devid);
3951 	disk->pstart = cpu_to_le64(cpu->pstart);
3952 	disk->pend = cpu_to_le64(cpu->pend);
3953 	disk->vstart = cpu_to_le64(cpu->vstart);
3954 	disk->vend = cpu_to_le64(cpu->vend);
3955 	disk->target = cpu_to_le64(cpu->target);
3956 	disk->flags = cpu_to_le64(cpu->flags);
3957 	disk->limit = cpu_to_le64(cpu->limit);
3958 	disk->stripes_min = cpu_to_le32(cpu->stripes_min);
3959 	disk->stripes_max = cpu_to_le32(cpu->stripes_max);
3960 }
3961 
3962 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3963 			       struct btrfs_balance_control *bctl)
3964 {
3965 	struct btrfs_root *root = fs_info->tree_root;
3966 	struct btrfs_trans_handle *trans;
3967 	struct btrfs_balance_item *item;
3968 	struct btrfs_disk_balance_args disk_bargs;
3969 	struct btrfs_path *path;
3970 	struct extent_buffer *leaf;
3971 	struct btrfs_key key;
3972 	int ret;
3973 
3974 	path = btrfs_alloc_path();
3975 	if (!path)
3976 		return -ENOMEM;
3977 
3978 	trans = btrfs_start_transaction(root, 0);
3979 	if (IS_ERR(trans)) {
3980 		btrfs_free_path(path);
3981 		return PTR_ERR(trans);
3982 	}
3983 
3984 	key.objectid = BTRFS_BALANCE_OBJECTID;
3985 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3986 	key.offset = 0;
3987 
3988 	ret = btrfs_insert_empty_item(trans, root, path, &key,
3989 				      sizeof(*item));
3990 	if (ret)
3991 		goto out;
3992 
3993 	leaf = path->nodes[0];
3994 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3995 
3996 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3997 
3998 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3999 	btrfs_set_balance_data(leaf, item, &disk_bargs);
4000 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
4001 	btrfs_set_balance_meta(leaf, item, &disk_bargs);
4002 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
4003 	btrfs_set_balance_sys(leaf, item, &disk_bargs);
4004 	btrfs_set_balance_flags(leaf, item, bctl->flags);
4005 out:
4006 	btrfs_free_path(path);
4007 	if (ret == 0)
4008 		ret = btrfs_commit_transaction(trans);
4009 	else
4010 		btrfs_end_transaction(trans);
4011 
4012 	return ret;
4013 }
4014 
4015 static int del_balance_item(struct btrfs_fs_info *fs_info)
4016 {
4017 	struct btrfs_root *root = fs_info->tree_root;
4018 	struct btrfs_trans_handle *trans;
4019 	struct btrfs_path *path;
4020 	struct btrfs_key key;
4021 	int ret;
4022 
4023 	path = btrfs_alloc_path();
4024 	if (!path)
4025 		return -ENOMEM;
4026 
4027 	trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
4028 	if (IS_ERR(trans)) {
4029 		btrfs_free_path(path);
4030 		return PTR_ERR(trans);
4031 	}
4032 
4033 	key.objectid = BTRFS_BALANCE_OBJECTID;
4034 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
4035 	key.offset = 0;
4036 
4037 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4038 	if (ret < 0)
4039 		goto out;
4040 	if (ret > 0) {
4041 		ret = -ENOENT;
4042 		goto out;
4043 	}
4044 
4045 	ret = btrfs_del_item(trans, root, path);
4046 out:
4047 	btrfs_free_path(path);
4048 	if (ret == 0)
4049 		ret = btrfs_commit_transaction(trans);
4050 	else
4051 		btrfs_end_transaction(trans);
4052 
4053 	return ret;
4054 }
4055 
4056 /*
4057  * This is a heuristic used to reduce the number of chunks balanced on
4058  * resume after balance was interrupted.
4059  */
4060 static void update_balance_args(struct btrfs_balance_control *bctl)
4061 {
4062 	/*
4063 	 * Turn on soft mode for chunk types that were being converted.
4064 	 */
4065 	if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
4066 		bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
4067 	if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
4068 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
4069 	if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
4070 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
4071 
4072 	/*
4073 	 * Turn on usage filter if is not already used.  The idea is
4074 	 * that chunks that we have already balanced should be
4075 	 * reasonably full.  Don't do it for chunks that are being
4076 	 * converted - that will keep us from relocating unconverted
4077 	 * (albeit full) chunks.
4078 	 */
4079 	if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
4080 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
4081 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
4082 		bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
4083 		bctl->data.usage = 90;
4084 	}
4085 	if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
4086 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
4087 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
4088 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
4089 		bctl->sys.usage = 90;
4090 	}
4091 	if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
4092 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
4093 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
4094 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
4095 		bctl->meta.usage = 90;
4096 	}
4097 }
4098 
4099 /*
4100  * Clear the balance status in fs_info and delete the balance item from disk.
4101  */
4102 static void reset_balance_state(struct btrfs_fs_info *fs_info)
4103 {
4104 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4105 	int ret;
4106 
4107 	ASSERT(fs_info->balance_ctl);
4108 
4109 	spin_lock(&fs_info->balance_lock);
4110 	fs_info->balance_ctl = NULL;
4111 	spin_unlock(&fs_info->balance_lock);
4112 
4113 	kfree(bctl);
4114 	ret = del_balance_item(fs_info);
4115 	if (ret)
4116 		btrfs_handle_fs_error(fs_info, ret, NULL);
4117 }
4118 
4119 /*
4120  * Balance filters.  Return 1 if chunk should be filtered out
4121  * (should not be balanced).
4122  */
4123 static bool chunk_profiles_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
4124 {
4125 	chunk_type = chunk_to_extended(chunk_type) &
4126 				BTRFS_EXTENDED_PROFILE_MASK;
4127 
4128 	if (bargs->profiles & chunk_type)
4129 		return false;
4130 
4131 	return true;
4132 }
4133 
4134 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
4135 				    struct btrfs_balance_args *bargs)
4136 {
4137 	struct btrfs_block_group *cache;
4138 	u64 chunk_used;
4139 	u64 user_thresh_min;
4140 	u64 user_thresh_max;
4141 	int ret = 1;
4142 
4143 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
4144 	if (unlikely(!cache)) {
4145 		btrfs_err(fs_info, "balance: chunk at bytenr %llu has no corresponding block group",
4146 			  chunk_offset);
4147 		return -EUCLEAN;
4148 	}
4149 	chunk_used = cache->used;
4150 
4151 	if (bargs->usage_min == 0)
4152 		user_thresh_min = 0;
4153 	else
4154 		user_thresh_min = mult_perc(cache->length, bargs->usage_min);
4155 
4156 	if (bargs->usage_max == 0)
4157 		user_thresh_max = 1;
4158 	else if (bargs->usage_max > 100)
4159 		user_thresh_max = cache->length;
4160 	else
4161 		user_thresh_max = mult_perc(cache->length, bargs->usage_max);
4162 
4163 	if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
4164 		ret = 0;
4165 
4166 	btrfs_put_block_group(cache);
4167 	return ret;
4168 }
4169 
4170 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
4171 			      struct btrfs_balance_args *bargs)
4172 {
4173 	struct btrfs_block_group *cache;
4174 	u64 chunk_used, user_thresh;
4175 	int ret = 1;
4176 
4177 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
4178 	if (unlikely(!cache)) {
4179 		btrfs_err(fs_info, "balance: chunk at bytenr %llu has no corresponding block group",
4180 			  chunk_offset);
4181 		return -EUCLEAN;
4182 	}
4183 	chunk_used = cache->used;
4184 
4185 	if (bargs->usage_min == 0)
4186 		user_thresh = 1;
4187 	else if (bargs->usage > 100)
4188 		user_thresh = cache->length;
4189 	else
4190 		user_thresh = mult_perc(cache->length, bargs->usage);
4191 
4192 	if (chunk_used < user_thresh)
4193 		ret = 0;
4194 
4195 	btrfs_put_block_group(cache);
4196 	return ret;
4197 }
4198 
4199 static bool chunk_devid_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4200 			       struct btrfs_balance_args *bargs)
4201 {
4202 	struct btrfs_stripe *stripe;
4203 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4204 	int i;
4205 
4206 	for (i = 0; i < num_stripes; i++) {
4207 		stripe = btrfs_stripe_nr(chunk, i);
4208 		if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
4209 			return false;
4210 	}
4211 
4212 	return true;
4213 }
4214 
4215 static u64 calc_data_stripes(u64 type, int num_stripes)
4216 {
4217 	const int index = btrfs_bg_flags_to_raid_index(type);
4218 	const int ncopies = btrfs_raid_array[index].ncopies;
4219 	const int nparity = btrfs_raid_array[index].nparity;
4220 
4221 	return (num_stripes - nparity) / ncopies;
4222 }
4223 
4224 /* [pstart, pend) */
4225 static bool chunk_drange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4226 				struct btrfs_balance_args *bargs)
4227 {
4228 	struct btrfs_stripe *stripe;
4229 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4230 	u64 stripe_offset;
4231 	u64 stripe_length;
4232 	u64 type;
4233 	int factor;
4234 	int i;
4235 
4236 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
4237 		return false;
4238 
4239 	type = btrfs_chunk_type(leaf, chunk);
4240 	factor = calc_data_stripes(type, num_stripes);
4241 
4242 	for (i = 0; i < num_stripes; i++) {
4243 		stripe = btrfs_stripe_nr(chunk, i);
4244 		if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
4245 			continue;
4246 
4247 		stripe_offset = btrfs_stripe_offset(leaf, stripe);
4248 		stripe_length = btrfs_chunk_length(leaf, chunk);
4249 		stripe_length = div_u64(stripe_length, factor);
4250 
4251 		if (stripe_offset < bargs->pend &&
4252 		    stripe_offset + stripe_length > bargs->pstart)
4253 			return false;
4254 	}
4255 
4256 	return true;
4257 }
4258 
4259 /* [vstart, vend) */
4260 static bool chunk_vrange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4261 				u64 chunk_offset, struct btrfs_balance_args *bargs)
4262 {
4263 	if (chunk_offset < bargs->vend &&
4264 	    chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
4265 		/* at least part of the chunk is inside this vrange */
4266 		return false;
4267 
4268 	return true;
4269 }
4270 
4271 static bool chunk_stripes_range_filter(struct extent_buffer *leaf,
4272 				       struct btrfs_chunk *chunk,
4273 				       struct btrfs_balance_args *bargs)
4274 {
4275 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4276 
4277 	if (bargs->stripes_min <= num_stripes
4278 			&& num_stripes <= bargs->stripes_max)
4279 		return false;
4280 
4281 	return true;
4282 }
4283 
4284 static bool chunk_soft_convert_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
4285 {
4286 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4287 		return false;
4288 
4289 	chunk_type = chunk_to_extended(chunk_type) &
4290 				BTRFS_EXTENDED_PROFILE_MASK;
4291 
4292 	if (bargs->target == chunk_type)
4293 		return true;
4294 
4295 	return false;
4296 }
4297 
4298 static int should_balance_chunk(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4299 				u64 chunk_offset)
4300 {
4301 	struct btrfs_fs_info *fs_info = leaf->fs_info;
4302 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4303 	struct btrfs_balance_args *bargs = NULL;
4304 	u64 chunk_type = btrfs_chunk_type(leaf, chunk);
4305 
4306 	/* Treat METADATA_REMAP chunks as METADATA. */
4307 	if (chunk_type & BTRFS_BLOCK_GROUP_METADATA_REMAP) {
4308 		chunk_type &= ~BTRFS_BLOCK_GROUP_METADATA_REMAP;
4309 		chunk_type |= BTRFS_BLOCK_GROUP_METADATA;
4310 	}
4311 
4312 	/* type filter */
4313 	if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
4314 	      (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
4315 		return false;
4316 	}
4317 
4318 	if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4319 		bargs = &bctl->data;
4320 	else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4321 		bargs = &bctl->sys;
4322 	else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4323 		bargs = &bctl->meta;
4324 
4325 	/* profiles filter */
4326 	if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
4327 	    chunk_profiles_filter(chunk_type, bargs)) {
4328 		return false;
4329 	}
4330 
4331 	/* usage filter */
4332 	if (bargs->flags & BTRFS_BALANCE_ARGS_USAGE) {
4333 		int ret2;
4334 
4335 		ret2 = chunk_usage_filter(fs_info, chunk_offset, bargs);
4336 		if (ret2 < 0)
4337 			return ret2;
4338 		if (ret2)
4339 			return false;
4340 	} else if (bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) {
4341 		int ret2;
4342 
4343 		ret2 = chunk_usage_range_filter(fs_info, chunk_offset, bargs);
4344 		if (ret2 < 0)
4345 			return ret2;
4346 		if (ret2)
4347 			return false;
4348 	}
4349 
4350 	/* devid filter */
4351 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
4352 	    chunk_devid_filter(leaf, chunk, bargs)) {
4353 		return false;
4354 	}
4355 
4356 	/* drange filter, makes sense only with devid filter */
4357 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
4358 	    chunk_drange_filter(leaf, chunk, bargs)) {
4359 		return false;
4360 	}
4361 
4362 	/* vrange filter */
4363 	if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
4364 	    chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
4365 		return false;
4366 	}
4367 
4368 	/* stripes filter */
4369 	if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
4370 	    chunk_stripes_range_filter(leaf, chunk, bargs)) {
4371 		return false;
4372 	}
4373 
4374 	/* soft profile changing mode */
4375 	if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
4376 	    chunk_soft_convert_filter(chunk_type, bargs)) {
4377 		return false;
4378 	}
4379 
4380 	/*
4381 	 * limited by count, must be the last filter
4382 	 */
4383 	if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
4384 		if (bargs->limit == 0)
4385 			return false;
4386 		else
4387 			bargs->limit--;
4388 	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
4389 		/*
4390 		 * Same logic as the 'limit' filter; the minimum cannot be
4391 		 * determined here because we do not have the global information
4392 		 * about the count of all chunks that satisfy the filters.
4393 		 */
4394 		if (bargs->limit_max == 0)
4395 			return false;
4396 		else
4397 			bargs->limit_max--;
4398 	}
4399 
4400 	return true;
4401 }
4402 
4403 struct remap_chunk_info {
4404 	struct list_head list;
4405 	u64 offset;
4406 	struct btrfs_block_group *bg;
4407 	bool made_ro;
4408 };
4409 
4410 static int cow_remap_tree(struct btrfs_trans_handle *trans, struct btrfs_path *path)
4411 {
4412 	struct btrfs_fs_info *fs_info = trans->fs_info;
4413 	struct btrfs_key key = { 0 };
4414 	int ret;
4415 
4416 	ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, 0, 1);
4417 	if (ret < 0)
4418 		return ret;
4419 
4420 	while (true) {
4421 		ret = btrfs_next_leaf(fs_info->remap_root, path);
4422 		if (ret < 0) {
4423 			return ret;
4424 		} else if (ret > 0) {
4425 			ret = 0;
4426 			break;
4427 		}
4428 
4429 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4430 
4431 		btrfs_release_path(path);
4432 
4433 		ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, 0, 1);
4434 		if (ret < 0)
4435 			break;
4436 	}
4437 
4438 	return ret;
4439 }
4440 
4441 static int balance_remap_chunks(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
4442 				struct list_head *chunks)
4443 {
4444 	struct remap_chunk_info *rci, *tmp;
4445 	struct btrfs_trans_handle *trans;
4446 	int ret;
4447 
4448 	list_for_each_entry_safe(rci, tmp, chunks, list) {
4449 		rci->bg = btrfs_lookup_block_group(fs_info, rci->offset);
4450 		if (!rci->bg) {
4451 			list_del(&rci->list);
4452 			kfree(rci);
4453 			continue;
4454 		}
4455 
4456 		ret = btrfs_inc_block_group_ro(rci->bg, false);
4457 		if (ret)
4458 			goto end;
4459 
4460 		rci->made_ro = true;
4461 	}
4462 
4463 	if (list_empty(chunks))
4464 		return 0;
4465 
4466 	trans = btrfs_start_transaction(fs_info->remap_root, 0);
4467 	if (IS_ERR(trans)) {
4468 		ret = PTR_ERR(trans);
4469 		goto end;
4470 	}
4471 
4472 	mutex_lock(&fs_info->remap_mutex);
4473 	ret = cow_remap_tree(trans, path);
4474 	mutex_unlock(&fs_info->remap_mutex);
4475 
4476 	btrfs_release_path(path);
4477 	btrfs_commit_transaction(trans);
4478 
4479 end:
4480 	while (!list_empty(chunks)) {
4481 		bool is_unused;
4482 		struct btrfs_block_group *bg;
4483 
4484 		rci = list_first_entry(chunks, struct remap_chunk_info, list);
4485 
4486 		bg = rci->bg;
4487 		if (bg) {
4488 			/*
4489 			 * This is a bit racy and the 'used' status can change
4490 			 * but this is not a problem as later functions will
4491 			 * verify it again.
4492 			 */
4493 			spin_lock(&bg->lock);
4494 			is_unused = !btrfs_is_block_group_used(bg);
4495 			spin_unlock(&bg->lock);
4496 
4497 			if (is_unused)
4498 				btrfs_mark_bg_unused(bg);
4499 
4500 			if (rci->made_ro)
4501 				btrfs_dec_block_group_ro(bg);
4502 
4503 			btrfs_put_block_group(bg);
4504 		}
4505 
4506 		list_del(&rci->list);
4507 		kfree(rci);
4508 	}
4509 
4510 	return ret;
4511 }
4512 
4513 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
4514 {
4515 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4516 	struct btrfs_root *chunk_root = fs_info->chunk_root;
4517 	u64 chunk_type;
4518 	struct btrfs_chunk *chunk;
4519 	BTRFS_PATH_AUTO_FREE(path);
4520 	struct btrfs_key key;
4521 	struct btrfs_key found_key;
4522 	struct extent_buffer *leaf;
4523 	int slot;
4524 	int ret;
4525 	int enospc_errors = 0;
4526 	bool counting = true;
4527 	/* The single value limit and min/max limits use the same bytes in the */
4528 	u64 limit_data = bctl->data.limit;
4529 	u64 limit_meta = bctl->meta.limit;
4530 	u64 limit_sys = bctl->sys.limit;
4531 	u32 count_data = 0;
4532 	u32 count_meta = 0;
4533 	u32 count_sys = 0;
4534 	bool chunk_reserved = false;
4535 	struct remap_chunk_info *rci;
4536 	unsigned int num_remap_chunks = 0;
4537 	LIST_HEAD(remap_chunks);
4538 
4539 	path = btrfs_alloc_path();
4540 	if (!path) {
4541 		ret = -ENOMEM;
4542 		goto error;
4543 	}
4544 
4545 	/* zero out stat counters */
4546 	spin_lock(&fs_info->balance_lock);
4547 	memset(&bctl->stat, 0, sizeof(bctl->stat));
4548 	spin_unlock(&fs_info->balance_lock);
4549 again:
4550 	if (!counting) {
4551 		/*
4552 		 * The single value limit and min/max limits use the same bytes
4553 		 * in the
4554 		 */
4555 		bctl->data.limit = limit_data;
4556 		bctl->meta.limit = limit_meta;
4557 		bctl->sys.limit = limit_sys;
4558 	}
4559 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4560 	key.type = BTRFS_CHUNK_ITEM_KEY;
4561 	key.offset = (u64)-1;
4562 
4563 	while (1) {
4564 		if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
4565 		    atomic_read(&fs_info->balance_cancel_req)) {
4566 			ret = -ECANCELED;
4567 			goto error;
4568 		}
4569 
4570 		mutex_lock(&fs_info->reclaim_bgs_lock);
4571 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
4572 		if (ret < 0) {
4573 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4574 			goto error;
4575 		}
4576 
4577 		/*
4578 		 * this shouldn't happen, it means the last relocate
4579 		 * failed
4580 		 */
4581 		if (unlikely(ret == 0)) {
4582 			btrfs_err(fs_info,
4583 				  "unexpected exact match of CHUNK_ITEM in chunk tree, offset 0x%llx",
4584 				  key.offset);
4585 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4586 			ret = -EUCLEAN;
4587 			goto error;
4588 		}
4589 
4590 		ret = btrfs_previous_item(chunk_root, path, 0,
4591 					  BTRFS_CHUNK_ITEM_KEY);
4592 		if (ret) {
4593 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4594 			ret = 0;
4595 			break;
4596 		}
4597 
4598 		leaf = path->nodes[0];
4599 		slot = path->slots[0];
4600 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4601 
4602 		if (found_key.objectid != key.objectid) {
4603 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4604 			break;
4605 		}
4606 
4607 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4608 		chunk_type = btrfs_chunk_type(leaf, chunk);
4609 
4610 		/* Check if chunk has already been fully relocated. */
4611 		if (chunk_type & BTRFS_BLOCK_GROUP_REMAPPED &&
4612 		    btrfs_chunk_num_stripes(leaf, chunk) == 0) {
4613 			btrfs_release_path(path);
4614 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4615 			goto loop;
4616 		}
4617 
4618 		if (!counting) {
4619 			spin_lock(&fs_info->balance_lock);
4620 			bctl->stat.considered++;
4621 			spin_unlock(&fs_info->balance_lock);
4622 		}
4623 
4624 		ret = should_balance_chunk(leaf, chunk, found_key.offset);
4625 
4626 		btrfs_release_path(path);
4627 		if (ret < 0) {
4628 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4629 			goto error;
4630 		}
4631 		if (!ret) {
4632 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4633 			goto loop;
4634 		}
4635 
4636 		if (counting) {
4637 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4638 			spin_lock(&fs_info->balance_lock);
4639 			bctl->stat.expected++;
4640 			spin_unlock(&fs_info->balance_lock);
4641 
4642 			if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4643 				count_data++;
4644 			else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4645 				count_sys++;
4646 			else if (chunk_type & (BTRFS_BLOCK_GROUP_METADATA |
4647 					       BTRFS_BLOCK_GROUP_METADATA_REMAP))
4648 				count_meta++;
4649 
4650 			goto loop;
4651 		}
4652 
4653 		/*
4654 		 * Apply limit_min filter, no need to check if the LIMITS
4655 		 * filter is used, limit_min is 0 by default
4656 		 */
4657 		if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4658 					count_data < bctl->data.limit_min)
4659 				|| ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4660 					count_meta < bctl->meta.limit_min)
4661 				|| ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4662 					count_sys < bctl->sys.limit_min)) {
4663 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4664 			goto loop;
4665 		}
4666 
4667 		/*
4668 		 * Balancing METADATA_REMAP chunks takes place separately - add
4669 		 * the details to a list so it can be processed later.
4670 		 */
4671 		if (chunk_type & BTRFS_BLOCK_GROUP_METADATA_REMAP) {
4672 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4673 
4674 			rci = kmalloc_obj(struct remap_chunk_info, GFP_NOFS);
4675 			if (!rci) {
4676 				ret = -ENOMEM;
4677 				goto error;
4678 			}
4679 
4680 			rci->offset = found_key.offset;
4681 			rci->bg = NULL;
4682 			rci->made_ro = false;
4683 			list_add_tail(&rci->list, &remap_chunks);
4684 
4685 			num_remap_chunks++;
4686 
4687 			goto loop;
4688 		}
4689 
4690 		if (!chunk_reserved) {
4691 			/*
4692 			 * We may be relocating the only data chunk we have,
4693 			 * which could potentially end up with losing data's
4694 			 * raid profile, so lets allocate an empty one in
4695 			 * advance.
4696 			 */
4697 			ret = btrfs_may_alloc_data_chunk(fs_info,
4698 							 found_key.offset);
4699 			if (ret < 0) {
4700 				mutex_unlock(&fs_info->reclaim_bgs_lock);
4701 				goto error;
4702 			} else if (ret == 1) {
4703 				chunk_reserved = true;
4704 			}
4705 		}
4706 
4707 		ret = btrfs_relocate_chunk(fs_info, found_key.offset, true);
4708 		mutex_unlock(&fs_info->reclaim_bgs_lock);
4709 		if (ret == -ENOSPC) {
4710 			enospc_errors++;
4711 		} else if (ret == -ETXTBSY) {
4712 			btrfs_warn(fs_info,
4713 	   "skipping relocation of block group %llu due to active swapfile",
4714 				   found_key.offset);
4715 			ret = 0;
4716 		} else if (ret) {
4717 			goto error;
4718 		} else {
4719 			spin_lock(&fs_info->balance_lock);
4720 			bctl->stat.completed++;
4721 			spin_unlock(&fs_info->balance_lock);
4722 		}
4723 loop:
4724 		if (found_key.offset == 0)
4725 			break;
4726 		key.offset = found_key.offset - 1;
4727 	}
4728 
4729 	btrfs_release_path(path);
4730 
4731 	if (counting) {
4732 		counting = false;
4733 		goto again;
4734 	}
4735 
4736 	if (!list_empty(&remap_chunks)) {
4737 		ret = balance_remap_chunks(fs_info, path, &remap_chunks);
4738 		if (ret == -ENOSPC)
4739 			enospc_errors++;
4740 
4741 		if (!ret) {
4742 			spin_lock(&fs_info->balance_lock);
4743 			bctl->stat.completed += num_remap_chunks;
4744 			spin_unlock(&fs_info->balance_lock);
4745 		}
4746 	}
4747 error:
4748 	if (enospc_errors) {
4749 		btrfs_info(fs_info, "%d enospc errors during balance",
4750 			   enospc_errors);
4751 		if (!ret)
4752 			ret = -ENOSPC;
4753 	}
4754 
4755 	return ret;
4756 }
4757 
4758 /*
4759  * See if a given profile is valid and reduced.
4760  *
4761  * @flags:     profile to validate
4762  * @extended:  if true @flags is treated as an extended profile
4763  */
4764 static int alloc_profile_is_valid(u64 flags, bool extended)
4765 {
4766 	u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4767 			       BTRFS_BLOCK_GROUP_PROFILE_MASK);
4768 
4769 	flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4770 
4771 	/* 1) check that all other bits are zeroed */
4772 	if (flags & ~mask)
4773 		return 0;
4774 
4775 	/* 2) see if profile is reduced */
4776 	if (flags == 0)
4777 		return !extended; /* "0" is valid for usual profiles */
4778 
4779 	return has_single_bit_set(flags);
4780 }
4781 
4782 /*
4783  * Validate target profile against allowed profiles and return true if it's OK.
4784  * Otherwise print the error message and return false.
4785  */
4786 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4787 		const struct btrfs_balance_args *bargs,
4788 		u64 allowed, const char *type)
4789 {
4790 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4791 		return true;
4792 
4793 	/* Profile is valid and does not have bits outside of the allowed set */
4794 	if (alloc_profile_is_valid(bargs->target, 1) &&
4795 	    (bargs->target & ~allowed) == 0)
4796 		return true;
4797 
4798 	btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4799 			type, btrfs_bg_type_to_raid_name(bargs->target));
4800 	return false;
4801 }
4802 
4803 /*
4804  * Fill @buf with textual description of balance filter flags @bargs, up to
4805  * @size_buf including the terminating null. The output may be trimmed if it
4806  * does not fit into the provided buffer.
4807  */
4808 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4809 				 u32 size_buf)
4810 {
4811 	int ret;
4812 	u32 size_bp = size_buf;
4813 	char *bp = buf;
4814 	u64 flags = bargs->flags;
4815 	char tmp_buf[128] = {'\0'};
4816 
4817 	if (!flags)
4818 		return;
4819 
4820 #define CHECK_APPEND_NOARG(a)						\
4821 	do {								\
4822 		ret = snprintf(bp, size_bp, (a));			\
4823 		if (ret < 0 || ret >= size_bp)				\
4824 			goto out_overflow;				\
4825 		size_bp -= ret;						\
4826 		bp += ret;						\
4827 	} while (0)
4828 
4829 #define CHECK_APPEND_1ARG(a, v1)					\
4830 	do {								\
4831 		ret = snprintf(bp, size_bp, (a), (v1));			\
4832 		if (ret < 0 || ret >= size_bp)				\
4833 			goto out_overflow;				\
4834 		size_bp -= ret;						\
4835 		bp += ret;						\
4836 	} while (0)
4837 
4838 #define CHECK_APPEND_2ARG(a, v1, v2)					\
4839 	do {								\
4840 		ret = snprintf(bp, size_bp, (a), (v1), (v2));		\
4841 		if (ret < 0 || ret >= size_bp)				\
4842 			goto out_overflow;				\
4843 		size_bp -= ret;						\
4844 		bp += ret;						\
4845 	} while (0)
4846 
4847 	if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4848 		CHECK_APPEND_1ARG("convert=%s,",
4849 				  btrfs_bg_type_to_raid_name(bargs->target));
4850 
4851 	if (flags & BTRFS_BALANCE_ARGS_SOFT)
4852 		CHECK_APPEND_NOARG("soft,");
4853 
4854 	if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4855 		btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4856 					    sizeof(tmp_buf));
4857 		CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4858 	}
4859 
4860 	if (flags & BTRFS_BALANCE_ARGS_USAGE)
4861 		CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4862 
4863 	if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4864 		CHECK_APPEND_2ARG("usage=%u..%u,",
4865 				  bargs->usage_min, bargs->usage_max);
4866 
4867 	if (flags & BTRFS_BALANCE_ARGS_DEVID)
4868 		CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4869 
4870 	if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4871 		CHECK_APPEND_2ARG("drange=%llu..%llu,",
4872 				  bargs->pstart, bargs->pend);
4873 
4874 	if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4875 		CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4876 				  bargs->vstart, bargs->vend);
4877 
4878 	if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4879 		CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4880 
4881 	if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4882 		CHECK_APPEND_2ARG("limit=%u..%u,",
4883 				bargs->limit_min, bargs->limit_max);
4884 
4885 	if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4886 		CHECK_APPEND_2ARG("stripes=%u..%u,",
4887 				  bargs->stripes_min, bargs->stripes_max);
4888 
4889 #undef CHECK_APPEND_2ARG
4890 #undef CHECK_APPEND_1ARG
4891 #undef CHECK_APPEND_NOARG
4892 
4893 out_overflow:
4894 
4895 	if (size_bp < size_buf)
4896 		buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4897 	else
4898 		buf[0] = '\0';
4899 }
4900 
4901 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4902 {
4903 	u32 size_buf = 1024;
4904 	char tmp_buf[192] = {'\0'};
4905 	char AUTO_KFREE(buf);
4906 	char *bp;
4907 	u32 size_bp = size_buf;
4908 	int ret;
4909 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4910 
4911 	buf = kzalloc(size_buf, GFP_KERNEL);
4912 	if (!buf)
4913 		return;
4914 
4915 	bp = buf;
4916 
4917 #define CHECK_APPEND_1ARG(a, v1)					\
4918 	do {								\
4919 		ret = snprintf(bp, size_bp, (a), (v1));			\
4920 		if (ret < 0 || ret >= size_bp)				\
4921 			goto out_overflow;				\
4922 		size_bp -= ret;						\
4923 		bp += ret;						\
4924 	} while (0)
4925 
4926 	if (bctl->flags & BTRFS_BALANCE_FORCE)
4927 		CHECK_APPEND_1ARG("%s", "-f ");
4928 
4929 	if (bctl->flags & BTRFS_BALANCE_DATA) {
4930 		describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4931 		CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4932 	}
4933 
4934 	if (bctl->flags & BTRFS_BALANCE_METADATA) {
4935 		describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4936 		CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4937 	}
4938 
4939 	if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4940 		describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4941 		CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4942 	}
4943 
4944 #undef CHECK_APPEND_1ARG
4945 
4946 out_overflow:
4947 
4948 	if (size_bp < size_buf)
4949 		buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4950 	btrfs_info(fs_info, "balance: %s %s",
4951 		   (bctl->flags & BTRFS_BALANCE_RESUME) ?
4952 		   "resume" : "start", buf);
4953 }
4954 
4955 /*
4956  * Should be called with balance mutex held
4957  */
4958 int btrfs_balance(struct btrfs_fs_info *fs_info,
4959 		  struct btrfs_balance_control *bctl,
4960 		  struct btrfs_ioctl_balance_args *bargs)
4961 {
4962 	u64 meta_target, data_target;
4963 	u64 allowed;
4964 	bool mixed = false;
4965 	int ret;
4966 	u64 num_devices;
4967 	unsigned seq;
4968 	bool reducing_redundancy;
4969 	bool paused = false;
4970 	int i;
4971 
4972 	if (btrfs_fs_closing(fs_info) ||
4973 	    atomic_read(&fs_info->balance_pause_req) ||
4974 	    btrfs_should_cancel_balance(fs_info)) {
4975 		ret = -EINVAL;
4976 		goto out;
4977 	}
4978 
4979 	allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4980 	if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4981 		mixed = true;
4982 
4983 	/*
4984 	 * In case of mixed groups both data and meta should be picked,
4985 	 * and identical options should be given for both of them.
4986 	 */
4987 	allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4988 	if (mixed && (bctl->flags & allowed)) {
4989 		if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4990 		    !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4991 		    memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4992 			btrfs_err(fs_info,
4993 	  "balance: mixed groups data and metadata options must be the same");
4994 			ret = -EINVAL;
4995 			goto out;
4996 		}
4997 	}
4998 
4999 	/*
5000 	 * rw_devices will not change at the moment, device add/delete/replace
5001 	 * are exclusive
5002 	 */
5003 	num_devices = fs_info->fs_devices->rw_devices;
5004 
5005 	/*
5006 	 * SINGLE profile on-disk has no profile bit, but in-memory we have a
5007 	 * special bit for it, to make it easier to distinguish.  Thus we need
5008 	 * to set it manually, or balance would refuse the profile.
5009 	 */
5010 	allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
5011 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
5012 		if (num_devices >= btrfs_raid_array[i].devs_min)
5013 			allowed |= btrfs_raid_array[i].bg_flag;
5014 
5015 	if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
5016 	    !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
5017 	    !validate_convert_profile(fs_info, &bctl->sys,  allowed, "system")) {
5018 		ret = -EINVAL;
5019 		goto out;
5020 	}
5021 
5022 	/*
5023 	 * Allow to reduce metadata or system integrity only if force set for
5024 	 * profiles with redundancy (copies, parity)
5025 	 */
5026 	allowed = 0;
5027 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
5028 		if (btrfs_raid_array[i].ncopies >= 2 ||
5029 		    btrfs_raid_array[i].tolerated_failures >= 1)
5030 			allowed |= btrfs_raid_array[i].bg_flag;
5031 	}
5032 	do {
5033 		seq = read_seqbegin(&fs_info->profiles_lock);
5034 
5035 		if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
5036 		     (fs_info->avail_system_alloc_bits & allowed) &&
5037 		     !(bctl->sys.target & allowed)) ||
5038 		    ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
5039 		     (fs_info->avail_metadata_alloc_bits & allowed) &&
5040 		     !(bctl->meta.target & allowed)))
5041 			reducing_redundancy = true;
5042 		else
5043 			reducing_redundancy = false;
5044 
5045 		/* if we're not converting, the target field is uninitialized */
5046 		meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
5047 			bctl->meta.target : fs_info->avail_metadata_alloc_bits;
5048 		data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
5049 			bctl->data.target : fs_info->avail_data_alloc_bits;
5050 	} while (read_seqretry(&fs_info->profiles_lock, seq));
5051 
5052 	if (reducing_redundancy) {
5053 		if (bctl->flags & BTRFS_BALANCE_FORCE) {
5054 			btrfs_info(fs_info,
5055 			   "balance: force reducing metadata redundancy");
5056 		} else {
5057 			btrfs_err(fs_info,
5058 	"balance: reduces metadata redundancy, use --force if you want this");
5059 			ret = -EINVAL;
5060 			goto out;
5061 		}
5062 	}
5063 
5064 	if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
5065 		btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
5066 		btrfs_warn(fs_info,
5067 	"balance: metadata profile %s has lower redundancy than data profile %s",
5068 				btrfs_bg_type_to_raid_name(meta_target),
5069 				btrfs_bg_type_to_raid_name(data_target));
5070 	}
5071 
5072 	ret = insert_balance_item(fs_info, bctl);
5073 	if (ret && ret != -EEXIST)
5074 		goto out;
5075 
5076 	if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
5077 		BUG_ON(ret == -EEXIST);
5078 		BUG_ON(fs_info->balance_ctl);
5079 		spin_lock(&fs_info->balance_lock);
5080 		fs_info->balance_ctl = bctl;
5081 		spin_unlock(&fs_info->balance_lock);
5082 	} else {
5083 		BUG_ON(ret != -EEXIST);
5084 		spin_lock(&fs_info->balance_lock);
5085 		update_balance_args(bctl);
5086 		spin_unlock(&fs_info->balance_lock);
5087 	}
5088 
5089 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5090 	set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
5091 	describe_balance_start_or_resume(fs_info);
5092 	mutex_unlock(&fs_info->balance_mutex);
5093 
5094 	ret = __btrfs_balance(fs_info);
5095 
5096 	mutex_lock(&fs_info->balance_mutex);
5097 	if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
5098 		btrfs_info(fs_info, "balance: paused");
5099 		btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
5100 		paused = true;
5101 	}
5102 	/*
5103 	 * Balance can be canceled by:
5104 	 *
5105 	 * - Regular cancel request
5106 	 *   Then ret == -ECANCELED and balance_cancel_req > 0
5107 	 *
5108 	 * - Fatal signal to "btrfs" process
5109 	 *   Either the signal caught by wait_reserve_ticket() and callers
5110 	 *   got -EINTR, or caught by btrfs_should_cancel_balance() and
5111 	 *   got -ECANCELED.
5112 	 *   Either way, in this case balance_cancel_req = 0, and
5113 	 *   ret == -EINTR or ret == -ECANCELED.
5114 	 *
5115 	 * So here we only check the return value to catch canceled balance.
5116 	 */
5117 	else if (ret == -ECANCELED || ret == -EINTR)
5118 		btrfs_info(fs_info, "balance: canceled");
5119 	else
5120 		btrfs_info(fs_info, "balance: ended with status: %d", ret);
5121 
5122 	clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
5123 
5124 	if (bargs) {
5125 		memset(bargs, 0, sizeof(*bargs));
5126 		btrfs_update_ioctl_balance_args(fs_info, bargs);
5127 	}
5128 
5129 	/* We didn't pause, we can clean everything up. */
5130 	if (!paused) {
5131 		reset_balance_state(fs_info);
5132 		btrfs_exclop_finish(fs_info);
5133 	}
5134 
5135 	wake_up(&fs_info->balance_wait_q);
5136 
5137 	return ret;
5138 out:
5139 	if (bctl->flags & BTRFS_BALANCE_RESUME)
5140 		reset_balance_state(fs_info);
5141 	else
5142 		kfree(bctl);
5143 	btrfs_exclop_finish(fs_info);
5144 
5145 	return ret;
5146 }
5147 
5148 static int balance_kthread(void *data)
5149 {
5150 	struct btrfs_fs_info *fs_info = data;
5151 	int ret = 0;
5152 
5153 	guard(super_write)(fs_info->sb);
5154 
5155 	mutex_lock(&fs_info->balance_mutex);
5156 	if (fs_info->balance_ctl)
5157 		ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
5158 	mutex_unlock(&fs_info->balance_mutex);
5159 
5160 	return ret;
5161 }
5162 
5163 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
5164 {
5165 	struct task_struct *tsk;
5166 
5167 	mutex_lock(&fs_info->balance_mutex);
5168 	if (!fs_info->balance_ctl) {
5169 		mutex_unlock(&fs_info->balance_mutex);
5170 		return 0;
5171 	}
5172 	mutex_unlock(&fs_info->balance_mutex);
5173 
5174 	if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
5175 		btrfs_info(fs_info, "balance: resume skipped");
5176 		return 0;
5177 	}
5178 
5179 	spin_lock(&fs_info->super_lock);
5180 	ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED,
5181 	       "exclusive_operation=%d", fs_info->exclusive_operation);
5182 	fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
5183 	spin_unlock(&fs_info->super_lock);
5184 	/*
5185 	 * A ro->rw remount sequence should continue with the paused balance
5186 	 * regardless of who pauses it, system or the user as of now, so set
5187 	 * the resume flag.
5188 	 */
5189 	spin_lock(&fs_info->balance_lock);
5190 	fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
5191 	spin_unlock(&fs_info->balance_lock);
5192 
5193 	tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
5194 	return PTR_ERR_OR_ZERO(tsk);
5195 }
5196 
5197 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
5198 {
5199 	struct btrfs_balance_control *bctl;
5200 	struct btrfs_balance_item *item;
5201 	struct btrfs_disk_balance_args disk_bargs;
5202 	BTRFS_PATH_AUTO_FREE(path);
5203 	struct extent_buffer *leaf;
5204 	struct btrfs_key key;
5205 	int ret;
5206 
5207 	path = btrfs_alloc_path();
5208 	if (!path)
5209 		return -ENOMEM;
5210 
5211 	key.objectid = BTRFS_BALANCE_OBJECTID;
5212 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
5213 	key.offset = 0;
5214 
5215 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5216 	if (ret < 0)
5217 		return ret;
5218 	if (ret > 0) { /* ret = -ENOENT; */
5219 		return 0;
5220 	}
5221 
5222 	bctl = kzalloc_obj(*bctl, GFP_NOFS);
5223 	if (!bctl)
5224 		return -ENOMEM;
5225 
5226 	leaf = path->nodes[0];
5227 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
5228 
5229 	bctl->flags = btrfs_balance_flags(leaf, item);
5230 	bctl->flags |= BTRFS_BALANCE_RESUME;
5231 
5232 	btrfs_balance_data(leaf, item, &disk_bargs);
5233 	btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
5234 	btrfs_balance_meta(leaf, item, &disk_bargs);
5235 	btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
5236 	btrfs_balance_sys(leaf, item, &disk_bargs);
5237 	btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
5238 
5239 	/*
5240 	 * This should never happen, as the paused balance state is recovered
5241 	 * during mount without any chance of other exclusive ops to collide.
5242 	 *
5243 	 * This gives the exclusive op status to balance and keeps in paused
5244 	 * state until user intervention (cancel or umount). If the ownership
5245 	 * cannot be assigned, show a message but do not fail. The balance
5246 	 * is in a paused state and must have fs_info::balance_ctl properly
5247 	 * set up.
5248 	 */
5249 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
5250 		btrfs_warn(fs_info,
5251 	"balance: cannot set exclusive op status, resume manually");
5252 
5253 	btrfs_release_path(path);
5254 
5255 	mutex_lock(&fs_info->balance_mutex);
5256 	BUG_ON(fs_info->balance_ctl);
5257 	spin_lock(&fs_info->balance_lock);
5258 	fs_info->balance_ctl = bctl;
5259 	spin_unlock(&fs_info->balance_lock);
5260 	mutex_unlock(&fs_info->balance_mutex);
5261 	return ret;
5262 }
5263 
5264 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
5265 {
5266 	int ret = 0;
5267 
5268 	mutex_lock(&fs_info->balance_mutex);
5269 	if (!fs_info->balance_ctl) {
5270 		mutex_unlock(&fs_info->balance_mutex);
5271 		return -ENOTCONN;
5272 	}
5273 
5274 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5275 		atomic_inc(&fs_info->balance_pause_req);
5276 		mutex_unlock(&fs_info->balance_mutex);
5277 
5278 		wait_event(fs_info->balance_wait_q,
5279 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5280 
5281 		mutex_lock(&fs_info->balance_mutex);
5282 		/* we are good with balance_ctl ripped off from under us */
5283 		BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5284 		atomic_dec(&fs_info->balance_pause_req);
5285 	} else {
5286 		ret = -ENOTCONN;
5287 	}
5288 
5289 	mutex_unlock(&fs_info->balance_mutex);
5290 	return ret;
5291 }
5292 
5293 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
5294 {
5295 	mutex_lock(&fs_info->balance_mutex);
5296 	if (!fs_info->balance_ctl) {
5297 		mutex_unlock(&fs_info->balance_mutex);
5298 		return -ENOTCONN;
5299 	}
5300 
5301 	/*
5302 	 * A paused balance with the item stored on disk can be resumed at
5303 	 * mount time if the mount is read-write. Otherwise it's still paused
5304 	 * and we must not allow cancelling as it deletes the item.
5305 	 */
5306 	if (sb_rdonly(fs_info->sb)) {
5307 		mutex_unlock(&fs_info->balance_mutex);
5308 		return -EROFS;
5309 	}
5310 
5311 	atomic_inc(&fs_info->balance_cancel_req);
5312 	/*
5313 	 * if we are running just wait and return, balance item is
5314 	 * deleted in btrfs_balance in this case
5315 	 */
5316 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5317 		mutex_unlock(&fs_info->balance_mutex);
5318 		wait_event(fs_info->balance_wait_q,
5319 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5320 		mutex_lock(&fs_info->balance_mutex);
5321 	} else {
5322 		mutex_unlock(&fs_info->balance_mutex);
5323 		/*
5324 		 * Lock released to allow other waiters to continue, we'll
5325 		 * reexamine the status again.
5326 		 */
5327 		mutex_lock(&fs_info->balance_mutex);
5328 
5329 		if (fs_info->balance_ctl) {
5330 			reset_balance_state(fs_info);
5331 			btrfs_exclop_finish(fs_info);
5332 			btrfs_info(fs_info, "balance: canceled");
5333 		}
5334 	}
5335 
5336 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5337 	atomic_dec(&fs_info->balance_cancel_req);
5338 	mutex_unlock(&fs_info->balance_mutex);
5339 	return 0;
5340 }
5341 
5342 /*
5343  * shrinking a device means finding all of the device extents past
5344  * the new size, and then following the back refs to the chunks.
5345  * The chunk relocation code actually frees the device extent
5346  */
5347 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
5348 {
5349 	struct btrfs_fs_info *fs_info = device->fs_info;
5350 	struct btrfs_root *root = fs_info->dev_root;
5351 	struct btrfs_trans_handle *trans;
5352 	struct btrfs_dev_extent *dev_extent = NULL;
5353 	struct btrfs_path *path;
5354 	u64 length;
5355 	u64 chunk_offset;
5356 	int ret;
5357 	int slot;
5358 	int failed = 0;
5359 	bool retried = false;
5360 	struct extent_buffer *l;
5361 	struct btrfs_key key;
5362 	struct btrfs_super_block *super_copy = fs_info->super_copy;
5363 	u64 old_total = btrfs_super_total_bytes(super_copy);
5364 	u64 old_size = btrfs_device_get_total_bytes(device);
5365 	u64 diff;
5366 	u64 start;
5367 	u64 free_diff = 0;
5368 	u64 pending_start, pending_end;
5369 
5370 	new_size = round_down(new_size, fs_info->sectorsize);
5371 	start = new_size;
5372 	diff = round_down(old_size - new_size, fs_info->sectorsize);
5373 
5374 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5375 		return -EINVAL;
5376 
5377 	path = btrfs_alloc_path();
5378 	if (!path)
5379 		return -ENOMEM;
5380 
5381 	path->reada = READA_BACK;
5382 
5383 	trans = btrfs_start_transaction(root, 0);
5384 	if (IS_ERR(trans)) {
5385 		btrfs_free_path(path);
5386 		return PTR_ERR(trans);
5387 	}
5388 
5389 	mutex_lock(&fs_info->chunk_mutex);
5390 
5391 	btrfs_device_set_total_bytes(device, new_size);
5392 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5393 		device->fs_devices->total_rw_bytes -= diff;
5394 
5395 		/*
5396 		 * The new free_chunk_space is new_size - used, so we have to
5397 		 * subtract the delta of the old free_chunk_space which included
5398 		 * old_size - used.  If used > new_size then just subtract this
5399 		 * entire device's free space.
5400 		 */
5401 		if (device->bytes_used < new_size)
5402 			free_diff = (old_size - device->bytes_used) -
5403 				    (new_size - device->bytes_used);
5404 		else
5405 			free_diff = old_size - device->bytes_used;
5406 		atomic64_sub(free_diff, &fs_info->free_chunk_space);
5407 	}
5408 
5409 	btrfs_update_per_profile_avail(fs_info);
5410 	/*
5411 	 * Once the device's size has been set to the new size, ensure all
5412 	 * in-memory chunks are synced to disk so that the loop below sees them
5413 	 * and relocates them accordingly.
5414 	 */
5415 	if (btrfs_first_pending_extent(device, start, diff, &pending_start, &pending_end)) {
5416 		mutex_unlock(&fs_info->chunk_mutex);
5417 		ret = btrfs_commit_transaction(trans);
5418 		if (ret)
5419 			goto done;
5420 	} else {
5421 		mutex_unlock(&fs_info->chunk_mutex);
5422 		btrfs_end_transaction(trans);
5423 	}
5424 
5425 again:
5426 	key.objectid = device->devid;
5427 	key.type = BTRFS_DEV_EXTENT_KEY;
5428 	key.offset = (u64)-1;
5429 
5430 	do {
5431 		mutex_lock(&fs_info->reclaim_bgs_lock);
5432 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5433 		if (ret < 0) {
5434 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5435 			goto done;
5436 		}
5437 
5438 		ret = btrfs_previous_item(root, path, 0, key.type);
5439 		if (ret) {
5440 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5441 			if (ret < 0)
5442 				goto done;
5443 			ret = 0;
5444 			btrfs_release_path(path);
5445 			break;
5446 		}
5447 
5448 		l = path->nodes[0];
5449 		slot = path->slots[0];
5450 		btrfs_item_key_to_cpu(l, &key, path->slots[0]);
5451 
5452 		if (key.objectid != device->devid) {
5453 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5454 			btrfs_release_path(path);
5455 			break;
5456 		}
5457 
5458 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
5459 		length = btrfs_dev_extent_length(l, dev_extent);
5460 
5461 		if (key.offset + length <= new_size) {
5462 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5463 			btrfs_release_path(path);
5464 			break;
5465 		}
5466 
5467 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
5468 		btrfs_release_path(path);
5469 
5470 		/*
5471 		 * We may be relocating the only data chunk we have,
5472 		 * which could potentially end up with losing data's
5473 		 * raid profile, so lets allocate an empty one in
5474 		 * advance.
5475 		 */
5476 		ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
5477 		if (ret < 0) {
5478 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5479 			goto done;
5480 		}
5481 
5482 		ret = btrfs_relocate_chunk(fs_info, chunk_offset, true);
5483 		mutex_unlock(&fs_info->reclaim_bgs_lock);
5484 		if (ret == -ENOSPC) {
5485 			failed++;
5486 		} else if (ret) {
5487 			if (ret == -ETXTBSY) {
5488 				btrfs_warn(fs_info,
5489 		   "could not shrink block group %llu due to active swapfile",
5490 					   chunk_offset);
5491 			}
5492 			goto done;
5493 		}
5494 	} while (key.offset-- > 0);
5495 
5496 	if (failed && !retried) {
5497 		failed = 0;
5498 		retried = true;
5499 		goto again;
5500 	} else if (failed && retried) {
5501 		ret = -ENOSPC;
5502 		goto done;
5503 	}
5504 
5505 	/* Shrinking succeeded, else we would be at "done". */
5506 	trans = btrfs_start_transaction(root, 0);
5507 	if (IS_ERR(trans)) {
5508 		ret = PTR_ERR(trans);
5509 		goto done;
5510 	}
5511 
5512 	mutex_lock(&fs_info->chunk_mutex);
5513 	/* Clear all state bits beyond the shrunk device size */
5514 	btrfs_clear_extent_bit(&device->alloc_state, new_size, (u64)-1,
5515 			       CHUNK_STATE_MASK, NULL);
5516 
5517 	btrfs_device_set_disk_total_bytes(device, new_size);
5518 	if (list_empty(&device->post_commit_list))
5519 		list_add_tail(&device->post_commit_list,
5520 			      &trans->transaction->dev_update_list);
5521 
5522 	WARN_ON(diff > old_total);
5523 	btrfs_set_super_total_bytes(super_copy,
5524 			round_down(old_total - diff, fs_info->sectorsize));
5525 	btrfs_update_per_profile_avail(fs_info);
5526 	mutex_unlock(&fs_info->chunk_mutex);
5527 
5528 	btrfs_reserve_chunk_metadata(trans, false);
5529 	/* Now btrfs_update_device() will change the on-disk size. */
5530 	ret = btrfs_update_device(trans, device);
5531 	btrfs_trans_release_chunk_metadata(trans);
5532 	if (unlikely(ret < 0)) {
5533 		btrfs_abort_transaction(trans, ret);
5534 		btrfs_end_transaction(trans);
5535 	} else {
5536 		ret = btrfs_commit_transaction(trans);
5537 	}
5538 done:
5539 	btrfs_free_path(path);
5540 	if (ret) {
5541 		mutex_lock(&fs_info->chunk_mutex);
5542 		btrfs_device_set_total_bytes(device, old_size);
5543 		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5544 			device->fs_devices->total_rw_bytes += diff;
5545 			atomic64_add(free_diff, &fs_info->free_chunk_space);
5546 		}
5547 		mutex_unlock(&fs_info->chunk_mutex);
5548 	}
5549 	return ret;
5550 }
5551 
5552 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5553 			   struct btrfs_key *key,
5554 			   struct btrfs_chunk *chunk, int item_size)
5555 {
5556 	struct btrfs_super_block *super_copy = fs_info->super_copy;
5557 	struct btrfs_disk_key disk_key;
5558 	u32 array_size;
5559 	u8 *ptr;
5560 
5561 	lockdep_assert_held(&fs_info->chunk_mutex);
5562 
5563 	array_size = btrfs_super_sys_array_size(super_copy);
5564 	if (array_size + item_size + sizeof(disk_key)
5565 			> BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5566 		return -EFBIG;
5567 
5568 	ptr = super_copy->sys_chunk_array + array_size;
5569 	btrfs_cpu_key_to_disk(&disk_key, key);
5570 	memcpy(ptr, &disk_key, sizeof(disk_key));
5571 	ptr += sizeof(disk_key);
5572 	memcpy(ptr, chunk, item_size);
5573 	item_size += sizeof(disk_key);
5574 	btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5575 
5576 	return 0;
5577 }
5578 
5579 /*
5580  * sort the devices in descending order by max_avail, total_avail
5581  */
5582 static int btrfs_cmp_device_info(const void *a, const void *b)
5583 {
5584 	const struct btrfs_device_info *di_a = a;
5585 	const struct btrfs_device_info *di_b = b;
5586 
5587 	if (di_a->max_avail > di_b->max_avail)
5588 		return -1;
5589 	if (di_a->max_avail < di_b->max_avail)
5590 		return 1;
5591 	if (di_a->total_avail > di_b->total_avail)
5592 		return -1;
5593 	if (di_a->total_avail < di_b->total_avail)
5594 		return 1;
5595 	return 0;
5596 }
5597 
5598 /*
5599  * Return 0 if we allocated any virtual(*) chunk, and restore the size to
5600  * @allocated.
5601  * Return -ENOSPC if we have no more space to allocate virtual chunk
5602  *
5603  * *: A virtual chunk is a chunk that only exists during per-profile available
5604  *    estimation.
5605  *    Those numbers won't really take on-disk space, but only to emulate
5606  *    chunk allocator behavior to get accurate estimation on available space.
5607  *
5608  *    Another difference is, a virtual chunk has no size limit and doesn't care
5609  *    about holes in the device tree, allowing us to exhaust device space
5610  *    much faster.
5611  */
5612 static int alloc_virtual_chunk(struct btrfs_fs_info *fs_info,
5613 			       struct btrfs_device_info *devices_info,
5614 			       enum btrfs_raid_types type,
5615 			       u64 *allocated)
5616 {
5617 	const struct btrfs_raid_attr *raid_attr = &btrfs_raid_array[type];
5618 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
5619 	struct btrfs_device *device;
5620 	u64 stripe_size;
5621 	int ndevs = 0;
5622 
5623 	lockdep_assert_held(&fs_info->chunk_mutex);
5624 
5625 	/* Go through devices to collect their unallocated space. */
5626 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5627 		u64 avail;
5628 
5629 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5630 					&device->dev_state) ||
5631 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5632 			continue;
5633 
5634 		if (device->total_bytes > device->bytes_used +
5635 				device->per_profile_allocated)
5636 			avail = device->total_bytes - device->bytes_used -
5637 				device->per_profile_allocated;
5638 		else
5639 			avail = 0;
5640 
5641 		avail = round_down(avail, fs_info->sectorsize);
5642 
5643 		/* And exclude the [0, 1M) reserved space. */
5644 		if (avail > BTRFS_DEVICE_RANGE_RESERVED)
5645 			avail -= BTRFS_DEVICE_RANGE_RESERVED;
5646 		else
5647 			avail = 0;
5648 
5649 		/*
5650 		 * Not enough to support a single stripe, this device
5651 		 * can not be utilized for chunk allocation.
5652 		 */
5653 		if (avail < BTRFS_STRIPE_LEN)
5654 			continue;
5655 
5656 		/*
5657 		 * Unlike chunk allocator, we don't care about stripe or hole
5658 		 * size, so here we use @avail directly.
5659 		 */
5660 		devices_info[ndevs].dev_offset = 0;
5661 		devices_info[ndevs].total_avail = avail;
5662 		devices_info[ndevs].max_avail = avail;
5663 		devices_info[ndevs].dev = device;
5664 		++ndevs;
5665 	}
5666 	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5667 	     btrfs_cmp_device_info, NULL);
5668 	ndevs = rounddown(ndevs, raid_attr->devs_increment);
5669 	if (ndevs < raid_attr->devs_min)
5670 		return -ENOSPC;
5671 	if (raid_attr->devs_max)
5672 		ndevs = min(ndevs, (int)raid_attr->devs_max);
5673 	else
5674 		ndevs = min(ndevs, (int)BTRFS_MAX_DEVS(fs_info));
5675 
5676 	/*
5677 	 * Stripe size will be determined by the device with the least
5678 	 * unallocated space.
5679 	 */
5680 	stripe_size = devices_info[ndevs - 1].total_avail;
5681 
5682 	for (int i = 0; i < ndevs; i++)
5683 		devices_info[i].dev->per_profile_allocated += stripe_size;
5684 	*allocated = div_u64(stripe_size * (ndevs - raid_attr->nparity),
5685 			     raid_attr->ncopies);
5686 	return 0;
5687 }
5688 
5689 static int calc_one_profile_avail(struct btrfs_fs_info *fs_info,
5690 				  enum btrfs_raid_types type,
5691 				  u64 *result_ret)
5692 {
5693 	struct btrfs_device_info *devices_info = NULL;
5694 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
5695 	struct btrfs_device *device;
5696 	u64 allocated;
5697 	u64 result = 0;
5698 	int ret = 0;
5699 
5700 	lockdep_assert_held(&fs_info->chunk_mutex);
5701 	ASSERT(type >= 0 && type < BTRFS_NR_RAID_TYPES);
5702 
5703 	/* Not enough devices, quick exit, just update the result. */
5704 	if (fs_devices->rw_devices < btrfs_raid_array[type].devs_min) {
5705 		ret = -ENOSPC;
5706 		goto out;
5707 	}
5708 
5709 	devices_info = kzalloc_objs(*devices_info, fs_devices->rw_devices, GFP_NOFS);
5710 	if (!devices_info) {
5711 		ret = -ENOMEM;
5712 		goto out;
5713 	}
5714 	/* Clear virtual chunk used space for each device. */
5715 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list)
5716 		device->per_profile_allocated = 0;
5717 
5718 	while (!alloc_virtual_chunk(fs_info, devices_info, type, &allocated))
5719 		result += allocated;
5720 
5721 out:
5722 	kfree(devices_info);
5723 	if (ret < 0 && ret != -ENOSPC)
5724 		return ret;
5725 	*result_ret = result;
5726 	return 0;
5727 }
5728 
5729 /* Update the per-profile available space array. */
5730 void btrfs_update_per_profile_avail(struct btrfs_fs_info *fs_info)
5731 {
5732 	u64 results[BTRFS_NR_RAID_TYPES];
5733 	int ret;
5734 
5735 	/*
5736 	 * Zoned is more complex as we can not simply get the amount of
5737 	 * available space for each device.
5738 	 */
5739 	if (btrfs_is_zoned(fs_info))
5740 		goto error;
5741 
5742 	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
5743 		ret = calc_one_profile_avail(fs_info, i, &results[i]);
5744 		if (ret < 0)
5745 			goto error;
5746 	}
5747 
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] = results[i];
5751 	spin_unlock(&fs_info->fs_devices->per_profile_lock);
5752 	return;
5753 error:
5754 	spin_lock(&fs_info->fs_devices->per_profile_lock);
5755 	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++)
5756 		fs_info->fs_devices->per_profile_avail[i] = U64_MAX;
5757 	spin_unlock(&fs_info->fs_devices->per_profile_lock);
5758 }
5759 
5760 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5761 {
5762 	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5763 		return;
5764 
5765 	btrfs_set_fs_incompat(info, RAID56);
5766 }
5767 
5768 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5769 {
5770 	if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5771 		return;
5772 
5773 	btrfs_set_fs_incompat(info, RAID1C34);
5774 }
5775 
5776 /*
5777  * Structure used internally for btrfs_create_chunk() function.
5778  * Wraps needed parameters.
5779  */
5780 struct alloc_chunk_ctl {
5781 	u64 start;
5782 	u64 type;
5783 	/* Total number of stripes to allocate */
5784 	int num_stripes;
5785 	/* sub_stripes info for map */
5786 	int sub_stripes;
5787 	/* Stripes per device */
5788 	int dev_stripes;
5789 	/* Maximum number of devices to use */
5790 	int devs_max;
5791 	/* Minimum number of devices to use */
5792 	int devs_min;
5793 	/* ndevs has to be a multiple of this */
5794 	int devs_increment;
5795 	/* Number of copies */
5796 	int ncopies;
5797 	/* Number of stripes worth of bytes to store parity information */
5798 	int nparity;
5799 	u64 max_stripe_size;
5800 	u64 max_chunk_size;
5801 	u64 dev_extent_min;
5802 	u64 stripe_size;
5803 	u64 chunk_size;
5804 	int ndevs;
5805 	/* Space_info the block group is going to belong. */
5806 	struct btrfs_space_info *space_info;
5807 };
5808 
5809 static void init_alloc_chunk_ctl_policy_regular(
5810 				struct btrfs_fs_devices *fs_devices,
5811 				struct alloc_chunk_ctl *ctl)
5812 {
5813 	struct btrfs_space_info *space_info;
5814 
5815 	space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5816 	ASSERT(space_info);
5817 
5818 	ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5819 	ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5820 
5821 	if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5822 		ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5823 
5824 	/* We don't want a chunk larger than 10% of writable space */
5825 	ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5826 				  ctl->max_chunk_size);
5827 	ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5828 }
5829 
5830 static void init_alloc_chunk_ctl_policy_zoned(
5831 				      struct btrfs_fs_devices *fs_devices,
5832 				      struct alloc_chunk_ctl *ctl)
5833 {
5834 	u64 zone_size = fs_devices->fs_info->zone_size;
5835 	u64 limit;
5836 	int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5837 	int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5838 	u64 min_chunk_size = min_data_stripes * zone_size;
5839 	u64 type = ctl->type;
5840 
5841 	ctl->max_stripe_size = zone_size;
5842 	if (type & BTRFS_BLOCK_GROUP_DATA) {
5843 		ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5844 						 zone_size);
5845 	} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5846 		ctl->max_chunk_size = ctl->max_stripe_size;
5847 	} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5848 		ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5849 		ctl->devs_max = min_t(int, ctl->devs_max,
5850 				      BTRFS_MAX_DEVS_SYS_CHUNK);
5851 	} else {
5852 		BUG();
5853 	}
5854 
5855 	/* We don't want a chunk larger than 10% of writable space */
5856 	limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5857 			       zone_size),
5858 		    min_chunk_size);
5859 	ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5860 	ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5861 }
5862 
5863 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5864 				 struct alloc_chunk_ctl *ctl)
5865 {
5866 	int index = btrfs_bg_flags_to_raid_index(ctl->type);
5867 
5868 	ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5869 	ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5870 	ctl->devs_max = btrfs_raid_array[index].devs_max;
5871 	if (!ctl->devs_max)
5872 		ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5873 	ctl->devs_min = btrfs_raid_array[index].devs_min;
5874 	ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5875 	ctl->ncopies = btrfs_raid_array[index].ncopies;
5876 	ctl->nparity = btrfs_raid_array[index].nparity;
5877 	ctl->ndevs = 0;
5878 
5879 	switch (fs_devices->chunk_alloc_policy) {
5880 	default:
5881 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5882 		fallthrough;
5883 	case BTRFS_CHUNK_ALLOC_REGULAR:
5884 		init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5885 		break;
5886 	case BTRFS_CHUNK_ALLOC_ZONED:
5887 		init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5888 		break;
5889 	}
5890 }
5891 
5892 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5893 			      struct alloc_chunk_ctl *ctl,
5894 			      struct btrfs_device_info *devices_info)
5895 {
5896 	struct btrfs_fs_info *info = fs_devices->fs_info;
5897 	struct btrfs_device *device;
5898 	u64 total_avail;
5899 	u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5900 	int ret;
5901 	int ndevs = 0;
5902 	u64 max_avail;
5903 	u64 dev_offset;
5904 
5905 	/*
5906 	 * in the first pass through the devices list, we gather information
5907 	 * about the available holes on each device.
5908 	 */
5909 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5910 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5911 			WARN(1, KERN_ERR
5912 			       "BTRFS: read-only device in alloc_list\n");
5913 			continue;
5914 		}
5915 
5916 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5917 					&device->dev_state) ||
5918 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5919 			continue;
5920 
5921 		if (device->total_bytes > device->bytes_used)
5922 			total_avail = device->total_bytes - device->bytes_used;
5923 		else
5924 			total_avail = 0;
5925 
5926 		/* If there is no space on this device, skip it. */
5927 		if (total_avail < ctl->dev_extent_min)
5928 			continue;
5929 
5930 		ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5931 					   &max_avail);
5932 		if (ret && ret != -ENOSPC)
5933 			return ret;
5934 
5935 		if (ret == 0)
5936 			max_avail = dev_extent_want;
5937 
5938 		if (max_avail < ctl->dev_extent_min) {
5939 			if (btrfs_test_opt(info, ENOSPC_DEBUG))
5940 				btrfs_debug(info,
5941 			"%s: devid %llu has no free space, have=%llu want=%llu",
5942 					    __func__, device->devid, max_avail,
5943 					    ctl->dev_extent_min);
5944 			continue;
5945 		}
5946 
5947 		if (ndevs == fs_devices->rw_devices) {
5948 			WARN(1, "%s: found more than %llu devices\n",
5949 			     __func__, fs_devices->rw_devices);
5950 			break;
5951 		}
5952 		devices_info[ndevs].dev_offset = dev_offset;
5953 		devices_info[ndevs].max_avail = max_avail;
5954 		devices_info[ndevs].total_avail = total_avail;
5955 		devices_info[ndevs].dev = device;
5956 		++ndevs;
5957 	}
5958 	ctl->ndevs = ndevs;
5959 
5960 	/*
5961 	 * now sort the devices by hole size / available space
5962 	 */
5963 	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5964 	     btrfs_cmp_device_info, NULL);
5965 
5966 	return 0;
5967 }
5968 
5969 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5970 				      struct btrfs_device_info *devices_info)
5971 {
5972 	/* Number of stripes that count for block group size */
5973 	int data_stripes;
5974 
5975 	/*
5976 	 * The primary goal is to maximize the number of stripes, so use as
5977 	 * many devices as possible, even if the stripes are not maximum sized.
5978 	 *
5979 	 * The DUP profile stores more than one stripe per device, the
5980 	 * max_avail is the total size so we have to adjust.
5981 	 */
5982 	ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5983 				   ctl->dev_stripes);
5984 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5985 
5986 	/* This will have to be fixed for RAID1 and RAID10 over more drives */
5987 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5988 
5989 	/*
5990 	 * Use the number of data stripes to figure out how big this chunk is
5991 	 * really going to be in terms of logical address space, and compare
5992 	 * that answer with the max chunk size. If it's higher, we try to
5993 	 * reduce stripe_size.
5994 	 */
5995 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5996 		/*
5997 		 * Reduce stripe_size, round it up to a 16MB boundary again and
5998 		 * then use it, unless it ends up being even bigger than the
5999 		 * previous value we had already.
6000 		 */
6001 		ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
6002 							data_stripes), SZ_16M),
6003 				       ctl->stripe_size);
6004 	}
6005 
6006 	/* Stripe size should not go beyond 1G. */
6007 	ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
6008 
6009 	/* Align to BTRFS_STRIPE_LEN */
6010 	ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
6011 	ctl->chunk_size = ctl->stripe_size * data_stripes;
6012 
6013 	return 0;
6014 }
6015 
6016 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
6017 				    struct btrfs_device_info *devices_info)
6018 {
6019 	u64 zone_size = devices_info[0].dev->zone_info->zone_size;
6020 	/* Number of stripes that count for block group size */
6021 	int data_stripes;
6022 
6023 	/*
6024 	 * It should hold because:
6025 	 *    dev_extent_min == dev_extent_want == zone_size * dev_stripes
6026 	 */
6027 	ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min,
6028 	       "ndevs=%d max_avail=%llu dev_extent_min=%llu", ctl->ndevs,
6029 	       devices_info[ctl->ndevs - 1].max_avail, ctl->dev_extent_min);
6030 
6031 	ctl->stripe_size = zone_size;
6032 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
6033 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
6034 
6035 	/* stripe_size is fixed in zoned filesystem. Reduce ndevs instead. */
6036 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
6037 		ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
6038 					     ctl->stripe_size) + ctl->nparity,
6039 				     ctl->dev_stripes);
6040 		ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
6041 		data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
6042 		ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size,
6043 		       "stripe_size=%llu data_stripes=%d max_chunk_size=%llu",
6044 		       ctl->stripe_size, data_stripes, ctl->max_chunk_size);
6045 	}
6046 
6047 	ctl->chunk_size = ctl->stripe_size * data_stripes;
6048 
6049 	return 0;
6050 }
6051 
6052 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
6053 			      struct alloc_chunk_ctl *ctl,
6054 			      struct btrfs_device_info *devices_info)
6055 {
6056 	struct btrfs_fs_info *info = fs_devices->fs_info;
6057 
6058 	/*
6059 	 * Round down to number of usable stripes, devs_increment can be any
6060 	 * number so we can't use round_down() that requires power of 2, while
6061 	 * rounddown is safe.
6062 	 */
6063 	ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
6064 
6065 	if (ctl->ndevs < ctl->devs_min) {
6066 		if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
6067 			btrfs_debug(info,
6068 	"%s: not enough devices with free space: have=%d minimum required=%d",
6069 				    __func__, ctl->ndevs, ctl->devs_min);
6070 		}
6071 		return -ENOSPC;
6072 	}
6073 
6074 	ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
6075 
6076 	switch (fs_devices->chunk_alloc_policy) {
6077 	default:
6078 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
6079 		fallthrough;
6080 	case BTRFS_CHUNK_ALLOC_REGULAR:
6081 		return decide_stripe_size_regular(ctl, devices_info);
6082 	case BTRFS_CHUNK_ALLOC_ZONED:
6083 		return decide_stripe_size_zoned(ctl, devices_info);
6084 	}
6085 }
6086 
6087 static void chunk_map_device_set_bits(struct btrfs_chunk_map *map, unsigned int bits)
6088 {
6089 	for (int i = 0; i < map->num_stripes; i++) {
6090 		struct btrfs_io_stripe *stripe = &map->stripes[i];
6091 		struct btrfs_device *device = stripe->dev;
6092 
6093 		btrfs_set_extent_bit(&device->alloc_state, stripe->physical,
6094 				     stripe->physical + map->stripe_size - 1,
6095 				     bits | EXTENT_NOWAIT, NULL);
6096 	}
6097 }
6098 
6099 void btrfs_chunk_map_device_clear_bits(struct btrfs_chunk_map *map, unsigned int bits)
6100 {
6101 	for (int i = 0; i < map->num_stripes; i++) {
6102 		struct btrfs_io_stripe *stripe = &map->stripes[i];
6103 		struct btrfs_device *device = stripe->dev;
6104 
6105 		btrfs_clear_extent_bit(&device->alloc_state, stripe->physical,
6106 				       stripe->physical + map->stripe_size - 1,
6107 				       bits | EXTENT_NOWAIT, NULL);
6108 	}
6109 }
6110 
6111 void btrfs_remove_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
6112 {
6113 	write_lock(&fs_info->mapping_tree_lock);
6114 	rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
6115 	RB_CLEAR_NODE(&map->rb_node);
6116 	btrfs_chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
6117 	write_unlock(&fs_info->mapping_tree_lock);
6118 
6119 	/* Once for the tree reference. */
6120 	btrfs_free_chunk_map(map);
6121 }
6122 
6123 static int btrfs_chunk_map_cmp(const struct rb_node *new,
6124 			       const struct rb_node *exist)
6125 {
6126 	const struct btrfs_chunk_map *new_map =
6127 		rb_entry(new, struct btrfs_chunk_map, rb_node);
6128 	const struct btrfs_chunk_map *exist_map =
6129 		rb_entry(exist, struct btrfs_chunk_map, rb_node);
6130 
6131 	if (new_map->start == exist_map->start)
6132 		return 0;
6133 	if (new_map->start < exist_map->start)
6134 		return -1;
6135 	return 1;
6136 }
6137 
6138 EXPORT_FOR_TESTS
6139 int btrfs_add_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
6140 {
6141 	struct rb_node *exist;
6142 
6143 	write_lock(&fs_info->mapping_tree_lock);
6144 	exist = rb_find_add_cached(&map->rb_node, &fs_info->mapping_tree,
6145 				   btrfs_chunk_map_cmp);
6146 
6147 	if (exist) {
6148 		write_unlock(&fs_info->mapping_tree_lock);
6149 		return -EEXIST;
6150 	}
6151 	chunk_map_device_set_bits(map, CHUNK_ALLOCATED);
6152 	btrfs_chunk_map_device_clear_bits(map, CHUNK_TRIMMED);
6153 	write_unlock(&fs_info->mapping_tree_lock);
6154 
6155 	return 0;
6156 }
6157 
6158 EXPORT_FOR_TESTS
6159 struct btrfs_chunk_map *btrfs_alloc_chunk_map(int num_stripes, gfp_t gfp)
6160 {
6161 	struct btrfs_chunk_map *map;
6162 
6163 	map = kmalloc(btrfs_chunk_map_size(num_stripes), gfp);
6164 	if (!map)
6165 		return NULL;
6166 
6167 	refcount_set(&map->refs, 1);
6168 	RB_CLEAR_NODE(&map->rb_node);
6169 
6170 	return map;
6171 }
6172 
6173 static void set_real_chunk_type(struct btrfs_chunk_map *map)
6174 {
6175 	map->type = map->on_disk_type;
6176 	if (likely((map->on_disk_type & BTRFS_BLOCK_GROUP_RAID56_MASK) == 0 ||
6177 		   nr_data_stripes(map) > 1))
6178 		return;
6179 	if (map->on_disk_type & BTRFS_BLOCK_GROUP_RAID5)
6180 		map->type |= BTRFS_BLOCK_GROUP_RAID1;
6181 	else
6182 		map->type |= BTRFS_BLOCK_GROUP_RAID1C3;
6183 	map->type &= ~BTRFS_BLOCK_GROUP_RAID56_MASK;
6184 }
6185 
6186 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
6187 			struct alloc_chunk_ctl *ctl,
6188 			struct btrfs_device_info *devices_info)
6189 {
6190 	struct btrfs_fs_info *info = trans->fs_info;
6191 	struct btrfs_chunk_map *map;
6192 	struct btrfs_block_group *block_group;
6193 	u64 start = ctl->start;
6194 	u64 type = ctl->type;
6195 	int ret;
6196 
6197 	map = btrfs_alloc_chunk_map(ctl->num_stripes, GFP_NOFS);
6198 	if (!map)
6199 		return ERR_PTR(-ENOMEM);
6200 
6201 	map->start = start;
6202 	map->chunk_len = ctl->chunk_size;
6203 	map->stripe_size = ctl->stripe_size;
6204 	map->on_disk_type = type;
6205 	map->sub_stripes = ctl->sub_stripes;
6206 	map->num_stripes = ctl->num_stripes;
6207 	set_real_chunk_type(map);
6208 
6209 	for (int i = 0; i < ctl->ndevs; i++) {
6210 		for (int j = 0; j < ctl->dev_stripes; j++) {
6211 			int s = i * ctl->dev_stripes + j;
6212 			map->stripes[s].dev = devices_info[i].dev;
6213 			map->stripes[s].physical = devices_info[i].dev_offset +
6214 						   j * ctl->stripe_size;
6215 		}
6216 	}
6217 
6218 	trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
6219 
6220 	ret = btrfs_add_chunk_map(info, map);
6221 	if (ret) {
6222 		btrfs_free_chunk_map(map);
6223 		return ERR_PTR(ret);
6224 	}
6225 
6226 	block_group = btrfs_make_block_group(trans, ctl->space_info, type, start,
6227 					     ctl->chunk_size);
6228 	if (IS_ERR(block_group)) {
6229 		btrfs_remove_chunk_map(info, map);
6230 		return block_group;
6231 	}
6232 
6233 	for (int i = 0; i < map->num_stripes; i++) {
6234 		struct btrfs_device *dev = map->stripes[i].dev;
6235 
6236 		btrfs_device_set_bytes_used(dev,
6237 					    dev->bytes_used + ctl->stripe_size);
6238 		if (list_empty(&dev->post_commit_list))
6239 			list_add_tail(&dev->post_commit_list,
6240 				      &trans->transaction->dev_update_list);
6241 	}
6242 
6243 	atomic64_sub(ctl->stripe_size * map->num_stripes,
6244 		     &info->free_chunk_space);
6245 
6246 	check_raid56_incompat_flag(info, type);
6247 	check_raid1c34_incompat_flag(info, type);
6248 
6249 	btrfs_update_per_profile_avail(info);
6250 
6251 	return block_group;
6252 }
6253 
6254 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
6255 					     struct btrfs_space_info *space_info,
6256 					     u64 type)
6257 {
6258 	struct btrfs_fs_info *info = trans->fs_info;
6259 	struct btrfs_fs_devices *fs_devices = info->fs_devices;
6260 	struct btrfs_device_info AUTO_KFREE(devices_info);
6261 	struct alloc_chunk_ctl ctl;
6262 	int ret;
6263 
6264 	lockdep_assert_held(&info->chunk_mutex);
6265 
6266 	if (unlikely(!alloc_profile_is_valid(type, 0))) {
6267 		DEBUG_WARN("invalid alloc profile for type %llu", type);
6268 		return ERR_PTR(-EINVAL);
6269 	}
6270 
6271 	if (list_empty(&fs_devices->alloc_list)) {
6272 		if (btrfs_test_opt(info, ENOSPC_DEBUG))
6273 			btrfs_debug(info, "%s: no writable device", __func__);
6274 		return ERR_PTR(-ENOSPC);
6275 	}
6276 
6277 	if (unlikely(!(type & BTRFS_BLOCK_GROUP_TYPE_MASK))) {
6278 		btrfs_err(info, "invalid chunk type 0x%llx requested", type);
6279 		DEBUG_WARN();
6280 		return ERR_PTR(-EINVAL);
6281 	}
6282 
6283 	ctl.start = find_next_chunk(info);
6284 	ctl.type = type;
6285 	ctl.space_info = space_info;
6286 	init_alloc_chunk_ctl(fs_devices, &ctl);
6287 
6288 	devices_info = kzalloc_objs(*devices_info, fs_devices->rw_devices, GFP_NOFS);
6289 	if (!devices_info)
6290 		return ERR_PTR(-ENOMEM);
6291 
6292 	ret = gather_device_info(fs_devices, &ctl, devices_info);
6293 	if (ret < 0)
6294 		return ERR_PTR(ret);
6295 
6296 	ret = decide_stripe_size(fs_devices, &ctl, devices_info);
6297 	if (ret < 0)
6298 		return ERR_PTR(ret);
6299 
6300 	return create_chunk(trans, &ctl, devices_info);
6301 }
6302 
6303 /*
6304  * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
6305  * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
6306  * chunks.
6307  *
6308  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
6309  * phases.
6310  */
6311 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
6312 				     struct btrfs_block_group *bg)
6313 {
6314 	struct btrfs_fs_info *fs_info = trans->fs_info;
6315 	struct btrfs_root *chunk_root = fs_info->chunk_root;
6316 	struct btrfs_key key;
6317 	struct btrfs_chunk *chunk;
6318 	struct btrfs_stripe *stripe;
6319 	struct btrfs_chunk_map *map;
6320 	size_t item_size;
6321 	int i;
6322 	int ret;
6323 
6324 	/*
6325 	 * We take the chunk_mutex for 2 reasons:
6326 	 *
6327 	 * 1) Updates and insertions in the chunk btree must be done while holding
6328 	 *    the chunk_mutex, as well as updating the system chunk array in the
6329 	 *    superblock. See the comment on top of btrfs_chunk_alloc() for the
6330 	 *    details;
6331 	 *
6332 	 * 2) To prevent races with the final phase of a device replace operation
6333 	 *    that replaces the device object associated with the map's stripes,
6334 	 *    because the device object's id can change at any time during that
6335 	 *    final phase of the device replace operation
6336 	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
6337 	 *    replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
6338 	 *    which would cause a failure when updating the device item, which does
6339 	 *    not exists, or persisting a stripe of the chunk item with such ID.
6340 	 *    Here we can't use the device_list_mutex because our caller already
6341 	 *    has locked the chunk_mutex, and the final phase of device replace
6342 	 *    acquires both mutexes - first the device_list_mutex and then the
6343 	 *    chunk_mutex. Using any of those two mutexes protects us from a
6344 	 *    concurrent device replace.
6345 	 */
6346 	lockdep_assert_held(&fs_info->chunk_mutex);
6347 
6348 	map = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
6349 	if (IS_ERR(map)) {
6350 		ret = PTR_ERR(map);
6351 		btrfs_abort_transaction(trans, ret);
6352 		return ret;
6353 	}
6354 
6355 	item_size = btrfs_chunk_item_size(map->num_stripes);
6356 
6357 	chunk = kzalloc(item_size, GFP_NOFS);
6358 	if (unlikely(!chunk)) {
6359 		ret = -ENOMEM;
6360 		btrfs_abort_transaction(trans, ret);
6361 		goto out;
6362 	}
6363 
6364 	for (i = 0; i < map->num_stripes; i++) {
6365 		struct btrfs_device *device = map->stripes[i].dev;
6366 
6367 		ret = btrfs_update_device(trans, device);
6368 		if (ret)
6369 			goto out;
6370 	}
6371 
6372 	stripe = &chunk->stripe;
6373 	for (i = 0; i < map->num_stripes; i++) {
6374 		struct btrfs_device *device = map->stripes[i].dev;
6375 		const u64 dev_offset = map->stripes[i].physical;
6376 
6377 		btrfs_set_stack_stripe_devid(stripe, device->devid);
6378 		btrfs_set_stack_stripe_offset(stripe, dev_offset);
6379 		memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
6380 		stripe++;
6381 	}
6382 
6383 	btrfs_set_stack_chunk_length(chunk, bg->length);
6384 	btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
6385 	btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
6386 	btrfs_set_stack_chunk_type(chunk, map->on_disk_type);
6387 	btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
6388 	btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
6389 	btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
6390 	btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
6391 	btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
6392 
6393 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
6394 	key.type = BTRFS_CHUNK_ITEM_KEY;
6395 	key.offset = bg->start;
6396 
6397 	ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
6398 	if (ret)
6399 		goto out;
6400 
6401 	set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
6402 
6403 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
6404 		ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
6405 		if (ret)
6406 			goto out;
6407 	}
6408 
6409 out:
6410 	kfree(chunk);
6411 	btrfs_free_chunk_map(map);
6412 	return ret;
6413 }
6414 
6415 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
6416 {
6417 	struct btrfs_fs_info *fs_info = trans->fs_info;
6418 	u64 alloc_profile;
6419 	struct btrfs_block_group *meta_bg;
6420 	struct btrfs_space_info *meta_space_info;
6421 	struct btrfs_block_group *sys_bg;
6422 	struct btrfs_space_info *sys_space_info;
6423 
6424 	/*
6425 	 * When adding a new device for sprouting, the seed device is read-only
6426 	 * so we must first allocate a metadata and a system chunk. But before
6427 	 * adding the block group items to the extent, device and chunk btrees,
6428 	 * we must first:
6429 	 *
6430 	 * 1) Create both chunks without doing any changes to the btrees, as
6431 	 *    otherwise we would get -ENOSPC since the block groups from the
6432 	 *    seed device are read-only;
6433 	 *
6434 	 * 2) Add the device item for the new sprout device - finishing the setup
6435 	 *    of a new block group requires updating the device item in the chunk
6436 	 *    btree, so it must exist when we attempt to do it. The previous step
6437 	 *    ensures this does not fail with -ENOSPC.
6438 	 *
6439 	 * After that we can add the block group items to their btrees:
6440 	 * update existing device item in the chunk btree, add a new block group
6441 	 * item to the extent btree, add a new chunk item to the chunk btree and
6442 	 * finally add the new device extent items to the devices btree.
6443 	 */
6444 
6445 	alloc_profile = btrfs_metadata_alloc_profile(fs_info);
6446 	meta_space_info = btrfs_find_space_info(fs_info, alloc_profile);
6447 	if (unlikely(!meta_space_info)) {
6448 		DEBUG_WARN();
6449 		return -EINVAL;
6450 	}
6451 	meta_bg = btrfs_create_chunk(trans, meta_space_info, alloc_profile);
6452 	if (IS_ERR(meta_bg))
6453 		return PTR_ERR(meta_bg);
6454 
6455 	alloc_profile = btrfs_system_alloc_profile(fs_info);
6456 	sys_space_info = btrfs_find_space_info(fs_info, alloc_profile);
6457 	if (unlikely(!sys_space_info)) {
6458 		DEBUG_WARN();
6459 		return -EINVAL;
6460 	}
6461 	sys_bg = btrfs_create_chunk(trans, sys_space_info, alloc_profile);
6462 	if (IS_ERR(sys_bg))
6463 		return PTR_ERR(sys_bg);
6464 
6465 	return 0;
6466 }
6467 
6468 static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map *map)
6469 {
6470 	const int index = btrfs_bg_flags_to_raid_index(map->type);
6471 
6472 	return btrfs_raid_array[index].tolerated_failures;
6473 }
6474 
6475 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
6476 {
6477 	struct btrfs_chunk_map *map;
6478 	int miss_ndevs = 0;
6479 	int i;
6480 	bool ret = true;
6481 
6482 	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
6483 	if (IS_ERR(map))
6484 		return false;
6485 
6486 	for (i = 0; i < map->num_stripes; i++) {
6487 		if (test_bit(BTRFS_DEV_STATE_MISSING,
6488 					&map->stripes[i].dev->dev_state)) {
6489 			miss_ndevs++;
6490 			continue;
6491 		}
6492 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
6493 					&map->stripes[i].dev->dev_state)) {
6494 			ret = false;
6495 			goto end;
6496 		}
6497 	}
6498 
6499 	/*
6500 	 * If the number of missing devices is larger than max errors, we can
6501 	 * not write the data into that chunk successfully.
6502 	 */
6503 	if (miss_ndevs > btrfs_chunk_max_errors(map))
6504 		ret = false;
6505 end:
6506 	btrfs_free_chunk_map(map);
6507 	return ret;
6508 }
6509 
6510 void btrfs_mapping_tree_free(struct btrfs_fs_info *fs_info)
6511 {
6512 	write_lock(&fs_info->mapping_tree_lock);
6513 	while (!RB_EMPTY_ROOT(&fs_info->mapping_tree.rb_root)) {
6514 		struct btrfs_chunk_map *map;
6515 		struct rb_node *node;
6516 
6517 		node = rb_first_cached(&fs_info->mapping_tree);
6518 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
6519 		rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
6520 		RB_CLEAR_NODE(&map->rb_node);
6521 		btrfs_chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
6522 		/* Once for the tree ref. */
6523 		btrfs_free_chunk_map(map);
6524 		cond_resched_rwlock_write(&fs_info->mapping_tree_lock);
6525 	}
6526 	write_unlock(&fs_info->mapping_tree_lock);
6527 }
6528 
6529 static int btrfs_chunk_map_num_copies(const struct btrfs_chunk_map *map)
6530 {
6531 	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(map->type);
6532 
6533 	if (map->type & BTRFS_BLOCK_GROUP_RAID5)
6534 		return 2;
6535 
6536 	/*
6537 	 * There could be two corrupted data stripes, we need to loop retry in
6538 	 * order to rebuild the correct data.
6539 	 *
6540 	 * Fail a stripe at a time on every retry except the stripe under
6541 	 * reconstruction.
6542 	 */
6543 	if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6544 		return map->num_stripes;
6545 
6546 	/* Non-RAID56, use their ncopies from btrfs_raid_array. */
6547 	return btrfs_raid_array[index].ncopies;
6548 }
6549 
6550 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
6551 {
6552 	struct btrfs_chunk_map *map;
6553 	int ret;
6554 
6555 	map = btrfs_get_chunk_map(fs_info, logical, len);
6556 	if (IS_ERR(map))
6557 		/*
6558 		 * We could return errors for these cases, but that could get
6559 		 * ugly and we'd probably do the same thing which is just not do
6560 		 * anything else and exit, so return 1 so the callers don't try
6561 		 * to use other copies.
6562 		 */
6563 		return 1;
6564 
6565 	ret = btrfs_chunk_map_num_copies(map);
6566 	btrfs_free_chunk_map(map);
6567 	return ret;
6568 }
6569 
6570 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
6571 				    u64 logical)
6572 {
6573 	struct btrfs_chunk_map *map;
6574 	unsigned long len = fs_info->sectorsize;
6575 
6576 	if (!btrfs_fs_incompat(fs_info, RAID56))
6577 		return len;
6578 
6579 	map = btrfs_get_chunk_map(fs_info, logical, len);
6580 
6581 	if (!WARN_ON(IS_ERR(map))) {
6582 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6583 			len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6584 		btrfs_free_chunk_map(map);
6585 	}
6586 	return len;
6587 }
6588 
6589 #ifdef CONFIG_BTRFS_EXPERIMENTAL
6590 static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
6591 {
6592 	for (int index = first; index < first + num_stripes; index++) {
6593 		const struct btrfs_device *device = map->stripes[index].dev;
6594 
6595 		if (device->devid == READ_ONCE(device->fs_devices->read_devid))
6596 			return index;
6597 	}
6598 
6599 	/* If no read-preferred device is set use the first stripe. */
6600 	return first;
6601 }
6602 
6603 struct stripe_mirror {
6604 	u64 devid;
6605 	int num;
6606 };
6607 
6608 static int btrfs_cmp_devid(const void *a, const void *b)
6609 {
6610 	const struct stripe_mirror *s1 = (const struct stripe_mirror *)a;
6611 	const struct stripe_mirror *s2 = (const struct stripe_mirror *)b;
6612 
6613 	if (s1->devid < s2->devid)
6614 		return -1;
6615 	if (s1->devid > s2->devid)
6616 		return 1;
6617 	return 0;
6618 }
6619 
6620 /*
6621  * Select a stripe for reading using the round-robin algorithm.
6622  *
6623  *  1. Compute the read cycle as the total sectors read divided by the minimum
6624  *     sectors per device.
6625  *  2. Determine the stripe number for the current read by taking the modulus
6626  *     of the read cycle with the total number of stripes:
6627  *
6628  *      stripe index = (total sectors / min sectors per dev) % num stripes
6629  *
6630  * The calculated stripe index is then used to select the corresponding device
6631  * from the list of devices, which is ordered by devid.
6632  */
6633 static int btrfs_read_rr(const struct btrfs_chunk_map *map, int first, int num_stripes)
6634 {
6635 	struct stripe_mirror stripes[BTRFS_RAID1_MAX_MIRRORS] = { 0 };
6636 	struct btrfs_device *device  = map->stripes[first].dev;
6637 	struct btrfs_fs_info *fs_info = device->fs_devices->fs_info;
6638 	unsigned int read_cycle;
6639 	unsigned int total_reads;
6640 	unsigned int min_reads_per_dev;
6641 
6642 	total_reads = percpu_counter_sum(&fs_info->stats_read_blocks);
6643 	min_reads_per_dev = READ_ONCE(fs_info->fs_devices->rr_min_contig_read) >>
6644 						       fs_info->sectorsize_bits;
6645 
6646 	for (int index = 0, i = first; i < first + num_stripes; i++) {
6647 		stripes[index].devid = map->stripes[i].dev->devid;
6648 		stripes[index].num = i;
6649 		index++;
6650 	}
6651 	sort(stripes, num_stripes, sizeof(struct stripe_mirror),
6652 	     btrfs_cmp_devid, NULL);
6653 
6654 	read_cycle = total_reads / min_reads_per_dev;
6655 	return stripes[read_cycle % num_stripes].num;
6656 }
6657 #endif
6658 
6659 static int find_live_mirror(struct btrfs_fs_info *fs_info,
6660 			    struct btrfs_chunk_map *map, int first,
6661 			    bool dev_replace_is_ongoing)
6662 {
6663 	const enum btrfs_read_policy policy = READ_ONCE(fs_info->fs_devices->read_policy);
6664 	int i;
6665 	int num_stripes;
6666 	int preferred_mirror;
6667 	int tolerance;
6668 	struct btrfs_device *srcdev;
6669 
6670 	ASSERT((map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)),
6671 	       "type=%llu", map->type);
6672 
6673 	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6674 		num_stripes = map->sub_stripes;
6675 	else
6676 		num_stripes = map->num_stripes;
6677 
6678 	switch (policy) {
6679 	default:
6680 		/* Shouldn't happen, just warn and use pid instead of failing */
6681 		btrfs_warn_rl(fs_info, "unknown read_policy type %u, reset to pid",
6682 			      policy);
6683 		WRITE_ONCE(fs_info->fs_devices->read_policy, BTRFS_READ_POLICY_PID);
6684 		fallthrough;
6685 	case BTRFS_READ_POLICY_PID:
6686 		preferred_mirror = first + (current->pid % num_stripes);
6687 		break;
6688 #ifdef CONFIG_BTRFS_EXPERIMENTAL
6689 	case BTRFS_READ_POLICY_RR:
6690 		preferred_mirror = btrfs_read_rr(map, first, num_stripes);
6691 		break;
6692 	case BTRFS_READ_POLICY_DEVID:
6693 		preferred_mirror = btrfs_read_preferred(map, first, num_stripes);
6694 		break;
6695 #endif
6696 	}
6697 
6698 	if (dev_replace_is_ongoing &&
6699 	    fs_info->dev_replace.cont_reading_from_srcdev_mode ==
6700 	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
6701 		srcdev = fs_info->dev_replace.srcdev;
6702 	else
6703 		srcdev = NULL;
6704 
6705 	/*
6706 	 * try to avoid the drive that is the source drive for a
6707 	 * dev-replace procedure, only choose it if no other non-missing
6708 	 * mirror is available
6709 	 */
6710 	for (tolerance = 0; tolerance < 2; tolerance++) {
6711 		if (map->stripes[preferred_mirror].dev->bdev &&
6712 		    (tolerance || map->stripes[preferred_mirror].dev != srcdev))
6713 			return preferred_mirror;
6714 		for (i = first; i < first + num_stripes; i++) {
6715 			if (map->stripes[i].dev->bdev &&
6716 			    (tolerance || map->stripes[i].dev != srcdev))
6717 				return i;
6718 		}
6719 	}
6720 
6721 	/* we couldn't find one that doesn't fail.  Just return something
6722 	 * and the io error handling code will clean up eventually
6723 	 */
6724 	return preferred_mirror;
6725 }
6726 
6727 EXPORT_FOR_TESTS
6728 struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
6729 						u64 logical, u16 total_stripes)
6730 {
6731 	struct btrfs_io_context *bioc;
6732 
6733 	bioc = kzalloc_flex(*bioc, stripes, total_stripes, GFP_NOFS);
6734 
6735 	if (!bioc)
6736 		return NULL;
6737 
6738 	refcount_set(&bioc->refs, 1);
6739 
6740 	bioc->fs_info = fs_info;
6741 	bioc->replace_stripe_src = -1;
6742 	bioc->full_stripe_logical = (u64)-1;
6743 	bioc->logical = logical;
6744 
6745 	return bioc;
6746 }
6747 
6748 void btrfs_get_bioc(struct btrfs_io_context *bioc)
6749 {
6750 	WARN_ON(!refcount_read(&bioc->refs));
6751 	refcount_inc(&bioc->refs);
6752 }
6753 
6754 void btrfs_put_bioc(struct btrfs_io_context *bioc)
6755 {
6756 	if (!bioc)
6757 		return;
6758 	if (refcount_dec_and_test(&bioc->refs))
6759 		kfree(bioc);
6760 }
6761 
6762 /*
6763  * Please note that, discard won't be sent to target device of device
6764  * replace.
6765  */
6766 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
6767 					       u64 logical, u64 *length_ret,
6768 					       u32 *num_stripes, bool do_remap)
6769 {
6770 	struct btrfs_chunk_map *map;
6771 	struct btrfs_discard_stripe *stripes;
6772 	u64 length = *length_ret;
6773 	u64 offset;
6774 	u32 stripe_nr;
6775 	u32 stripe_nr_end;
6776 	u32 stripe_cnt;
6777 	u64 stripe_end_offset;
6778 	u64 stripe_offset;
6779 	u32 stripe_index;
6780 	u32 factor = 0;
6781 	u32 sub_stripes = 0;
6782 	u32 stripes_per_dev = 0;
6783 	u32 remaining_stripes = 0;
6784 	u32 last_stripe = 0;
6785 	int ret;
6786 	int i;
6787 
6788 	map = btrfs_get_chunk_map(fs_info, logical, length);
6789 	if (IS_ERR(map))
6790 		return ERR_CAST(map);
6791 
6792 	if (do_remap && (map->type & BTRFS_BLOCK_GROUP_REMAPPED)) {
6793 		u64 new_logical = logical;
6794 
6795 		ret = btrfs_translate_remap(fs_info, &new_logical, &length);
6796 		if (ret)
6797 			goto out_free_map;
6798 
6799 		if (new_logical != logical) {
6800 			btrfs_free_chunk_map(map);
6801 
6802 			map = btrfs_get_chunk_map(fs_info, new_logical, length);
6803 			if (IS_ERR(map))
6804 				return ERR_CAST(map);
6805 
6806 			logical = new_logical;
6807 		}
6808 	}
6809 
6810 	/* we don't discard raid56 yet */
6811 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6812 		ret = -EOPNOTSUPP;
6813 		goto out_free_map;
6814 	}
6815 
6816 	offset = logical - map->start;
6817 	length = min_t(u64, map->start + map->chunk_len - logical, length);
6818 	*length_ret = length;
6819 
6820 	/*
6821 	 * stripe_nr counts the total number of stripes we have to stride
6822 	 * to get to this block
6823 	 */
6824 	stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6825 
6826 	/* stripe_offset is the offset of this block in its stripe */
6827 	stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
6828 
6829 	stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
6830 			BTRFS_STRIPE_LEN_SHIFT;
6831 	stripe_cnt = stripe_nr_end - stripe_nr;
6832 	stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
6833 			    (offset + length);
6834 	/*
6835 	 * after this, stripe_nr is the number of stripes on this
6836 	 * device we have to walk to find the data, and stripe_index is
6837 	 * the number of our device in the stripe array
6838 	 */
6839 	*num_stripes = 1;
6840 	stripe_index = 0;
6841 	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6842 			 BTRFS_BLOCK_GROUP_RAID10)) {
6843 		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6844 			sub_stripes = 1;
6845 		else
6846 			sub_stripes = map->sub_stripes;
6847 
6848 		factor = map->num_stripes / sub_stripes;
6849 		*num_stripes = min_t(u64, map->num_stripes,
6850 				    sub_stripes * stripe_cnt);
6851 		stripe_index = stripe_nr % factor;
6852 		stripe_nr /= factor;
6853 		stripe_index *= sub_stripes;
6854 
6855 		remaining_stripes = stripe_cnt % factor;
6856 		stripes_per_dev = stripe_cnt / factor;
6857 		last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
6858 	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6859 				BTRFS_BLOCK_GROUP_DUP)) {
6860 		*num_stripes = map->num_stripes;
6861 	} else {
6862 		stripe_index = stripe_nr % map->num_stripes;
6863 		stripe_nr /= map->num_stripes;
6864 	}
6865 
6866 	stripes = kzalloc_objs(*stripes, *num_stripes, GFP_NOFS);
6867 	if (!stripes) {
6868 		ret = -ENOMEM;
6869 		goto out_free_map;
6870 	}
6871 
6872 	for (i = 0; i < *num_stripes; i++) {
6873 		stripes[i].physical =
6874 			map->stripes[stripe_index].physical +
6875 			stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6876 		stripes[i].dev = map->stripes[stripe_index].dev;
6877 
6878 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6879 				 BTRFS_BLOCK_GROUP_RAID10)) {
6880 			stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6881 
6882 			if (i / sub_stripes < remaining_stripes)
6883 				stripes[i].length += BTRFS_STRIPE_LEN;
6884 
6885 			/*
6886 			 * Special for the first stripe and
6887 			 * the last stripe:
6888 			 *
6889 			 * |-------|...|-------|
6890 			 *     |----------|
6891 			 *    off     end_off
6892 			 */
6893 			if (i < sub_stripes)
6894 				stripes[i].length -= stripe_offset;
6895 
6896 			if (stripe_index >= last_stripe &&
6897 			    stripe_index <= (last_stripe +
6898 					     sub_stripes - 1))
6899 				stripes[i].length -= stripe_end_offset;
6900 
6901 			if (i == sub_stripes - 1)
6902 				stripe_offset = 0;
6903 		} else {
6904 			stripes[i].length = length;
6905 		}
6906 
6907 		stripe_index++;
6908 		if (stripe_index == map->num_stripes) {
6909 			stripe_index = 0;
6910 			stripe_nr++;
6911 		}
6912 	}
6913 
6914 	btrfs_free_chunk_map(map);
6915 	return stripes;
6916 out_free_map:
6917 	btrfs_free_chunk_map(map);
6918 	return ERR_PTR(ret);
6919 }
6920 
6921 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6922 {
6923 	struct btrfs_block_group *cache;
6924 	bool ret;
6925 
6926 	/* Non zoned filesystem does not use "to_copy" flag */
6927 	if (!btrfs_is_zoned(fs_info))
6928 		return false;
6929 
6930 	cache = btrfs_lookup_block_group(fs_info, logical);
6931 
6932 	ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6933 
6934 	btrfs_put_block_group(cache);
6935 	return ret;
6936 }
6937 
6938 static void handle_ops_on_dev_replace(struct btrfs_io_context *bioc,
6939 				      struct btrfs_dev_replace *dev_replace,
6940 				      u64 logical,
6941 				      struct btrfs_io_geometry *io_geom)
6942 {
6943 	u64 srcdev_devid = dev_replace->srcdev->devid;
6944 	/*
6945 	 * At this stage, num_stripes is still the real number of stripes,
6946 	 * excluding the duplicated stripes.
6947 	 */
6948 	int num_stripes = io_geom->num_stripes;
6949 	int max_errors = io_geom->max_errors;
6950 	int nr_extra_stripes = 0;
6951 	int i;
6952 
6953 	/*
6954 	 * A block group which has "to_copy" set will eventually be copied by
6955 	 * the dev-replace process. We can avoid cloning IO here.
6956 	 */
6957 	if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6958 		return;
6959 
6960 	/*
6961 	 * Duplicate the write operations while the dev-replace procedure is
6962 	 * running. Since the copying of the old disk to the new disk takes
6963 	 * place at run time while the filesystem is mounted writable, the
6964 	 * regular write operations to the old disk have to be duplicated to go
6965 	 * to the new disk as well.
6966 	 *
6967 	 * Note that device->missing is handled by the caller, and that the
6968 	 * write to the old disk is already set up in the stripes array.
6969 	 */
6970 	for (i = 0; i < num_stripes; i++) {
6971 		struct btrfs_io_stripe *old = &bioc->stripes[i];
6972 		struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6973 
6974 		if (old->dev->devid != srcdev_devid)
6975 			continue;
6976 
6977 		new->physical = old->physical;
6978 		new->dev = dev_replace->tgtdev;
6979 		if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6980 			bioc->replace_stripe_src = i;
6981 		nr_extra_stripes++;
6982 	}
6983 
6984 	/* We can only have at most 2 extra nr_stripes (for DUP). */
6985 	ASSERT(nr_extra_stripes <= 2, "nr_extra_stripes=%d", nr_extra_stripes);
6986 	/*
6987 	 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6988 	 * replace.
6989 	 * If we have 2 extra stripes, only choose the one with smaller physical.
6990 	 */
6991 	if (io_geom->op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6992 		struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6993 		struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6994 
6995 		/* Only DUP can have two extra stripes. */
6996 		ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP,
6997 		       "map_type=%llu", bioc->map_type);
6998 
6999 		/*
7000 		 * Swap the last stripe stripes and reduce @nr_extra_stripes.
7001 		 * The extra stripe would still be there, but won't be accessed.
7002 		 */
7003 		if (first->physical > second->physical) {
7004 			swap(second->physical, first->physical);
7005 			swap(second->dev, first->dev);
7006 			nr_extra_stripes--;
7007 		}
7008 	}
7009 
7010 	io_geom->num_stripes = num_stripes + nr_extra_stripes;
7011 	io_geom->max_errors = max_errors + nr_extra_stripes;
7012 	bioc->replace_nr_stripes = nr_extra_stripes;
7013 }
7014 
7015 static u64 btrfs_max_io_len(struct btrfs_chunk_map *map, u64 offset,
7016 			    struct btrfs_io_geometry *io_geom)
7017 {
7018 	/*
7019 	 * Stripe_nr is the stripe where this block falls.  stripe_offset is
7020 	 * the offset of this block in its stripe.
7021 	 */
7022 	io_geom->stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
7023 	io_geom->stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
7024 	ASSERT(io_geom->stripe_offset < U32_MAX,
7025 	       "stripe_offset=%llu", io_geom->stripe_offset);
7026 
7027 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
7028 		unsigned long full_stripe_len =
7029 			btrfs_stripe_nr_to_offset(nr_data_stripes(map));
7030 
7031 		/*
7032 		 * For full stripe start, we use previously calculated
7033 		 * @stripe_nr. Align it to nr_data_stripes, then multiply with
7034 		 * STRIPE_LEN.
7035 		 *
7036 		 * By this we can avoid u64 division completely.  And we have
7037 		 * to go rounddown(), not round_down(), as nr_data_stripes is
7038 		 * not ensured to be power of 2.
7039 		 */
7040 		io_geom->raid56_full_stripe_start = btrfs_stripe_nr_to_offset(
7041 			rounddown(io_geom->stripe_nr, nr_data_stripes(map)));
7042 
7043 		ASSERT(io_geom->raid56_full_stripe_start + full_stripe_len > offset,
7044 		       "raid56_full_stripe_start=%llu full_stripe_len=%lu offset=%llu",
7045 		       io_geom->raid56_full_stripe_start, full_stripe_len, offset);
7046 		ASSERT(io_geom->raid56_full_stripe_start <= offset,
7047 		       "raid56_full_stripe_start=%llu offset=%llu",
7048 		       io_geom->raid56_full_stripe_start, offset);
7049 		/*
7050 		 * For writes to RAID56, allow to write a full stripe set, but
7051 		 * no straddling of stripe sets.
7052 		 */
7053 		if (io_geom->op == BTRFS_MAP_WRITE)
7054 			return full_stripe_len - (offset - io_geom->raid56_full_stripe_start);
7055 	}
7056 
7057 	/*
7058 	 * For other RAID types and for RAID56 reads, allow a single stripe (on
7059 	 * a single disk).
7060 	 */
7061 	if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
7062 		return BTRFS_STRIPE_LEN - io_geom->stripe_offset;
7063 	return U64_MAX;
7064 }
7065 
7066 static int set_io_stripe(struct btrfs_fs_info *fs_info, u64 logical,
7067 			 u64 *length, struct btrfs_io_stripe *dst,
7068 			 struct btrfs_chunk_map *map,
7069 			 struct btrfs_io_geometry *io_geom)
7070 {
7071 	dst->dev = map->stripes[io_geom->stripe_index].dev;
7072 
7073 	if (io_geom->op == BTRFS_MAP_READ && io_geom->use_rst)
7074 		return btrfs_get_raid_extent_offset(fs_info, logical, length,
7075 						    map->type,
7076 						    io_geom->stripe_index, dst);
7077 
7078 	dst->physical = map->stripes[io_geom->stripe_index].physical +
7079 			io_geom->stripe_offset +
7080 			btrfs_stripe_nr_to_offset(io_geom->stripe_nr);
7081 	return 0;
7082 }
7083 
7084 static bool is_single_device_io(struct btrfs_fs_info *fs_info,
7085 				const struct btrfs_io_stripe *smap,
7086 				const struct btrfs_chunk_map *map,
7087 				int num_alloc_stripes,
7088 				struct btrfs_io_geometry *io_geom)
7089 {
7090 	if (!smap)
7091 		return false;
7092 
7093 	if (num_alloc_stripes != 1)
7094 		return false;
7095 
7096 	if (io_geom->use_rst && io_geom->op != BTRFS_MAP_READ)
7097 		return false;
7098 
7099 	if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && io_geom->mirror_num > 1)
7100 		return false;
7101 
7102 	return true;
7103 }
7104 
7105 static void map_blocks_raid0(const struct btrfs_chunk_map *map,
7106 			     struct btrfs_io_geometry *io_geom)
7107 {
7108 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
7109 	io_geom->stripe_nr /= map->num_stripes;
7110 	if (io_geom->op == BTRFS_MAP_READ)
7111 		io_geom->mirror_num = 1;
7112 }
7113 
7114 static void map_blocks_raid1(struct btrfs_fs_info *fs_info,
7115 			     struct btrfs_chunk_map *map,
7116 			     struct btrfs_io_geometry *io_geom,
7117 			     bool dev_replace_is_ongoing)
7118 {
7119 	if (io_geom->op != BTRFS_MAP_READ) {
7120 		io_geom->num_stripes = map->num_stripes;
7121 		return;
7122 	}
7123 
7124 	if (io_geom->mirror_num) {
7125 		io_geom->stripe_index = io_geom->mirror_num - 1;
7126 		return;
7127 	}
7128 
7129 	io_geom->stripe_index = find_live_mirror(fs_info, map, 0,
7130 						 dev_replace_is_ongoing);
7131 	io_geom->mirror_num = io_geom->stripe_index + 1;
7132 }
7133 
7134 static void map_blocks_dup(const struct btrfs_chunk_map *map,
7135 			   struct btrfs_io_geometry *io_geom)
7136 {
7137 	if (io_geom->op != BTRFS_MAP_READ) {
7138 		io_geom->num_stripes = map->num_stripes;
7139 		return;
7140 	}
7141 
7142 	if (io_geom->mirror_num) {
7143 		io_geom->stripe_index = io_geom->mirror_num - 1;
7144 		return;
7145 	}
7146 
7147 	io_geom->mirror_num = 1;
7148 }
7149 
7150 static void map_blocks_raid10(struct btrfs_fs_info *fs_info,
7151 			      struct btrfs_chunk_map *map,
7152 			      struct btrfs_io_geometry *io_geom,
7153 			      bool dev_replace_is_ongoing)
7154 {
7155 	u32 factor = map->num_stripes / map->sub_stripes;
7156 	int old_stripe_index;
7157 
7158 	io_geom->stripe_index = (io_geom->stripe_nr % factor) * map->sub_stripes;
7159 	io_geom->stripe_nr /= factor;
7160 
7161 	if (io_geom->op != BTRFS_MAP_READ) {
7162 		io_geom->num_stripes = map->sub_stripes;
7163 		return;
7164 	}
7165 
7166 	if (io_geom->mirror_num) {
7167 		io_geom->stripe_index += io_geom->mirror_num - 1;
7168 		return;
7169 	}
7170 
7171 	old_stripe_index = io_geom->stripe_index;
7172 	io_geom->stripe_index = find_live_mirror(fs_info, map,
7173 						 io_geom->stripe_index,
7174 						 dev_replace_is_ongoing);
7175 	io_geom->mirror_num = io_geom->stripe_index - old_stripe_index + 1;
7176 }
7177 
7178 static void map_blocks_raid56_write(struct btrfs_chunk_map *map,
7179 				    struct btrfs_io_geometry *io_geom,
7180 				    u64 logical, u64 *length)
7181 {
7182 	int data_stripes = nr_data_stripes(map);
7183 
7184 	/*
7185 	 * Needs full stripe mapping.
7186 	 *
7187 	 * Push stripe_nr back to the start of the full stripe For those cases
7188 	 * needing a full stripe, @stripe_nr is the full stripe number.
7189 	 *
7190 	 * Originally we go raid56_full_stripe_start / full_stripe_len, but
7191 	 * that can be expensive.  Here we just divide @stripe_nr with
7192 	 * @data_stripes.
7193 	 */
7194 	io_geom->stripe_nr /= data_stripes;
7195 
7196 	/* RAID[56] write or recovery. Return all stripes */
7197 	io_geom->num_stripes = map->num_stripes;
7198 	io_geom->max_errors = btrfs_chunk_max_errors(map);
7199 
7200 	/* Return the length to the full stripe end. */
7201 	*length = min(logical + *length,
7202 		      io_geom->raid56_full_stripe_start + map->start +
7203 		      btrfs_stripe_nr_to_offset(data_stripes)) -
7204 		logical;
7205 	io_geom->stripe_index = 0;
7206 	io_geom->stripe_offset = 0;
7207 }
7208 
7209 static void map_blocks_raid56_read(struct btrfs_chunk_map *map,
7210 				   struct btrfs_io_geometry *io_geom)
7211 {
7212 	int data_stripes = nr_data_stripes(map);
7213 
7214 	ASSERT(io_geom->mirror_num <= 1, "mirror_num=%d", io_geom->mirror_num);
7215 	/* Just grab the data stripe directly. */
7216 	io_geom->stripe_index = io_geom->stripe_nr % data_stripes;
7217 	io_geom->stripe_nr /= data_stripes;
7218 
7219 	/* We distribute the parity blocks across stripes. */
7220 	io_geom->stripe_index =
7221 		(io_geom->stripe_nr + io_geom->stripe_index) % map->num_stripes;
7222 
7223 	if (io_geom->op == BTRFS_MAP_READ && io_geom->mirror_num < 1)
7224 		io_geom->mirror_num = 1;
7225 }
7226 
7227 static void map_blocks_single(const struct btrfs_chunk_map *map,
7228 			      struct btrfs_io_geometry *io_geom)
7229 {
7230 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
7231 	io_geom->stripe_nr /= map->num_stripes;
7232 	io_geom->mirror_num = io_geom->stripe_index + 1;
7233 }
7234 
7235 /*
7236  * Map one logical range to one or more physical ranges.
7237  *
7238  * @length:		(Mandatory) mapped length of this run.
7239  *			One logical range can be split into different segments
7240  *			due to factors like zones and RAID0/5/6/10 stripe
7241  *			boundaries.
7242  *
7243  * @bioc_ret:		(Mandatory) returned btrfs_io_context structure.
7244  *			which has one or more physical ranges (btrfs_io_stripe)
7245  *			recorded inside.
7246  *			Caller should call btrfs_put_bioc() to free it after use.
7247  *
7248  * @smap:		(Optional) single physical range optimization.
7249  *			If the map request can be fulfilled by one single
7250  *			physical range, and this is parameter is not NULL,
7251  *			then @bioc_ret would be NULL, and @smap would be
7252  *			updated.
7253  *
7254  * @mirror_num_ret:	(Mandatory) returned mirror number if the original
7255  *			value is 0.
7256  *
7257  *			Mirror number 0 means to choose any live mirrors.
7258  *
7259  *			For non-RAID56 profiles, non-zero mirror_num means
7260  *			the Nth mirror. (e.g. mirror_num 1 means the first
7261  *			copy).
7262  *
7263  *			For RAID56 profile, mirror 1 means rebuild from P and
7264  *			the remaining data stripes.
7265  *
7266  *			For RAID6 profile, mirror > 2 means mark another
7267  *			data/P stripe error and rebuild from the remaining
7268  *			stripes..
7269  */
7270 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
7271 		    u64 logical, u64 *length,
7272 		    struct btrfs_io_context **bioc_ret,
7273 		    struct btrfs_io_stripe *smap, int *mirror_num_ret)
7274 {
7275 	struct btrfs_chunk_map *map;
7276 	struct btrfs_io_geometry io_geom = { 0 };
7277 	u64 map_offset;
7278 	int ret = 0;
7279 	int num_copies;
7280 	struct btrfs_io_context *bioc = NULL;
7281 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
7282 	bool dev_replace_is_ongoing = false;
7283 	u16 num_alloc_stripes;
7284 	u64 max_len;
7285 
7286 	ASSERT(bioc_ret);
7287 
7288 	io_geom.mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
7289 	io_geom.num_stripes = 1;
7290 	io_geom.stripe_index = 0;
7291 	io_geom.op = op;
7292 
7293 	map = btrfs_get_chunk_map(fs_info, logical, *length);
7294 	if (IS_ERR(map))
7295 		return PTR_ERR(map);
7296 
7297 	if (map->type & BTRFS_BLOCK_GROUP_REMAPPED) {
7298 		u64 new_logical = logical;
7299 
7300 		ret = btrfs_translate_remap(fs_info, &new_logical, length);
7301 		if (ret)
7302 			goto out;
7303 
7304 		if (new_logical != logical) {
7305 			btrfs_free_chunk_map(map);
7306 
7307 			map = btrfs_get_chunk_map(fs_info, new_logical, *length);
7308 			if (IS_ERR(map))
7309 				return PTR_ERR(map);
7310 
7311 			logical = new_logical;
7312 		}
7313 	}
7314 
7315 	num_copies = btrfs_chunk_map_num_copies(map);
7316 	if (io_geom.mirror_num > num_copies) {
7317 		ret = -EINVAL;
7318 		goto out;
7319 	}
7320 
7321 	map_offset = logical - map->start;
7322 	io_geom.raid56_full_stripe_start = (u64)-1;
7323 	max_len = btrfs_max_io_len(map, map_offset, &io_geom);
7324 	*length = min_t(u64, map->chunk_len - map_offset, max_len);
7325 	io_geom.use_rst = btrfs_need_stripe_tree_update(fs_info, map->type);
7326 
7327 	if (dev_replace->replace_task != current)
7328 		down_read(&dev_replace->rwsem);
7329 
7330 	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
7331 	/*
7332 	 * Hold the semaphore for read during the whole operation, write is
7333 	 * requested at commit time but must wait.
7334 	 */
7335 	if (!dev_replace_is_ongoing && dev_replace->replace_task != current)
7336 		up_read(&dev_replace->rwsem);
7337 
7338 	switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7339 	case BTRFS_BLOCK_GROUP_RAID0:
7340 		map_blocks_raid0(map, &io_geom);
7341 		break;
7342 	case BTRFS_BLOCK_GROUP_RAID1:
7343 	case BTRFS_BLOCK_GROUP_RAID1C3:
7344 	case BTRFS_BLOCK_GROUP_RAID1C4:
7345 		map_blocks_raid1(fs_info, map, &io_geom, dev_replace_is_ongoing);
7346 		break;
7347 	case BTRFS_BLOCK_GROUP_DUP:
7348 		map_blocks_dup(map, &io_geom);
7349 		break;
7350 	case BTRFS_BLOCK_GROUP_RAID10:
7351 		map_blocks_raid10(fs_info, map, &io_geom, dev_replace_is_ongoing);
7352 		break;
7353 	case BTRFS_BLOCK_GROUP_RAID5:
7354 	case BTRFS_BLOCK_GROUP_RAID6:
7355 		if (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)
7356 			map_blocks_raid56_write(map, &io_geom, logical, length);
7357 		else
7358 			map_blocks_raid56_read(map, &io_geom);
7359 		break;
7360 	default:
7361 		/*
7362 		 * After this, stripe_nr is the number of stripes on this
7363 		 * device we have to walk to find the data, and stripe_index is
7364 		 * the number of our device in the stripe array
7365 		 */
7366 		map_blocks_single(map, &io_geom);
7367 		break;
7368 	}
7369 	if (io_geom.stripe_index >= map->num_stripes) {
7370 		btrfs_crit(fs_info,
7371 			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
7372 			   io_geom.stripe_index, map->num_stripes);
7373 		ret = -EINVAL;
7374 		goto out;
7375 	}
7376 
7377 	num_alloc_stripes = io_geom.num_stripes;
7378 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
7379 	    op != BTRFS_MAP_READ)
7380 		/*
7381 		 * For replace case, we need to add extra stripes for extra
7382 		 * duplicated stripes.
7383 		 *
7384 		 * For both WRITE and GET_READ_MIRRORS, we may have at most
7385 		 * 2 more stripes (DUP types, otherwise 1).
7386 		 */
7387 		num_alloc_stripes += 2;
7388 
7389 	/*
7390 	 * If this I/O maps to a single device, try to return the device and
7391 	 * physical block information on the stack instead of allocating an
7392 	 * I/O context structure.
7393 	 */
7394 	if (is_single_device_io(fs_info, smap, map, num_alloc_stripes, &io_geom)) {
7395 		ret = set_io_stripe(fs_info, logical, length, smap, map, &io_geom);
7396 		if (mirror_num_ret)
7397 			*mirror_num_ret = io_geom.mirror_num;
7398 		*bioc_ret = NULL;
7399 		goto out;
7400 	}
7401 
7402 	bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
7403 	if (!bioc) {
7404 		ret = -ENOMEM;
7405 		goto out;
7406 	}
7407 	bioc->map_type = map->type;
7408 	bioc->use_rst = io_geom.use_rst;
7409 
7410 	/*
7411 	 * For RAID56 full map, we need to make sure the stripes[] follows the
7412 	 * rule that data stripes are all ordered, then followed with P and Q
7413 	 * (if we have).
7414 	 *
7415 	 * It's still mostly the same as other profiles, just with extra rotation.
7416 	 */
7417 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
7418 	    (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)) {
7419 		/*
7420 		 * For RAID56 @stripe_nr is already the number of full stripes
7421 		 * before us, which is also the rotation value (needs to modulo
7422 		 * with num_stripes).
7423 		 *
7424 		 * In this case, we just add @stripe_nr with @i, then do the
7425 		 * modulo, to reduce one modulo call.
7426 		 */
7427 		bioc->full_stripe_logical = map->start +
7428 			btrfs_stripe_nr_to_offset(io_geom.stripe_nr *
7429 						  nr_data_stripes(map));
7430 		for (int i = 0; i < io_geom.num_stripes; i++) {
7431 			struct btrfs_io_stripe *dst = &bioc->stripes[i];
7432 			u32 stripe_index;
7433 
7434 			stripe_index = (i + io_geom.stripe_nr) % io_geom.num_stripes;
7435 			dst->dev = map->stripes[stripe_index].dev;
7436 			dst->physical =
7437 				map->stripes[stripe_index].physical +
7438 				io_geom.stripe_offset +
7439 				btrfs_stripe_nr_to_offset(io_geom.stripe_nr);
7440 		}
7441 	} else {
7442 		/*
7443 		 * For all other non-RAID56 profiles, just copy the target
7444 		 * stripe into the bioc.
7445 		 */
7446 		for (int i = 0; i < io_geom.num_stripes; i++) {
7447 			ret = set_io_stripe(fs_info, logical, length,
7448 					    &bioc->stripes[i], map, &io_geom);
7449 			if (ret < 0)
7450 				break;
7451 			io_geom.stripe_index++;
7452 		}
7453 	}
7454 
7455 	if (ret) {
7456 		*bioc_ret = NULL;
7457 		btrfs_put_bioc(bioc);
7458 		goto out;
7459 	}
7460 
7461 	if (op != BTRFS_MAP_READ)
7462 		io_geom.max_errors = btrfs_chunk_max_errors(map);
7463 
7464 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
7465 	    op != BTRFS_MAP_READ) {
7466 		handle_ops_on_dev_replace(bioc, dev_replace, logical, &io_geom);
7467 	}
7468 
7469 	*bioc_ret = bioc;
7470 	bioc->num_stripes = io_geom.num_stripes;
7471 	bioc->max_errors = io_geom.max_errors;
7472 	bioc->mirror_num = io_geom.mirror_num;
7473 
7474 out:
7475 	if (dev_replace_is_ongoing && dev_replace->replace_task != current) {
7476 		lockdep_assert_held(&dev_replace->rwsem);
7477 		/* Unlock and let waiting writers proceed */
7478 		up_read(&dev_replace->rwsem);
7479 	}
7480 	btrfs_free_chunk_map(map);
7481 	return ret;
7482 }
7483 
7484 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
7485 				      const struct btrfs_fs_devices *fs_devices)
7486 {
7487 	if (args->fsid == NULL)
7488 		return true;
7489 	if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
7490 		return true;
7491 	return false;
7492 }
7493 
7494 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
7495 				  const struct btrfs_device *device)
7496 {
7497 	if (args->devt)
7498 		return device->devt == args->devt;
7499 	if (args->missing) {
7500 		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
7501 		    !device->bdev)
7502 			return true;
7503 		return false;
7504 	}
7505 
7506 	if (device->devid != args->devid)
7507 		return false;
7508 	if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
7509 		return false;
7510 	return true;
7511 }
7512 
7513 /*
7514  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
7515  * return NULL.
7516  *
7517  * If devid and uuid are both specified, the match must be exact, otherwise
7518  * only devid is used.
7519  */
7520 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
7521 				       const struct btrfs_dev_lookup_args *args)
7522 {
7523 	struct btrfs_device *device;
7524 	struct btrfs_fs_devices *seed_devs;
7525 
7526 	if (dev_args_match_fs_devices(args, fs_devices)) {
7527 		list_for_each_entry(device, &fs_devices->devices, dev_list) {
7528 			if (dev_args_match_device(args, device))
7529 				return device;
7530 		}
7531 	}
7532 
7533 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7534 		if (!dev_args_match_fs_devices(args, seed_devs))
7535 			continue;
7536 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7537 			if (dev_args_match_device(args, device))
7538 				return device;
7539 		}
7540 	}
7541 
7542 	return NULL;
7543 }
7544 
7545 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
7546 					    u64 devid, u8 *dev_uuid)
7547 {
7548 	struct btrfs_device *device;
7549 	unsigned int nofs_flag;
7550 
7551 	/*
7552 	 * We call this under the chunk_mutex, so we want to use NOFS for this
7553 	 * allocation, however we don't want to change btrfs_alloc_device() to
7554 	 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
7555 	 * places.
7556 	 */
7557 
7558 	nofs_flag = memalloc_nofs_save();
7559 	device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
7560 	memalloc_nofs_restore(nofs_flag);
7561 	if (IS_ERR(device))
7562 		return device;
7563 
7564 	list_add(&device->dev_list, &fs_devices->devices);
7565 	device->fs_devices = fs_devices;
7566 	fs_devices->num_devices++;
7567 
7568 	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7569 	fs_devices->missing_devices++;
7570 
7571 	return device;
7572 }
7573 
7574 /*
7575  * Allocate new device struct, set up devid and UUID.
7576  *
7577  * @fs_info:	used only for generating a new devid, can be NULL if
7578  *		devid is provided (i.e. @devid != NULL).
7579  * @devid:	a pointer to devid for this device.  If NULL a new devid
7580  *		is generated.
7581  * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
7582  *		is generated.
7583  * @path:	a pointer to device path if available, NULL otherwise.
7584  *
7585  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
7586  * on error.  Returned struct is not linked onto any lists and must be
7587  * destroyed with btrfs_free_device.
7588  */
7589 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
7590 					const u64 *devid, const u8 *uuid,
7591 					const char *path)
7592 {
7593 	struct btrfs_device *dev;
7594 	u64 tmp;
7595 
7596 	if (WARN_ON(!devid && !fs_info))
7597 		return ERR_PTR(-EINVAL);
7598 
7599 	dev = kzalloc_obj(*dev);
7600 	if (!dev)
7601 		return ERR_PTR(-ENOMEM);
7602 
7603 	INIT_LIST_HEAD(&dev->dev_list);
7604 	INIT_LIST_HEAD(&dev->dev_alloc_list);
7605 	INIT_LIST_HEAD(&dev->post_commit_list);
7606 
7607 	atomic_set(&dev->dev_stats_ccnt, 0);
7608 	btrfs_device_data_ordered_init(dev);
7609 	btrfs_extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
7610 
7611 	if (devid)
7612 		tmp = *devid;
7613 	else {
7614 		int ret;
7615 
7616 		ret = find_next_devid(fs_info, &tmp);
7617 		if (ret) {
7618 			btrfs_free_device(dev);
7619 			return ERR_PTR(ret);
7620 		}
7621 	}
7622 	dev->devid = tmp;
7623 
7624 	if (uuid)
7625 		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
7626 	else
7627 		generate_random_uuid(dev->uuid);
7628 
7629 	if (path) {
7630 		const char *name;
7631 
7632 		name = kstrdup(path, GFP_KERNEL);
7633 		if (!name) {
7634 			btrfs_free_device(dev);
7635 			return ERR_PTR(-ENOMEM);
7636 		}
7637 		rcu_assign_pointer(dev->name, name);
7638 	}
7639 
7640 	return dev;
7641 }
7642 
7643 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
7644 					u64 devid, u8 *uuid, bool error)
7645 {
7646 	if (error)
7647 		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
7648 			      devid, uuid);
7649 	else
7650 		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
7651 			      devid, uuid);
7652 }
7653 
7654 u64 btrfs_calc_stripe_length(const struct btrfs_chunk_map *map)
7655 {
7656 	const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
7657 
7658 	return div_u64(map->chunk_len, data_stripes);
7659 }
7660 
7661 #if BITS_PER_LONG == 32
7662 /*
7663  * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
7664  * can't be accessed on 32bit systems.
7665  *
7666  * This function do mount time check to reject the fs if it already has
7667  * metadata chunk beyond that limit.
7668  */
7669 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7670 				  u64 logical, u64 length, u64 type)
7671 {
7672 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7673 		return 0;
7674 
7675 	if (logical + length < MAX_LFS_FILESIZE)
7676 		return 0;
7677 
7678 	btrfs_err_32bit_limit(fs_info);
7679 	return -EOVERFLOW;
7680 }
7681 
7682 /*
7683  * This is to give early warning for any metadata chunk reaching
7684  * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7685  * Although we can still access the metadata, it's not going to be possible
7686  * once the limit is reached.
7687  */
7688 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7689 				  u64 logical, u64 length, u64 type)
7690 {
7691 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7692 		return;
7693 
7694 	if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7695 		return;
7696 
7697 	btrfs_warn_32bit_limit(fs_info);
7698 }
7699 #endif
7700 
7701 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7702 						  u64 devid, u8 *uuid)
7703 {
7704 	struct btrfs_device *dev;
7705 
7706 	if (!btrfs_test_opt(fs_info, DEGRADED)) {
7707 		btrfs_report_missing_device(fs_info, devid, uuid, true);
7708 		return ERR_PTR(-ENOENT);
7709 	}
7710 
7711 	dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7712 	if (IS_ERR(dev)) {
7713 		btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7714 			  devid, PTR_ERR(dev));
7715 		return dev;
7716 	}
7717 	btrfs_report_missing_device(fs_info, devid, uuid, false);
7718 
7719 	return dev;
7720 }
7721 
7722 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7723 			  struct btrfs_chunk *chunk)
7724 {
7725 	BTRFS_DEV_LOOKUP_ARGS(args);
7726 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7727 	struct btrfs_chunk_map *map;
7728 	u64 logical;
7729 	u64 length;
7730 	u64 devid;
7731 	u64 type;
7732 	u8 uuid[BTRFS_UUID_SIZE];
7733 	int index;
7734 	int num_stripes;
7735 	int ret;
7736 	int i;
7737 
7738 	logical = key->offset;
7739 	length = btrfs_chunk_length(leaf, chunk);
7740 	type = btrfs_chunk_type(leaf, chunk);
7741 	index = btrfs_bg_flags_to_raid_index(type);
7742 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7743 
7744 #if BITS_PER_LONG == 32
7745 	ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7746 	if (ret < 0)
7747 		return ret;
7748 	warn_32bit_meta_chunk(fs_info, logical, length, type);
7749 #endif
7750 
7751 	map = btrfs_find_chunk_map(fs_info, logical, 1);
7752 
7753 	/* already mapped? */
7754 	if (map && map->start <= logical && map->start + map->chunk_len > logical) {
7755 		btrfs_free_chunk_map(map);
7756 		return 0;
7757 	} else if (map) {
7758 		btrfs_free_chunk_map(map);
7759 	}
7760 
7761 	map = btrfs_alloc_chunk_map(num_stripes, GFP_NOFS);
7762 	if (!map)
7763 		return -ENOMEM;
7764 
7765 	map->start = logical;
7766 	map->chunk_len = length;
7767 	map->num_stripes = num_stripes;
7768 	map->on_disk_type = type;
7769 	/*
7770 	 * We can't use the sub_stripes value, as for profiles other than
7771 	 * RAID10, they may have 0 as sub_stripes for filesystems created by
7772 	 * older mkfs (<v5.4).
7773 	 * In that case, it can cause divide-by-zero errors later.
7774 	 * Since currently sub_stripes is fixed for each profile, let's
7775 	 * use the trusted value instead.
7776 	 */
7777 	map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7778 	map->verified_stripes = 0;
7779 	set_real_chunk_type(map);
7780 
7781 	if (num_stripes > 0)
7782 		map->stripe_size = btrfs_calc_stripe_length(map);
7783 	else
7784 		map->stripe_size = 0;
7785 
7786 	for (i = 0; i < num_stripes; i++) {
7787 		map->stripes[i].physical =
7788 			btrfs_stripe_offset_nr(leaf, chunk, i);
7789 		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7790 		args.devid = devid;
7791 		read_extent_buffer(leaf, uuid, (unsigned long)
7792 				   btrfs_stripe_dev_uuid_nr(chunk, i),
7793 				   BTRFS_UUID_SIZE);
7794 		args.uuid = uuid;
7795 		map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7796 		if (!map->stripes[i].dev) {
7797 			map->stripes[i].dev = handle_missing_device(fs_info,
7798 								    devid, uuid);
7799 			if (IS_ERR(map->stripes[i].dev)) {
7800 				ret = PTR_ERR(map->stripes[i].dev);
7801 				btrfs_free_chunk_map(map);
7802 				return ret;
7803 			}
7804 		}
7805 
7806 		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7807 				&(map->stripes[i].dev->dev_state));
7808 	}
7809 
7810 	ret = btrfs_add_chunk_map(fs_info, map);
7811 	if (ret < 0) {
7812 		btrfs_err(fs_info,
7813 			  "failed to add chunk map, start=%llu len=%llu: %d",
7814 			  map->start, map->chunk_len, ret);
7815 		btrfs_free_chunk_map(map);
7816 	}
7817 
7818 	return ret;
7819 }
7820 
7821 static void fill_device_from_item(struct extent_buffer *leaf,
7822 				 struct btrfs_dev_item *dev_item,
7823 				 struct btrfs_device *device)
7824 {
7825 	unsigned long ptr;
7826 
7827 	device->devid = btrfs_device_id(leaf, dev_item);
7828 	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7829 	device->total_bytes = device->disk_total_bytes;
7830 	device->commit_total_bytes = device->disk_total_bytes;
7831 	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7832 	device->commit_bytes_used = device->bytes_used;
7833 	device->type = btrfs_device_type(leaf, dev_item);
7834 	device->io_align = btrfs_device_io_align(leaf, dev_item);
7835 	device->io_width = btrfs_device_io_width(leaf, dev_item);
7836 	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7837 	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7838 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7839 
7840 	ptr = btrfs_device_uuid(dev_item);
7841 	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7842 }
7843 
7844 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7845 						  u8 *fsid)
7846 {
7847 	struct btrfs_fs_devices *fs_devices;
7848 	int ret;
7849 
7850 	lockdep_assert_held(&uuid_mutex);
7851 	ASSERT(fsid);
7852 
7853 	/* This will match only for multi-device seed fs */
7854 	list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7855 		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7856 			return fs_devices;
7857 
7858 
7859 	fs_devices = find_fsid(fsid, NULL);
7860 	if (!fs_devices) {
7861 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7862 			btrfs_err(fs_info,
7863 		"failed to find fsid %pU when attempting to open seed devices",
7864 				  fsid);
7865 			return ERR_PTR(-ENOENT);
7866 		}
7867 
7868 		fs_devices = alloc_fs_devices(fsid);
7869 		if (IS_ERR(fs_devices))
7870 			return fs_devices;
7871 
7872 		fs_devices->seeding = true;
7873 		fs_devices->opened = 1;
7874 		list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7875 		return fs_devices;
7876 	}
7877 
7878 	/*
7879 	 * Upon first call for a seed fs fsid, just create a private copy of the
7880 	 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7881 	 */
7882 	fs_devices = clone_fs_devices(fs_devices);
7883 	if (IS_ERR(fs_devices))
7884 		return fs_devices;
7885 
7886 	ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->sb);
7887 	if (ret) {
7888 		free_fs_devices(fs_devices);
7889 		return ERR_PTR(ret);
7890 	}
7891 
7892 	if (!fs_devices->seeding) {
7893 		close_fs_devices(fs_devices);
7894 		free_fs_devices(fs_devices);
7895 		return ERR_PTR(-EINVAL);
7896 	}
7897 
7898 	list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7899 
7900 	return fs_devices;
7901 }
7902 
7903 static int read_one_dev(struct extent_buffer *leaf,
7904 			struct btrfs_dev_item *dev_item)
7905 {
7906 	BTRFS_DEV_LOOKUP_ARGS(args);
7907 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7908 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7909 	struct btrfs_device *device;
7910 	u64 devid;
7911 	u8 fs_uuid[BTRFS_FSID_SIZE];
7912 	u8 dev_uuid[BTRFS_UUID_SIZE];
7913 
7914 	devid = btrfs_device_id(leaf, dev_item);
7915 	args.devid = devid;
7916 	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7917 			   BTRFS_UUID_SIZE);
7918 	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7919 			   BTRFS_FSID_SIZE);
7920 	args.uuid = dev_uuid;
7921 	args.fsid = fs_uuid;
7922 
7923 	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7924 		fs_devices = open_seed_devices(fs_info, fs_uuid);
7925 		if (IS_ERR(fs_devices))
7926 			return PTR_ERR(fs_devices);
7927 	}
7928 
7929 	device = btrfs_find_device(fs_info->fs_devices, &args);
7930 	if (!device) {
7931 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7932 			btrfs_report_missing_device(fs_info, devid,
7933 							dev_uuid, true);
7934 			return -ENOENT;
7935 		}
7936 
7937 		device = add_missing_dev(fs_devices, devid, dev_uuid);
7938 		if (IS_ERR(device)) {
7939 			btrfs_err(fs_info,
7940 				"failed to add missing dev %llu: %ld",
7941 				devid, PTR_ERR(device));
7942 			return PTR_ERR(device);
7943 		}
7944 		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7945 	} else {
7946 		if (!device->bdev) {
7947 			if (!btrfs_test_opt(fs_info, DEGRADED)) {
7948 				btrfs_report_missing_device(fs_info,
7949 						devid, dev_uuid, true);
7950 				return -ENOENT;
7951 			}
7952 			btrfs_report_missing_device(fs_info, devid,
7953 							dev_uuid, false);
7954 		}
7955 
7956 		if (!device->bdev &&
7957 		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7958 			/*
7959 			 * this happens when a device that was properly setup
7960 			 * in the device info lists suddenly goes bad.
7961 			 * device->bdev is NULL, and so we have to set
7962 			 * device->missing to one here
7963 			 */
7964 			device->fs_devices->missing_devices++;
7965 			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7966 		}
7967 
7968 		/* Move the device to its own fs_devices */
7969 		if (device->fs_devices != fs_devices) {
7970 			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7971 							&device->dev_state));
7972 
7973 			list_move(&device->dev_list, &fs_devices->devices);
7974 			device->fs_devices->num_devices--;
7975 			fs_devices->num_devices++;
7976 
7977 			device->fs_devices->missing_devices--;
7978 			fs_devices->missing_devices++;
7979 
7980 			device->fs_devices = fs_devices;
7981 		}
7982 	}
7983 
7984 	if (device->fs_devices != fs_info->fs_devices) {
7985 		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7986 		if (device->generation !=
7987 		    btrfs_device_generation(leaf, dev_item))
7988 			return -EINVAL;
7989 	}
7990 
7991 	fill_device_from_item(leaf, dev_item, device);
7992 	if (device->bdev) {
7993 		u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7994 
7995 		if (device->total_bytes > max_total_bytes) {
7996 			btrfs_err(fs_info,
7997 			"device total_bytes should be at most %llu but found %llu",
7998 				  max_total_bytes, device->total_bytes);
7999 			return -EINVAL;
8000 		}
8001 	}
8002 	set_bit(BTRFS_DEV_STATE_ITEM_FOUND, &device->dev_state);
8003 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
8004 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
8005 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
8006 		device->fs_devices->total_rw_bytes += device->total_bytes;
8007 		atomic64_add(device->total_bytes - device->bytes_used,
8008 				&fs_info->free_chunk_space);
8009 	}
8010 
8011 	return 0;
8012 }
8013 
8014 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
8015 {
8016 	struct btrfs_super_block *super_copy = fs_info->super_copy;
8017 	struct extent_buffer *sb;
8018 	u8 *array_ptr;
8019 	unsigned long sb_array_offset;
8020 	int ret = 0;
8021 	u32 array_size;
8022 	u32 cur_offset;
8023 	struct btrfs_key key;
8024 
8025 	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
8026 
8027 	/*
8028 	 * We allocated a dummy extent, just to use extent buffer accessors.
8029 	 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
8030 	 * that's fine, we will not go beyond system chunk array anyway.
8031 	 */
8032 	sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
8033 	if (!sb)
8034 		return -ENOMEM;
8035 	set_extent_buffer_uptodate(sb);
8036 
8037 	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
8038 	array_size = btrfs_super_sys_array_size(super_copy);
8039 
8040 	array_ptr = super_copy->sys_chunk_array;
8041 	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
8042 	cur_offset = 0;
8043 
8044 	while (cur_offset < array_size) {
8045 		struct btrfs_chunk *chunk;
8046 		struct btrfs_disk_key *disk_key = (struct btrfs_disk_key *)array_ptr;
8047 		u32 len = sizeof(*disk_key);
8048 
8049 		/*
8050 		 * The sys_chunk_array has been already verified at super block
8051 		 * read time.  Only do ASSERT()s for basic checks.
8052 		 */
8053 		ASSERT(cur_offset + len <= array_size);
8054 
8055 		btrfs_disk_key_to_cpu(&key, disk_key);
8056 
8057 		array_ptr += len;
8058 		sb_array_offset += len;
8059 		cur_offset += len;
8060 
8061 		ASSERT(key.type == BTRFS_CHUNK_ITEM_KEY);
8062 
8063 		chunk = (struct btrfs_chunk *)sb_array_offset;
8064 		ASSERT(btrfs_chunk_type(sb, chunk) & BTRFS_BLOCK_GROUP_SYSTEM);
8065 
8066 		len = btrfs_chunk_item_size(btrfs_chunk_num_stripes(sb, chunk));
8067 
8068 		ASSERT(cur_offset + len <= array_size);
8069 
8070 		ret = read_one_chunk(&key, sb, chunk);
8071 		if (ret)
8072 			break;
8073 
8074 		array_ptr += len;
8075 		sb_array_offset += len;
8076 		cur_offset += len;
8077 	}
8078 	clear_extent_buffer_uptodate(sb);
8079 	free_extent_buffer_stale(sb);
8080 	return ret;
8081 }
8082 
8083 /*
8084  * Check if all chunks in the fs are OK for read-write degraded mount
8085  *
8086  * If the @failing_dev is specified, it's accounted as missing.
8087  *
8088  * Return true if all chunks meet the minimal RW mount requirements.
8089  * Return false if any chunk doesn't meet the minimal RW mount requirements.
8090  */
8091 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
8092 					struct btrfs_device *failing_dev)
8093 {
8094 	struct btrfs_chunk_map *map;
8095 	u64 next_start;
8096 	bool ret = true;
8097 
8098 	map = btrfs_find_chunk_map(fs_info, 0, U64_MAX);
8099 	/* No chunk at all? Return false anyway */
8100 	if (!map)
8101 		return false;
8102 
8103 	while (map) {
8104 		int missing = 0;
8105 		int max_tolerated;
8106 		int i;
8107 
8108 		max_tolerated =
8109 			btrfs_get_num_tolerated_disk_barrier_failures(
8110 					map->type);
8111 		for (i = 0; i < map->num_stripes; i++) {
8112 			struct btrfs_device *dev = map->stripes[i].dev;
8113 
8114 			if (!dev || !dev->bdev ||
8115 			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
8116 			    test_bit(BTRFS_DEV_STATE_FLUSH_FAILED, &dev->dev_state))
8117 				missing++;
8118 			else if (failing_dev && failing_dev == dev)
8119 				missing++;
8120 		}
8121 		if (missing > max_tolerated) {
8122 			if (!failing_dev)
8123 				btrfs_warn(fs_info,
8124 	"chunk %llu missing %d devices, max tolerance is %d for writable mount",
8125 				   map->start, missing, max_tolerated);
8126 			btrfs_free_chunk_map(map);
8127 			return false;
8128 		}
8129 		next_start = map->start + map->chunk_len;
8130 		btrfs_free_chunk_map(map);
8131 
8132 		map = btrfs_find_chunk_map(fs_info, next_start, U64_MAX - next_start);
8133 	}
8134 
8135 	return ret;
8136 }
8137 
8138 static void readahead_tree_node_children(struct extent_buffer *node)
8139 {
8140 	int i;
8141 	const int nr_items = btrfs_header_nritems(node);
8142 
8143 	for (i = 0; i < nr_items; i++)
8144 		btrfs_readahead_node_child(node, i);
8145 }
8146 
8147 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
8148 {
8149 	struct btrfs_root *root = fs_info->chunk_root;
8150 	BTRFS_PATH_AUTO_FREE(path);
8151 	struct extent_buffer *leaf;
8152 	struct btrfs_key key;
8153 	struct btrfs_key found_key;
8154 	int ret;
8155 	int slot;
8156 	int iter_ret = 0;
8157 	u64 total_dev = 0;
8158 	u64 last_ra_node = 0;
8159 
8160 	path = btrfs_alloc_path();
8161 	if (!path)
8162 		return -ENOMEM;
8163 
8164 	/*
8165 	 * uuid_mutex is needed only if we are mounting a sprout FS
8166 	 * otherwise we don't need it.
8167 	 */
8168 	mutex_lock(&uuid_mutex);
8169 
8170 	/*
8171 	 * It is possible for mount and umount to race in such a way that
8172 	 * we execute this code path, but open_fs_devices failed to clear
8173 	 * total_rw_bytes. We certainly want it cleared before reading the
8174 	 * device items, so clear it here.
8175 	 */
8176 	fs_info->fs_devices->total_rw_bytes = 0;
8177 
8178 	/*
8179 	 * Lockdep complains about possible circular locking dependency between
8180 	 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
8181 	 * used for freeze protection of a fs (struct super_block.s_writers),
8182 	 * which we take when starting a transaction, and extent buffers of the
8183 	 * chunk tree if we call read_one_dev() while holding a lock on an
8184 	 * extent buffer of the chunk tree. Since we are mounting the filesystem
8185 	 * and at this point there can't be any concurrent task modifying the
8186 	 * chunk tree, to keep it simple, just skip locking on the chunk tree.
8187 	 */
8188 	ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
8189 	path->skip_locking = true;
8190 
8191 	/*
8192 	 * Read all device items, and then all the chunk items. All
8193 	 * device items are found before any chunk item (their object id
8194 	 * is smaller than the lowest possible object id for a chunk
8195 	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
8196 	 */
8197 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
8198 	key.type = 0;
8199 	key.offset = 0;
8200 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
8201 		struct extent_buffer *node = path->nodes[1];
8202 
8203 		leaf = path->nodes[0];
8204 		slot = path->slots[0];
8205 
8206 		if (node) {
8207 			if (last_ra_node != node->start) {
8208 				readahead_tree_node_children(node);
8209 				last_ra_node = node->start;
8210 			}
8211 		}
8212 		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
8213 			struct btrfs_dev_item *dev_item;
8214 			dev_item = btrfs_item_ptr(leaf, slot,
8215 						  struct btrfs_dev_item);
8216 			ret = read_one_dev(leaf, dev_item);
8217 			if (ret)
8218 				goto error;
8219 			total_dev++;
8220 		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
8221 			struct btrfs_chunk *chunk;
8222 
8223 			/*
8224 			 * We are only called at mount time, so no need to take
8225 			 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
8226 			 * we always lock first fs_info->chunk_mutex before
8227 			 * acquiring any locks on the chunk tree. This is a
8228 			 * requirement for chunk allocation, see the comment on
8229 			 * top of btrfs_chunk_alloc() for details.
8230 			 */
8231 			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
8232 			ret = read_one_chunk(&found_key, leaf, chunk);
8233 			if (ret)
8234 				goto error;
8235 		}
8236 	}
8237 	/* Catch error found during iteration */
8238 	if (iter_ret < 0) {
8239 		ret = iter_ret;
8240 		goto error;
8241 	}
8242 
8243 	/*
8244 	 * After loading chunk tree, we've got all device information,
8245 	 * do another round of validation checks.
8246 	 */
8247 	if (total_dev != fs_info->fs_devices->total_devices) {
8248 		btrfs_warn(fs_info,
8249 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
8250 			  btrfs_super_num_devices(fs_info->super_copy),
8251 			  total_dev);
8252 		fs_info->fs_devices->total_devices = total_dev;
8253 		btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
8254 	}
8255 	if (btrfs_super_total_bytes(fs_info->super_copy) <
8256 	    fs_info->fs_devices->total_rw_bytes) {
8257 		btrfs_err(fs_info,
8258 	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
8259 			  btrfs_super_total_bytes(fs_info->super_copy),
8260 			  fs_info->fs_devices->total_rw_bytes);
8261 		ret = -EINVAL;
8262 		goto error;
8263 	}
8264 	ret = 0;
8265 error:
8266 	mutex_unlock(&uuid_mutex);
8267 	return ret;
8268 }
8269 
8270 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
8271 {
8272 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
8273 	struct btrfs_device *device;
8274 	int ret = 0;
8275 
8276 	mutex_lock(&fs_devices->device_list_mutex);
8277 	list_for_each_entry(device, &fs_devices->devices, dev_list)
8278 		device->fs_info = fs_info;
8279 
8280 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
8281 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
8282 			device->fs_info = fs_info;
8283 			ret = btrfs_get_dev_zone_info(device, false);
8284 			if (ret)
8285 				break;
8286 		}
8287 
8288 		seed_devs->fs_info = fs_info;
8289 	}
8290 	mutex_unlock(&fs_devices->device_list_mutex);
8291 
8292 	return ret;
8293 }
8294 
8295 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
8296 				 const struct btrfs_dev_stats_item *ptr,
8297 				 int index)
8298 {
8299 	u64 val;
8300 
8301 	read_extent_buffer(eb, &val,
8302 			   offsetof(struct btrfs_dev_stats_item, values) +
8303 			    ((unsigned long)ptr) + (index * sizeof(u64)),
8304 			   sizeof(val));
8305 	return val;
8306 }
8307 
8308 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
8309 				      struct btrfs_dev_stats_item *ptr,
8310 				      int index, u64 val)
8311 {
8312 	write_extent_buffer(eb, &val,
8313 			    offsetof(struct btrfs_dev_stats_item, values) +
8314 			     ((unsigned long)ptr) + (index * sizeof(u64)),
8315 			    sizeof(val));
8316 }
8317 
8318 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
8319 				       struct btrfs_path *path)
8320 {
8321 	struct btrfs_dev_stats_item *ptr;
8322 	struct extent_buffer *eb;
8323 	struct btrfs_key key;
8324 	int item_size;
8325 	int i, ret, slot;
8326 
8327 	if (!device->fs_info->dev_root)
8328 		return 0;
8329 
8330 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
8331 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
8332 	key.offset = device->devid;
8333 	ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
8334 	if (ret) {
8335 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8336 			btrfs_dev_stat_set(device, i, 0);
8337 		device->dev_stats_valid = 1;
8338 		btrfs_release_path(path);
8339 		return ret < 0 ? ret : 0;
8340 	}
8341 	slot = path->slots[0];
8342 	eb = path->nodes[0];
8343 	item_size = btrfs_item_size(eb, slot);
8344 
8345 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
8346 
8347 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
8348 		if (item_size >= (1 + i) * sizeof(__le64))
8349 			atomic_set(device->dev_stat_values + i,
8350 				   btrfs_dev_stats_value(eb, ptr, i));
8351 		else
8352 			btrfs_dev_stat_set(device, i, 0);
8353 	}
8354 
8355 	device->dev_stats_valid = 1;
8356 	btrfs_dev_stat_print_on_load(device);
8357 	btrfs_release_path(path);
8358 
8359 	return 0;
8360 }
8361 
8362 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
8363 {
8364 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
8365 	struct btrfs_device *device;
8366 	BTRFS_PATH_AUTO_FREE(path);
8367 	int ret = 0;
8368 
8369 	path = btrfs_alloc_path();
8370 	if (!path)
8371 		return -ENOMEM;
8372 
8373 	mutex_lock(&fs_devices->device_list_mutex);
8374 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
8375 		ret = btrfs_device_init_dev_stats(device, path);
8376 		if (ret)
8377 			goto out;
8378 	}
8379 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
8380 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
8381 			ret = btrfs_device_init_dev_stats(device, path);
8382 			if (ret)
8383 				goto out;
8384 		}
8385 	}
8386 out:
8387 	mutex_unlock(&fs_devices->device_list_mutex);
8388 	return ret;
8389 }
8390 
8391 int btrfs_init_writeback_bio_size(struct btrfs_fs_info *fs_info)
8392 {
8393 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8394 	struct btrfs_device *device;
8395 	u32 writeback_bio_size = fs_info->sectorsize;
8396 
8397 	mutex_lock(&fs_devices->device_list_mutex);
8398 	/*
8399 	 * Let's take maximum over optimal request sizes for all devices. For
8400 	 * RAID profiles writeback will submit stripe (64k) sized bios anyway
8401 	 * so our value doesn't matter and for simple profiles this is a good
8402 	 * approximation of sensible IO chunking.
8403 	 */
8404 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
8405 		struct request_queue *queue;
8406 		unsigned int io_opt;
8407 
8408 		if (!device->bdev || test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
8409 			continue;
8410 		queue = bdev_get_queue(device->bdev);
8411 		io_opt = queue_io_opt(queue) ? :
8412 				queue_max_sectors(queue) << SECTOR_SHIFT;
8413 		writeback_bio_size = max(writeback_bio_size, io_opt);
8414 	}
8415 	mutex_unlock(&fs_devices->device_list_mutex);
8416 
8417 	fs_info->writeback_bio_size = writeback_bio_size;
8418 
8419 	return 0;
8420 }
8421 
8422 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
8423 				struct btrfs_device *device)
8424 {
8425 	struct btrfs_fs_info *fs_info = trans->fs_info;
8426 	struct btrfs_root *dev_root = fs_info->dev_root;
8427 	BTRFS_PATH_AUTO_FREE(path);
8428 	struct btrfs_key key;
8429 	struct extent_buffer *eb;
8430 	struct btrfs_dev_stats_item *ptr;
8431 	int ret;
8432 	int i;
8433 
8434 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
8435 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
8436 	key.offset = device->devid;
8437 
8438 	path = btrfs_alloc_path();
8439 	if (!path)
8440 		return -ENOMEM;
8441 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
8442 	if (ret < 0) {
8443 		btrfs_warn(fs_info,
8444 			"error %d while searching for dev_stats item for device %s",
8445 				  ret, btrfs_dev_name(device));
8446 		return ret;
8447 	}
8448 
8449 	if (ret == 0 &&
8450 	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
8451 		/* need to delete old one and insert a new one */
8452 		ret = btrfs_del_item(trans, dev_root, path);
8453 		if (ret != 0) {
8454 			btrfs_warn(fs_info,
8455 				"delete too small dev_stats item for device %s failed %d",
8456 					  btrfs_dev_name(device), ret);
8457 			return ret;
8458 		}
8459 		ret = 1;
8460 	}
8461 
8462 	if (ret == 1) {
8463 		/* need to insert a new item */
8464 		btrfs_release_path(path);
8465 		ret = btrfs_insert_empty_item(trans, dev_root, path,
8466 					      &key, sizeof(*ptr));
8467 		if (ret < 0) {
8468 			btrfs_warn(fs_info,
8469 				"insert dev_stats item for device %s failed %d",
8470 				btrfs_dev_name(device), ret);
8471 			return ret;
8472 		}
8473 	}
8474 
8475 	eb = path->nodes[0];
8476 	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
8477 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8478 		btrfs_set_dev_stats_value(eb, ptr, i,
8479 					  btrfs_dev_stat_read(device, i));
8480 	return ret;
8481 }
8482 
8483 /*
8484  * called from commit_transaction. Writes all changed device stats to disk.
8485  */
8486 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
8487 {
8488 	struct btrfs_fs_info *fs_info = trans->fs_info;
8489 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8490 	struct btrfs_device *device;
8491 	int stats_cnt;
8492 	int ret = 0;
8493 	bool need_update_dev_stats = false;
8494 
8495 	/*
8496 	 * Do an initial pass using RCU to see if we need to update any dev
8497 	 * stats item. This is to avoid taking the device_list_mutex which is
8498 	 * acquired by the fitrim operation and can take a while since it does
8499 	 * discard operations while holding that mutex. Most of the time, if
8500 	 * we are on a healthy filesystem, we don't have new stat updates, so
8501 	 * this avoids blocking on that mutex, which is specially important
8502 	 * because we are called during the critical section of a transaction
8503 	 * commit, therefore blocking new transactions from starting while
8504 	 * discard is running.
8505 	 *
8506 	 * Also note that adding/removing devices also requires starting a
8507 	 * transaction, and since we are called from the critical section of a
8508 	 * transaction commit, no one can be concurrently adding or removing a
8509 	 * device.
8510 	 */
8511 	rcu_read_lock();
8512 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
8513 		if (device->dev_stats_valid &&
8514 		    atomic_read(&device->dev_stats_ccnt) != 0) {
8515 			need_update_dev_stats = true;
8516 			break;
8517 		}
8518 	}
8519 	rcu_read_unlock();
8520 
8521 	if (!need_update_dev_stats)
8522 		return 0;
8523 
8524 	mutex_lock(&fs_devices->device_list_mutex);
8525 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
8526 		stats_cnt = atomic_read(&device->dev_stats_ccnt);
8527 		if (!device->dev_stats_valid || stats_cnt == 0)
8528 			continue;
8529 
8530 
8531 		/*
8532 		 * There is a LOAD-LOAD control dependency between the value of
8533 		 * dev_stats_ccnt and updating the on-disk values which requires
8534 		 * reading the in-memory counters. Such control dependencies
8535 		 * require explicit read memory barriers.
8536 		 *
8537 		 * This memory barriers pairs with smp_mb__before_atomic in
8538 		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
8539 		 * barrier implied by atomic_xchg in
8540 		 * btrfs_dev_stats_read_and_reset
8541 		 */
8542 		smp_rmb();
8543 
8544 		ret = update_dev_stat_item(trans, device);
8545 		if (ret)
8546 			break;
8547 		atomic_sub(stats_cnt, &device->dev_stats_ccnt);
8548 	}
8549 	mutex_unlock(&fs_devices->device_list_mutex);
8550 
8551 	return ret;
8552 }
8553 
8554 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
8555 {
8556 	btrfs_dev_stat_inc(dev, index);
8557 
8558 	if (!dev->dev_stats_valid)
8559 		return;
8560 	btrfs_err_rl(dev->fs_info,
8561 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8562 			   btrfs_dev_name(dev),
8563 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8564 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8565 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8566 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8567 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8568 }
8569 
8570 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
8571 {
8572 	int i;
8573 
8574 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8575 		if (btrfs_dev_stat_read(dev, i) != 0)
8576 			break;
8577 	if (i == BTRFS_DEV_STAT_VALUES_MAX)
8578 		return; /* all values == 0, suppress message */
8579 
8580 	btrfs_info(dev->fs_info,
8581 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8582 	       btrfs_dev_name(dev),
8583 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8584 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8585 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8586 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8587 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8588 }
8589 
8590 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
8591 			struct btrfs_ioctl_get_dev_stats *stats)
8592 {
8593 	BTRFS_DEV_LOOKUP_ARGS(args);
8594 	struct btrfs_device *dev;
8595 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8596 	int i;
8597 
8598 	mutex_lock(&fs_devices->device_list_mutex);
8599 	args.devid = stats->devid;
8600 	dev = btrfs_find_device(fs_info->fs_devices, &args);
8601 	mutex_unlock(&fs_devices->device_list_mutex);
8602 
8603 	if (!dev) {
8604 		btrfs_warn(fs_info, "get dev_stats failed, device not found");
8605 		return -ENODEV;
8606 	} else if (!dev->dev_stats_valid) {
8607 		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
8608 		return -ENODEV;
8609 	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
8610 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
8611 			if (stats->nr_items > i)
8612 				stats->values[i] =
8613 					btrfs_dev_stat_read_and_reset(dev, i);
8614 			else
8615 				btrfs_dev_stat_set(dev, i, 0);
8616 		}
8617 		btrfs_info(fs_info, "device stats zeroed by %s (%d)",
8618 			   current->comm, task_pid_nr(current));
8619 	} else {
8620 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8621 			if (stats->nr_items > i)
8622 				stats->values[i] = btrfs_dev_stat_read(dev, i);
8623 	}
8624 	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
8625 		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
8626 	return 0;
8627 }
8628 
8629 /*
8630  * Update the size and bytes used for each device where it changed.  This is
8631  * delayed since we would otherwise get errors while writing out the
8632  * superblocks.
8633  *
8634  * Must be invoked during transaction commit.
8635  */
8636 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
8637 {
8638 	struct btrfs_device *curr, *next;
8639 
8640 	ASSERT(trans->state == TRANS_STATE_COMMIT_DOING, "state=%d" , trans->state);
8641 
8642 	if (list_empty(&trans->dev_update_list))
8643 		return;
8644 
8645 	/*
8646 	 * We don't need the device_list_mutex here.  This list is owned by the
8647 	 * transaction and the transaction must complete before the device is
8648 	 * released.
8649 	 */
8650 	mutex_lock(&trans->fs_info->chunk_mutex);
8651 	list_for_each_entry_safe(curr, next, &trans->dev_update_list,
8652 				 post_commit_list) {
8653 		list_del_init(&curr->post_commit_list);
8654 		curr->commit_total_bytes = curr->disk_total_bytes;
8655 		curr->commit_bytes_used = curr->bytes_used;
8656 	}
8657 	mutex_unlock(&trans->fs_info->chunk_mutex);
8658 }
8659 
8660 /*
8661  * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
8662  */
8663 int btrfs_bg_type_to_factor(u64 flags)
8664 {
8665 	const int index = btrfs_bg_flags_to_raid_index(flags);
8666 
8667 	return btrfs_raid_array[index].ncopies;
8668 }
8669 
8670 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
8671 				 u64 chunk_offset, u64 devid,
8672 				 u64 physical_offset, u64 physical_len)
8673 {
8674 	struct btrfs_dev_lookup_args args = { .devid = devid };
8675 	struct btrfs_chunk_map *map;
8676 	struct btrfs_device *dev;
8677 	u64 stripe_len;
8678 	bool found = false;
8679 	int ret = 0;
8680 	int i;
8681 
8682 	map = btrfs_find_chunk_map(fs_info, chunk_offset, 1);
8683 	if (unlikely(!map)) {
8684 		btrfs_err(fs_info,
8685 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
8686 			  physical_offset, devid);
8687 		ret = -EUCLEAN;
8688 		goto out;
8689 	}
8690 
8691 	stripe_len = btrfs_calc_stripe_length(map);
8692 	if (unlikely(physical_len != stripe_len)) {
8693 		btrfs_err(fs_info,
8694 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8695 			  physical_offset, devid, map->start, physical_len,
8696 			  stripe_len);
8697 		ret = -EUCLEAN;
8698 		goto out;
8699 	}
8700 
8701 	/*
8702 	 * Very old mkfs.btrfs (before v4.15) will not respect the reserved
8703 	 * space. Although kernel can handle it without problem, better to warn
8704 	 * the users.
8705 	 */
8706 	if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
8707 		btrfs_warn(fs_info,
8708 		"devid %llu physical %llu len %llu inside the reserved space",
8709 			   devid, physical_offset, physical_len);
8710 
8711 	for (i = 0; i < map->num_stripes; i++) {
8712 		if (unlikely(map->stripes[i].dev->devid == devid &&
8713 			     map->stripes[i].physical == physical_offset)) {
8714 			found = true;
8715 			if (map->verified_stripes >= map->num_stripes) {
8716 				btrfs_err(fs_info,
8717 				"too many dev extents for chunk %llu found",
8718 					  map->start);
8719 				ret = -EUCLEAN;
8720 				goto out;
8721 			}
8722 			map->verified_stripes++;
8723 			break;
8724 		}
8725 	}
8726 	if (unlikely(!found)) {
8727 		btrfs_err(fs_info,
8728 	"dev extent physical offset %llu devid %llu has no corresponding chunk",
8729 			physical_offset, devid);
8730 		ret = -EUCLEAN;
8731 	}
8732 
8733 	/* Make sure no dev extent is beyond device boundary */
8734 	dev = btrfs_find_device(fs_info->fs_devices, &args);
8735 	if (unlikely(!dev)) {
8736 		btrfs_err(fs_info, "failed to find devid %llu", devid);
8737 		ret = -EUCLEAN;
8738 		goto out;
8739 	}
8740 
8741 	if (unlikely(physical_offset + physical_len > dev->disk_total_bytes)) {
8742 		btrfs_err(fs_info,
8743 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8744 			  devid, physical_offset, physical_len,
8745 			  dev->disk_total_bytes);
8746 		ret = -EUCLEAN;
8747 		goto out;
8748 	}
8749 
8750 	if (dev->zone_info) {
8751 		u64 zone_size = dev->zone_info->zone_size;
8752 
8753 		if (unlikely(!IS_ALIGNED(physical_offset, zone_size) ||
8754 			     !IS_ALIGNED(physical_len, zone_size))) {
8755 			btrfs_err(fs_info,
8756 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8757 				  devid, physical_offset, physical_len);
8758 			ret = -EUCLEAN;
8759 			goto out;
8760 		}
8761 	}
8762 
8763 out:
8764 	btrfs_free_chunk_map(map);
8765 	return ret;
8766 }
8767 
8768 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8769 {
8770 	struct rb_node *node;
8771 	int ret = 0;
8772 
8773 	read_lock(&fs_info->mapping_tree_lock);
8774 	for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) {
8775 		struct btrfs_chunk_map *map;
8776 
8777 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
8778 		if (unlikely(map->num_stripes != map->verified_stripes)) {
8779 			btrfs_err(fs_info,
8780 			"chunk %llu has missing dev extent, have %d expect %d",
8781 				  map->start, map->verified_stripes, map->num_stripes);
8782 			ret = -EUCLEAN;
8783 			goto out;
8784 		}
8785 	}
8786 out:
8787 	read_unlock(&fs_info->mapping_tree_lock);
8788 	return ret;
8789 }
8790 
8791 /*
8792  * Ensure that all dev extents are mapped to correct chunk, otherwise
8793  * later chunk allocation/free would cause unexpected behavior.
8794  *
8795  * NOTE: This will iterate through the whole device tree, which should be of
8796  * the same size level as the chunk tree.  This slightly increases mount time.
8797  */
8798 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8799 {
8800 	BTRFS_PATH_AUTO_FREE(path);
8801 	struct btrfs_root *root = fs_info->dev_root;
8802 	struct btrfs_key key;
8803 	u64 prev_devid = 0;
8804 	u64 prev_dev_ext_end = 0;
8805 	int ret = 0;
8806 
8807 	/*
8808 	 * We don't have a dev_root because we mounted with ignorebadroots and
8809 	 * failed to load the root, so we want to skip the verification in this
8810 	 * case for sure.
8811 	 *
8812 	 * However if the dev root is fine, but the tree itself is corrupted
8813 	 * we'd still fail to mount.  This verification is only to make sure
8814 	 * writes can happen safely, so instead just bypass this check
8815 	 * completely in the case of IGNOREBADROOTS.
8816 	 */
8817 	if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8818 		return 0;
8819 
8820 	key.objectid = 1;
8821 	key.type = BTRFS_DEV_EXTENT_KEY;
8822 	key.offset = 0;
8823 
8824 	path = btrfs_alloc_path();
8825 	if (!path)
8826 		return -ENOMEM;
8827 
8828 	path->reada = READA_FORWARD_ALWAYS;
8829 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8830 	if (ret < 0)
8831 		return ret;
8832 
8833 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8834 		ret = btrfs_next_leaf(root, path);
8835 		if (ret < 0)
8836 			return ret;
8837 		/* No dev extents at all? Not good */
8838 		if (unlikely(ret > 0))
8839 			return -EUCLEAN;
8840 	}
8841 	while (1) {
8842 		struct extent_buffer *leaf = path->nodes[0];
8843 		struct btrfs_dev_extent *dext;
8844 		int slot = path->slots[0];
8845 		u64 chunk_offset;
8846 		u64 physical_offset;
8847 		u64 physical_len;
8848 		u64 devid;
8849 
8850 		btrfs_item_key_to_cpu(leaf, &key, slot);
8851 		if (key.type != BTRFS_DEV_EXTENT_KEY)
8852 			break;
8853 		devid = key.objectid;
8854 		physical_offset = key.offset;
8855 
8856 		dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8857 		chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8858 		physical_len = btrfs_dev_extent_length(leaf, dext);
8859 
8860 		/* Check if this dev extent overlaps with the previous one */
8861 		if (unlikely(devid == prev_devid && physical_offset < prev_dev_ext_end)) {
8862 			btrfs_err(fs_info,
8863 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8864 				  devid, physical_offset, prev_dev_ext_end);
8865 			return -EUCLEAN;
8866 		}
8867 
8868 		ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8869 					    physical_offset, physical_len);
8870 		if (ret < 0)
8871 			return ret;
8872 		prev_devid = devid;
8873 		prev_dev_ext_end = physical_offset + physical_len;
8874 
8875 		ret = btrfs_next_item(root, path);
8876 		if (ret < 0)
8877 			return ret;
8878 		if (ret > 0) {
8879 			ret = 0;
8880 			break;
8881 		}
8882 	}
8883 
8884 	/* Ensure all chunks have corresponding dev extents */
8885 	ret = verify_chunk_dev_extent_mapping(fs_info);
8886 	if (ret < 0)
8887 		return ret;
8888 
8889 	mutex_lock(&fs_info->chunk_mutex);
8890 	btrfs_update_per_profile_avail(fs_info);
8891 	mutex_unlock(&fs_info->chunk_mutex);
8892 	return 0;
8893 }
8894 
8895 /*
8896  * Ensure that all devices registered in the fs have their device items in the
8897  * chunk tree.
8898  *
8899  * Return true if unexpected device is found.
8900  * Return false otherwise.
8901  */
8902 bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info)
8903 {
8904 	struct btrfs_fs_devices *seed_devs;
8905 	struct btrfs_device *dev;
8906 	bool ret = false;
8907 
8908 	mutex_lock(&uuid_mutex);
8909 	list_for_each_entry(dev, &fs_info->fs_devices->devices, dev_list) {
8910 		/*
8911 		 * Replace target dev item (devid 0) is not inserted into chunk tree.
8912 		 * So skip the DEV_STATE_ITEM check.
8913 		 */
8914 		if (dev->devid != BTRFS_DEV_REPLACE_DEVID &&
8915 		    !test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8916 			btrfs_err(fs_info,
8917 			"devid %llu path %s is registered but not found in chunk tree",
8918 				  dev->devid, btrfs_dev_name(dev));
8919 			ret = true;
8920 		}
8921 	}
8922 	list_for_each_entry(seed_devs, &fs_info->fs_devices->seed_list, seed_list) {
8923 		list_for_each_entry(dev, &seed_devs->devices, dev_list) {
8924 			if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8925 				btrfs_err(fs_info,
8926 			"devid %llu path %s is registered but not found in chunk tree",
8927 					  dev->devid, btrfs_dev_name(dev));
8928 				ret = true;
8929 			}
8930 		}
8931 	}
8932 	mutex_unlock(&uuid_mutex);
8933 	if (ret)
8934 		btrfs_err(fs_info,
8935 "remove the above devices or use 'btrfs device scan --forget <dev>' to unregister them before mount");
8936 	return ret;
8937 }
8938 
8939 /*
8940  * Check whether the given block group or device is pinned by any inode being
8941  * used as a swapfile.
8942  */
8943 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8944 {
8945 	struct btrfs_swapfile_pin *sp;
8946 	struct rb_node *node;
8947 
8948 	spin_lock(&fs_info->swapfile_pins_lock);
8949 	node = fs_info->swapfile_pins.rb_node;
8950 	while (node) {
8951 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8952 		if (ptr < sp->ptr)
8953 			node = node->rb_left;
8954 		else if (ptr > sp->ptr)
8955 			node = node->rb_right;
8956 		else
8957 			break;
8958 	}
8959 	spin_unlock(&fs_info->swapfile_pins_lock);
8960 	return node != NULL;
8961 }
8962 
8963 static int relocating_repair_kthread(void *data)
8964 {
8965 	struct btrfs_block_group *cache = data;
8966 	struct btrfs_fs_info *fs_info = cache->fs_info;
8967 	u64 target;
8968 	int ret = 0;
8969 
8970 	target = cache->start;
8971 	btrfs_put_block_group(cache);
8972 
8973 	guard(super_write)(fs_info->sb);
8974 
8975 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8976 		btrfs_info(fs_info,
8977 			   "zoned: skip relocating block group %llu to repair: EBUSY",
8978 			   target);
8979 		return -EBUSY;
8980 	}
8981 
8982 	mutex_lock(&fs_info->reclaim_bgs_lock);
8983 
8984 	/* Ensure block group still exists */
8985 	cache = btrfs_lookup_block_group(fs_info, target);
8986 	if (!cache)
8987 		goto out;
8988 
8989 	if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8990 		goto out;
8991 
8992 	ret = btrfs_may_alloc_data_chunk(fs_info, target);
8993 	if (ret < 0)
8994 		goto out;
8995 
8996 	btrfs_info(fs_info,
8997 		   "zoned: relocating block group %llu to repair IO failure",
8998 		   target);
8999 	ret = btrfs_relocate_chunk(fs_info, target, true);
9000 
9001 out:
9002 	if (cache)
9003 		btrfs_put_block_group(cache);
9004 	mutex_unlock(&fs_info->reclaim_bgs_lock);
9005 	btrfs_exclop_finish(fs_info);
9006 
9007 	return ret;
9008 }
9009 
9010 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
9011 {
9012 	struct btrfs_block_group *cache;
9013 	struct task_struct *task;
9014 
9015 	if (!btrfs_is_zoned(fs_info))
9016 		return false;
9017 
9018 	/* Do not attempt to repair in degraded state */
9019 	if (btrfs_test_opt(fs_info, DEGRADED))
9020 		return true;
9021 
9022 	cache = btrfs_lookup_block_group(fs_info, logical);
9023 	if (!cache)
9024 		return true;
9025 
9026 	if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
9027 		btrfs_put_block_group(cache);
9028 		return true;
9029 	}
9030 
9031 	task = kthread_run(relocating_repair_kthread, cache, "btrfs-relocating-repair");
9032 	if (IS_ERR(task))
9033 		btrfs_put_block_group(cache);
9034 
9035 	return true;
9036 }
9037 
9038 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
9039 				    struct btrfs_io_stripe *smap,
9040 				    u64 logical)
9041 {
9042 	int data_stripes = nr_bioc_data_stripes(bioc);
9043 	int i;
9044 
9045 	for (i = 0; i < data_stripes; i++) {
9046 		u64 stripe_start = bioc->full_stripe_logical +
9047 				   btrfs_stripe_nr_to_offset(i);
9048 
9049 		if (logical >= stripe_start &&
9050 		    logical < stripe_start + BTRFS_STRIPE_LEN)
9051 			break;
9052 	}
9053 	ASSERT(i < data_stripes, "i=%d data_stripes=%d", i, data_stripes);
9054 	smap->dev = bioc->stripes[i].dev;
9055 	smap->physical = bioc->stripes[i].physical +
9056 			((logical - bioc->full_stripe_logical) &
9057 			 BTRFS_STRIPE_LEN_MASK);
9058 }
9059 
9060 /*
9061  * Map a repair write into a single device.
9062  *
9063  * A repair write is triggered by read time repair or scrub, which would only
9064  * update the contents of a single device.
9065  * Not update any other mirrors nor go through RMW path.
9066  *
9067  * Callers should ensure:
9068  *
9069  * - Call btrfs_bio_counter_inc_blocked() first
9070  * - The range does not cross stripe boundary
9071  * - Has a valid @mirror_num passed in.
9072  */
9073 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
9074 			   struct btrfs_io_stripe *smap, u64 logical,
9075 			   u32 length, int mirror_num)
9076 {
9077 	struct btrfs_io_context *bioc = NULL;
9078 	u64 map_length = length;
9079 	int mirror_ret = mirror_num;
9080 	int ret;
9081 
9082 	ASSERT(mirror_num > 0, "mirror_num=%d", mirror_num);
9083 
9084 	ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
9085 			      &bioc, smap, &mirror_ret);
9086 	if (ret < 0)
9087 		return ret;
9088 
9089 	/* The map range should not cross stripe boundary. */
9090 	ASSERT(map_length >= length, "map_length=%llu length=%u", map_length, length);
9091 
9092 	/* Already mapped to single stripe. */
9093 	if (!bioc)
9094 		goto out;
9095 
9096 	/* Map the RAID56 multi-stripe writes to a single one. */
9097 	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
9098 		map_raid56_repair_block(bioc, smap, logical);
9099 		goto out;
9100 	}
9101 
9102 	ASSERT(mirror_num <= bioc->num_stripes,
9103 	       "mirror_num=%d num_stripes=%d", mirror_num,  bioc->num_stripes);
9104 	smap->dev = bioc->stripes[mirror_num - 1].dev;
9105 	smap->physical = bioc->stripes[mirror_num - 1].physical;
9106 out:
9107 	btrfs_put_bioc(bioc);
9108 	ASSERT(smap->dev);
9109 	return 0;
9110 }
9111