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