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