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