xref: /linux/fs/btrfs/volumes.c (revision 978d337c2ed6e5313ee426871a410eddc796ccfd)
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 terminated.  We use
1381 	 * '%s' to print the label, if not properly NUL terminated 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 (unlikely(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 
2006 	if (!kern_path(device_path, LOOKUP_FOLLOW, &path)) {
2007 		vfs_utimes(&path, NULL);
2008 		path_put(&path);
2009 	}
2010 }
2011 
btrfs_rm_dev_item(struct btrfs_trans_handle * trans,struct btrfs_device * device)2012 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
2013 			     struct btrfs_device *device)
2014 {
2015 	struct btrfs_root *root = device->fs_info->chunk_root;
2016 	int ret;
2017 	struct btrfs_path *path;
2018 	struct btrfs_key key;
2019 
2020 	path = btrfs_alloc_path();
2021 	if (!path)
2022 		return -ENOMEM;
2023 
2024 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2025 	key.type = BTRFS_DEV_ITEM_KEY;
2026 	key.offset = device->devid;
2027 
2028 	btrfs_reserve_chunk_metadata(trans, false);
2029 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2030 	btrfs_trans_release_chunk_metadata(trans);
2031 	if (ret) {
2032 		if (ret > 0)
2033 			ret = -ENOENT;
2034 		goto out;
2035 	}
2036 
2037 	ret = btrfs_del_item(trans, root, path);
2038 out:
2039 	btrfs_free_path(path);
2040 	return ret;
2041 }
2042 
2043 /*
2044  * Verify that @num_devices satisfies the RAID profile constraints in the whole
2045  * filesystem. It's up to the caller to adjust that number regarding eg. device
2046  * replace.
2047  */
btrfs_check_raid_min_devices(struct btrfs_fs_info * fs_info,u64 num_devices)2048 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2049 		u64 num_devices)
2050 {
2051 	u64 all_avail;
2052 	unsigned seq;
2053 	int i;
2054 
2055 	do {
2056 		seq = read_seqbegin(&fs_info->profiles_lock);
2057 
2058 		all_avail = fs_info->avail_data_alloc_bits |
2059 			    fs_info->avail_system_alloc_bits |
2060 			    fs_info->avail_metadata_alloc_bits;
2061 	} while (read_seqretry(&fs_info->profiles_lock, seq));
2062 
2063 	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2064 		if (!(all_avail & btrfs_raid_array[i].bg_flag))
2065 			continue;
2066 
2067 		if (num_devices < btrfs_raid_array[i].devs_min)
2068 			return btrfs_raid_array[i].mindev_error;
2069 	}
2070 
2071 	return 0;
2072 }
2073 
btrfs_find_next_active_device(struct btrfs_fs_devices * fs_devs,struct btrfs_device * device)2074 static struct btrfs_device * btrfs_find_next_active_device(
2075 		struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2076 {
2077 	struct btrfs_device *next_device;
2078 
2079 	list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2080 		if (next_device != device &&
2081 		    !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2082 		    && next_device->bdev)
2083 			return next_device;
2084 	}
2085 
2086 	return NULL;
2087 }
2088 
2089 /*
2090  * Helper function to check if the given device is part of s_bdev / latest_dev
2091  * and replace it with the provided or the next active device, in the context
2092  * where this function called, there should be always be another device (or
2093  * this_dev) which is active.
2094  */
btrfs_assign_next_active_device(struct btrfs_device * device,struct btrfs_device * next_device)2095 void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2096 					    struct btrfs_device *next_device)
2097 {
2098 	struct btrfs_fs_info *fs_info = device->fs_info;
2099 
2100 	if (!next_device)
2101 		next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2102 							    device);
2103 	ASSERT(next_device);
2104 
2105 	if (fs_info->sb->s_bdev &&
2106 			(fs_info->sb->s_bdev == device->bdev))
2107 		fs_info->sb->s_bdev = next_device->bdev;
2108 
2109 	if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
2110 		fs_info->fs_devices->latest_dev = next_device;
2111 }
2112 
2113 /*
2114  * Return btrfs_fs_devices::num_devices excluding the device that's being
2115  * currently replaced.
2116  */
btrfs_num_devices(struct btrfs_fs_info * fs_info)2117 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2118 {
2119 	u64 num_devices = fs_info->fs_devices->num_devices;
2120 
2121 	down_read(&fs_info->dev_replace.rwsem);
2122 	if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2123 		ASSERT(num_devices > 1, "num_devices=%llu", num_devices);
2124 		num_devices--;
2125 	}
2126 	up_read(&fs_info->dev_replace.rwsem);
2127 
2128 	return num_devices;
2129 }
2130 
btrfs_scratch_superblock(struct btrfs_fs_info * fs_info,struct block_device * bdev,int copy_num)2131 static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info,
2132 				     struct block_device *bdev, int copy_num)
2133 {
2134 	struct btrfs_super_block *disk_super;
2135 	const size_t len = sizeof(disk_super->magic);
2136 	const u64 bytenr = btrfs_sb_offset(copy_num);
2137 	int ret;
2138 
2139 	disk_super = btrfs_read_disk_super(bdev, copy_num, false);
2140 	if (IS_ERR(disk_super))
2141 		return;
2142 
2143 	memset(&disk_super->magic, 0, len);
2144 	folio_mark_dirty(virt_to_folio(disk_super));
2145 	btrfs_release_disk_super(disk_super);
2146 
2147 	ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1);
2148 	if (ret)
2149 		btrfs_warn(fs_info, "error clearing superblock number %d (%d)",
2150 			copy_num, ret);
2151 }
2152 
btrfs_scratch_superblocks(struct btrfs_fs_info * fs_info,struct btrfs_device * device)2153 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info, struct btrfs_device *device)
2154 {
2155 	int copy_num;
2156 	struct block_device *bdev = device->bdev;
2157 
2158 	if (!bdev)
2159 		return;
2160 
2161 	for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2162 		if (bdev_is_zoned(bdev))
2163 			btrfs_reset_sb_log_zones(bdev, copy_num);
2164 		else
2165 			btrfs_scratch_superblock(fs_info, bdev, copy_num);
2166 	}
2167 
2168 	/* Notify udev that device has changed */
2169 	btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2170 
2171 	/* Update ctime/mtime for device path for libblkid */
2172 	update_dev_time(rcu_dereference_raw(device->name));
2173 }
2174 
btrfs_rm_device(struct btrfs_fs_info * fs_info,struct btrfs_dev_lookup_args * args,struct file ** bdev_file)2175 int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2176 		    struct btrfs_dev_lookup_args *args,
2177 		    struct file **bdev_file)
2178 {
2179 	struct btrfs_trans_handle *trans;
2180 	struct btrfs_device *device;
2181 	struct btrfs_fs_devices *cur_devices;
2182 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2183 	u64 num_devices;
2184 	int ret = 0;
2185 
2186 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2187 		btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2188 		return -EINVAL;
2189 	}
2190 
2191 	/*
2192 	 * The device list in fs_devices is accessed without locks (neither
2193 	 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2194 	 * filesystem and another device rm cannot run.
2195 	 */
2196 	num_devices = btrfs_num_devices(fs_info);
2197 
2198 	ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2199 	if (ret)
2200 		return ret;
2201 
2202 	device = btrfs_find_device(fs_info->fs_devices, args);
2203 	if (!device) {
2204 		if (args->missing)
2205 			ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2206 		else
2207 			ret = -ENOENT;
2208 		return ret;
2209 	}
2210 
2211 	if (btrfs_pinned_by_swapfile(fs_info, device)) {
2212 		btrfs_warn(fs_info,
2213 		  "cannot remove device %s (devid %llu) due to active swapfile",
2214 				  btrfs_dev_name(device), device->devid);
2215 		return -ETXTBSY;
2216 	}
2217 
2218 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2219 		return BTRFS_ERROR_DEV_TGT_REPLACE;
2220 
2221 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2222 	    fs_info->fs_devices->rw_devices == 1)
2223 		return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2224 
2225 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2226 		mutex_lock(&fs_info->chunk_mutex);
2227 		list_del_init(&device->dev_alloc_list);
2228 		device->fs_devices->rw_devices--;
2229 		mutex_unlock(&fs_info->chunk_mutex);
2230 	}
2231 
2232 	ret = btrfs_shrink_device(device, 0);
2233 	if (ret)
2234 		goto error_undo;
2235 
2236 	trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2237 	if (IS_ERR(trans)) {
2238 		ret = PTR_ERR(trans);
2239 		goto error_undo;
2240 	}
2241 
2242 	ret = btrfs_rm_dev_item(trans, device);
2243 	if (unlikely(ret)) {
2244 		/* Any error in dev item removal is critical */
2245 		btrfs_crit(fs_info,
2246 			   "failed to remove device item for devid %llu: %d",
2247 			   device->devid, ret);
2248 		btrfs_abort_transaction(trans, ret);
2249 		btrfs_end_transaction(trans);
2250 		return ret;
2251 	}
2252 
2253 	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2254 	btrfs_scrub_cancel_dev(device);
2255 
2256 	/*
2257 	 * the device list mutex makes sure that we don't change
2258 	 * the device list while someone else is writing out all
2259 	 * the device supers. Whoever is writing all supers, should
2260 	 * lock the device list mutex before getting the number of
2261 	 * devices in the super block (super_copy). Conversely,
2262 	 * whoever updates the number of devices in the super block
2263 	 * (super_copy) should hold the device list mutex.
2264 	 */
2265 
2266 	/*
2267 	 * In normal cases the cur_devices == fs_devices. But in case
2268 	 * of deleting a seed device, the cur_devices should point to
2269 	 * its own fs_devices listed under the fs_devices->seed_list.
2270 	 */
2271 	cur_devices = device->fs_devices;
2272 	mutex_lock(&fs_devices->device_list_mutex);
2273 	list_del_rcu(&device->dev_list);
2274 
2275 	cur_devices->num_devices--;
2276 	cur_devices->total_devices--;
2277 	/* Update total_devices of the parent fs_devices if it's seed */
2278 	if (cur_devices != fs_devices)
2279 		fs_devices->total_devices--;
2280 
2281 	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2282 		cur_devices->missing_devices--;
2283 
2284 	btrfs_assign_next_active_device(device, NULL);
2285 
2286 	if (device->bdev_file) {
2287 		cur_devices->open_devices--;
2288 		/* remove sysfs entry */
2289 		btrfs_sysfs_remove_device(device);
2290 	}
2291 
2292 	num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2293 	btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2294 	mutex_unlock(&fs_devices->device_list_mutex);
2295 
2296 	/*
2297 	 * At this point, the device is zero sized and detached from the
2298 	 * devices list.  All that's left is to zero out the old supers and
2299 	 * free the device.
2300 	 *
2301 	 * We cannot call btrfs_close_bdev() here because we're holding the sb
2302 	 * write lock, and bdev_fput() on the block device will pull in the
2303 	 * ->open_mutex on the block device and it's dependencies.  Instead
2304 	 *  just flush the device and let the caller do the final bdev_release.
2305 	 */
2306 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2307 		btrfs_scratch_superblocks(fs_info, device);
2308 		if (device->bdev) {
2309 			sync_blockdev(device->bdev);
2310 			invalidate_bdev(device->bdev);
2311 		}
2312 	}
2313 
2314 	*bdev_file = device->bdev_file;
2315 	synchronize_rcu();
2316 	btrfs_free_device(device);
2317 
2318 	/*
2319 	 * This can happen if cur_devices is the private seed devices list.  We
2320 	 * cannot call close_fs_devices() here because it expects the uuid_mutex
2321 	 * to be held, but in fact we don't need that for the private
2322 	 * seed_devices, we can simply decrement cur_devices->opened and then
2323 	 * remove it from our list and free the fs_devices.
2324 	 */
2325 	if (cur_devices->num_devices == 0) {
2326 		list_del_init(&cur_devices->seed_list);
2327 		ASSERT(cur_devices->opened == 1, "opened=%d", cur_devices->opened);
2328 		cur_devices->opened--;
2329 		free_fs_devices(cur_devices);
2330 	}
2331 
2332 	ret = btrfs_commit_transaction(trans);
2333 
2334 	return ret;
2335 
2336 error_undo:
2337 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2338 		mutex_lock(&fs_info->chunk_mutex);
2339 		list_add(&device->dev_alloc_list,
2340 			 &fs_devices->alloc_list);
2341 		device->fs_devices->rw_devices++;
2342 		mutex_unlock(&fs_info->chunk_mutex);
2343 	}
2344 	return ret;
2345 }
2346 
btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device * srcdev)2347 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2348 {
2349 	struct btrfs_fs_devices *fs_devices;
2350 
2351 	lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2352 
2353 	/*
2354 	 * in case of fs with no seed, srcdev->fs_devices will point
2355 	 * to fs_devices of fs_info. However when the dev being replaced is
2356 	 * a seed dev it will point to the seed's local fs_devices. In short
2357 	 * srcdev will have its correct fs_devices in both the cases.
2358 	 */
2359 	fs_devices = srcdev->fs_devices;
2360 
2361 	list_del_rcu(&srcdev->dev_list);
2362 	list_del(&srcdev->dev_alloc_list);
2363 	fs_devices->num_devices--;
2364 	if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2365 		fs_devices->missing_devices--;
2366 
2367 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2368 		fs_devices->rw_devices--;
2369 
2370 	if (srcdev->bdev)
2371 		fs_devices->open_devices--;
2372 }
2373 
btrfs_rm_dev_replace_free_srcdev(struct btrfs_device * srcdev)2374 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2375 {
2376 	struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2377 
2378 	mutex_lock(&uuid_mutex);
2379 
2380 	btrfs_close_bdev(srcdev);
2381 	synchronize_rcu();
2382 	btrfs_free_device(srcdev);
2383 
2384 	/* if this is no devs we rather delete the fs_devices */
2385 	if (!fs_devices->num_devices) {
2386 		/*
2387 		 * On a mounted FS, num_devices can't be zero unless it's a
2388 		 * seed. In case of a seed device being replaced, the replace
2389 		 * target added to the sprout FS, so there will be no more
2390 		 * device left under the seed FS.
2391 		 */
2392 		ASSERT(fs_devices->seeding);
2393 
2394 		list_del_init(&fs_devices->seed_list);
2395 		close_fs_devices(fs_devices);
2396 		free_fs_devices(fs_devices);
2397 	}
2398 	mutex_unlock(&uuid_mutex);
2399 }
2400 
btrfs_destroy_dev_replace_tgtdev(struct btrfs_device * tgtdev)2401 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2402 {
2403 	struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2404 
2405 	mutex_lock(&fs_devices->device_list_mutex);
2406 
2407 	btrfs_sysfs_remove_device(tgtdev);
2408 
2409 	if (tgtdev->bdev)
2410 		fs_devices->open_devices--;
2411 
2412 	fs_devices->num_devices--;
2413 
2414 	btrfs_assign_next_active_device(tgtdev, NULL);
2415 
2416 	list_del_rcu(&tgtdev->dev_list);
2417 
2418 	mutex_unlock(&fs_devices->device_list_mutex);
2419 
2420 	btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev);
2421 
2422 	btrfs_close_bdev(tgtdev);
2423 	synchronize_rcu();
2424 	btrfs_free_device(tgtdev);
2425 }
2426 
2427 /*
2428  * Populate args from device at path.
2429  *
2430  * @fs_info:	the filesystem
2431  * @args:	the args to populate
2432  * @path:	the path to the device
2433  *
2434  * This will read the super block of the device at @path and populate @args with
2435  * the devid, fsid, and uuid.  This is meant to be used for ioctls that need to
2436  * lookup a device to operate on, but need to do it before we take any locks.
2437  * This properly handles the special case of "missing" that a user may pass in,
2438  * and does some basic sanity checks.  The caller must make sure that @path is
2439  * properly NUL terminated before calling in, and must call
2440  * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2441  * uuid buffers.
2442  *
2443  * Return: 0 for success, -errno for failure
2444  */
btrfs_get_dev_args_from_path(struct btrfs_fs_info * fs_info,struct btrfs_dev_lookup_args * args,const char * path)2445 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2446 				 struct btrfs_dev_lookup_args *args,
2447 				 const char *path)
2448 {
2449 	struct btrfs_super_block *disk_super;
2450 	struct file *bdev_file;
2451 	int ret;
2452 
2453 	if (!path || !path[0])
2454 		return -EINVAL;
2455 	if (!strcmp(path, "missing")) {
2456 		args->missing = true;
2457 		return 0;
2458 	}
2459 
2460 	args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2461 	args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2462 	if (!args->uuid || !args->fsid) {
2463 		btrfs_put_dev_args_from_path(args);
2464 		return -ENOMEM;
2465 	}
2466 
2467 	ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0,
2468 				    &bdev_file, &disk_super);
2469 	if (ret) {
2470 		btrfs_put_dev_args_from_path(args);
2471 		return ret;
2472 	}
2473 
2474 	args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2475 	memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2476 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2477 		memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2478 	else
2479 		memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2480 	btrfs_release_disk_super(disk_super);
2481 	bdev_fput(bdev_file);
2482 	return 0;
2483 }
2484 
2485 /*
2486  * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2487  * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2488  * that don't need to be freed.
2489  */
btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args * args)2490 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2491 {
2492 	kfree(args->uuid);
2493 	kfree(args->fsid);
2494 	args->uuid = NULL;
2495 	args->fsid = NULL;
2496 }
2497 
btrfs_find_device_by_devspec(struct btrfs_fs_info * fs_info,u64 devid,const char * device_path)2498 struct btrfs_device *btrfs_find_device_by_devspec(
2499 		struct btrfs_fs_info *fs_info, u64 devid,
2500 		const char *device_path)
2501 {
2502 	BTRFS_DEV_LOOKUP_ARGS(args);
2503 	struct btrfs_device *device;
2504 	int ret;
2505 
2506 	if (devid) {
2507 		args.devid = devid;
2508 		device = btrfs_find_device(fs_info->fs_devices, &args);
2509 		if (!device)
2510 			return ERR_PTR(-ENOENT);
2511 		return device;
2512 	}
2513 
2514 	ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2515 	if (ret)
2516 		return ERR_PTR(ret);
2517 	device = btrfs_find_device(fs_info->fs_devices, &args);
2518 	btrfs_put_dev_args_from_path(&args);
2519 	if (!device)
2520 		return ERR_PTR(-ENOENT);
2521 	return device;
2522 }
2523 
btrfs_init_sprout(struct btrfs_fs_info * fs_info)2524 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2525 {
2526 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2527 	struct btrfs_fs_devices *old_devices;
2528 	struct btrfs_fs_devices *seed_devices;
2529 
2530 	lockdep_assert_held(&uuid_mutex);
2531 	if (!fs_devices->seeding)
2532 		return ERR_PTR(-EINVAL);
2533 
2534 	/*
2535 	 * Private copy of the seed devices, anchored at
2536 	 * fs_info->fs_devices->seed_list
2537 	 */
2538 	seed_devices = alloc_fs_devices(NULL);
2539 	if (IS_ERR(seed_devices))
2540 		return seed_devices;
2541 
2542 	/*
2543 	 * It's necessary to retain a copy of the original seed fs_devices in
2544 	 * fs_uuids so that filesystems which have been seeded can successfully
2545 	 * reference the seed device from open_seed_devices. This also supports
2546 	 * multiple fs seed.
2547 	 */
2548 	old_devices = clone_fs_devices(fs_devices);
2549 	if (IS_ERR(old_devices)) {
2550 		kfree(seed_devices);
2551 		return old_devices;
2552 	}
2553 
2554 	list_add(&old_devices->fs_list, &fs_uuids);
2555 
2556 	memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2557 	seed_devices->opened = 1;
2558 	INIT_LIST_HEAD(&seed_devices->devices);
2559 	INIT_LIST_HEAD(&seed_devices->alloc_list);
2560 	mutex_init(&seed_devices->device_list_mutex);
2561 
2562 	return seed_devices;
2563 }
2564 
2565 /*
2566  * Splice seed devices into the sprout fs_devices.
2567  * Generate a new fsid for the sprouted read-write filesystem.
2568  */
btrfs_setup_sprout(struct btrfs_fs_info * fs_info,struct btrfs_fs_devices * seed_devices)2569 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2570 			       struct btrfs_fs_devices *seed_devices)
2571 {
2572 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2573 	struct btrfs_super_block *disk_super = fs_info->super_copy;
2574 	struct btrfs_device *device;
2575 	u64 super_flags;
2576 
2577 	/*
2578 	 * We are updating the fsid, the thread leading to device_list_add()
2579 	 * could race, so uuid_mutex is needed.
2580 	 */
2581 	lockdep_assert_held(&uuid_mutex);
2582 
2583 	/*
2584 	 * The threads listed below may traverse dev_list but can do that without
2585 	 * device_list_mutex:
2586 	 * - All device ops and balance - as we are in btrfs_exclop_start.
2587 	 * - Various dev_list readers - are using RCU.
2588 	 * - btrfs_ioctl_fitrim() - is using RCU.
2589 	 *
2590 	 * For-read threads as below are using device_list_mutex:
2591 	 * - Readonly scrub btrfs_scrub_dev()
2592 	 * - Readonly scrub btrfs_scrub_progress()
2593 	 * - btrfs_get_dev_stats()
2594 	 */
2595 	lockdep_assert_held(&fs_devices->device_list_mutex);
2596 
2597 	list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2598 			      synchronize_rcu);
2599 	list_for_each_entry(device, &seed_devices->devices, dev_list)
2600 		device->fs_devices = seed_devices;
2601 
2602 	fs_devices->seeding = false;
2603 	fs_devices->num_devices = 0;
2604 	fs_devices->open_devices = 0;
2605 	fs_devices->missing_devices = 0;
2606 	fs_devices->rotating = false;
2607 	list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2608 
2609 	generate_random_uuid(fs_devices->fsid);
2610 	memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2611 	memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2612 
2613 	super_flags = btrfs_super_flags(disk_super) &
2614 		      ~BTRFS_SUPER_FLAG_SEEDING;
2615 	btrfs_set_super_flags(disk_super, super_flags);
2616 }
2617 
2618 /*
2619  * Store the expected generation for seed devices in device items.
2620  */
btrfs_finish_sprout(struct btrfs_trans_handle * trans)2621 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2622 {
2623 	BTRFS_DEV_LOOKUP_ARGS(args);
2624 	struct btrfs_fs_info *fs_info = trans->fs_info;
2625 	struct btrfs_root *root = fs_info->chunk_root;
2626 	struct btrfs_path *path;
2627 	struct extent_buffer *leaf;
2628 	struct btrfs_dev_item *dev_item;
2629 	struct btrfs_device *device;
2630 	struct btrfs_key key;
2631 	u8 fs_uuid[BTRFS_FSID_SIZE];
2632 	u8 dev_uuid[BTRFS_UUID_SIZE];
2633 	int ret;
2634 
2635 	path = btrfs_alloc_path();
2636 	if (!path)
2637 		return -ENOMEM;
2638 
2639 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2640 	key.type = BTRFS_DEV_ITEM_KEY;
2641 	key.offset = 0;
2642 
2643 	while (1) {
2644 		btrfs_reserve_chunk_metadata(trans, false);
2645 		ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2646 		btrfs_trans_release_chunk_metadata(trans);
2647 		if (ret < 0)
2648 			goto error;
2649 
2650 		leaf = path->nodes[0];
2651 next_slot:
2652 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2653 			ret = btrfs_next_leaf(root, path);
2654 			if (ret > 0)
2655 				break;
2656 			if (ret < 0)
2657 				goto error;
2658 			leaf = path->nodes[0];
2659 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2660 			btrfs_release_path(path);
2661 			continue;
2662 		}
2663 
2664 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2665 		if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2666 		    key.type != BTRFS_DEV_ITEM_KEY)
2667 			break;
2668 
2669 		dev_item = btrfs_item_ptr(leaf, path->slots[0],
2670 					  struct btrfs_dev_item);
2671 		args.devid = btrfs_device_id(leaf, dev_item);
2672 		read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2673 				   BTRFS_UUID_SIZE);
2674 		read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2675 				   BTRFS_FSID_SIZE);
2676 		args.uuid = dev_uuid;
2677 		args.fsid = fs_uuid;
2678 		device = btrfs_find_device(fs_info->fs_devices, &args);
2679 		BUG_ON(!device); /* Logic error */
2680 
2681 		if (device->fs_devices->seeding)
2682 			btrfs_set_device_generation(leaf, dev_item,
2683 						    device->generation);
2684 
2685 		path->slots[0]++;
2686 		goto next_slot;
2687 	}
2688 	ret = 0;
2689 error:
2690 	btrfs_free_path(path);
2691 	return ret;
2692 }
2693 
btrfs_init_new_device(struct btrfs_fs_info * fs_info,const char * device_path)2694 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2695 {
2696 	struct btrfs_root *root = fs_info->dev_root;
2697 	struct btrfs_trans_handle *trans;
2698 	struct btrfs_device *device;
2699 	struct file *bdev_file;
2700 	struct super_block *sb = fs_info->sb;
2701 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2702 	struct btrfs_fs_devices *seed_devices = NULL;
2703 	u64 orig_super_total_bytes;
2704 	u64 orig_super_num_devices;
2705 	int ret = 0;
2706 	bool seeding_dev = false;
2707 	bool locked = false;
2708 
2709 	if (sb_rdonly(sb) && !fs_devices->seeding)
2710 		return -EROFS;
2711 
2712 	bdev_file = bdev_file_open_by_path(device_path, BLK_OPEN_WRITE,
2713 					   fs_info->sb, &fs_holder_ops);
2714 	if (IS_ERR(bdev_file))
2715 		return PTR_ERR(bdev_file);
2716 
2717 	if (!btrfs_check_device_zone_type(fs_info, file_bdev(bdev_file))) {
2718 		ret = -EINVAL;
2719 		goto error;
2720 	}
2721 
2722 	if (bdev_nr_bytes(file_bdev(bdev_file)) <= BTRFS_DEVICE_RANGE_RESERVED) {
2723 		ret = -EINVAL;
2724 		goto error;
2725 	}
2726 
2727 	if (fs_devices->seeding) {
2728 		seeding_dev = true;
2729 		down_write(&sb->s_umount);
2730 		mutex_lock(&uuid_mutex);
2731 		locked = true;
2732 	}
2733 
2734 	sync_blockdev(file_bdev(bdev_file));
2735 
2736 	rcu_read_lock();
2737 	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2738 		if (device->bdev == file_bdev(bdev_file)) {
2739 			ret = -EEXIST;
2740 			rcu_read_unlock();
2741 			goto error;
2742 		}
2743 	}
2744 	rcu_read_unlock();
2745 
2746 	device = btrfs_alloc_device(fs_info, NULL, NULL, device_path);
2747 	if (IS_ERR(device)) {
2748 		/* we can safely leave the fs_devices entry around */
2749 		ret = PTR_ERR(device);
2750 		goto error;
2751 	}
2752 
2753 	device->fs_info = fs_info;
2754 	device->bdev_file = bdev_file;
2755 	device->bdev = file_bdev(bdev_file);
2756 	ret = lookup_bdev(device_path, &device->devt);
2757 	if (ret)
2758 		goto error_free_device;
2759 
2760 	ret = btrfs_get_dev_zone_info(device, false);
2761 	if (ret)
2762 		goto error_free_device;
2763 
2764 	trans = btrfs_start_transaction(root, 0);
2765 	if (IS_ERR(trans)) {
2766 		ret = PTR_ERR(trans);
2767 		goto error_free_zone;
2768 	}
2769 
2770 	set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2771 	device->generation = trans->transid;
2772 	device->io_width = fs_info->sectorsize;
2773 	device->io_align = fs_info->sectorsize;
2774 	device->sector_size = fs_info->sectorsize;
2775 	device->total_bytes =
2776 		round_down(bdev_nr_bytes(device->bdev), fs_info->sectorsize);
2777 	device->disk_total_bytes = device->total_bytes;
2778 	device->commit_total_bytes = device->total_bytes;
2779 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2780 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2781 	device->dev_stats_valid = 1;
2782 	set_blocksize(device->bdev_file, BTRFS_BDEV_BLOCKSIZE);
2783 
2784 	if (seeding_dev) {
2785 		/* GFP_KERNEL allocation must not be under device_list_mutex */
2786 		seed_devices = btrfs_init_sprout(fs_info);
2787 		if (IS_ERR(seed_devices)) {
2788 			ret = PTR_ERR(seed_devices);
2789 			btrfs_abort_transaction(trans, ret);
2790 			goto error_trans;
2791 		}
2792 	}
2793 
2794 	mutex_lock(&fs_devices->device_list_mutex);
2795 	if (seeding_dev) {
2796 		btrfs_setup_sprout(fs_info, seed_devices);
2797 		btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2798 						device);
2799 	}
2800 
2801 	device->fs_devices = fs_devices;
2802 
2803 	mutex_lock(&fs_info->chunk_mutex);
2804 	list_add_rcu(&device->dev_list, &fs_devices->devices);
2805 	list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2806 	fs_devices->num_devices++;
2807 	fs_devices->open_devices++;
2808 	fs_devices->rw_devices++;
2809 	fs_devices->total_devices++;
2810 	fs_devices->total_rw_bytes += device->total_bytes;
2811 
2812 	atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2813 
2814 	if (!bdev_nonrot(device->bdev))
2815 		fs_devices->rotating = true;
2816 
2817 	orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2818 	btrfs_set_super_total_bytes(fs_info->super_copy,
2819 		round_down(orig_super_total_bytes + device->total_bytes,
2820 			   fs_info->sectorsize));
2821 
2822 	orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2823 	btrfs_set_super_num_devices(fs_info->super_copy,
2824 				    orig_super_num_devices + 1);
2825 
2826 	/*
2827 	 * we've got more storage, clear any full flags on the space
2828 	 * infos
2829 	 */
2830 	btrfs_clear_space_info_full(fs_info);
2831 
2832 	mutex_unlock(&fs_info->chunk_mutex);
2833 
2834 	/* Add sysfs device entry */
2835 	btrfs_sysfs_add_device(device);
2836 
2837 	mutex_unlock(&fs_devices->device_list_mutex);
2838 
2839 	if (seeding_dev) {
2840 		mutex_lock(&fs_info->chunk_mutex);
2841 		ret = init_first_rw_device(trans);
2842 		mutex_unlock(&fs_info->chunk_mutex);
2843 		if (unlikely(ret)) {
2844 			btrfs_abort_transaction(trans, ret);
2845 			goto error_sysfs;
2846 		}
2847 	}
2848 
2849 	ret = btrfs_add_dev_item(trans, device);
2850 	if (unlikely(ret)) {
2851 		btrfs_abort_transaction(trans, ret);
2852 		goto error_sysfs;
2853 	}
2854 
2855 	if (seeding_dev) {
2856 		ret = btrfs_finish_sprout(trans);
2857 		if (unlikely(ret)) {
2858 			btrfs_abort_transaction(trans, ret);
2859 			goto error_sysfs;
2860 		}
2861 
2862 		/*
2863 		 * fs_devices now represents the newly sprouted filesystem and
2864 		 * its fsid has been changed by btrfs_sprout_splice().
2865 		 */
2866 		btrfs_sysfs_update_sprout_fsid(fs_devices);
2867 	}
2868 
2869 	ret = btrfs_commit_transaction(trans);
2870 
2871 	if (seeding_dev) {
2872 		mutex_unlock(&uuid_mutex);
2873 		up_write(&sb->s_umount);
2874 		locked = false;
2875 
2876 		if (ret) /* transaction commit */
2877 			return ret;
2878 
2879 		ret = btrfs_relocate_sys_chunks(fs_info);
2880 		if (ret < 0)
2881 			btrfs_handle_fs_error(fs_info, ret,
2882 				    "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2883 		trans = btrfs_attach_transaction(root);
2884 		if (IS_ERR(trans)) {
2885 			if (PTR_ERR(trans) == -ENOENT)
2886 				return 0;
2887 			ret = PTR_ERR(trans);
2888 			trans = NULL;
2889 			goto error_sysfs;
2890 		}
2891 		ret = btrfs_commit_transaction(trans);
2892 	}
2893 
2894 	/*
2895 	 * Now that we have written a new super block to this device, check all
2896 	 * other fs_devices list if device_path alienates any other scanned
2897 	 * device.
2898 	 * We can ignore the return value as it typically returns -EINVAL and
2899 	 * only succeeds if the device was an alien.
2900 	 */
2901 	btrfs_forget_devices(device->devt);
2902 
2903 	/* Update ctime/mtime for blkid or udev */
2904 	update_dev_time(device_path);
2905 
2906 	return ret;
2907 
2908 error_sysfs:
2909 	btrfs_sysfs_remove_device(device);
2910 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
2911 	mutex_lock(&fs_info->chunk_mutex);
2912 	list_del_rcu(&device->dev_list);
2913 	list_del(&device->dev_alloc_list);
2914 	fs_info->fs_devices->num_devices--;
2915 	fs_info->fs_devices->open_devices--;
2916 	fs_info->fs_devices->rw_devices--;
2917 	fs_info->fs_devices->total_devices--;
2918 	fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2919 	atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2920 	btrfs_set_super_total_bytes(fs_info->super_copy,
2921 				    orig_super_total_bytes);
2922 	btrfs_set_super_num_devices(fs_info->super_copy,
2923 				    orig_super_num_devices);
2924 	mutex_unlock(&fs_info->chunk_mutex);
2925 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2926 error_trans:
2927 	if (trans)
2928 		btrfs_end_transaction(trans);
2929 error_free_zone:
2930 	btrfs_destroy_dev_zone_info(device);
2931 error_free_device:
2932 	btrfs_free_device(device);
2933 error:
2934 	bdev_fput(bdev_file);
2935 	if (locked) {
2936 		mutex_unlock(&uuid_mutex);
2937 		up_write(&sb->s_umount);
2938 	}
2939 	return ret;
2940 }
2941 
btrfs_update_device(struct btrfs_trans_handle * trans,struct btrfs_device * device)2942 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2943 					struct btrfs_device *device)
2944 {
2945 	int ret;
2946 	struct btrfs_path *path;
2947 	struct btrfs_root *root = device->fs_info->chunk_root;
2948 	struct btrfs_dev_item *dev_item;
2949 	struct extent_buffer *leaf;
2950 	struct btrfs_key key;
2951 
2952 	path = btrfs_alloc_path();
2953 	if (!path)
2954 		return -ENOMEM;
2955 
2956 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2957 	key.type = BTRFS_DEV_ITEM_KEY;
2958 	key.offset = device->devid;
2959 
2960 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2961 	if (ret < 0)
2962 		goto out;
2963 
2964 	if (ret > 0) {
2965 		ret = -ENOENT;
2966 		goto out;
2967 	}
2968 
2969 	leaf = path->nodes[0];
2970 	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2971 
2972 	btrfs_set_device_id(leaf, dev_item, device->devid);
2973 	btrfs_set_device_type(leaf, dev_item, device->type);
2974 	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2975 	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2976 	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2977 	btrfs_set_device_total_bytes(leaf, dev_item,
2978 				     btrfs_device_get_disk_total_bytes(device));
2979 	btrfs_set_device_bytes_used(leaf, dev_item,
2980 				    btrfs_device_get_bytes_used(device));
2981 out:
2982 	btrfs_free_path(path);
2983 	return ret;
2984 }
2985 
btrfs_grow_device(struct btrfs_trans_handle * trans,struct btrfs_device * device,u64 new_size)2986 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2987 		      struct btrfs_device *device, u64 new_size)
2988 {
2989 	struct btrfs_fs_info *fs_info = device->fs_info;
2990 	struct btrfs_super_block *super_copy = fs_info->super_copy;
2991 	u64 old_total;
2992 	u64 diff;
2993 	int ret;
2994 
2995 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2996 		return -EACCES;
2997 
2998 	new_size = round_down(new_size, fs_info->sectorsize);
2999 
3000 	mutex_lock(&fs_info->chunk_mutex);
3001 	old_total = btrfs_super_total_bytes(super_copy);
3002 	diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
3003 
3004 	if (new_size <= device->total_bytes ||
3005 	    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
3006 		mutex_unlock(&fs_info->chunk_mutex);
3007 		return -EINVAL;
3008 	}
3009 
3010 	btrfs_set_super_total_bytes(super_copy,
3011 			round_down(old_total + diff, fs_info->sectorsize));
3012 	device->fs_devices->total_rw_bytes += diff;
3013 	atomic64_add(diff, &fs_info->free_chunk_space);
3014 
3015 	btrfs_device_set_total_bytes(device, new_size);
3016 	btrfs_device_set_disk_total_bytes(device, new_size);
3017 	btrfs_clear_space_info_full(device->fs_info);
3018 	if (list_empty(&device->post_commit_list))
3019 		list_add_tail(&device->post_commit_list,
3020 			      &trans->transaction->dev_update_list);
3021 	mutex_unlock(&fs_info->chunk_mutex);
3022 
3023 	btrfs_reserve_chunk_metadata(trans, false);
3024 	ret = btrfs_update_device(trans, device);
3025 	btrfs_trans_release_chunk_metadata(trans);
3026 
3027 	return ret;
3028 }
3029 
btrfs_free_chunk(struct btrfs_trans_handle * trans,u64 chunk_offset)3030 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3031 {
3032 	struct btrfs_fs_info *fs_info = trans->fs_info;
3033 	struct btrfs_root *root = fs_info->chunk_root;
3034 	int ret;
3035 	struct btrfs_path *path;
3036 	struct btrfs_key key;
3037 
3038 	path = btrfs_alloc_path();
3039 	if (!path)
3040 		return -ENOMEM;
3041 
3042 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3043 	key.type = BTRFS_CHUNK_ITEM_KEY;
3044 	key.offset = chunk_offset;
3045 
3046 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3047 	if (ret < 0)
3048 		goto out;
3049 	else if (unlikely(ret > 0)) { /* Logic error or corruption */
3050 		btrfs_err(fs_info, "failed to lookup chunk %llu when freeing",
3051 			  chunk_offset);
3052 		btrfs_abort_transaction(trans, -ENOENT);
3053 		ret = -EUCLEAN;
3054 		goto out;
3055 	}
3056 
3057 	ret = btrfs_del_item(trans, root, path);
3058 	if (unlikely(ret < 0)) {
3059 		btrfs_err(fs_info, "failed to delete chunk %llu item", chunk_offset);
3060 		btrfs_abort_transaction(trans, ret);
3061 		goto out;
3062 	}
3063 out:
3064 	btrfs_free_path(path);
3065 	return ret;
3066 }
3067 
btrfs_del_sys_chunk(struct btrfs_fs_info * fs_info,u64 chunk_offset)3068 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3069 {
3070 	struct btrfs_super_block *super_copy = fs_info->super_copy;
3071 	struct btrfs_disk_key *disk_key;
3072 	struct btrfs_chunk *chunk;
3073 	u8 *ptr;
3074 	int ret = 0;
3075 	u32 num_stripes;
3076 	u32 array_size;
3077 	u32 len = 0;
3078 	u32 cur;
3079 	struct btrfs_key key;
3080 
3081 	lockdep_assert_held(&fs_info->chunk_mutex);
3082 	array_size = btrfs_super_sys_array_size(super_copy);
3083 
3084 	ptr = super_copy->sys_chunk_array;
3085 	cur = 0;
3086 
3087 	while (cur < array_size) {
3088 		disk_key = (struct btrfs_disk_key *)ptr;
3089 		btrfs_disk_key_to_cpu(&key, disk_key);
3090 
3091 		len = sizeof(*disk_key);
3092 
3093 		if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3094 			chunk = (struct btrfs_chunk *)(ptr + len);
3095 			num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3096 			len += btrfs_chunk_item_size(num_stripes);
3097 		} else {
3098 			ret = -EIO;
3099 			break;
3100 		}
3101 		if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3102 		    key.offset == chunk_offset) {
3103 			memmove(ptr, ptr + len, array_size - (cur + len));
3104 			array_size -= len;
3105 			btrfs_set_super_sys_array_size(super_copy, array_size);
3106 		} else {
3107 			ptr += len;
3108 			cur += len;
3109 		}
3110 	}
3111 	return ret;
3112 }
3113 
btrfs_find_chunk_map_nolock(struct btrfs_fs_info * fs_info,u64 logical,u64 length)3114 struct btrfs_chunk_map *btrfs_find_chunk_map_nolock(struct btrfs_fs_info *fs_info,
3115 						    u64 logical, u64 length)
3116 {
3117 	struct rb_node *node = fs_info->mapping_tree.rb_root.rb_node;
3118 	struct rb_node *prev = NULL;
3119 	struct rb_node *orig_prev;
3120 	struct btrfs_chunk_map *map;
3121 	struct btrfs_chunk_map *prev_map = NULL;
3122 
3123 	while (node) {
3124 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
3125 		prev = node;
3126 		prev_map = map;
3127 
3128 		if (logical < map->start) {
3129 			node = node->rb_left;
3130 		} else if (logical >= map->start + map->chunk_len) {
3131 			node = node->rb_right;
3132 		} else {
3133 			refcount_inc(&map->refs);
3134 			return map;
3135 		}
3136 	}
3137 
3138 	if (!prev)
3139 		return NULL;
3140 
3141 	orig_prev = prev;
3142 	while (prev && logical >= prev_map->start + prev_map->chunk_len) {
3143 		prev = rb_next(prev);
3144 		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3145 	}
3146 
3147 	if (!prev) {
3148 		prev = orig_prev;
3149 		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3150 		while (prev && logical < prev_map->start) {
3151 			prev = rb_prev(prev);
3152 			prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3153 		}
3154 	}
3155 
3156 	if (prev) {
3157 		u64 end = logical + length;
3158 
3159 		/*
3160 		 * Caller can pass a U64_MAX length when it wants to get any
3161 		 * chunk starting at an offset of 'logical' or higher, so deal
3162 		 * with underflow by resetting the end offset to U64_MAX.
3163 		 */
3164 		if (end < logical)
3165 			end = U64_MAX;
3166 
3167 		if (end > prev_map->start &&
3168 		    logical < prev_map->start + prev_map->chunk_len) {
3169 			refcount_inc(&prev_map->refs);
3170 			return prev_map;
3171 		}
3172 	}
3173 
3174 	return NULL;
3175 }
3176 
btrfs_find_chunk_map(struct btrfs_fs_info * fs_info,u64 logical,u64 length)3177 struct btrfs_chunk_map *btrfs_find_chunk_map(struct btrfs_fs_info *fs_info,
3178 					     u64 logical, u64 length)
3179 {
3180 	struct btrfs_chunk_map *map;
3181 
3182 	read_lock(&fs_info->mapping_tree_lock);
3183 	map = btrfs_find_chunk_map_nolock(fs_info, logical, length);
3184 	read_unlock(&fs_info->mapping_tree_lock);
3185 
3186 	return map;
3187 }
3188 
3189 /*
3190  * Find the mapping containing the given logical extent.
3191  *
3192  * @logical: Logical block offset in bytes.
3193  * @length: Length of extent in bytes.
3194  *
3195  * Return: Chunk mapping or ERR_PTR.
3196  */
btrfs_get_chunk_map(struct btrfs_fs_info * fs_info,u64 logical,u64 length)3197 struct btrfs_chunk_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3198 					    u64 logical, u64 length)
3199 {
3200 	struct btrfs_chunk_map *map;
3201 
3202 	map = btrfs_find_chunk_map(fs_info, logical, length);
3203 
3204 	if (unlikely(!map)) {
3205 		btrfs_crit(fs_info,
3206 			   "unable to find chunk map for logical %llu length %llu",
3207 			   logical, length);
3208 		return ERR_PTR(-EINVAL);
3209 	}
3210 
3211 	if (unlikely(map->start > logical || map->start + map->chunk_len <= logical)) {
3212 		btrfs_crit(fs_info,
3213 			   "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3214 			   logical, logical + length, map->start,
3215 			   map->start + map->chunk_len);
3216 		btrfs_free_chunk_map(map);
3217 		return ERR_PTR(-EINVAL);
3218 	}
3219 
3220 	/* Callers are responsible for dropping the reference. */
3221 	return map;
3222 }
3223 
remove_chunk_item(struct btrfs_trans_handle * trans,struct btrfs_chunk_map * map,u64 chunk_offset)3224 static int remove_chunk_item(struct btrfs_trans_handle *trans,
3225 			     struct btrfs_chunk_map *map, u64 chunk_offset)
3226 {
3227 	int i;
3228 
3229 	/*
3230 	 * Removing chunk items and updating the device items in the chunks btree
3231 	 * requires holding the chunk_mutex.
3232 	 * See the comment at btrfs_chunk_alloc() for the details.
3233 	 */
3234 	lockdep_assert_held(&trans->fs_info->chunk_mutex);
3235 
3236 	for (i = 0; i < map->num_stripes; i++) {
3237 		int ret;
3238 
3239 		ret = btrfs_update_device(trans, map->stripes[i].dev);
3240 		if (ret)
3241 			return ret;
3242 	}
3243 
3244 	return btrfs_free_chunk(trans, chunk_offset);
3245 }
3246 
btrfs_remove_chunk(struct btrfs_trans_handle * trans,u64 chunk_offset)3247 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3248 {
3249 	struct btrfs_fs_info *fs_info = trans->fs_info;
3250 	struct btrfs_chunk_map *map;
3251 	u64 dev_extent_len = 0;
3252 	int i, ret = 0;
3253 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3254 
3255 	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3256 	if (IS_ERR(map)) {
3257 		/*
3258 		 * This is a logic error, but we don't want to just rely on the
3259 		 * user having built with ASSERT enabled, so if ASSERT doesn't
3260 		 * do anything we still error out.
3261 		 */
3262 		DEBUG_WARN("errr %ld reading chunk map at offset %llu",
3263 			   PTR_ERR(map), chunk_offset);
3264 		return PTR_ERR(map);
3265 	}
3266 
3267 	/*
3268 	 * First delete the device extent items from the devices btree.
3269 	 * We take the device_list_mutex to avoid racing with the finishing phase
3270 	 * of a device replace operation. See the comment below before acquiring
3271 	 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3272 	 * because that can result in a deadlock when deleting the device extent
3273 	 * items from the devices btree - COWing an extent buffer from the btree
3274 	 * may result in allocating a new metadata chunk, which would attempt to
3275 	 * lock again fs_info->chunk_mutex.
3276 	 */
3277 	mutex_lock(&fs_devices->device_list_mutex);
3278 	for (i = 0; i < map->num_stripes; i++) {
3279 		struct btrfs_device *device = map->stripes[i].dev;
3280 		ret = btrfs_free_dev_extent(trans, device,
3281 					    map->stripes[i].physical,
3282 					    &dev_extent_len);
3283 		if (unlikely(ret)) {
3284 			mutex_unlock(&fs_devices->device_list_mutex);
3285 			btrfs_abort_transaction(trans, ret);
3286 			goto out;
3287 		}
3288 
3289 		if (device->bytes_used > 0) {
3290 			mutex_lock(&fs_info->chunk_mutex);
3291 			btrfs_device_set_bytes_used(device,
3292 					device->bytes_used - dev_extent_len);
3293 			atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3294 			btrfs_clear_space_info_full(fs_info);
3295 
3296 			if (list_empty(&device->post_commit_list)) {
3297 				list_add_tail(&device->post_commit_list,
3298 					      &trans->transaction->dev_update_list);
3299 			}
3300 
3301 			mutex_unlock(&fs_info->chunk_mutex);
3302 		}
3303 	}
3304 	mutex_unlock(&fs_devices->device_list_mutex);
3305 
3306 	/*
3307 	 * We acquire fs_info->chunk_mutex for 2 reasons:
3308 	 *
3309 	 * 1) Just like with the first phase of the chunk allocation, we must
3310 	 *    reserve system space, do all chunk btree updates and deletions, and
3311 	 *    update the system chunk array in the superblock while holding this
3312 	 *    mutex. This is for similar reasons as explained on the comment at
3313 	 *    the top of btrfs_chunk_alloc();
3314 	 *
3315 	 * 2) Prevent races with the final phase of a device replace operation
3316 	 *    that replaces the device object associated with the map's stripes,
3317 	 *    because the device object's id can change at any time during that
3318 	 *    final phase of the device replace operation
3319 	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3320 	 *    replaced device and then see it with an ID of
3321 	 *    BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3322 	 *    the device item, which does not exists on the chunk btree.
3323 	 *    The finishing phase of device replace acquires both the
3324 	 *    device_list_mutex and the chunk_mutex, in that order, so we are
3325 	 *    safe by just acquiring the chunk_mutex.
3326 	 */
3327 	trans->removing_chunk = true;
3328 	mutex_lock(&fs_info->chunk_mutex);
3329 
3330 	check_system_chunk(trans, map->type);
3331 
3332 	ret = remove_chunk_item(trans, map, chunk_offset);
3333 	/*
3334 	 * Normally we should not get -ENOSPC since we reserved space before
3335 	 * through the call to check_system_chunk().
3336 	 *
3337 	 * Despite our system space_info having enough free space, we may not
3338 	 * be able to allocate extents from its block groups, because all have
3339 	 * an incompatible profile, which will force us to allocate a new system
3340 	 * block group with the right profile, or right after we called
3341 	 * check_system_space() above, a scrub turned the only system block group
3342 	 * with enough free space into RO mode.
3343 	 * This is explained with more detail at do_chunk_alloc().
3344 	 *
3345 	 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3346 	 */
3347 	if (ret == -ENOSPC) {
3348 		const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3349 		struct btrfs_block_group *sys_bg;
3350 		struct btrfs_space_info *space_info;
3351 
3352 		space_info = btrfs_find_space_info(fs_info, sys_flags);
3353 		if (unlikely(!space_info)) {
3354 			ret = -EINVAL;
3355 			btrfs_abort_transaction(trans, ret);
3356 			goto out;
3357 		}
3358 
3359 		sys_bg = btrfs_create_chunk(trans, space_info, sys_flags);
3360 		if (IS_ERR(sys_bg)) {
3361 			ret = PTR_ERR(sys_bg);
3362 			btrfs_abort_transaction(trans, ret);
3363 			goto out;
3364 		}
3365 
3366 		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3367 		if (unlikely(ret)) {
3368 			btrfs_abort_transaction(trans, ret);
3369 			goto out;
3370 		}
3371 
3372 		ret = remove_chunk_item(trans, map, chunk_offset);
3373 		if (unlikely(ret)) {
3374 			btrfs_abort_transaction(trans, ret);
3375 			goto out;
3376 		}
3377 	} else if (unlikely(ret)) {
3378 		btrfs_abort_transaction(trans, ret);
3379 		goto out;
3380 	}
3381 
3382 	trace_btrfs_chunk_free(fs_info, map, chunk_offset, map->chunk_len);
3383 
3384 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3385 		ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3386 		if (unlikely(ret)) {
3387 			btrfs_abort_transaction(trans, ret);
3388 			goto out;
3389 		}
3390 	}
3391 
3392 	mutex_unlock(&fs_info->chunk_mutex);
3393 	trans->removing_chunk = false;
3394 
3395 	/*
3396 	 * We are done with chunk btree updates and deletions, so release the
3397 	 * system space we previously reserved (with check_system_chunk()).
3398 	 */
3399 	btrfs_trans_release_chunk_metadata(trans);
3400 
3401 	ret = btrfs_remove_block_group(trans, map);
3402 	if (unlikely(ret)) {
3403 		btrfs_abort_transaction(trans, ret);
3404 		goto out;
3405 	}
3406 
3407 out:
3408 	if (trans->removing_chunk) {
3409 		mutex_unlock(&fs_info->chunk_mutex);
3410 		trans->removing_chunk = false;
3411 	}
3412 	/* once for us */
3413 	btrfs_free_chunk_map(map);
3414 	return ret;
3415 }
3416 
btrfs_relocate_chunk(struct btrfs_fs_info * fs_info,u64 chunk_offset,bool verbose)3417 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3418 			 bool verbose)
3419 {
3420 	struct btrfs_root *root = fs_info->chunk_root;
3421 	struct btrfs_trans_handle *trans;
3422 	struct btrfs_block_group *block_group;
3423 	u64 length;
3424 	int ret;
3425 
3426 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3427 		btrfs_err(fs_info,
3428 			  "relocate: not supported on extent tree v2 yet");
3429 		return -EINVAL;
3430 	}
3431 
3432 	/*
3433 	 * Prevent races with automatic removal of unused block groups.
3434 	 * After we relocate and before we remove the chunk with offset
3435 	 * chunk_offset, automatic removal of the block group can kick in,
3436 	 * resulting in a failure when calling btrfs_remove_chunk() below.
3437 	 *
3438 	 * Make sure to acquire this mutex before doing a tree search (dev
3439 	 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3440 	 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3441 	 * we release the path used to search the chunk/dev tree and before
3442 	 * the current task acquires this mutex and calls us.
3443 	 */
3444 	lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3445 
3446 	/* step one, relocate all the extents inside this chunk */
3447 	btrfs_scrub_pause(fs_info);
3448 	ret = btrfs_relocate_block_group(fs_info, chunk_offset, true);
3449 	btrfs_scrub_continue(fs_info);
3450 	if (ret) {
3451 		/*
3452 		 * If we had a transaction abort, stop all running scrubs.
3453 		 * See transaction.c:cleanup_transaction() why we do it here.
3454 		 */
3455 		if (BTRFS_FS_ERROR(fs_info))
3456 			btrfs_scrub_cancel(fs_info);
3457 		return ret;
3458 	}
3459 
3460 	block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3461 	if (!block_group)
3462 		return -ENOENT;
3463 	btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3464 	length = block_group->length;
3465 	btrfs_put_block_group(block_group);
3466 
3467 	/*
3468 	 * On a zoned file system, discard the whole block group, this will
3469 	 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3470 	 * resetting the zone fails, don't treat it as a fatal problem from the
3471 	 * filesystem's point of view.
3472 	 */
3473 	if (btrfs_is_zoned(fs_info)) {
3474 		ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3475 		if (ret)
3476 			btrfs_info(fs_info,
3477 				"failed to reset zone %llu after relocation",
3478 				chunk_offset);
3479 	}
3480 
3481 	trans = btrfs_start_trans_remove_block_group(root->fs_info,
3482 						     chunk_offset);
3483 	if (IS_ERR(trans)) {
3484 		ret = PTR_ERR(trans);
3485 		btrfs_handle_fs_error(root->fs_info, ret, NULL);
3486 		return ret;
3487 	}
3488 
3489 	/*
3490 	 * step two, delete the device extents and the
3491 	 * chunk tree entries
3492 	 */
3493 	ret = btrfs_remove_chunk(trans, chunk_offset);
3494 	btrfs_end_transaction(trans);
3495 	return ret;
3496 }
3497 
btrfs_relocate_sys_chunks(struct btrfs_fs_info * fs_info)3498 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3499 {
3500 	struct btrfs_root *chunk_root = fs_info->chunk_root;
3501 	struct btrfs_path *path;
3502 	struct extent_buffer *leaf;
3503 	struct btrfs_chunk *chunk;
3504 	struct btrfs_key key;
3505 	struct btrfs_key found_key;
3506 	u64 chunk_type;
3507 	bool retried = false;
3508 	int failed = 0;
3509 	int ret;
3510 
3511 	path = btrfs_alloc_path();
3512 	if (!path)
3513 		return -ENOMEM;
3514 
3515 again:
3516 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3517 	key.type = BTRFS_CHUNK_ITEM_KEY;
3518 	key.offset = (u64)-1;
3519 
3520 	while (1) {
3521 		mutex_lock(&fs_info->reclaim_bgs_lock);
3522 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3523 		if (ret < 0) {
3524 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3525 			goto error;
3526 		}
3527 		if (unlikely(ret == 0)) {
3528 			/*
3529 			 * On the first search we would find chunk tree with
3530 			 * offset -1, which is not possible. On subsequent
3531 			 * loops this would find an existing item on an invalid
3532 			 * offset (one less than the previous one, wrong
3533 			 * alignment and size).
3534 			 */
3535 			ret = -EUCLEAN;
3536 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3537 			goto error;
3538 		}
3539 
3540 		ret = btrfs_previous_item(chunk_root, path, key.objectid,
3541 					  key.type);
3542 		if (ret)
3543 			mutex_unlock(&fs_info->reclaim_bgs_lock);
3544 		if (ret < 0)
3545 			goto error;
3546 		if (ret > 0)
3547 			break;
3548 
3549 		leaf = path->nodes[0];
3550 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3551 
3552 		chunk = btrfs_item_ptr(leaf, path->slots[0],
3553 				       struct btrfs_chunk);
3554 		chunk_type = btrfs_chunk_type(leaf, chunk);
3555 		btrfs_release_path(path);
3556 
3557 		if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3558 			ret = btrfs_relocate_chunk(fs_info, found_key.offset,
3559 						   true);
3560 			if (ret == -ENOSPC)
3561 				failed++;
3562 			else
3563 				BUG_ON(ret);
3564 		}
3565 		mutex_unlock(&fs_info->reclaim_bgs_lock);
3566 
3567 		if (found_key.offset == 0)
3568 			break;
3569 		key.offset = found_key.offset - 1;
3570 	}
3571 	ret = 0;
3572 	if (failed && !retried) {
3573 		failed = 0;
3574 		retried = true;
3575 		goto again;
3576 	} else if (WARN_ON(failed && retried)) {
3577 		ret = -ENOSPC;
3578 	}
3579 error:
3580 	btrfs_free_path(path);
3581 	return ret;
3582 }
3583 
3584 /*
3585  * return 1 : allocate a data chunk successfully,
3586  * return <0: errors during allocating a data chunk,
3587  * return 0 : no need to allocate a data chunk.
3588  */
btrfs_may_alloc_data_chunk(struct btrfs_fs_info * fs_info,u64 chunk_offset)3589 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3590 				      u64 chunk_offset)
3591 {
3592 	struct btrfs_block_group *cache;
3593 	u64 bytes_used;
3594 	u64 chunk_type;
3595 
3596 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3597 	ASSERT(cache);
3598 	chunk_type = cache->flags;
3599 	btrfs_put_block_group(cache);
3600 
3601 	if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3602 		return 0;
3603 
3604 	spin_lock(&fs_info->data_sinfo->lock);
3605 	bytes_used = fs_info->data_sinfo->bytes_used;
3606 	spin_unlock(&fs_info->data_sinfo->lock);
3607 
3608 	if (!bytes_used) {
3609 		struct btrfs_trans_handle *trans;
3610 		int ret;
3611 
3612 		trans =	btrfs_join_transaction(fs_info->tree_root);
3613 		if (IS_ERR(trans))
3614 			return PTR_ERR(trans);
3615 
3616 		ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3617 		btrfs_end_transaction(trans);
3618 		if (ret < 0)
3619 			return ret;
3620 		return 1;
3621 	}
3622 
3623 	return 0;
3624 }
3625 
btrfs_disk_balance_args_to_cpu(struct btrfs_balance_args * cpu,const struct btrfs_disk_balance_args * disk)3626 static void btrfs_disk_balance_args_to_cpu(struct btrfs_balance_args *cpu,
3627 					   const struct btrfs_disk_balance_args *disk)
3628 {
3629 	memset(cpu, 0, sizeof(*cpu));
3630 
3631 	cpu->profiles = le64_to_cpu(disk->profiles);
3632 	cpu->usage = le64_to_cpu(disk->usage);
3633 	cpu->devid = le64_to_cpu(disk->devid);
3634 	cpu->pstart = le64_to_cpu(disk->pstart);
3635 	cpu->pend = le64_to_cpu(disk->pend);
3636 	cpu->vstart = le64_to_cpu(disk->vstart);
3637 	cpu->vend = le64_to_cpu(disk->vend);
3638 	cpu->target = le64_to_cpu(disk->target);
3639 	cpu->flags = le64_to_cpu(disk->flags);
3640 	cpu->limit = le64_to_cpu(disk->limit);
3641 	cpu->stripes_min = le32_to_cpu(disk->stripes_min);
3642 	cpu->stripes_max = le32_to_cpu(disk->stripes_max);
3643 }
3644 
btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args * disk,const struct btrfs_balance_args * cpu)3645 static void btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args *disk,
3646 					   const struct btrfs_balance_args *cpu)
3647 {
3648 	memset(disk, 0, sizeof(*disk));
3649 
3650 	disk->profiles = cpu_to_le64(cpu->profiles);
3651 	disk->usage = cpu_to_le64(cpu->usage);
3652 	disk->devid = cpu_to_le64(cpu->devid);
3653 	disk->pstart = cpu_to_le64(cpu->pstart);
3654 	disk->pend = cpu_to_le64(cpu->pend);
3655 	disk->vstart = cpu_to_le64(cpu->vstart);
3656 	disk->vend = cpu_to_le64(cpu->vend);
3657 	disk->target = cpu_to_le64(cpu->target);
3658 	disk->flags = cpu_to_le64(cpu->flags);
3659 	disk->limit = cpu_to_le64(cpu->limit);
3660 	disk->stripes_min = cpu_to_le32(cpu->stripes_min);
3661 	disk->stripes_max = cpu_to_le32(cpu->stripes_max);
3662 }
3663 
insert_balance_item(struct btrfs_fs_info * fs_info,struct btrfs_balance_control * bctl)3664 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3665 			       struct btrfs_balance_control *bctl)
3666 {
3667 	struct btrfs_root *root = fs_info->tree_root;
3668 	struct btrfs_trans_handle *trans;
3669 	struct btrfs_balance_item *item;
3670 	struct btrfs_disk_balance_args disk_bargs;
3671 	struct btrfs_path *path;
3672 	struct extent_buffer *leaf;
3673 	struct btrfs_key key;
3674 	int ret, err;
3675 
3676 	path = btrfs_alloc_path();
3677 	if (!path)
3678 		return -ENOMEM;
3679 
3680 	trans = btrfs_start_transaction(root, 0);
3681 	if (IS_ERR(trans)) {
3682 		btrfs_free_path(path);
3683 		return PTR_ERR(trans);
3684 	}
3685 
3686 	key.objectid = BTRFS_BALANCE_OBJECTID;
3687 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3688 	key.offset = 0;
3689 
3690 	ret = btrfs_insert_empty_item(trans, root, path, &key,
3691 				      sizeof(*item));
3692 	if (ret)
3693 		goto out;
3694 
3695 	leaf = path->nodes[0];
3696 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3697 
3698 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3699 
3700 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3701 	btrfs_set_balance_data(leaf, item, &disk_bargs);
3702 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3703 	btrfs_set_balance_meta(leaf, item, &disk_bargs);
3704 	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3705 	btrfs_set_balance_sys(leaf, item, &disk_bargs);
3706 	btrfs_set_balance_flags(leaf, item, bctl->flags);
3707 out:
3708 	btrfs_free_path(path);
3709 	err = btrfs_commit_transaction(trans);
3710 	if (err && !ret)
3711 		ret = err;
3712 	return ret;
3713 }
3714 
del_balance_item(struct btrfs_fs_info * fs_info)3715 static int del_balance_item(struct btrfs_fs_info *fs_info)
3716 {
3717 	struct btrfs_root *root = fs_info->tree_root;
3718 	struct btrfs_trans_handle *trans;
3719 	struct btrfs_path *path;
3720 	struct btrfs_key key;
3721 	int ret, err;
3722 
3723 	path = btrfs_alloc_path();
3724 	if (!path)
3725 		return -ENOMEM;
3726 
3727 	trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3728 	if (IS_ERR(trans)) {
3729 		btrfs_free_path(path);
3730 		return PTR_ERR(trans);
3731 	}
3732 
3733 	key.objectid = BTRFS_BALANCE_OBJECTID;
3734 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3735 	key.offset = 0;
3736 
3737 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3738 	if (ret < 0)
3739 		goto out;
3740 	if (ret > 0) {
3741 		ret = -ENOENT;
3742 		goto out;
3743 	}
3744 
3745 	ret = btrfs_del_item(trans, root, path);
3746 out:
3747 	btrfs_free_path(path);
3748 	err = btrfs_commit_transaction(trans);
3749 	if (err && !ret)
3750 		ret = err;
3751 	return ret;
3752 }
3753 
3754 /*
3755  * This is a heuristic used to reduce the number of chunks balanced on
3756  * resume after balance was interrupted.
3757  */
update_balance_args(struct btrfs_balance_control * bctl)3758 static void update_balance_args(struct btrfs_balance_control *bctl)
3759 {
3760 	/*
3761 	 * Turn on soft mode for chunk types that were being converted.
3762 	 */
3763 	if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3764 		bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3765 	if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3766 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3767 	if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3768 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3769 
3770 	/*
3771 	 * Turn on usage filter if is not already used.  The idea is
3772 	 * that chunks that we have already balanced should be
3773 	 * reasonably full.  Don't do it for chunks that are being
3774 	 * converted - that will keep us from relocating unconverted
3775 	 * (albeit full) chunks.
3776 	 */
3777 	if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3778 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3779 	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3780 		bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3781 		bctl->data.usage = 90;
3782 	}
3783 	if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3784 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3785 	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3786 		bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3787 		bctl->sys.usage = 90;
3788 	}
3789 	if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3790 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3791 	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3792 		bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3793 		bctl->meta.usage = 90;
3794 	}
3795 }
3796 
3797 /*
3798  * Clear the balance status in fs_info and delete the balance item from disk.
3799  */
reset_balance_state(struct btrfs_fs_info * fs_info)3800 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3801 {
3802 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3803 	int ret;
3804 
3805 	ASSERT(fs_info->balance_ctl);
3806 
3807 	spin_lock(&fs_info->balance_lock);
3808 	fs_info->balance_ctl = NULL;
3809 	spin_unlock(&fs_info->balance_lock);
3810 
3811 	kfree(bctl);
3812 	ret = del_balance_item(fs_info);
3813 	if (ret)
3814 		btrfs_handle_fs_error(fs_info, ret, NULL);
3815 }
3816 
3817 /*
3818  * Balance filters.  Return 1 if chunk should be filtered out
3819  * (should not be balanced).
3820  */
chunk_profiles_filter(u64 chunk_type,struct btrfs_balance_args * bargs)3821 static bool chunk_profiles_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
3822 {
3823 	chunk_type = chunk_to_extended(chunk_type) &
3824 				BTRFS_EXTENDED_PROFILE_MASK;
3825 
3826 	if (bargs->profiles & chunk_type)
3827 		return false;
3828 
3829 	return true;
3830 }
3831 
chunk_usage_range_filter(struct btrfs_fs_info * fs_info,u64 chunk_offset,struct btrfs_balance_args * bargs)3832 static bool chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3833 				     struct btrfs_balance_args *bargs)
3834 {
3835 	struct btrfs_block_group *cache;
3836 	u64 chunk_used;
3837 	u64 user_thresh_min;
3838 	u64 user_thresh_max;
3839 	bool ret = true;
3840 
3841 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3842 	chunk_used = cache->used;
3843 
3844 	if (bargs->usage_min == 0)
3845 		user_thresh_min = 0;
3846 	else
3847 		user_thresh_min = mult_perc(cache->length, bargs->usage_min);
3848 
3849 	if (bargs->usage_max == 0)
3850 		user_thresh_max = 1;
3851 	else if (bargs->usage_max > 100)
3852 		user_thresh_max = cache->length;
3853 	else
3854 		user_thresh_max = mult_perc(cache->length, bargs->usage_max);
3855 
3856 	if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3857 		ret = false;
3858 
3859 	btrfs_put_block_group(cache);
3860 	return ret;
3861 }
3862 
chunk_usage_filter(struct btrfs_fs_info * fs_info,u64 chunk_offset,struct btrfs_balance_args * bargs)3863 static bool chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3864 			       struct btrfs_balance_args *bargs)
3865 {
3866 	struct btrfs_block_group *cache;
3867 	u64 chunk_used, user_thresh;
3868 	bool ret = true;
3869 
3870 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3871 	chunk_used = cache->used;
3872 
3873 	if (bargs->usage_min == 0)
3874 		user_thresh = 1;
3875 	else if (bargs->usage > 100)
3876 		user_thresh = cache->length;
3877 	else
3878 		user_thresh = mult_perc(cache->length, bargs->usage);
3879 
3880 	if (chunk_used < user_thresh)
3881 		ret = false;
3882 
3883 	btrfs_put_block_group(cache);
3884 	return ret;
3885 }
3886 
chunk_devid_filter(struct extent_buffer * leaf,struct btrfs_chunk * chunk,struct btrfs_balance_args * bargs)3887 static bool chunk_devid_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
3888 			       struct btrfs_balance_args *bargs)
3889 {
3890 	struct btrfs_stripe *stripe;
3891 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3892 	int i;
3893 
3894 	for (i = 0; i < num_stripes; i++) {
3895 		stripe = btrfs_stripe_nr(chunk, i);
3896 		if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3897 			return false;
3898 	}
3899 
3900 	return true;
3901 }
3902 
calc_data_stripes(u64 type,int num_stripes)3903 static u64 calc_data_stripes(u64 type, int num_stripes)
3904 {
3905 	const int index = btrfs_bg_flags_to_raid_index(type);
3906 	const int ncopies = btrfs_raid_array[index].ncopies;
3907 	const int nparity = btrfs_raid_array[index].nparity;
3908 
3909 	return (num_stripes - nparity) / ncopies;
3910 }
3911 
3912 /* [pstart, pend) */
chunk_drange_filter(struct extent_buffer * leaf,struct btrfs_chunk * chunk,struct btrfs_balance_args * bargs)3913 static bool chunk_drange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
3914 				struct btrfs_balance_args *bargs)
3915 {
3916 	struct btrfs_stripe *stripe;
3917 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3918 	u64 stripe_offset;
3919 	u64 stripe_length;
3920 	u64 type;
3921 	int factor;
3922 	int i;
3923 
3924 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3925 		return false;
3926 
3927 	type = btrfs_chunk_type(leaf, chunk);
3928 	factor = calc_data_stripes(type, num_stripes);
3929 
3930 	for (i = 0; i < num_stripes; i++) {
3931 		stripe = btrfs_stripe_nr(chunk, i);
3932 		if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3933 			continue;
3934 
3935 		stripe_offset = btrfs_stripe_offset(leaf, stripe);
3936 		stripe_length = btrfs_chunk_length(leaf, chunk);
3937 		stripe_length = div_u64(stripe_length, factor);
3938 
3939 		if (stripe_offset < bargs->pend &&
3940 		    stripe_offset + stripe_length > bargs->pstart)
3941 			return false;
3942 	}
3943 
3944 	return true;
3945 }
3946 
3947 /* [vstart, vend) */
chunk_vrange_filter(struct extent_buffer * leaf,struct btrfs_chunk * chunk,u64 chunk_offset,struct btrfs_balance_args * bargs)3948 static bool chunk_vrange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
3949 				u64 chunk_offset, struct btrfs_balance_args *bargs)
3950 {
3951 	if (chunk_offset < bargs->vend &&
3952 	    chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3953 		/* at least part of the chunk is inside this vrange */
3954 		return false;
3955 
3956 	return true;
3957 }
3958 
chunk_stripes_range_filter(struct extent_buffer * leaf,struct btrfs_chunk * chunk,struct btrfs_balance_args * bargs)3959 static bool chunk_stripes_range_filter(struct extent_buffer *leaf,
3960 				       struct btrfs_chunk *chunk,
3961 				       struct btrfs_balance_args *bargs)
3962 {
3963 	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3964 
3965 	if (bargs->stripes_min <= num_stripes
3966 			&& num_stripes <= bargs->stripes_max)
3967 		return false;
3968 
3969 	return true;
3970 }
3971 
chunk_soft_convert_filter(u64 chunk_type,struct btrfs_balance_args * bargs)3972 static bool chunk_soft_convert_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
3973 {
3974 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3975 		return false;
3976 
3977 	chunk_type = chunk_to_extended(chunk_type) &
3978 				BTRFS_EXTENDED_PROFILE_MASK;
3979 
3980 	if (bargs->target == chunk_type)
3981 		return true;
3982 
3983 	return false;
3984 }
3985 
should_balance_chunk(struct extent_buffer * leaf,struct btrfs_chunk * chunk,u64 chunk_offset)3986 static bool should_balance_chunk(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
3987 				 u64 chunk_offset)
3988 {
3989 	struct btrfs_fs_info *fs_info = leaf->fs_info;
3990 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3991 	struct btrfs_balance_args *bargs = NULL;
3992 	u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3993 
3994 	/* type filter */
3995 	if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3996 	      (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3997 		return false;
3998 	}
3999 
4000 	if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4001 		bargs = &bctl->data;
4002 	else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4003 		bargs = &bctl->sys;
4004 	else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4005 		bargs = &bctl->meta;
4006 
4007 	/* profiles filter */
4008 	if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
4009 	    chunk_profiles_filter(chunk_type, bargs)) {
4010 		return false;
4011 	}
4012 
4013 	/* usage filter */
4014 	if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
4015 	    chunk_usage_filter(fs_info, chunk_offset, bargs)) {
4016 		return false;
4017 	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
4018 	    chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
4019 		return false;
4020 	}
4021 
4022 	/* devid filter */
4023 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
4024 	    chunk_devid_filter(leaf, chunk, bargs)) {
4025 		return false;
4026 	}
4027 
4028 	/* drange filter, makes sense only with devid filter */
4029 	if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
4030 	    chunk_drange_filter(leaf, chunk, bargs)) {
4031 		return false;
4032 	}
4033 
4034 	/* vrange filter */
4035 	if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
4036 	    chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
4037 		return false;
4038 	}
4039 
4040 	/* stripes filter */
4041 	if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
4042 	    chunk_stripes_range_filter(leaf, chunk, bargs)) {
4043 		return false;
4044 	}
4045 
4046 	/* soft profile changing mode */
4047 	if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
4048 	    chunk_soft_convert_filter(chunk_type, bargs)) {
4049 		return false;
4050 	}
4051 
4052 	/*
4053 	 * limited by count, must be the last filter
4054 	 */
4055 	if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
4056 		if (bargs->limit == 0)
4057 			return false;
4058 		else
4059 			bargs->limit--;
4060 	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
4061 		/*
4062 		 * Same logic as the 'limit' filter; the minimum cannot be
4063 		 * determined here because we do not have the global information
4064 		 * about the count of all chunks that satisfy the filters.
4065 		 */
4066 		if (bargs->limit_max == 0)
4067 			return false;
4068 		else
4069 			bargs->limit_max--;
4070 	}
4071 
4072 	return true;
4073 }
4074 
__btrfs_balance(struct btrfs_fs_info * fs_info)4075 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
4076 {
4077 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4078 	struct btrfs_root *chunk_root = fs_info->chunk_root;
4079 	u64 chunk_type;
4080 	struct btrfs_chunk *chunk;
4081 	struct btrfs_path *path = NULL;
4082 	struct btrfs_key key;
4083 	struct btrfs_key found_key;
4084 	struct extent_buffer *leaf;
4085 	int slot;
4086 	int ret;
4087 	int enospc_errors = 0;
4088 	bool counting = true;
4089 	/* The single value limit and min/max limits use the same bytes in the */
4090 	u64 limit_data = bctl->data.limit;
4091 	u64 limit_meta = bctl->meta.limit;
4092 	u64 limit_sys = bctl->sys.limit;
4093 	u32 count_data = 0;
4094 	u32 count_meta = 0;
4095 	u32 count_sys = 0;
4096 	int chunk_reserved = 0;
4097 
4098 	path = btrfs_alloc_path();
4099 	if (!path) {
4100 		ret = -ENOMEM;
4101 		goto error;
4102 	}
4103 
4104 	/* zero out stat counters */
4105 	spin_lock(&fs_info->balance_lock);
4106 	memset(&bctl->stat, 0, sizeof(bctl->stat));
4107 	spin_unlock(&fs_info->balance_lock);
4108 again:
4109 	if (!counting) {
4110 		/*
4111 		 * The single value limit and min/max limits use the same bytes
4112 		 * in the
4113 		 */
4114 		bctl->data.limit = limit_data;
4115 		bctl->meta.limit = limit_meta;
4116 		bctl->sys.limit = limit_sys;
4117 	}
4118 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4119 	key.type = BTRFS_CHUNK_ITEM_KEY;
4120 	key.offset = (u64)-1;
4121 
4122 	while (1) {
4123 		if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
4124 		    atomic_read(&fs_info->balance_cancel_req)) {
4125 			ret = -ECANCELED;
4126 			goto error;
4127 		}
4128 
4129 		mutex_lock(&fs_info->reclaim_bgs_lock);
4130 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
4131 		if (ret < 0) {
4132 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4133 			goto error;
4134 		}
4135 
4136 		/*
4137 		 * this shouldn't happen, it means the last relocate
4138 		 * failed
4139 		 */
4140 		if (ret == 0)
4141 			BUG(); /* FIXME break ? */
4142 
4143 		ret = btrfs_previous_item(chunk_root, path, 0,
4144 					  BTRFS_CHUNK_ITEM_KEY);
4145 		if (ret) {
4146 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4147 			ret = 0;
4148 			break;
4149 		}
4150 
4151 		leaf = path->nodes[0];
4152 		slot = path->slots[0];
4153 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4154 
4155 		if (found_key.objectid != key.objectid) {
4156 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4157 			break;
4158 		}
4159 
4160 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4161 		chunk_type = btrfs_chunk_type(leaf, chunk);
4162 
4163 		if (!counting) {
4164 			spin_lock(&fs_info->balance_lock);
4165 			bctl->stat.considered++;
4166 			spin_unlock(&fs_info->balance_lock);
4167 		}
4168 
4169 		ret = should_balance_chunk(leaf, chunk, found_key.offset);
4170 
4171 		btrfs_release_path(path);
4172 		if (!ret) {
4173 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4174 			goto loop;
4175 		}
4176 
4177 		if (counting) {
4178 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4179 			spin_lock(&fs_info->balance_lock);
4180 			bctl->stat.expected++;
4181 			spin_unlock(&fs_info->balance_lock);
4182 
4183 			if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4184 				count_data++;
4185 			else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4186 				count_sys++;
4187 			else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4188 				count_meta++;
4189 
4190 			goto loop;
4191 		}
4192 
4193 		/*
4194 		 * Apply limit_min filter, no need to check if the LIMITS
4195 		 * filter is used, limit_min is 0 by default
4196 		 */
4197 		if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4198 					count_data < bctl->data.limit_min)
4199 				|| ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4200 					count_meta < bctl->meta.limit_min)
4201 				|| ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4202 					count_sys < bctl->sys.limit_min)) {
4203 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4204 			goto loop;
4205 		}
4206 
4207 		if (!chunk_reserved) {
4208 			/*
4209 			 * We may be relocating the only data chunk we have,
4210 			 * which could potentially end up with losing data's
4211 			 * raid profile, so lets allocate an empty one in
4212 			 * advance.
4213 			 */
4214 			ret = btrfs_may_alloc_data_chunk(fs_info,
4215 							 found_key.offset);
4216 			if (ret < 0) {
4217 				mutex_unlock(&fs_info->reclaim_bgs_lock);
4218 				goto error;
4219 			} else if (ret == 1) {
4220 				chunk_reserved = 1;
4221 			}
4222 		}
4223 
4224 		ret = btrfs_relocate_chunk(fs_info, found_key.offset, true);
4225 		mutex_unlock(&fs_info->reclaim_bgs_lock);
4226 		if (ret == -ENOSPC) {
4227 			enospc_errors++;
4228 		} else if (ret == -ETXTBSY) {
4229 			btrfs_info(fs_info,
4230 	   "skipping relocation of block group %llu due to active swapfile",
4231 				   found_key.offset);
4232 			ret = 0;
4233 		} else if (ret) {
4234 			goto error;
4235 		} else {
4236 			spin_lock(&fs_info->balance_lock);
4237 			bctl->stat.completed++;
4238 			spin_unlock(&fs_info->balance_lock);
4239 		}
4240 loop:
4241 		if (found_key.offset == 0)
4242 			break;
4243 		key.offset = found_key.offset - 1;
4244 	}
4245 
4246 	if (counting) {
4247 		btrfs_release_path(path);
4248 		counting = false;
4249 		goto again;
4250 	}
4251 error:
4252 	btrfs_free_path(path);
4253 	if (enospc_errors) {
4254 		btrfs_info(fs_info, "%d enospc errors during balance",
4255 			   enospc_errors);
4256 		if (!ret)
4257 			ret = -ENOSPC;
4258 	}
4259 
4260 	return ret;
4261 }
4262 
4263 /*
4264  * See if a given profile is valid and reduced.
4265  *
4266  * @flags:     profile to validate
4267  * @extended:  if true @flags is treated as an extended profile
4268  */
alloc_profile_is_valid(u64 flags,bool extended)4269 static int alloc_profile_is_valid(u64 flags, bool extended)
4270 {
4271 	u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4272 			       BTRFS_BLOCK_GROUP_PROFILE_MASK);
4273 
4274 	flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4275 
4276 	/* 1) check that all other bits are zeroed */
4277 	if (flags & ~mask)
4278 		return 0;
4279 
4280 	/* 2) see if profile is reduced */
4281 	if (flags == 0)
4282 		return !extended; /* "0" is valid for usual profiles */
4283 
4284 	return has_single_bit_set(flags);
4285 }
4286 
4287 /*
4288  * Validate target profile against allowed profiles and return true if it's OK.
4289  * Otherwise print the error message and return false.
4290  */
validate_convert_profile(struct btrfs_fs_info * fs_info,const struct btrfs_balance_args * bargs,u64 allowed,const char * type)4291 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4292 		const struct btrfs_balance_args *bargs,
4293 		u64 allowed, const char *type)
4294 {
4295 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4296 		return true;
4297 
4298 	/* Profile is valid and does not have bits outside of the allowed set */
4299 	if (alloc_profile_is_valid(bargs->target, 1) &&
4300 	    (bargs->target & ~allowed) == 0)
4301 		return true;
4302 
4303 	btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4304 			type, btrfs_bg_type_to_raid_name(bargs->target));
4305 	return false;
4306 }
4307 
4308 /*
4309  * Fill @buf with textual description of balance filter flags @bargs, up to
4310  * @size_buf including the terminating null. The output may be trimmed if it
4311  * does not fit into the provided buffer.
4312  */
describe_balance_args(struct btrfs_balance_args * bargs,char * buf,u32 size_buf)4313 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4314 				 u32 size_buf)
4315 {
4316 	int ret;
4317 	u32 size_bp = size_buf;
4318 	char *bp = buf;
4319 	u64 flags = bargs->flags;
4320 	char tmp_buf[128] = {'\0'};
4321 
4322 	if (!flags)
4323 		return;
4324 
4325 #define CHECK_APPEND_NOARG(a)						\
4326 	do {								\
4327 		ret = snprintf(bp, size_bp, (a));			\
4328 		if (ret < 0 || ret >= size_bp)				\
4329 			goto out_overflow;				\
4330 		size_bp -= ret;						\
4331 		bp += ret;						\
4332 	} while (0)
4333 
4334 #define CHECK_APPEND_1ARG(a, v1)					\
4335 	do {								\
4336 		ret = snprintf(bp, size_bp, (a), (v1));			\
4337 		if (ret < 0 || ret >= size_bp)				\
4338 			goto out_overflow;				\
4339 		size_bp -= ret;						\
4340 		bp += ret;						\
4341 	} while (0)
4342 
4343 #define CHECK_APPEND_2ARG(a, v1, v2)					\
4344 	do {								\
4345 		ret = snprintf(bp, size_bp, (a), (v1), (v2));		\
4346 		if (ret < 0 || ret >= size_bp)				\
4347 			goto out_overflow;				\
4348 		size_bp -= ret;						\
4349 		bp += ret;						\
4350 	} while (0)
4351 
4352 	if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4353 		CHECK_APPEND_1ARG("convert=%s,",
4354 				  btrfs_bg_type_to_raid_name(bargs->target));
4355 
4356 	if (flags & BTRFS_BALANCE_ARGS_SOFT)
4357 		CHECK_APPEND_NOARG("soft,");
4358 
4359 	if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4360 		btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4361 					    sizeof(tmp_buf));
4362 		CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4363 	}
4364 
4365 	if (flags & BTRFS_BALANCE_ARGS_USAGE)
4366 		CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4367 
4368 	if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4369 		CHECK_APPEND_2ARG("usage=%u..%u,",
4370 				  bargs->usage_min, bargs->usage_max);
4371 
4372 	if (flags & BTRFS_BALANCE_ARGS_DEVID)
4373 		CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4374 
4375 	if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4376 		CHECK_APPEND_2ARG("drange=%llu..%llu,",
4377 				  bargs->pstart, bargs->pend);
4378 
4379 	if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4380 		CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4381 				  bargs->vstart, bargs->vend);
4382 
4383 	if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4384 		CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4385 
4386 	if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4387 		CHECK_APPEND_2ARG("limit=%u..%u,",
4388 				bargs->limit_min, bargs->limit_max);
4389 
4390 	if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4391 		CHECK_APPEND_2ARG("stripes=%u..%u,",
4392 				  bargs->stripes_min, bargs->stripes_max);
4393 
4394 #undef CHECK_APPEND_2ARG
4395 #undef CHECK_APPEND_1ARG
4396 #undef CHECK_APPEND_NOARG
4397 
4398 out_overflow:
4399 
4400 	if (size_bp < size_buf)
4401 		buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4402 	else
4403 		buf[0] = '\0';
4404 }
4405 
describe_balance_start_or_resume(struct btrfs_fs_info * fs_info)4406 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4407 {
4408 	u32 size_buf = 1024;
4409 	char tmp_buf[192] = {'\0'};
4410 	char *buf;
4411 	char *bp;
4412 	u32 size_bp = size_buf;
4413 	int ret;
4414 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4415 
4416 	buf = kzalloc(size_buf, GFP_KERNEL);
4417 	if (!buf)
4418 		return;
4419 
4420 	bp = buf;
4421 
4422 #define CHECK_APPEND_1ARG(a, v1)					\
4423 	do {								\
4424 		ret = snprintf(bp, size_bp, (a), (v1));			\
4425 		if (ret < 0 || ret >= size_bp)				\
4426 			goto out_overflow;				\
4427 		size_bp -= ret;						\
4428 		bp += ret;						\
4429 	} while (0)
4430 
4431 	if (bctl->flags & BTRFS_BALANCE_FORCE)
4432 		CHECK_APPEND_1ARG("%s", "-f ");
4433 
4434 	if (bctl->flags & BTRFS_BALANCE_DATA) {
4435 		describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4436 		CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4437 	}
4438 
4439 	if (bctl->flags & BTRFS_BALANCE_METADATA) {
4440 		describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4441 		CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4442 	}
4443 
4444 	if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4445 		describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4446 		CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4447 	}
4448 
4449 #undef CHECK_APPEND_1ARG
4450 
4451 out_overflow:
4452 
4453 	if (size_bp < size_buf)
4454 		buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4455 	btrfs_info(fs_info, "balance: %s %s",
4456 		   (bctl->flags & BTRFS_BALANCE_RESUME) ?
4457 		   "resume" : "start", buf);
4458 
4459 	kfree(buf);
4460 }
4461 
4462 /*
4463  * Should be called with balance mutex held
4464  */
btrfs_balance(struct btrfs_fs_info * fs_info,struct btrfs_balance_control * bctl,struct btrfs_ioctl_balance_args * bargs)4465 int btrfs_balance(struct btrfs_fs_info *fs_info,
4466 		  struct btrfs_balance_control *bctl,
4467 		  struct btrfs_ioctl_balance_args *bargs)
4468 {
4469 	u64 meta_target, data_target;
4470 	u64 allowed;
4471 	int mixed = 0;
4472 	int ret;
4473 	u64 num_devices;
4474 	unsigned seq;
4475 	bool reducing_redundancy;
4476 	bool paused = false;
4477 	int i;
4478 
4479 	if (btrfs_fs_closing(fs_info) ||
4480 	    atomic_read(&fs_info->balance_pause_req) ||
4481 	    btrfs_should_cancel_balance(fs_info)) {
4482 		ret = -EINVAL;
4483 		goto out;
4484 	}
4485 
4486 	allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4487 	if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4488 		mixed = 1;
4489 
4490 	/*
4491 	 * In case of mixed groups both data and meta should be picked,
4492 	 * and identical options should be given for both of them.
4493 	 */
4494 	allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4495 	if (mixed && (bctl->flags & allowed)) {
4496 		if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4497 		    !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4498 		    memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4499 			btrfs_err(fs_info,
4500 	  "balance: mixed groups data and metadata options must be the same");
4501 			ret = -EINVAL;
4502 			goto out;
4503 		}
4504 	}
4505 
4506 	/*
4507 	 * rw_devices will not change at the moment, device add/delete/replace
4508 	 * are exclusive
4509 	 */
4510 	num_devices = fs_info->fs_devices->rw_devices;
4511 
4512 	/*
4513 	 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4514 	 * special bit for it, to make it easier to distinguish.  Thus we need
4515 	 * to set it manually, or balance would refuse the profile.
4516 	 */
4517 	allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4518 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4519 		if (num_devices >= btrfs_raid_array[i].devs_min)
4520 			allowed |= btrfs_raid_array[i].bg_flag;
4521 
4522 	if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4523 	    !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4524 	    !validate_convert_profile(fs_info, &bctl->sys,  allowed, "system")) {
4525 		ret = -EINVAL;
4526 		goto out;
4527 	}
4528 
4529 	/*
4530 	 * Allow to reduce metadata or system integrity only if force set for
4531 	 * profiles with redundancy (copies, parity)
4532 	 */
4533 	allowed = 0;
4534 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4535 		if (btrfs_raid_array[i].ncopies >= 2 ||
4536 		    btrfs_raid_array[i].tolerated_failures >= 1)
4537 			allowed |= btrfs_raid_array[i].bg_flag;
4538 	}
4539 	do {
4540 		seq = read_seqbegin(&fs_info->profiles_lock);
4541 
4542 		if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4543 		     (fs_info->avail_system_alloc_bits & allowed) &&
4544 		     !(bctl->sys.target & allowed)) ||
4545 		    ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4546 		     (fs_info->avail_metadata_alloc_bits & allowed) &&
4547 		     !(bctl->meta.target & allowed)))
4548 			reducing_redundancy = true;
4549 		else
4550 			reducing_redundancy = false;
4551 
4552 		/* if we're not converting, the target field is uninitialized */
4553 		meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4554 			bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4555 		data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4556 			bctl->data.target : fs_info->avail_data_alloc_bits;
4557 	} while (read_seqretry(&fs_info->profiles_lock, seq));
4558 
4559 	if (reducing_redundancy) {
4560 		if (bctl->flags & BTRFS_BALANCE_FORCE) {
4561 			btrfs_info(fs_info,
4562 			   "balance: force reducing metadata redundancy");
4563 		} else {
4564 			btrfs_err(fs_info,
4565 	"balance: reduces metadata redundancy, use --force if you want this");
4566 			ret = -EINVAL;
4567 			goto out;
4568 		}
4569 	}
4570 
4571 	if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4572 		btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4573 		btrfs_warn(fs_info,
4574 	"balance: metadata profile %s has lower redundancy than data profile %s",
4575 				btrfs_bg_type_to_raid_name(meta_target),
4576 				btrfs_bg_type_to_raid_name(data_target));
4577 	}
4578 
4579 	ret = insert_balance_item(fs_info, bctl);
4580 	if (ret && ret != -EEXIST)
4581 		goto out;
4582 
4583 	if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4584 		BUG_ON(ret == -EEXIST);
4585 		BUG_ON(fs_info->balance_ctl);
4586 		spin_lock(&fs_info->balance_lock);
4587 		fs_info->balance_ctl = bctl;
4588 		spin_unlock(&fs_info->balance_lock);
4589 	} else {
4590 		BUG_ON(ret != -EEXIST);
4591 		spin_lock(&fs_info->balance_lock);
4592 		update_balance_args(bctl);
4593 		spin_unlock(&fs_info->balance_lock);
4594 	}
4595 
4596 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4597 	set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4598 	describe_balance_start_or_resume(fs_info);
4599 	mutex_unlock(&fs_info->balance_mutex);
4600 
4601 	ret = __btrfs_balance(fs_info);
4602 
4603 	mutex_lock(&fs_info->balance_mutex);
4604 	if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4605 		btrfs_info(fs_info, "balance: paused");
4606 		btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4607 		paused = true;
4608 	}
4609 	/*
4610 	 * Balance can be canceled by:
4611 	 *
4612 	 * - Regular cancel request
4613 	 *   Then ret == -ECANCELED and balance_cancel_req > 0
4614 	 *
4615 	 * - Fatal signal to "btrfs" process
4616 	 *   Either the signal caught by wait_reserve_ticket() and callers
4617 	 *   got -EINTR, or caught by btrfs_should_cancel_balance() and
4618 	 *   got -ECANCELED.
4619 	 *   Either way, in this case balance_cancel_req = 0, and
4620 	 *   ret == -EINTR or ret == -ECANCELED.
4621 	 *
4622 	 * So here we only check the return value to catch canceled balance.
4623 	 */
4624 	else if (ret == -ECANCELED || ret == -EINTR)
4625 		btrfs_info(fs_info, "balance: canceled");
4626 	else
4627 		btrfs_info(fs_info, "balance: ended with status: %d", ret);
4628 
4629 	clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4630 
4631 	if (bargs) {
4632 		memset(bargs, 0, sizeof(*bargs));
4633 		btrfs_update_ioctl_balance_args(fs_info, bargs);
4634 	}
4635 
4636 	/* We didn't pause, we can clean everything up. */
4637 	if (!paused) {
4638 		reset_balance_state(fs_info);
4639 		btrfs_exclop_finish(fs_info);
4640 	}
4641 
4642 	wake_up(&fs_info->balance_wait_q);
4643 
4644 	return ret;
4645 out:
4646 	if (bctl->flags & BTRFS_BALANCE_RESUME)
4647 		reset_balance_state(fs_info);
4648 	else
4649 		kfree(bctl);
4650 	btrfs_exclop_finish(fs_info);
4651 
4652 	return ret;
4653 }
4654 
balance_kthread(void * data)4655 static int balance_kthread(void *data)
4656 {
4657 	struct btrfs_fs_info *fs_info = data;
4658 	int ret = 0;
4659 
4660 	guard(super_write)(fs_info->sb);
4661 
4662 	mutex_lock(&fs_info->balance_mutex);
4663 	if (fs_info->balance_ctl)
4664 		ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4665 	mutex_unlock(&fs_info->balance_mutex);
4666 
4667 	return ret;
4668 }
4669 
btrfs_resume_balance_async(struct btrfs_fs_info * fs_info)4670 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4671 {
4672 	struct task_struct *tsk;
4673 
4674 	mutex_lock(&fs_info->balance_mutex);
4675 	if (!fs_info->balance_ctl) {
4676 		mutex_unlock(&fs_info->balance_mutex);
4677 		return 0;
4678 	}
4679 	mutex_unlock(&fs_info->balance_mutex);
4680 
4681 	if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4682 		btrfs_info(fs_info, "balance: resume skipped");
4683 		return 0;
4684 	}
4685 
4686 	spin_lock(&fs_info->super_lock);
4687 	ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED,
4688 	       "exclusive_operation=%d", fs_info->exclusive_operation);
4689 	fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4690 	spin_unlock(&fs_info->super_lock);
4691 	/*
4692 	 * A ro->rw remount sequence should continue with the paused balance
4693 	 * regardless of who pauses it, system or the user as of now, so set
4694 	 * the resume flag.
4695 	 */
4696 	spin_lock(&fs_info->balance_lock);
4697 	fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4698 	spin_unlock(&fs_info->balance_lock);
4699 
4700 	tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4701 	return PTR_ERR_OR_ZERO(tsk);
4702 }
4703 
btrfs_recover_balance(struct btrfs_fs_info * fs_info)4704 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4705 {
4706 	struct btrfs_balance_control *bctl;
4707 	struct btrfs_balance_item *item;
4708 	struct btrfs_disk_balance_args disk_bargs;
4709 	struct btrfs_path *path;
4710 	struct extent_buffer *leaf;
4711 	struct btrfs_key key;
4712 	int ret;
4713 
4714 	path = btrfs_alloc_path();
4715 	if (!path)
4716 		return -ENOMEM;
4717 
4718 	key.objectid = BTRFS_BALANCE_OBJECTID;
4719 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
4720 	key.offset = 0;
4721 
4722 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4723 	if (ret < 0)
4724 		goto out;
4725 	if (ret > 0) { /* ret = -ENOENT; */
4726 		ret = 0;
4727 		goto out;
4728 	}
4729 
4730 	bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4731 	if (!bctl) {
4732 		ret = -ENOMEM;
4733 		goto out;
4734 	}
4735 
4736 	leaf = path->nodes[0];
4737 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4738 
4739 	bctl->flags = btrfs_balance_flags(leaf, item);
4740 	bctl->flags |= BTRFS_BALANCE_RESUME;
4741 
4742 	btrfs_balance_data(leaf, item, &disk_bargs);
4743 	btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4744 	btrfs_balance_meta(leaf, item, &disk_bargs);
4745 	btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4746 	btrfs_balance_sys(leaf, item, &disk_bargs);
4747 	btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4748 
4749 	/*
4750 	 * This should never happen, as the paused balance state is recovered
4751 	 * during mount without any chance of other exclusive ops to collide.
4752 	 *
4753 	 * This gives the exclusive op status to balance and keeps in paused
4754 	 * state until user intervention (cancel or umount). If the ownership
4755 	 * cannot be assigned, show a message but do not fail. The balance
4756 	 * is in a paused state and must have fs_info::balance_ctl properly
4757 	 * set up.
4758 	 */
4759 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4760 		btrfs_warn(fs_info,
4761 	"balance: cannot set exclusive op status, resume manually");
4762 
4763 	btrfs_release_path(path);
4764 
4765 	mutex_lock(&fs_info->balance_mutex);
4766 	BUG_ON(fs_info->balance_ctl);
4767 	spin_lock(&fs_info->balance_lock);
4768 	fs_info->balance_ctl = bctl;
4769 	spin_unlock(&fs_info->balance_lock);
4770 	mutex_unlock(&fs_info->balance_mutex);
4771 out:
4772 	btrfs_free_path(path);
4773 	return ret;
4774 }
4775 
btrfs_pause_balance(struct btrfs_fs_info * fs_info)4776 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4777 {
4778 	int ret = 0;
4779 
4780 	mutex_lock(&fs_info->balance_mutex);
4781 	if (!fs_info->balance_ctl) {
4782 		mutex_unlock(&fs_info->balance_mutex);
4783 		return -ENOTCONN;
4784 	}
4785 
4786 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4787 		atomic_inc(&fs_info->balance_pause_req);
4788 		mutex_unlock(&fs_info->balance_mutex);
4789 
4790 		wait_event(fs_info->balance_wait_q,
4791 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4792 
4793 		mutex_lock(&fs_info->balance_mutex);
4794 		/* we are good with balance_ctl ripped off from under us */
4795 		BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4796 		atomic_dec(&fs_info->balance_pause_req);
4797 	} else {
4798 		ret = -ENOTCONN;
4799 	}
4800 
4801 	mutex_unlock(&fs_info->balance_mutex);
4802 	return ret;
4803 }
4804 
btrfs_cancel_balance(struct btrfs_fs_info * fs_info)4805 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4806 {
4807 	mutex_lock(&fs_info->balance_mutex);
4808 	if (!fs_info->balance_ctl) {
4809 		mutex_unlock(&fs_info->balance_mutex);
4810 		return -ENOTCONN;
4811 	}
4812 
4813 	/*
4814 	 * A paused balance with the item stored on disk can be resumed at
4815 	 * mount time if the mount is read-write. Otherwise it's still paused
4816 	 * and we must not allow cancelling as it deletes the item.
4817 	 */
4818 	if (sb_rdonly(fs_info->sb)) {
4819 		mutex_unlock(&fs_info->balance_mutex);
4820 		return -EROFS;
4821 	}
4822 
4823 	atomic_inc(&fs_info->balance_cancel_req);
4824 	/*
4825 	 * if we are running just wait and return, balance item is
4826 	 * deleted in btrfs_balance in this case
4827 	 */
4828 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4829 		mutex_unlock(&fs_info->balance_mutex);
4830 		wait_event(fs_info->balance_wait_q,
4831 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4832 		mutex_lock(&fs_info->balance_mutex);
4833 	} else {
4834 		mutex_unlock(&fs_info->balance_mutex);
4835 		/*
4836 		 * Lock released to allow other waiters to continue, we'll
4837 		 * reexamine the status again.
4838 		 */
4839 		mutex_lock(&fs_info->balance_mutex);
4840 
4841 		if (fs_info->balance_ctl) {
4842 			reset_balance_state(fs_info);
4843 			btrfs_exclop_finish(fs_info);
4844 			btrfs_info(fs_info, "balance: canceled");
4845 		}
4846 	}
4847 
4848 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4849 	atomic_dec(&fs_info->balance_cancel_req);
4850 	mutex_unlock(&fs_info->balance_mutex);
4851 	return 0;
4852 }
4853 
4854 /*
4855  * shrinking a device means finding all of the device extents past
4856  * the new size, and then following the back refs to the chunks.
4857  * The chunk relocation code actually frees the device extent
4858  */
btrfs_shrink_device(struct btrfs_device * device,u64 new_size)4859 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4860 {
4861 	struct btrfs_fs_info *fs_info = device->fs_info;
4862 	struct btrfs_root *root = fs_info->dev_root;
4863 	struct btrfs_trans_handle *trans;
4864 	struct btrfs_dev_extent *dev_extent = NULL;
4865 	struct btrfs_path *path;
4866 	u64 length;
4867 	u64 chunk_offset;
4868 	int ret;
4869 	int slot;
4870 	int failed = 0;
4871 	bool retried = false;
4872 	struct extent_buffer *l;
4873 	struct btrfs_key key;
4874 	struct btrfs_super_block *super_copy = fs_info->super_copy;
4875 	u64 old_total = btrfs_super_total_bytes(super_copy);
4876 	u64 old_size = btrfs_device_get_total_bytes(device);
4877 	u64 diff;
4878 	u64 start;
4879 	u64 free_diff = 0;
4880 
4881 	new_size = round_down(new_size, fs_info->sectorsize);
4882 	start = new_size;
4883 	diff = round_down(old_size - new_size, fs_info->sectorsize);
4884 
4885 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4886 		return -EINVAL;
4887 
4888 	path = btrfs_alloc_path();
4889 	if (!path)
4890 		return -ENOMEM;
4891 
4892 	path->reada = READA_BACK;
4893 
4894 	trans = btrfs_start_transaction(root, 0);
4895 	if (IS_ERR(trans)) {
4896 		btrfs_free_path(path);
4897 		return PTR_ERR(trans);
4898 	}
4899 
4900 	mutex_lock(&fs_info->chunk_mutex);
4901 
4902 	btrfs_device_set_total_bytes(device, new_size);
4903 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4904 		device->fs_devices->total_rw_bytes -= diff;
4905 
4906 		/*
4907 		 * The new free_chunk_space is new_size - used, so we have to
4908 		 * subtract the delta of the old free_chunk_space which included
4909 		 * old_size - used.  If used > new_size then just subtract this
4910 		 * entire device's free space.
4911 		 */
4912 		if (device->bytes_used < new_size)
4913 			free_diff = (old_size - device->bytes_used) -
4914 				    (new_size - device->bytes_used);
4915 		else
4916 			free_diff = old_size - device->bytes_used;
4917 		atomic64_sub(free_diff, &fs_info->free_chunk_space);
4918 	}
4919 
4920 	/*
4921 	 * Once the device's size has been set to the new size, ensure all
4922 	 * in-memory chunks are synced to disk so that the loop below sees them
4923 	 * and relocates them accordingly.
4924 	 */
4925 	if (contains_pending_extent(device, &start, diff)) {
4926 		mutex_unlock(&fs_info->chunk_mutex);
4927 		ret = btrfs_commit_transaction(trans);
4928 		if (ret)
4929 			goto done;
4930 	} else {
4931 		mutex_unlock(&fs_info->chunk_mutex);
4932 		btrfs_end_transaction(trans);
4933 	}
4934 
4935 again:
4936 	key.objectid = device->devid;
4937 	key.type = BTRFS_DEV_EXTENT_KEY;
4938 	key.offset = (u64)-1;
4939 
4940 	do {
4941 		mutex_lock(&fs_info->reclaim_bgs_lock);
4942 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4943 		if (ret < 0) {
4944 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4945 			goto done;
4946 		}
4947 
4948 		ret = btrfs_previous_item(root, path, 0, key.type);
4949 		if (ret) {
4950 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4951 			if (ret < 0)
4952 				goto done;
4953 			ret = 0;
4954 			btrfs_release_path(path);
4955 			break;
4956 		}
4957 
4958 		l = path->nodes[0];
4959 		slot = path->slots[0];
4960 		btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4961 
4962 		if (key.objectid != device->devid) {
4963 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4964 			btrfs_release_path(path);
4965 			break;
4966 		}
4967 
4968 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4969 		length = btrfs_dev_extent_length(l, dev_extent);
4970 
4971 		if (key.offset + length <= new_size) {
4972 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4973 			btrfs_release_path(path);
4974 			break;
4975 		}
4976 
4977 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4978 		btrfs_release_path(path);
4979 
4980 		/*
4981 		 * We may be relocating the only data chunk we have,
4982 		 * which could potentially end up with losing data's
4983 		 * raid profile, so lets allocate an empty one in
4984 		 * advance.
4985 		 */
4986 		ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4987 		if (ret < 0) {
4988 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4989 			goto done;
4990 		}
4991 
4992 		ret = btrfs_relocate_chunk(fs_info, chunk_offset, true);
4993 		mutex_unlock(&fs_info->reclaim_bgs_lock);
4994 		if (ret == -ENOSPC) {
4995 			failed++;
4996 		} else if (ret) {
4997 			if (ret == -ETXTBSY) {
4998 				btrfs_warn(fs_info,
4999 		   "could not shrink block group %llu due to active swapfile",
5000 					   chunk_offset);
5001 			}
5002 			goto done;
5003 		}
5004 	} while (key.offset-- > 0);
5005 
5006 	if (failed && !retried) {
5007 		failed = 0;
5008 		retried = true;
5009 		goto again;
5010 	} else if (failed && retried) {
5011 		ret = -ENOSPC;
5012 		goto done;
5013 	}
5014 
5015 	/* Shrinking succeeded, else we would be at "done". */
5016 	trans = btrfs_start_transaction(root, 0);
5017 	if (IS_ERR(trans)) {
5018 		ret = PTR_ERR(trans);
5019 		goto done;
5020 	}
5021 
5022 	mutex_lock(&fs_info->chunk_mutex);
5023 	/* Clear all state bits beyond the shrunk device size */
5024 	btrfs_clear_extent_bit(&device->alloc_state, new_size, (u64)-1,
5025 			       CHUNK_STATE_MASK, NULL);
5026 
5027 	btrfs_device_set_disk_total_bytes(device, new_size);
5028 	if (list_empty(&device->post_commit_list))
5029 		list_add_tail(&device->post_commit_list,
5030 			      &trans->transaction->dev_update_list);
5031 
5032 	WARN_ON(diff > old_total);
5033 	btrfs_set_super_total_bytes(super_copy,
5034 			round_down(old_total - diff, fs_info->sectorsize));
5035 	mutex_unlock(&fs_info->chunk_mutex);
5036 
5037 	btrfs_reserve_chunk_metadata(trans, false);
5038 	/* Now btrfs_update_device() will change the on-disk size. */
5039 	ret = btrfs_update_device(trans, device);
5040 	btrfs_trans_release_chunk_metadata(trans);
5041 	if (unlikely(ret < 0)) {
5042 		btrfs_abort_transaction(trans, ret);
5043 		btrfs_end_transaction(trans);
5044 	} else {
5045 		ret = btrfs_commit_transaction(trans);
5046 	}
5047 done:
5048 	btrfs_free_path(path);
5049 	if (ret) {
5050 		mutex_lock(&fs_info->chunk_mutex);
5051 		btrfs_device_set_total_bytes(device, old_size);
5052 		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5053 			device->fs_devices->total_rw_bytes += diff;
5054 			atomic64_add(free_diff, &fs_info->free_chunk_space);
5055 		}
5056 		mutex_unlock(&fs_info->chunk_mutex);
5057 	}
5058 	return ret;
5059 }
5060 
btrfs_add_system_chunk(struct btrfs_fs_info * fs_info,struct btrfs_key * key,struct btrfs_chunk * chunk,int item_size)5061 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5062 			   struct btrfs_key *key,
5063 			   struct btrfs_chunk *chunk, int item_size)
5064 {
5065 	struct btrfs_super_block *super_copy = fs_info->super_copy;
5066 	struct btrfs_disk_key disk_key;
5067 	u32 array_size;
5068 	u8 *ptr;
5069 
5070 	lockdep_assert_held(&fs_info->chunk_mutex);
5071 
5072 	array_size = btrfs_super_sys_array_size(super_copy);
5073 	if (array_size + item_size + sizeof(disk_key)
5074 			> BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5075 		return -EFBIG;
5076 
5077 	ptr = super_copy->sys_chunk_array + array_size;
5078 	btrfs_cpu_key_to_disk(&disk_key, key);
5079 	memcpy(ptr, &disk_key, sizeof(disk_key));
5080 	ptr += sizeof(disk_key);
5081 	memcpy(ptr, chunk, item_size);
5082 	item_size += sizeof(disk_key);
5083 	btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5084 
5085 	return 0;
5086 }
5087 
5088 /*
5089  * sort the devices in descending order by max_avail, total_avail
5090  */
btrfs_cmp_device_info(const void * a,const void * b)5091 static int btrfs_cmp_device_info(const void *a, const void *b)
5092 {
5093 	const struct btrfs_device_info *di_a = a;
5094 	const struct btrfs_device_info *di_b = b;
5095 
5096 	if (di_a->max_avail > di_b->max_avail)
5097 		return -1;
5098 	if (di_a->max_avail < di_b->max_avail)
5099 		return 1;
5100 	if (di_a->total_avail > di_b->total_avail)
5101 		return -1;
5102 	if (di_a->total_avail < di_b->total_avail)
5103 		return 1;
5104 	return 0;
5105 }
5106 
check_raid56_incompat_flag(struct btrfs_fs_info * info,u64 type)5107 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5108 {
5109 	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5110 		return;
5111 
5112 	btrfs_set_fs_incompat(info, RAID56);
5113 }
5114 
check_raid1c34_incompat_flag(struct btrfs_fs_info * info,u64 type)5115 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5116 {
5117 	if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5118 		return;
5119 
5120 	btrfs_set_fs_incompat(info, RAID1C34);
5121 }
5122 
5123 /*
5124  * Structure used internally for btrfs_create_chunk() function.
5125  * Wraps needed parameters.
5126  */
5127 struct alloc_chunk_ctl {
5128 	u64 start;
5129 	u64 type;
5130 	/* Total number of stripes to allocate */
5131 	int num_stripes;
5132 	/* sub_stripes info for map */
5133 	int sub_stripes;
5134 	/* Stripes per device */
5135 	int dev_stripes;
5136 	/* Maximum number of devices to use */
5137 	int devs_max;
5138 	/* Minimum number of devices to use */
5139 	int devs_min;
5140 	/* ndevs has to be a multiple of this */
5141 	int devs_increment;
5142 	/* Number of copies */
5143 	int ncopies;
5144 	/* Number of stripes worth of bytes to store parity information */
5145 	int nparity;
5146 	u64 max_stripe_size;
5147 	u64 max_chunk_size;
5148 	u64 dev_extent_min;
5149 	u64 stripe_size;
5150 	u64 chunk_size;
5151 	int ndevs;
5152 	/* Space_info the block group is going to belong. */
5153 	struct btrfs_space_info *space_info;
5154 };
5155 
init_alloc_chunk_ctl_policy_regular(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5156 static void init_alloc_chunk_ctl_policy_regular(
5157 				struct btrfs_fs_devices *fs_devices,
5158 				struct alloc_chunk_ctl *ctl)
5159 {
5160 	struct btrfs_space_info *space_info;
5161 
5162 	space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5163 	ASSERT(space_info);
5164 
5165 	ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5166 	ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5167 
5168 	if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5169 		ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5170 
5171 	/* We don't want a chunk larger than 10% of writable space */
5172 	ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5173 				  ctl->max_chunk_size);
5174 	ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5175 }
5176 
init_alloc_chunk_ctl_policy_zoned(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5177 static void init_alloc_chunk_ctl_policy_zoned(
5178 				      struct btrfs_fs_devices *fs_devices,
5179 				      struct alloc_chunk_ctl *ctl)
5180 {
5181 	u64 zone_size = fs_devices->fs_info->zone_size;
5182 	u64 limit;
5183 	int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5184 	int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5185 	u64 min_chunk_size = min_data_stripes * zone_size;
5186 	u64 type = ctl->type;
5187 
5188 	ctl->max_stripe_size = zone_size;
5189 	if (type & BTRFS_BLOCK_GROUP_DATA) {
5190 		ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5191 						 zone_size);
5192 	} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5193 		ctl->max_chunk_size = ctl->max_stripe_size;
5194 	} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5195 		ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5196 		ctl->devs_max = min_t(int, ctl->devs_max,
5197 				      BTRFS_MAX_DEVS_SYS_CHUNK);
5198 	} else {
5199 		BUG();
5200 	}
5201 
5202 	/* We don't want a chunk larger than 10% of writable space */
5203 	limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5204 			       zone_size),
5205 		    min_chunk_size);
5206 	ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5207 	ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5208 }
5209 
init_alloc_chunk_ctl(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5210 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5211 				 struct alloc_chunk_ctl *ctl)
5212 {
5213 	int index = btrfs_bg_flags_to_raid_index(ctl->type);
5214 
5215 	ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5216 	ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5217 	ctl->devs_max = btrfs_raid_array[index].devs_max;
5218 	if (!ctl->devs_max)
5219 		ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5220 	ctl->devs_min = btrfs_raid_array[index].devs_min;
5221 	ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5222 	ctl->ncopies = btrfs_raid_array[index].ncopies;
5223 	ctl->nparity = btrfs_raid_array[index].nparity;
5224 	ctl->ndevs = 0;
5225 
5226 	switch (fs_devices->chunk_alloc_policy) {
5227 	default:
5228 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5229 		fallthrough;
5230 	case BTRFS_CHUNK_ALLOC_REGULAR:
5231 		init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5232 		break;
5233 	case BTRFS_CHUNK_ALLOC_ZONED:
5234 		init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5235 		break;
5236 	}
5237 }
5238 
gather_device_info(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5239 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5240 			      struct alloc_chunk_ctl *ctl,
5241 			      struct btrfs_device_info *devices_info)
5242 {
5243 	struct btrfs_fs_info *info = fs_devices->fs_info;
5244 	struct btrfs_device *device;
5245 	u64 total_avail;
5246 	u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5247 	int ret;
5248 	int ndevs = 0;
5249 	u64 max_avail;
5250 	u64 dev_offset;
5251 
5252 	/*
5253 	 * in the first pass through the devices list, we gather information
5254 	 * about the available holes on each device.
5255 	 */
5256 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5257 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5258 			WARN(1, KERN_ERR
5259 			       "BTRFS: read-only device in alloc_list\n");
5260 			continue;
5261 		}
5262 
5263 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5264 					&device->dev_state) ||
5265 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5266 			continue;
5267 
5268 		if (device->total_bytes > device->bytes_used)
5269 			total_avail = device->total_bytes - device->bytes_used;
5270 		else
5271 			total_avail = 0;
5272 
5273 		/* If there is no space on this device, skip it. */
5274 		if (total_avail < ctl->dev_extent_min)
5275 			continue;
5276 
5277 		ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5278 					   &max_avail);
5279 		if (ret && ret != -ENOSPC)
5280 			return ret;
5281 
5282 		if (ret == 0)
5283 			max_avail = dev_extent_want;
5284 
5285 		if (max_avail < ctl->dev_extent_min) {
5286 			if (btrfs_test_opt(info, ENOSPC_DEBUG))
5287 				btrfs_debug(info,
5288 			"%s: devid %llu has no free space, have=%llu want=%llu",
5289 					    __func__, device->devid, max_avail,
5290 					    ctl->dev_extent_min);
5291 			continue;
5292 		}
5293 
5294 		if (ndevs == fs_devices->rw_devices) {
5295 			WARN(1, "%s: found more than %llu devices\n",
5296 			     __func__, fs_devices->rw_devices);
5297 			break;
5298 		}
5299 		devices_info[ndevs].dev_offset = dev_offset;
5300 		devices_info[ndevs].max_avail = max_avail;
5301 		devices_info[ndevs].total_avail = total_avail;
5302 		devices_info[ndevs].dev = device;
5303 		++ndevs;
5304 	}
5305 	ctl->ndevs = ndevs;
5306 
5307 	/*
5308 	 * now sort the devices by hole size / available space
5309 	 */
5310 	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5311 	     btrfs_cmp_device_info, NULL);
5312 
5313 	return 0;
5314 }
5315 
decide_stripe_size_regular(struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5316 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5317 				      struct btrfs_device_info *devices_info)
5318 {
5319 	/* Number of stripes that count for block group size */
5320 	int data_stripes;
5321 
5322 	/*
5323 	 * The primary goal is to maximize the number of stripes, so use as
5324 	 * many devices as possible, even if the stripes are not maximum sized.
5325 	 *
5326 	 * The DUP profile stores more than one stripe per device, the
5327 	 * max_avail is the total size so we have to adjust.
5328 	 */
5329 	ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5330 				   ctl->dev_stripes);
5331 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5332 
5333 	/* This will have to be fixed for RAID1 and RAID10 over more drives */
5334 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5335 
5336 	/*
5337 	 * Use the number of data stripes to figure out how big this chunk is
5338 	 * really going to be in terms of logical address space, and compare
5339 	 * that answer with the max chunk size. If it's higher, we try to
5340 	 * reduce stripe_size.
5341 	 */
5342 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5343 		/*
5344 		 * Reduce stripe_size, round it up to a 16MB boundary again and
5345 		 * then use it, unless it ends up being even bigger than the
5346 		 * previous value we had already.
5347 		 */
5348 		ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5349 							data_stripes), SZ_16M),
5350 				       ctl->stripe_size);
5351 	}
5352 
5353 	/* Stripe size should not go beyond 1G. */
5354 	ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5355 
5356 	/* Align to BTRFS_STRIPE_LEN */
5357 	ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5358 	ctl->chunk_size = ctl->stripe_size * data_stripes;
5359 
5360 	return 0;
5361 }
5362 
decide_stripe_size_zoned(struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5363 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5364 				    struct btrfs_device_info *devices_info)
5365 {
5366 	u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5367 	/* Number of stripes that count for block group size */
5368 	int data_stripes;
5369 
5370 	/*
5371 	 * It should hold because:
5372 	 *    dev_extent_min == dev_extent_want == zone_size * dev_stripes
5373 	 */
5374 	ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min,
5375 	       "ndevs=%d max_avail=%llu dev_extent_min=%llu", ctl->ndevs,
5376 	       devices_info[ctl->ndevs - 1].max_avail, ctl->dev_extent_min);
5377 
5378 	ctl->stripe_size = zone_size;
5379 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5380 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5381 
5382 	/* stripe_size is fixed in zoned filesystem. Reduce ndevs instead. */
5383 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5384 		ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5385 					     ctl->stripe_size) + ctl->nparity,
5386 				     ctl->dev_stripes);
5387 		ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5388 		data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5389 		ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size,
5390 		       "stripe_size=%llu data_stripes=%d max_chunk_size=%llu",
5391 		       ctl->stripe_size, data_stripes, ctl->max_chunk_size);
5392 	}
5393 
5394 	ctl->chunk_size = ctl->stripe_size * data_stripes;
5395 
5396 	return 0;
5397 }
5398 
decide_stripe_size(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5399 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5400 			      struct alloc_chunk_ctl *ctl,
5401 			      struct btrfs_device_info *devices_info)
5402 {
5403 	struct btrfs_fs_info *info = fs_devices->fs_info;
5404 
5405 	/*
5406 	 * Round down to number of usable stripes, devs_increment can be any
5407 	 * number so we can't use round_down() that requires power of 2, while
5408 	 * rounddown is safe.
5409 	 */
5410 	ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5411 
5412 	if (ctl->ndevs < ctl->devs_min) {
5413 		if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5414 			btrfs_debug(info,
5415 	"%s: not enough devices with free space: have=%d minimum required=%d",
5416 				    __func__, ctl->ndevs, ctl->devs_min);
5417 		}
5418 		return -ENOSPC;
5419 	}
5420 
5421 	ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5422 
5423 	switch (fs_devices->chunk_alloc_policy) {
5424 	default:
5425 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5426 		fallthrough;
5427 	case BTRFS_CHUNK_ALLOC_REGULAR:
5428 		return decide_stripe_size_regular(ctl, devices_info);
5429 	case BTRFS_CHUNK_ALLOC_ZONED:
5430 		return decide_stripe_size_zoned(ctl, devices_info);
5431 	}
5432 }
5433 
chunk_map_device_set_bits(struct btrfs_chunk_map * map,unsigned int bits)5434 static void chunk_map_device_set_bits(struct btrfs_chunk_map *map, unsigned int bits)
5435 {
5436 	for (int i = 0; i < map->num_stripes; i++) {
5437 		struct btrfs_io_stripe *stripe = &map->stripes[i];
5438 		struct btrfs_device *device = stripe->dev;
5439 
5440 		btrfs_set_extent_bit(&device->alloc_state, stripe->physical,
5441 				     stripe->physical + map->stripe_size - 1,
5442 				     bits | EXTENT_NOWAIT, NULL);
5443 	}
5444 }
5445 
chunk_map_device_clear_bits(struct btrfs_chunk_map * map,unsigned int bits)5446 static void chunk_map_device_clear_bits(struct btrfs_chunk_map *map, unsigned int bits)
5447 {
5448 	for (int i = 0; i < map->num_stripes; i++) {
5449 		struct btrfs_io_stripe *stripe = &map->stripes[i];
5450 		struct btrfs_device *device = stripe->dev;
5451 
5452 		btrfs_clear_extent_bit(&device->alloc_state, stripe->physical,
5453 				       stripe->physical + map->stripe_size - 1,
5454 				       bits | EXTENT_NOWAIT, NULL);
5455 	}
5456 }
5457 
btrfs_remove_chunk_map(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map)5458 void btrfs_remove_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5459 {
5460 	write_lock(&fs_info->mapping_tree_lock);
5461 	rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5462 	RB_CLEAR_NODE(&map->rb_node);
5463 	chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5464 	write_unlock(&fs_info->mapping_tree_lock);
5465 
5466 	/* Once for the tree reference. */
5467 	btrfs_free_chunk_map(map);
5468 }
5469 
btrfs_chunk_map_cmp(const struct rb_node * new,const struct rb_node * exist)5470 static int btrfs_chunk_map_cmp(const struct rb_node *new,
5471 			       const struct rb_node *exist)
5472 {
5473 	const struct btrfs_chunk_map *new_map =
5474 		rb_entry(new, struct btrfs_chunk_map, rb_node);
5475 	const struct btrfs_chunk_map *exist_map =
5476 		rb_entry(exist, struct btrfs_chunk_map, rb_node);
5477 
5478 	if (new_map->start == exist_map->start)
5479 		return 0;
5480 	if (new_map->start < exist_map->start)
5481 		return -1;
5482 	return 1;
5483 }
5484 
5485 EXPORT_FOR_TESTS
btrfs_add_chunk_map(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map)5486 int btrfs_add_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5487 {
5488 	struct rb_node *exist;
5489 
5490 	write_lock(&fs_info->mapping_tree_lock);
5491 	exist = rb_find_add_cached(&map->rb_node, &fs_info->mapping_tree,
5492 				   btrfs_chunk_map_cmp);
5493 
5494 	if (exist) {
5495 		write_unlock(&fs_info->mapping_tree_lock);
5496 		return -EEXIST;
5497 	}
5498 	chunk_map_device_set_bits(map, CHUNK_ALLOCATED);
5499 	chunk_map_device_clear_bits(map, CHUNK_TRIMMED);
5500 	write_unlock(&fs_info->mapping_tree_lock);
5501 
5502 	return 0;
5503 }
5504 
5505 EXPORT_FOR_TESTS
btrfs_alloc_chunk_map(int num_stripes,gfp_t gfp)5506 struct btrfs_chunk_map *btrfs_alloc_chunk_map(int num_stripes, gfp_t gfp)
5507 {
5508 	struct btrfs_chunk_map *map;
5509 
5510 	map = kmalloc(btrfs_chunk_map_size(num_stripes), gfp);
5511 	if (!map)
5512 		return NULL;
5513 
5514 	refcount_set(&map->refs, 1);
5515 	RB_CLEAR_NODE(&map->rb_node);
5516 
5517 	return map;
5518 }
5519 
create_chunk(struct btrfs_trans_handle * trans,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5520 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5521 			struct alloc_chunk_ctl *ctl,
5522 			struct btrfs_device_info *devices_info)
5523 {
5524 	struct btrfs_fs_info *info = trans->fs_info;
5525 	struct btrfs_chunk_map *map;
5526 	struct btrfs_block_group *block_group;
5527 	u64 start = ctl->start;
5528 	u64 type = ctl->type;
5529 	int ret;
5530 
5531 	map = btrfs_alloc_chunk_map(ctl->num_stripes, GFP_NOFS);
5532 	if (!map)
5533 		return ERR_PTR(-ENOMEM);
5534 
5535 	map->start = start;
5536 	map->chunk_len = ctl->chunk_size;
5537 	map->stripe_size = ctl->stripe_size;
5538 	map->type = type;
5539 	map->io_align = BTRFS_STRIPE_LEN;
5540 	map->io_width = BTRFS_STRIPE_LEN;
5541 	map->sub_stripes = ctl->sub_stripes;
5542 	map->num_stripes = ctl->num_stripes;
5543 
5544 	for (int i = 0; i < ctl->ndevs; i++) {
5545 		for (int j = 0; j < ctl->dev_stripes; j++) {
5546 			int s = i * ctl->dev_stripes + j;
5547 			map->stripes[s].dev = devices_info[i].dev;
5548 			map->stripes[s].physical = devices_info[i].dev_offset +
5549 						   j * ctl->stripe_size;
5550 		}
5551 	}
5552 
5553 	trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5554 
5555 	ret = btrfs_add_chunk_map(info, map);
5556 	if (ret) {
5557 		btrfs_free_chunk_map(map);
5558 		return ERR_PTR(ret);
5559 	}
5560 
5561 	block_group = btrfs_make_block_group(trans, ctl->space_info, type, start,
5562 					     ctl->chunk_size);
5563 	if (IS_ERR(block_group)) {
5564 		btrfs_remove_chunk_map(info, map);
5565 		return block_group;
5566 	}
5567 
5568 	for (int i = 0; i < map->num_stripes; i++) {
5569 		struct btrfs_device *dev = map->stripes[i].dev;
5570 
5571 		btrfs_device_set_bytes_used(dev,
5572 					    dev->bytes_used + ctl->stripe_size);
5573 		if (list_empty(&dev->post_commit_list))
5574 			list_add_tail(&dev->post_commit_list,
5575 				      &trans->transaction->dev_update_list);
5576 	}
5577 
5578 	atomic64_sub(ctl->stripe_size * map->num_stripes,
5579 		     &info->free_chunk_space);
5580 
5581 	check_raid56_incompat_flag(info, type);
5582 	check_raid1c34_incompat_flag(info, type);
5583 
5584 	return block_group;
5585 }
5586 
btrfs_create_chunk(struct btrfs_trans_handle * trans,struct btrfs_space_info * space_info,u64 type)5587 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5588 					     struct btrfs_space_info *space_info,
5589 					     u64 type)
5590 {
5591 	struct btrfs_fs_info *info = trans->fs_info;
5592 	struct btrfs_fs_devices *fs_devices = info->fs_devices;
5593 	struct btrfs_device_info *devices_info = NULL;
5594 	struct alloc_chunk_ctl ctl;
5595 	struct btrfs_block_group *block_group;
5596 	int ret;
5597 
5598 	lockdep_assert_held(&info->chunk_mutex);
5599 
5600 	if (!alloc_profile_is_valid(type, 0)) {
5601 		DEBUG_WARN("invalid alloc profile for type %llu", type);
5602 		return ERR_PTR(-EINVAL);
5603 	}
5604 
5605 	if (list_empty(&fs_devices->alloc_list)) {
5606 		if (btrfs_test_opt(info, ENOSPC_DEBUG))
5607 			btrfs_debug(info, "%s: no writable device", __func__);
5608 		return ERR_PTR(-ENOSPC);
5609 	}
5610 
5611 	if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5612 		btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5613 		DEBUG_WARN();
5614 		return ERR_PTR(-EINVAL);
5615 	}
5616 
5617 	ctl.start = find_next_chunk(info);
5618 	ctl.type = type;
5619 	ctl.space_info = space_info;
5620 	init_alloc_chunk_ctl(fs_devices, &ctl);
5621 
5622 	devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5623 			       GFP_NOFS);
5624 	if (!devices_info)
5625 		return ERR_PTR(-ENOMEM);
5626 
5627 	ret = gather_device_info(fs_devices, &ctl, devices_info);
5628 	if (ret < 0) {
5629 		block_group = ERR_PTR(ret);
5630 		goto out;
5631 	}
5632 
5633 	ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5634 	if (ret < 0) {
5635 		block_group = ERR_PTR(ret);
5636 		goto out;
5637 	}
5638 
5639 	block_group = create_chunk(trans, &ctl, devices_info);
5640 
5641 out:
5642 	kfree(devices_info);
5643 	return block_group;
5644 }
5645 
5646 /*
5647  * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5648  * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5649  * chunks.
5650  *
5651  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5652  * phases.
5653  */
btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle * trans,struct btrfs_block_group * bg)5654 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5655 				     struct btrfs_block_group *bg)
5656 {
5657 	struct btrfs_fs_info *fs_info = trans->fs_info;
5658 	struct btrfs_root *chunk_root = fs_info->chunk_root;
5659 	struct btrfs_key key;
5660 	struct btrfs_chunk *chunk;
5661 	struct btrfs_stripe *stripe;
5662 	struct btrfs_chunk_map *map;
5663 	size_t item_size;
5664 	int i;
5665 	int ret;
5666 
5667 	/*
5668 	 * We take the chunk_mutex for 2 reasons:
5669 	 *
5670 	 * 1) Updates and insertions in the chunk btree must be done while holding
5671 	 *    the chunk_mutex, as well as updating the system chunk array in the
5672 	 *    superblock. See the comment on top of btrfs_chunk_alloc() for the
5673 	 *    details;
5674 	 *
5675 	 * 2) To prevent races with the final phase of a device replace operation
5676 	 *    that replaces the device object associated with the map's stripes,
5677 	 *    because the device object's id can change at any time during that
5678 	 *    final phase of the device replace operation
5679 	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5680 	 *    replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5681 	 *    which would cause a failure when updating the device item, which does
5682 	 *    not exists, or persisting a stripe of the chunk item with such ID.
5683 	 *    Here we can't use the device_list_mutex because our caller already
5684 	 *    has locked the chunk_mutex, and the final phase of device replace
5685 	 *    acquires both mutexes - first the device_list_mutex and then the
5686 	 *    chunk_mutex. Using any of those two mutexes protects us from a
5687 	 *    concurrent device replace.
5688 	 */
5689 	lockdep_assert_held(&fs_info->chunk_mutex);
5690 
5691 	map = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5692 	if (IS_ERR(map)) {
5693 		ret = PTR_ERR(map);
5694 		btrfs_abort_transaction(trans, ret);
5695 		return ret;
5696 	}
5697 
5698 	item_size = btrfs_chunk_item_size(map->num_stripes);
5699 
5700 	chunk = kzalloc(item_size, GFP_NOFS);
5701 	if (unlikely(!chunk)) {
5702 		ret = -ENOMEM;
5703 		btrfs_abort_transaction(trans, ret);
5704 		goto out;
5705 	}
5706 
5707 	for (i = 0; i < map->num_stripes; i++) {
5708 		struct btrfs_device *device = map->stripes[i].dev;
5709 
5710 		ret = btrfs_update_device(trans, device);
5711 		if (ret)
5712 			goto out;
5713 	}
5714 
5715 	stripe = &chunk->stripe;
5716 	for (i = 0; i < map->num_stripes; i++) {
5717 		struct btrfs_device *device = map->stripes[i].dev;
5718 		const u64 dev_offset = map->stripes[i].physical;
5719 
5720 		btrfs_set_stack_stripe_devid(stripe, device->devid);
5721 		btrfs_set_stack_stripe_offset(stripe, dev_offset);
5722 		memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5723 		stripe++;
5724 	}
5725 
5726 	btrfs_set_stack_chunk_length(chunk, bg->length);
5727 	btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5728 	btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5729 	btrfs_set_stack_chunk_type(chunk, map->type);
5730 	btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5731 	btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5732 	btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5733 	btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5734 	btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5735 
5736 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5737 	key.type = BTRFS_CHUNK_ITEM_KEY;
5738 	key.offset = bg->start;
5739 
5740 	ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5741 	if (ret)
5742 		goto out;
5743 
5744 	set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5745 
5746 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5747 		ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5748 		if (ret)
5749 			goto out;
5750 	}
5751 
5752 out:
5753 	kfree(chunk);
5754 	btrfs_free_chunk_map(map);
5755 	return ret;
5756 }
5757 
init_first_rw_device(struct btrfs_trans_handle * trans)5758 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5759 {
5760 	struct btrfs_fs_info *fs_info = trans->fs_info;
5761 	u64 alloc_profile;
5762 	struct btrfs_block_group *meta_bg;
5763 	struct btrfs_space_info *meta_space_info;
5764 	struct btrfs_block_group *sys_bg;
5765 	struct btrfs_space_info *sys_space_info;
5766 
5767 	/*
5768 	 * When adding a new device for sprouting, the seed device is read-only
5769 	 * so we must first allocate a metadata and a system chunk. But before
5770 	 * adding the block group items to the extent, device and chunk btrees,
5771 	 * we must first:
5772 	 *
5773 	 * 1) Create both chunks without doing any changes to the btrees, as
5774 	 *    otherwise we would get -ENOSPC since the block groups from the
5775 	 *    seed device are read-only;
5776 	 *
5777 	 * 2) Add the device item for the new sprout device - finishing the setup
5778 	 *    of a new block group requires updating the device item in the chunk
5779 	 *    btree, so it must exist when we attempt to do it. The previous step
5780 	 *    ensures this does not fail with -ENOSPC.
5781 	 *
5782 	 * After that we can add the block group items to their btrees:
5783 	 * update existing device item in the chunk btree, add a new block group
5784 	 * item to the extent btree, add a new chunk item to the chunk btree and
5785 	 * finally add the new device extent items to the devices btree.
5786 	 */
5787 
5788 	alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5789 	meta_space_info = btrfs_find_space_info(fs_info, alloc_profile);
5790 	if (!meta_space_info) {
5791 		DEBUG_WARN();
5792 		return -EINVAL;
5793 	}
5794 	meta_bg = btrfs_create_chunk(trans, meta_space_info, alloc_profile);
5795 	if (IS_ERR(meta_bg))
5796 		return PTR_ERR(meta_bg);
5797 
5798 	alloc_profile = btrfs_system_alloc_profile(fs_info);
5799 	sys_space_info = btrfs_find_space_info(fs_info, alloc_profile);
5800 	if (!sys_space_info) {
5801 		DEBUG_WARN();
5802 		return -EINVAL;
5803 	}
5804 	sys_bg = btrfs_create_chunk(trans, sys_space_info, alloc_profile);
5805 	if (IS_ERR(sys_bg))
5806 		return PTR_ERR(sys_bg);
5807 
5808 	return 0;
5809 }
5810 
btrfs_chunk_max_errors(struct btrfs_chunk_map * map)5811 static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map *map)
5812 {
5813 	const int index = btrfs_bg_flags_to_raid_index(map->type);
5814 
5815 	return btrfs_raid_array[index].tolerated_failures;
5816 }
5817 
btrfs_chunk_writeable(struct btrfs_fs_info * fs_info,u64 chunk_offset)5818 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5819 {
5820 	struct btrfs_chunk_map *map;
5821 	int miss_ndevs = 0;
5822 	int i;
5823 	bool ret = true;
5824 
5825 	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5826 	if (IS_ERR(map))
5827 		return false;
5828 
5829 	for (i = 0; i < map->num_stripes; i++) {
5830 		if (test_bit(BTRFS_DEV_STATE_MISSING,
5831 					&map->stripes[i].dev->dev_state)) {
5832 			miss_ndevs++;
5833 			continue;
5834 		}
5835 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5836 					&map->stripes[i].dev->dev_state)) {
5837 			ret = false;
5838 			goto end;
5839 		}
5840 	}
5841 
5842 	/*
5843 	 * If the number of missing devices is larger than max errors, we can
5844 	 * not write the data into that chunk successfully.
5845 	 */
5846 	if (miss_ndevs > btrfs_chunk_max_errors(map))
5847 		ret = false;
5848 end:
5849 	btrfs_free_chunk_map(map);
5850 	return ret;
5851 }
5852 
btrfs_mapping_tree_free(struct btrfs_fs_info * fs_info)5853 void btrfs_mapping_tree_free(struct btrfs_fs_info *fs_info)
5854 {
5855 	write_lock(&fs_info->mapping_tree_lock);
5856 	while (!RB_EMPTY_ROOT(&fs_info->mapping_tree.rb_root)) {
5857 		struct btrfs_chunk_map *map;
5858 		struct rb_node *node;
5859 
5860 		node = rb_first_cached(&fs_info->mapping_tree);
5861 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
5862 		rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5863 		RB_CLEAR_NODE(&map->rb_node);
5864 		chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5865 		/* Once for the tree ref. */
5866 		btrfs_free_chunk_map(map);
5867 		cond_resched_rwlock_write(&fs_info->mapping_tree_lock);
5868 	}
5869 	write_unlock(&fs_info->mapping_tree_lock);
5870 }
5871 
btrfs_chunk_map_num_copies(const struct btrfs_chunk_map * map)5872 static int btrfs_chunk_map_num_copies(const struct btrfs_chunk_map *map)
5873 {
5874 	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(map->type);
5875 
5876 	if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5877 		return 2;
5878 
5879 	/*
5880 	 * There could be two corrupted data stripes, we need to loop retry in
5881 	 * order to rebuild the correct data.
5882 	 *
5883 	 * Fail a stripe at a time on every retry except the stripe under
5884 	 * reconstruction.
5885 	 */
5886 	if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5887 		return map->num_stripes;
5888 
5889 	/* Non-RAID56, use their ncopies from btrfs_raid_array. */
5890 	return btrfs_raid_array[index].ncopies;
5891 }
5892 
btrfs_num_copies(struct btrfs_fs_info * fs_info,u64 logical,u64 len)5893 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5894 {
5895 	struct btrfs_chunk_map *map;
5896 	int ret;
5897 
5898 	map = btrfs_get_chunk_map(fs_info, logical, len);
5899 	if (IS_ERR(map))
5900 		/*
5901 		 * We could return errors for these cases, but that could get
5902 		 * ugly and we'd probably do the same thing which is just not do
5903 		 * anything else and exit, so return 1 so the callers don't try
5904 		 * to use other copies.
5905 		 */
5906 		return 1;
5907 
5908 	ret = btrfs_chunk_map_num_copies(map);
5909 	btrfs_free_chunk_map(map);
5910 	return ret;
5911 }
5912 
btrfs_full_stripe_len(struct btrfs_fs_info * fs_info,u64 logical)5913 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5914 				    u64 logical)
5915 {
5916 	struct btrfs_chunk_map *map;
5917 	unsigned long len = fs_info->sectorsize;
5918 
5919 	if (!btrfs_fs_incompat(fs_info, RAID56))
5920 		return len;
5921 
5922 	map = btrfs_get_chunk_map(fs_info, logical, len);
5923 
5924 	if (!WARN_ON(IS_ERR(map))) {
5925 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5926 			len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
5927 		btrfs_free_chunk_map(map);
5928 	}
5929 	return len;
5930 }
5931 
5932 #ifdef CONFIG_BTRFS_EXPERIMENTAL
btrfs_read_preferred(struct btrfs_chunk_map * map,int first,int num_stripes)5933 static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
5934 {
5935 	for (int index = first; index < first + num_stripes; index++) {
5936 		const struct btrfs_device *device = map->stripes[index].dev;
5937 
5938 		if (device->devid == READ_ONCE(device->fs_devices->read_devid))
5939 			return index;
5940 	}
5941 
5942 	/* If no read-preferred device is set use the first stripe. */
5943 	return first;
5944 }
5945 
5946 struct stripe_mirror {
5947 	u64 devid;
5948 	int num;
5949 };
5950 
btrfs_cmp_devid(const void * a,const void * b)5951 static int btrfs_cmp_devid(const void *a, const void *b)
5952 {
5953 	const struct stripe_mirror *s1 = (const struct stripe_mirror *)a;
5954 	const struct stripe_mirror *s2 = (const struct stripe_mirror *)b;
5955 
5956 	if (s1->devid < s2->devid)
5957 		return -1;
5958 	if (s1->devid > s2->devid)
5959 		return 1;
5960 	return 0;
5961 }
5962 
5963 /*
5964  * Select a stripe for reading using the round-robin algorithm.
5965  *
5966  *  1. Compute the read cycle as the total sectors read divided by the minimum
5967  *     sectors per device.
5968  *  2. Determine the stripe number for the current read by taking the modulus
5969  *     of the read cycle with the total number of stripes:
5970  *
5971  *      stripe index = (total sectors / min sectors per dev) % num stripes
5972  *
5973  * The calculated stripe index is then used to select the corresponding device
5974  * from the list of devices, which is ordered by devid.
5975  */
btrfs_read_rr(const struct btrfs_chunk_map * map,int first,int num_stripes)5976 static int btrfs_read_rr(const struct btrfs_chunk_map *map, int first, int num_stripes)
5977 {
5978 	struct stripe_mirror stripes[BTRFS_RAID1_MAX_MIRRORS] = { 0 };
5979 	struct btrfs_device *device  = map->stripes[first].dev;
5980 	struct btrfs_fs_info *fs_info = device->fs_devices->fs_info;
5981 	unsigned int read_cycle;
5982 	unsigned int total_reads;
5983 	unsigned int min_reads_per_dev;
5984 
5985 	total_reads = percpu_counter_sum(&fs_info->stats_read_blocks);
5986 	min_reads_per_dev = READ_ONCE(fs_info->fs_devices->rr_min_contig_read) >>
5987 						       fs_info->sectorsize_bits;
5988 
5989 	for (int index = 0, i = first; i < first + num_stripes; i++) {
5990 		stripes[index].devid = map->stripes[i].dev->devid;
5991 		stripes[index].num = i;
5992 		index++;
5993 	}
5994 	sort(stripes, num_stripes, sizeof(struct stripe_mirror),
5995 	     btrfs_cmp_devid, NULL);
5996 
5997 	read_cycle = total_reads / min_reads_per_dev;
5998 	return stripes[read_cycle % num_stripes].num;
5999 }
6000 #endif
6001 
find_live_mirror(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map,int first,bool dev_replace_is_ongoing)6002 static int find_live_mirror(struct btrfs_fs_info *fs_info,
6003 			    struct btrfs_chunk_map *map, int first,
6004 			    bool dev_replace_is_ongoing)
6005 {
6006 	const enum btrfs_read_policy policy = READ_ONCE(fs_info->fs_devices->read_policy);
6007 	int i;
6008 	int num_stripes;
6009 	int preferred_mirror;
6010 	int tolerance;
6011 	struct btrfs_device *srcdev;
6012 
6013 	ASSERT((map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)),
6014 	       "type=%llu", map->type);
6015 
6016 	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6017 		num_stripes = map->sub_stripes;
6018 	else
6019 		num_stripes = map->num_stripes;
6020 
6021 	switch (policy) {
6022 	default:
6023 		/* Shouldn't happen, just warn and use pid instead of failing */
6024 		btrfs_warn_rl(fs_info, "unknown read_policy type %u, reset to pid",
6025 			      policy);
6026 		WRITE_ONCE(fs_info->fs_devices->read_policy, BTRFS_READ_POLICY_PID);
6027 		fallthrough;
6028 	case BTRFS_READ_POLICY_PID:
6029 		preferred_mirror = first + (current->pid % num_stripes);
6030 		break;
6031 #ifdef CONFIG_BTRFS_EXPERIMENTAL
6032 	case BTRFS_READ_POLICY_RR:
6033 		preferred_mirror = btrfs_read_rr(map, first, num_stripes);
6034 		break;
6035 	case BTRFS_READ_POLICY_DEVID:
6036 		preferred_mirror = btrfs_read_preferred(map, first, num_stripes);
6037 		break;
6038 #endif
6039 	}
6040 
6041 	if (dev_replace_is_ongoing &&
6042 	    fs_info->dev_replace.cont_reading_from_srcdev_mode ==
6043 	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
6044 		srcdev = fs_info->dev_replace.srcdev;
6045 	else
6046 		srcdev = NULL;
6047 
6048 	/*
6049 	 * try to avoid the drive that is the source drive for a
6050 	 * dev-replace procedure, only choose it if no other non-missing
6051 	 * mirror is available
6052 	 */
6053 	for (tolerance = 0; tolerance < 2; tolerance++) {
6054 		if (map->stripes[preferred_mirror].dev->bdev &&
6055 		    (tolerance || map->stripes[preferred_mirror].dev != srcdev))
6056 			return preferred_mirror;
6057 		for (i = first; i < first + num_stripes; i++) {
6058 			if (map->stripes[i].dev->bdev &&
6059 			    (tolerance || map->stripes[i].dev != srcdev))
6060 				return i;
6061 		}
6062 	}
6063 
6064 	/* we couldn't find one that doesn't fail.  Just return something
6065 	 * and the io error handling code will clean up eventually
6066 	 */
6067 	return preferred_mirror;
6068 }
6069 
6070 EXPORT_FOR_TESTS
alloc_btrfs_io_context(struct btrfs_fs_info * fs_info,u64 logical,u16 total_stripes)6071 struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
6072 						u64 logical, u16 total_stripes)
6073 {
6074 	struct btrfs_io_context *bioc;
6075 
6076 	bioc = kzalloc(
6077 		 /* The size of btrfs_io_context */
6078 		sizeof(struct btrfs_io_context) +
6079 		/* Plus the variable array for the stripes */
6080 		sizeof(struct btrfs_io_stripe) * (total_stripes),
6081 		GFP_NOFS);
6082 
6083 	if (!bioc)
6084 		return NULL;
6085 
6086 	refcount_set(&bioc->refs, 1);
6087 
6088 	bioc->fs_info = fs_info;
6089 	bioc->replace_stripe_src = -1;
6090 	bioc->full_stripe_logical = (u64)-1;
6091 	bioc->logical = logical;
6092 
6093 	return bioc;
6094 }
6095 
btrfs_get_bioc(struct btrfs_io_context * bioc)6096 void btrfs_get_bioc(struct btrfs_io_context *bioc)
6097 {
6098 	WARN_ON(!refcount_read(&bioc->refs));
6099 	refcount_inc(&bioc->refs);
6100 }
6101 
btrfs_put_bioc(struct btrfs_io_context * bioc)6102 void btrfs_put_bioc(struct btrfs_io_context *bioc)
6103 {
6104 	if (!bioc)
6105 		return;
6106 	if (refcount_dec_and_test(&bioc->refs))
6107 		kfree(bioc);
6108 }
6109 
6110 /*
6111  * Please note that, discard won't be sent to target device of device
6112  * replace.
6113  */
btrfs_map_discard(struct btrfs_fs_info * fs_info,u64 logical,u64 * length_ret,u32 * num_stripes)6114 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
6115 					       u64 logical, u64 *length_ret,
6116 					       u32 *num_stripes)
6117 {
6118 	struct btrfs_chunk_map *map;
6119 	struct btrfs_discard_stripe *stripes;
6120 	u64 length = *length_ret;
6121 	u64 offset;
6122 	u32 stripe_nr;
6123 	u32 stripe_nr_end;
6124 	u32 stripe_cnt;
6125 	u64 stripe_end_offset;
6126 	u64 stripe_offset;
6127 	u32 stripe_index;
6128 	u32 factor = 0;
6129 	u32 sub_stripes = 0;
6130 	u32 stripes_per_dev = 0;
6131 	u32 remaining_stripes = 0;
6132 	u32 last_stripe = 0;
6133 	int ret;
6134 	int i;
6135 
6136 	map = btrfs_get_chunk_map(fs_info, logical, length);
6137 	if (IS_ERR(map))
6138 		return ERR_CAST(map);
6139 
6140 	/* we don't discard raid56 yet */
6141 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6142 		ret = -EOPNOTSUPP;
6143 		goto out_free_map;
6144 	}
6145 
6146 	offset = logical - map->start;
6147 	length = min_t(u64, map->start + map->chunk_len - logical, length);
6148 	*length_ret = length;
6149 
6150 	/*
6151 	 * stripe_nr counts the total number of stripes we have to stride
6152 	 * to get to this block
6153 	 */
6154 	stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6155 
6156 	/* stripe_offset is the offset of this block in its stripe */
6157 	stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
6158 
6159 	stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
6160 			BTRFS_STRIPE_LEN_SHIFT;
6161 	stripe_cnt = stripe_nr_end - stripe_nr;
6162 	stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
6163 			    (offset + length);
6164 	/*
6165 	 * after this, stripe_nr is the number of stripes on this
6166 	 * device we have to walk to find the data, and stripe_index is
6167 	 * the number of our device in the stripe array
6168 	 */
6169 	*num_stripes = 1;
6170 	stripe_index = 0;
6171 	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6172 			 BTRFS_BLOCK_GROUP_RAID10)) {
6173 		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6174 			sub_stripes = 1;
6175 		else
6176 			sub_stripes = map->sub_stripes;
6177 
6178 		factor = map->num_stripes / sub_stripes;
6179 		*num_stripes = min_t(u64, map->num_stripes,
6180 				    sub_stripes * stripe_cnt);
6181 		stripe_index = stripe_nr % factor;
6182 		stripe_nr /= factor;
6183 		stripe_index *= sub_stripes;
6184 
6185 		remaining_stripes = stripe_cnt % factor;
6186 		stripes_per_dev = stripe_cnt / factor;
6187 		last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
6188 	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6189 				BTRFS_BLOCK_GROUP_DUP)) {
6190 		*num_stripes = map->num_stripes;
6191 	} else {
6192 		stripe_index = stripe_nr % map->num_stripes;
6193 		stripe_nr /= map->num_stripes;
6194 	}
6195 
6196 	stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
6197 	if (!stripes) {
6198 		ret = -ENOMEM;
6199 		goto out_free_map;
6200 	}
6201 
6202 	for (i = 0; i < *num_stripes; i++) {
6203 		stripes[i].physical =
6204 			map->stripes[stripe_index].physical +
6205 			stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6206 		stripes[i].dev = map->stripes[stripe_index].dev;
6207 
6208 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6209 				 BTRFS_BLOCK_GROUP_RAID10)) {
6210 			stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6211 
6212 			if (i / sub_stripes < remaining_stripes)
6213 				stripes[i].length += BTRFS_STRIPE_LEN;
6214 
6215 			/*
6216 			 * Special for the first stripe and
6217 			 * the last stripe:
6218 			 *
6219 			 * |-------|...|-------|
6220 			 *     |----------|
6221 			 *    off     end_off
6222 			 */
6223 			if (i < sub_stripes)
6224 				stripes[i].length -= stripe_offset;
6225 
6226 			if (stripe_index >= last_stripe &&
6227 			    stripe_index <= (last_stripe +
6228 					     sub_stripes - 1))
6229 				stripes[i].length -= stripe_end_offset;
6230 
6231 			if (i == sub_stripes - 1)
6232 				stripe_offset = 0;
6233 		} else {
6234 			stripes[i].length = length;
6235 		}
6236 
6237 		stripe_index++;
6238 		if (stripe_index == map->num_stripes) {
6239 			stripe_index = 0;
6240 			stripe_nr++;
6241 		}
6242 	}
6243 
6244 	btrfs_free_chunk_map(map);
6245 	return stripes;
6246 out_free_map:
6247 	btrfs_free_chunk_map(map);
6248 	return ERR_PTR(ret);
6249 }
6250 
is_block_group_to_copy(struct btrfs_fs_info * fs_info,u64 logical)6251 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6252 {
6253 	struct btrfs_block_group *cache;
6254 	bool ret;
6255 
6256 	/* Non zoned filesystem does not use "to_copy" flag */
6257 	if (!btrfs_is_zoned(fs_info))
6258 		return false;
6259 
6260 	cache = btrfs_lookup_block_group(fs_info, logical);
6261 
6262 	ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6263 
6264 	btrfs_put_block_group(cache);
6265 	return ret;
6266 }
6267 
handle_ops_on_dev_replace(struct btrfs_io_context * bioc,struct btrfs_dev_replace * dev_replace,u64 logical,struct btrfs_io_geometry * io_geom)6268 static void handle_ops_on_dev_replace(struct btrfs_io_context *bioc,
6269 				      struct btrfs_dev_replace *dev_replace,
6270 				      u64 logical,
6271 				      struct btrfs_io_geometry *io_geom)
6272 {
6273 	u64 srcdev_devid = dev_replace->srcdev->devid;
6274 	/*
6275 	 * At this stage, num_stripes is still the real number of stripes,
6276 	 * excluding the duplicated stripes.
6277 	 */
6278 	int num_stripes = io_geom->num_stripes;
6279 	int max_errors = io_geom->max_errors;
6280 	int nr_extra_stripes = 0;
6281 	int i;
6282 
6283 	/*
6284 	 * A block group which has "to_copy" set will eventually be copied by
6285 	 * the dev-replace process. We can avoid cloning IO here.
6286 	 */
6287 	if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6288 		return;
6289 
6290 	/*
6291 	 * Duplicate the write operations while the dev-replace procedure is
6292 	 * running. Since the copying of the old disk to the new disk takes
6293 	 * place at run time while the filesystem is mounted writable, the
6294 	 * regular write operations to the old disk have to be duplicated to go
6295 	 * to the new disk as well.
6296 	 *
6297 	 * Note that device->missing is handled by the caller, and that the
6298 	 * write to the old disk is already set up in the stripes array.
6299 	 */
6300 	for (i = 0; i < num_stripes; i++) {
6301 		struct btrfs_io_stripe *old = &bioc->stripes[i];
6302 		struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6303 
6304 		if (old->dev->devid != srcdev_devid)
6305 			continue;
6306 
6307 		new->physical = old->physical;
6308 		new->dev = dev_replace->tgtdev;
6309 		if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6310 			bioc->replace_stripe_src = i;
6311 		nr_extra_stripes++;
6312 	}
6313 
6314 	/* We can only have at most 2 extra nr_stripes (for DUP). */
6315 	ASSERT(nr_extra_stripes <= 2, "nr_extra_stripes=%d", nr_extra_stripes);
6316 	/*
6317 	 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6318 	 * replace.
6319 	 * If we have 2 extra stripes, only choose the one with smaller physical.
6320 	 */
6321 	if (io_geom->op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6322 		struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6323 		struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6324 
6325 		/* Only DUP can have two extra stripes. */
6326 		ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP,
6327 		       "map_type=%llu", bioc->map_type);
6328 
6329 		/*
6330 		 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6331 		 * The extra stripe would still be there, but won't be accessed.
6332 		 */
6333 		if (first->physical > second->physical) {
6334 			swap(second->physical, first->physical);
6335 			swap(second->dev, first->dev);
6336 			nr_extra_stripes--;
6337 		}
6338 	}
6339 
6340 	io_geom->num_stripes = num_stripes + nr_extra_stripes;
6341 	io_geom->max_errors = max_errors + nr_extra_stripes;
6342 	bioc->replace_nr_stripes = nr_extra_stripes;
6343 }
6344 
btrfs_max_io_len(struct btrfs_chunk_map * map,u64 offset,struct btrfs_io_geometry * io_geom)6345 static u64 btrfs_max_io_len(struct btrfs_chunk_map *map, u64 offset,
6346 			    struct btrfs_io_geometry *io_geom)
6347 {
6348 	/*
6349 	 * Stripe_nr is the stripe where this block falls.  stripe_offset is
6350 	 * the offset of this block in its stripe.
6351 	 */
6352 	io_geom->stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6353 	io_geom->stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6354 	ASSERT(io_geom->stripe_offset < U32_MAX,
6355 	       "stripe_offset=%llu", io_geom->stripe_offset);
6356 
6357 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6358 		unsigned long full_stripe_len =
6359 			btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6360 
6361 		/*
6362 		 * For full stripe start, we use previously calculated
6363 		 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6364 		 * STRIPE_LEN.
6365 		 *
6366 		 * By this we can avoid u64 division completely.  And we have
6367 		 * to go rounddown(), not round_down(), as nr_data_stripes is
6368 		 * not ensured to be power of 2.
6369 		 */
6370 		io_geom->raid56_full_stripe_start = btrfs_stripe_nr_to_offset(
6371 			rounddown(io_geom->stripe_nr, nr_data_stripes(map)));
6372 
6373 		ASSERT(io_geom->raid56_full_stripe_start + full_stripe_len > offset,
6374 		       "raid56_full_stripe_start=%llu full_stripe_len=%lu offset=%llu",
6375 		       io_geom->raid56_full_stripe_start, full_stripe_len, offset);
6376 		ASSERT(io_geom->raid56_full_stripe_start <= offset,
6377 		       "raid56_full_stripe_start=%llu offset=%llu",
6378 		       io_geom->raid56_full_stripe_start, offset);
6379 		/*
6380 		 * For writes to RAID56, allow to write a full stripe set, but
6381 		 * no straddling of stripe sets.
6382 		 */
6383 		if (io_geom->op == BTRFS_MAP_WRITE)
6384 			return full_stripe_len - (offset - io_geom->raid56_full_stripe_start);
6385 	}
6386 
6387 	/*
6388 	 * For other RAID types and for RAID56 reads, allow a single stripe (on
6389 	 * a single disk).
6390 	 */
6391 	if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6392 		return BTRFS_STRIPE_LEN - io_geom->stripe_offset;
6393 	return U64_MAX;
6394 }
6395 
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)6396 static int set_io_stripe(struct btrfs_fs_info *fs_info, u64 logical,
6397 			 u64 *length, struct btrfs_io_stripe *dst,
6398 			 struct btrfs_chunk_map *map,
6399 			 struct btrfs_io_geometry *io_geom)
6400 {
6401 	dst->dev = map->stripes[io_geom->stripe_index].dev;
6402 
6403 	if (io_geom->op == BTRFS_MAP_READ && io_geom->use_rst)
6404 		return btrfs_get_raid_extent_offset(fs_info, logical, length,
6405 						    map->type,
6406 						    io_geom->stripe_index, dst);
6407 
6408 	dst->physical = map->stripes[io_geom->stripe_index].physical +
6409 			io_geom->stripe_offset +
6410 			btrfs_stripe_nr_to_offset(io_geom->stripe_nr);
6411 	return 0;
6412 }
6413 
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)6414 static bool is_single_device_io(struct btrfs_fs_info *fs_info,
6415 				const struct btrfs_io_stripe *smap,
6416 				const struct btrfs_chunk_map *map,
6417 				int num_alloc_stripes,
6418 				struct btrfs_io_geometry *io_geom)
6419 {
6420 	if (!smap)
6421 		return false;
6422 
6423 	if (num_alloc_stripes != 1)
6424 		return false;
6425 
6426 	if (io_geom->use_rst && io_geom->op != BTRFS_MAP_READ)
6427 		return false;
6428 
6429 	if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && io_geom->mirror_num > 1)
6430 		return false;
6431 
6432 	return true;
6433 }
6434 
map_blocks_raid0(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6435 static void map_blocks_raid0(const struct btrfs_chunk_map *map,
6436 			     struct btrfs_io_geometry *io_geom)
6437 {
6438 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6439 	io_geom->stripe_nr /= map->num_stripes;
6440 	if (io_geom->op == BTRFS_MAP_READ)
6441 		io_geom->mirror_num = 1;
6442 }
6443 
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)6444 static void map_blocks_raid1(struct btrfs_fs_info *fs_info,
6445 			     struct btrfs_chunk_map *map,
6446 			     struct btrfs_io_geometry *io_geom,
6447 			     bool dev_replace_is_ongoing)
6448 {
6449 	if (io_geom->op != BTRFS_MAP_READ) {
6450 		io_geom->num_stripes = map->num_stripes;
6451 		return;
6452 	}
6453 
6454 	if (io_geom->mirror_num) {
6455 		io_geom->stripe_index = io_geom->mirror_num - 1;
6456 		return;
6457 	}
6458 
6459 	io_geom->stripe_index = find_live_mirror(fs_info, map, 0,
6460 						 dev_replace_is_ongoing);
6461 	io_geom->mirror_num = io_geom->stripe_index + 1;
6462 }
6463 
map_blocks_dup(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6464 static void map_blocks_dup(const struct btrfs_chunk_map *map,
6465 			   struct btrfs_io_geometry *io_geom)
6466 {
6467 	if (io_geom->op != BTRFS_MAP_READ) {
6468 		io_geom->num_stripes = map->num_stripes;
6469 		return;
6470 	}
6471 
6472 	if (io_geom->mirror_num) {
6473 		io_geom->stripe_index = io_geom->mirror_num - 1;
6474 		return;
6475 	}
6476 
6477 	io_geom->mirror_num = 1;
6478 }
6479 
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)6480 static void map_blocks_raid10(struct btrfs_fs_info *fs_info,
6481 			      struct btrfs_chunk_map *map,
6482 			      struct btrfs_io_geometry *io_geom,
6483 			      bool dev_replace_is_ongoing)
6484 {
6485 	u32 factor = map->num_stripes / map->sub_stripes;
6486 	int old_stripe_index;
6487 
6488 	io_geom->stripe_index = (io_geom->stripe_nr % factor) * map->sub_stripes;
6489 	io_geom->stripe_nr /= factor;
6490 
6491 	if (io_geom->op != BTRFS_MAP_READ) {
6492 		io_geom->num_stripes = map->sub_stripes;
6493 		return;
6494 	}
6495 
6496 	if (io_geom->mirror_num) {
6497 		io_geom->stripe_index += io_geom->mirror_num - 1;
6498 		return;
6499 	}
6500 
6501 	old_stripe_index = io_geom->stripe_index;
6502 	io_geom->stripe_index = find_live_mirror(fs_info, map,
6503 						 io_geom->stripe_index,
6504 						 dev_replace_is_ongoing);
6505 	io_geom->mirror_num = io_geom->stripe_index - old_stripe_index + 1;
6506 }
6507 
map_blocks_raid56_write(struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom,u64 logical,u64 * length)6508 static void map_blocks_raid56_write(struct btrfs_chunk_map *map,
6509 				    struct btrfs_io_geometry *io_geom,
6510 				    u64 logical, u64 *length)
6511 {
6512 	int data_stripes = nr_data_stripes(map);
6513 
6514 	/*
6515 	 * Needs full stripe mapping.
6516 	 *
6517 	 * Push stripe_nr back to the start of the full stripe For those cases
6518 	 * needing a full stripe, @stripe_nr is the full stripe number.
6519 	 *
6520 	 * Originally we go raid56_full_stripe_start / full_stripe_len, but
6521 	 * that can be expensive.  Here we just divide @stripe_nr with
6522 	 * @data_stripes.
6523 	 */
6524 	io_geom->stripe_nr /= data_stripes;
6525 
6526 	/* RAID[56] write or recovery. Return all stripes */
6527 	io_geom->num_stripes = map->num_stripes;
6528 	io_geom->max_errors = btrfs_chunk_max_errors(map);
6529 
6530 	/* Return the length to the full stripe end. */
6531 	*length = min(logical + *length,
6532 		      io_geom->raid56_full_stripe_start + map->start +
6533 		      btrfs_stripe_nr_to_offset(data_stripes)) -
6534 		logical;
6535 	io_geom->stripe_index = 0;
6536 	io_geom->stripe_offset = 0;
6537 }
6538 
map_blocks_raid56_read(struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6539 static void map_blocks_raid56_read(struct btrfs_chunk_map *map,
6540 				   struct btrfs_io_geometry *io_geom)
6541 {
6542 	int data_stripes = nr_data_stripes(map);
6543 
6544 	ASSERT(io_geom->mirror_num <= 1, "mirror_num=%d", io_geom->mirror_num);
6545 	/* Just grab the data stripe directly. */
6546 	io_geom->stripe_index = io_geom->stripe_nr % data_stripes;
6547 	io_geom->stripe_nr /= data_stripes;
6548 
6549 	/* We distribute the parity blocks across stripes. */
6550 	io_geom->stripe_index =
6551 		(io_geom->stripe_nr + io_geom->stripe_index) % map->num_stripes;
6552 
6553 	if (io_geom->op == BTRFS_MAP_READ && io_geom->mirror_num < 1)
6554 		io_geom->mirror_num = 1;
6555 }
6556 
map_blocks_single(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6557 static void map_blocks_single(const struct btrfs_chunk_map *map,
6558 			      struct btrfs_io_geometry *io_geom)
6559 {
6560 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6561 	io_geom->stripe_nr /= map->num_stripes;
6562 	io_geom->mirror_num = io_geom->stripe_index + 1;
6563 }
6564 
6565 /*
6566  * Map one logical range to one or more physical ranges.
6567  *
6568  * @length:		(Mandatory) mapped length of this run.
6569  *			One logical range can be split into different segments
6570  *			due to factors like zones and RAID0/5/6/10 stripe
6571  *			boundaries.
6572  *
6573  * @bioc_ret:		(Mandatory) returned btrfs_io_context structure.
6574  *			which has one or more physical ranges (btrfs_io_stripe)
6575  *			recorded inside.
6576  *			Caller should call btrfs_put_bioc() to free it after use.
6577  *
6578  * @smap:		(Optional) single physical range optimization.
6579  *			If the map request can be fulfilled by one single
6580  *			physical range, and this is parameter is not NULL,
6581  *			then @bioc_ret would be NULL, and @smap would be
6582  *			updated.
6583  *
6584  * @mirror_num_ret:	(Mandatory) returned mirror number if the original
6585  *			value is 0.
6586  *
6587  *			Mirror number 0 means to choose any live mirrors.
6588  *
6589  *			For non-RAID56 profiles, non-zero mirror_num means
6590  *			the Nth mirror. (e.g. mirror_num 1 means the first
6591  *			copy).
6592  *
6593  *			For RAID56 profile, mirror 1 means rebuild from P and
6594  *			the remaining data stripes.
6595  *
6596  *			For RAID6 profile, mirror > 2 means mark another
6597  *			data/P stripe error and rebuild from the remaining
6598  *			stripes..
6599  */
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)6600 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6601 		    u64 logical, u64 *length,
6602 		    struct btrfs_io_context **bioc_ret,
6603 		    struct btrfs_io_stripe *smap, int *mirror_num_ret)
6604 {
6605 	struct btrfs_chunk_map *map;
6606 	struct btrfs_io_geometry io_geom = { 0 };
6607 	u64 map_offset;
6608 	int ret = 0;
6609 	int num_copies;
6610 	struct btrfs_io_context *bioc = NULL;
6611 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6612 	bool dev_replace_is_ongoing = false;
6613 	u16 num_alloc_stripes;
6614 	u64 max_len;
6615 
6616 	ASSERT(bioc_ret);
6617 
6618 	io_geom.mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6619 	io_geom.num_stripes = 1;
6620 	io_geom.stripe_index = 0;
6621 	io_geom.op = op;
6622 
6623 	map = btrfs_get_chunk_map(fs_info, logical, *length);
6624 	if (IS_ERR(map))
6625 		return PTR_ERR(map);
6626 
6627 	num_copies = btrfs_chunk_map_num_copies(map);
6628 	if (io_geom.mirror_num > num_copies)
6629 		return -EINVAL;
6630 
6631 	map_offset = logical - map->start;
6632 	io_geom.raid56_full_stripe_start = (u64)-1;
6633 	max_len = btrfs_max_io_len(map, map_offset, &io_geom);
6634 	*length = min_t(u64, map->chunk_len - map_offset, max_len);
6635 	io_geom.use_rst = btrfs_need_stripe_tree_update(fs_info, map->type);
6636 
6637 	if (dev_replace->replace_task != current)
6638 		down_read(&dev_replace->rwsem);
6639 
6640 	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6641 	/*
6642 	 * Hold the semaphore for read during the whole operation, write is
6643 	 * requested at commit time but must wait.
6644 	 */
6645 	if (!dev_replace_is_ongoing && dev_replace->replace_task != current)
6646 		up_read(&dev_replace->rwsem);
6647 
6648 	switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6649 	case BTRFS_BLOCK_GROUP_RAID0:
6650 		map_blocks_raid0(map, &io_geom);
6651 		break;
6652 	case BTRFS_BLOCK_GROUP_RAID1:
6653 	case BTRFS_BLOCK_GROUP_RAID1C3:
6654 	case BTRFS_BLOCK_GROUP_RAID1C4:
6655 		map_blocks_raid1(fs_info, map, &io_geom, dev_replace_is_ongoing);
6656 		break;
6657 	case BTRFS_BLOCK_GROUP_DUP:
6658 		map_blocks_dup(map, &io_geom);
6659 		break;
6660 	case BTRFS_BLOCK_GROUP_RAID10:
6661 		map_blocks_raid10(fs_info, map, &io_geom, dev_replace_is_ongoing);
6662 		break;
6663 	case BTRFS_BLOCK_GROUP_RAID5:
6664 	case BTRFS_BLOCK_GROUP_RAID6:
6665 		if (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)
6666 			map_blocks_raid56_write(map, &io_geom, logical, length);
6667 		else
6668 			map_blocks_raid56_read(map, &io_geom);
6669 		break;
6670 	default:
6671 		/*
6672 		 * After this, stripe_nr is the number of stripes on this
6673 		 * device we have to walk to find the data, and stripe_index is
6674 		 * the number of our device in the stripe array
6675 		 */
6676 		map_blocks_single(map, &io_geom);
6677 		break;
6678 	}
6679 	if (io_geom.stripe_index >= map->num_stripes) {
6680 		btrfs_crit(fs_info,
6681 			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6682 			   io_geom.stripe_index, map->num_stripes);
6683 		ret = -EINVAL;
6684 		goto out;
6685 	}
6686 
6687 	num_alloc_stripes = io_geom.num_stripes;
6688 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6689 	    op != BTRFS_MAP_READ)
6690 		/*
6691 		 * For replace case, we need to add extra stripes for extra
6692 		 * duplicated stripes.
6693 		 *
6694 		 * For both WRITE and GET_READ_MIRRORS, we may have at most
6695 		 * 2 more stripes (DUP types, otherwise 1).
6696 		 */
6697 		num_alloc_stripes += 2;
6698 
6699 	/*
6700 	 * If this I/O maps to a single device, try to return the device and
6701 	 * physical block information on the stack instead of allocating an
6702 	 * I/O context structure.
6703 	 */
6704 	if (is_single_device_io(fs_info, smap, map, num_alloc_stripes, &io_geom)) {
6705 		ret = set_io_stripe(fs_info, logical, length, smap, map, &io_geom);
6706 		if (mirror_num_ret)
6707 			*mirror_num_ret = io_geom.mirror_num;
6708 		*bioc_ret = NULL;
6709 		goto out;
6710 	}
6711 
6712 	bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
6713 	if (!bioc) {
6714 		ret = -ENOMEM;
6715 		goto out;
6716 	}
6717 	bioc->map_type = map->type;
6718 	bioc->use_rst = io_geom.use_rst;
6719 
6720 	/*
6721 	 * For RAID56 full map, we need to make sure the stripes[] follows the
6722 	 * rule that data stripes are all ordered, then followed with P and Q
6723 	 * (if we have).
6724 	 *
6725 	 * It's still mostly the same as other profiles, just with extra rotation.
6726 	 */
6727 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
6728 	    (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)) {
6729 		/*
6730 		 * For RAID56 @stripe_nr is already the number of full stripes
6731 		 * before us, which is also the rotation value (needs to modulo
6732 		 * with num_stripes).
6733 		 *
6734 		 * In this case, we just add @stripe_nr with @i, then do the
6735 		 * modulo, to reduce one modulo call.
6736 		 */
6737 		bioc->full_stripe_logical = map->start +
6738 			btrfs_stripe_nr_to_offset(io_geom.stripe_nr *
6739 						  nr_data_stripes(map));
6740 		for (int i = 0; i < io_geom.num_stripes; i++) {
6741 			struct btrfs_io_stripe *dst = &bioc->stripes[i];
6742 			u32 stripe_index;
6743 
6744 			stripe_index = (i + io_geom.stripe_nr) % io_geom.num_stripes;
6745 			dst->dev = map->stripes[stripe_index].dev;
6746 			dst->physical =
6747 				map->stripes[stripe_index].physical +
6748 				io_geom.stripe_offset +
6749 				btrfs_stripe_nr_to_offset(io_geom.stripe_nr);
6750 		}
6751 	} else {
6752 		/*
6753 		 * For all other non-RAID56 profiles, just copy the target
6754 		 * stripe into the bioc.
6755 		 */
6756 		for (int i = 0; i < io_geom.num_stripes; i++) {
6757 			ret = set_io_stripe(fs_info, logical, length,
6758 					    &bioc->stripes[i], map, &io_geom);
6759 			if (ret < 0)
6760 				break;
6761 			io_geom.stripe_index++;
6762 		}
6763 	}
6764 
6765 	if (ret) {
6766 		*bioc_ret = NULL;
6767 		btrfs_put_bioc(bioc);
6768 		goto out;
6769 	}
6770 
6771 	if (op != BTRFS_MAP_READ)
6772 		io_geom.max_errors = btrfs_chunk_max_errors(map);
6773 
6774 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6775 	    op != BTRFS_MAP_READ) {
6776 		handle_ops_on_dev_replace(bioc, dev_replace, logical, &io_geom);
6777 	}
6778 
6779 	*bioc_ret = bioc;
6780 	bioc->num_stripes = io_geom.num_stripes;
6781 	bioc->max_errors = io_geom.max_errors;
6782 	bioc->mirror_num = io_geom.mirror_num;
6783 
6784 out:
6785 	if (dev_replace_is_ongoing && dev_replace->replace_task != current) {
6786 		lockdep_assert_held(&dev_replace->rwsem);
6787 		/* Unlock and let waiting writers proceed */
6788 		up_read(&dev_replace->rwsem);
6789 	}
6790 	btrfs_free_chunk_map(map);
6791 	return ret;
6792 }
6793 
dev_args_match_fs_devices(const struct btrfs_dev_lookup_args * args,const struct btrfs_fs_devices * fs_devices)6794 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6795 				      const struct btrfs_fs_devices *fs_devices)
6796 {
6797 	if (args->fsid == NULL)
6798 		return true;
6799 	if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6800 		return true;
6801 	return false;
6802 }
6803 
dev_args_match_device(const struct btrfs_dev_lookup_args * args,const struct btrfs_device * device)6804 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6805 				  const struct btrfs_device *device)
6806 {
6807 	if (args->missing) {
6808 		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6809 		    !device->bdev)
6810 			return true;
6811 		return false;
6812 	}
6813 
6814 	if (device->devid != args->devid)
6815 		return false;
6816 	if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6817 		return false;
6818 	return true;
6819 }
6820 
6821 /*
6822  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6823  * return NULL.
6824  *
6825  * If devid and uuid are both specified, the match must be exact, otherwise
6826  * only devid is used.
6827  */
btrfs_find_device(const struct btrfs_fs_devices * fs_devices,const struct btrfs_dev_lookup_args * args)6828 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6829 				       const struct btrfs_dev_lookup_args *args)
6830 {
6831 	struct btrfs_device *device;
6832 	struct btrfs_fs_devices *seed_devs;
6833 
6834 	if (dev_args_match_fs_devices(args, fs_devices)) {
6835 		list_for_each_entry(device, &fs_devices->devices, dev_list) {
6836 			if (dev_args_match_device(args, device))
6837 				return device;
6838 		}
6839 	}
6840 
6841 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6842 		if (!dev_args_match_fs_devices(args, seed_devs))
6843 			continue;
6844 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
6845 			if (dev_args_match_device(args, device))
6846 				return device;
6847 		}
6848 	}
6849 
6850 	return NULL;
6851 }
6852 
add_missing_dev(struct btrfs_fs_devices * fs_devices,u64 devid,u8 * dev_uuid)6853 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6854 					    u64 devid, u8 *dev_uuid)
6855 {
6856 	struct btrfs_device *device;
6857 	unsigned int nofs_flag;
6858 
6859 	/*
6860 	 * We call this under the chunk_mutex, so we want to use NOFS for this
6861 	 * allocation, however we don't want to change btrfs_alloc_device() to
6862 	 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6863 	 * places.
6864 	 */
6865 
6866 	nofs_flag = memalloc_nofs_save();
6867 	device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
6868 	memalloc_nofs_restore(nofs_flag);
6869 	if (IS_ERR(device))
6870 		return device;
6871 
6872 	list_add(&device->dev_list, &fs_devices->devices);
6873 	device->fs_devices = fs_devices;
6874 	fs_devices->num_devices++;
6875 
6876 	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6877 	fs_devices->missing_devices++;
6878 
6879 	return device;
6880 }
6881 
6882 /*
6883  * Allocate new device struct, set up devid and UUID.
6884  *
6885  * @fs_info:	used only for generating a new devid, can be NULL if
6886  *		devid is provided (i.e. @devid != NULL).
6887  * @devid:	a pointer to devid for this device.  If NULL a new devid
6888  *		is generated.
6889  * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
6890  *		is generated.
6891  * @path:	a pointer to device path if available, NULL otherwise.
6892  *
6893  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6894  * on error.  Returned struct is not linked onto any lists and must be
6895  * destroyed with btrfs_free_device.
6896  */
btrfs_alloc_device(struct btrfs_fs_info * fs_info,const u64 * devid,const u8 * uuid,const char * path)6897 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6898 					const u64 *devid, const u8 *uuid,
6899 					const char *path)
6900 {
6901 	struct btrfs_device *dev;
6902 	u64 tmp;
6903 
6904 	if (WARN_ON(!devid && !fs_info))
6905 		return ERR_PTR(-EINVAL);
6906 
6907 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6908 	if (!dev)
6909 		return ERR_PTR(-ENOMEM);
6910 
6911 	INIT_LIST_HEAD(&dev->dev_list);
6912 	INIT_LIST_HEAD(&dev->dev_alloc_list);
6913 	INIT_LIST_HEAD(&dev->post_commit_list);
6914 
6915 	atomic_set(&dev->dev_stats_ccnt, 0);
6916 	btrfs_device_data_ordered_init(dev);
6917 	btrfs_extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
6918 
6919 	if (devid)
6920 		tmp = *devid;
6921 	else {
6922 		int ret;
6923 
6924 		ret = find_next_devid(fs_info, &tmp);
6925 		if (ret) {
6926 			btrfs_free_device(dev);
6927 			return ERR_PTR(ret);
6928 		}
6929 	}
6930 	dev->devid = tmp;
6931 
6932 	if (uuid)
6933 		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6934 	else
6935 		generate_random_uuid(dev->uuid);
6936 
6937 	if (path) {
6938 		const char *name;
6939 
6940 		name = kstrdup(path, GFP_KERNEL);
6941 		if (!name) {
6942 			btrfs_free_device(dev);
6943 			return ERR_PTR(-ENOMEM);
6944 		}
6945 		rcu_assign_pointer(dev->name, name);
6946 	}
6947 
6948 	return dev;
6949 }
6950 
btrfs_report_missing_device(struct btrfs_fs_info * fs_info,u64 devid,u8 * uuid,bool error)6951 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6952 					u64 devid, u8 *uuid, bool error)
6953 {
6954 	if (error)
6955 		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6956 			      devid, uuid);
6957 	else
6958 		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6959 			      devid, uuid);
6960 }
6961 
btrfs_calc_stripe_length(const struct btrfs_chunk_map * map)6962 u64 btrfs_calc_stripe_length(const struct btrfs_chunk_map *map)
6963 {
6964 	const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
6965 
6966 	return div_u64(map->chunk_len, data_stripes);
6967 }
6968 
6969 #if BITS_PER_LONG == 32
6970 /*
6971  * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
6972  * can't be accessed on 32bit systems.
6973  *
6974  * This function do mount time check to reject the fs if it already has
6975  * metadata chunk beyond that limit.
6976  */
check_32bit_meta_chunk(struct btrfs_fs_info * fs_info,u64 logical,u64 length,u64 type)6977 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6978 				  u64 logical, u64 length, u64 type)
6979 {
6980 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
6981 		return 0;
6982 
6983 	if (logical + length < MAX_LFS_FILESIZE)
6984 		return 0;
6985 
6986 	btrfs_err_32bit_limit(fs_info);
6987 	return -EOVERFLOW;
6988 }
6989 
6990 /*
6991  * This is to give early warning for any metadata chunk reaching
6992  * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
6993  * Although we can still access the metadata, it's not going to be possible
6994  * once the limit is reached.
6995  */
warn_32bit_meta_chunk(struct btrfs_fs_info * fs_info,u64 logical,u64 length,u64 type)6996 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
6997 				  u64 logical, u64 length, u64 type)
6998 {
6999 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7000 		return;
7001 
7002 	if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7003 		return;
7004 
7005 	btrfs_warn_32bit_limit(fs_info);
7006 }
7007 #endif
7008 
handle_missing_device(struct btrfs_fs_info * fs_info,u64 devid,u8 * uuid)7009 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7010 						  u64 devid, u8 *uuid)
7011 {
7012 	struct btrfs_device *dev;
7013 
7014 	if (!btrfs_test_opt(fs_info, DEGRADED)) {
7015 		btrfs_report_missing_device(fs_info, devid, uuid, true);
7016 		return ERR_PTR(-ENOENT);
7017 	}
7018 
7019 	dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7020 	if (IS_ERR(dev)) {
7021 		btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7022 			  devid, PTR_ERR(dev));
7023 		return dev;
7024 	}
7025 	btrfs_report_missing_device(fs_info, devid, uuid, false);
7026 
7027 	return dev;
7028 }
7029 
read_one_chunk(struct btrfs_key * key,struct extent_buffer * leaf,struct btrfs_chunk * chunk)7030 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7031 			  struct btrfs_chunk *chunk)
7032 {
7033 	BTRFS_DEV_LOOKUP_ARGS(args);
7034 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7035 	struct btrfs_chunk_map *map;
7036 	u64 logical;
7037 	u64 length;
7038 	u64 devid;
7039 	u64 type;
7040 	u8 uuid[BTRFS_UUID_SIZE];
7041 	int index;
7042 	int num_stripes;
7043 	int ret;
7044 	int i;
7045 
7046 	logical = key->offset;
7047 	length = btrfs_chunk_length(leaf, chunk);
7048 	type = btrfs_chunk_type(leaf, chunk);
7049 	index = btrfs_bg_flags_to_raid_index(type);
7050 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7051 
7052 #if BITS_PER_LONG == 32
7053 	ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7054 	if (ret < 0)
7055 		return ret;
7056 	warn_32bit_meta_chunk(fs_info, logical, length, type);
7057 #endif
7058 
7059 	map = btrfs_find_chunk_map(fs_info, logical, 1);
7060 
7061 	/* already mapped? */
7062 	if (map && map->start <= logical && map->start + map->chunk_len > logical) {
7063 		btrfs_free_chunk_map(map);
7064 		return 0;
7065 	} else if (map) {
7066 		btrfs_free_chunk_map(map);
7067 	}
7068 
7069 	map = btrfs_alloc_chunk_map(num_stripes, GFP_NOFS);
7070 	if (!map)
7071 		return -ENOMEM;
7072 
7073 	map->start = logical;
7074 	map->chunk_len = length;
7075 	map->num_stripes = num_stripes;
7076 	map->io_width = btrfs_chunk_io_width(leaf, chunk);
7077 	map->io_align = btrfs_chunk_io_align(leaf, chunk);
7078 	map->type = type;
7079 	/*
7080 	 * We can't use the sub_stripes value, as for profiles other than
7081 	 * RAID10, they may have 0 as sub_stripes for filesystems created by
7082 	 * older mkfs (<v5.4).
7083 	 * In that case, it can cause divide-by-zero errors later.
7084 	 * Since currently sub_stripes is fixed for each profile, let's
7085 	 * use the trusted value instead.
7086 	 */
7087 	map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7088 	map->verified_stripes = 0;
7089 	map->stripe_size = btrfs_calc_stripe_length(map);
7090 	for (i = 0; i < num_stripes; i++) {
7091 		map->stripes[i].physical =
7092 			btrfs_stripe_offset_nr(leaf, chunk, i);
7093 		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7094 		args.devid = devid;
7095 		read_extent_buffer(leaf, uuid, (unsigned long)
7096 				   btrfs_stripe_dev_uuid_nr(chunk, i),
7097 				   BTRFS_UUID_SIZE);
7098 		args.uuid = uuid;
7099 		map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7100 		if (!map->stripes[i].dev) {
7101 			map->stripes[i].dev = handle_missing_device(fs_info,
7102 								    devid, uuid);
7103 			if (IS_ERR(map->stripes[i].dev)) {
7104 				ret = PTR_ERR(map->stripes[i].dev);
7105 				btrfs_free_chunk_map(map);
7106 				return ret;
7107 			}
7108 		}
7109 
7110 		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7111 				&(map->stripes[i].dev->dev_state));
7112 	}
7113 
7114 	ret = btrfs_add_chunk_map(fs_info, map);
7115 	if (ret < 0) {
7116 		btrfs_err(fs_info,
7117 			  "failed to add chunk map, start=%llu len=%llu: %d",
7118 			  map->start, map->chunk_len, ret);
7119 		btrfs_free_chunk_map(map);
7120 	}
7121 
7122 	return ret;
7123 }
7124 
fill_device_from_item(struct extent_buffer * leaf,struct btrfs_dev_item * dev_item,struct btrfs_device * device)7125 static void fill_device_from_item(struct extent_buffer *leaf,
7126 				 struct btrfs_dev_item *dev_item,
7127 				 struct btrfs_device *device)
7128 {
7129 	unsigned long ptr;
7130 
7131 	device->devid = btrfs_device_id(leaf, dev_item);
7132 	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7133 	device->total_bytes = device->disk_total_bytes;
7134 	device->commit_total_bytes = device->disk_total_bytes;
7135 	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7136 	device->commit_bytes_used = device->bytes_used;
7137 	device->type = btrfs_device_type(leaf, dev_item);
7138 	device->io_align = btrfs_device_io_align(leaf, dev_item);
7139 	device->io_width = btrfs_device_io_width(leaf, dev_item);
7140 	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7141 	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7142 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7143 
7144 	ptr = btrfs_device_uuid(dev_item);
7145 	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7146 }
7147 
open_seed_devices(struct btrfs_fs_info * fs_info,u8 * fsid)7148 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7149 						  u8 *fsid)
7150 {
7151 	struct btrfs_fs_devices *fs_devices;
7152 	int ret;
7153 
7154 	lockdep_assert_held(&uuid_mutex);
7155 	ASSERT(fsid);
7156 
7157 	/* This will match only for multi-device seed fs */
7158 	list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7159 		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7160 			return fs_devices;
7161 
7162 
7163 	fs_devices = find_fsid(fsid, NULL);
7164 	if (!fs_devices) {
7165 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7166 			btrfs_err(fs_info,
7167 		"failed to find fsid %pU when attempting to open seed devices",
7168 				  fsid);
7169 			return ERR_PTR(-ENOENT);
7170 		}
7171 
7172 		fs_devices = alloc_fs_devices(fsid);
7173 		if (IS_ERR(fs_devices))
7174 			return fs_devices;
7175 
7176 		fs_devices->seeding = true;
7177 		fs_devices->opened = 1;
7178 		return fs_devices;
7179 	}
7180 
7181 	/*
7182 	 * Upon first call for a seed fs fsid, just create a private copy of the
7183 	 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7184 	 */
7185 	fs_devices = clone_fs_devices(fs_devices);
7186 	if (IS_ERR(fs_devices))
7187 		return fs_devices;
7188 
7189 	ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->sb);
7190 	if (ret) {
7191 		free_fs_devices(fs_devices);
7192 		return ERR_PTR(ret);
7193 	}
7194 
7195 	if (!fs_devices->seeding) {
7196 		close_fs_devices(fs_devices);
7197 		free_fs_devices(fs_devices);
7198 		return ERR_PTR(-EINVAL);
7199 	}
7200 
7201 	list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7202 
7203 	return fs_devices;
7204 }
7205 
read_one_dev(struct extent_buffer * leaf,struct btrfs_dev_item * dev_item)7206 static int read_one_dev(struct extent_buffer *leaf,
7207 			struct btrfs_dev_item *dev_item)
7208 {
7209 	BTRFS_DEV_LOOKUP_ARGS(args);
7210 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7211 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7212 	struct btrfs_device *device;
7213 	u64 devid;
7214 	int ret;
7215 	u8 fs_uuid[BTRFS_FSID_SIZE];
7216 	u8 dev_uuid[BTRFS_UUID_SIZE];
7217 
7218 	devid = btrfs_device_id(leaf, dev_item);
7219 	args.devid = devid;
7220 	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7221 			   BTRFS_UUID_SIZE);
7222 	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7223 			   BTRFS_FSID_SIZE);
7224 	args.uuid = dev_uuid;
7225 	args.fsid = fs_uuid;
7226 
7227 	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7228 		fs_devices = open_seed_devices(fs_info, fs_uuid);
7229 		if (IS_ERR(fs_devices))
7230 			return PTR_ERR(fs_devices);
7231 	}
7232 
7233 	device = btrfs_find_device(fs_info->fs_devices, &args);
7234 	if (!device) {
7235 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7236 			btrfs_report_missing_device(fs_info, devid,
7237 							dev_uuid, true);
7238 			return -ENOENT;
7239 		}
7240 
7241 		device = add_missing_dev(fs_devices, devid, dev_uuid);
7242 		if (IS_ERR(device)) {
7243 			btrfs_err(fs_info,
7244 				"failed to add missing dev %llu: %ld",
7245 				devid, PTR_ERR(device));
7246 			return PTR_ERR(device);
7247 		}
7248 		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7249 	} else {
7250 		if (!device->bdev) {
7251 			if (!btrfs_test_opt(fs_info, DEGRADED)) {
7252 				btrfs_report_missing_device(fs_info,
7253 						devid, dev_uuid, true);
7254 				return -ENOENT;
7255 			}
7256 			btrfs_report_missing_device(fs_info, devid,
7257 							dev_uuid, false);
7258 		}
7259 
7260 		if (!device->bdev &&
7261 		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7262 			/*
7263 			 * this happens when a device that was properly setup
7264 			 * in the device info lists suddenly goes bad.
7265 			 * device->bdev is NULL, and so we have to set
7266 			 * device->missing to one here
7267 			 */
7268 			device->fs_devices->missing_devices++;
7269 			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7270 		}
7271 
7272 		/* Move the device to its own fs_devices */
7273 		if (device->fs_devices != fs_devices) {
7274 			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7275 							&device->dev_state));
7276 
7277 			list_move(&device->dev_list, &fs_devices->devices);
7278 			device->fs_devices->num_devices--;
7279 			fs_devices->num_devices++;
7280 
7281 			device->fs_devices->missing_devices--;
7282 			fs_devices->missing_devices++;
7283 
7284 			device->fs_devices = fs_devices;
7285 		}
7286 	}
7287 
7288 	if (device->fs_devices != fs_info->fs_devices) {
7289 		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7290 		if (device->generation !=
7291 		    btrfs_device_generation(leaf, dev_item))
7292 			return -EINVAL;
7293 	}
7294 
7295 	fill_device_from_item(leaf, dev_item, device);
7296 	if (device->bdev) {
7297 		u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7298 
7299 		if (device->total_bytes > max_total_bytes) {
7300 			btrfs_err(fs_info,
7301 			"device total_bytes should be at most %llu but found %llu",
7302 				  max_total_bytes, device->total_bytes);
7303 			return -EINVAL;
7304 		}
7305 	}
7306 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7307 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7308 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7309 		device->fs_devices->total_rw_bytes += device->total_bytes;
7310 		atomic64_add(device->total_bytes - device->bytes_used,
7311 				&fs_info->free_chunk_space);
7312 	}
7313 	ret = 0;
7314 	return ret;
7315 }
7316 
btrfs_read_sys_array(struct btrfs_fs_info * fs_info)7317 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7318 {
7319 	struct btrfs_super_block *super_copy = fs_info->super_copy;
7320 	struct extent_buffer *sb;
7321 	u8 *array_ptr;
7322 	unsigned long sb_array_offset;
7323 	int ret = 0;
7324 	u32 array_size;
7325 	u32 cur_offset;
7326 	struct btrfs_key key;
7327 
7328 	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7329 
7330 	/*
7331 	 * We allocated a dummy extent, just to use extent buffer accessors.
7332 	 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7333 	 * that's fine, we will not go beyond system chunk array anyway.
7334 	 */
7335 	sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7336 	if (!sb)
7337 		return -ENOMEM;
7338 	set_extent_buffer_uptodate(sb);
7339 
7340 	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7341 	array_size = btrfs_super_sys_array_size(super_copy);
7342 
7343 	array_ptr = super_copy->sys_chunk_array;
7344 	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7345 	cur_offset = 0;
7346 
7347 	while (cur_offset < array_size) {
7348 		struct btrfs_chunk *chunk;
7349 		struct btrfs_disk_key *disk_key = (struct btrfs_disk_key *)array_ptr;
7350 		u32 len = sizeof(*disk_key);
7351 
7352 		/*
7353 		 * The sys_chunk_array has been already verified at super block
7354 		 * read time.  Only do ASSERT()s for basic checks.
7355 		 */
7356 		ASSERT(cur_offset + len <= array_size);
7357 
7358 		btrfs_disk_key_to_cpu(&key, disk_key);
7359 
7360 		array_ptr += len;
7361 		sb_array_offset += len;
7362 		cur_offset += len;
7363 
7364 		ASSERT(key.type == BTRFS_CHUNK_ITEM_KEY);
7365 
7366 		chunk = (struct btrfs_chunk *)sb_array_offset;
7367 		ASSERT(btrfs_chunk_type(sb, chunk) & BTRFS_BLOCK_GROUP_SYSTEM);
7368 
7369 		len = btrfs_chunk_item_size(btrfs_chunk_num_stripes(sb, chunk));
7370 
7371 		ASSERT(cur_offset + len <= array_size);
7372 
7373 		ret = read_one_chunk(&key, sb, chunk);
7374 		if (ret)
7375 			break;
7376 
7377 		array_ptr += len;
7378 		sb_array_offset += len;
7379 		cur_offset += len;
7380 	}
7381 	clear_extent_buffer_uptodate(sb);
7382 	free_extent_buffer_stale(sb);
7383 	return ret;
7384 }
7385 
7386 /*
7387  * Check if all chunks in the fs are OK for read-write degraded mount
7388  *
7389  * If the @failing_dev is specified, it's accounted as missing.
7390  *
7391  * Return true if all chunks meet the minimal RW mount requirements.
7392  * Return false if any chunk doesn't meet the minimal RW mount requirements.
7393  */
btrfs_check_rw_degradable(struct btrfs_fs_info * fs_info,struct btrfs_device * failing_dev)7394 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7395 					struct btrfs_device *failing_dev)
7396 {
7397 	struct btrfs_chunk_map *map;
7398 	u64 next_start;
7399 	bool ret = true;
7400 
7401 	map = btrfs_find_chunk_map(fs_info, 0, U64_MAX);
7402 	/* No chunk at all? Return false anyway */
7403 	if (!map) {
7404 		ret = false;
7405 		goto out;
7406 	}
7407 	while (map) {
7408 		int missing = 0;
7409 		int max_tolerated;
7410 		int i;
7411 
7412 		max_tolerated =
7413 			btrfs_get_num_tolerated_disk_barrier_failures(
7414 					map->type);
7415 		for (i = 0; i < map->num_stripes; i++) {
7416 			struct btrfs_device *dev = map->stripes[i].dev;
7417 
7418 			if (!dev || !dev->bdev ||
7419 			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7420 			    dev->last_flush_error)
7421 				missing++;
7422 			else if (failing_dev && failing_dev == dev)
7423 				missing++;
7424 		}
7425 		if (missing > max_tolerated) {
7426 			if (!failing_dev)
7427 				btrfs_warn(fs_info,
7428 	"chunk %llu missing %d devices, max tolerance is %d for writable mount",
7429 				   map->start, missing, max_tolerated);
7430 			btrfs_free_chunk_map(map);
7431 			ret = false;
7432 			goto out;
7433 		}
7434 		next_start = map->start + map->chunk_len;
7435 		btrfs_free_chunk_map(map);
7436 
7437 		map = btrfs_find_chunk_map(fs_info, next_start, U64_MAX - next_start);
7438 	}
7439 out:
7440 	return ret;
7441 }
7442 
readahead_tree_node_children(struct extent_buffer * node)7443 static void readahead_tree_node_children(struct extent_buffer *node)
7444 {
7445 	int i;
7446 	const int nr_items = btrfs_header_nritems(node);
7447 
7448 	for (i = 0; i < nr_items; i++)
7449 		btrfs_readahead_node_child(node, i);
7450 }
7451 
btrfs_read_chunk_tree(struct btrfs_fs_info * fs_info)7452 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7453 {
7454 	struct btrfs_root *root = fs_info->chunk_root;
7455 	struct btrfs_path *path;
7456 	struct extent_buffer *leaf;
7457 	struct btrfs_key key;
7458 	struct btrfs_key found_key;
7459 	int ret;
7460 	int slot;
7461 	int iter_ret = 0;
7462 	u64 total_dev = 0;
7463 	u64 last_ra_node = 0;
7464 
7465 	path = btrfs_alloc_path();
7466 	if (!path)
7467 		return -ENOMEM;
7468 
7469 	/*
7470 	 * uuid_mutex is needed only if we are mounting a sprout FS
7471 	 * otherwise we don't need it.
7472 	 */
7473 	mutex_lock(&uuid_mutex);
7474 
7475 	/*
7476 	 * It is possible for mount and umount to race in such a way that
7477 	 * we execute this code path, but open_fs_devices failed to clear
7478 	 * total_rw_bytes. We certainly want it cleared before reading the
7479 	 * device items, so clear it here.
7480 	 */
7481 	fs_info->fs_devices->total_rw_bytes = 0;
7482 
7483 	/*
7484 	 * Lockdep complains about possible circular locking dependency between
7485 	 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7486 	 * used for freeze protection of a fs (struct super_block.s_writers),
7487 	 * which we take when starting a transaction, and extent buffers of the
7488 	 * chunk tree if we call read_one_dev() while holding a lock on an
7489 	 * extent buffer of the chunk tree. Since we are mounting the filesystem
7490 	 * and at this point there can't be any concurrent task modifying the
7491 	 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7492 	 */
7493 	ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7494 	path->skip_locking = 1;
7495 
7496 	/*
7497 	 * Read all device items, and then all the chunk items. All
7498 	 * device items are found before any chunk item (their object id
7499 	 * is smaller than the lowest possible object id for a chunk
7500 	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7501 	 */
7502 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7503 	key.type = 0;
7504 	key.offset = 0;
7505 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7506 		struct extent_buffer *node = path->nodes[1];
7507 
7508 		leaf = path->nodes[0];
7509 		slot = path->slots[0];
7510 
7511 		if (node) {
7512 			if (last_ra_node != node->start) {
7513 				readahead_tree_node_children(node);
7514 				last_ra_node = node->start;
7515 			}
7516 		}
7517 		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7518 			struct btrfs_dev_item *dev_item;
7519 			dev_item = btrfs_item_ptr(leaf, slot,
7520 						  struct btrfs_dev_item);
7521 			ret = read_one_dev(leaf, dev_item);
7522 			if (ret)
7523 				goto error;
7524 			total_dev++;
7525 		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7526 			struct btrfs_chunk *chunk;
7527 
7528 			/*
7529 			 * We are only called at mount time, so no need to take
7530 			 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7531 			 * we always lock first fs_info->chunk_mutex before
7532 			 * acquiring any locks on the chunk tree. This is a
7533 			 * requirement for chunk allocation, see the comment on
7534 			 * top of btrfs_chunk_alloc() for details.
7535 			 */
7536 			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7537 			ret = read_one_chunk(&found_key, leaf, chunk);
7538 			if (ret)
7539 				goto error;
7540 		}
7541 	}
7542 	/* Catch error found during iteration */
7543 	if (iter_ret < 0) {
7544 		ret = iter_ret;
7545 		goto error;
7546 	}
7547 
7548 	/*
7549 	 * After loading chunk tree, we've got all device information,
7550 	 * do another round of validation checks.
7551 	 */
7552 	if (total_dev != fs_info->fs_devices->total_devices) {
7553 		btrfs_warn(fs_info,
7554 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7555 			  btrfs_super_num_devices(fs_info->super_copy),
7556 			  total_dev);
7557 		fs_info->fs_devices->total_devices = total_dev;
7558 		btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7559 	}
7560 	if (btrfs_super_total_bytes(fs_info->super_copy) <
7561 	    fs_info->fs_devices->total_rw_bytes) {
7562 		btrfs_err(fs_info,
7563 	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7564 			  btrfs_super_total_bytes(fs_info->super_copy),
7565 			  fs_info->fs_devices->total_rw_bytes);
7566 		ret = -EINVAL;
7567 		goto error;
7568 	}
7569 	ret = 0;
7570 error:
7571 	mutex_unlock(&uuid_mutex);
7572 
7573 	btrfs_free_path(path);
7574 	return ret;
7575 }
7576 
btrfs_init_devices_late(struct btrfs_fs_info * fs_info)7577 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7578 {
7579 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7580 	struct btrfs_device *device;
7581 	int ret = 0;
7582 
7583 	mutex_lock(&fs_devices->device_list_mutex);
7584 	list_for_each_entry(device, &fs_devices->devices, dev_list)
7585 		device->fs_info = fs_info;
7586 
7587 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7588 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7589 			device->fs_info = fs_info;
7590 			ret = btrfs_get_dev_zone_info(device, false);
7591 			if (ret)
7592 				break;
7593 		}
7594 
7595 		seed_devs->fs_info = fs_info;
7596 	}
7597 	mutex_unlock(&fs_devices->device_list_mutex);
7598 
7599 	return ret;
7600 }
7601 
btrfs_dev_stats_value(const struct extent_buffer * eb,const struct btrfs_dev_stats_item * ptr,int index)7602 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7603 				 const struct btrfs_dev_stats_item *ptr,
7604 				 int index)
7605 {
7606 	u64 val;
7607 
7608 	read_extent_buffer(eb, &val,
7609 			   offsetof(struct btrfs_dev_stats_item, values) +
7610 			    ((unsigned long)ptr) + (index * sizeof(u64)),
7611 			   sizeof(val));
7612 	return val;
7613 }
7614 
btrfs_set_dev_stats_value(struct extent_buffer * eb,struct btrfs_dev_stats_item * ptr,int index,u64 val)7615 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7616 				      struct btrfs_dev_stats_item *ptr,
7617 				      int index, u64 val)
7618 {
7619 	write_extent_buffer(eb, &val,
7620 			    offsetof(struct btrfs_dev_stats_item, values) +
7621 			     ((unsigned long)ptr) + (index * sizeof(u64)),
7622 			    sizeof(val));
7623 }
7624 
btrfs_device_init_dev_stats(struct btrfs_device * device,struct btrfs_path * path)7625 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7626 				       struct btrfs_path *path)
7627 {
7628 	struct btrfs_dev_stats_item *ptr;
7629 	struct extent_buffer *eb;
7630 	struct btrfs_key key;
7631 	int item_size;
7632 	int i, ret, slot;
7633 
7634 	if (!device->fs_info->dev_root)
7635 		return 0;
7636 
7637 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7638 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7639 	key.offset = device->devid;
7640 	ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7641 	if (ret) {
7642 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7643 			btrfs_dev_stat_set(device, i, 0);
7644 		device->dev_stats_valid = 1;
7645 		btrfs_release_path(path);
7646 		return ret < 0 ? ret : 0;
7647 	}
7648 	slot = path->slots[0];
7649 	eb = path->nodes[0];
7650 	item_size = btrfs_item_size(eb, slot);
7651 
7652 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7653 
7654 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7655 		if (item_size >= (1 + i) * sizeof(__le64))
7656 			btrfs_dev_stat_set(device, i,
7657 					   btrfs_dev_stats_value(eb, ptr, i));
7658 		else
7659 			btrfs_dev_stat_set(device, i, 0);
7660 	}
7661 
7662 	device->dev_stats_valid = 1;
7663 	btrfs_dev_stat_print_on_load(device);
7664 	btrfs_release_path(path);
7665 
7666 	return 0;
7667 }
7668 
btrfs_init_dev_stats(struct btrfs_fs_info * fs_info)7669 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7670 {
7671 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7672 	struct btrfs_device *device;
7673 	struct btrfs_path *path = NULL;
7674 	int ret = 0;
7675 
7676 	path = btrfs_alloc_path();
7677 	if (!path)
7678 		return -ENOMEM;
7679 
7680 	mutex_lock(&fs_devices->device_list_mutex);
7681 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7682 		ret = btrfs_device_init_dev_stats(device, path);
7683 		if (ret)
7684 			goto out;
7685 	}
7686 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7687 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7688 			ret = btrfs_device_init_dev_stats(device, path);
7689 			if (ret)
7690 				goto out;
7691 		}
7692 	}
7693 out:
7694 	mutex_unlock(&fs_devices->device_list_mutex);
7695 
7696 	btrfs_free_path(path);
7697 	return ret;
7698 }
7699 
update_dev_stat_item(struct btrfs_trans_handle * trans,struct btrfs_device * device)7700 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7701 				struct btrfs_device *device)
7702 {
7703 	struct btrfs_fs_info *fs_info = trans->fs_info;
7704 	struct btrfs_root *dev_root = fs_info->dev_root;
7705 	struct btrfs_path *path;
7706 	struct btrfs_key key;
7707 	struct extent_buffer *eb;
7708 	struct btrfs_dev_stats_item *ptr;
7709 	int ret;
7710 	int i;
7711 
7712 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7713 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7714 	key.offset = device->devid;
7715 
7716 	path = btrfs_alloc_path();
7717 	if (!path)
7718 		return -ENOMEM;
7719 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7720 	if (ret < 0) {
7721 		btrfs_warn(fs_info,
7722 			"error %d while searching for dev_stats item for device %s",
7723 				  ret, btrfs_dev_name(device));
7724 		goto out;
7725 	}
7726 
7727 	if (ret == 0 &&
7728 	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7729 		/* need to delete old one and insert a new one */
7730 		ret = btrfs_del_item(trans, dev_root, path);
7731 		if (ret != 0) {
7732 			btrfs_warn(fs_info,
7733 				"delete too small dev_stats item for device %s failed %d",
7734 					  btrfs_dev_name(device), ret);
7735 			goto out;
7736 		}
7737 		ret = 1;
7738 	}
7739 
7740 	if (ret == 1) {
7741 		/* need to insert a new item */
7742 		btrfs_release_path(path);
7743 		ret = btrfs_insert_empty_item(trans, dev_root, path,
7744 					      &key, sizeof(*ptr));
7745 		if (ret < 0) {
7746 			btrfs_warn(fs_info,
7747 				"insert dev_stats item for device %s failed %d",
7748 				btrfs_dev_name(device), ret);
7749 			goto out;
7750 		}
7751 	}
7752 
7753 	eb = path->nodes[0];
7754 	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7755 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7756 		btrfs_set_dev_stats_value(eb, ptr, i,
7757 					  btrfs_dev_stat_read(device, i));
7758 out:
7759 	btrfs_free_path(path);
7760 	return ret;
7761 }
7762 
7763 /*
7764  * called from commit_transaction. Writes all changed device stats to disk.
7765  */
btrfs_run_dev_stats(struct btrfs_trans_handle * trans)7766 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7767 {
7768 	struct btrfs_fs_info *fs_info = trans->fs_info;
7769 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7770 	struct btrfs_device *device;
7771 	int stats_cnt;
7772 	int ret = 0;
7773 
7774 	mutex_lock(&fs_devices->device_list_mutex);
7775 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7776 		stats_cnt = atomic_read(&device->dev_stats_ccnt);
7777 		if (!device->dev_stats_valid || stats_cnt == 0)
7778 			continue;
7779 
7780 
7781 		/*
7782 		 * There is a LOAD-LOAD control dependency between the value of
7783 		 * dev_stats_ccnt and updating the on-disk values which requires
7784 		 * reading the in-memory counters. Such control dependencies
7785 		 * require explicit read memory barriers.
7786 		 *
7787 		 * This memory barriers pairs with smp_mb__before_atomic in
7788 		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7789 		 * barrier implied by atomic_xchg in
7790 		 * btrfs_dev_stats_read_and_reset
7791 		 */
7792 		smp_rmb();
7793 
7794 		ret = update_dev_stat_item(trans, device);
7795 		if (!ret)
7796 			atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7797 	}
7798 	mutex_unlock(&fs_devices->device_list_mutex);
7799 
7800 	return ret;
7801 }
7802 
btrfs_dev_stat_inc_and_print(struct btrfs_device * dev,int index)7803 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7804 {
7805 	btrfs_dev_stat_inc(dev, index);
7806 
7807 	if (!dev->dev_stats_valid)
7808 		return;
7809 	btrfs_err_rl(dev->fs_info,
7810 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7811 			   btrfs_dev_name(dev),
7812 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7813 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7814 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7815 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7816 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7817 }
7818 
btrfs_dev_stat_print_on_load(struct btrfs_device * dev)7819 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7820 {
7821 	int i;
7822 
7823 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7824 		if (btrfs_dev_stat_read(dev, i) != 0)
7825 			break;
7826 	if (i == BTRFS_DEV_STAT_VALUES_MAX)
7827 		return; /* all values == 0, suppress message */
7828 
7829 	btrfs_info(dev->fs_info,
7830 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7831 	       btrfs_dev_name(dev),
7832 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7833 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7834 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7835 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7836 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7837 }
7838 
btrfs_get_dev_stats(struct btrfs_fs_info * fs_info,struct btrfs_ioctl_get_dev_stats * stats)7839 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7840 			struct btrfs_ioctl_get_dev_stats *stats)
7841 {
7842 	BTRFS_DEV_LOOKUP_ARGS(args);
7843 	struct btrfs_device *dev;
7844 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7845 	int i;
7846 
7847 	mutex_lock(&fs_devices->device_list_mutex);
7848 	args.devid = stats->devid;
7849 	dev = btrfs_find_device(fs_info->fs_devices, &args);
7850 	mutex_unlock(&fs_devices->device_list_mutex);
7851 
7852 	if (!dev) {
7853 		btrfs_warn(fs_info, "get dev_stats failed, device not found");
7854 		return -ENODEV;
7855 	} else if (!dev->dev_stats_valid) {
7856 		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7857 		return -ENODEV;
7858 	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7859 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7860 			if (stats->nr_items > i)
7861 				stats->values[i] =
7862 					btrfs_dev_stat_read_and_reset(dev, i);
7863 			else
7864 				btrfs_dev_stat_set(dev, i, 0);
7865 		}
7866 		btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7867 			   current->comm, task_pid_nr(current));
7868 	} else {
7869 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7870 			if (stats->nr_items > i)
7871 				stats->values[i] = btrfs_dev_stat_read(dev, i);
7872 	}
7873 	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7874 		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7875 	return 0;
7876 }
7877 
7878 /*
7879  * Update the size and bytes used for each device where it changed.  This is
7880  * delayed since we would otherwise get errors while writing out the
7881  * superblocks.
7882  *
7883  * Must be invoked during transaction commit.
7884  */
btrfs_commit_device_sizes(struct btrfs_transaction * trans)7885 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7886 {
7887 	struct btrfs_device *curr, *next;
7888 
7889 	ASSERT(trans->state == TRANS_STATE_COMMIT_DOING, "state=%d" , trans->state);
7890 
7891 	if (list_empty(&trans->dev_update_list))
7892 		return;
7893 
7894 	/*
7895 	 * We don't need the device_list_mutex here.  This list is owned by the
7896 	 * transaction and the transaction must complete before the device is
7897 	 * released.
7898 	 */
7899 	mutex_lock(&trans->fs_info->chunk_mutex);
7900 	list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7901 				 post_commit_list) {
7902 		list_del_init(&curr->post_commit_list);
7903 		curr->commit_total_bytes = curr->disk_total_bytes;
7904 		curr->commit_bytes_used = curr->bytes_used;
7905 	}
7906 	mutex_unlock(&trans->fs_info->chunk_mutex);
7907 }
7908 
7909 /*
7910  * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7911  */
btrfs_bg_type_to_factor(u64 flags)7912 int btrfs_bg_type_to_factor(u64 flags)
7913 {
7914 	const int index = btrfs_bg_flags_to_raid_index(flags);
7915 
7916 	return btrfs_raid_array[index].ncopies;
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 (unlikely(!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 (unlikely(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 (unlikely(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 (unlikely(!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 (unlikely(!dev)) {
7985 		btrfs_err(fs_info, "failed to find devid %llu", devid);
7986 		ret = -EUCLEAN;
7987 		goto out;
7988 	}
7989 
7990 	if (unlikely(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 (unlikely(!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 (unlikely(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 (unlikely(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 (unlikely(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 	guard(super_write)(fs_info->sb);
8178 
8179 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8180 		btrfs_info(fs_info,
8181 			   "zoned: skip relocating block group %llu to repair: EBUSY",
8182 			   target);
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 
8211 	return ret;
8212 }
8213 
btrfs_repair_one_zone(struct btrfs_fs_info * fs_info,u64 logical)8214 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8215 {
8216 	struct btrfs_block_group *cache;
8217 
8218 	if (!btrfs_is_zoned(fs_info))
8219 		return false;
8220 
8221 	/* Do not attempt to repair in degraded state */
8222 	if (btrfs_test_opt(fs_info, DEGRADED))
8223 		return true;
8224 
8225 	cache = btrfs_lookup_block_group(fs_info, logical);
8226 	if (!cache)
8227 		return true;
8228 
8229 	if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8230 		btrfs_put_block_group(cache);
8231 		return true;
8232 	}
8233 
8234 	kthread_run(relocating_repair_kthread, cache,
8235 		    "btrfs-relocating-repair");
8236 
8237 	return true;
8238 }
8239 
map_raid56_repair_block(struct btrfs_io_context * bioc,struct btrfs_io_stripe * smap,u64 logical)8240 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8241 				    struct btrfs_io_stripe *smap,
8242 				    u64 logical)
8243 {
8244 	int data_stripes = nr_bioc_data_stripes(bioc);
8245 	int i;
8246 
8247 	for (i = 0; i < data_stripes; i++) {
8248 		u64 stripe_start = bioc->full_stripe_logical +
8249 				   btrfs_stripe_nr_to_offset(i);
8250 
8251 		if (logical >= stripe_start &&
8252 		    logical < stripe_start + BTRFS_STRIPE_LEN)
8253 			break;
8254 	}
8255 	ASSERT(i < data_stripes, "i=%d data_stripes=%d", i, data_stripes);
8256 	smap->dev = bioc->stripes[i].dev;
8257 	smap->physical = bioc->stripes[i].physical +
8258 			((logical - bioc->full_stripe_logical) &
8259 			 BTRFS_STRIPE_LEN_MASK);
8260 }
8261 
8262 /*
8263  * Map a repair write into a single device.
8264  *
8265  * A repair write is triggered by read time repair or scrub, which would only
8266  * update the contents of a single device.
8267  * Not update any other mirrors nor go through RMW path.
8268  *
8269  * Callers should ensure:
8270  *
8271  * - Call btrfs_bio_counter_inc_blocked() first
8272  * - The range does not cross stripe boundary
8273  * - Has a valid @mirror_num passed in.
8274  */
btrfs_map_repair_block(struct btrfs_fs_info * fs_info,struct btrfs_io_stripe * smap,u64 logical,u32 length,int mirror_num)8275 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8276 			   struct btrfs_io_stripe *smap, u64 logical,
8277 			   u32 length, int mirror_num)
8278 {
8279 	struct btrfs_io_context *bioc = NULL;
8280 	u64 map_length = length;
8281 	int mirror_ret = mirror_num;
8282 	int ret;
8283 
8284 	ASSERT(mirror_num > 0, "mirror_num=%d", mirror_num);
8285 
8286 	ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8287 			      &bioc, smap, &mirror_ret);
8288 	if (ret < 0)
8289 		return ret;
8290 
8291 	/* The map range should not cross stripe boundary. */
8292 	ASSERT(map_length >= length, "map_length=%llu length=%u", map_length, length);
8293 
8294 	/* Already mapped to single stripe. */
8295 	if (!bioc)
8296 		goto out;
8297 
8298 	/* Map the RAID56 multi-stripe writes to a single one. */
8299 	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8300 		map_raid56_repair_block(bioc, smap, logical);
8301 		goto out;
8302 	}
8303 
8304 	ASSERT(mirror_num <= bioc->num_stripes,
8305 	       "mirror_num=%d num_stripes=%d", mirror_num,  bioc->num_stripes);
8306 	smap->dev = bioc->stripes[mirror_num - 1].dev;
8307 	smap->physical = bioc->stripes[mirror_num - 1].physical;
8308 out:
8309 	btrfs_put_bioc(bioc);
8310 	ASSERT(smap->dev);
8311 	return 0;
8312 }
8313