xref: /linux/fs/btrfs/volumes.c (revision bf4afc53b77aeaa48b5409da5c8da6bb4eff7f43)
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, true);
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 
4281 		rci = list_first_entry(chunks, struct remap_chunk_info, list);
4282 
4283 		spin_lock(&rci->bg->lock);
4284 		is_unused = !btrfs_is_block_group_used(rci->bg);
4285 		spin_unlock(&rci->bg->lock);
4286 
4287 		if (is_unused)
4288 			btrfs_mark_bg_unused(rci->bg);
4289 
4290 		if (rci->made_ro)
4291 			btrfs_dec_block_group_ro(rci->bg);
4292 
4293 		btrfs_put_block_group(rci->bg);
4294 
4295 		list_del(&rci->list);
4296 		kfree(rci);
4297 	}
4298 
4299 	return ret;
4300 }
4301 
__btrfs_balance(struct btrfs_fs_info * fs_info)4302 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
4303 {
4304 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4305 	struct btrfs_root *chunk_root = fs_info->chunk_root;
4306 	u64 chunk_type;
4307 	struct btrfs_chunk *chunk;
4308 	BTRFS_PATH_AUTO_FREE(path);
4309 	struct btrfs_key key;
4310 	struct btrfs_key found_key;
4311 	struct extent_buffer *leaf;
4312 	int slot;
4313 	int ret;
4314 	int enospc_errors = 0;
4315 	bool counting = true;
4316 	/* The single value limit and min/max limits use the same bytes in the */
4317 	u64 limit_data = bctl->data.limit;
4318 	u64 limit_meta = bctl->meta.limit;
4319 	u64 limit_sys = bctl->sys.limit;
4320 	u32 count_data = 0;
4321 	u32 count_meta = 0;
4322 	u32 count_sys = 0;
4323 	int chunk_reserved = 0;
4324 	struct remap_chunk_info *rci;
4325 	unsigned int num_remap_chunks = 0;
4326 	LIST_HEAD(remap_chunks);
4327 
4328 	path = btrfs_alloc_path();
4329 	if (!path) {
4330 		ret = -ENOMEM;
4331 		goto error;
4332 	}
4333 
4334 	/* zero out stat counters */
4335 	spin_lock(&fs_info->balance_lock);
4336 	memset(&bctl->stat, 0, sizeof(bctl->stat));
4337 	spin_unlock(&fs_info->balance_lock);
4338 again:
4339 	if (!counting) {
4340 		/*
4341 		 * The single value limit and min/max limits use the same bytes
4342 		 * in the
4343 		 */
4344 		bctl->data.limit = limit_data;
4345 		bctl->meta.limit = limit_meta;
4346 		bctl->sys.limit = limit_sys;
4347 	}
4348 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4349 	key.type = BTRFS_CHUNK_ITEM_KEY;
4350 	key.offset = (u64)-1;
4351 
4352 	while (1) {
4353 		if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
4354 		    atomic_read(&fs_info->balance_cancel_req)) {
4355 			ret = -ECANCELED;
4356 			goto error;
4357 		}
4358 
4359 		mutex_lock(&fs_info->reclaim_bgs_lock);
4360 		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
4361 		if (ret < 0) {
4362 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4363 			goto error;
4364 		}
4365 
4366 		/*
4367 		 * this shouldn't happen, it means the last relocate
4368 		 * failed
4369 		 */
4370 		if (unlikely(ret == 0)) {
4371 			btrfs_err(fs_info,
4372 				  "unexpected exact match of CHUNK_ITEM in chunk tree, offset 0x%llx",
4373 				  key.offset);
4374 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4375 			ret = -EUCLEAN;
4376 			goto error;
4377 		}
4378 
4379 		ret = btrfs_previous_item(chunk_root, path, 0,
4380 					  BTRFS_CHUNK_ITEM_KEY);
4381 		if (ret) {
4382 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4383 			ret = 0;
4384 			break;
4385 		}
4386 
4387 		leaf = path->nodes[0];
4388 		slot = path->slots[0];
4389 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4390 
4391 		if (found_key.objectid != key.objectid) {
4392 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4393 			break;
4394 		}
4395 
4396 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4397 		chunk_type = btrfs_chunk_type(leaf, chunk);
4398 
4399 		/* Check if chunk has already been fully relocated. */
4400 		if (chunk_type & BTRFS_BLOCK_GROUP_REMAPPED &&
4401 		    btrfs_chunk_num_stripes(leaf, chunk) == 0) {
4402 			btrfs_release_path(path);
4403 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4404 			goto loop;
4405 		}
4406 
4407 		if (!counting) {
4408 			spin_lock(&fs_info->balance_lock);
4409 			bctl->stat.considered++;
4410 			spin_unlock(&fs_info->balance_lock);
4411 		}
4412 
4413 		ret = should_balance_chunk(leaf, chunk, found_key.offset);
4414 
4415 		btrfs_release_path(path);
4416 		if (!ret) {
4417 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4418 			goto loop;
4419 		}
4420 
4421 		if (counting) {
4422 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4423 			spin_lock(&fs_info->balance_lock);
4424 			bctl->stat.expected++;
4425 			spin_unlock(&fs_info->balance_lock);
4426 
4427 			if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4428 				count_data++;
4429 			else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4430 				count_sys++;
4431 			else if (chunk_type & (BTRFS_BLOCK_GROUP_METADATA |
4432 					       BTRFS_BLOCK_GROUP_METADATA_REMAP))
4433 				count_meta++;
4434 
4435 			goto loop;
4436 		}
4437 
4438 		/*
4439 		 * Apply limit_min filter, no need to check if the LIMITS
4440 		 * filter is used, limit_min is 0 by default
4441 		 */
4442 		if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4443 					count_data < bctl->data.limit_min)
4444 				|| ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4445 					count_meta < bctl->meta.limit_min)
4446 				|| ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4447 					count_sys < bctl->sys.limit_min)) {
4448 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4449 			goto loop;
4450 		}
4451 
4452 		/*
4453 		 * Balancing METADATA_REMAP chunks takes place separately - add
4454 		 * the details to a list so it can be processed later.
4455 		 */
4456 		if (chunk_type & BTRFS_BLOCK_GROUP_METADATA_REMAP) {
4457 			mutex_unlock(&fs_info->reclaim_bgs_lock);
4458 
4459 			rci = kmalloc_obj(struct remap_chunk_info, GFP_NOFS);
4460 			if (!rci) {
4461 				ret = -ENOMEM;
4462 				goto error;
4463 			}
4464 
4465 			rci->offset = found_key.offset;
4466 			rci->bg = NULL;
4467 			rci->made_ro = false;
4468 			list_add_tail(&rci->list, &remap_chunks);
4469 
4470 			num_remap_chunks++;
4471 
4472 			goto loop;
4473 		}
4474 
4475 		if (!chunk_reserved) {
4476 			/*
4477 			 * We may be relocating the only data chunk we have,
4478 			 * which could potentially end up with losing data's
4479 			 * raid profile, so lets allocate an empty one in
4480 			 * advance.
4481 			 */
4482 			ret = btrfs_may_alloc_data_chunk(fs_info,
4483 							 found_key.offset);
4484 			if (ret < 0) {
4485 				mutex_unlock(&fs_info->reclaim_bgs_lock);
4486 				goto error;
4487 			} else if (ret == 1) {
4488 				chunk_reserved = 1;
4489 			}
4490 		}
4491 
4492 		ret = btrfs_relocate_chunk(fs_info, found_key.offset, true);
4493 		mutex_unlock(&fs_info->reclaim_bgs_lock);
4494 		if (ret == -ENOSPC) {
4495 			enospc_errors++;
4496 		} else if (ret == -ETXTBSY) {
4497 			btrfs_info(fs_info,
4498 	   "skipping relocation of block group %llu due to active swapfile",
4499 				   found_key.offset);
4500 			ret = 0;
4501 		} else if (ret) {
4502 			goto error;
4503 		} else {
4504 			spin_lock(&fs_info->balance_lock);
4505 			bctl->stat.completed++;
4506 			spin_unlock(&fs_info->balance_lock);
4507 		}
4508 loop:
4509 		if (found_key.offset == 0)
4510 			break;
4511 		key.offset = found_key.offset - 1;
4512 	}
4513 
4514 	btrfs_release_path(path);
4515 
4516 	if (counting) {
4517 		counting = false;
4518 		goto again;
4519 	}
4520 
4521 	if (!list_empty(&remap_chunks)) {
4522 		ret = balance_remap_chunks(fs_info, path, &remap_chunks);
4523 		if (ret == -ENOSPC)
4524 			enospc_errors++;
4525 
4526 		if (!ret) {
4527 			spin_lock(&fs_info->balance_lock);
4528 			bctl->stat.completed += num_remap_chunks;
4529 			spin_unlock(&fs_info->balance_lock);
4530 		}
4531 	}
4532 error:
4533 	if (enospc_errors) {
4534 		btrfs_info(fs_info, "%d enospc errors during balance",
4535 			   enospc_errors);
4536 		if (!ret)
4537 			ret = -ENOSPC;
4538 	}
4539 
4540 	return ret;
4541 }
4542 
4543 /*
4544  * See if a given profile is valid and reduced.
4545  *
4546  * @flags:     profile to validate
4547  * @extended:  if true @flags is treated as an extended profile
4548  */
alloc_profile_is_valid(u64 flags,bool extended)4549 static int alloc_profile_is_valid(u64 flags, bool extended)
4550 {
4551 	u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4552 			       BTRFS_BLOCK_GROUP_PROFILE_MASK);
4553 
4554 	flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4555 
4556 	/* 1) check that all other bits are zeroed */
4557 	if (flags & ~mask)
4558 		return 0;
4559 
4560 	/* 2) see if profile is reduced */
4561 	if (flags == 0)
4562 		return !extended; /* "0" is valid for usual profiles */
4563 
4564 	return has_single_bit_set(flags);
4565 }
4566 
4567 /*
4568  * Validate target profile against allowed profiles and return true if it's OK.
4569  * Otherwise print the error message and return false.
4570  */
validate_convert_profile(struct btrfs_fs_info * fs_info,const struct btrfs_balance_args * bargs,u64 allowed,const char * type)4571 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4572 		const struct btrfs_balance_args *bargs,
4573 		u64 allowed, const char *type)
4574 {
4575 	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4576 		return true;
4577 
4578 	/* Profile is valid and does not have bits outside of the allowed set */
4579 	if (alloc_profile_is_valid(bargs->target, 1) &&
4580 	    (bargs->target & ~allowed) == 0)
4581 		return true;
4582 
4583 	btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4584 			type, btrfs_bg_type_to_raid_name(bargs->target));
4585 	return false;
4586 }
4587 
4588 /*
4589  * Fill @buf with textual description of balance filter flags @bargs, up to
4590  * @size_buf including the terminating null. The output may be trimmed if it
4591  * does not fit into the provided buffer.
4592  */
describe_balance_args(struct btrfs_balance_args * bargs,char * buf,u32 size_buf)4593 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4594 				 u32 size_buf)
4595 {
4596 	int ret;
4597 	u32 size_bp = size_buf;
4598 	char *bp = buf;
4599 	u64 flags = bargs->flags;
4600 	char tmp_buf[128] = {'\0'};
4601 
4602 	if (!flags)
4603 		return;
4604 
4605 #define CHECK_APPEND_NOARG(a)						\
4606 	do {								\
4607 		ret = snprintf(bp, size_bp, (a));			\
4608 		if (ret < 0 || ret >= size_bp)				\
4609 			goto out_overflow;				\
4610 		size_bp -= ret;						\
4611 		bp += ret;						\
4612 	} while (0)
4613 
4614 #define CHECK_APPEND_1ARG(a, v1)					\
4615 	do {								\
4616 		ret = snprintf(bp, size_bp, (a), (v1));			\
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_2ARG(a, v1, v2)					\
4624 	do {								\
4625 		ret = snprintf(bp, size_bp, (a), (v1), (v2));		\
4626 		if (ret < 0 || ret >= size_bp)				\
4627 			goto out_overflow;				\
4628 		size_bp -= ret;						\
4629 		bp += ret;						\
4630 	} while (0)
4631 
4632 	if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4633 		CHECK_APPEND_1ARG("convert=%s,",
4634 				  btrfs_bg_type_to_raid_name(bargs->target));
4635 
4636 	if (flags & BTRFS_BALANCE_ARGS_SOFT)
4637 		CHECK_APPEND_NOARG("soft,");
4638 
4639 	if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4640 		btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4641 					    sizeof(tmp_buf));
4642 		CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4643 	}
4644 
4645 	if (flags & BTRFS_BALANCE_ARGS_USAGE)
4646 		CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4647 
4648 	if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4649 		CHECK_APPEND_2ARG("usage=%u..%u,",
4650 				  bargs->usage_min, bargs->usage_max);
4651 
4652 	if (flags & BTRFS_BALANCE_ARGS_DEVID)
4653 		CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4654 
4655 	if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4656 		CHECK_APPEND_2ARG("drange=%llu..%llu,",
4657 				  bargs->pstart, bargs->pend);
4658 
4659 	if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4660 		CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4661 				  bargs->vstart, bargs->vend);
4662 
4663 	if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4664 		CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4665 
4666 	if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4667 		CHECK_APPEND_2ARG("limit=%u..%u,",
4668 				bargs->limit_min, bargs->limit_max);
4669 
4670 	if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4671 		CHECK_APPEND_2ARG("stripes=%u..%u,",
4672 				  bargs->stripes_min, bargs->stripes_max);
4673 
4674 #undef CHECK_APPEND_2ARG
4675 #undef CHECK_APPEND_1ARG
4676 #undef CHECK_APPEND_NOARG
4677 
4678 out_overflow:
4679 
4680 	if (size_bp < size_buf)
4681 		buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4682 	else
4683 		buf[0] = '\0';
4684 }
4685 
describe_balance_start_or_resume(struct btrfs_fs_info * fs_info)4686 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4687 {
4688 	u32 size_buf = 1024;
4689 	char tmp_buf[192] = {'\0'};
4690 	char AUTO_KFREE(buf);
4691 	char *bp;
4692 	u32 size_bp = size_buf;
4693 	int ret;
4694 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4695 
4696 	buf = kzalloc(size_buf, GFP_KERNEL);
4697 	if (!buf)
4698 		return;
4699 
4700 	bp = buf;
4701 
4702 #define CHECK_APPEND_1ARG(a, v1)					\
4703 	do {								\
4704 		ret = snprintf(bp, size_bp, (a), (v1));			\
4705 		if (ret < 0 || ret >= size_bp)				\
4706 			goto out_overflow;				\
4707 		size_bp -= ret;						\
4708 		bp += ret;						\
4709 	} while (0)
4710 
4711 	if (bctl->flags & BTRFS_BALANCE_FORCE)
4712 		CHECK_APPEND_1ARG("%s", "-f ");
4713 
4714 	if (bctl->flags & BTRFS_BALANCE_DATA) {
4715 		describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4716 		CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4717 	}
4718 
4719 	if (bctl->flags & BTRFS_BALANCE_METADATA) {
4720 		describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4721 		CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4722 	}
4723 
4724 	if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4725 		describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4726 		CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4727 	}
4728 
4729 #undef CHECK_APPEND_1ARG
4730 
4731 out_overflow:
4732 
4733 	if (size_bp < size_buf)
4734 		buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4735 	btrfs_info(fs_info, "balance: %s %s",
4736 		   (bctl->flags & BTRFS_BALANCE_RESUME) ?
4737 		   "resume" : "start", buf);
4738 }
4739 
4740 /*
4741  * Should be called with balance mutex held
4742  */
btrfs_balance(struct btrfs_fs_info * fs_info,struct btrfs_balance_control * bctl,struct btrfs_ioctl_balance_args * bargs)4743 int btrfs_balance(struct btrfs_fs_info *fs_info,
4744 		  struct btrfs_balance_control *bctl,
4745 		  struct btrfs_ioctl_balance_args *bargs)
4746 {
4747 	u64 meta_target, data_target;
4748 	u64 allowed;
4749 	int mixed = 0;
4750 	int ret;
4751 	u64 num_devices;
4752 	unsigned seq;
4753 	bool reducing_redundancy;
4754 	bool paused = false;
4755 	int i;
4756 
4757 	if (btrfs_fs_closing(fs_info) ||
4758 	    atomic_read(&fs_info->balance_pause_req) ||
4759 	    btrfs_should_cancel_balance(fs_info)) {
4760 		ret = -EINVAL;
4761 		goto out;
4762 	}
4763 
4764 	allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4765 	if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4766 		mixed = 1;
4767 
4768 	/*
4769 	 * In case of mixed groups both data and meta should be picked,
4770 	 * and identical options should be given for both of them.
4771 	 */
4772 	allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4773 	if (mixed && (bctl->flags & allowed)) {
4774 		if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4775 		    !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4776 		    memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4777 			btrfs_err(fs_info,
4778 	  "balance: mixed groups data and metadata options must be the same");
4779 			ret = -EINVAL;
4780 			goto out;
4781 		}
4782 	}
4783 
4784 	/*
4785 	 * rw_devices will not change at the moment, device add/delete/replace
4786 	 * are exclusive
4787 	 */
4788 	num_devices = fs_info->fs_devices->rw_devices;
4789 
4790 	/*
4791 	 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4792 	 * special bit for it, to make it easier to distinguish.  Thus we need
4793 	 * to set it manually, or balance would refuse the profile.
4794 	 */
4795 	allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4796 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4797 		if (num_devices >= btrfs_raid_array[i].devs_min)
4798 			allowed |= btrfs_raid_array[i].bg_flag;
4799 
4800 	if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4801 	    !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4802 	    !validate_convert_profile(fs_info, &bctl->sys,  allowed, "system")) {
4803 		ret = -EINVAL;
4804 		goto out;
4805 	}
4806 
4807 	/*
4808 	 * Allow to reduce metadata or system integrity only if force set for
4809 	 * profiles with redundancy (copies, parity)
4810 	 */
4811 	allowed = 0;
4812 	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4813 		if (btrfs_raid_array[i].ncopies >= 2 ||
4814 		    btrfs_raid_array[i].tolerated_failures >= 1)
4815 			allowed |= btrfs_raid_array[i].bg_flag;
4816 	}
4817 	do {
4818 		seq = read_seqbegin(&fs_info->profiles_lock);
4819 
4820 		if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4821 		     (fs_info->avail_system_alloc_bits & allowed) &&
4822 		     !(bctl->sys.target & allowed)) ||
4823 		    ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4824 		     (fs_info->avail_metadata_alloc_bits & allowed) &&
4825 		     !(bctl->meta.target & allowed)))
4826 			reducing_redundancy = true;
4827 		else
4828 			reducing_redundancy = false;
4829 
4830 		/* if we're not converting, the target field is uninitialized */
4831 		meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4832 			bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4833 		data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4834 			bctl->data.target : fs_info->avail_data_alloc_bits;
4835 	} while (read_seqretry(&fs_info->profiles_lock, seq));
4836 
4837 	if (reducing_redundancy) {
4838 		if (bctl->flags & BTRFS_BALANCE_FORCE) {
4839 			btrfs_info(fs_info,
4840 			   "balance: force reducing metadata redundancy");
4841 		} else {
4842 			btrfs_err(fs_info,
4843 	"balance: reduces metadata redundancy, use --force if you want this");
4844 			ret = -EINVAL;
4845 			goto out;
4846 		}
4847 	}
4848 
4849 	if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4850 		btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4851 		btrfs_warn(fs_info,
4852 	"balance: metadata profile %s has lower redundancy than data profile %s",
4853 				btrfs_bg_type_to_raid_name(meta_target),
4854 				btrfs_bg_type_to_raid_name(data_target));
4855 	}
4856 
4857 	ret = insert_balance_item(fs_info, bctl);
4858 	if (ret && ret != -EEXIST)
4859 		goto out;
4860 
4861 	if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4862 		BUG_ON(ret == -EEXIST);
4863 		BUG_ON(fs_info->balance_ctl);
4864 		spin_lock(&fs_info->balance_lock);
4865 		fs_info->balance_ctl = bctl;
4866 		spin_unlock(&fs_info->balance_lock);
4867 	} else {
4868 		BUG_ON(ret != -EEXIST);
4869 		spin_lock(&fs_info->balance_lock);
4870 		update_balance_args(bctl);
4871 		spin_unlock(&fs_info->balance_lock);
4872 	}
4873 
4874 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4875 	set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4876 	describe_balance_start_or_resume(fs_info);
4877 	mutex_unlock(&fs_info->balance_mutex);
4878 
4879 	ret = __btrfs_balance(fs_info);
4880 
4881 	mutex_lock(&fs_info->balance_mutex);
4882 	if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4883 		btrfs_info(fs_info, "balance: paused");
4884 		btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4885 		paused = true;
4886 	}
4887 	/*
4888 	 * Balance can be canceled by:
4889 	 *
4890 	 * - Regular cancel request
4891 	 *   Then ret == -ECANCELED and balance_cancel_req > 0
4892 	 *
4893 	 * - Fatal signal to "btrfs" process
4894 	 *   Either the signal caught by wait_reserve_ticket() and callers
4895 	 *   got -EINTR, or caught by btrfs_should_cancel_balance() and
4896 	 *   got -ECANCELED.
4897 	 *   Either way, in this case balance_cancel_req = 0, and
4898 	 *   ret == -EINTR or ret == -ECANCELED.
4899 	 *
4900 	 * So here we only check the return value to catch canceled balance.
4901 	 */
4902 	else if (ret == -ECANCELED || ret == -EINTR)
4903 		btrfs_info(fs_info, "balance: canceled");
4904 	else
4905 		btrfs_info(fs_info, "balance: ended with status: %d", ret);
4906 
4907 	clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4908 
4909 	if (bargs) {
4910 		memset(bargs, 0, sizeof(*bargs));
4911 		btrfs_update_ioctl_balance_args(fs_info, bargs);
4912 	}
4913 
4914 	/* We didn't pause, we can clean everything up. */
4915 	if (!paused) {
4916 		reset_balance_state(fs_info);
4917 		btrfs_exclop_finish(fs_info);
4918 	}
4919 
4920 	wake_up(&fs_info->balance_wait_q);
4921 
4922 	return ret;
4923 out:
4924 	if (bctl->flags & BTRFS_BALANCE_RESUME)
4925 		reset_balance_state(fs_info);
4926 	else
4927 		kfree(bctl);
4928 	btrfs_exclop_finish(fs_info);
4929 
4930 	return ret;
4931 }
4932 
balance_kthread(void * data)4933 static int balance_kthread(void *data)
4934 {
4935 	struct btrfs_fs_info *fs_info = data;
4936 	int ret = 0;
4937 
4938 	guard(super_write)(fs_info->sb);
4939 
4940 	mutex_lock(&fs_info->balance_mutex);
4941 	if (fs_info->balance_ctl)
4942 		ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4943 	mutex_unlock(&fs_info->balance_mutex);
4944 
4945 	return ret;
4946 }
4947 
btrfs_resume_balance_async(struct btrfs_fs_info * fs_info)4948 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4949 {
4950 	struct task_struct *tsk;
4951 
4952 	mutex_lock(&fs_info->balance_mutex);
4953 	if (!fs_info->balance_ctl) {
4954 		mutex_unlock(&fs_info->balance_mutex);
4955 		return 0;
4956 	}
4957 	mutex_unlock(&fs_info->balance_mutex);
4958 
4959 	if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4960 		btrfs_info(fs_info, "balance: resume skipped");
4961 		return 0;
4962 	}
4963 
4964 	spin_lock(&fs_info->super_lock);
4965 	ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED,
4966 	       "exclusive_operation=%d", fs_info->exclusive_operation);
4967 	fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4968 	spin_unlock(&fs_info->super_lock);
4969 	/*
4970 	 * A ro->rw remount sequence should continue with the paused balance
4971 	 * regardless of who pauses it, system or the user as of now, so set
4972 	 * the resume flag.
4973 	 */
4974 	spin_lock(&fs_info->balance_lock);
4975 	fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4976 	spin_unlock(&fs_info->balance_lock);
4977 
4978 	tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4979 	return PTR_ERR_OR_ZERO(tsk);
4980 }
4981 
btrfs_recover_balance(struct btrfs_fs_info * fs_info)4982 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4983 {
4984 	struct btrfs_balance_control *bctl;
4985 	struct btrfs_balance_item *item;
4986 	struct btrfs_disk_balance_args disk_bargs;
4987 	BTRFS_PATH_AUTO_FREE(path);
4988 	struct extent_buffer *leaf;
4989 	struct btrfs_key key;
4990 	int ret;
4991 
4992 	path = btrfs_alloc_path();
4993 	if (!path)
4994 		return -ENOMEM;
4995 
4996 	key.objectid = BTRFS_BALANCE_OBJECTID;
4997 	key.type = BTRFS_TEMPORARY_ITEM_KEY;
4998 	key.offset = 0;
4999 
5000 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5001 	if (ret < 0)
5002 		return ret;
5003 	if (ret > 0) { /* ret = -ENOENT; */
5004 		return 0;
5005 	}
5006 
5007 	bctl = kzalloc_obj(*bctl, GFP_NOFS);
5008 	if (!bctl)
5009 		return -ENOMEM;
5010 
5011 	leaf = path->nodes[0];
5012 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
5013 
5014 	bctl->flags = btrfs_balance_flags(leaf, item);
5015 	bctl->flags |= BTRFS_BALANCE_RESUME;
5016 
5017 	btrfs_balance_data(leaf, item, &disk_bargs);
5018 	btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
5019 	btrfs_balance_meta(leaf, item, &disk_bargs);
5020 	btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
5021 	btrfs_balance_sys(leaf, item, &disk_bargs);
5022 	btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
5023 
5024 	/*
5025 	 * This should never happen, as the paused balance state is recovered
5026 	 * during mount without any chance of other exclusive ops to collide.
5027 	 *
5028 	 * This gives the exclusive op status to balance and keeps in paused
5029 	 * state until user intervention (cancel or umount). If the ownership
5030 	 * cannot be assigned, show a message but do not fail. The balance
5031 	 * is in a paused state and must have fs_info::balance_ctl properly
5032 	 * set up.
5033 	 */
5034 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
5035 		btrfs_warn(fs_info,
5036 	"balance: cannot set exclusive op status, resume manually");
5037 
5038 	btrfs_release_path(path);
5039 
5040 	mutex_lock(&fs_info->balance_mutex);
5041 	BUG_ON(fs_info->balance_ctl);
5042 	spin_lock(&fs_info->balance_lock);
5043 	fs_info->balance_ctl = bctl;
5044 	spin_unlock(&fs_info->balance_lock);
5045 	mutex_unlock(&fs_info->balance_mutex);
5046 	return ret;
5047 }
5048 
btrfs_pause_balance(struct btrfs_fs_info * fs_info)5049 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
5050 {
5051 	int ret = 0;
5052 
5053 	mutex_lock(&fs_info->balance_mutex);
5054 	if (!fs_info->balance_ctl) {
5055 		mutex_unlock(&fs_info->balance_mutex);
5056 		return -ENOTCONN;
5057 	}
5058 
5059 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5060 		atomic_inc(&fs_info->balance_pause_req);
5061 		mutex_unlock(&fs_info->balance_mutex);
5062 
5063 		wait_event(fs_info->balance_wait_q,
5064 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5065 
5066 		mutex_lock(&fs_info->balance_mutex);
5067 		/* we are good with balance_ctl ripped off from under us */
5068 		BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5069 		atomic_dec(&fs_info->balance_pause_req);
5070 	} else {
5071 		ret = -ENOTCONN;
5072 	}
5073 
5074 	mutex_unlock(&fs_info->balance_mutex);
5075 	return ret;
5076 }
5077 
btrfs_cancel_balance(struct btrfs_fs_info * fs_info)5078 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
5079 {
5080 	mutex_lock(&fs_info->balance_mutex);
5081 	if (!fs_info->balance_ctl) {
5082 		mutex_unlock(&fs_info->balance_mutex);
5083 		return -ENOTCONN;
5084 	}
5085 
5086 	/*
5087 	 * A paused balance with the item stored on disk can be resumed at
5088 	 * mount time if the mount is read-write. Otherwise it's still paused
5089 	 * and we must not allow cancelling as it deletes the item.
5090 	 */
5091 	if (sb_rdonly(fs_info->sb)) {
5092 		mutex_unlock(&fs_info->balance_mutex);
5093 		return -EROFS;
5094 	}
5095 
5096 	atomic_inc(&fs_info->balance_cancel_req);
5097 	/*
5098 	 * if we are running just wait and return, balance item is
5099 	 * deleted in btrfs_balance in this case
5100 	 */
5101 	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5102 		mutex_unlock(&fs_info->balance_mutex);
5103 		wait_event(fs_info->balance_wait_q,
5104 			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5105 		mutex_lock(&fs_info->balance_mutex);
5106 	} else {
5107 		mutex_unlock(&fs_info->balance_mutex);
5108 		/*
5109 		 * Lock released to allow other waiters to continue, we'll
5110 		 * reexamine the status again.
5111 		 */
5112 		mutex_lock(&fs_info->balance_mutex);
5113 
5114 		if (fs_info->balance_ctl) {
5115 			reset_balance_state(fs_info);
5116 			btrfs_exclop_finish(fs_info);
5117 			btrfs_info(fs_info, "balance: canceled");
5118 		}
5119 	}
5120 
5121 	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
5122 	atomic_dec(&fs_info->balance_cancel_req);
5123 	mutex_unlock(&fs_info->balance_mutex);
5124 	return 0;
5125 }
5126 
5127 /*
5128  * shrinking a device means finding all of the device extents past
5129  * the new size, and then following the back refs to the chunks.
5130  * The chunk relocation code actually frees the device extent
5131  */
btrfs_shrink_device(struct btrfs_device * device,u64 new_size)5132 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
5133 {
5134 	struct btrfs_fs_info *fs_info = device->fs_info;
5135 	struct btrfs_root *root = fs_info->dev_root;
5136 	struct btrfs_trans_handle *trans;
5137 	struct btrfs_dev_extent *dev_extent = NULL;
5138 	struct btrfs_path *path;
5139 	u64 length;
5140 	u64 chunk_offset;
5141 	int ret;
5142 	int slot;
5143 	int failed = 0;
5144 	bool retried = false;
5145 	struct extent_buffer *l;
5146 	struct btrfs_key key;
5147 	struct btrfs_super_block *super_copy = fs_info->super_copy;
5148 	u64 old_total = btrfs_super_total_bytes(super_copy);
5149 	u64 old_size = btrfs_device_get_total_bytes(device);
5150 	u64 diff;
5151 	u64 start;
5152 	u64 free_diff = 0;
5153 	u64 pending_start, pending_end;
5154 
5155 	new_size = round_down(new_size, fs_info->sectorsize);
5156 	start = new_size;
5157 	diff = round_down(old_size - new_size, fs_info->sectorsize);
5158 
5159 	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5160 		return -EINVAL;
5161 
5162 	path = btrfs_alloc_path();
5163 	if (!path)
5164 		return -ENOMEM;
5165 
5166 	path->reada = READA_BACK;
5167 
5168 	trans = btrfs_start_transaction(root, 0);
5169 	if (IS_ERR(trans)) {
5170 		btrfs_free_path(path);
5171 		return PTR_ERR(trans);
5172 	}
5173 
5174 	mutex_lock(&fs_info->chunk_mutex);
5175 
5176 	btrfs_device_set_total_bytes(device, new_size);
5177 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5178 		device->fs_devices->total_rw_bytes -= diff;
5179 
5180 		/*
5181 		 * The new free_chunk_space is new_size - used, so we have to
5182 		 * subtract the delta of the old free_chunk_space which included
5183 		 * old_size - used.  If used > new_size then just subtract this
5184 		 * entire device's free space.
5185 		 */
5186 		if (device->bytes_used < new_size)
5187 			free_diff = (old_size - device->bytes_used) -
5188 				    (new_size - device->bytes_used);
5189 		else
5190 			free_diff = old_size - device->bytes_used;
5191 		atomic64_sub(free_diff, &fs_info->free_chunk_space);
5192 	}
5193 
5194 	/*
5195 	 * Once the device's size has been set to the new size, ensure all
5196 	 * in-memory chunks are synced to disk so that the loop below sees them
5197 	 * and relocates them accordingly.
5198 	 */
5199 	if (btrfs_first_pending_extent(device, start, diff, &pending_start, &pending_end)) {
5200 		mutex_unlock(&fs_info->chunk_mutex);
5201 		ret = btrfs_commit_transaction(trans);
5202 		if (ret)
5203 			goto done;
5204 	} else {
5205 		mutex_unlock(&fs_info->chunk_mutex);
5206 		btrfs_end_transaction(trans);
5207 	}
5208 
5209 again:
5210 	key.objectid = device->devid;
5211 	key.type = BTRFS_DEV_EXTENT_KEY;
5212 	key.offset = (u64)-1;
5213 
5214 	do {
5215 		mutex_lock(&fs_info->reclaim_bgs_lock);
5216 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5217 		if (ret < 0) {
5218 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5219 			goto done;
5220 		}
5221 
5222 		ret = btrfs_previous_item(root, path, 0, key.type);
5223 		if (ret) {
5224 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5225 			if (ret < 0)
5226 				goto done;
5227 			ret = 0;
5228 			btrfs_release_path(path);
5229 			break;
5230 		}
5231 
5232 		l = path->nodes[0];
5233 		slot = path->slots[0];
5234 		btrfs_item_key_to_cpu(l, &key, path->slots[0]);
5235 
5236 		if (key.objectid != device->devid) {
5237 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5238 			btrfs_release_path(path);
5239 			break;
5240 		}
5241 
5242 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
5243 		length = btrfs_dev_extent_length(l, dev_extent);
5244 
5245 		if (key.offset + length <= new_size) {
5246 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5247 			btrfs_release_path(path);
5248 			break;
5249 		}
5250 
5251 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
5252 		btrfs_release_path(path);
5253 
5254 		/*
5255 		 * We may be relocating the only data chunk we have,
5256 		 * which could potentially end up with losing data's
5257 		 * raid profile, so lets allocate an empty one in
5258 		 * advance.
5259 		 */
5260 		ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
5261 		if (ret < 0) {
5262 			mutex_unlock(&fs_info->reclaim_bgs_lock);
5263 			goto done;
5264 		}
5265 
5266 		ret = btrfs_relocate_chunk(fs_info, chunk_offset, true);
5267 		mutex_unlock(&fs_info->reclaim_bgs_lock);
5268 		if (ret == -ENOSPC) {
5269 			failed++;
5270 		} else if (ret) {
5271 			if (ret == -ETXTBSY) {
5272 				btrfs_warn(fs_info,
5273 		   "could not shrink block group %llu due to active swapfile",
5274 					   chunk_offset);
5275 			}
5276 			goto done;
5277 		}
5278 	} while (key.offset-- > 0);
5279 
5280 	if (failed && !retried) {
5281 		failed = 0;
5282 		retried = true;
5283 		goto again;
5284 	} else if (failed && retried) {
5285 		ret = -ENOSPC;
5286 		goto done;
5287 	}
5288 
5289 	/* Shrinking succeeded, else we would be at "done". */
5290 	trans = btrfs_start_transaction(root, 0);
5291 	if (IS_ERR(trans)) {
5292 		ret = PTR_ERR(trans);
5293 		goto done;
5294 	}
5295 
5296 	mutex_lock(&fs_info->chunk_mutex);
5297 	/* Clear all state bits beyond the shrunk device size */
5298 	btrfs_clear_extent_bit(&device->alloc_state, new_size, (u64)-1,
5299 			       CHUNK_STATE_MASK, NULL);
5300 
5301 	btrfs_device_set_disk_total_bytes(device, new_size);
5302 	if (list_empty(&device->post_commit_list))
5303 		list_add_tail(&device->post_commit_list,
5304 			      &trans->transaction->dev_update_list);
5305 
5306 	WARN_ON(diff > old_total);
5307 	btrfs_set_super_total_bytes(super_copy,
5308 			round_down(old_total - diff, fs_info->sectorsize));
5309 	mutex_unlock(&fs_info->chunk_mutex);
5310 
5311 	btrfs_reserve_chunk_metadata(trans, false);
5312 	/* Now btrfs_update_device() will change the on-disk size. */
5313 	ret = btrfs_update_device(trans, device);
5314 	btrfs_trans_release_chunk_metadata(trans);
5315 	if (unlikely(ret < 0)) {
5316 		btrfs_abort_transaction(trans, ret);
5317 		btrfs_end_transaction(trans);
5318 	} else {
5319 		ret = btrfs_commit_transaction(trans);
5320 	}
5321 done:
5322 	btrfs_free_path(path);
5323 	if (ret) {
5324 		mutex_lock(&fs_info->chunk_mutex);
5325 		btrfs_device_set_total_bytes(device, old_size);
5326 		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5327 			device->fs_devices->total_rw_bytes += diff;
5328 			atomic64_add(free_diff, &fs_info->free_chunk_space);
5329 		}
5330 		mutex_unlock(&fs_info->chunk_mutex);
5331 	}
5332 	return ret;
5333 }
5334 
btrfs_add_system_chunk(struct btrfs_fs_info * fs_info,struct btrfs_key * key,struct btrfs_chunk * chunk,int item_size)5335 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5336 			   struct btrfs_key *key,
5337 			   struct btrfs_chunk *chunk, int item_size)
5338 {
5339 	struct btrfs_super_block *super_copy = fs_info->super_copy;
5340 	struct btrfs_disk_key disk_key;
5341 	u32 array_size;
5342 	u8 *ptr;
5343 
5344 	lockdep_assert_held(&fs_info->chunk_mutex);
5345 
5346 	array_size = btrfs_super_sys_array_size(super_copy);
5347 	if (array_size + item_size + sizeof(disk_key)
5348 			> BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5349 		return -EFBIG;
5350 
5351 	ptr = super_copy->sys_chunk_array + array_size;
5352 	btrfs_cpu_key_to_disk(&disk_key, key);
5353 	memcpy(ptr, &disk_key, sizeof(disk_key));
5354 	ptr += sizeof(disk_key);
5355 	memcpy(ptr, chunk, item_size);
5356 	item_size += sizeof(disk_key);
5357 	btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5358 
5359 	return 0;
5360 }
5361 
5362 /*
5363  * sort the devices in descending order by max_avail, total_avail
5364  */
btrfs_cmp_device_info(const void * a,const void * b)5365 static int btrfs_cmp_device_info(const void *a, const void *b)
5366 {
5367 	const struct btrfs_device_info *di_a = a;
5368 	const struct btrfs_device_info *di_b = b;
5369 
5370 	if (di_a->max_avail > di_b->max_avail)
5371 		return -1;
5372 	if (di_a->max_avail < di_b->max_avail)
5373 		return 1;
5374 	if (di_a->total_avail > di_b->total_avail)
5375 		return -1;
5376 	if (di_a->total_avail < di_b->total_avail)
5377 		return 1;
5378 	return 0;
5379 }
5380 
check_raid56_incompat_flag(struct btrfs_fs_info * info,u64 type)5381 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5382 {
5383 	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5384 		return;
5385 
5386 	btrfs_set_fs_incompat(info, RAID56);
5387 }
5388 
check_raid1c34_incompat_flag(struct btrfs_fs_info * info,u64 type)5389 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5390 {
5391 	if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5392 		return;
5393 
5394 	btrfs_set_fs_incompat(info, RAID1C34);
5395 }
5396 
5397 /*
5398  * Structure used internally for btrfs_create_chunk() function.
5399  * Wraps needed parameters.
5400  */
5401 struct alloc_chunk_ctl {
5402 	u64 start;
5403 	u64 type;
5404 	/* Total number of stripes to allocate */
5405 	int num_stripes;
5406 	/* sub_stripes info for map */
5407 	int sub_stripes;
5408 	/* Stripes per device */
5409 	int dev_stripes;
5410 	/* Maximum number of devices to use */
5411 	int devs_max;
5412 	/* Minimum number of devices to use */
5413 	int devs_min;
5414 	/* ndevs has to be a multiple of this */
5415 	int devs_increment;
5416 	/* Number of copies */
5417 	int ncopies;
5418 	/* Number of stripes worth of bytes to store parity information */
5419 	int nparity;
5420 	u64 max_stripe_size;
5421 	u64 max_chunk_size;
5422 	u64 dev_extent_min;
5423 	u64 stripe_size;
5424 	u64 chunk_size;
5425 	int ndevs;
5426 	/* Space_info the block group is going to belong. */
5427 	struct btrfs_space_info *space_info;
5428 };
5429 
init_alloc_chunk_ctl_policy_regular(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5430 static void init_alloc_chunk_ctl_policy_regular(
5431 				struct btrfs_fs_devices *fs_devices,
5432 				struct alloc_chunk_ctl *ctl)
5433 {
5434 	struct btrfs_space_info *space_info;
5435 
5436 	space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5437 	ASSERT(space_info);
5438 
5439 	ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5440 	ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5441 
5442 	if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5443 		ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5444 
5445 	/* We don't want a chunk larger than 10% of writable space */
5446 	ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5447 				  ctl->max_chunk_size);
5448 	ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5449 }
5450 
init_alloc_chunk_ctl_policy_zoned(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5451 static void init_alloc_chunk_ctl_policy_zoned(
5452 				      struct btrfs_fs_devices *fs_devices,
5453 				      struct alloc_chunk_ctl *ctl)
5454 {
5455 	u64 zone_size = fs_devices->fs_info->zone_size;
5456 	u64 limit;
5457 	int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5458 	int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5459 	u64 min_chunk_size = min_data_stripes * zone_size;
5460 	u64 type = ctl->type;
5461 
5462 	ctl->max_stripe_size = zone_size;
5463 	if (type & BTRFS_BLOCK_GROUP_DATA) {
5464 		ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5465 						 zone_size);
5466 	} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5467 		ctl->max_chunk_size = ctl->max_stripe_size;
5468 	} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5469 		ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5470 		ctl->devs_max = min_t(int, ctl->devs_max,
5471 				      BTRFS_MAX_DEVS_SYS_CHUNK);
5472 	} else {
5473 		BUG();
5474 	}
5475 
5476 	/* We don't want a chunk larger than 10% of writable space */
5477 	limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5478 			       zone_size),
5479 		    min_chunk_size);
5480 	ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5481 	ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5482 }
5483 
init_alloc_chunk_ctl(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl)5484 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5485 				 struct alloc_chunk_ctl *ctl)
5486 {
5487 	int index = btrfs_bg_flags_to_raid_index(ctl->type);
5488 
5489 	ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5490 	ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5491 	ctl->devs_max = btrfs_raid_array[index].devs_max;
5492 	if (!ctl->devs_max)
5493 		ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5494 	ctl->devs_min = btrfs_raid_array[index].devs_min;
5495 	ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5496 	ctl->ncopies = btrfs_raid_array[index].ncopies;
5497 	ctl->nparity = btrfs_raid_array[index].nparity;
5498 	ctl->ndevs = 0;
5499 
5500 	switch (fs_devices->chunk_alloc_policy) {
5501 	default:
5502 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5503 		fallthrough;
5504 	case BTRFS_CHUNK_ALLOC_REGULAR:
5505 		init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5506 		break;
5507 	case BTRFS_CHUNK_ALLOC_ZONED:
5508 		init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5509 		break;
5510 	}
5511 }
5512 
gather_device_info(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5513 static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5514 			      struct alloc_chunk_ctl *ctl,
5515 			      struct btrfs_device_info *devices_info)
5516 {
5517 	struct btrfs_fs_info *info = fs_devices->fs_info;
5518 	struct btrfs_device *device;
5519 	u64 total_avail;
5520 	u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5521 	int ret;
5522 	int ndevs = 0;
5523 	u64 max_avail;
5524 	u64 dev_offset;
5525 
5526 	/*
5527 	 * in the first pass through the devices list, we gather information
5528 	 * about the available holes on each device.
5529 	 */
5530 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5531 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5532 			WARN(1, KERN_ERR
5533 			       "BTRFS: read-only device in alloc_list\n");
5534 			continue;
5535 		}
5536 
5537 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5538 					&device->dev_state) ||
5539 		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5540 			continue;
5541 
5542 		if (device->total_bytes > device->bytes_used)
5543 			total_avail = device->total_bytes - device->bytes_used;
5544 		else
5545 			total_avail = 0;
5546 
5547 		/* If there is no space on this device, skip it. */
5548 		if (total_avail < ctl->dev_extent_min)
5549 			continue;
5550 
5551 		ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5552 					   &max_avail);
5553 		if (ret && ret != -ENOSPC)
5554 			return ret;
5555 
5556 		if (ret == 0)
5557 			max_avail = dev_extent_want;
5558 
5559 		if (max_avail < ctl->dev_extent_min) {
5560 			if (btrfs_test_opt(info, ENOSPC_DEBUG))
5561 				btrfs_debug(info,
5562 			"%s: devid %llu has no free space, have=%llu want=%llu",
5563 					    __func__, device->devid, max_avail,
5564 					    ctl->dev_extent_min);
5565 			continue;
5566 		}
5567 
5568 		if (ndevs == fs_devices->rw_devices) {
5569 			WARN(1, "%s: found more than %llu devices\n",
5570 			     __func__, fs_devices->rw_devices);
5571 			break;
5572 		}
5573 		devices_info[ndevs].dev_offset = dev_offset;
5574 		devices_info[ndevs].max_avail = max_avail;
5575 		devices_info[ndevs].total_avail = total_avail;
5576 		devices_info[ndevs].dev = device;
5577 		++ndevs;
5578 	}
5579 	ctl->ndevs = ndevs;
5580 
5581 	/*
5582 	 * now sort the devices by hole size / available space
5583 	 */
5584 	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5585 	     btrfs_cmp_device_info, NULL);
5586 
5587 	return 0;
5588 }
5589 
decide_stripe_size_regular(struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5590 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5591 				      struct btrfs_device_info *devices_info)
5592 {
5593 	/* Number of stripes that count for block group size */
5594 	int data_stripes;
5595 
5596 	/*
5597 	 * The primary goal is to maximize the number of stripes, so use as
5598 	 * many devices as possible, even if the stripes are not maximum sized.
5599 	 *
5600 	 * The DUP profile stores more than one stripe per device, the
5601 	 * max_avail is the total size so we have to adjust.
5602 	 */
5603 	ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5604 				   ctl->dev_stripes);
5605 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5606 
5607 	/* This will have to be fixed for RAID1 and RAID10 over more drives */
5608 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5609 
5610 	/*
5611 	 * Use the number of data stripes to figure out how big this chunk is
5612 	 * really going to be in terms of logical address space, and compare
5613 	 * that answer with the max chunk size. If it's higher, we try to
5614 	 * reduce stripe_size.
5615 	 */
5616 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5617 		/*
5618 		 * Reduce stripe_size, round it up to a 16MB boundary again and
5619 		 * then use it, unless it ends up being even bigger than the
5620 		 * previous value we had already.
5621 		 */
5622 		ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5623 							data_stripes), SZ_16M),
5624 				       ctl->stripe_size);
5625 	}
5626 
5627 	/* Stripe size should not go beyond 1G. */
5628 	ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5629 
5630 	/* Align to BTRFS_STRIPE_LEN */
5631 	ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5632 	ctl->chunk_size = ctl->stripe_size * data_stripes;
5633 
5634 	return 0;
5635 }
5636 
decide_stripe_size_zoned(struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5637 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5638 				    struct btrfs_device_info *devices_info)
5639 {
5640 	u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5641 	/* Number of stripes that count for block group size */
5642 	int data_stripes;
5643 
5644 	/*
5645 	 * It should hold because:
5646 	 *    dev_extent_min == dev_extent_want == zone_size * dev_stripes
5647 	 */
5648 	ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min,
5649 	       "ndevs=%d max_avail=%llu dev_extent_min=%llu", ctl->ndevs,
5650 	       devices_info[ctl->ndevs - 1].max_avail, ctl->dev_extent_min);
5651 
5652 	ctl->stripe_size = zone_size;
5653 	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5654 	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5655 
5656 	/* stripe_size is fixed in zoned filesystem. Reduce ndevs instead. */
5657 	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5658 		ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5659 					     ctl->stripe_size) + ctl->nparity,
5660 				     ctl->dev_stripes);
5661 		ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5662 		data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5663 		ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size,
5664 		       "stripe_size=%llu data_stripes=%d max_chunk_size=%llu",
5665 		       ctl->stripe_size, data_stripes, ctl->max_chunk_size);
5666 	}
5667 
5668 	ctl->chunk_size = ctl->stripe_size * data_stripes;
5669 
5670 	return 0;
5671 }
5672 
decide_stripe_size(struct btrfs_fs_devices * fs_devices,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5673 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5674 			      struct alloc_chunk_ctl *ctl,
5675 			      struct btrfs_device_info *devices_info)
5676 {
5677 	struct btrfs_fs_info *info = fs_devices->fs_info;
5678 
5679 	/*
5680 	 * Round down to number of usable stripes, devs_increment can be any
5681 	 * number so we can't use round_down() that requires power of 2, while
5682 	 * rounddown is safe.
5683 	 */
5684 	ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5685 
5686 	if (ctl->ndevs < ctl->devs_min) {
5687 		if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5688 			btrfs_debug(info,
5689 	"%s: not enough devices with free space: have=%d minimum required=%d",
5690 				    __func__, ctl->ndevs, ctl->devs_min);
5691 		}
5692 		return -ENOSPC;
5693 	}
5694 
5695 	ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5696 
5697 	switch (fs_devices->chunk_alloc_policy) {
5698 	default:
5699 		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5700 		fallthrough;
5701 	case BTRFS_CHUNK_ALLOC_REGULAR:
5702 		return decide_stripe_size_regular(ctl, devices_info);
5703 	case BTRFS_CHUNK_ALLOC_ZONED:
5704 		return decide_stripe_size_zoned(ctl, devices_info);
5705 	}
5706 }
5707 
chunk_map_device_set_bits(struct btrfs_chunk_map * map,unsigned int bits)5708 static void chunk_map_device_set_bits(struct btrfs_chunk_map *map, unsigned int bits)
5709 {
5710 	for (int i = 0; i < map->num_stripes; i++) {
5711 		struct btrfs_io_stripe *stripe = &map->stripes[i];
5712 		struct btrfs_device *device = stripe->dev;
5713 
5714 		btrfs_set_extent_bit(&device->alloc_state, stripe->physical,
5715 				     stripe->physical + map->stripe_size - 1,
5716 				     bits | EXTENT_NOWAIT, NULL);
5717 	}
5718 }
5719 
btrfs_chunk_map_device_clear_bits(struct btrfs_chunk_map * map,unsigned int bits)5720 void btrfs_chunk_map_device_clear_bits(struct btrfs_chunk_map *map, unsigned int bits)
5721 {
5722 	for (int i = 0; i < map->num_stripes; i++) {
5723 		struct btrfs_io_stripe *stripe = &map->stripes[i];
5724 		struct btrfs_device *device = stripe->dev;
5725 
5726 		btrfs_clear_extent_bit(&device->alloc_state, stripe->physical,
5727 				       stripe->physical + map->stripe_size - 1,
5728 				       bits | EXTENT_NOWAIT, NULL);
5729 	}
5730 }
5731 
btrfs_remove_chunk_map(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map)5732 void btrfs_remove_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5733 {
5734 	write_lock(&fs_info->mapping_tree_lock);
5735 	rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5736 	RB_CLEAR_NODE(&map->rb_node);
5737 	btrfs_chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5738 	write_unlock(&fs_info->mapping_tree_lock);
5739 
5740 	/* Once for the tree reference. */
5741 	btrfs_free_chunk_map(map);
5742 }
5743 
btrfs_chunk_map_cmp(const struct rb_node * new,const struct rb_node * exist)5744 static int btrfs_chunk_map_cmp(const struct rb_node *new,
5745 			       const struct rb_node *exist)
5746 {
5747 	const struct btrfs_chunk_map *new_map =
5748 		rb_entry(new, struct btrfs_chunk_map, rb_node);
5749 	const struct btrfs_chunk_map *exist_map =
5750 		rb_entry(exist, struct btrfs_chunk_map, rb_node);
5751 
5752 	if (new_map->start == exist_map->start)
5753 		return 0;
5754 	if (new_map->start < exist_map->start)
5755 		return -1;
5756 	return 1;
5757 }
5758 
5759 EXPORT_FOR_TESTS
btrfs_add_chunk_map(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map)5760 int btrfs_add_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5761 {
5762 	struct rb_node *exist;
5763 
5764 	write_lock(&fs_info->mapping_tree_lock);
5765 	exist = rb_find_add_cached(&map->rb_node, &fs_info->mapping_tree,
5766 				   btrfs_chunk_map_cmp);
5767 
5768 	if (exist) {
5769 		write_unlock(&fs_info->mapping_tree_lock);
5770 		return -EEXIST;
5771 	}
5772 	chunk_map_device_set_bits(map, CHUNK_ALLOCATED);
5773 	btrfs_chunk_map_device_clear_bits(map, CHUNK_TRIMMED);
5774 	write_unlock(&fs_info->mapping_tree_lock);
5775 
5776 	return 0;
5777 }
5778 
5779 EXPORT_FOR_TESTS
btrfs_alloc_chunk_map(int num_stripes,gfp_t gfp)5780 struct btrfs_chunk_map *btrfs_alloc_chunk_map(int num_stripes, gfp_t gfp)
5781 {
5782 	struct btrfs_chunk_map *map;
5783 
5784 	map = kmalloc(btrfs_chunk_map_size(num_stripes), gfp);
5785 	if (!map)
5786 		return NULL;
5787 
5788 	refcount_set(&map->refs, 1);
5789 	RB_CLEAR_NODE(&map->rb_node);
5790 
5791 	return map;
5792 }
5793 
create_chunk(struct btrfs_trans_handle * trans,struct alloc_chunk_ctl * ctl,struct btrfs_device_info * devices_info)5794 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5795 			struct alloc_chunk_ctl *ctl,
5796 			struct btrfs_device_info *devices_info)
5797 {
5798 	struct btrfs_fs_info *info = trans->fs_info;
5799 	struct btrfs_chunk_map *map;
5800 	struct btrfs_block_group *block_group;
5801 	u64 start = ctl->start;
5802 	u64 type = ctl->type;
5803 	int ret;
5804 
5805 	map = btrfs_alloc_chunk_map(ctl->num_stripes, GFP_NOFS);
5806 	if (!map)
5807 		return ERR_PTR(-ENOMEM);
5808 
5809 	map->start = start;
5810 	map->chunk_len = ctl->chunk_size;
5811 	map->stripe_size = ctl->stripe_size;
5812 	map->type = type;
5813 	map->io_align = BTRFS_STRIPE_LEN;
5814 	map->io_width = BTRFS_STRIPE_LEN;
5815 	map->sub_stripes = ctl->sub_stripes;
5816 	map->num_stripes = ctl->num_stripes;
5817 
5818 	for (int i = 0; i < ctl->ndevs; i++) {
5819 		for (int j = 0; j < ctl->dev_stripes; j++) {
5820 			int s = i * ctl->dev_stripes + j;
5821 			map->stripes[s].dev = devices_info[i].dev;
5822 			map->stripes[s].physical = devices_info[i].dev_offset +
5823 						   j * ctl->stripe_size;
5824 		}
5825 	}
5826 
5827 	trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5828 
5829 	ret = btrfs_add_chunk_map(info, map);
5830 	if (ret) {
5831 		btrfs_free_chunk_map(map);
5832 		return ERR_PTR(ret);
5833 	}
5834 
5835 	block_group = btrfs_make_block_group(trans, ctl->space_info, type, start,
5836 					     ctl->chunk_size);
5837 	if (IS_ERR(block_group)) {
5838 		btrfs_remove_chunk_map(info, map);
5839 		return block_group;
5840 	}
5841 
5842 	for (int i = 0; i < map->num_stripes; i++) {
5843 		struct btrfs_device *dev = map->stripes[i].dev;
5844 
5845 		btrfs_device_set_bytes_used(dev,
5846 					    dev->bytes_used + ctl->stripe_size);
5847 		if (list_empty(&dev->post_commit_list))
5848 			list_add_tail(&dev->post_commit_list,
5849 				      &trans->transaction->dev_update_list);
5850 	}
5851 
5852 	atomic64_sub(ctl->stripe_size * map->num_stripes,
5853 		     &info->free_chunk_space);
5854 
5855 	check_raid56_incompat_flag(info, type);
5856 	check_raid1c34_incompat_flag(info, type);
5857 
5858 	return block_group;
5859 }
5860 
btrfs_create_chunk(struct btrfs_trans_handle * trans,struct btrfs_space_info * space_info,u64 type)5861 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5862 					     struct btrfs_space_info *space_info,
5863 					     u64 type)
5864 {
5865 	struct btrfs_fs_info *info = trans->fs_info;
5866 	struct btrfs_fs_devices *fs_devices = info->fs_devices;
5867 	struct btrfs_device_info AUTO_KFREE(devices_info);
5868 	struct alloc_chunk_ctl ctl;
5869 	int ret;
5870 
5871 	lockdep_assert_held(&info->chunk_mutex);
5872 
5873 	if (!alloc_profile_is_valid(type, 0)) {
5874 		DEBUG_WARN("invalid alloc profile for type %llu", type);
5875 		return ERR_PTR(-EINVAL);
5876 	}
5877 
5878 	if (list_empty(&fs_devices->alloc_list)) {
5879 		if (btrfs_test_opt(info, ENOSPC_DEBUG))
5880 			btrfs_debug(info, "%s: no writable device", __func__);
5881 		return ERR_PTR(-ENOSPC);
5882 	}
5883 
5884 	if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5885 		btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5886 		DEBUG_WARN();
5887 		return ERR_PTR(-EINVAL);
5888 	}
5889 
5890 	ctl.start = find_next_chunk(info);
5891 	ctl.type = type;
5892 	ctl.space_info = space_info;
5893 	init_alloc_chunk_ctl(fs_devices, &ctl);
5894 
5895 	devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5896 			       GFP_NOFS);
5897 	if (!devices_info)
5898 		return ERR_PTR(-ENOMEM);
5899 
5900 	ret = gather_device_info(fs_devices, &ctl, devices_info);
5901 	if (ret < 0)
5902 		return ERR_PTR(ret);
5903 
5904 	ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5905 	if (ret < 0)
5906 		return ERR_PTR(ret);
5907 
5908 	return create_chunk(trans, &ctl, devices_info);
5909 }
5910 
5911 /*
5912  * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5913  * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5914  * chunks.
5915  *
5916  * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5917  * phases.
5918  */
btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle * trans,struct btrfs_block_group * bg)5919 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5920 				     struct btrfs_block_group *bg)
5921 {
5922 	struct btrfs_fs_info *fs_info = trans->fs_info;
5923 	struct btrfs_root *chunk_root = fs_info->chunk_root;
5924 	struct btrfs_key key;
5925 	struct btrfs_chunk *chunk;
5926 	struct btrfs_stripe *stripe;
5927 	struct btrfs_chunk_map *map;
5928 	size_t item_size;
5929 	int i;
5930 	int ret;
5931 
5932 	/*
5933 	 * We take the chunk_mutex for 2 reasons:
5934 	 *
5935 	 * 1) Updates and insertions in the chunk btree must be done while holding
5936 	 *    the chunk_mutex, as well as updating the system chunk array in the
5937 	 *    superblock. See the comment on top of btrfs_chunk_alloc() for the
5938 	 *    details;
5939 	 *
5940 	 * 2) To prevent races with the final phase of a device replace operation
5941 	 *    that replaces the device object associated with the map's stripes,
5942 	 *    because the device object's id can change at any time during that
5943 	 *    final phase of the device replace operation
5944 	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5945 	 *    replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5946 	 *    which would cause a failure when updating the device item, which does
5947 	 *    not exists, or persisting a stripe of the chunk item with such ID.
5948 	 *    Here we can't use the device_list_mutex because our caller already
5949 	 *    has locked the chunk_mutex, and the final phase of device replace
5950 	 *    acquires both mutexes - first the device_list_mutex and then the
5951 	 *    chunk_mutex. Using any of those two mutexes protects us from a
5952 	 *    concurrent device replace.
5953 	 */
5954 	lockdep_assert_held(&fs_info->chunk_mutex);
5955 
5956 	map = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5957 	if (IS_ERR(map)) {
5958 		ret = PTR_ERR(map);
5959 		btrfs_abort_transaction(trans, ret);
5960 		return ret;
5961 	}
5962 
5963 	item_size = btrfs_chunk_item_size(map->num_stripes);
5964 
5965 	chunk = kzalloc(item_size, GFP_NOFS);
5966 	if (unlikely(!chunk)) {
5967 		ret = -ENOMEM;
5968 		btrfs_abort_transaction(trans, ret);
5969 		goto out;
5970 	}
5971 
5972 	for (i = 0; i < map->num_stripes; i++) {
5973 		struct btrfs_device *device = map->stripes[i].dev;
5974 
5975 		ret = btrfs_update_device(trans, device);
5976 		if (ret)
5977 			goto out;
5978 	}
5979 
5980 	stripe = &chunk->stripe;
5981 	for (i = 0; i < map->num_stripes; i++) {
5982 		struct btrfs_device *device = map->stripes[i].dev;
5983 		const u64 dev_offset = map->stripes[i].physical;
5984 
5985 		btrfs_set_stack_stripe_devid(stripe, device->devid);
5986 		btrfs_set_stack_stripe_offset(stripe, dev_offset);
5987 		memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5988 		stripe++;
5989 	}
5990 
5991 	btrfs_set_stack_chunk_length(chunk, bg->length);
5992 	btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5993 	btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5994 	btrfs_set_stack_chunk_type(chunk, map->type);
5995 	btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5996 	btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5997 	btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5998 	btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5999 	btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
6000 
6001 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
6002 	key.type = BTRFS_CHUNK_ITEM_KEY;
6003 	key.offset = bg->start;
6004 
6005 	ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
6006 	if (ret)
6007 		goto out;
6008 
6009 	set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
6010 
6011 	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
6012 		ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
6013 		if (ret)
6014 			goto out;
6015 	}
6016 
6017 out:
6018 	kfree(chunk);
6019 	btrfs_free_chunk_map(map);
6020 	return ret;
6021 }
6022 
init_first_rw_device(struct btrfs_trans_handle * trans)6023 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
6024 {
6025 	struct btrfs_fs_info *fs_info = trans->fs_info;
6026 	u64 alloc_profile;
6027 	struct btrfs_block_group *meta_bg;
6028 	struct btrfs_space_info *meta_space_info;
6029 	struct btrfs_block_group *sys_bg;
6030 	struct btrfs_space_info *sys_space_info;
6031 
6032 	/*
6033 	 * When adding a new device for sprouting, the seed device is read-only
6034 	 * so we must first allocate a metadata and a system chunk. But before
6035 	 * adding the block group items to the extent, device and chunk btrees,
6036 	 * we must first:
6037 	 *
6038 	 * 1) Create both chunks without doing any changes to the btrees, as
6039 	 *    otherwise we would get -ENOSPC since the block groups from the
6040 	 *    seed device are read-only;
6041 	 *
6042 	 * 2) Add the device item for the new sprout device - finishing the setup
6043 	 *    of a new block group requires updating the device item in the chunk
6044 	 *    btree, so it must exist when we attempt to do it. The previous step
6045 	 *    ensures this does not fail with -ENOSPC.
6046 	 *
6047 	 * After that we can add the block group items to their btrees:
6048 	 * update existing device item in the chunk btree, add a new block group
6049 	 * item to the extent btree, add a new chunk item to the chunk btree and
6050 	 * finally add the new device extent items to the devices btree.
6051 	 */
6052 
6053 	alloc_profile = btrfs_metadata_alloc_profile(fs_info);
6054 	meta_space_info = btrfs_find_space_info(fs_info, alloc_profile);
6055 	if (!meta_space_info) {
6056 		DEBUG_WARN();
6057 		return -EINVAL;
6058 	}
6059 	meta_bg = btrfs_create_chunk(trans, meta_space_info, alloc_profile);
6060 	if (IS_ERR(meta_bg))
6061 		return PTR_ERR(meta_bg);
6062 
6063 	alloc_profile = btrfs_system_alloc_profile(fs_info);
6064 	sys_space_info = btrfs_find_space_info(fs_info, alloc_profile);
6065 	if (!sys_space_info) {
6066 		DEBUG_WARN();
6067 		return -EINVAL;
6068 	}
6069 	sys_bg = btrfs_create_chunk(trans, sys_space_info, alloc_profile);
6070 	if (IS_ERR(sys_bg))
6071 		return PTR_ERR(sys_bg);
6072 
6073 	return 0;
6074 }
6075 
btrfs_chunk_max_errors(struct btrfs_chunk_map * map)6076 static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map *map)
6077 {
6078 	const int index = btrfs_bg_flags_to_raid_index(map->type);
6079 
6080 	return btrfs_raid_array[index].tolerated_failures;
6081 }
6082 
btrfs_chunk_writeable(struct btrfs_fs_info * fs_info,u64 chunk_offset)6083 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
6084 {
6085 	struct btrfs_chunk_map *map;
6086 	int miss_ndevs = 0;
6087 	int i;
6088 	bool ret = true;
6089 
6090 	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
6091 	if (IS_ERR(map))
6092 		return false;
6093 
6094 	for (i = 0; i < map->num_stripes; i++) {
6095 		if (test_bit(BTRFS_DEV_STATE_MISSING,
6096 					&map->stripes[i].dev->dev_state)) {
6097 			miss_ndevs++;
6098 			continue;
6099 		}
6100 		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
6101 					&map->stripes[i].dev->dev_state)) {
6102 			ret = false;
6103 			goto end;
6104 		}
6105 	}
6106 
6107 	/*
6108 	 * If the number of missing devices is larger than max errors, we can
6109 	 * not write the data into that chunk successfully.
6110 	 */
6111 	if (miss_ndevs > btrfs_chunk_max_errors(map))
6112 		ret = false;
6113 end:
6114 	btrfs_free_chunk_map(map);
6115 	return ret;
6116 }
6117 
btrfs_mapping_tree_free(struct btrfs_fs_info * fs_info)6118 void btrfs_mapping_tree_free(struct btrfs_fs_info *fs_info)
6119 {
6120 	write_lock(&fs_info->mapping_tree_lock);
6121 	while (!RB_EMPTY_ROOT(&fs_info->mapping_tree.rb_root)) {
6122 		struct btrfs_chunk_map *map;
6123 		struct rb_node *node;
6124 
6125 		node = rb_first_cached(&fs_info->mapping_tree);
6126 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
6127 		rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
6128 		RB_CLEAR_NODE(&map->rb_node);
6129 		btrfs_chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
6130 		/* Once for the tree ref. */
6131 		btrfs_free_chunk_map(map);
6132 		cond_resched_rwlock_write(&fs_info->mapping_tree_lock);
6133 	}
6134 	write_unlock(&fs_info->mapping_tree_lock);
6135 }
6136 
btrfs_chunk_map_num_copies(const struct btrfs_chunk_map * map)6137 static int btrfs_chunk_map_num_copies(const struct btrfs_chunk_map *map)
6138 {
6139 	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(map->type);
6140 
6141 	if (map->type & BTRFS_BLOCK_GROUP_RAID5)
6142 		return 2;
6143 
6144 	/*
6145 	 * There could be two corrupted data stripes, we need to loop retry in
6146 	 * order to rebuild the correct data.
6147 	 *
6148 	 * Fail a stripe at a time on every retry except the stripe under
6149 	 * reconstruction.
6150 	 */
6151 	if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6152 		return map->num_stripes;
6153 
6154 	/* Non-RAID56, use their ncopies from btrfs_raid_array. */
6155 	return btrfs_raid_array[index].ncopies;
6156 }
6157 
btrfs_num_copies(struct btrfs_fs_info * fs_info,u64 logical,u64 len)6158 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
6159 {
6160 	struct btrfs_chunk_map *map;
6161 	int ret;
6162 
6163 	map = btrfs_get_chunk_map(fs_info, logical, len);
6164 	if (IS_ERR(map))
6165 		/*
6166 		 * We could return errors for these cases, but that could get
6167 		 * ugly and we'd probably do the same thing which is just not do
6168 		 * anything else and exit, so return 1 so the callers don't try
6169 		 * to use other copies.
6170 		 */
6171 		return 1;
6172 
6173 	ret = btrfs_chunk_map_num_copies(map);
6174 	btrfs_free_chunk_map(map);
6175 	return ret;
6176 }
6177 
btrfs_full_stripe_len(struct btrfs_fs_info * fs_info,u64 logical)6178 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
6179 				    u64 logical)
6180 {
6181 	struct btrfs_chunk_map *map;
6182 	unsigned long len = fs_info->sectorsize;
6183 
6184 	if (!btrfs_fs_incompat(fs_info, RAID56))
6185 		return len;
6186 
6187 	map = btrfs_get_chunk_map(fs_info, logical, len);
6188 
6189 	if (!WARN_ON(IS_ERR(map))) {
6190 		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6191 			len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6192 		btrfs_free_chunk_map(map);
6193 	}
6194 	return len;
6195 }
6196 
6197 #ifdef CONFIG_BTRFS_EXPERIMENTAL
btrfs_read_preferred(struct btrfs_chunk_map * map,int first,int num_stripes)6198 static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
6199 {
6200 	for (int index = first; index < first + num_stripes; index++) {
6201 		const struct btrfs_device *device = map->stripes[index].dev;
6202 
6203 		if (device->devid == READ_ONCE(device->fs_devices->read_devid))
6204 			return index;
6205 	}
6206 
6207 	/* If no read-preferred device is set use the first stripe. */
6208 	return first;
6209 }
6210 
6211 struct stripe_mirror {
6212 	u64 devid;
6213 	int num;
6214 };
6215 
btrfs_cmp_devid(const void * a,const void * b)6216 static int btrfs_cmp_devid(const void *a, const void *b)
6217 {
6218 	const struct stripe_mirror *s1 = (const struct stripe_mirror *)a;
6219 	const struct stripe_mirror *s2 = (const struct stripe_mirror *)b;
6220 
6221 	if (s1->devid < s2->devid)
6222 		return -1;
6223 	if (s1->devid > s2->devid)
6224 		return 1;
6225 	return 0;
6226 }
6227 
6228 /*
6229  * Select a stripe for reading using the round-robin algorithm.
6230  *
6231  *  1. Compute the read cycle as the total sectors read divided by the minimum
6232  *     sectors per device.
6233  *  2. Determine the stripe number for the current read by taking the modulus
6234  *     of the read cycle with the total number of stripes:
6235  *
6236  *      stripe index = (total sectors / min sectors per dev) % num stripes
6237  *
6238  * The calculated stripe index is then used to select the corresponding device
6239  * from the list of devices, which is ordered by devid.
6240  */
btrfs_read_rr(const struct btrfs_chunk_map * map,int first,int num_stripes)6241 static int btrfs_read_rr(const struct btrfs_chunk_map *map, int first, int num_stripes)
6242 {
6243 	struct stripe_mirror stripes[BTRFS_RAID1_MAX_MIRRORS] = { 0 };
6244 	struct btrfs_device *device  = map->stripes[first].dev;
6245 	struct btrfs_fs_info *fs_info = device->fs_devices->fs_info;
6246 	unsigned int read_cycle;
6247 	unsigned int total_reads;
6248 	unsigned int min_reads_per_dev;
6249 
6250 	total_reads = percpu_counter_sum(&fs_info->stats_read_blocks);
6251 	min_reads_per_dev = READ_ONCE(fs_info->fs_devices->rr_min_contig_read) >>
6252 						       fs_info->sectorsize_bits;
6253 
6254 	for (int index = 0, i = first; i < first + num_stripes; i++) {
6255 		stripes[index].devid = map->stripes[i].dev->devid;
6256 		stripes[index].num = i;
6257 		index++;
6258 	}
6259 	sort(stripes, num_stripes, sizeof(struct stripe_mirror),
6260 	     btrfs_cmp_devid, NULL);
6261 
6262 	read_cycle = total_reads / min_reads_per_dev;
6263 	return stripes[read_cycle % num_stripes].num;
6264 }
6265 #endif
6266 
find_live_mirror(struct btrfs_fs_info * fs_info,struct btrfs_chunk_map * map,int first,bool dev_replace_is_ongoing)6267 static int find_live_mirror(struct btrfs_fs_info *fs_info,
6268 			    struct btrfs_chunk_map *map, int first,
6269 			    bool dev_replace_is_ongoing)
6270 {
6271 	const enum btrfs_read_policy policy = READ_ONCE(fs_info->fs_devices->read_policy);
6272 	int i;
6273 	int num_stripes;
6274 	int preferred_mirror;
6275 	int tolerance;
6276 	struct btrfs_device *srcdev;
6277 
6278 	ASSERT((map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)),
6279 	       "type=%llu", map->type);
6280 
6281 	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6282 		num_stripes = map->sub_stripes;
6283 	else
6284 		num_stripes = map->num_stripes;
6285 
6286 	switch (policy) {
6287 	default:
6288 		/* Shouldn't happen, just warn and use pid instead of failing */
6289 		btrfs_warn_rl(fs_info, "unknown read_policy type %u, reset to pid",
6290 			      policy);
6291 		WRITE_ONCE(fs_info->fs_devices->read_policy, BTRFS_READ_POLICY_PID);
6292 		fallthrough;
6293 	case BTRFS_READ_POLICY_PID:
6294 		preferred_mirror = first + (current->pid % num_stripes);
6295 		break;
6296 #ifdef CONFIG_BTRFS_EXPERIMENTAL
6297 	case BTRFS_READ_POLICY_RR:
6298 		preferred_mirror = btrfs_read_rr(map, first, num_stripes);
6299 		break;
6300 	case BTRFS_READ_POLICY_DEVID:
6301 		preferred_mirror = btrfs_read_preferred(map, first, num_stripes);
6302 		break;
6303 #endif
6304 	}
6305 
6306 	if (dev_replace_is_ongoing &&
6307 	    fs_info->dev_replace.cont_reading_from_srcdev_mode ==
6308 	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
6309 		srcdev = fs_info->dev_replace.srcdev;
6310 	else
6311 		srcdev = NULL;
6312 
6313 	/*
6314 	 * try to avoid the drive that is the source drive for a
6315 	 * dev-replace procedure, only choose it if no other non-missing
6316 	 * mirror is available
6317 	 */
6318 	for (tolerance = 0; tolerance < 2; tolerance++) {
6319 		if (map->stripes[preferred_mirror].dev->bdev &&
6320 		    (tolerance || map->stripes[preferred_mirror].dev != srcdev))
6321 			return preferred_mirror;
6322 		for (i = first; i < first + num_stripes; i++) {
6323 			if (map->stripes[i].dev->bdev &&
6324 			    (tolerance || map->stripes[i].dev != srcdev))
6325 				return i;
6326 		}
6327 	}
6328 
6329 	/* we couldn't find one that doesn't fail.  Just return something
6330 	 * and the io error handling code will clean up eventually
6331 	 */
6332 	return preferred_mirror;
6333 }
6334 
6335 EXPORT_FOR_TESTS
alloc_btrfs_io_context(struct btrfs_fs_info * fs_info,u64 logical,u16 total_stripes)6336 struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
6337 						u64 logical, u16 total_stripes)
6338 {
6339 	struct btrfs_io_context *bioc;
6340 
6341 	bioc = kzalloc_flex(*bioc, stripes, total_stripes, GFP_NOFS);
6342 
6343 	if (!bioc)
6344 		return NULL;
6345 
6346 	refcount_set(&bioc->refs, 1);
6347 
6348 	bioc->fs_info = fs_info;
6349 	bioc->replace_stripe_src = -1;
6350 	bioc->full_stripe_logical = (u64)-1;
6351 	bioc->logical = logical;
6352 
6353 	return bioc;
6354 }
6355 
btrfs_get_bioc(struct btrfs_io_context * bioc)6356 void btrfs_get_bioc(struct btrfs_io_context *bioc)
6357 {
6358 	WARN_ON(!refcount_read(&bioc->refs));
6359 	refcount_inc(&bioc->refs);
6360 }
6361 
btrfs_put_bioc(struct btrfs_io_context * bioc)6362 void btrfs_put_bioc(struct btrfs_io_context *bioc)
6363 {
6364 	if (!bioc)
6365 		return;
6366 	if (refcount_dec_and_test(&bioc->refs))
6367 		kfree(bioc);
6368 }
6369 
6370 /*
6371  * Please note that, discard won't be sent to target device of device
6372  * replace.
6373  */
btrfs_map_discard(struct btrfs_fs_info * fs_info,u64 logical,u64 * length_ret,u32 * num_stripes,bool do_remap)6374 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
6375 					       u64 logical, u64 *length_ret,
6376 					       u32 *num_stripes, bool do_remap)
6377 {
6378 	struct btrfs_chunk_map *map;
6379 	struct btrfs_discard_stripe *stripes;
6380 	u64 length = *length_ret;
6381 	u64 offset;
6382 	u32 stripe_nr;
6383 	u32 stripe_nr_end;
6384 	u32 stripe_cnt;
6385 	u64 stripe_end_offset;
6386 	u64 stripe_offset;
6387 	u32 stripe_index;
6388 	u32 factor = 0;
6389 	u32 sub_stripes = 0;
6390 	u32 stripes_per_dev = 0;
6391 	u32 remaining_stripes = 0;
6392 	u32 last_stripe = 0;
6393 	int ret;
6394 	int i;
6395 
6396 	map = btrfs_get_chunk_map(fs_info, logical, length);
6397 	if (IS_ERR(map))
6398 		return ERR_CAST(map);
6399 
6400 	if (do_remap && (map->type & BTRFS_BLOCK_GROUP_REMAPPED)) {
6401 		u64 new_logical = logical;
6402 
6403 		ret = btrfs_translate_remap(fs_info, &new_logical, &length);
6404 		if (ret)
6405 			goto out_free_map;
6406 
6407 		if (new_logical != logical) {
6408 			btrfs_free_chunk_map(map);
6409 
6410 			map = btrfs_get_chunk_map(fs_info, new_logical, length);
6411 			if (IS_ERR(map))
6412 				return ERR_CAST(map);
6413 
6414 			logical = new_logical;
6415 		}
6416 	}
6417 
6418 	/* we don't discard raid56 yet */
6419 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6420 		ret = -EOPNOTSUPP;
6421 		goto out_free_map;
6422 	}
6423 
6424 	offset = logical - map->start;
6425 	length = min_t(u64, map->start + map->chunk_len - logical, length);
6426 	*length_ret = length;
6427 
6428 	/*
6429 	 * stripe_nr counts the total number of stripes we have to stride
6430 	 * to get to this block
6431 	 */
6432 	stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6433 
6434 	/* stripe_offset is the offset of this block in its stripe */
6435 	stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
6436 
6437 	stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
6438 			BTRFS_STRIPE_LEN_SHIFT;
6439 	stripe_cnt = stripe_nr_end - stripe_nr;
6440 	stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
6441 			    (offset + length);
6442 	/*
6443 	 * after this, stripe_nr is the number of stripes on this
6444 	 * device we have to walk to find the data, and stripe_index is
6445 	 * the number of our device in the stripe array
6446 	 */
6447 	*num_stripes = 1;
6448 	stripe_index = 0;
6449 	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6450 			 BTRFS_BLOCK_GROUP_RAID10)) {
6451 		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6452 			sub_stripes = 1;
6453 		else
6454 			sub_stripes = map->sub_stripes;
6455 
6456 		factor = map->num_stripes / sub_stripes;
6457 		*num_stripes = min_t(u64, map->num_stripes,
6458 				    sub_stripes * stripe_cnt);
6459 		stripe_index = stripe_nr % factor;
6460 		stripe_nr /= factor;
6461 		stripe_index *= sub_stripes;
6462 
6463 		remaining_stripes = stripe_cnt % factor;
6464 		stripes_per_dev = stripe_cnt / factor;
6465 		last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
6466 	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6467 				BTRFS_BLOCK_GROUP_DUP)) {
6468 		*num_stripes = map->num_stripes;
6469 	} else {
6470 		stripe_index = stripe_nr % map->num_stripes;
6471 		stripe_nr /= map->num_stripes;
6472 	}
6473 
6474 	stripes = kzalloc_objs(*stripes, *num_stripes, GFP_NOFS);
6475 	if (!stripes) {
6476 		ret = -ENOMEM;
6477 		goto out_free_map;
6478 	}
6479 
6480 	for (i = 0; i < *num_stripes; i++) {
6481 		stripes[i].physical =
6482 			map->stripes[stripe_index].physical +
6483 			stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6484 		stripes[i].dev = map->stripes[stripe_index].dev;
6485 
6486 		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6487 				 BTRFS_BLOCK_GROUP_RAID10)) {
6488 			stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6489 
6490 			if (i / sub_stripes < remaining_stripes)
6491 				stripes[i].length += BTRFS_STRIPE_LEN;
6492 
6493 			/*
6494 			 * Special for the first stripe and
6495 			 * the last stripe:
6496 			 *
6497 			 * |-------|...|-------|
6498 			 *     |----------|
6499 			 *    off     end_off
6500 			 */
6501 			if (i < sub_stripes)
6502 				stripes[i].length -= stripe_offset;
6503 
6504 			if (stripe_index >= last_stripe &&
6505 			    stripe_index <= (last_stripe +
6506 					     sub_stripes - 1))
6507 				stripes[i].length -= stripe_end_offset;
6508 
6509 			if (i == sub_stripes - 1)
6510 				stripe_offset = 0;
6511 		} else {
6512 			stripes[i].length = length;
6513 		}
6514 
6515 		stripe_index++;
6516 		if (stripe_index == map->num_stripes) {
6517 			stripe_index = 0;
6518 			stripe_nr++;
6519 		}
6520 	}
6521 
6522 	btrfs_free_chunk_map(map);
6523 	return stripes;
6524 out_free_map:
6525 	btrfs_free_chunk_map(map);
6526 	return ERR_PTR(ret);
6527 }
6528 
is_block_group_to_copy(struct btrfs_fs_info * fs_info,u64 logical)6529 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6530 {
6531 	struct btrfs_block_group *cache;
6532 	bool ret;
6533 
6534 	/* Non zoned filesystem does not use "to_copy" flag */
6535 	if (!btrfs_is_zoned(fs_info))
6536 		return false;
6537 
6538 	cache = btrfs_lookup_block_group(fs_info, logical);
6539 
6540 	ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6541 
6542 	btrfs_put_block_group(cache);
6543 	return ret;
6544 }
6545 
handle_ops_on_dev_replace(struct btrfs_io_context * bioc,struct btrfs_dev_replace * dev_replace,u64 logical,struct btrfs_io_geometry * io_geom)6546 static void handle_ops_on_dev_replace(struct btrfs_io_context *bioc,
6547 				      struct btrfs_dev_replace *dev_replace,
6548 				      u64 logical,
6549 				      struct btrfs_io_geometry *io_geom)
6550 {
6551 	u64 srcdev_devid = dev_replace->srcdev->devid;
6552 	/*
6553 	 * At this stage, num_stripes is still the real number of stripes,
6554 	 * excluding the duplicated stripes.
6555 	 */
6556 	int num_stripes = io_geom->num_stripes;
6557 	int max_errors = io_geom->max_errors;
6558 	int nr_extra_stripes = 0;
6559 	int i;
6560 
6561 	/*
6562 	 * A block group which has "to_copy" set will eventually be copied by
6563 	 * the dev-replace process. We can avoid cloning IO here.
6564 	 */
6565 	if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6566 		return;
6567 
6568 	/*
6569 	 * Duplicate the write operations while the dev-replace procedure is
6570 	 * running. Since the copying of the old disk to the new disk takes
6571 	 * place at run time while the filesystem is mounted writable, the
6572 	 * regular write operations to the old disk have to be duplicated to go
6573 	 * to the new disk as well.
6574 	 *
6575 	 * Note that device->missing is handled by the caller, and that the
6576 	 * write to the old disk is already set up in the stripes array.
6577 	 */
6578 	for (i = 0; i < num_stripes; i++) {
6579 		struct btrfs_io_stripe *old = &bioc->stripes[i];
6580 		struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6581 
6582 		if (old->dev->devid != srcdev_devid)
6583 			continue;
6584 
6585 		new->physical = old->physical;
6586 		new->dev = dev_replace->tgtdev;
6587 		if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6588 			bioc->replace_stripe_src = i;
6589 		nr_extra_stripes++;
6590 	}
6591 
6592 	/* We can only have at most 2 extra nr_stripes (for DUP). */
6593 	ASSERT(nr_extra_stripes <= 2, "nr_extra_stripes=%d", nr_extra_stripes);
6594 	/*
6595 	 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6596 	 * replace.
6597 	 * If we have 2 extra stripes, only choose the one with smaller physical.
6598 	 */
6599 	if (io_geom->op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6600 		struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6601 		struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6602 
6603 		/* Only DUP can have two extra stripes. */
6604 		ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP,
6605 		       "map_type=%llu", bioc->map_type);
6606 
6607 		/*
6608 		 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6609 		 * The extra stripe would still be there, but won't be accessed.
6610 		 */
6611 		if (first->physical > second->physical) {
6612 			swap(second->physical, first->physical);
6613 			swap(second->dev, first->dev);
6614 			nr_extra_stripes--;
6615 		}
6616 	}
6617 
6618 	io_geom->num_stripes = num_stripes + nr_extra_stripes;
6619 	io_geom->max_errors = max_errors + nr_extra_stripes;
6620 	bioc->replace_nr_stripes = nr_extra_stripes;
6621 }
6622 
btrfs_max_io_len(struct btrfs_chunk_map * map,u64 offset,struct btrfs_io_geometry * io_geom)6623 static u64 btrfs_max_io_len(struct btrfs_chunk_map *map, u64 offset,
6624 			    struct btrfs_io_geometry *io_geom)
6625 {
6626 	/*
6627 	 * Stripe_nr is the stripe where this block falls.  stripe_offset is
6628 	 * the offset of this block in its stripe.
6629 	 */
6630 	io_geom->stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6631 	io_geom->stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6632 	ASSERT(io_geom->stripe_offset < U32_MAX,
6633 	       "stripe_offset=%llu", io_geom->stripe_offset);
6634 
6635 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6636 		unsigned long full_stripe_len =
6637 			btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6638 
6639 		/*
6640 		 * For full stripe start, we use previously calculated
6641 		 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6642 		 * STRIPE_LEN.
6643 		 *
6644 		 * By this we can avoid u64 division completely.  And we have
6645 		 * to go rounddown(), not round_down(), as nr_data_stripes is
6646 		 * not ensured to be power of 2.
6647 		 */
6648 		io_geom->raid56_full_stripe_start = btrfs_stripe_nr_to_offset(
6649 			rounddown(io_geom->stripe_nr, nr_data_stripes(map)));
6650 
6651 		ASSERT(io_geom->raid56_full_stripe_start + full_stripe_len > offset,
6652 		       "raid56_full_stripe_start=%llu full_stripe_len=%lu offset=%llu",
6653 		       io_geom->raid56_full_stripe_start, full_stripe_len, offset);
6654 		ASSERT(io_geom->raid56_full_stripe_start <= offset,
6655 		       "raid56_full_stripe_start=%llu offset=%llu",
6656 		       io_geom->raid56_full_stripe_start, offset);
6657 		/*
6658 		 * For writes to RAID56, allow to write a full stripe set, but
6659 		 * no straddling of stripe sets.
6660 		 */
6661 		if (io_geom->op == BTRFS_MAP_WRITE)
6662 			return full_stripe_len - (offset - io_geom->raid56_full_stripe_start);
6663 	}
6664 
6665 	/*
6666 	 * For other RAID types and for RAID56 reads, allow a single stripe (on
6667 	 * a single disk).
6668 	 */
6669 	if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6670 		return BTRFS_STRIPE_LEN - io_geom->stripe_offset;
6671 	return U64_MAX;
6672 }
6673 
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)6674 static int set_io_stripe(struct btrfs_fs_info *fs_info, u64 logical,
6675 			 u64 *length, struct btrfs_io_stripe *dst,
6676 			 struct btrfs_chunk_map *map,
6677 			 struct btrfs_io_geometry *io_geom)
6678 {
6679 	dst->dev = map->stripes[io_geom->stripe_index].dev;
6680 
6681 	if (io_geom->op == BTRFS_MAP_READ && io_geom->use_rst)
6682 		return btrfs_get_raid_extent_offset(fs_info, logical, length,
6683 						    map->type,
6684 						    io_geom->stripe_index, dst);
6685 
6686 	dst->physical = map->stripes[io_geom->stripe_index].physical +
6687 			io_geom->stripe_offset +
6688 			btrfs_stripe_nr_to_offset(io_geom->stripe_nr);
6689 	return 0;
6690 }
6691 
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)6692 static bool is_single_device_io(struct btrfs_fs_info *fs_info,
6693 				const struct btrfs_io_stripe *smap,
6694 				const struct btrfs_chunk_map *map,
6695 				int num_alloc_stripes,
6696 				struct btrfs_io_geometry *io_geom)
6697 {
6698 	if (!smap)
6699 		return false;
6700 
6701 	if (num_alloc_stripes != 1)
6702 		return false;
6703 
6704 	if (io_geom->use_rst && io_geom->op != BTRFS_MAP_READ)
6705 		return false;
6706 
6707 	if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && io_geom->mirror_num > 1)
6708 		return false;
6709 
6710 	return true;
6711 }
6712 
map_blocks_raid0(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6713 static void map_blocks_raid0(const struct btrfs_chunk_map *map,
6714 			     struct btrfs_io_geometry *io_geom)
6715 {
6716 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6717 	io_geom->stripe_nr /= map->num_stripes;
6718 	if (io_geom->op == BTRFS_MAP_READ)
6719 		io_geom->mirror_num = 1;
6720 }
6721 
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)6722 static void map_blocks_raid1(struct btrfs_fs_info *fs_info,
6723 			     struct btrfs_chunk_map *map,
6724 			     struct btrfs_io_geometry *io_geom,
6725 			     bool dev_replace_is_ongoing)
6726 {
6727 	if (io_geom->op != BTRFS_MAP_READ) {
6728 		io_geom->num_stripes = map->num_stripes;
6729 		return;
6730 	}
6731 
6732 	if (io_geom->mirror_num) {
6733 		io_geom->stripe_index = io_geom->mirror_num - 1;
6734 		return;
6735 	}
6736 
6737 	io_geom->stripe_index = find_live_mirror(fs_info, map, 0,
6738 						 dev_replace_is_ongoing);
6739 	io_geom->mirror_num = io_geom->stripe_index + 1;
6740 }
6741 
map_blocks_dup(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6742 static void map_blocks_dup(const struct btrfs_chunk_map *map,
6743 			   struct btrfs_io_geometry *io_geom)
6744 {
6745 	if (io_geom->op != BTRFS_MAP_READ) {
6746 		io_geom->num_stripes = map->num_stripes;
6747 		return;
6748 	}
6749 
6750 	if (io_geom->mirror_num) {
6751 		io_geom->stripe_index = io_geom->mirror_num - 1;
6752 		return;
6753 	}
6754 
6755 	io_geom->mirror_num = 1;
6756 }
6757 
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)6758 static void map_blocks_raid10(struct btrfs_fs_info *fs_info,
6759 			      struct btrfs_chunk_map *map,
6760 			      struct btrfs_io_geometry *io_geom,
6761 			      bool dev_replace_is_ongoing)
6762 {
6763 	u32 factor = map->num_stripes / map->sub_stripes;
6764 	int old_stripe_index;
6765 
6766 	io_geom->stripe_index = (io_geom->stripe_nr % factor) * map->sub_stripes;
6767 	io_geom->stripe_nr /= factor;
6768 
6769 	if (io_geom->op != BTRFS_MAP_READ) {
6770 		io_geom->num_stripes = map->sub_stripes;
6771 		return;
6772 	}
6773 
6774 	if (io_geom->mirror_num) {
6775 		io_geom->stripe_index += io_geom->mirror_num - 1;
6776 		return;
6777 	}
6778 
6779 	old_stripe_index = io_geom->stripe_index;
6780 	io_geom->stripe_index = find_live_mirror(fs_info, map,
6781 						 io_geom->stripe_index,
6782 						 dev_replace_is_ongoing);
6783 	io_geom->mirror_num = io_geom->stripe_index - old_stripe_index + 1;
6784 }
6785 
map_blocks_raid56_write(struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom,u64 logical,u64 * length)6786 static void map_blocks_raid56_write(struct btrfs_chunk_map *map,
6787 				    struct btrfs_io_geometry *io_geom,
6788 				    u64 logical, u64 *length)
6789 {
6790 	int data_stripes = nr_data_stripes(map);
6791 
6792 	/*
6793 	 * Needs full stripe mapping.
6794 	 *
6795 	 * Push stripe_nr back to the start of the full stripe For those cases
6796 	 * needing a full stripe, @stripe_nr is the full stripe number.
6797 	 *
6798 	 * Originally we go raid56_full_stripe_start / full_stripe_len, but
6799 	 * that can be expensive.  Here we just divide @stripe_nr with
6800 	 * @data_stripes.
6801 	 */
6802 	io_geom->stripe_nr /= data_stripes;
6803 
6804 	/* RAID[56] write or recovery. Return all stripes */
6805 	io_geom->num_stripes = map->num_stripes;
6806 	io_geom->max_errors = btrfs_chunk_max_errors(map);
6807 
6808 	/* Return the length to the full stripe end. */
6809 	*length = min(logical + *length,
6810 		      io_geom->raid56_full_stripe_start + map->start +
6811 		      btrfs_stripe_nr_to_offset(data_stripes)) -
6812 		logical;
6813 	io_geom->stripe_index = 0;
6814 	io_geom->stripe_offset = 0;
6815 }
6816 
map_blocks_raid56_read(struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6817 static void map_blocks_raid56_read(struct btrfs_chunk_map *map,
6818 				   struct btrfs_io_geometry *io_geom)
6819 {
6820 	int data_stripes = nr_data_stripes(map);
6821 
6822 	ASSERT(io_geom->mirror_num <= 1, "mirror_num=%d", io_geom->mirror_num);
6823 	/* Just grab the data stripe directly. */
6824 	io_geom->stripe_index = io_geom->stripe_nr % data_stripes;
6825 	io_geom->stripe_nr /= data_stripes;
6826 
6827 	/* We distribute the parity blocks across stripes. */
6828 	io_geom->stripe_index =
6829 		(io_geom->stripe_nr + io_geom->stripe_index) % map->num_stripes;
6830 
6831 	if (io_geom->op == BTRFS_MAP_READ && io_geom->mirror_num < 1)
6832 		io_geom->mirror_num = 1;
6833 }
6834 
map_blocks_single(const struct btrfs_chunk_map * map,struct btrfs_io_geometry * io_geom)6835 static void map_blocks_single(const struct btrfs_chunk_map *map,
6836 			      struct btrfs_io_geometry *io_geom)
6837 {
6838 	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6839 	io_geom->stripe_nr /= map->num_stripes;
6840 	io_geom->mirror_num = io_geom->stripe_index + 1;
6841 }
6842 
6843 /*
6844  * Map one logical range to one or more physical ranges.
6845  *
6846  * @length:		(Mandatory) mapped length of this run.
6847  *			One logical range can be split into different segments
6848  *			due to factors like zones and RAID0/5/6/10 stripe
6849  *			boundaries.
6850  *
6851  * @bioc_ret:		(Mandatory) returned btrfs_io_context structure.
6852  *			which has one or more physical ranges (btrfs_io_stripe)
6853  *			recorded inside.
6854  *			Caller should call btrfs_put_bioc() to free it after use.
6855  *
6856  * @smap:		(Optional) single physical range optimization.
6857  *			If the map request can be fulfilled by one single
6858  *			physical range, and this is parameter is not NULL,
6859  *			then @bioc_ret would be NULL, and @smap would be
6860  *			updated.
6861  *
6862  * @mirror_num_ret:	(Mandatory) returned mirror number if the original
6863  *			value is 0.
6864  *
6865  *			Mirror number 0 means to choose any live mirrors.
6866  *
6867  *			For non-RAID56 profiles, non-zero mirror_num means
6868  *			the Nth mirror. (e.g. mirror_num 1 means the first
6869  *			copy).
6870  *
6871  *			For RAID56 profile, mirror 1 means rebuild from P and
6872  *			the remaining data stripes.
6873  *
6874  *			For RAID6 profile, mirror > 2 means mark another
6875  *			data/P stripe error and rebuild from the remaining
6876  *			stripes..
6877  */
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)6878 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6879 		    u64 logical, u64 *length,
6880 		    struct btrfs_io_context **bioc_ret,
6881 		    struct btrfs_io_stripe *smap, int *mirror_num_ret)
6882 {
6883 	struct btrfs_chunk_map *map;
6884 	struct btrfs_io_geometry io_geom = { 0 };
6885 	u64 map_offset;
6886 	int ret = 0;
6887 	int num_copies;
6888 	struct btrfs_io_context *bioc = NULL;
6889 	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6890 	bool dev_replace_is_ongoing = false;
6891 	u16 num_alloc_stripes;
6892 	u64 max_len;
6893 
6894 	ASSERT(bioc_ret);
6895 
6896 	io_geom.mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6897 	io_geom.num_stripes = 1;
6898 	io_geom.stripe_index = 0;
6899 	io_geom.op = op;
6900 
6901 	map = btrfs_get_chunk_map(fs_info, logical, *length);
6902 	if (IS_ERR(map))
6903 		return PTR_ERR(map);
6904 
6905 	if (map->type & BTRFS_BLOCK_GROUP_REMAPPED) {
6906 		u64 new_logical = logical;
6907 
6908 		ret = btrfs_translate_remap(fs_info, &new_logical, length);
6909 		if (ret)
6910 			return ret;
6911 
6912 		if (new_logical != logical) {
6913 			btrfs_free_chunk_map(map);
6914 
6915 			map = btrfs_get_chunk_map(fs_info, new_logical, *length);
6916 			if (IS_ERR(map))
6917 				return PTR_ERR(map);
6918 
6919 			logical = new_logical;
6920 		}
6921 	}
6922 
6923 	num_copies = btrfs_chunk_map_num_copies(map);
6924 	if (io_geom.mirror_num > num_copies)
6925 		return -EINVAL;
6926 
6927 	map_offset = logical - map->start;
6928 	io_geom.raid56_full_stripe_start = (u64)-1;
6929 	max_len = btrfs_max_io_len(map, map_offset, &io_geom);
6930 	*length = min_t(u64, map->chunk_len - map_offset, max_len);
6931 	io_geom.use_rst = btrfs_need_stripe_tree_update(fs_info, map->type);
6932 
6933 	if (dev_replace->replace_task != current)
6934 		down_read(&dev_replace->rwsem);
6935 
6936 	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6937 	/*
6938 	 * Hold the semaphore for read during the whole operation, write is
6939 	 * requested at commit time but must wait.
6940 	 */
6941 	if (!dev_replace_is_ongoing && dev_replace->replace_task != current)
6942 		up_read(&dev_replace->rwsem);
6943 
6944 	switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6945 	case BTRFS_BLOCK_GROUP_RAID0:
6946 		map_blocks_raid0(map, &io_geom);
6947 		break;
6948 	case BTRFS_BLOCK_GROUP_RAID1:
6949 	case BTRFS_BLOCK_GROUP_RAID1C3:
6950 	case BTRFS_BLOCK_GROUP_RAID1C4:
6951 		map_blocks_raid1(fs_info, map, &io_geom, dev_replace_is_ongoing);
6952 		break;
6953 	case BTRFS_BLOCK_GROUP_DUP:
6954 		map_blocks_dup(map, &io_geom);
6955 		break;
6956 	case BTRFS_BLOCK_GROUP_RAID10:
6957 		map_blocks_raid10(fs_info, map, &io_geom, dev_replace_is_ongoing);
6958 		break;
6959 	case BTRFS_BLOCK_GROUP_RAID5:
6960 	case BTRFS_BLOCK_GROUP_RAID6:
6961 		if (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)
6962 			map_blocks_raid56_write(map, &io_geom, logical, length);
6963 		else
6964 			map_blocks_raid56_read(map, &io_geom);
6965 		break;
6966 	default:
6967 		/*
6968 		 * After this, stripe_nr is the number of stripes on this
6969 		 * device we have to walk to find the data, and stripe_index is
6970 		 * the number of our device in the stripe array
6971 		 */
6972 		map_blocks_single(map, &io_geom);
6973 		break;
6974 	}
6975 	if (io_geom.stripe_index >= map->num_stripes) {
6976 		btrfs_crit(fs_info,
6977 			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6978 			   io_geom.stripe_index, map->num_stripes);
6979 		ret = -EINVAL;
6980 		goto out;
6981 	}
6982 
6983 	num_alloc_stripes = io_geom.num_stripes;
6984 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6985 	    op != BTRFS_MAP_READ)
6986 		/*
6987 		 * For replace case, we need to add extra stripes for extra
6988 		 * duplicated stripes.
6989 		 *
6990 		 * For both WRITE and GET_READ_MIRRORS, we may have at most
6991 		 * 2 more stripes (DUP types, otherwise 1).
6992 		 */
6993 		num_alloc_stripes += 2;
6994 
6995 	/*
6996 	 * If this I/O maps to a single device, try to return the device and
6997 	 * physical block information on the stack instead of allocating an
6998 	 * I/O context structure.
6999 	 */
7000 	if (is_single_device_io(fs_info, smap, map, num_alloc_stripes, &io_geom)) {
7001 		ret = set_io_stripe(fs_info, logical, length, smap, map, &io_geom);
7002 		if (mirror_num_ret)
7003 			*mirror_num_ret = io_geom.mirror_num;
7004 		*bioc_ret = NULL;
7005 		goto out;
7006 	}
7007 
7008 	bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
7009 	if (!bioc) {
7010 		ret = -ENOMEM;
7011 		goto out;
7012 	}
7013 	bioc->map_type = map->type;
7014 	bioc->use_rst = io_geom.use_rst;
7015 
7016 	/*
7017 	 * For RAID56 full map, we need to make sure the stripes[] follows the
7018 	 * rule that data stripes are all ordered, then followed with P and Q
7019 	 * (if we have).
7020 	 *
7021 	 * It's still mostly the same as other profiles, just with extra rotation.
7022 	 */
7023 	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
7024 	    (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)) {
7025 		/*
7026 		 * For RAID56 @stripe_nr is already the number of full stripes
7027 		 * before us, which is also the rotation value (needs to modulo
7028 		 * with num_stripes).
7029 		 *
7030 		 * In this case, we just add @stripe_nr with @i, then do the
7031 		 * modulo, to reduce one modulo call.
7032 		 */
7033 		bioc->full_stripe_logical = map->start +
7034 			btrfs_stripe_nr_to_offset(io_geom.stripe_nr *
7035 						  nr_data_stripes(map));
7036 		for (int i = 0; i < io_geom.num_stripes; i++) {
7037 			struct btrfs_io_stripe *dst = &bioc->stripes[i];
7038 			u32 stripe_index;
7039 
7040 			stripe_index = (i + io_geom.stripe_nr) % io_geom.num_stripes;
7041 			dst->dev = map->stripes[stripe_index].dev;
7042 			dst->physical =
7043 				map->stripes[stripe_index].physical +
7044 				io_geom.stripe_offset +
7045 				btrfs_stripe_nr_to_offset(io_geom.stripe_nr);
7046 		}
7047 	} else {
7048 		/*
7049 		 * For all other non-RAID56 profiles, just copy the target
7050 		 * stripe into the bioc.
7051 		 */
7052 		for (int i = 0; i < io_geom.num_stripes; i++) {
7053 			ret = set_io_stripe(fs_info, logical, length,
7054 					    &bioc->stripes[i], map, &io_geom);
7055 			if (ret < 0)
7056 				break;
7057 			io_geom.stripe_index++;
7058 		}
7059 	}
7060 
7061 	if (ret) {
7062 		*bioc_ret = NULL;
7063 		btrfs_put_bioc(bioc);
7064 		goto out;
7065 	}
7066 
7067 	if (op != BTRFS_MAP_READ)
7068 		io_geom.max_errors = btrfs_chunk_max_errors(map);
7069 
7070 	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
7071 	    op != BTRFS_MAP_READ) {
7072 		handle_ops_on_dev_replace(bioc, dev_replace, logical, &io_geom);
7073 	}
7074 
7075 	*bioc_ret = bioc;
7076 	bioc->num_stripes = io_geom.num_stripes;
7077 	bioc->max_errors = io_geom.max_errors;
7078 	bioc->mirror_num = io_geom.mirror_num;
7079 
7080 out:
7081 	if (dev_replace_is_ongoing && dev_replace->replace_task != current) {
7082 		lockdep_assert_held(&dev_replace->rwsem);
7083 		/* Unlock and let waiting writers proceed */
7084 		up_read(&dev_replace->rwsem);
7085 	}
7086 	btrfs_free_chunk_map(map);
7087 	return ret;
7088 }
7089 
dev_args_match_fs_devices(const struct btrfs_dev_lookup_args * args,const struct btrfs_fs_devices * fs_devices)7090 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
7091 				      const struct btrfs_fs_devices *fs_devices)
7092 {
7093 	if (args->fsid == NULL)
7094 		return true;
7095 	if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
7096 		return true;
7097 	return false;
7098 }
7099 
dev_args_match_device(const struct btrfs_dev_lookup_args * args,const struct btrfs_device * device)7100 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
7101 				  const struct btrfs_device *device)
7102 {
7103 	if (args->devt)
7104 		return device->devt == args->devt;
7105 	if (args->missing) {
7106 		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
7107 		    !device->bdev)
7108 			return true;
7109 		return false;
7110 	}
7111 
7112 	if (device->devid != args->devid)
7113 		return false;
7114 	if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
7115 		return false;
7116 	return true;
7117 }
7118 
7119 /*
7120  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
7121  * return NULL.
7122  *
7123  * If devid and uuid are both specified, the match must be exact, otherwise
7124  * only devid is used.
7125  */
btrfs_find_device(const struct btrfs_fs_devices * fs_devices,const struct btrfs_dev_lookup_args * args)7126 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
7127 				       const struct btrfs_dev_lookup_args *args)
7128 {
7129 	struct btrfs_device *device;
7130 	struct btrfs_fs_devices *seed_devs;
7131 
7132 	if (dev_args_match_fs_devices(args, fs_devices)) {
7133 		list_for_each_entry(device, &fs_devices->devices, dev_list) {
7134 			if (dev_args_match_device(args, device))
7135 				return device;
7136 		}
7137 	}
7138 
7139 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7140 		if (!dev_args_match_fs_devices(args, seed_devs))
7141 			continue;
7142 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7143 			if (dev_args_match_device(args, device))
7144 				return device;
7145 		}
7146 	}
7147 
7148 	return NULL;
7149 }
7150 
add_missing_dev(struct btrfs_fs_devices * fs_devices,u64 devid,u8 * dev_uuid)7151 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
7152 					    u64 devid, u8 *dev_uuid)
7153 {
7154 	struct btrfs_device *device;
7155 	unsigned int nofs_flag;
7156 
7157 	/*
7158 	 * We call this under the chunk_mutex, so we want to use NOFS for this
7159 	 * allocation, however we don't want to change btrfs_alloc_device() to
7160 	 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
7161 	 * places.
7162 	 */
7163 
7164 	nofs_flag = memalloc_nofs_save();
7165 	device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
7166 	memalloc_nofs_restore(nofs_flag);
7167 	if (IS_ERR(device))
7168 		return device;
7169 
7170 	list_add(&device->dev_list, &fs_devices->devices);
7171 	device->fs_devices = fs_devices;
7172 	fs_devices->num_devices++;
7173 
7174 	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7175 	fs_devices->missing_devices++;
7176 
7177 	return device;
7178 }
7179 
7180 /*
7181  * Allocate new device struct, set up devid and UUID.
7182  *
7183  * @fs_info:	used only for generating a new devid, can be NULL if
7184  *		devid is provided (i.e. @devid != NULL).
7185  * @devid:	a pointer to devid for this device.  If NULL a new devid
7186  *		is generated.
7187  * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
7188  *		is generated.
7189  * @path:	a pointer to device path if available, NULL otherwise.
7190  *
7191  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
7192  * on error.  Returned struct is not linked onto any lists and must be
7193  * destroyed with btrfs_free_device.
7194  */
btrfs_alloc_device(struct btrfs_fs_info * fs_info,const u64 * devid,const u8 * uuid,const char * path)7195 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
7196 					const u64 *devid, const u8 *uuid,
7197 					const char *path)
7198 {
7199 	struct btrfs_device *dev;
7200 	u64 tmp;
7201 
7202 	if (WARN_ON(!devid && !fs_info))
7203 		return ERR_PTR(-EINVAL);
7204 
7205 	dev = kzalloc_obj(*dev);
7206 	if (!dev)
7207 		return ERR_PTR(-ENOMEM);
7208 
7209 	INIT_LIST_HEAD(&dev->dev_list);
7210 	INIT_LIST_HEAD(&dev->dev_alloc_list);
7211 	INIT_LIST_HEAD(&dev->post_commit_list);
7212 
7213 	atomic_set(&dev->dev_stats_ccnt, 0);
7214 	btrfs_device_data_ordered_init(dev);
7215 	btrfs_extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
7216 
7217 	if (devid)
7218 		tmp = *devid;
7219 	else {
7220 		int ret;
7221 
7222 		ret = find_next_devid(fs_info, &tmp);
7223 		if (ret) {
7224 			btrfs_free_device(dev);
7225 			return ERR_PTR(ret);
7226 		}
7227 	}
7228 	dev->devid = tmp;
7229 
7230 	if (uuid)
7231 		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
7232 	else
7233 		generate_random_uuid(dev->uuid);
7234 
7235 	if (path) {
7236 		const char *name;
7237 
7238 		name = kstrdup(path, GFP_KERNEL);
7239 		if (!name) {
7240 			btrfs_free_device(dev);
7241 			return ERR_PTR(-ENOMEM);
7242 		}
7243 		rcu_assign_pointer(dev->name, name);
7244 	}
7245 
7246 	return dev;
7247 }
7248 
btrfs_report_missing_device(struct btrfs_fs_info * fs_info,u64 devid,u8 * uuid,bool error)7249 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
7250 					u64 devid, u8 *uuid, bool error)
7251 {
7252 	if (error)
7253 		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
7254 			      devid, uuid);
7255 	else
7256 		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
7257 			      devid, uuid);
7258 }
7259 
btrfs_calc_stripe_length(const struct btrfs_chunk_map * map)7260 u64 btrfs_calc_stripe_length(const struct btrfs_chunk_map *map)
7261 {
7262 	const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
7263 
7264 	return div_u64(map->chunk_len, data_stripes);
7265 }
7266 
7267 #if BITS_PER_LONG == 32
7268 /*
7269  * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
7270  * can't be accessed on 32bit systems.
7271  *
7272  * This function do mount time check to reject the fs if it already has
7273  * metadata chunk beyond that limit.
7274  */
check_32bit_meta_chunk(struct btrfs_fs_info * fs_info,u64 logical,u64 length,u64 type)7275 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7276 				  u64 logical, u64 length, u64 type)
7277 {
7278 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7279 		return 0;
7280 
7281 	if (logical + length < MAX_LFS_FILESIZE)
7282 		return 0;
7283 
7284 	btrfs_err_32bit_limit(fs_info);
7285 	return -EOVERFLOW;
7286 }
7287 
7288 /*
7289  * This is to give early warning for any metadata chunk reaching
7290  * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7291  * Although we can still access the metadata, it's not going to be possible
7292  * once the limit is reached.
7293  */
warn_32bit_meta_chunk(struct btrfs_fs_info * fs_info,u64 logical,u64 length,u64 type)7294 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7295 				  u64 logical, u64 length, u64 type)
7296 {
7297 	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7298 		return;
7299 
7300 	if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7301 		return;
7302 
7303 	btrfs_warn_32bit_limit(fs_info);
7304 }
7305 #endif
7306 
handle_missing_device(struct btrfs_fs_info * fs_info,u64 devid,u8 * uuid)7307 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7308 						  u64 devid, u8 *uuid)
7309 {
7310 	struct btrfs_device *dev;
7311 
7312 	if (!btrfs_test_opt(fs_info, DEGRADED)) {
7313 		btrfs_report_missing_device(fs_info, devid, uuid, true);
7314 		return ERR_PTR(-ENOENT);
7315 	}
7316 
7317 	dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7318 	if (IS_ERR(dev)) {
7319 		btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7320 			  devid, PTR_ERR(dev));
7321 		return dev;
7322 	}
7323 	btrfs_report_missing_device(fs_info, devid, uuid, false);
7324 
7325 	return dev;
7326 }
7327 
read_one_chunk(struct btrfs_key * key,struct extent_buffer * leaf,struct btrfs_chunk * chunk)7328 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7329 			  struct btrfs_chunk *chunk)
7330 {
7331 	BTRFS_DEV_LOOKUP_ARGS(args);
7332 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7333 	struct btrfs_chunk_map *map;
7334 	u64 logical;
7335 	u64 length;
7336 	u64 devid;
7337 	u64 type;
7338 	u8 uuid[BTRFS_UUID_SIZE];
7339 	int index;
7340 	int num_stripes;
7341 	int ret;
7342 	int i;
7343 
7344 	logical = key->offset;
7345 	length = btrfs_chunk_length(leaf, chunk);
7346 	type = btrfs_chunk_type(leaf, chunk);
7347 	index = btrfs_bg_flags_to_raid_index(type);
7348 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7349 
7350 #if BITS_PER_LONG == 32
7351 	ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7352 	if (ret < 0)
7353 		return ret;
7354 	warn_32bit_meta_chunk(fs_info, logical, length, type);
7355 #endif
7356 
7357 	map = btrfs_find_chunk_map(fs_info, logical, 1);
7358 
7359 	/* already mapped? */
7360 	if (map && map->start <= logical && map->start + map->chunk_len > logical) {
7361 		btrfs_free_chunk_map(map);
7362 		return 0;
7363 	} else if (map) {
7364 		btrfs_free_chunk_map(map);
7365 	}
7366 
7367 	map = btrfs_alloc_chunk_map(num_stripes, GFP_NOFS);
7368 	if (!map)
7369 		return -ENOMEM;
7370 
7371 	map->start = logical;
7372 	map->chunk_len = length;
7373 	map->num_stripes = num_stripes;
7374 	map->io_width = btrfs_chunk_io_width(leaf, chunk);
7375 	map->io_align = btrfs_chunk_io_align(leaf, chunk);
7376 	map->type = type;
7377 	/*
7378 	 * We can't use the sub_stripes value, as for profiles other than
7379 	 * RAID10, they may have 0 as sub_stripes for filesystems created by
7380 	 * older mkfs (<v5.4).
7381 	 * In that case, it can cause divide-by-zero errors later.
7382 	 * Since currently sub_stripes is fixed for each profile, let's
7383 	 * use the trusted value instead.
7384 	 */
7385 	map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7386 	map->verified_stripes = 0;
7387 
7388 	if (num_stripes > 0)
7389 		map->stripe_size = btrfs_calc_stripe_length(map);
7390 	else
7391 		map->stripe_size = 0;
7392 
7393 	for (i = 0; i < num_stripes; i++) {
7394 		map->stripes[i].physical =
7395 			btrfs_stripe_offset_nr(leaf, chunk, i);
7396 		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7397 		args.devid = devid;
7398 		read_extent_buffer(leaf, uuid, (unsigned long)
7399 				   btrfs_stripe_dev_uuid_nr(chunk, i),
7400 				   BTRFS_UUID_SIZE);
7401 		args.uuid = uuid;
7402 		map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7403 		if (!map->stripes[i].dev) {
7404 			map->stripes[i].dev = handle_missing_device(fs_info,
7405 								    devid, uuid);
7406 			if (IS_ERR(map->stripes[i].dev)) {
7407 				ret = PTR_ERR(map->stripes[i].dev);
7408 				btrfs_free_chunk_map(map);
7409 				return ret;
7410 			}
7411 		}
7412 
7413 		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7414 				&(map->stripes[i].dev->dev_state));
7415 	}
7416 
7417 	ret = btrfs_add_chunk_map(fs_info, map);
7418 	if (ret < 0) {
7419 		btrfs_err(fs_info,
7420 			  "failed to add chunk map, start=%llu len=%llu: %d",
7421 			  map->start, map->chunk_len, ret);
7422 		btrfs_free_chunk_map(map);
7423 	}
7424 
7425 	return ret;
7426 }
7427 
fill_device_from_item(struct extent_buffer * leaf,struct btrfs_dev_item * dev_item,struct btrfs_device * device)7428 static void fill_device_from_item(struct extent_buffer *leaf,
7429 				 struct btrfs_dev_item *dev_item,
7430 				 struct btrfs_device *device)
7431 {
7432 	unsigned long ptr;
7433 
7434 	device->devid = btrfs_device_id(leaf, dev_item);
7435 	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7436 	device->total_bytes = device->disk_total_bytes;
7437 	device->commit_total_bytes = device->disk_total_bytes;
7438 	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7439 	device->commit_bytes_used = device->bytes_used;
7440 	device->type = btrfs_device_type(leaf, dev_item);
7441 	device->io_align = btrfs_device_io_align(leaf, dev_item);
7442 	device->io_width = btrfs_device_io_width(leaf, dev_item);
7443 	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7444 	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7445 	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7446 
7447 	ptr = btrfs_device_uuid(dev_item);
7448 	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7449 }
7450 
open_seed_devices(struct btrfs_fs_info * fs_info,u8 * fsid)7451 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7452 						  u8 *fsid)
7453 {
7454 	struct btrfs_fs_devices *fs_devices;
7455 	int ret;
7456 
7457 	lockdep_assert_held(&uuid_mutex);
7458 	ASSERT(fsid);
7459 
7460 	/* This will match only for multi-device seed fs */
7461 	list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7462 		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7463 			return fs_devices;
7464 
7465 
7466 	fs_devices = find_fsid(fsid, NULL);
7467 	if (!fs_devices) {
7468 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7469 			btrfs_err(fs_info,
7470 		"failed to find fsid %pU when attempting to open seed devices",
7471 				  fsid);
7472 			return ERR_PTR(-ENOENT);
7473 		}
7474 
7475 		fs_devices = alloc_fs_devices(fsid);
7476 		if (IS_ERR(fs_devices))
7477 			return fs_devices;
7478 
7479 		fs_devices->seeding = true;
7480 		fs_devices->opened = 1;
7481 		list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7482 		return fs_devices;
7483 	}
7484 
7485 	/*
7486 	 * Upon first call for a seed fs fsid, just create a private copy of the
7487 	 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7488 	 */
7489 	fs_devices = clone_fs_devices(fs_devices);
7490 	if (IS_ERR(fs_devices))
7491 		return fs_devices;
7492 
7493 	ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->sb);
7494 	if (ret) {
7495 		free_fs_devices(fs_devices);
7496 		return ERR_PTR(ret);
7497 	}
7498 
7499 	if (!fs_devices->seeding) {
7500 		close_fs_devices(fs_devices);
7501 		free_fs_devices(fs_devices);
7502 		return ERR_PTR(-EINVAL);
7503 	}
7504 
7505 	list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7506 
7507 	return fs_devices;
7508 }
7509 
read_one_dev(struct extent_buffer * leaf,struct btrfs_dev_item * dev_item)7510 static int read_one_dev(struct extent_buffer *leaf,
7511 			struct btrfs_dev_item *dev_item)
7512 {
7513 	BTRFS_DEV_LOOKUP_ARGS(args);
7514 	struct btrfs_fs_info *fs_info = leaf->fs_info;
7515 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7516 	struct btrfs_device *device;
7517 	u64 devid;
7518 	u8 fs_uuid[BTRFS_FSID_SIZE];
7519 	u8 dev_uuid[BTRFS_UUID_SIZE];
7520 
7521 	devid = btrfs_device_id(leaf, dev_item);
7522 	args.devid = devid;
7523 	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7524 			   BTRFS_UUID_SIZE);
7525 	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7526 			   BTRFS_FSID_SIZE);
7527 	args.uuid = dev_uuid;
7528 	args.fsid = fs_uuid;
7529 
7530 	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7531 		fs_devices = open_seed_devices(fs_info, fs_uuid);
7532 		if (IS_ERR(fs_devices))
7533 			return PTR_ERR(fs_devices);
7534 	}
7535 
7536 	device = btrfs_find_device(fs_info->fs_devices, &args);
7537 	if (!device) {
7538 		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7539 			btrfs_report_missing_device(fs_info, devid,
7540 							dev_uuid, true);
7541 			return -ENOENT;
7542 		}
7543 
7544 		device = add_missing_dev(fs_devices, devid, dev_uuid);
7545 		if (IS_ERR(device)) {
7546 			btrfs_err(fs_info,
7547 				"failed to add missing dev %llu: %ld",
7548 				devid, PTR_ERR(device));
7549 			return PTR_ERR(device);
7550 		}
7551 		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7552 	} else {
7553 		if (!device->bdev) {
7554 			if (!btrfs_test_opt(fs_info, DEGRADED)) {
7555 				btrfs_report_missing_device(fs_info,
7556 						devid, dev_uuid, true);
7557 				return -ENOENT;
7558 			}
7559 			btrfs_report_missing_device(fs_info, devid,
7560 							dev_uuid, false);
7561 		}
7562 
7563 		if (!device->bdev &&
7564 		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7565 			/*
7566 			 * this happens when a device that was properly setup
7567 			 * in the device info lists suddenly goes bad.
7568 			 * device->bdev is NULL, and so we have to set
7569 			 * device->missing to one here
7570 			 */
7571 			device->fs_devices->missing_devices++;
7572 			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7573 		}
7574 
7575 		/* Move the device to its own fs_devices */
7576 		if (device->fs_devices != fs_devices) {
7577 			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7578 							&device->dev_state));
7579 
7580 			list_move(&device->dev_list, &fs_devices->devices);
7581 			device->fs_devices->num_devices--;
7582 			fs_devices->num_devices++;
7583 
7584 			device->fs_devices->missing_devices--;
7585 			fs_devices->missing_devices++;
7586 
7587 			device->fs_devices = fs_devices;
7588 		}
7589 	}
7590 
7591 	if (device->fs_devices != fs_info->fs_devices) {
7592 		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7593 		if (device->generation !=
7594 		    btrfs_device_generation(leaf, dev_item))
7595 			return -EINVAL;
7596 	}
7597 
7598 	fill_device_from_item(leaf, dev_item, device);
7599 	if (device->bdev) {
7600 		u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7601 
7602 		if (device->total_bytes > max_total_bytes) {
7603 			btrfs_err(fs_info,
7604 			"device total_bytes should be at most %llu but found %llu",
7605 				  max_total_bytes, device->total_bytes);
7606 			return -EINVAL;
7607 		}
7608 	}
7609 	set_bit(BTRFS_DEV_STATE_ITEM_FOUND, &device->dev_state);
7610 	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7611 	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7612 	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7613 		device->fs_devices->total_rw_bytes += device->total_bytes;
7614 		atomic64_add(device->total_bytes - device->bytes_used,
7615 				&fs_info->free_chunk_space);
7616 	}
7617 
7618 	return 0;
7619 }
7620 
btrfs_read_sys_array(struct btrfs_fs_info * fs_info)7621 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7622 {
7623 	struct btrfs_super_block *super_copy = fs_info->super_copy;
7624 	struct extent_buffer *sb;
7625 	u8 *array_ptr;
7626 	unsigned long sb_array_offset;
7627 	int ret = 0;
7628 	u32 array_size;
7629 	u32 cur_offset;
7630 	struct btrfs_key key;
7631 
7632 	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7633 
7634 	/*
7635 	 * We allocated a dummy extent, just to use extent buffer accessors.
7636 	 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7637 	 * that's fine, we will not go beyond system chunk array anyway.
7638 	 */
7639 	sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7640 	if (!sb)
7641 		return -ENOMEM;
7642 	set_extent_buffer_uptodate(sb);
7643 
7644 	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7645 	array_size = btrfs_super_sys_array_size(super_copy);
7646 
7647 	array_ptr = super_copy->sys_chunk_array;
7648 	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7649 	cur_offset = 0;
7650 
7651 	while (cur_offset < array_size) {
7652 		struct btrfs_chunk *chunk;
7653 		struct btrfs_disk_key *disk_key = (struct btrfs_disk_key *)array_ptr;
7654 		u32 len = sizeof(*disk_key);
7655 
7656 		/*
7657 		 * The sys_chunk_array has been already verified at super block
7658 		 * read time.  Only do ASSERT()s for basic checks.
7659 		 */
7660 		ASSERT(cur_offset + len <= array_size);
7661 
7662 		btrfs_disk_key_to_cpu(&key, disk_key);
7663 
7664 		array_ptr += len;
7665 		sb_array_offset += len;
7666 		cur_offset += len;
7667 
7668 		ASSERT(key.type == BTRFS_CHUNK_ITEM_KEY);
7669 
7670 		chunk = (struct btrfs_chunk *)sb_array_offset;
7671 		ASSERT(btrfs_chunk_type(sb, chunk) & BTRFS_BLOCK_GROUP_SYSTEM);
7672 
7673 		len = btrfs_chunk_item_size(btrfs_chunk_num_stripes(sb, chunk));
7674 
7675 		ASSERT(cur_offset + len <= array_size);
7676 
7677 		ret = read_one_chunk(&key, sb, chunk);
7678 		if (ret)
7679 			break;
7680 
7681 		array_ptr += len;
7682 		sb_array_offset += len;
7683 		cur_offset += len;
7684 	}
7685 	clear_extent_buffer_uptodate(sb);
7686 	free_extent_buffer_stale(sb);
7687 	return ret;
7688 }
7689 
7690 /*
7691  * Check if all chunks in the fs are OK for read-write degraded mount
7692  *
7693  * If the @failing_dev is specified, it's accounted as missing.
7694  *
7695  * Return true if all chunks meet the minimal RW mount requirements.
7696  * Return false if any chunk doesn't meet the minimal RW mount requirements.
7697  */
btrfs_check_rw_degradable(struct btrfs_fs_info * fs_info,struct btrfs_device * failing_dev)7698 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7699 					struct btrfs_device *failing_dev)
7700 {
7701 	struct btrfs_chunk_map *map;
7702 	u64 next_start;
7703 	bool ret = true;
7704 
7705 	map = btrfs_find_chunk_map(fs_info, 0, U64_MAX);
7706 	/* No chunk at all? Return false anyway */
7707 	if (!map)
7708 		return false;
7709 
7710 	while (map) {
7711 		int missing = 0;
7712 		int max_tolerated;
7713 		int i;
7714 
7715 		max_tolerated =
7716 			btrfs_get_num_tolerated_disk_barrier_failures(
7717 					map->type);
7718 		for (i = 0; i < map->num_stripes; i++) {
7719 			struct btrfs_device *dev = map->stripes[i].dev;
7720 
7721 			if (!dev || !dev->bdev ||
7722 			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7723 			    test_bit(BTRFS_DEV_STATE_FLUSH_FAILED, &dev->dev_state))
7724 				missing++;
7725 			else if (failing_dev && failing_dev == dev)
7726 				missing++;
7727 		}
7728 		if (missing > max_tolerated) {
7729 			if (!failing_dev)
7730 				btrfs_warn(fs_info,
7731 	"chunk %llu missing %d devices, max tolerance is %d for writable mount",
7732 				   map->start, missing, max_tolerated);
7733 			btrfs_free_chunk_map(map);
7734 			return false;
7735 		}
7736 		next_start = map->start + map->chunk_len;
7737 		btrfs_free_chunk_map(map);
7738 
7739 		map = btrfs_find_chunk_map(fs_info, next_start, U64_MAX - next_start);
7740 	}
7741 
7742 	return ret;
7743 }
7744 
readahead_tree_node_children(struct extent_buffer * node)7745 static void readahead_tree_node_children(struct extent_buffer *node)
7746 {
7747 	int i;
7748 	const int nr_items = btrfs_header_nritems(node);
7749 
7750 	for (i = 0; i < nr_items; i++)
7751 		btrfs_readahead_node_child(node, i);
7752 }
7753 
btrfs_read_chunk_tree(struct btrfs_fs_info * fs_info)7754 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7755 {
7756 	struct btrfs_root *root = fs_info->chunk_root;
7757 	BTRFS_PATH_AUTO_FREE(path);
7758 	struct extent_buffer *leaf;
7759 	struct btrfs_key key;
7760 	struct btrfs_key found_key;
7761 	int ret;
7762 	int slot;
7763 	int iter_ret = 0;
7764 	u64 total_dev = 0;
7765 	u64 last_ra_node = 0;
7766 
7767 	path = btrfs_alloc_path();
7768 	if (!path)
7769 		return -ENOMEM;
7770 
7771 	/*
7772 	 * uuid_mutex is needed only if we are mounting a sprout FS
7773 	 * otherwise we don't need it.
7774 	 */
7775 	mutex_lock(&uuid_mutex);
7776 
7777 	/*
7778 	 * It is possible for mount and umount to race in such a way that
7779 	 * we execute this code path, but open_fs_devices failed to clear
7780 	 * total_rw_bytes. We certainly want it cleared before reading the
7781 	 * device items, so clear it here.
7782 	 */
7783 	fs_info->fs_devices->total_rw_bytes = 0;
7784 
7785 	/*
7786 	 * Lockdep complains about possible circular locking dependency between
7787 	 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7788 	 * used for freeze protection of a fs (struct super_block.s_writers),
7789 	 * which we take when starting a transaction, and extent buffers of the
7790 	 * chunk tree if we call read_one_dev() while holding a lock on an
7791 	 * extent buffer of the chunk tree. Since we are mounting the filesystem
7792 	 * and at this point there can't be any concurrent task modifying the
7793 	 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7794 	 */
7795 	ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7796 	path->skip_locking = true;
7797 
7798 	/*
7799 	 * Read all device items, and then all the chunk items. All
7800 	 * device items are found before any chunk item (their object id
7801 	 * is smaller than the lowest possible object id for a chunk
7802 	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7803 	 */
7804 	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7805 	key.type = 0;
7806 	key.offset = 0;
7807 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7808 		struct extent_buffer *node = path->nodes[1];
7809 
7810 		leaf = path->nodes[0];
7811 		slot = path->slots[0];
7812 
7813 		if (node) {
7814 			if (last_ra_node != node->start) {
7815 				readahead_tree_node_children(node);
7816 				last_ra_node = node->start;
7817 			}
7818 		}
7819 		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7820 			struct btrfs_dev_item *dev_item;
7821 			dev_item = btrfs_item_ptr(leaf, slot,
7822 						  struct btrfs_dev_item);
7823 			ret = read_one_dev(leaf, dev_item);
7824 			if (ret)
7825 				goto error;
7826 			total_dev++;
7827 		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7828 			struct btrfs_chunk *chunk;
7829 
7830 			/*
7831 			 * We are only called at mount time, so no need to take
7832 			 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7833 			 * we always lock first fs_info->chunk_mutex before
7834 			 * acquiring any locks on the chunk tree. This is a
7835 			 * requirement for chunk allocation, see the comment on
7836 			 * top of btrfs_chunk_alloc() for details.
7837 			 */
7838 			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7839 			ret = read_one_chunk(&found_key, leaf, chunk);
7840 			if (ret)
7841 				goto error;
7842 		}
7843 	}
7844 	/* Catch error found during iteration */
7845 	if (iter_ret < 0) {
7846 		ret = iter_ret;
7847 		goto error;
7848 	}
7849 
7850 	/*
7851 	 * After loading chunk tree, we've got all device information,
7852 	 * do another round of validation checks.
7853 	 */
7854 	if (total_dev != fs_info->fs_devices->total_devices) {
7855 		btrfs_warn(fs_info,
7856 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7857 			  btrfs_super_num_devices(fs_info->super_copy),
7858 			  total_dev);
7859 		fs_info->fs_devices->total_devices = total_dev;
7860 		btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7861 	}
7862 	if (btrfs_super_total_bytes(fs_info->super_copy) <
7863 	    fs_info->fs_devices->total_rw_bytes) {
7864 		btrfs_err(fs_info,
7865 	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7866 			  btrfs_super_total_bytes(fs_info->super_copy),
7867 			  fs_info->fs_devices->total_rw_bytes);
7868 		ret = -EINVAL;
7869 		goto error;
7870 	}
7871 	ret = 0;
7872 error:
7873 	mutex_unlock(&uuid_mutex);
7874 	return ret;
7875 }
7876 
btrfs_init_devices_late(struct btrfs_fs_info * fs_info)7877 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7878 {
7879 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7880 	struct btrfs_device *device;
7881 	int ret = 0;
7882 
7883 	mutex_lock(&fs_devices->device_list_mutex);
7884 	list_for_each_entry(device, &fs_devices->devices, dev_list)
7885 		device->fs_info = fs_info;
7886 
7887 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7888 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7889 			device->fs_info = fs_info;
7890 			ret = btrfs_get_dev_zone_info(device, false);
7891 			if (ret)
7892 				break;
7893 		}
7894 
7895 		seed_devs->fs_info = fs_info;
7896 	}
7897 	mutex_unlock(&fs_devices->device_list_mutex);
7898 
7899 	return ret;
7900 }
7901 
btrfs_dev_stats_value(const struct extent_buffer * eb,const struct btrfs_dev_stats_item * ptr,int index)7902 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7903 				 const struct btrfs_dev_stats_item *ptr,
7904 				 int index)
7905 {
7906 	u64 val;
7907 
7908 	read_extent_buffer(eb, &val,
7909 			   offsetof(struct btrfs_dev_stats_item, values) +
7910 			    ((unsigned long)ptr) + (index * sizeof(u64)),
7911 			   sizeof(val));
7912 	return val;
7913 }
7914 
btrfs_set_dev_stats_value(struct extent_buffer * eb,struct btrfs_dev_stats_item * ptr,int index,u64 val)7915 static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7916 				      struct btrfs_dev_stats_item *ptr,
7917 				      int index, u64 val)
7918 {
7919 	write_extent_buffer(eb, &val,
7920 			    offsetof(struct btrfs_dev_stats_item, values) +
7921 			     ((unsigned long)ptr) + (index * sizeof(u64)),
7922 			    sizeof(val));
7923 }
7924 
btrfs_device_init_dev_stats(struct btrfs_device * device,struct btrfs_path * path)7925 static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7926 				       struct btrfs_path *path)
7927 {
7928 	struct btrfs_dev_stats_item *ptr;
7929 	struct extent_buffer *eb;
7930 	struct btrfs_key key;
7931 	int item_size;
7932 	int i, ret, slot;
7933 
7934 	if (!device->fs_info->dev_root)
7935 		return 0;
7936 
7937 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7938 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7939 	key.offset = device->devid;
7940 	ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7941 	if (ret) {
7942 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7943 			btrfs_dev_stat_set(device, i, 0);
7944 		device->dev_stats_valid = 1;
7945 		btrfs_release_path(path);
7946 		return ret < 0 ? ret : 0;
7947 	}
7948 	slot = path->slots[0];
7949 	eb = path->nodes[0];
7950 	item_size = btrfs_item_size(eb, slot);
7951 
7952 	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7953 
7954 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7955 		if (item_size >= (1 + i) * sizeof(__le64))
7956 			btrfs_dev_stat_set(device, i,
7957 					   btrfs_dev_stats_value(eb, ptr, i));
7958 		else
7959 			btrfs_dev_stat_set(device, i, 0);
7960 	}
7961 
7962 	device->dev_stats_valid = 1;
7963 	btrfs_dev_stat_print_on_load(device);
7964 	btrfs_release_path(path);
7965 
7966 	return 0;
7967 }
7968 
btrfs_init_dev_stats(struct btrfs_fs_info * fs_info)7969 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7970 {
7971 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7972 	struct btrfs_device *device;
7973 	BTRFS_PATH_AUTO_FREE(path);
7974 	int ret = 0;
7975 
7976 	path = btrfs_alloc_path();
7977 	if (!path)
7978 		return -ENOMEM;
7979 
7980 	mutex_lock(&fs_devices->device_list_mutex);
7981 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7982 		ret = btrfs_device_init_dev_stats(device, path);
7983 		if (ret)
7984 			goto out;
7985 	}
7986 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7987 		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7988 			ret = btrfs_device_init_dev_stats(device, path);
7989 			if (ret)
7990 				goto out;
7991 		}
7992 	}
7993 out:
7994 	mutex_unlock(&fs_devices->device_list_mutex);
7995 	return ret;
7996 }
7997 
update_dev_stat_item(struct btrfs_trans_handle * trans,struct btrfs_device * device)7998 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7999 				struct btrfs_device *device)
8000 {
8001 	struct btrfs_fs_info *fs_info = trans->fs_info;
8002 	struct btrfs_root *dev_root = fs_info->dev_root;
8003 	BTRFS_PATH_AUTO_FREE(path);
8004 	struct btrfs_key key;
8005 	struct extent_buffer *eb;
8006 	struct btrfs_dev_stats_item *ptr;
8007 	int ret;
8008 	int i;
8009 
8010 	key.objectid = BTRFS_DEV_STATS_OBJECTID;
8011 	key.type = BTRFS_PERSISTENT_ITEM_KEY;
8012 	key.offset = device->devid;
8013 
8014 	path = btrfs_alloc_path();
8015 	if (!path)
8016 		return -ENOMEM;
8017 	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
8018 	if (ret < 0) {
8019 		btrfs_warn(fs_info,
8020 			"error %d while searching for dev_stats item for device %s",
8021 				  ret, btrfs_dev_name(device));
8022 		return ret;
8023 	}
8024 
8025 	if (ret == 0 &&
8026 	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
8027 		/* need to delete old one and insert a new one */
8028 		ret = btrfs_del_item(trans, dev_root, path);
8029 		if (ret != 0) {
8030 			btrfs_warn(fs_info,
8031 				"delete too small dev_stats item for device %s failed %d",
8032 					  btrfs_dev_name(device), ret);
8033 			return ret;
8034 		}
8035 		ret = 1;
8036 	}
8037 
8038 	if (ret == 1) {
8039 		/* need to insert a new item */
8040 		btrfs_release_path(path);
8041 		ret = btrfs_insert_empty_item(trans, dev_root, path,
8042 					      &key, sizeof(*ptr));
8043 		if (ret < 0) {
8044 			btrfs_warn(fs_info,
8045 				"insert dev_stats item for device %s failed %d",
8046 				btrfs_dev_name(device), ret);
8047 			return ret;
8048 		}
8049 	}
8050 
8051 	eb = path->nodes[0];
8052 	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
8053 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8054 		btrfs_set_dev_stats_value(eb, ptr, i,
8055 					  btrfs_dev_stat_read(device, i));
8056 	return ret;
8057 }
8058 
8059 /*
8060  * called from commit_transaction. Writes all changed device stats to disk.
8061  */
btrfs_run_dev_stats(struct btrfs_trans_handle * trans)8062 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
8063 {
8064 	struct btrfs_fs_info *fs_info = trans->fs_info;
8065 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8066 	struct btrfs_device *device;
8067 	int stats_cnt;
8068 	int ret = 0;
8069 
8070 	mutex_lock(&fs_devices->device_list_mutex);
8071 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
8072 		stats_cnt = atomic_read(&device->dev_stats_ccnt);
8073 		if (!device->dev_stats_valid || stats_cnt == 0)
8074 			continue;
8075 
8076 
8077 		/*
8078 		 * There is a LOAD-LOAD control dependency between the value of
8079 		 * dev_stats_ccnt and updating the on-disk values which requires
8080 		 * reading the in-memory counters. Such control dependencies
8081 		 * require explicit read memory barriers.
8082 		 *
8083 		 * This memory barriers pairs with smp_mb__before_atomic in
8084 		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
8085 		 * barrier implied by atomic_xchg in
8086 		 * btrfs_dev_stats_read_and_reset
8087 		 */
8088 		smp_rmb();
8089 
8090 		ret = update_dev_stat_item(trans, device);
8091 		if (!ret)
8092 			atomic_sub(stats_cnt, &device->dev_stats_ccnt);
8093 	}
8094 	mutex_unlock(&fs_devices->device_list_mutex);
8095 
8096 	return ret;
8097 }
8098 
btrfs_dev_stat_inc_and_print(struct btrfs_device * dev,int index)8099 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
8100 {
8101 	btrfs_dev_stat_inc(dev, index);
8102 
8103 	if (!dev->dev_stats_valid)
8104 		return;
8105 	btrfs_err_rl(dev->fs_info,
8106 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8107 			   btrfs_dev_name(dev),
8108 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8109 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8110 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8111 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8112 			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8113 }
8114 
btrfs_dev_stat_print_on_load(struct btrfs_device * dev)8115 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
8116 {
8117 	int i;
8118 
8119 	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8120 		if (btrfs_dev_stat_read(dev, i) != 0)
8121 			break;
8122 	if (i == BTRFS_DEV_STAT_VALUES_MAX)
8123 		return; /* all values == 0, suppress message */
8124 
8125 	btrfs_info(dev->fs_info,
8126 		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
8127 	       btrfs_dev_name(dev),
8128 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
8129 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
8130 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
8131 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
8132 	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
8133 }
8134 
btrfs_get_dev_stats(struct btrfs_fs_info * fs_info,struct btrfs_ioctl_get_dev_stats * stats)8135 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
8136 			struct btrfs_ioctl_get_dev_stats *stats)
8137 {
8138 	BTRFS_DEV_LOOKUP_ARGS(args);
8139 	struct btrfs_device *dev;
8140 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8141 	int i;
8142 
8143 	mutex_lock(&fs_devices->device_list_mutex);
8144 	args.devid = stats->devid;
8145 	dev = btrfs_find_device(fs_info->fs_devices, &args);
8146 	mutex_unlock(&fs_devices->device_list_mutex);
8147 
8148 	if (!dev) {
8149 		btrfs_warn(fs_info, "get dev_stats failed, device not found");
8150 		return -ENODEV;
8151 	} else if (!dev->dev_stats_valid) {
8152 		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
8153 		return -ENODEV;
8154 	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
8155 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
8156 			if (stats->nr_items > i)
8157 				stats->values[i] =
8158 					btrfs_dev_stat_read_and_reset(dev, i);
8159 			else
8160 				btrfs_dev_stat_set(dev, i, 0);
8161 		}
8162 		btrfs_info(fs_info, "device stats zeroed by %s (%d)",
8163 			   current->comm, task_pid_nr(current));
8164 	} else {
8165 		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
8166 			if (stats->nr_items > i)
8167 				stats->values[i] = btrfs_dev_stat_read(dev, i);
8168 	}
8169 	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
8170 		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
8171 	return 0;
8172 }
8173 
8174 /*
8175  * Update the size and bytes used for each device where it changed.  This is
8176  * delayed since we would otherwise get errors while writing out the
8177  * superblocks.
8178  *
8179  * Must be invoked during transaction commit.
8180  */
btrfs_commit_device_sizes(struct btrfs_transaction * trans)8181 void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
8182 {
8183 	struct btrfs_device *curr, *next;
8184 
8185 	ASSERT(trans->state == TRANS_STATE_COMMIT_DOING, "state=%d" , trans->state);
8186 
8187 	if (list_empty(&trans->dev_update_list))
8188 		return;
8189 
8190 	/*
8191 	 * We don't need the device_list_mutex here.  This list is owned by the
8192 	 * transaction and the transaction must complete before the device is
8193 	 * released.
8194 	 */
8195 	mutex_lock(&trans->fs_info->chunk_mutex);
8196 	list_for_each_entry_safe(curr, next, &trans->dev_update_list,
8197 				 post_commit_list) {
8198 		list_del_init(&curr->post_commit_list);
8199 		curr->commit_total_bytes = curr->disk_total_bytes;
8200 		curr->commit_bytes_used = curr->bytes_used;
8201 	}
8202 	mutex_unlock(&trans->fs_info->chunk_mutex);
8203 }
8204 
8205 /*
8206  * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
8207  */
btrfs_bg_type_to_factor(u64 flags)8208 int btrfs_bg_type_to_factor(u64 flags)
8209 {
8210 	const int index = btrfs_bg_flags_to_raid_index(flags);
8211 
8212 	return btrfs_raid_array[index].ncopies;
8213 }
8214 
verify_one_dev_extent(struct btrfs_fs_info * fs_info,u64 chunk_offset,u64 devid,u64 physical_offset,u64 physical_len)8215 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
8216 				 u64 chunk_offset, u64 devid,
8217 				 u64 physical_offset, u64 physical_len)
8218 {
8219 	struct btrfs_dev_lookup_args args = { .devid = devid };
8220 	struct btrfs_chunk_map *map;
8221 	struct btrfs_device *dev;
8222 	u64 stripe_len;
8223 	bool found = false;
8224 	int ret = 0;
8225 	int i;
8226 
8227 	map = btrfs_find_chunk_map(fs_info, chunk_offset, 1);
8228 	if (unlikely(!map)) {
8229 		btrfs_err(fs_info,
8230 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
8231 			  physical_offset, devid);
8232 		ret = -EUCLEAN;
8233 		goto out;
8234 	}
8235 
8236 	stripe_len = btrfs_calc_stripe_length(map);
8237 	if (unlikely(physical_len != stripe_len)) {
8238 		btrfs_err(fs_info,
8239 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8240 			  physical_offset, devid, map->start, physical_len,
8241 			  stripe_len);
8242 		ret = -EUCLEAN;
8243 		goto out;
8244 	}
8245 
8246 	/*
8247 	 * Very old mkfs.btrfs (before v4.15) will not respect the reserved
8248 	 * space. Although kernel can handle it without problem, better to warn
8249 	 * the users.
8250 	 */
8251 	if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
8252 		btrfs_warn(fs_info,
8253 		"devid %llu physical %llu len %llu inside the reserved space",
8254 			   devid, physical_offset, physical_len);
8255 
8256 	for (i = 0; i < map->num_stripes; i++) {
8257 		if (unlikely(map->stripes[i].dev->devid == devid &&
8258 			     map->stripes[i].physical == physical_offset)) {
8259 			found = true;
8260 			if (map->verified_stripes >= map->num_stripes) {
8261 				btrfs_err(fs_info,
8262 				"too many dev extents for chunk %llu found",
8263 					  map->start);
8264 				ret = -EUCLEAN;
8265 				goto out;
8266 			}
8267 			map->verified_stripes++;
8268 			break;
8269 		}
8270 	}
8271 	if (unlikely(!found)) {
8272 		btrfs_err(fs_info,
8273 	"dev extent physical offset %llu devid %llu has no corresponding chunk",
8274 			physical_offset, devid);
8275 		ret = -EUCLEAN;
8276 	}
8277 
8278 	/* Make sure no dev extent is beyond device boundary */
8279 	dev = btrfs_find_device(fs_info->fs_devices, &args);
8280 	if (unlikely(!dev)) {
8281 		btrfs_err(fs_info, "failed to find devid %llu", devid);
8282 		ret = -EUCLEAN;
8283 		goto out;
8284 	}
8285 
8286 	if (unlikely(physical_offset + physical_len > dev->disk_total_bytes)) {
8287 		btrfs_err(fs_info,
8288 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8289 			  devid, physical_offset, physical_len,
8290 			  dev->disk_total_bytes);
8291 		ret = -EUCLEAN;
8292 		goto out;
8293 	}
8294 
8295 	if (dev->zone_info) {
8296 		u64 zone_size = dev->zone_info->zone_size;
8297 
8298 		if (unlikely(!IS_ALIGNED(physical_offset, zone_size) ||
8299 			     !IS_ALIGNED(physical_len, zone_size))) {
8300 			btrfs_err(fs_info,
8301 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8302 				  devid, physical_offset, physical_len);
8303 			ret = -EUCLEAN;
8304 			goto out;
8305 		}
8306 	}
8307 
8308 out:
8309 	btrfs_free_chunk_map(map);
8310 	return ret;
8311 }
8312 
verify_chunk_dev_extent_mapping(struct btrfs_fs_info * fs_info)8313 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8314 {
8315 	struct rb_node *node;
8316 	int ret = 0;
8317 
8318 	read_lock(&fs_info->mapping_tree_lock);
8319 	for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) {
8320 		struct btrfs_chunk_map *map;
8321 
8322 		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
8323 		if (unlikely(map->num_stripes != map->verified_stripes)) {
8324 			btrfs_err(fs_info,
8325 			"chunk %llu has missing dev extent, have %d expect %d",
8326 				  map->start, map->verified_stripes, map->num_stripes);
8327 			ret = -EUCLEAN;
8328 			goto out;
8329 		}
8330 	}
8331 out:
8332 	read_unlock(&fs_info->mapping_tree_lock);
8333 	return ret;
8334 }
8335 
8336 /*
8337  * Ensure that all dev extents are mapped to correct chunk, otherwise
8338  * later chunk allocation/free would cause unexpected behavior.
8339  *
8340  * NOTE: This will iterate through the whole device tree, which should be of
8341  * the same size level as the chunk tree.  This slightly increases mount time.
8342  */
btrfs_verify_dev_extents(struct btrfs_fs_info * fs_info)8343 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8344 {
8345 	BTRFS_PATH_AUTO_FREE(path);
8346 	struct btrfs_root *root = fs_info->dev_root;
8347 	struct btrfs_key key;
8348 	u64 prev_devid = 0;
8349 	u64 prev_dev_ext_end = 0;
8350 	int ret = 0;
8351 
8352 	/*
8353 	 * We don't have a dev_root because we mounted with ignorebadroots and
8354 	 * failed to load the root, so we want to skip the verification in this
8355 	 * case for sure.
8356 	 *
8357 	 * However if the dev root is fine, but the tree itself is corrupted
8358 	 * we'd still fail to mount.  This verification is only to make sure
8359 	 * writes can happen safely, so instead just bypass this check
8360 	 * completely in the case of IGNOREBADROOTS.
8361 	 */
8362 	if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8363 		return 0;
8364 
8365 	key.objectid = 1;
8366 	key.type = BTRFS_DEV_EXTENT_KEY;
8367 	key.offset = 0;
8368 
8369 	path = btrfs_alloc_path();
8370 	if (!path)
8371 		return -ENOMEM;
8372 
8373 	path->reada = READA_FORWARD_ALWAYS;
8374 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8375 	if (ret < 0)
8376 		return ret;
8377 
8378 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8379 		ret = btrfs_next_leaf(root, path);
8380 		if (ret < 0)
8381 			return ret;
8382 		/* No dev extents at all? Not good */
8383 		if (unlikely(ret > 0))
8384 			return -EUCLEAN;
8385 	}
8386 	while (1) {
8387 		struct extent_buffer *leaf = path->nodes[0];
8388 		struct btrfs_dev_extent *dext;
8389 		int slot = path->slots[0];
8390 		u64 chunk_offset;
8391 		u64 physical_offset;
8392 		u64 physical_len;
8393 		u64 devid;
8394 
8395 		btrfs_item_key_to_cpu(leaf, &key, slot);
8396 		if (key.type != BTRFS_DEV_EXTENT_KEY)
8397 			break;
8398 		devid = key.objectid;
8399 		physical_offset = key.offset;
8400 
8401 		dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8402 		chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8403 		physical_len = btrfs_dev_extent_length(leaf, dext);
8404 
8405 		/* Check if this dev extent overlaps with the previous one */
8406 		if (unlikely(devid == prev_devid && physical_offset < prev_dev_ext_end)) {
8407 			btrfs_err(fs_info,
8408 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8409 				  devid, physical_offset, prev_dev_ext_end);
8410 			return -EUCLEAN;
8411 		}
8412 
8413 		ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8414 					    physical_offset, physical_len);
8415 		if (ret < 0)
8416 			return ret;
8417 		prev_devid = devid;
8418 		prev_dev_ext_end = physical_offset + physical_len;
8419 
8420 		ret = btrfs_next_item(root, path);
8421 		if (ret < 0)
8422 			return ret;
8423 		if (ret > 0) {
8424 			ret = 0;
8425 			break;
8426 		}
8427 	}
8428 
8429 	/* Ensure all chunks have corresponding dev extents */
8430 	return verify_chunk_dev_extent_mapping(fs_info);
8431 }
8432 
8433 /*
8434  * Ensure that all devices registered in the fs have their device items in the
8435  * chunk tree.
8436  *
8437  * Return true if unexpected device is found.
8438  * Return false otherwise.
8439  */
btrfs_verify_dev_items(const struct btrfs_fs_info * fs_info)8440 bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info)
8441 {
8442 	struct btrfs_fs_devices *seed_devs;
8443 	struct btrfs_device *dev;
8444 	bool ret = false;
8445 
8446 	mutex_lock(&uuid_mutex);
8447 	list_for_each_entry(dev, &fs_info->fs_devices->devices, dev_list) {
8448 		if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8449 			btrfs_err(fs_info,
8450 			"devid %llu path %s is registered but not found in chunk tree",
8451 				  dev->devid, btrfs_dev_name(dev));
8452 			ret = true;
8453 		}
8454 	}
8455 	list_for_each_entry(seed_devs, &fs_info->fs_devices->seed_list, seed_list) {
8456 		list_for_each_entry(dev, &seed_devs->devices, dev_list) {
8457 			if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8458 				btrfs_err(fs_info,
8459 			"devid %llu path %s is registered but not found in chunk tree",
8460 					  dev->devid, btrfs_dev_name(dev));
8461 				ret = true;
8462 			}
8463 		}
8464 	}
8465 	mutex_unlock(&uuid_mutex);
8466 	if (ret)
8467 		btrfs_err(fs_info,
8468 "remove the above devices or use 'btrfs device scan --forget <dev>' to unregister them before mount");
8469 	return ret;
8470 }
8471 
8472 /*
8473  * Check whether the given block group or device is pinned by any inode being
8474  * used as a swapfile.
8475  */
btrfs_pinned_by_swapfile(struct btrfs_fs_info * fs_info,void * ptr)8476 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8477 {
8478 	struct btrfs_swapfile_pin *sp;
8479 	struct rb_node *node;
8480 
8481 	spin_lock(&fs_info->swapfile_pins_lock);
8482 	node = fs_info->swapfile_pins.rb_node;
8483 	while (node) {
8484 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8485 		if (ptr < sp->ptr)
8486 			node = node->rb_left;
8487 		else if (ptr > sp->ptr)
8488 			node = node->rb_right;
8489 		else
8490 			break;
8491 	}
8492 	spin_unlock(&fs_info->swapfile_pins_lock);
8493 	return node != NULL;
8494 }
8495 
relocating_repair_kthread(void * data)8496 static int relocating_repair_kthread(void *data)
8497 {
8498 	struct btrfs_block_group *cache = data;
8499 	struct btrfs_fs_info *fs_info = cache->fs_info;
8500 	u64 target;
8501 	int ret = 0;
8502 
8503 	target = cache->start;
8504 	btrfs_put_block_group(cache);
8505 
8506 	guard(super_write)(fs_info->sb);
8507 
8508 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8509 		btrfs_info(fs_info,
8510 			   "zoned: skip relocating block group %llu to repair: EBUSY",
8511 			   target);
8512 		return -EBUSY;
8513 	}
8514 
8515 	mutex_lock(&fs_info->reclaim_bgs_lock);
8516 
8517 	/* Ensure block group still exists */
8518 	cache = btrfs_lookup_block_group(fs_info, target);
8519 	if (!cache)
8520 		goto out;
8521 
8522 	if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8523 		goto out;
8524 
8525 	ret = btrfs_may_alloc_data_chunk(fs_info, target);
8526 	if (ret < 0)
8527 		goto out;
8528 
8529 	btrfs_info(fs_info,
8530 		   "zoned: relocating block group %llu to repair IO failure",
8531 		   target);
8532 	ret = btrfs_relocate_chunk(fs_info, target, true);
8533 
8534 out:
8535 	if (cache)
8536 		btrfs_put_block_group(cache);
8537 	mutex_unlock(&fs_info->reclaim_bgs_lock);
8538 	btrfs_exclop_finish(fs_info);
8539 
8540 	return ret;
8541 }
8542 
btrfs_repair_one_zone(struct btrfs_fs_info * fs_info,u64 logical)8543 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8544 {
8545 	struct btrfs_block_group *cache;
8546 
8547 	if (!btrfs_is_zoned(fs_info))
8548 		return false;
8549 
8550 	/* Do not attempt to repair in degraded state */
8551 	if (btrfs_test_opt(fs_info, DEGRADED))
8552 		return true;
8553 
8554 	cache = btrfs_lookup_block_group(fs_info, logical);
8555 	if (!cache)
8556 		return true;
8557 
8558 	if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8559 		btrfs_put_block_group(cache);
8560 		return true;
8561 	}
8562 
8563 	kthread_run(relocating_repair_kthread, cache,
8564 		    "btrfs-relocating-repair");
8565 
8566 	return true;
8567 }
8568 
map_raid56_repair_block(struct btrfs_io_context * bioc,struct btrfs_io_stripe * smap,u64 logical)8569 static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8570 				    struct btrfs_io_stripe *smap,
8571 				    u64 logical)
8572 {
8573 	int data_stripes = nr_bioc_data_stripes(bioc);
8574 	int i;
8575 
8576 	for (i = 0; i < data_stripes; i++) {
8577 		u64 stripe_start = bioc->full_stripe_logical +
8578 				   btrfs_stripe_nr_to_offset(i);
8579 
8580 		if (logical >= stripe_start &&
8581 		    logical < stripe_start + BTRFS_STRIPE_LEN)
8582 			break;
8583 	}
8584 	ASSERT(i < data_stripes, "i=%d data_stripes=%d", i, data_stripes);
8585 	smap->dev = bioc->stripes[i].dev;
8586 	smap->physical = bioc->stripes[i].physical +
8587 			((logical - bioc->full_stripe_logical) &
8588 			 BTRFS_STRIPE_LEN_MASK);
8589 }
8590 
8591 /*
8592  * Map a repair write into a single device.
8593  *
8594  * A repair write is triggered by read time repair or scrub, which would only
8595  * update the contents of a single device.
8596  * Not update any other mirrors nor go through RMW path.
8597  *
8598  * Callers should ensure:
8599  *
8600  * - Call btrfs_bio_counter_inc_blocked() first
8601  * - The range does not cross stripe boundary
8602  * - Has a valid @mirror_num passed in.
8603  */
btrfs_map_repair_block(struct btrfs_fs_info * fs_info,struct btrfs_io_stripe * smap,u64 logical,u32 length,int mirror_num)8604 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8605 			   struct btrfs_io_stripe *smap, u64 logical,
8606 			   u32 length, int mirror_num)
8607 {
8608 	struct btrfs_io_context *bioc = NULL;
8609 	u64 map_length = length;
8610 	int mirror_ret = mirror_num;
8611 	int ret;
8612 
8613 	ASSERT(mirror_num > 0, "mirror_num=%d", mirror_num);
8614 
8615 	ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8616 			      &bioc, smap, &mirror_ret);
8617 	if (ret < 0)
8618 		return ret;
8619 
8620 	/* The map range should not cross stripe boundary. */
8621 	ASSERT(map_length >= length, "map_length=%llu length=%u", map_length, length);
8622 
8623 	/* Already mapped to single stripe. */
8624 	if (!bioc)
8625 		goto out;
8626 
8627 	/* Map the RAID56 multi-stripe writes to a single one. */
8628 	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8629 		map_raid56_repair_block(bioc, smap, logical);
8630 		goto out;
8631 	}
8632 
8633 	ASSERT(mirror_num <= bioc->num_stripes,
8634 	       "mirror_num=%d num_stripes=%d", mirror_num,  bioc->num_stripes);
8635 	smap->dev = bioc->stripes[mirror_num - 1].dev;
8636 	smap->physical = bioc->stripes[mirror_num - 1].physical;
8637 out:
8638 	btrfs_put_bioc(bioc);
8639 	ASSERT(smap->dev);
8640 	return 0;
8641 }
8642