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