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