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