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