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