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