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