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