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