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