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