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