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