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