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