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