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