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