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