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