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