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