xref: /openbmc/linux/fs/btrfs/volumes.c (revision 2bbc72f1)
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,
253 			     u64 logical, u64 *length,
254 			     struct btrfs_io_context **bioc_ret,
255 			     int mirror_num, 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);
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 	atomic_set(&bioc->error, 0);
5902 	refcount_set(&bioc->refs, 1);
5903 
5904 	bioc->fs_info = fs_info;
5905 	bioc->tgtdev_map = (int *)(bioc->stripes + total_stripes);
5906 	bioc->raid_map = (u64 *)(bioc->tgtdev_map + real_stripes);
5907 
5908 	return bioc;
5909 }
5910 
5911 void btrfs_get_bioc(struct btrfs_io_context *bioc)
5912 {
5913 	WARN_ON(!refcount_read(&bioc->refs));
5914 	refcount_inc(&bioc->refs);
5915 }
5916 
5917 void btrfs_put_bioc(struct btrfs_io_context *bioc)
5918 {
5919 	if (!bioc)
5920 		return;
5921 	if (refcount_dec_and_test(&bioc->refs))
5922 		kfree(bioc);
5923 }
5924 
5925 /*
5926  * Please note that, discard won't be sent to target device of device
5927  * replace.
5928  */
5929 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
5930 					       u64 logical, u64 *length_ret,
5931 					       u32 *num_stripes)
5932 {
5933 	struct extent_map *em;
5934 	struct map_lookup *map;
5935 	struct btrfs_discard_stripe *stripes;
5936 	u64 length = *length_ret;
5937 	u64 offset;
5938 	u64 stripe_nr;
5939 	u64 stripe_nr_end;
5940 	u64 stripe_end_offset;
5941 	u64 stripe_cnt;
5942 	u64 stripe_len;
5943 	u64 stripe_offset;
5944 	u32 stripe_index;
5945 	u32 factor = 0;
5946 	u32 sub_stripes = 0;
5947 	u64 stripes_per_dev = 0;
5948 	u32 remaining_stripes = 0;
5949 	u32 last_stripe = 0;
5950 	int ret;
5951 	int i;
5952 
5953 	em = btrfs_get_chunk_map(fs_info, logical, length);
5954 	if (IS_ERR(em))
5955 		return ERR_CAST(em);
5956 
5957 	map = em->map_lookup;
5958 
5959 	/* we don't discard raid56 yet */
5960 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5961 		ret = -EOPNOTSUPP;
5962 		goto out_free_map;
5963 }
5964 
5965 	offset = logical - em->start;
5966 	length = min_t(u64, em->start + em->len - logical, length);
5967 	*length_ret = length;
5968 
5969 	stripe_len = map->stripe_len;
5970 	/*
5971 	 * stripe_nr counts the total number of stripes we have to stride
5972 	 * to get to this block
5973 	 */
5974 	stripe_nr = div64_u64(offset, stripe_len);
5975 
5976 	/* stripe_offset is the offset of this block in its stripe */
5977 	stripe_offset = offset - stripe_nr * stripe_len;
5978 
5979 	stripe_nr_end = round_up(offset + length, map->stripe_len);
5980 	stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5981 	stripe_cnt = stripe_nr_end - stripe_nr;
5982 	stripe_end_offset = stripe_nr_end * map->stripe_len -
5983 			    (offset + length);
5984 	/*
5985 	 * after this, stripe_nr is the number of stripes on this
5986 	 * device we have to walk to find the data, and stripe_index is
5987 	 * the number of our device in the stripe array
5988 	 */
5989 	*num_stripes = 1;
5990 	stripe_index = 0;
5991 	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5992 			 BTRFS_BLOCK_GROUP_RAID10)) {
5993 		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5994 			sub_stripes = 1;
5995 		else
5996 			sub_stripes = map->sub_stripes;
5997 
5998 		factor = map->num_stripes / sub_stripes;
5999 		*num_stripes = min_t(u64, map->num_stripes,
6000 				    sub_stripes * stripe_cnt);
6001 		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6002 		stripe_index *= sub_stripes;
6003 		stripes_per_dev = div_u64_rem(stripe_cnt, factor,
6004 					      &remaining_stripes);
6005 		div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
6006 		last_stripe *= sub_stripes;
6007 	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6008 				BTRFS_BLOCK_GROUP_DUP)) {
6009 		*num_stripes = map->num_stripes;
6010 	} else {
6011 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6012 					&stripe_index);
6013 	}
6014 
6015 	stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
6016 	if (!stripes) {
6017 		ret = -ENOMEM;
6018 		goto out_free_map;
6019 	}
6020 
6021 	for (i = 0; i < *num_stripes; i++) {
6022 		stripes[i].physical =
6023 			map->stripes[stripe_index].physical +
6024 			stripe_offset + stripe_nr * map->stripe_len;
6025 		stripes[i].dev = map->stripes[stripe_index].dev;
6026 
6027 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6028 				 BTRFS_BLOCK_GROUP_RAID10)) {
6029 			stripes[i].length = stripes_per_dev * map->stripe_len;
6030 
6031 			if (i / sub_stripes < remaining_stripes)
6032 				stripes[i].length += map->stripe_len;
6033 
6034 			/*
6035 			 * Special for the first stripe and
6036 			 * the last stripe:
6037 			 *
6038 			 * |-------|...|-------|
6039 			 *     |----------|
6040 			 *    off     end_off
6041 			 */
6042 			if (i < sub_stripes)
6043 				stripes[i].length -= stripe_offset;
6044 
6045 			if (stripe_index >= last_stripe &&
6046 			    stripe_index <= (last_stripe +
6047 					     sub_stripes - 1))
6048 				stripes[i].length -= stripe_end_offset;
6049 
6050 			if (i == sub_stripes - 1)
6051 				stripe_offset = 0;
6052 		} else {
6053 			stripes[i].length = length;
6054 		}
6055 
6056 		stripe_index++;
6057 		if (stripe_index == map->num_stripes) {
6058 			stripe_index = 0;
6059 			stripe_nr++;
6060 		}
6061 	}
6062 
6063 	free_extent_map(em);
6064 	return stripes;
6065 out_free_map:
6066 	free_extent_map(em);
6067 	return ERR_PTR(ret);
6068 }
6069 
6070 /*
6071  * In dev-replace case, for repair case (that's the only case where the mirror
6072  * is selected explicitly when calling btrfs_map_block), blocks left of the
6073  * left cursor can also be read from the target drive.
6074  *
6075  * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
6076  * array of stripes.
6077  * For READ, it also needs to be supported using the same mirror number.
6078  *
6079  * If the requested block is not left of the left cursor, EIO is returned. This
6080  * can happen because btrfs_num_copies() returns one more in the dev-replace
6081  * case.
6082  */
6083 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
6084 					 u64 logical, u64 length,
6085 					 u64 srcdev_devid, int *mirror_num,
6086 					 u64 *physical)
6087 {
6088 	struct btrfs_io_context *bioc = NULL;
6089 	int num_stripes;
6090 	int index_srcdev = 0;
6091 	int found = 0;
6092 	u64 physical_of_found = 0;
6093 	int i;
6094 	int ret = 0;
6095 
6096 	ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
6097 				logical, &length, &bioc, 0, 0);
6098 	if (ret) {
6099 		ASSERT(bioc == NULL);
6100 		return ret;
6101 	}
6102 
6103 	num_stripes = bioc->num_stripes;
6104 	if (*mirror_num > num_stripes) {
6105 		/*
6106 		 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
6107 		 * that means that the requested area is not left of the left
6108 		 * cursor
6109 		 */
6110 		btrfs_put_bioc(bioc);
6111 		return -EIO;
6112 	}
6113 
6114 	/*
6115 	 * process the rest of the function using the mirror_num of the source
6116 	 * drive. Therefore look it up first.  At the end, patch the device
6117 	 * pointer to the one of the target drive.
6118 	 */
6119 	for (i = 0; i < num_stripes; i++) {
6120 		if (bioc->stripes[i].dev->devid != srcdev_devid)
6121 			continue;
6122 
6123 		/*
6124 		 * In case of DUP, in order to keep it simple, only add the
6125 		 * mirror with the lowest physical address
6126 		 */
6127 		if (found &&
6128 		    physical_of_found <= bioc->stripes[i].physical)
6129 			continue;
6130 
6131 		index_srcdev = i;
6132 		found = 1;
6133 		physical_of_found = bioc->stripes[i].physical;
6134 	}
6135 
6136 	btrfs_put_bioc(bioc);
6137 
6138 	ASSERT(found);
6139 	if (!found)
6140 		return -EIO;
6141 
6142 	*mirror_num = index_srcdev + 1;
6143 	*physical = physical_of_found;
6144 	return ret;
6145 }
6146 
6147 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6148 {
6149 	struct btrfs_block_group *cache;
6150 	bool ret;
6151 
6152 	/* Non zoned filesystem does not use "to_copy" flag */
6153 	if (!btrfs_is_zoned(fs_info))
6154 		return false;
6155 
6156 	cache = btrfs_lookup_block_group(fs_info, logical);
6157 
6158 	ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6159 
6160 	btrfs_put_block_group(cache);
6161 	return ret;
6162 }
6163 
6164 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
6165 				      struct btrfs_io_context **bioc_ret,
6166 				      struct btrfs_dev_replace *dev_replace,
6167 				      u64 logical,
6168 				      int *num_stripes_ret, int *max_errors_ret)
6169 {
6170 	struct btrfs_io_context *bioc = *bioc_ret;
6171 	u64 srcdev_devid = dev_replace->srcdev->devid;
6172 	int tgtdev_indexes = 0;
6173 	int num_stripes = *num_stripes_ret;
6174 	int max_errors = *max_errors_ret;
6175 	int i;
6176 
6177 	if (op == BTRFS_MAP_WRITE) {
6178 		int index_where_to_add;
6179 
6180 		/*
6181 		 * A block group which have "to_copy" set will eventually
6182 		 * copied by dev-replace process. We can avoid cloning IO here.
6183 		 */
6184 		if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6185 			return;
6186 
6187 		/*
6188 		 * duplicate the write operations while the dev replace
6189 		 * procedure is running. Since the copying of the old disk to
6190 		 * the new disk takes place at run time while the filesystem is
6191 		 * mounted writable, the regular write operations to the old
6192 		 * disk have to be duplicated to go to the new disk as well.
6193 		 *
6194 		 * Note that device->missing is handled by the caller, and that
6195 		 * the write to the old disk is already set up in the stripes
6196 		 * array.
6197 		 */
6198 		index_where_to_add = num_stripes;
6199 		for (i = 0; i < num_stripes; i++) {
6200 			if (bioc->stripes[i].dev->devid == srcdev_devid) {
6201 				/* write to new disk, too */
6202 				struct btrfs_io_stripe *new =
6203 					bioc->stripes + index_where_to_add;
6204 				struct btrfs_io_stripe *old =
6205 					bioc->stripes + i;
6206 
6207 				new->physical = old->physical;
6208 				new->dev = dev_replace->tgtdev;
6209 				bioc->tgtdev_map[i] = index_where_to_add;
6210 				index_where_to_add++;
6211 				max_errors++;
6212 				tgtdev_indexes++;
6213 			}
6214 		}
6215 		num_stripes = index_where_to_add;
6216 	} else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
6217 		int index_srcdev = 0;
6218 		int found = 0;
6219 		u64 physical_of_found = 0;
6220 
6221 		/*
6222 		 * During the dev-replace procedure, the target drive can also
6223 		 * be used to read data in case it is needed to repair a corrupt
6224 		 * block elsewhere. This is possible if the requested area is
6225 		 * left of the left cursor. In this area, the target drive is a
6226 		 * full copy of the source drive.
6227 		 */
6228 		for (i = 0; i < num_stripes; i++) {
6229 			if (bioc->stripes[i].dev->devid == srcdev_devid) {
6230 				/*
6231 				 * In case of DUP, in order to keep it simple,
6232 				 * only add the mirror with the lowest physical
6233 				 * address
6234 				 */
6235 				if (found &&
6236 				    physical_of_found <= bioc->stripes[i].physical)
6237 					continue;
6238 				index_srcdev = i;
6239 				found = 1;
6240 				physical_of_found = bioc->stripes[i].physical;
6241 			}
6242 		}
6243 		if (found) {
6244 			struct btrfs_io_stripe *tgtdev_stripe =
6245 				bioc->stripes + num_stripes;
6246 
6247 			tgtdev_stripe->physical = physical_of_found;
6248 			tgtdev_stripe->dev = dev_replace->tgtdev;
6249 			bioc->tgtdev_map[index_srcdev] = num_stripes;
6250 
6251 			tgtdev_indexes++;
6252 			num_stripes++;
6253 		}
6254 	}
6255 
6256 	*num_stripes_ret = num_stripes;
6257 	*max_errors_ret = max_errors;
6258 	bioc->num_tgtdevs = tgtdev_indexes;
6259 	*bioc_ret = bioc;
6260 }
6261 
6262 static bool need_full_stripe(enum btrfs_map_op op)
6263 {
6264 	return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
6265 }
6266 
6267 /*
6268  * Calculate the geometry of a particular (address, len) tuple. This
6269  * information is used to calculate how big a particular bio can get before it
6270  * straddles a stripe.
6271  *
6272  * @fs_info: the filesystem
6273  * @em:      mapping containing the logical extent
6274  * @op:      type of operation - write or read
6275  * @logical: address that we want to figure out the geometry of
6276  * @io_geom: pointer used to return values
6277  *
6278  * Returns < 0 in case a chunk for the given logical address cannot be found,
6279  * usually shouldn't happen unless @logical is corrupted, 0 otherwise.
6280  */
6281 int btrfs_get_io_geometry(struct btrfs_fs_info *fs_info, struct extent_map *em,
6282 			  enum btrfs_map_op op, u64 logical,
6283 			  struct btrfs_io_geometry *io_geom)
6284 {
6285 	struct map_lookup *map;
6286 	u64 len;
6287 	u64 offset;
6288 	u64 stripe_offset;
6289 	u64 stripe_nr;
6290 	u32 stripe_len;
6291 	u64 raid56_full_stripe_start = (u64)-1;
6292 	int data_stripes;
6293 
6294 	ASSERT(op != BTRFS_MAP_DISCARD);
6295 
6296 	map = em->map_lookup;
6297 	/* Offset of this logical address in the chunk */
6298 	offset = logical - em->start;
6299 	/* Len of a stripe in a chunk */
6300 	stripe_len = map->stripe_len;
6301 	/*
6302 	 * Stripe_nr is where this block falls in
6303 	 * stripe_offset is the offset of this block in its stripe.
6304 	 */
6305 	stripe_nr = div64_u64_rem(offset, stripe_len, &stripe_offset);
6306 	ASSERT(stripe_offset < U32_MAX);
6307 
6308 	data_stripes = nr_data_stripes(map);
6309 
6310 	/* Only stripe based profiles needs to check against stripe length. */
6311 	if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK) {
6312 		u64 max_len = stripe_len - stripe_offset;
6313 
6314 		/*
6315 		 * In case of raid56, we need to know the stripe aligned start
6316 		 */
6317 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6318 			unsigned long full_stripe_len = stripe_len * data_stripes;
6319 			raid56_full_stripe_start = offset;
6320 
6321 			/*
6322 			 * Allow a write of a full stripe, but make sure we
6323 			 * don't allow straddling of stripes
6324 			 */
6325 			raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
6326 					full_stripe_len);
6327 			raid56_full_stripe_start *= full_stripe_len;
6328 
6329 			/*
6330 			 * For writes to RAID[56], allow a full stripeset across
6331 			 * all disks. For other RAID types and for RAID[56]
6332 			 * reads, just allow a single stripe (on a single disk).
6333 			 */
6334 			if (op == BTRFS_MAP_WRITE) {
6335 				max_len = stripe_len * data_stripes -
6336 					  (offset - raid56_full_stripe_start);
6337 			}
6338 		}
6339 		len = min_t(u64, em->len - offset, max_len);
6340 	} else {
6341 		len = em->len - offset;
6342 	}
6343 
6344 	io_geom->len = len;
6345 	io_geom->offset = offset;
6346 	io_geom->stripe_len = stripe_len;
6347 	io_geom->stripe_nr = stripe_nr;
6348 	io_geom->stripe_offset = stripe_offset;
6349 	io_geom->raid56_stripe_offset = raid56_full_stripe_start;
6350 
6351 	return 0;
6352 }
6353 
6354 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
6355 			     enum btrfs_map_op op,
6356 			     u64 logical, u64 *length,
6357 			     struct btrfs_io_context **bioc_ret,
6358 			     int mirror_num, int need_raid_map)
6359 {
6360 	struct extent_map *em;
6361 	struct map_lookup *map;
6362 	u64 stripe_offset;
6363 	u64 stripe_nr;
6364 	u64 stripe_len;
6365 	u32 stripe_index;
6366 	int data_stripes;
6367 	int i;
6368 	int ret = 0;
6369 	int num_stripes;
6370 	int max_errors = 0;
6371 	int tgtdev_indexes = 0;
6372 	struct btrfs_io_context *bioc = NULL;
6373 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6374 	int dev_replace_is_ongoing = 0;
6375 	int num_alloc_stripes;
6376 	int patch_the_first_stripe_for_dev_replace = 0;
6377 	u64 physical_to_patch_in_first_stripe = 0;
6378 	u64 raid56_full_stripe_start = (u64)-1;
6379 	struct btrfs_io_geometry geom;
6380 
6381 	ASSERT(bioc_ret);
6382 	ASSERT(op != BTRFS_MAP_DISCARD);
6383 
6384 	em = btrfs_get_chunk_map(fs_info, logical, *length);
6385 	ASSERT(!IS_ERR(em));
6386 
6387 	ret = btrfs_get_io_geometry(fs_info, em, op, logical, &geom);
6388 	if (ret < 0)
6389 		return ret;
6390 
6391 	map = em->map_lookup;
6392 
6393 	*length = geom.len;
6394 	stripe_len = geom.stripe_len;
6395 	stripe_nr = geom.stripe_nr;
6396 	stripe_offset = geom.stripe_offset;
6397 	raid56_full_stripe_start = geom.raid56_stripe_offset;
6398 	data_stripes = nr_data_stripes(map);
6399 
6400 	down_read(&dev_replace->rwsem);
6401 	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6402 	/*
6403 	 * Hold the semaphore for read during the whole operation, write is
6404 	 * requested at commit time but must wait.
6405 	 */
6406 	if (!dev_replace_is_ongoing)
6407 		up_read(&dev_replace->rwsem);
6408 
6409 	if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
6410 	    !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
6411 		ret = get_extra_mirror_from_replace(fs_info, logical, *length,
6412 						    dev_replace->srcdev->devid,
6413 						    &mirror_num,
6414 					    &physical_to_patch_in_first_stripe);
6415 		if (ret)
6416 			goto out;
6417 		else
6418 			patch_the_first_stripe_for_dev_replace = 1;
6419 	} else if (mirror_num > map->num_stripes) {
6420 		mirror_num = 0;
6421 	}
6422 
6423 	num_stripes = 1;
6424 	stripe_index = 0;
6425 	if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6426 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6427 				&stripe_index);
6428 		if (!need_full_stripe(op))
6429 			mirror_num = 1;
6430 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) {
6431 		if (need_full_stripe(op))
6432 			num_stripes = map->num_stripes;
6433 		else if (mirror_num)
6434 			stripe_index = mirror_num - 1;
6435 		else {
6436 			stripe_index = find_live_mirror(fs_info, map, 0,
6437 					    dev_replace_is_ongoing);
6438 			mirror_num = stripe_index + 1;
6439 		}
6440 
6441 	} else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
6442 		if (need_full_stripe(op)) {
6443 			num_stripes = map->num_stripes;
6444 		} else if (mirror_num) {
6445 			stripe_index = mirror_num - 1;
6446 		} else {
6447 			mirror_num = 1;
6448 		}
6449 
6450 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6451 		u32 factor = map->num_stripes / map->sub_stripes;
6452 
6453 		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
6454 		stripe_index *= map->sub_stripes;
6455 
6456 		if (need_full_stripe(op))
6457 			num_stripes = map->sub_stripes;
6458 		else if (mirror_num)
6459 			stripe_index += mirror_num - 1;
6460 		else {
6461 			int old_stripe_index = stripe_index;
6462 			stripe_index = find_live_mirror(fs_info, map,
6463 					      stripe_index,
6464 					      dev_replace_is_ongoing);
6465 			mirror_num = stripe_index - old_stripe_index + 1;
6466 		}
6467 
6468 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6469 		ASSERT(map->stripe_len == BTRFS_STRIPE_LEN);
6470 		if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
6471 			/* push stripe_nr back to the start of the full stripe */
6472 			stripe_nr = div64_u64(raid56_full_stripe_start,
6473 					stripe_len * data_stripes);
6474 
6475 			/* RAID[56] write or recovery. Return all stripes */
6476 			num_stripes = map->num_stripes;
6477 			max_errors = btrfs_chunk_max_errors(map);
6478 
6479 			/* Return the length to the full stripe end */
6480 			*length = min(logical + *length,
6481 				      raid56_full_stripe_start + em->start +
6482 				      data_stripes * stripe_len) - logical;
6483 			stripe_index = 0;
6484 			stripe_offset = 0;
6485 		} else {
6486 			/*
6487 			 * Mirror #0 or #1 means the original data block.
6488 			 * Mirror #2 is RAID5 parity block.
6489 			 * Mirror #3 is RAID6 Q block.
6490 			 */
6491 			stripe_nr = div_u64_rem(stripe_nr,
6492 					data_stripes, &stripe_index);
6493 			if (mirror_num > 1)
6494 				stripe_index = data_stripes + mirror_num - 2;
6495 
6496 			/* We distribute the parity blocks across stripes */
6497 			div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6498 					&stripe_index);
6499 			if (!need_full_stripe(op) && mirror_num <= 1)
6500 				mirror_num = 1;
6501 		}
6502 	} else {
6503 		/*
6504 		 * after this, stripe_nr is the number of stripes on this
6505 		 * device we have to walk to find the data, and stripe_index is
6506 		 * the number of our device in the stripe array
6507 		 */
6508 		stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6509 				&stripe_index);
6510 		mirror_num = stripe_index + 1;
6511 	}
6512 	if (stripe_index >= map->num_stripes) {
6513 		btrfs_crit(fs_info,
6514 			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6515 			   stripe_index, map->num_stripes);
6516 		ret = -EINVAL;
6517 		goto out;
6518 	}
6519 
6520 	num_alloc_stripes = num_stripes;
6521 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6522 		if (op == BTRFS_MAP_WRITE)
6523 			num_alloc_stripes <<= 1;
6524 		if (op == BTRFS_MAP_GET_READ_MIRRORS)
6525 			num_alloc_stripes++;
6526 		tgtdev_indexes = num_stripes;
6527 	}
6528 
6529 	bioc = alloc_btrfs_io_context(fs_info, num_alloc_stripes, tgtdev_indexes);
6530 	if (!bioc) {
6531 		ret = -ENOMEM;
6532 		goto out;
6533 	}
6534 
6535 	for (i = 0; i < num_stripes; i++) {
6536 		bioc->stripes[i].physical = map->stripes[stripe_index].physical +
6537 			stripe_offset + stripe_nr * map->stripe_len;
6538 		bioc->stripes[i].dev = map->stripes[stripe_index].dev;
6539 		stripe_index++;
6540 	}
6541 
6542 	/* Build raid_map */
6543 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6544 	    (need_full_stripe(op) || mirror_num > 1)) {
6545 		u64 tmp;
6546 		unsigned rot;
6547 
6548 		/* Work out the disk rotation on this stripe-set */
6549 		div_u64_rem(stripe_nr, num_stripes, &rot);
6550 
6551 		/* Fill in the logical address of each stripe */
6552 		tmp = stripe_nr * data_stripes;
6553 		for (i = 0; i < data_stripes; i++)
6554 			bioc->raid_map[(i + rot) % num_stripes] =
6555 				em->start + (tmp + i) * map->stripe_len;
6556 
6557 		bioc->raid_map[(i + rot) % map->num_stripes] = RAID5_P_STRIPE;
6558 		if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6559 			bioc->raid_map[(i + rot + 1) % num_stripes] =
6560 				RAID6_Q_STRIPE;
6561 
6562 		sort_parity_stripes(bioc, num_stripes);
6563 	}
6564 
6565 	if (need_full_stripe(op))
6566 		max_errors = btrfs_chunk_max_errors(map);
6567 
6568 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6569 	    need_full_stripe(op)) {
6570 		handle_ops_on_dev_replace(op, &bioc, dev_replace, logical,
6571 					  &num_stripes, &max_errors);
6572 	}
6573 
6574 	*bioc_ret = bioc;
6575 	bioc->map_type = map->type;
6576 	bioc->num_stripes = num_stripes;
6577 	bioc->max_errors = max_errors;
6578 	bioc->mirror_num = mirror_num;
6579 
6580 	/*
6581 	 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6582 	 * mirror_num == num_stripes + 1 && dev_replace target drive is
6583 	 * available as a mirror
6584 	 */
6585 	if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6586 		WARN_ON(num_stripes > 1);
6587 		bioc->stripes[0].dev = dev_replace->tgtdev;
6588 		bioc->stripes[0].physical = physical_to_patch_in_first_stripe;
6589 		bioc->mirror_num = map->num_stripes + 1;
6590 	}
6591 out:
6592 	if (dev_replace_is_ongoing) {
6593 		lockdep_assert_held(&dev_replace->rwsem);
6594 		/* Unlock and let waiting writers proceed */
6595 		up_read(&dev_replace->rwsem);
6596 	}
6597 	free_extent_map(em);
6598 	return ret;
6599 }
6600 
6601 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6602 		      u64 logical, u64 *length,
6603 		      struct btrfs_io_context **bioc_ret, int mirror_num)
6604 {
6605 	return __btrfs_map_block(fs_info, op, logical, length, bioc_ret,
6606 				 mirror_num, 0);
6607 }
6608 
6609 /* For Scrub/replace */
6610 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6611 		     u64 logical, u64 *length,
6612 		     struct btrfs_io_context **bioc_ret)
6613 {
6614 	return __btrfs_map_block(fs_info, op, logical, length, bioc_ret, 0, 1);
6615 }
6616 
6617 /*
6618  * Initialize a btrfs_bio structure.  This skips the embedded bio itself as it
6619  * is already initialized by the block layer.
6620  */
6621 static inline void btrfs_bio_init(struct btrfs_bio *bbio)
6622 {
6623 	memset(bbio, 0, offsetof(struct btrfs_bio, bio));
6624 }
6625 
6626 /*
6627  * Allocate a btrfs_bio structure.  The btrfs_bio is the main I/O container for
6628  * btrfs, and is used for all I/O submitted through btrfs_submit_bio.
6629  *
6630  * Just like the underlying bio_alloc_bioset it will not fail as it is backed by
6631  * a mempool.
6632  */
6633 struct bio *btrfs_bio_alloc(unsigned int nr_vecs, blk_opf_t opf)
6634 {
6635 	struct bio *bio;
6636 
6637 	bio = bio_alloc_bioset(NULL, nr_vecs, opf, GFP_NOFS, &btrfs_bioset);
6638 	btrfs_bio_init(btrfs_bio(bio));
6639 	return bio;
6640 }
6641 
6642 struct bio *btrfs_bio_clone_partial(struct bio *orig, u64 offset, u64 size)
6643 {
6644 	struct bio *bio;
6645 	struct btrfs_bio *bbio;
6646 
6647 	ASSERT(offset <= UINT_MAX && size <= UINT_MAX);
6648 
6649 	bio = bio_alloc_clone(orig->bi_bdev, orig, GFP_NOFS, &btrfs_bioset);
6650 	bbio = btrfs_bio(bio);
6651 	btrfs_bio_init(bbio);
6652 
6653 	bio_trim(bio, offset >> 9, size >> 9);
6654 	bbio->iter = bio->bi_iter;
6655 	return bio;
6656 
6657 }
6658 
6659 static struct workqueue_struct *btrfs_end_io_wq(struct btrfs_io_context *bioc)
6660 {
6661 	if (bioc->orig_bio->bi_opf & REQ_META)
6662 		return bioc->fs_info->endio_meta_workers;
6663 	return bioc->fs_info->endio_workers;
6664 }
6665 
6666 static void btrfs_end_bio_work(struct work_struct *work)
6667 {
6668 	struct btrfs_bio *bbio =
6669 		container_of(work, struct btrfs_bio, end_io_work);
6670 
6671 	bio_endio(&bbio->bio);
6672 }
6673 
6674 static void btrfs_end_bioc(struct btrfs_io_context *bioc, bool async)
6675 {
6676 	struct bio *orig_bio = bioc->orig_bio;
6677 	struct btrfs_bio *bbio = btrfs_bio(orig_bio);
6678 
6679 	btrfs_bio_counter_dec(bioc->fs_info);
6680 
6681 	bbio->mirror_num = bioc->mirror_num;
6682 	orig_bio->bi_private = bioc->private;
6683 	orig_bio->bi_end_io = bioc->end_io;
6684 
6685 	/*
6686 	 * Only send an error to the higher layers if it is beyond the tolerance
6687 	 * threshold.
6688 	 */
6689 	if (atomic_read(&bioc->error) > bioc->max_errors)
6690 		orig_bio->bi_status = BLK_STS_IOERR;
6691 	else
6692 		orig_bio->bi_status = BLK_STS_OK;
6693 
6694 	if (btrfs_op(orig_bio) == BTRFS_MAP_READ && async) {
6695 		INIT_WORK(&bbio->end_io_work, btrfs_end_bio_work);
6696 		queue_work(btrfs_end_io_wq(bioc), &bbio->end_io_work);
6697 	} else {
6698 		bio_endio(orig_bio);
6699 	}
6700 
6701 	btrfs_put_bioc(bioc);
6702 }
6703 
6704 static void btrfs_end_bio(struct bio *bio)
6705 {
6706 	struct btrfs_io_stripe *stripe = bio->bi_private;
6707 	struct btrfs_io_context *bioc = stripe->bioc;
6708 
6709 	if (bio->bi_status) {
6710 		atomic_inc(&bioc->error);
6711 		if (bio->bi_status == BLK_STS_IOERR ||
6712 		    bio->bi_status == BLK_STS_TARGET) {
6713 			if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6714 				btrfs_dev_stat_inc_and_print(stripe->dev,
6715 						BTRFS_DEV_STAT_WRITE_ERRS);
6716 			else if (!(bio->bi_opf & REQ_RAHEAD))
6717 				btrfs_dev_stat_inc_and_print(stripe->dev,
6718 						BTRFS_DEV_STAT_READ_ERRS);
6719 			if (bio->bi_opf & REQ_PREFLUSH)
6720 				btrfs_dev_stat_inc_and_print(stripe->dev,
6721 						BTRFS_DEV_STAT_FLUSH_ERRS);
6722 		}
6723 	}
6724 
6725 	if (bio != bioc->orig_bio)
6726 		bio_put(bio);
6727 
6728 	if (atomic_dec_and_test(&bioc->stripes_pending))
6729 		btrfs_end_bioc(bioc, true);
6730 }
6731 
6732 static void submit_stripe_bio(struct btrfs_io_context *bioc,
6733 			      struct bio *orig_bio, int dev_nr, bool clone)
6734 {
6735 	struct btrfs_fs_info *fs_info = bioc->fs_info;
6736 	struct btrfs_device *dev = bioc->stripes[dev_nr].dev;
6737 	u64 physical = bioc->stripes[dev_nr].physical;
6738 	struct bio *bio;
6739 
6740 	if (!dev || !dev->bdev ||
6741 	    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6742 	    (btrfs_op(orig_bio) == BTRFS_MAP_WRITE &&
6743 	     !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6744 		atomic_inc(&bioc->error);
6745 		if (atomic_dec_and_test(&bioc->stripes_pending))
6746 			btrfs_end_bioc(bioc, false);
6747 		return;
6748 	}
6749 
6750 	if (clone) {
6751 		bio = bio_alloc_clone(dev->bdev, orig_bio, GFP_NOFS, &fs_bio_set);
6752 	} else {
6753 		bio = orig_bio;
6754 		bio_set_dev(bio, dev->bdev);
6755 		btrfs_bio(bio)->device = dev;
6756 	}
6757 
6758 	bioc->stripes[dev_nr].bioc = bioc;
6759 	bio->bi_private = &bioc->stripes[dev_nr];
6760 	bio->bi_end_io = btrfs_end_bio;
6761 	bio->bi_iter.bi_sector = physical >> 9;
6762 	/*
6763 	 * For zone append writing, bi_sector must point the beginning of the
6764 	 * zone
6765 	 */
6766 	if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
6767 		if (btrfs_dev_is_sequential(dev, physical)) {
6768 			u64 zone_start = round_down(physical, fs_info->zone_size);
6769 
6770 			bio->bi_iter.bi_sector = zone_start >> SECTOR_SHIFT;
6771 		} else {
6772 			bio->bi_opf &= ~REQ_OP_ZONE_APPEND;
6773 			bio->bi_opf |= REQ_OP_WRITE;
6774 		}
6775 	}
6776 	btrfs_debug_in_rcu(fs_info,
6777 	"%s: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6778 		__func__, bio_op(bio), bio->bi_opf, bio->bi_iter.bi_sector,
6779 		(unsigned long)dev->bdev->bd_dev, rcu_str_deref(dev->name),
6780 		dev->devid, bio->bi_iter.bi_size);
6781 
6782 	btrfsic_check_bio(bio);
6783 	submit_bio(bio);
6784 }
6785 
6786 void btrfs_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio, int mirror_num)
6787 {
6788 	u64 logical = bio->bi_iter.bi_sector << 9;
6789 	u64 length = bio->bi_iter.bi_size;
6790 	u64 map_length = length;
6791 	int ret;
6792 	int dev_nr;
6793 	int total_devs;
6794 	struct btrfs_io_context *bioc = NULL;
6795 
6796 	btrfs_bio_counter_inc_blocked(fs_info);
6797 	ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6798 				&map_length, &bioc, mirror_num, 1);
6799 	if (ret) {
6800 		btrfs_bio_counter_dec(fs_info);
6801 		bio->bi_status = errno_to_blk_status(ret);
6802 		bio_endio(bio);
6803 		return;
6804 	}
6805 
6806 	total_devs = bioc->num_stripes;
6807 	bioc->orig_bio = bio;
6808 	bioc->private = bio->bi_private;
6809 	bioc->end_io = bio->bi_end_io;
6810 	atomic_set(&bioc->stripes_pending, total_devs);
6811 
6812 	if ((bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6813 	    ((btrfs_op(bio) == BTRFS_MAP_WRITE) || (mirror_num > 1))) {
6814 		if (btrfs_op(bio) == BTRFS_MAP_WRITE)
6815 			raid56_parity_write(bio, bioc);
6816 		else
6817 			raid56_parity_recover(bio, bioc, mirror_num, true);
6818 		return;
6819 	}
6820 
6821 	if (map_length < length) {
6822 		btrfs_crit(fs_info,
6823 			   "mapping failed logical %llu bio len %llu len %llu",
6824 			   logical, length, map_length);
6825 		BUG();
6826 	}
6827 
6828 	for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6829 		const bool should_clone = (dev_nr < total_devs - 1);
6830 
6831 		submit_stripe_bio(bioc, bio, dev_nr, should_clone);
6832 	}
6833 }
6834 
6835 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6836 				      const struct btrfs_fs_devices *fs_devices)
6837 {
6838 	if (args->fsid == NULL)
6839 		return true;
6840 	if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6841 		return true;
6842 	return false;
6843 }
6844 
6845 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6846 				  const struct btrfs_device *device)
6847 {
6848 	ASSERT((args->devid != (u64)-1) || args->missing);
6849 
6850 	if ((args->devid != (u64)-1) && device->devid != args->devid)
6851 		return false;
6852 	if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6853 		return false;
6854 	if (!args->missing)
6855 		return true;
6856 	if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6857 	    !device->bdev)
6858 		return true;
6859 	return false;
6860 }
6861 
6862 /*
6863  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6864  * return NULL.
6865  *
6866  * If devid and uuid are both specified, the match must be exact, otherwise
6867  * only devid is used.
6868  */
6869 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6870 				       const struct btrfs_dev_lookup_args *args)
6871 {
6872 	struct btrfs_device *device;
6873 	struct btrfs_fs_devices *seed_devs;
6874 
6875 	if (dev_args_match_fs_devices(args, fs_devices)) {
6876 		list_for_each_entry(device, &fs_devices->devices, dev_list) {
6877 			if (dev_args_match_device(args, device))
6878 				return device;
6879 		}
6880 	}
6881 
6882 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6883 		if (!dev_args_match_fs_devices(args, seed_devs))
6884 			continue;
6885 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
6886 			if (dev_args_match_device(args, device))
6887 				return device;
6888 		}
6889 	}
6890 
6891 	return NULL;
6892 }
6893 
6894 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6895 					    u64 devid, u8 *dev_uuid)
6896 {
6897 	struct btrfs_device *device;
6898 	unsigned int nofs_flag;
6899 
6900 	/*
6901 	 * We call this under the chunk_mutex, so we want to use NOFS for this
6902 	 * allocation, however we don't want to change btrfs_alloc_device() to
6903 	 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6904 	 * places.
6905 	 */
6906 	nofs_flag = memalloc_nofs_save();
6907 	device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6908 	memalloc_nofs_restore(nofs_flag);
6909 	if (IS_ERR(device))
6910 		return device;
6911 
6912 	list_add(&device->dev_list, &fs_devices->devices);
6913 	device->fs_devices = fs_devices;
6914 	fs_devices->num_devices++;
6915 
6916 	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6917 	fs_devices->missing_devices++;
6918 
6919 	return device;
6920 }
6921 
6922 /**
6923  * btrfs_alloc_device - allocate struct btrfs_device
6924  * @fs_info:	used only for generating a new devid, can be NULL if
6925  *		devid is provided (i.e. @devid != NULL).
6926  * @devid:	a pointer to devid for this device.  If NULL a new devid
6927  *		is generated.
6928  * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
6929  *		is generated.
6930  *
6931  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6932  * on error.  Returned struct is not linked onto any lists and must be
6933  * destroyed with btrfs_free_device.
6934  */
6935 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6936 					const u64 *devid,
6937 					const u8 *uuid)
6938 {
6939 	struct btrfs_device *dev;
6940 	u64 tmp;
6941 
6942 	if (WARN_ON(!devid && !fs_info))
6943 		return ERR_PTR(-EINVAL);
6944 
6945 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6946 	if (!dev)
6947 		return ERR_PTR(-ENOMEM);
6948 
6949 	INIT_LIST_HEAD(&dev->dev_list);
6950 	INIT_LIST_HEAD(&dev->dev_alloc_list);
6951 	INIT_LIST_HEAD(&dev->post_commit_list);
6952 
6953 	atomic_set(&dev->dev_stats_ccnt, 0);
6954 	btrfs_device_data_ordered_init(dev);
6955 	extent_io_tree_init(fs_info, &dev->alloc_state,
6956 			    IO_TREE_DEVICE_ALLOC_STATE, NULL);
6957 
6958 	if (devid)
6959 		tmp = *devid;
6960 	else {
6961 		int ret;
6962 
6963 		ret = find_next_devid(fs_info, &tmp);
6964 		if (ret) {
6965 			btrfs_free_device(dev);
6966 			return ERR_PTR(ret);
6967 		}
6968 	}
6969 	dev->devid = tmp;
6970 
6971 	if (uuid)
6972 		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6973 	else
6974 		generate_random_uuid(dev->uuid);
6975 
6976 	return dev;
6977 }
6978 
6979 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6980 					u64 devid, u8 *uuid, bool error)
6981 {
6982 	if (error)
6983 		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6984 			      devid, uuid);
6985 	else
6986 		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6987 			      devid, uuid);
6988 }
6989 
6990 u64 btrfs_calc_stripe_length(const struct extent_map *em)
6991 {
6992 	const struct map_lookup *map = em->map_lookup;
6993 	const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
6994 
6995 	return div_u64(em->len, data_stripes);
6996 }
6997 
6998 #if BITS_PER_LONG == 32
6999 /*
7000  * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
7001  * can't be accessed on 32bit systems.
7002  *
7003  * This function do mount time check to reject the fs if it already has
7004  * metadata chunk beyond that limit.
7005  */
7006 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7007 				  u64 logical, u64 length, u64 type)
7008 {
7009 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7010 		return 0;
7011 
7012 	if (logical + length < MAX_LFS_FILESIZE)
7013 		return 0;
7014 
7015 	btrfs_err_32bit_limit(fs_info);
7016 	return -EOVERFLOW;
7017 }
7018 
7019 /*
7020  * This is to give early warning for any metadata chunk reaching
7021  * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7022  * Although we can still access the metadata, it's not going to be possible
7023  * once the limit is reached.
7024  */
7025 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7026 				  u64 logical, u64 length, u64 type)
7027 {
7028 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7029 		return;
7030 
7031 	if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7032 		return;
7033 
7034 	btrfs_warn_32bit_limit(fs_info);
7035 }
7036 #endif
7037 
7038 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7039 						  u64 devid, u8 *uuid)
7040 {
7041 	struct btrfs_device *dev;
7042 
7043 	if (!btrfs_test_opt(fs_info, DEGRADED)) {
7044 		btrfs_report_missing_device(fs_info, devid, uuid, true);
7045 		return ERR_PTR(-ENOENT);
7046 	}
7047 
7048 	dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7049 	if (IS_ERR(dev)) {
7050 		btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7051 			  devid, PTR_ERR(dev));
7052 		return dev;
7053 	}
7054 	btrfs_report_missing_device(fs_info, devid, uuid, false);
7055 
7056 	return dev;
7057 }
7058 
7059 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7060 			  struct btrfs_chunk *chunk)
7061 {
7062 	BTRFS_DEV_LOOKUP_ARGS(args);
7063 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7064 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7065 	struct map_lookup *map;
7066 	struct extent_map *em;
7067 	u64 logical;
7068 	u64 length;
7069 	u64 devid;
7070 	u64 type;
7071 	u8 uuid[BTRFS_UUID_SIZE];
7072 	int num_stripes;
7073 	int ret;
7074 	int i;
7075 
7076 	logical = key->offset;
7077 	length = btrfs_chunk_length(leaf, chunk);
7078 	type = btrfs_chunk_type(leaf, chunk);
7079 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7080 
7081 #if BITS_PER_LONG == 32
7082 	ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7083 	if (ret < 0)
7084 		return ret;
7085 	warn_32bit_meta_chunk(fs_info, logical, length, type);
7086 #endif
7087 
7088 	/*
7089 	 * Only need to verify chunk item if we're reading from sys chunk array,
7090 	 * as chunk item in tree block is already verified by tree-checker.
7091 	 */
7092 	if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
7093 		ret = btrfs_check_chunk_valid(leaf, chunk, logical);
7094 		if (ret)
7095 			return ret;
7096 	}
7097 
7098 	read_lock(&map_tree->lock);
7099 	em = lookup_extent_mapping(map_tree, logical, 1);
7100 	read_unlock(&map_tree->lock);
7101 
7102 	/* already mapped? */
7103 	if (em && em->start <= logical && em->start + em->len > logical) {
7104 		free_extent_map(em);
7105 		return 0;
7106 	} else if (em) {
7107 		free_extent_map(em);
7108 	}
7109 
7110 	em = alloc_extent_map();
7111 	if (!em)
7112 		return -ENOMEM;
7113 	map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
7114 	if (!map) {
7115 		free_extent_map(em);
7116 		return -ENOMEM;
7117 	}
7118 
7119 	set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
7120 	em->map_lookup = map;
7121 	em->start = logical;
7122 	em->len = length;
7123 	em->orig_start = 0;
7124 	em->block_start = 0;
7125 	em->block_len = em->len;
7126 
7127 	map->num_stripes = num_stripes;
7128 	map->io_width = btrfs_chunk_io_width(leaf, chunk);
7129 	map->io_align = btrfs_chunk_io_align(leaf, chunk);
7130 	map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
7131 	map->type = type;
7132 	map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
7133 	map->verified_stripes = 0;
7134 	em->orig_block_len = btrfs_calc_stripe_length(em);
7135 	for (i = 0; i < num_stripes; i++) {
7136 		map->stripes[i].physical =
7137 			btrfs_stripe_offset_nr(leaf, chunk, i);
7138 		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7139 		args.devid = devid;
7140 		read_extent_buffer(leaf, uuid, (unsigned long)
7141 				   btrfs_stripe_dev_uuid_nr(chunk, i),
7142 				   BTRFS_UUID_SIZE);
7143 		args.uuid = uuid;
7144 		map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7145 		if (!map->stripes[i].dev) {
7146 			map->stripes[i].dev = handle_missing_device(fs_info,
7147 								    devid, uuid);
7148 			if (IS_ERR(map->stripes[i].dev)) {
7149 				free_extent_map(em);
7150 				return PTR_ERR(map->stripes[i].dev);
7151 			}
7152 		}
7153 
7154 		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7155 				&(map->stripes[i].dev->dev_state));
7156 	}
7157 
7158 	write_lock(&map_tree->lock);
7159 	ret = add_extent_mapping(map_tree, em, 0);
7160 	write_unlock(&map_tree->lock);
7161 	if (ret < 0) {
7162 		btrfs_err(fs_info,
7163 			  "failed to add chunk map, start=%llu len=%llu: %d",
7164 			  em->start, em->len, ret);
7165 	}
7166 	free_extent_map(em);
7167 
7168 	return ret;
7169 }
7170 
7171 static void fill_device_from_item(struct extent_buffer *leaf,
7172 				 struct btrfs_dev_item *dev_item,
7173 				 struct btrfs_device *device)
7174 {
7175 	unsigned long ptr;
7176 
7177 	device->devid = btrfs_device_id(leaf, dev_item);
7178 	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7179 	device->total_bytes = device->disk_total_bytes;
7180 	device->commit_total_bytes = device->disk_total_bytes;
7181 	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7182 	device->commit_bytes_used = device->bytes_used;
7183 	device->type = btrfs_device_type(leaf, dev_item);
7184 	device->io_align = btrfs_device_io_align(leaf, dev_item);
7185 	device->io_width = btrfs_device_io_width(leaf, dev_item);
7186 	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7187 	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7188 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7189 
7190 	ptr = btrfs_device_uuid(dev_item);
7191 	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7192 }
7193 
7194 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7195 						  u8 *fsid)
7196 {
7197 	struct btrfs_fs_devices *fs_devices;
7198 	int ret;
7199 
7200 	lockdep_assert_held(&uuid_mutex);
7201 	ASSERT(fsid);
7202 
7203 	/* This will match only for multi-device seed fs */
7204 	list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7205 		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7206 			return fs_devices;
7207 
7208 
7209 	fs_devices = find_fsid(fsid, NULL);
7210 	if (!fs_devices) {
7211 		if (!btrfs_test_opt(fs_info, DEGRADED))
7212 			return ERR_PTR(-ENOENT);
7213 
7214 		fs_devices = alloc_fs_devices(fsid, NULL);
7215 		if (IS_ERR(fs_devices))
7216 			return fs_devices;
7217 
7218 		fs_devices->seeding = true;
7219 		fs_devices->opened = 1;
7220 		return fs_devices;
7221 	}
7222 
7223 	/*
7224 	 * Upon first call for a seed fs fsid, just create a private copy of the
7225 	 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7226 	 */
7227 	fs_devices = clone_fs_devices(fs_devices);
7228 	if (IS_ERR(fs_devices))
7229 		return fs_devices;
7230 
7231 	ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
7232 	if (ret) {
7233 		free_fs_devices(fs_devices);
7234 		return ERR_PTR(ret);
7235 	}
7236 
7237 	if (!fs_devices->seeding) {
7238 		close_fs_devices(fs_devices);
7239 		free_fs_devices(fs_devices);
7240 		return ERR_PTR(-EINVAL);
7241 	}
7242 
7243 	list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7244 
7245 	return fs_devices;
7246 }
7247 
7248 static int read_one_dev(struct extent_buffer *leaf,
7249 			struct btrfs_dev_item *dev_item)
7250 {
7251 	BTRFS_DEV_LOOKUP_ARGS(args);
7252 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7253 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7254 	struct btrfs_device *device;
7255 	u64 devid;
7256 	int ret;
7257 	u8 fs_uuid[BTRFS_FSID_SIZE];
7258 	u8 dev_uuid[BTRFS_UUID_SIZE];
7259 
7260 	devid = btrfs_device_id(leaf, dev_item);
7261 	args.devid = devid;
7262 	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7263 			   BTRFS_UUID_SIZE);
7264 	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7265 			   BTRFS_FSID_SIZE);
7266 	args.uuid = dev_uuid;
7267 	args.fsid = fs_uuid;
7268 
7269 	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7270 		fs_devices = open_seed_devices(fs_info, fs_uuid);
7271 		if (IS_ERR(fs_devices))
7272 			return PTR_ERR(fs_devices);
7273 	}
7274 
7275 	device = btrfs_find_device(fs_info->fs_devices, &args);
7276 	if (!device) {
7277 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7278 			btrfs_report_missing_device(fs_info, devid,
7279 							dev_uuid, true);
7280 			return -ENOENT;
7281 		}
7282 
7283 		device = add_missing_dev(fs_devices, devid, dev_uuid);
7284 		if (IS_ERR(device)) {
7285 			btrfs_err(fs_info,
7286 				"failed to add missing dev %llu: %ld",
7287 				devid, PTR_ERR(device));
7288 			return PTR_ERR(device);
7289 		}
7290 		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7291 	} else {
7292 		if (!device->bdev) {
7293 			if (!btrfs_test_opt(fs_info, DEGRADED)) {
7294 				btrfs_report_missing_device(fs_info,
7295 						devid, dev_uuid, true);
7296 				return -ENOENT;
7297 			}
7298 			btrfs_report_missing_device(fs_info, devid,
7299 							dev_uuid, false);
7300 		}
7301 
7302 		if (!device->bdev &&
7303 		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7304 			/*
7305 			 * this happens when a device that was properly setup
7306 			 * in the device info lists suddenly goes bad.
7307 			 * device->bdev is NULL, and so we have to set
7308 			 * device->missing to one here
7309 			 */
7310 			device->fs_devices->missing_devices++;
7311 			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7312 		}
7313 
7314 		/* Move the device to its own fs_devices */
7315 		if (device->fs_devices != fs_devices) {
7316 			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7317 							&device->dev_state));
7318 
7319 			list_move(&device->dev_list, &fs_devices->devices);
7320 			device->fs_devices->num_devices--;
7321 			fs_devices->num_devices++;
7322 
7323 			device->fs_devices->missing_devices--;
7324 			fs_devices->missing_devices++;
7325 
7326 			device->fs_devices = fs_devices;
7327 		}
7328 	}
7329 
7330 	if (device->fs_devices != fs_info->fs_devices) {
7331 		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7332 		if (device->generation !=
7333 		    btrfs_device_generation(leaf, dev_item))
7334 			return -EINVAL;
7335 	}
7336 
7337 	fill_device_from_item(leaf, dev_item, device);
7338 	if (device->bdev) {
7339 		u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7340 
7341 		if (device->total_bytes > max_total_bytes) {
7342 			btrfs_err(fs_info,
7343 			"device total_bytes should be at most %llu but found %llu",
7344 				  max_total_bytes, device->total_bytes);
7345 			return -EINVAL;
7346 		}
7347 	}
7348 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7349 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7350 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7351 		device->fs_devices->total_rw_bytes += device->total_bytes;
7352 		atomic64_add(device->total_bytes - device->bytes_used,
7353 				&fs_info->free_chunk_space);
7354 	}
7355 	ret = 0;
7356 	return ret;
7357 }
7358 
7359 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7360 {
7361 	struct btrfs_super_block *super_copy = fs_info->super_copy;
7362 	struct extent_buffer *sb;
7363 	struct btrfs_disk_key *disk_key;
7364 	struct btrfs_chunk *chunk;
7365 	u8 *array_ptr;
7366 	unsigned long sb_array_offset;
7367 	int ret = 0;
7368 	u32 num_stripes;
7369 	u32 array_size;
7370 	u32 len = 0;
7371 	u32 cur_offset;
7372 	u64 type;
7373 	struct btrfs_key key;
7374 
7375 	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7376 
7377 	/*
7378 	 * We allocated a dummy extent, just to use extent buffer accessors.
7379 	 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7380 	 * that's fine, we will not go beyond system chunk array anyway.
7381 	 */
7382 	sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7383 	if (!sb)
7384 		return -ENOMEM;
7385 	set_extent_buffer_uptodate(sb);
7386 
7387 	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7388 	array_size = btrfs_super_sys_array_size(super_copy);
7389 
7390 	array_ptr = super_copy->sys_chunk_array;
7391 	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7392 	cur_offset = 0;
7393 
7394 	while (cur_offset < array_size) {
7395 		disk_key = (struct btrfs_disk_key *)array_ptr;
7396 		len = sizeof(*disk_key);
7397 		if (cur_offset + len > array_size)
7398 			goto out_short_read;
7399 
7400 		btrfs_disk_key_to_cpu(&key, disk_key);
7401 
7402 		array_ptr += len;
7403 		sb_array_offset += len;
7404 		cur_offset += len;
7405 
7406 		if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7407 			btrfs_err(fs_info,
7408 			    "unexpected item type %u in sys_array at offset %u",
7409 				  (u32)key.type, cur_offset);
7410 			ret = -EIO;
7411 			break;
7412 		}
7413 
7414 		chunk = (struct btrfs_chunk *)sb_array_offset;
7415 		/*
7416 		 * At least one btrfs_chunk with one stripe must be present,
7417 		 * exact stripe count check comes afterwards
7418 		 */
7419 		len = btrfs_chunk_item_size(1);
7420 		if (cur_offset + len > array_size)
7421 			goto out_short_read;
7422 
7423 		num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7424 		if (!num_stripes) {
7425 			btrfs_err(fs_info,
7426 			"invalid number of stripes %u in sys_array at offset %u",
7427 				  num_stripes, cur_offset);
7428 			ret = -EIO;
7429 			break;
7430 		}
7431 
7432 		type = btrfs_chunk_type(sb, chunk);
7433 		if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7434 			btrfs_err(fs_info,
7435 			"invalid chunk type %llu in sys_array at offset %u",
7436 				  type, cur_offset);
7437 			ret = -EIO;
7438 			break;
7439 		}
7440 
7441 		len = btrfs_chunk_item_size(num_stripes);
7442 		if (cur_offset + len > array_size)
7443 			goto out_short_read;
7444 
7445 		ret = read_one_chunk(&key, sb, chunk);
7446 		if (ret)
7447 			break;
7448 
7449 		array_ptr += len;
7450 		sb_array_offset += len;
7451 		cur_offset += len;
7452 	}
7453 	clear_extent_buffer_uptodate(sb);
7454 	free_extent_buffer_stale(sb);
7455 	return ret;
7456 
7457 out_short_read:
7458 	btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7459 			len, cur_offset);
7460 	clear_extent_buffer_uptodate(sb);
7461 	free_extent_buffer_stale(sb);
7462 	return -EIO;
7463 }
7464 
7465 /*
7466  * Check if all chunks in the fs are OK for read-write degraded mount
7467  *
7468  * If the @failing_dev is specified, it's accounted as missing.
7469  *
7470  * Return true if all chunks meet the minimal RW mount requirements.
7471  * Return false if any chunk doesn't meet the minimal RW mount requirements.
7472  */
7473 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7474 					struct btrfs_device *failing_dev)
7475 {
7476 	struct extent_map_tree *map_tree = &fs_info->mapping_tree;
7477 	struct extent_map *em;
7478 	u64 next_start = 0;
7479 	bool ret = true;
7480 
7481 	read_lock(&map_tree->lock);
7482 	em = lookup_extent_mapping(map_tree, 0, (u64)-1);
7483 	read_unlock(&map_tree->lock);
7484 	/* No chunk at all? Return false anyway */
7485 	if (!em) {
7486 		ret = false;
7487 		goto out;
7488 	}
7489 	while (em) {
7490 		struct map_lookup *map;
7491 		int missing = 0;
7492 		int max_tolerated;
7493 		int i;
7494 
7495 		map = em->map_lookup;
7496 		max_tolerated =
7497 			btrfs_get_num_tolerated_disk_barrier_failures(
7498 					map->type);
7499 		for (i = 0; i < map->num_stripes; i++) {
7500 			struct btrfs_device *dev = map->stripes[i].dev;
7501 
7502 			if (!dev || !dev->bdev ||
7503 			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7504 			    dev->last_flush_error)
7505 				missing++;
7506 			else if (failing_dev && failing_dev == dev)
7507 				missing++;
7508 		}
7509 		if (missing > max_tolerated) {
7510 			if (!failing_dev)
7511 				btrfs_warn(fs_info,
7512 	"chunk %llu missing %d devices, max tolerance is %d for writable mount",
7513 				   em->start, missing, max_tolerated);
7514 			free_extent_map(em);
7515 			ret = false;
7516 			goto out;
7517 		}
7518 		next_start = extent_map_end(em);
7519 		free_extent_map(em);
7520 
7521 		read_lock(&map_tree->lock);
7522 		em = lookup_extent_mapping(map_tree, next_start,
7523 					   (u64)(-1) - next_start);
7524 		read_unlock(&map_tree->lock);
7525 	}
7526 out:
7527 	return ret;
7528 }
7529 
7530 static void readahead_tree_node_children(struct extent_buffer *node)
7531 {
7532 	int i;
7533 	const int nr_items = btrfs_header_nritems(node);
7534 
7535 	for (i = 0; i < nr_items; i++)
7536 		btrfs_readahead_node_child(node, i);
7537 }
7538 
7539 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7540 {
7541 	struct btrfs_root *root = fs_info->chunk_root;
7542 	struct btrfs_path *path;
7543 	struct extent_buffer *leaf;
7544 	struct btrfs_key key;
7545 	struct btrfs_key found_key;
7546 	int ret;
7547 	int slot;
7548 	int iter_ret = 0;
7549 	u64 total_dev = 0;
7550 	u64 last_ra_node = 0;
7551 
7552 	path = btrfs_alloc_path();
7553 	if (!path)
7554 		return -ENOMEM;
7555 
7556 	/*
7557 	 * uuid_mutex is needed only if we are mounting a sprout FS
7558 	 * otherwise we don't need it.
7559 	 */
7560 	mutex_lock(&uuid_mutex);
7561 
7562 	/*
7563 	 * It is possible for mount and umount to race in such a way that
7564 	 * we execute this code path, but open_fs_devices failed to clear
7565 	 * total_rw_bytes. We certainly want it cleared before reading the
7566 	 * device items, so clear it here.
7567 	 */
7568 	fs_info->fs_devices->total_rw_bytes = 0;
7569 
7570 	/*
7571 	 * Lockdep complains about possible circular locking dependency between
7572 	 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7573 	 * used for freeze procection of a fs (struct super_block.s_writers),
7574 	 * which we take when starting a transaction, and extent buffers of the
7575 	 * chunk tree if we call read_one_dev() while holding a lock on an
7576 	 * extent buffer of the chunk tree. Since we are mounting the filesystem
7577 	 * and at this point there can't be any concurrent task modifying the
7578 	 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7579 	 */
7580 	ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7581 	path->skip_locking = 1;
7582 
7583 	/*
7584 	 * Read all device items, and then all the chunk items. All
7585 	 * device items are found before any chunk item (their object id
7586 	 * is smaller than the lowest possible object id for a chunk
7587 	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7588 	 */
7589 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7590 	key.offset = 0;
7591 	key.type = 0;
7592 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7593 		struct extent_buffer *node = path->nodes[1];
7594 
7595 		leaf = path->nodes[0];
7596 		slot = path->slots[0];
7597 
7598 		if (node) {
7599 			if (last_ra_node != node->start) {
7600 				readahead_tree_node_children(node);
7601 				last_ra_node = node->start;
7602 			}
7603 		}
7604 		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7605 			struct btrfs_dev_item *dev_item;
7606 			dev_item = btrfs_item_ptr(leaf, slot,
7607 						  struct btrfs_dev_item);
7608 			ret = read_one_dev(leaf, dev_item);
7609 			if (ret)
7610 				goto error;
7611 			total_dev++;
7612 		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7613 			struct btrfs_chunk *chunk;
7614 
7615 			/*
7616 			 * We are only called at mount time, so no need to take
7617 			 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7618 			 * we always lock first fs_info->chunk_mutex before
7619 			 * acquiring any locks on the chunk tree. This is a
7620 			 * requirement for chunk allocation, see the comment on
7621 			 * top of btrfs_chunk_alloc() for details.
7622 			 */
7623 			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7624 			ret = read_one_chunk(&found_key, leaf, chunk);
7625 			if (ret)
7626 				goto error;
7627 		}
7628 	}
7629 	/* Catch error found during iteration */
7630 	if (iter_ret < 0) {
7631 		ret = iter_ret;
7632 		goto error;
7633 	}
7634 
7635 	/*
7636 	 * After loading chunk tree, we've got all device information,
7637 	 * do another round of validation checks.
7638 	 */
7639 	if (total_dev != fs_info->fs_devices->total_devices) {
7640 		btrfs_warn(fs_info,
7641 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7642 			  btrfs_super_num_devices(fs_info->super_copy),
7643 			  total_dev);
7644 		fs_info->fs_devices->total_devices = total_dev;
7645 		btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7646 	}
7647 	if (btrfs_super_total_bytes(fs_info->super_copy) <
7648 	    fs_info->fs_devices->total_rw_bytes) {
7649 		btrfs_err(fs_info,
7650 	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7651 			  btrfs_super_total_bytes(fs_info->super_copy),
7652 			  fs_info->fs_devices->total_rw_bytes);
7653 		ret = -EINVAL;
7654 		goto error;
7655 	}
7656 	ret = 0;
7657 error:
7658 	mutex_unlock(&uuid_mutex);
7659 
7660 	btrfs_free_path(path);
7661 	return ret;
7662 }
7663 
7664 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7665 {
7666 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7667 	struct btrfs_device *device;
7668 
7669 	fs_devices->fs_info = fs_info;
7670 
7671 	mutex_lock(&fs_devices->device_list_mutex);
7672 	list_for_each_entry(device, &fs_devices->devices, dev_list)
7673 		device->fs_info = fs_info;
7674 
7675 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7676 		list_for_each_entry(device, &seed_devs->devices, dev_list)
7677 			device->fs_info = fs_info;
7678 
7679 		seed_devs->fs_info = fs_info;
7680 	}
7681 	mutex_unlock(&fs_devices->device_list_mutex);
7682 }
7683 
7684 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7685 				 const struct btrfs_dev_stats_item *ptr,
7686 				 int index)
7687 {
7688 	u64 val;
7689 
7690 	read_extent_buffer(eb, &val,
7691 			   offsetof(struct btrfs_dev_stats_item, values) +
7692 			    ((unsigned long)ptr) + (index * sizeof(u64)),
7693 			   sizeof(val));
7694 	return val;
7695 }
7696 
7697 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7698 				      struct btrfs_dev_stats_item *ptr,
7699 				      int index, u64 val)
7700 {
7701 	write_extent_buffer(eb, &val,
7702 			    offsetof(struct btrfs_dev_stats_item, values) +
7703 			     ((unsigned long)ptr) + (index * sizeof(u64)),
7704 			    sizeof(val));
7705 }
7706 
7707 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7708 				       struct btrfs_path *path)
7709 {
7710 	struct btrfs_dev_stats_item *ptr;
7711 	struct extent_buffer *eb;
7712 	struct btrfs_key key;
7713 	int item_size;
7714 	int i, ret, slot;
7715 
7716 	if (!device->fs_info->dev_root)
7717 		return 0;
7718 
7719 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7720 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7721 	key.offset = device->devid;
7722 	ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7723 	if (ret) {
7724 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7725 			btrfs_dev_stat_set(device, i, 0);
7726 		device->dev_stats_valid = 1;
7727 		btrfs_release_path(path);
7728 		return ret < 0 ? ret : 0;
7729 	}
7730 	slot = path->slots[0];
7731 	eb = path->nodes[0];
7732 	item_size = btrfs_item_size(eb, slot);
7733 
7734 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7735 
7736 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7737 		if (item_size >= (1 + i) * sizeof(__le64))
7738 			btrfs_dev_stat_set(device, i,
7739 					   btrfs_dev_stats_value(eb, ptr, i));
7740 		else
7741 			btrfs_dev_stat_set(device, i, 0);
7742 	}
7743 
7744 	device->dev_stats_valid = 1;
7745 	btrfs_dev_stat_print_on_load(device);
7746 	btrfs_release_path(path);
7747 
7748 	return 0;
7749 }
7750 
7751 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7752 {
7753 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7754 	struct btrfs_device *device;
7755 	struct btrfs_path *path = NULL;
7756 	int ret = 0;
7757 
7758 	path = btrfs_alloc_path();
7759 	if (!path)
7760 		return -ENOMEM;
7761 
7762 	mutex_lock(&fs_devices->device_list_mutex);
7763 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7764 		ret = btrfs_device_init_dev_stats(device, path);
7765 		if (ret)
7766 			goto out;
7767 	}
7768 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7769 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7770 			ret = btrfs_device_init_dev_stats(device, path);
7771 			if (ret)
7772 				goto out;
7773 		}
7774 	}
7775 out:
7776 	mutex_unlock(&fs_devices->device_list_mutex);
7777 
7778 	btrfs_free_path(path);
7779 	return ret;
7780 }
7781 
7782 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7783 				struct btrfs_device *device)
7784 {
7785 	struct btrfs_fs_info *fs_info = trans->fs_info;
7786 	struct btrfs_root *dev_root = fs_info->dev_root;
7787 	struct btrfs_path *path;
7788 	struct btrfs_key key;
7789 	struct extent_buffer *eb;
7790 	struct btrfs_dev_stats_item *ptr;
7791 	int ret;
7792 	int i;
7793 
7794 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7795 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7796 	key.offset = device->devid;
7797 
7798 	path = btrfs_alloc_path();
7799 	if (!path)
7800 		return -ENOMEM;
7801 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7802 	if (ret < 0) {
7803 		btrfs_warn_in_rcu(fs_info,
7804 			"error %d while searching for dev_stats item for device %s",
7805 			      ret, rcu_str_deref(device->name));
7806 		goto out;
7807 	}
7808 
7809 	if (ret == 0 &&
7810 	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7811 		/* need to delete old one and insert a new one */
7812 		ret = btrfs_del_item(trans, dev_root, path);
7813 		if (ret != 0) {
7814 			btrfs_warn_in_rcu(fs_info,
7815 				"delete too small dev_stats item for device %s failed %d",
7816 				      rcu_str_deref(device->name), ret);
7817 			goto out;
7818 		}
7819 		ret = 1;
7820 	}
7821 
7822 	if (ret == 1) {
7823 		/* need to insert a new item */
7824 		btrfs_release_path(path);
7825 		ret = btrfs_insert_empty_item(trans, dev_root, path,
7826 					      &key, sizeof(*ptr));
7827 		if (ret < 0) {
7828 			btrfs_warn_in_rcu(fs_info,
7829 				"insert dev_stats item for device %s failed %d",
7830 				rcu_str_deref(device->name), ret);
7831 			goto out;
7832 		}
7833 	}
7834 
7835 	eb = path->nodes[0];
7836 	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7837 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7838 		btrfs_set_dev_stats_value(eb, ptr, i,
7839 					  btrfs_dev_stat_read(device, i));
7840 	btrfs_mark_buffer_dirty(eb);
7841 
7842 out:
7843 	btrfs_free_path(path);
7844 	return ret;
7845 }
7846 
7847 /*
7848  * called from commit_transaction. Writes all changed device stats to disk.
7849  */
7850 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7851 {
7852 	struct btrfs_fs_info *fs_info = trans->fs_info;
7853 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7854 	struct btrfs_device *device;
7855 	int stats_cnt;
7856 	int ret = 0;
7857 
7858 	mutex_lock(&fs_devices->device_list_mutex);
7859 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7860 		stats_cnt = atomic_read(&device->dev_stats_ccnt);
7861 		if (!device->dev_stats_valid || stats_cnt == 0)
7862 			continue;
7863 
7864 
7865 		/*
7866 		 * There is a LOAD-LOAD control dependency between the value of
7867 		 * dev_stats_ccnt and updating the on-disk values which requires
7868 		 * reading the in-memory counters. Such control dependencies
7869 		 * require explicit read memory barriers.
7870 		 *
7871 		 * This memory barriers pairs with smp_mb__before_atomic in
7872 		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7873 		 * barrier implied by atomic_xchg in
7874 		 * btrfs_dev_stats_read_and_reset
7875 		 */
7876 		smp_rmb();
7877 
7878 		ret = update_dev_stat_item(trans, device);
7879 		if (!ret)
7880 			atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7881 	}
7882 	mutex_unlock(&fs_devices->device_list_mutex);
7883 
7884 	return ret;
7885 }
7886 
7887 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7888 {
7889 	btrfs_dev_stat_inc(dev, index);
7890 
7891 	if (!dev->dev_stats_valid)
7892 		return;
7893 	btrfs_err_rl_in_rcu(dev->fs_info,
7894 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7895 			   rcu_str_deref(dev->name),
7896 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7897 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7898 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7899 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7900 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7901 }
7902 
7903 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7904 {
7905 	int i;
7906 
7907 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7908 		if (btrfs_dev_stat_read(dev, i) != 0)
7909 			break;
7910 	if (i == BTRFS_DEV_STAT_VALUES_MAX)
7911 		return; /* all values == 0, suppress message */
7912 
7913 	btrfs_info_in_rcu(dev->fs_info,
7914 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7915 	       rcu_str_deref(dev->name),
7916 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7917 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7918 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7919 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7920 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7921 }
7922 
7923 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7924 			struct btrfs_ioctl_get_dev_stats *stats)
7925 {
7926 	BTRFS_DEV_LOOKUP_ARGS(args);
7927 	struct btrfs_device *dev;
7928 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7929 	int i;
7930 
7931 	mutex_lock(&fs_devices->device_list_mutex);
7932 	args.devid = stats->devid;
7933 	dev = btrfs_find_device(fs_info->fs_devices, &args);
7934 	mutex_unlock(&fs_devices->device_list_mutex);
7935 
7936 	if (!dev) {
7937 		btrfs_warn(fs_info, "get dev_stats failed, device not found");
7938 		return -ENODEV;
7939 	} else if (!dev->dev_stats_valid) {
7940 		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7941 		return -ENODEV;
7942 	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7943 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7944 			if (stats->nr_items > i)
7945 				stats->values[i] =
7946 					btrfs_dev_stat_read_and_reset(dev, i);
7947 			else
7948 				btrfs_dev_stat_set(dev, i, 0);
7949 		}
7950 		btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7951 			   current->comm, task_pid_nr(current));
7952 	} else {
7953 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7954 			if (stats->nr_items > i)
7955 				stats->values[i] = btrfs_dev_stat_read(dev, i);
7956 	}
7957 	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7958 		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7959 	return 0;
7960 }
7961 
7962 /*
7963  * Update the size and bytes used for each device where it changed.  This is
7964  * delayed since we would otherwise get errors while writing out the
7965  * superblocks.
7966  *
7967  * Must be invoked during transaction commit.
7968  */
7969 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7970 {
7971 	struct btrfs_device *curr, *next;
7972 
7973 	ASSERT(trans->state == TRANS_STATE_COMMIT_DOING);
7974 
7975 	if (list_empty(&trans->dev_update_list))
7976 		return;
7977 
7978 	/*
7979 	 * We don't need the device_list_mutex here.  This list is owned by the
7980 	 * transaction and the transaction must complete before the device is
7981 	 * released.
7982 	 */
7983 	mutex_lock(&trans->fs_info->chunk_mutex);
7984 	list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7985 				 post_commit_list) {
7986 		list_del_init(&curr->post_commit_list);
7987 		curr->commit_total_bytes = curr->disk_total_bytes;
7988 		curr->commit_bytes_used = curr->bytes_used;
7989 	}
7990 	mutex_unlock(&trans->fs_info->chunk_mutex);
7991 }
7992 
7993 /*
7994  * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7995  */
7996 int btrfs_bg_type_to_factor(u64 flags)
7997 {
7998 	const int index = btrfs_bg_flags_to_raid_index(flags);
7999 
8000 	return btrfs_raid_array[index].ncopies;
8001 }
8002 
8003 
8004 
8005 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
8006 				 u64 chunk_offset, u64 devid,
8007 				 u64 physical_offset, u64 physical_len)
8008 {
8009 	struct btrfs_dev_lookup_args args = { .devid = devid };
8010 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8011 	struct extent_map *em;
8012 	struct map_lookup *map;
8013 	struct btrfs_device *dev;
8014 	u64 stripe_len;
8015 	bool found = false;
8016 	int ret = 0;
8017 	int i;
8018 
8019 	read_lock(&em_tree->lock);
8020 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
8021 	read_unlock(&em_tree->lock);
8022 
8023 	if (!em) {
8024 		btrfs_err(fs_info,
8025 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
8026 			  physical_offset, devid);
8027 		ret = -EUCLEAN;
8028 		goto out;
8029 	}
8030 
8031 	map = em->map_lookup;
8032 	stripe_len = btrfs_calc_stripe_length(em);
8033 	if (physical_len != stripe_len) {
8034 		btrfs_err(fs_info,
8035 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8036 			  physical_offset, devid, em->start, physical_len,
8037 			  stripe_len);
8038 		ret = -EUCLEAN;
8039 		goto out;
8040 	}
8041 
8042 	/*
8043 	 * Very old mkfs.btrfs (before v4.1) will not respect the reserved
8044 	 * space. Although kernel can handle it without problem, better to warn
8045 	 * the users.
8046 	 */
8047 	if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
8048 		btrfs_warn(fs_info,
8049 		"devid %llu physical %llu len %llu inside the reserved space",
8050 			   devid, physical_offset, physical_len);
8051 
8052 	for (i = 0; i < map->num_stripes; i++) {
8053 		if (map->stripes[i].dev->devid == devid &&
8054 		    map->stripes[i].physical == physical_offset) {
8055 			found = true;
8056 			if (map->verified_stripes >= map->num_stripes) {
8057 				btrfs_err(fs_info,
8058 				"too many dev extents for chunk %llu found",
8059 					  em->start);
8060 				ret = -EUCLEAN;
8061 				goto out;
8062 			}
8063 			map->verified_stripes++;
8064 			break;
8065 		}
8066 	}
8067 	if (!found) {
8068 		btrfs_err(fs_info,
8069 	"dev extent physical offset %llu devid %llu has no corresponding chunk",
8070 			physical_offset, devid);
8071 		ret = -EUCLEAN;
8072 	}
8073 
8074 	/* Make sure no dev extent is beyond device boundary */
8075 	dev = btrfs_find_device(fs_info->fs_devices, &args);
8076 	if (!dev) {
8077 		btrfs_err(fs_info, "failed to find devid %llu", devid);
8078 		ret = -EUCLEAN;
8079 		goto out;
8080 	}
8081 
8082 	if (physical_offset + physical_len > dev->disk_total_bytes) {
8083 		btrfs_err(fs_info,
8084 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8085 			  devid, physical_offset, physical_len,
8086 			  dev->disk_total_bytes);
8087 		ret = -EUCLEAN;
8088 		goto out;
8089 	}
8090 
8091 	if (dev->zone_info) {
8092 		u64 zone_size = dev->zone_info->zone_size;
8093 
8094 		if (!IS_ALIGNED(physical_offset, zone_size) ||
8095 		    !IS_ALIGNED(physical_len, zone_size)) {
8096 			btrfs_err(fs_info,
8097 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8098 				  devid, physical_offset, physical_len);
8099 			ret = -EUCLEAN;
8100 			goto out;
8101 		}
8102 	}
8103 
8104 out:
8105 	free_extent_map(em);
8106 	return ret;
8107 }
8108 
8109 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8110 {
8111 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
8112 	struct extent_map *em;
8113 	struct rb_node *node;
8114 	int ret = 0;
8115 
8116 	read_lock(&em_tree->lock);
8117 	for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
8118 		em = rb_entry(node, struct extent_map, rb_node);
8119 		if (em->map_lookup->num_stripes !=
8120 		    em->map_lookup->verified_stripes) {
8121 			btrfs_err(fs_info,
8122 			"chunk %llu has missing dev extent, have %d expect %d",
8123 				  em->start, em->map_lookup->verified_stripes,
8124 				  em->map_lookup->num_stripes);
8125 			ret = -EUCLEAN;
8126 			goto out;
8127 		}
8128 	}
8129 out:
8130 	read_unlock(&em_tree->lock);
8131 	return ret;
8132 }
8133 
8134 /*
8135  * Ensure that all dev extents are mapped to correct chunk, otherwise
8136  * later chunk allocation/free would cause unexpected behavior.
8137  *
8138  * NOTE: This will iterate through the whole device tree, which should be of
8139  * the same size level as the chunk tree.  This slightly increases mount time.
8140  */
8141 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8142 {
8143 	struct btrfs_path *path;
8144 	struct btrfs_root *root = fs_info->dev_root;
8145 	struct btrfs_key key;
8146 	u64 prev_devid = 0;
8147 	u64 prev_dev_ext_end = 0;
8148 	int ret = 0;
8149 
8150 	/*
8151 	 * We don't have a dev_root because we mounted with ignorebadroots and
8152 	 * failed to load the root, so we want to skip the verification in this
8153 	 * case for sure.
8154 	 *
8155 	 * However if the dev root is fine, but the tree itself is corrupted
8156 	 * we'd still fail to mount.  This verification is only to make sure
8157 	 * writes can happen safely, so instead just bypass this check
8158 	 * completely in the case of IGNOREBADROOTS.
8159 	 */
8160 	if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8161 		return 0;
8162 
8163 	key.objectid = 1;
8164 	key.type = BTRFS_DEV_EXTENT_KEY;
8165 	key.offset = 0;
8166 
8167 	path = btrfs_alloc_path();
8168 	if (!path)
8169 		return -ENOMEM;
8170 
8171 	path->reada = READA_FORWARD;
8172 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8173 	if (ret < 0)
8174 		goto out;
8175 
8176 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8177 		ret = btrfs_next_leaf(root, path);
8178 		if (ret < 0)
8179 			goto out;
8180 		/* No dev extents at all? Not good */
8181 		if (ret > 0) {
8182 			ret = -EUCLEAN;
8183 			goto out;
8184 		}
8185 	}
8186 	while (1) {
8187 		struct extent_buffer *leaf = path->nodes[0];
8188 		struct btrfs_dev_extent *dext;
8189 		int slot = path->slots[0];
8190 		u64 chunk_offset;
8191 		u64 physical_offset;
8192 		u64 physical_len;
8193 		u64 devid;
8194 
8195 		btrfs_item_key_to_cpu(leaf, &key, slot);
8196 		if (key.type != BTRFS_DEV_EXTENT_KEY)
8197 			break;
8198 		devid = key.objectid;
8199 		physical_offset = key.offset;
8200 
8201 		dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8202 		chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8203 		physical_len = btrfs_dev_extent_length(leaf, dext);
8204 
8205 		/* Check if this dev extent overlaps with the previous one */
8206 		if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
8207 			btrfs_err(fs_info,
8208 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8209 				  devid, physical_offset, prev_dev_ext_end);
8210 			ret = -EUCLEAN;
8211 			goto out;
8212 		}
8213 
8214 		ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8215 					    physical_offset, physical_len);
8216 		if (ret < 0)
8217 			goto out;
8218 		prev_devid = devid;
8219 		prev_dev_ext_end = physical_offset + physical_len;
8220 
8221 		ret = btrfs_next_item(root, path);
8222 		if (ret < 0)
8223 			goto out;
8224 		if (ret > 0) {
8225 			ret = 0;
8226 			break;
8227 		}
8228 	}
8229 
8230 	/* Ensure all chunks have corresponding dev extents */
8231 	ret = verify_chunk_dev_extent_mapping(fs_info);
8232 out:
8233 	btrfs_free_path(path);
8234 	return ret;
8235 }
8236 
8237 /*
8238  * Check whether the given block group or device is pinned by any inode being
8239  * used as a swapfile.
8240  */
8241 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8242 {
8243 	struct btrfs_swapfile_pin *sp;
8244 	struct rb_node *node;
8245 
8246 	spin_lock(&fs_info->swapfile_pins_lock);
8247 	node = fs_info->swapfile_pins.rb_node;
8248 	while (node) {
8249 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8250 		if (ptr < sp->ptr)
8251 			node = node->rb_left;
8252 		else if (ptr > sp->ptr)
8253 			node = node->rb_right;
8254 		else
8255 			break;
8256 	}
8257 	spin_unlock(&fs_info->swapfile_pins_lock);
8258 	return node != NULL;
8259 }
8260 
8261 static int relocating_repair_kthread(void *data)
8262 {
8263 	struct btrfs_block_group *cache = data;
8264 	struct btrfs_fs_info *fs_info = cache->fs_info;
8265 	u64 target;
8266 	int ret = 0;
8267 
8268 	target = cache->start;
8269 	btrfs_put_block_group(cache);
8270 
8271 	sb_start_write(fs_info->sb);
8272 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8273 		btrfs_info(fs_info,
8274 			   "zoned: skip relocating block group %llu to repair: EBUSY",
8275 			   target);
8276 		sb_end_write(fs_info->sb);
8277 		return -EBUSY;
8278 	}
8279 
8280 	mutex_lock(&fs_info->reclaim_bgs_lock);
8281 
8282 	/* Ensure block group still exists */
8283 	cache = btrfs_lookup_block_group(fs_info, target);
8284 	if (!cache)
8285 		goto out;
8286 
8287 	if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8288 		goto out;
8289 
8290 	ret = btrfs_may_alloc_data_chunk(fs_info, target);
8291 	if (ret < 0)
8292 		goto out;
8293 
8294 	btrfs_info(fs_info,
8295 		   "zoned: relocating block group %llu to repair IO failure",
8296 		   target);
8297 	ret = btrfs_relocate_chunk(fs_info, target);
8298 
8299 out:
8300 	if (cache)
8301 		btrfs_put_block_group(cache);
8302 	mutex_unlock(&fs_info->reclaim_bgs_lock);
8303 	btrfs_exclop_finish(fs_info);
8304 	sb_end_write(fs_info->sb);
8305 
8306 	return ret;
8307 }
8308 
8309 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8310 {
8311 	struct btrfs_block_group *cache;
8312 
8313 	if (!btrfs_is_zoned(fs_info))
8314 		return false;
8315 
8316 	/* Do not attempt to repair in degraded state */
8317 	if (btrfs_test_opt(fs_info, DEGRADED))
8318 		return true;
8319 
8320 	cache = btrfs_lookup_block_group(fs_info, logical);
8321 	if (!cache)
8322 		return true;
8323 
8324 	if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8325 		btrfs_put_block_group(cache);
8326 		return true;
8327 	}
8328 
8329 	kthread_run(relocating_repair_kthread, cache,
8330 		    "btrfs-relocating-repair");
8331 
8332 	return true;
8333 }
8334 
8335 int __init btrfs_bioset_init(void)
8336 {
8337 	if (bioset_init(&btrfs_bioset, BIO_POOL_SIZE,
8338 			offsetof(struct btrfs_bio, bio),
8339 			BIOSET_NEED_BVECS))
8340 		return -ENOMEM;
8341 	return 0;
8342 }
8343 
8344 void __cold btrfs_bioset_exit(void)
8345 {
8346 	bioset_exit(&btrfs_bioset);
8347 }
8348