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