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