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