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