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