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