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