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