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