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