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