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