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