xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 315bf8ef)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6e20d96d6SChris Mason #include <linux/fs.h>
7d98237b3SChris Mason #include <linux/blkdev.h>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10d397712bSChris Mason #include <linux/buffer_head.h>
11ce9adaa5SChris Mason #include <linux/workqueue.h>
12a74a4b97SChris Mason #include <linux/kthread.h>
135a0e3ad6STejun Heo #include <linux/slab.h>
14784b4e29SChris Mason #include <linux/migrate.h>
157a36ddecSDavid Sterba #include <linux/ratelimit.h>
166463fe58SStefan Behrens #include <linux/uuid.h>
17803b2f54SStefan Behrens #include <linux/semaphore.h>
18540adea3SMasami Hiramatsu #include <linux/error-injection.h>
199678c543SNikolay Borisov #include <linux/crc32c.h>
20b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
217e75bf3fSDavid Sterba #include <asm/unaligned.h>
226d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
23eb60ceacSChris Mason #include "ctree.h"
24eb60ceacSChris Mason #include "disk-io.h"
25e089f05cSChris Mason #include "transaction.h"
260f7d52f4SChris Mason #include "btrfs_inode.h"
270b86a832SChris Mason #include "volumes.h"
28db94535dSChris Mason #include "print-tree.h"
29925baeddSChris Mason #include "locking.h"
30e02119d5SChris Mason #include "tree-log.h"
31fa9c0d79SChris Mason #include "free-space-cache.h"
3270f6d82eSOmar Sandoval #include "free-space-tree.h"
33581bb050SLi Zefan #include "inode-map.h"
3421adbd5cSStefan Behrens #include "check-integrity.h"
35606686eeSJosef Bacik #include "rcu-string.h"
368dabb742SStefan Behrens #include "dev-replace.h"
3753b381b3SDavid Woodhouse #include "raid56.h"
385ac1d209SJeff Mahoney #include "sysfs.h"
39fcebe456SJosef Bacik #include "qgroup.h"
40ebb8765bSAnand Jain #include "compression.h"
41557ea5ddSQu Wenruo #include "tree-checker.h"
42fd708b81SJosef Bacik #include "ref-verify.h"
43aac0023cSJosef Bacik #include "block-group.h"
44b0643e59SDennis Zhou #include "discard.h"
45eb60ceacSChris Mason 
46319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
47319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
48319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
50e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
52319e4d06SQu Wenruo 
53e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops;
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101d352ac68SChris Mason /*
102d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
103d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
104d352ac68SChris Mason  * just before they are sent down the IO stack.
105d352ac68SChris Mason  */
10644b8bd7eSChris Mason struct async_submit_bio {
107c6100a4bSJosef Bacik 	void *private_data;
10844b8bd7eSChris Mason 	struct bio *bio;
109a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11044b8bd7eSChris Mason 	int mirror_num;
111eaf25d93SChris Mason 	/*
112eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
113eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
114eaf25d93SChris Mason 	 */
115eaf25d93SChris Mason 	u64 bio_offset;
1168b712842SChris Mason 	struct btrfs_work work;
1174e4cbee9SChristoph Hellwig 	blk_status_t status;
11844b8bd7eSChris Mason };
11944b8bd7eSChris Mason 
12085d4e461SChris Mason /*
12185d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12285d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12385d4e461SChris Mason  * the level the eb occupies in the tree.
1244008c04aSChris Mason  *
12585d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
12685d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
12785d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1284fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1294fd786e6SMisono Tomohiro  * roots have separate keysets.
1304008c04aSChris Mason  *
13185d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13285d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13385d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
13685d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
13785d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
13885d4e461SChris Mason  *
13985d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14085d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14185d4e461SChris Mason  * needs update as well.
1424008c04aSChris Mason  */
1434008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1444008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1454008c04aSChris Mason #  error
1464008c04aSChris Mason # endif
14785d4e461SChris Mason 
14885d4e461SChris Mason static struct btrfs_lockdep_keyset {
14985d4e461SChris Mason 	u64			id;		/* root objectid */
15085d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
15185d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
15285d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
15385d4e461SChris Mason } btrfs_lockdep_keysets[] = {
15485d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
15585d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
15685d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
15785d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
15885d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
15985d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
16060b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
16185d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
16285d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
16385d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
16413fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
1656b20e0adSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	.name_stem = "free-space" },
16685d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1674008c04aSChris Mason };
16885d4e461SChris Mason 
16985d4e461SChris Mason void __init btrfs_init_lockdep(void)
17085d4e461SChris Mason {
17185d4e461SChris Mason 	int i, j;
17285d4e461SChris Mason 
17385d4e461SChris Mason 	/* initialize lockdep class names */
17485d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
17585d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
17685d4e461SChris Mason 
17785d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
17885d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
17985d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
18085d4e461SChris Mason 	}
18185d4e461SChris Mason }
18285d4e461SChris Mason 
18385d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18485d4e461SChris Mason 				    int level)
18585d4e461SChris Mason {
18685d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
18785d4e461SChris Mason 
18885d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
18985d4e461SChris Mason 
19085d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19185d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19285d4e461SChris Mason 		if (ks->id == objectid)
19385d4e461SChris Mason 			break;
19485d4e461SChris Mason 
19585d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
19685d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
19785d4e461SChris Mason }
19885d4e461SChris Mason 
1994008c04aSChris Mason #endif
2004008c04aSChris Mason 
201d352ac68SChris Mason /*
202d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
203d352ac68SChris Mason  * that covers the entire device
204d352ac68SChris Mason  */
2056af49dbdSDavid Sterba struct extent_map *btree_get_extent(struct btrfs_inode *inode,
20639b07b5dSOmar Sandoval 				    struct page *page, size_t pg_offset,
20739b07b5dSOmar Sandoval 				    u64 start, u64 len)
2085f39d397SChris Mason {
209fc4f21b1SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
2105f39d397SChris Mason 	struct extent_map *em;
2115f39d397SChris Mason 	int ret;
2125f39d397SChris Mason 
213890871beSChris Mason 	read_lock(&em_tree->lock);
214d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
215a061fc8dSChris Mason 	if (em) {
216890871beSChris Mason 		read_unlock(&em_tree->lock);
2175f39d397SChris Mason 		goto out;
218a061fc8dSChris Mason 	}
219890871beSChris Mason 	read_unlock(&em_tree->lock);
2207b13b7b1SChris Mason 
221172ddd60SDavid Sterba 	em = alloc_extent_map();
2225f39d397SChris Mason 	if (!em) {
2235f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2245f39d397SChris Mason 		goto out;
2255f39d397SChris Mason 	}
2265f39d397SChris Mason 	em->start = 0;
2270afbaf8cSChris Mason 	em->len = (u64)-1;
228c8b97818SChris Mason 	em->block_len = (u64)-1;
2295f39d397SChris Mason 	em->block_start = 0;
230d1310b2eSChris Mason 
231890871beSChris Mason 	write_lock(&em_tree->lock);
23209a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2335f39d397SChris Mason 	if (ret == -EEXIST) {
2345f39d397SChris Mason 		free_extent_map(em);
2357b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
236b4f359abSTsutomu Itoh 		if (!em)
2370433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2385f39d397SChris Mason 	} else if (ret) {
2397b13b7b1SChris Mason 		free_extent_map(em);
2400433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2415f39d397SChris Mason 	}
242890871beSChris Mason 	write_unlock(&em_tree->lock);
2437b13b7b1SChris Mason 
2445f39d397SChris Mason out:
2455f39d397SChris Mason 	return em;
2465f39d397SChris Mason }
2475f39d397SChris Mason 
248d352ac68SChris Mason /*
2492996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
2502996e1f8SJohannes Thumshirn  *
2512996e1f8SJohannes Thumshirn  * Returns error if the extent buffer cannot be mapped.
252d352ac68SChris Mason  */
2532996e1f8SJohannes Thumshirn static int csum_tree_block(struct extent_buffer *buf, u8 *result)
25419c00ddcSChris Mason {
255d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
256d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
25719c00ddcSChris Mason 	unsigned long len;
25819c00ddcSChris Mason 	unsigned long cur_len;
25919c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
26019c00ddcSChris Mason 	char *kaddr;
26119c00ddcSChris Mason 	unsigned long map_start;
26219c00ddcSChris Mason 	unsigned long map_len;
26319c00ddcSChris Mason 	int err;
264d5178578SJohannes Thumshirn 
265d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
266d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
26719c00ddcSChris Mason 
26819c00ddcSChris Mason 	len = buf->len - offset;
269d5178578SJohannes Thumshirn 
27019c00ddcSChris Mason 	while (len > 0) {
271d2e174d5SJohannes Thumshirn 		/*
272d2e174d5SJohannes Thumshirn 		 * Note: we don't need to check for the err == 1 case here, as
273d2e174d5SJohannes Thumshirn 		 * with the given combination of 'start = BTRFS_CSUM_SIZE (32)'
274d2e174d5SJohannes Thumshirn 		 * and 'min_len = 32' and the currently implemented mapping
275d2e174d5SJohannes Thumshirn 		 * algorithm we cannot cross a page boundary.
276d2e174d5SJohannes Thumshirn 		 */
27719c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
278a6591715SChris Mason 					&kaddr, &map_start, &map_len);
279c53839fcSJohannes Thumshirn 		if (WARN_ON(err))
2808bd98f0eSAlex Lyakas 			return err;
28119c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
282d5178578SJohannes Thumshirn 		crypto_shash_update(shash, kaddr + offset - map_start, cur_len);
28319c00ddcSChris Mason 		len -= cur_len;
28419c00ddcSChris Mason 		offset += cur_len;
28519c00ddcSChris Mason 	}
28671a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
287607d432dSJosef Bacik 
288d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
28919c00ddcSChris Mason 
29019c00ddcSChris Mason 	return 0;
29119c00ddcSChris Mason }
29219c00ddcSChris Mason 
293d352ac68SChris Mason /*
294d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
295d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
296d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
297d352ac68SChris Mason  * in the wrong place.
298d352ac68SChris Mason  */
2991259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
300b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
301b9fab919SChris Mason 				 int atomic)
3021259ab75SChris Mason {
3032ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3041259ab75SChris Mason 	int ret;
3052755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
3061259ab75SChris Mason 
3071259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
3081259ab75SChris Mason 		return 0;
3091259ab75SChris Mason 
310b9fab919SChris Mason 	if (atomic)
311b9fab919SChris Mason 		return -EAGAIN;
312b9fab919SChris Mason 
313a26e8c9fSJosef Bacik 	if (need_lock) {
314a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
315300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb);
316a26e8c9fSJosef Bacik 	}
317a26e8c9fSJosef Bacik 
3182ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
319ff13db41SDavid Sterba 			 &cached_state);
3200b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3211259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3221259ab75SChris Mason 		ret = 0;
3231259ab75SChris Mason 		goto out;
3241259ab75SChris Mason 	}
32594647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
32694647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
32794647322SDavid Sterba 			eb->start,
32829549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3291259ab75SChris Mason 	ret = 1;
330a26e8c9fSJosef Bacik 
331a26e8c9fSJosef Bacik 	/*
332a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
333a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
33401327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
335a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
336a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
337a26e8c9fSJosef Bacik 	 * making everybody very sad.
338a26e8c9fSJosef Bacik 	 */
339a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3400b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
34133958dc6SChris Mason out:
3422ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
343e43bbe5eSDavid Sterba 			     &cached_state);
344472b909fSJosef Bacik 	if (need_lock)
345a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3461259ab75SChris Mason 	return ret;
3471259ab75SChris Mason }
3481259ab75SChris Mason 
349e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
350e7e16f48SJohannes Thumshirn {
351e7e16f48SJohannes Thumshirn 	switch (csum_type) {
352e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
3533951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
3543831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
355352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
356e7e16f48SJohannes Thumshirn 		return true;
357e7e16f48SJohannes Thumshirn 	default:
358e7e16f48SJohannes Thumshirn 		return false;
359e7e16f48SJohannes Thumshirn 	}
360e7e16f48SJohannes Thumshirn }
361e7e16f48SJohannes Thumshirn 
362d352ac68SChris Mason /*
3631104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3641104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3651104a885SDavid Sterba  */
366ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
367ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
3681104a885SDavid Sterba {
3691104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3701104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
37151bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
372d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
373d5178578SJohannes Thumshirn 
374d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
375d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
3761104a885SDavid Sterba 
3771104a885SDavid Sterba 	/*
3781104a885SDavid Sterba 	 * The super_block structure does not span the whole
37951bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
38051bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3811104a885SDavid Sterba 	 */
382d5178578SJohannes Thumshirn 	crypto_shash_update(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
383d5178578SJohannes Thumshirn 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
384d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
3851104a885SDavid Sterba 
38651bce6c9SJohannes Thumshirn 	if (memcmp(disk_sb->csum, result, btrfs_super_csum_size(disk_sb)))
387e7e16f48SJohannes Thumshirn 		return 1;
3881104a885SDavid Sterba 
389e7e16f48SJohannes Thumshirn 	return 0;
3901104a885SDavid Sterba }
3911104a885SDavid Sterba 
392e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
393ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
394581c1760SQu Wenruo {
395e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
396581c1760SQu Wenruo 	int found_level;
397581c1760SQu Wenruo 	struct btrfs_key found_key;
398581c1760SQu Wenruo 	int ret;
399581c1760SQu Wenruo 
400581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
401581c1760SQu Wenruo 	if (found_level != level) {
40263489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
40363489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
404581c1760SQu Wenruo 		btrfs_err(fs_info,
405581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
406581c1760SQu Wenruo 			  eb->start, level, found_level);
407581c1760SQu Wenruo 		return -EIO;
408581c1760SQu Wenruo 	}
409581c1760SQu Wenruo 
410581c1760SQu Wenruo 	if (!first_key)
411581c1760SQu Wenruo 		return 0;
412581c1760SQu Wenruo 
4135d41be6fSQu Wenruo 	/*
4145d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
4155d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
4165d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
4175d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
4185d41be6fSQu Wenruo 	 */
4195d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
4205d41be6fSQu Wenruo 		return 0;
42162fdaa52SQu Wenruo 
42262fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
42362fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
42462fdaa52SQu Wenruo 		btrfs_err(fs_info,
42562fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
42662fdaa52SQu Wenruo 			  eb->start);
42762fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
42862fdaa52SQu Wenruo 		return -EUCLEAN;
42962fdaa52SQu Wenruo 	}
43062fdaa52SQu Wenruo 
431581c1760SQu Wenruo 	if (found_level)
432581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
433581c1760SQu Wenruo 	else
434581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
435581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
436581c1760SQu Wenruo 
437581c1760SQu Wenruo 	if (ret) {
43863489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
43963489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
440581c1760SQu Wenruo 		btrfs_err(fs_info,
441ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
442ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
443ff76a864SLiu Bo 			  first_key->type, first_key->offset,
444ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
445ff76a864SLiu Bo 			  found_key.offset);
446581c1760SQu Wenruo 	}
447581c1760SQu Wenruo 	return ret;
448581c1760SQu Wenruo }
449581c1760SQu Wenruo 
4501104a885SDavid Sterba /*
451d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
452d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
453581c1760SQu Wenruo  *
454581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
455581c1760SQu Wenruo  * @level:		expected level, mandatory check
456581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
457d352ac68SChris Mason  */
4585ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
459581c1760SQu Wenruo 					  u64 parent_transid, int level,
460581c1760SQu Wenruo 					  struct btrfs_key *first_key)
461f188591eSChris Mason {
4625ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
463f188591eSChris Mason 	struct extent_io_tree *io_tree;
464ea466794SJosef Bacik 	int failed = 0;
465f188591eSChris Mason 	int ret;
466f188591eSChris Mason 	int num_copies = 0;
467f188591eSChris Mason 	int mirror_num = 0;
468ea466794SJosef Bacik 	int failed_mirror = 0;
469f188591eSChris Mason 
4700b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
471f188591eSChris Mason 	while (1) {
472f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
473c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
474256dd1bbSStefan Behrens 		if (!ret) {
475581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
476b9fab919SChris Mason 						   parent_transid, 0))
477256dd1bbSStefan Behrens 				ret = -EIO;
478e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
479ff76a864SLiu Bo 						first_key, parent_transid))
480581c1760SQu Wenruo 				ret = -EUCLEAN;
481581c1760SQu Wenruo 			else
482581c1760SQu Wenruo 				break;
483256dd1bbSStefan Behrens 		}
484d397712bSChris Mason 
4850b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
486f188591eSChris Mason 					      eb->start, eb->len);
4874235298eSChris Mason 		if (num_copies == 1)
488ea466794SJosef Bacik 			break;
4894235298eSChris Mason 
4905cf1ab56SJosef Bacik 		if (!failed_mirror) {
4915cf1ab56SJosef Bacik 			failed = 1;
4925cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4935cf1ab56SJosef Bacik 		}
4945cf1ab56SJosef Bacik 
495f188591eSChris Mason 		mirror_num++;
496ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
497ea466794SJosef Bacik 			mirror_num++;
498ea466794SJosef Bacik 
4994235298eSChris Mason 		if (mirror_num > num_copies)
500ea466794SJosef Bacik 			break;
501f188591eSChris Mason 	}
502ea466794SJosef Bacik 
503c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
50420a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
505ea466794SJosef Bacik 
506ea466794SJosef Bacik 	return ret;
507f188591eSChris Mason }
50819c00ddcSChris Mason 
509d352ac68SChris Mason /*
510d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
511d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
512d352ac68SChris Mason  */
513d397712bSChris Mason 
51401d58472SDaniel Dressler static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
51519c00ddcSChris Mason {
5164eee4fa4SMiao Xie 	u64 start = page_offset(page);
51719c00ddcSChris Mason 	u64 found_start;
5182996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
5192996e1f8SJohannes Thumshirn 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
52019c00ddcSChris Mason 	struct extent_buffer *eb;
5218d47a0d8SQu Wenruo 	int ret;
522f188591eSChris Mason 
5234f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5244f2de97aSJosef Bacik 	if (page != eb->pages[0])
5254f2de97aSJosef Bacik 		return 0;
5260f805531SAlex Lyakas 
52719c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
5280f805531SAlex Lyakas 	/*
5290f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5300f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5310f805531SAlex Lyakas 	 */
5320f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5330f805531SAlex Lyakas 		return -EUCLEAN;
5340f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5350f805531SAlex Lyakas 		return -EUCLEAN;
5360f805531SAlex Lyakas 
537de37aa51SNikolay Borisov 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
5380f805531SAlex Lyakas 			btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
5390f805531SAlex Lyakas 
5402996e1f8SJohannes Thumshirn 	if (csum_tree_block(eb, result))
5412996e1f8SJohannes Thumshirn 		return -EINVAL;
5422996e1f8SJohannes Thumshirn 
5438d47a0d8SQu Wenruo 	if (btrfs_header_level(eb))
5448d47a0d8SQu Wenruo 		ret = btrfs_check_node(eb);
5458d47a0d8SQu Wenruo 	else
5468d47a0d8SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
5478d47a0d8SQu Wenruo 
5488d47a0d8SQu Wenruo 	if (ret < 0) {
549c06631b0SQu Wenruo 		btrfs_print_tree(eb, 0);
5508d47a0d8SQu Wenruo 		btrfs_err(fs_info,
5518d47a0d8SQu Wenruo 		"block=%llu write time tree block corruption detected",
5528d47a0d8SQu Wenruo 			  eb->start);
553c06631b0SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5548d47a0d8SQu Wenruo 		return ret;
5558d47a0d8SQu Wenruo 	}
5562996e1f8SJohannes Thumshirn 	write_extent_buffer(eb, result, 0, csum_size);
5578d47a0d8SQu Wenruo 
5582996e1f8SJohannes Thumshirn 	return 0;
55919c00ddcSChris Mason }
56019c00ddcSChris Mason 
561b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5622b82032cSYan Zheng {
563b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
56401d58472SDaniel Dressler 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
56544880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
5662b82032cSYan Zheng 	int ret = 1;
5672b82032cSYan Zheng 
5680a4e5586SRoss Kirk 	read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
5692b82032cSYan Zheng 	while (fs_devices) {
5707239ff4bSNikolay Borisov 		u8 *metadata_uuid;
5717239ff4bSNikolay Borisov 
5727239ff4bSNikolay Borisov 		/*
5737239ff4bSNikolay Borisov 		 * Checking the incompat flag is only valid for the current
5747239ff4bSNikolay Borisov 		 * fs. For seed devices it's forbidden to have their uuid
5757239ff4bSNikolay Borisov 		 * changed so reading ->fsid in this case is fine
5767239ff4bSNikolay Borisov 		 */
5777239ff4bSNikolay Borisov 		if (fs_devices == fs_info->fs_devices &&
5787239ff4bSNikolay Borisov 		    btrfs_fs_incompat(fs_info, METADATA_UUID))
5797239ff4bSNikolay Borisov 			metadata_uuid = fs_devices->metadata_uuid;
5807239ff4bSNikolay Borisov 		else
5817239ff4bSNikolay Borisov 			metadata_uuid = fs_devices->fsid;
5827239ff4bSNikolay Borisov 
5837239ff4bSNikolay Borisov 		if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE)) {
5842b82032cSYan Zheng 			ret = 0;
5852b82032cSYan Zheng 			break;
5862b82032cSYan Zheng 		}
5872b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5882b82032cSYan Zheng 	}
5892b82032cSYan Zheng 	return ret;
5902b82032cSYan Zheng }
5912b82032cSYan Zheng 
592facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
593facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
594facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
595ce9adaa5SChris Mason {
596ce9adaa5SChris Mason 	u64 found_start;
597ce9adaa5SChris Mason 	int found_level;
598ce9adaa5SChris Mason 	struct extent_buffer *eb;
599ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
60002873e43SZhao Lei 	struct btrfs_fs_info *fs_info = root->fs_info;
6012996e1f8SJohannes Thumshirn 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
602f188591eSChris Mason 	int ret = 0;
6032996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
604727011e0SChris Mason 	int reads_done;
605ce9adaa5SChris Mason 
606ce9adaa5SChris Mason 	if (!page->private)
607ce9adaa5SChris Mason 		goto out;
608d397712bSChris Mason 
6094f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
610d397712bSChris Mason 
6110b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
6120b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
6130b32f4bbSJosef Bacik 	 */
61467439dadSDavid Sterba 	atomic_inc(&eb->refs);
6150b32f4bbSJosef Bacik 
6160b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
617727011e0SChris Mason 	if (!reads_done)
618727011e0SChris Mason 		goto err;
619f188591eSChris Mason 
6205cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
621656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
622ea466794SJosef Bacik 		ret = -EIO;
623ea466794SJosef Bacik 		goto err;
624ea466794SJosef Bacik 	}
625ea466794SJosef Bacik 
626ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
627727011e0SChris Mason 	if (found_start != eb->start) {
628893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
629893bf4b1SSu Yue 			     eb->start, found_start);
630f188591eSChris Mason 		ret = -EIO;
631ce9adaa5SChris Mason 		goto err;
632ce9adaa5SChris Mason 	}
633b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
63402873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
63594647322SDavid Sterba 			     eb->start);
6361259ab75SChris Mason 		ret = -EIO;
6371259ab75SChris Mason 		goto err;
6381259ab75SChris Mason 	}
639ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6401c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
641893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
642893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
6431c24c3ceSJosef Bacik 		ret = -EIO;
6441c24c3ceSJosef Bacik 		goto err;
6451c24c3ceSJosef Bacik 	}
646ce9adaa5SChris Mason 
64785d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
64885d4e461SChris Mason 				       eb, found_level);
6494008c04aSChris Mason 
6502996e1f8SJohannes Thumshirn 	ret = csum_tree_block(eb, result);
6518bd98f0eSAlex Lyakas 	if (ret)
652a826d6dcSJosef Bacik 		goto err;
653a826d6dcSJosef Bacik 
6542996e1f8SJohannes Thumshirn 	if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
6552996e1f8SJohannes Thumshirn 		u32 val;
6562996e1f8SJohannes Thumshirn 		u32 found = 0;
6572996e1f8SJohannes Thumshirn 
6582996e1f8SJohannes Thumshirn 		memcpy(&found, result, csum_size);
6592996e1f8SJohannes Thumshirn 
6602996e1f8SJohannes Thumshirn 		read_extent_buffer(eb, &val, 0, csum_size);
6612996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
6622996e1f8SJohannes Thumshirn 		"%s checksum verify failed on %llu wanted %x found %x level %d",
6632996e1f8SJohannes Thumshirn 			      fs_info->sb->s_id, eb->start,
6642996e1f8SJohannes Thumshirn 			      val, found, btrfs_header_level(eb));
6652996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
6662996e1f8SJohannes Thumshirn 		goto err;
6672996e1f8SJohannes Thumshirn 	}
6682996e1f8SJohannes Thumshirn 
669a826d6dcSJosef Bacik 	/*
670a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
671a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
672a826d6dcSJosef Bacik 	 * return -EIO.
673a826d6dcSJosef Bacik 	 */
6741c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
675a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
676a826d6dcSJosef Bacik 		ret = -EIO;
677a826d6dcSJosef Bacik 	}
678ce9adaa5SChris Mason 
679813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
680053ab70fSLiu Bo 		ret = -EIO;
681053ab70fSLiu Bo 
6820b32f4bbSJosef Bacik 	if (!ret)
6830b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
68475391f0dSQu Wenruo 	else
68575391f0dSQu Wenruo 		btrfs_err(fs_info,
68675391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
68775391f0dSQu Wenruo 			  eb->start);
688ce9adaa5SChris Mason err:
68979fb65a1SJosef Bacik 	if (reads_done &&
69079fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
691d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6924bb31e92SArne Jansen 
69353b381b3SDavid Woodhouse 	if (ret) {
69453b381b3SDavid Woodhouse 		/*
69553b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
69653b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
69753b381b3SDavid Woodhouse 		 * to decrement
69853b381b3SDavid Woodhouse 		 */
69953b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7000b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
70153b381b3SDavid Woodhouse 	}
7020b32f4bbSJosef Bacik 	free_extent_buffer(eb);
703ce9adaa5SChris Mason out:
704f188591eSChris Mason 	return ret;
705ce9adaa5SChris Mason }
706ce9adaa5SChris Mason 
7074246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
708ce9adaa5SChris Mason {
70997eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
710ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7119e0af237SLiu Bo 	struct btrfs_workqueue *wq;
712ce9adaa5SChris Mason 
713ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7144e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
715d20f7043SChris Mason 
71637226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
717a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7189e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
719a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7209e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
721a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7229e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
723a0cac0ecSOmar Sandoval 		else
7249e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7259e0af237SLiu Bo 	} else {
726a0cac0ecSOmar Sandoval 		if (unlikely(end_io_wq->metadata == BTRFS_WQ_ENDIO_DIO_REPAIR))
7278b110e39SMiao Xie 			wq = fs_info->endio_repair_workers;
728a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7299e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
730a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7319e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
732a0cac0ecSOmar Sandoval 		else
7339e0af237SLiu Bo 			wq = fs_info->endio_workers;
7349e0af237SLiu Bo 	}
7359e0af237SLiu Bo 
736a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7379e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
738ce9adaa5SChris Mason }
739ce9adaa5SChris Mason 
7404e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
741bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7420b86a832SChris Mason {
74397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7448b110e39SMiao Xie 
74597eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
746ce9adaa5SChris Mason 	if (!end_io_wq)
7474e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
748ce9adaa5SChris Mason 
749ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
750ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
75122c59948SChris Mason 	end_io_wq->info = info;
7524e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
753ce9adaa5SChris Mason 	end_io_wq->bio = bio;
75422c59948SChris Mason 	end_io_wq->metadata = metadata;
755ce9adaa5SChris Mason 
756ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
757ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
75822c59948SChris Mason 	return 0;
75922c59948SChris Mason }
76022c59948SChris Mason 
7614a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7624a69a410SChris Mason {
7634a69a410SChris Mason 	struct async_submit_bio *async;
7644e4cbee9SChristoph Hellwig 	blk_status_t ret;
7654a69a410SChris Mason 
7664a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
767c6100a4bSJosef Bacik 	ret = async->submit_bio_start(async->private_data, async->bio,
768eaf25d93SChris Mason 				      async->bio_offset);
76979787eaaSJeff Mahoney 	if (ret)
7704e4cbee9SChristoph Hellwig 		async->status = ret;
7714a69a410SChris Mason }
7724a69a410SChris Mason 
77306ea01b1SDavid Sterba /*
77406ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
77506ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
77606ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
77706ea01b1SDavid Sterba  *
77806ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
77906ea01b1SDavid Sterba  * inserted into the tree.
78006ea01b1SDavid Sterba  */
7814a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7828b712842SChris Mason {
7838b712842SChris Mason 	struct async_submit_bio *async;
78406ea01b1SDavid Sterba 	struct inode *inode;
78506ea01b1SDavid Sterba 	blk_status_t ret;
7868b712842SChris Mason 
7878b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
78806ea01b1SDavid Sterba 	inode = async->private_data;
7894854ddd0SChris Mason 
790bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7914e4cbee9SChristoph Hellwig 	if (async->status) {
7924e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7934246a0b6SChristoph Hellwig 		bio_endio(async->bio);
79479787eaaSJeff Mahoney 		return;
79579787eaaSJeff Mahoney 	}
79679787eaaSJeff Mahoney 
797ec39f769SChris Mason 	/*
798ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
799ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
800ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
801ec39f769SChris Mason 	 */
802ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
80308635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
80406ea01b1SDavid Sterba 	if (ret) {
80506ea01b1SDavid Sterba 		async->bio->bi_status = ret;
80606ea01b1SDavid Sterba 		bio_endio(async->bio);
80706ea01b1SDavid Sterba 	}
8084a69a410SChris Mason }
8094a69a410SChris Mason 
8104a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8114a69a410SChris Mason {
8124a69a410SChris Mason 	struct async_submit_bio *async;
8134a69a410SChris Mason 
8144a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8158b712842SChris Mason 	kfree(async);
8168b712842SChris Mason }
8178b712842SChris Mason 
8188c27cb35SLinus Torvalds blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
819c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
820c6100a4bSJosef Bacik 				 u64 bio_offset, void *private_data,
821e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
82244b8bd7eSChris Mason {
82344b8bd7eSChris Mason 	struct async_submit_bio *async;
82444b8bd7eSChris Mason 
82544b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
82644b8bd7eSChris Mason 	if (!async)
8274e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
82844b8bd7eSChris Mason 
829c6100a4bSJosef Bacik 	async->private_data = private_data;
83044b8bd7eSChris Mason 	async->bio = bio;
83144b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8324a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8334a69a410SChris Mason 
834a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
835a0cac0ecSOmar Sandoval 			run_one_async_free);
8364a69a410SChris Mason 
837eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8388c8bee1dSChris Mason 
8394e4cbee9SChristoph Hellwig 	async->status = 0;
84079787eaaSJeff Mahoney 
84167f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8425cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
843d313d7a3SChris Mason 
8445cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
84544b8bd7eSChris Mason 	return 0;
84644b8bd7eSChris Mason }
84744b8bd7eSChris Mason 
8484e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
849ce3ed71aSChris Mason {
8502c30c71bSKent Overstreet 	struct bio_vec *bvec;
851ce3ed71aSChris Mason 	struct btrfs_root *root;
8522b070cfeSChristoph Hellwig 	int ret = 0;
8536dc4f100SMing Lei 	struct bvec_iter_all iter_all;
854ce3ed71aSChris Mason 
855c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8562b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
857ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
85801d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
85979787eaaSJeff Mahoney 		if (ret)
86079787eaaSJeff Mahoney 			break;
861ce3ed71aSChris Mason 	}
8622c30c71bSKent Overstreet 
8634e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
864ce3ed71aSChris Mason }
865ce3ed71aSChris Mason 
866d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
867eaf25d93SChris Mason 					     u64 bio_offset)
86822c59948SChris Mason {
8698b712842SChris Mason 	/*
8708b712842SChris Mason 	 * when we're called for a write, we're already in the async
8715443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8728b712842SChris Mason 	 */
87379787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
87422c59948SChris Mason }
87522c59948SChris Mason 
8769b4e675aSDavid Sterba static int check_async_write(struct btrfs_fs_info *fs_info,
8779b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
878de0022b9SJosef Bacik {
8796300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8806300463bSLiu Bo 		return 0;
8819b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
882de0022b9SJosef Bacik 		return 0;
883de0022b9SJosef Bacik 	return 1;
884de0022b9SJosef Bacik }
885de0022b9SJosef Bacik 
886a56b1c7bSNikolay Borisov static blk_status_t btree_submit_bio_hook(struct inode *inode, struct bio *bio,
88750489a57SNikolay Borisov 					  int mirror_num,
88850489a57SNikolay Borisov 					  unsigned long bio_flags)
88944b8bd7eSChris Mason {
8900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8919b4e675aSDavid Sterba 	int async = check_async_write(fs_info, BTRFS_I(inode));
8924e4cbee9SChristoph Hellwig 	blk_status_t ret;
893cad321adSChris Mason 
89437226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
895cad321adSChris Mason 		/*
896cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
897cad321adSChris Mason 		 * can happen in the async kernel threads
898cad321adSChris Mason 		 */
8990b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
9000b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
9011d4284bdSChris Mason 		if (ret)
90261891923SStefan Behrens 			goto out_w_error;
90308635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
904de0022b9SJosef Bacik 	} else if (!async) {
905de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
906de0022b9SJosef Bacik 		if (ret)
90761891923SStefan Behrens 			goto out_w_error;
90808635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
90961891923SStefan Behrens 	} else {
910cad321adSChris Mason 		/*
91161891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
91261891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
913cad321adSChris Mason 		 */
914c6100a4bSJosef Bacik 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
915e68f2ee7SNikolay Borisov 					  0, inode, btree_submit_bio_start);
91644b8bd7eSChris Mason 	}
91744b8bd7eSChris Mason 
9184246a0b6SChristoph Hellwig 	if (ret)
9194246a0b6SChristoph Hellwig 		goto out_w_error;
9204246a0b6SChristoph Hellwig 	return 0;
9214246a0b6SChristoph Hellwig 
92261891923SStefan Behrens out_w_error:
9234e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9244246a0b6SChristoph Hellwig 	bio_endio(bio);
92561891923SStefan Behrens 	return ret;
92661891923SStefan Behrens }
92761891923SStefan Behrens 
9283dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
929784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
930a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
931a6bc32b8SMel Gorman 			enum migrate_mode mode)
932784b4e29SChris Mason {
933784b4e29SChris Mason 	/*
934784b4e29SChris Mason 	 * we can't safely write a btree page from here,
935784b4e29SChris Mason 	 * we haven't done the locking hook
936784b4e29SChris Mason 	 */
937784b4e29SChris Mason 	if (PageDirty(page))
938784b4e29SChris Mason 		return -EAGAIN;
939784b4e29SChris Mason 	/*
940784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
941784b4e29SChris Mason 	 * We must have no buffers or drop them.
942784b4e29SChris Mason 	 */
943784b4e29SChris Mason 	if (page_has_private(page) &&
944784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
945784b4e29SChris Mason 		return -EAGAIN;
946a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
947784b4e29SChris Mason }
9483dd1462eSJan Beulich #endif
949784b4e29SChris Mason 
9500da5468fSChris Mason 
9510da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9520da5468fSChris Mason 			    struct writeback_control *wbc)
9530da5468fSChris Mason {
954e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
955e2d84521SMiao Xie 	int ret;
956e2d84521SMiao Xie 
957d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
958448d640bSChris Mason 
959448d640bSChris Mason 		if (wbc->for_kupdate)
960448d640bSChris Mason 			return 0;
961448d640bSChris Mason 
962e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
963b9473439SChris Mason 		/* this is a bit racy, but that's ok */
964d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
965d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
966d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
967e2d84521SMiao Xie 		if (ret < 0)
968793955bcSChris Mason 			return 0;
969793955bcSChris Mason 	}
9700b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9710da5468fSChris Mason }
9720da5468fSChris Mason 
973b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9745f39d397SChris Mason {
975d1310b2eSChris Mason 	struct extent_io_tree *tree;
976d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9778ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
9785f39d397SChris Mason }
9795f39d397SChris Mason 
98070dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9815f39d397SChris Mason {
98298509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
98398509cfcSChris Mason 		return 0;
9840c4e538bSDavid Sterba 
985f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
986d98237b3SChris Mason }
987d98237b3SChris Mason 
988d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
989d47992f8SLukas Czerner 				 unsigned int length)
990d98237b3SChris Mason {
991d1310b2eSChris Mason 	struct extent_io_tree *tree;
992d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9935f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9945f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9959ad6b7bcSChris Mason 	if (PagePrivate(page)) {
996efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
997efe120a0SFrank Holton 			   "page private not zero on page %llu",
998efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
9999ad6b7bcSChris Mason 		ClearPagePrivate(page);
10009ad6b7bcSChris Mason 		set_page_private(page, 0);
100109cbfeafSKirill A. Shutemov 		put_page(page);
10029ad6b7bcSChris Mason 	}
1003d98237b3SChris Mason }
1004d98237b3SChris Mason 
10050b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10060b32f4bbSJosef Bacik {
1007bb146eb2SJosef Bacik #ifdef DEBUG
10080b32f4bbSJosef Bacik 	struct extent_buffer *eb;
10090b32f4bbSJosef Bacik 
10100b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
10110b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
10120b32f4bbSJosef Bacik 	BUG_ON(!eb);
10130b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10140b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
10150b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
1016bb146eb2SJosef Bacik #endif
10170b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10180b32f4bbSJosef Bacik }
10190b32f4bbSJosef Bacik 
10207f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
1021d98237b3SChris Mason 	.readpage	= btree_readpage,
10220da5468fSChris Mason 	.writepages	= btree_writepages,
10235f39d397SChris Mason 	.releasepage	= btree_releasepage,
10245f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10255a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1026784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10275a92bc88SChris Mason #endif
10280b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1029d98237b3SChris Mason };
1030123abc88SChris Mason 
10312ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1032090d1875SChris Mason {
10335f39d397SChris Mason 	struct extent_buffer *buf = NULL;
1034537f38f0SNikolay Borisov 	int ret;
1035090d1875SChris Mason 
10362ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1037c871b0f2SLiu Bo 	if (IS_ERR(buf))
10386197d86eSDavid Sterba 		return;
1039537f38f0SNikolay Borisov 
1040c2ccfbc6SNikolay Borisov 	ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
1041537f38f0SNikolay Borisov 	if (ret < 0)
1042537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
1043537f38f0SNikolay Borisov 	else
10445f39d397SChris Mason 		free_extent_buffer(buf);
1045090d1875SChris Mason }
1046090d1875SChris Mason 
10472ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10482ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10490308af44SDavid Sterba 						u64 bytenr)
10500999df54SChris Mason {
10510b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10520b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10530b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
10540999df54SChris Mason }
10550999df54SChris Mason 
1056581c1760SQu Wenruo /*
1057581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1058581c1760SQu Wenruo  * verification.
1059581c1760SQu Wenruo  *
1060581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1061581c1760SQu Wenruo  * @level:		expected level, mandatory check
1062581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1063581c1760SQu Wenruo  */
10642ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1065581c1760SQu Wenruo 				      u64 parent_transid, int level,
1066581c1760SQu Wenruo 				      struct btrfs_key *first_key)
1067e20d96d6SChris Mason {
10685f39d397SChris Mason 	struct extent_buffer *buf = NULL;
106919c00ddcSChris Mason 	int ret;
107019c00ddcSChris Mason 
10712ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1072c871b0f2SLiu Bo 	if (IS_ERR(buf))
1073c871b0f2SLiu Bo 		return buf;
1074e4204dedSChris Mason 
10755ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1076581c1760SQu Wenruo 					     level, first_key);
10770f0fe8f7SFilipe David Borba Manana 	if (ret) {
1078537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
107964c043deSLiu Bo 		return ERR_PTR(ret);
10800f0fe8f7SFilipe David Borba Manana 	}
10815f39d397SChris Mason 	return buf;
1082ce9adaa5SChris Mason 
1083eb60ceacSChris Mason }
1084eb60ceacSChris Mason 
10856a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1086ed2ff2cbSChris Mason {
10876a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
108855c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1089e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1090b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1091b4ce94deSChris Mason 
1092b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1093104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1094e2d84521SMiao Xie 						 -buf->len,
1095e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
1096b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
10978bead258SDavid Sterba 			btrfs_set_lock_blocking_write(buf);
10980b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1099925baeddSChris Mason 		}
11005f39d397SChris Mason 	}
1101ed7b63ebSJosef Bacik }
11025f39d397SChris Mason 
11038257b2dcSMiao Xie static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
11048257b2dcSMiao Xie {
11058257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
11068257b2dcSMiao Xie 	int ret;
11078257b2dcSMiao Xie 
11088257b2dcSMiao Xie 	writers = kmalloc(sizeof(*writers), GFP_NOFS);
11098257b2dcSMiao Xie 	if (!writers)
11108257b2dcSMiao Xie 		return ERR_PTR(-ENOMEM);
11118257b2dcSMiao Xie 
11128a5a916dSJeff Mahoney 	ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
11138257b2dcSMiao Xie 	if (ret < 0) {
11148257b2dcSMiao Xie 		kfree(writers);
11158257b2dcSMiao Xie 		return ERR_PTR(ret);
11168257b2dcSMiao Xie 	}
11178257b2dcSMiao Xie 
11188257b2dcSMiao Xie 	init_waitqueue_head(&writers->wait);
11198257b2dcSMiao Xie 	return writers;
11208257b2dcSMiao Xie }
11218257b2dcSMiao Xie 
11228257b2dcSMiao Xie static void
11238257b2dcSMiao Xie btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
11248257b2dcSMiao Xie {
11258257b2dcSMiao Xie 	percpu_counter_destroy(&writers->counter);
11268257b2dcSMiao Xie 	kfree(writers);
11278257b2dcSMiao Xie }
11288257b2dcSMiao Xie 
1129da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1130e20d96d6SChris Mason 			 u64 objectid)
1131d97e63b6SChris Mason {
11327c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1133cfaa7295SChris Mason 	root->node = NULL;
1134a28ec197SChris Mason 	root->commit_root = NULL;
113527cdeb70SMiao Xie 	root->state = 0;
1136d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11370b86a832SChris Mason 
11380f7d52f4SChris Mason 	root->last_trans = 0;
113913a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1140eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1141199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11426bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
114316cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1144f0486c68SYan, Zheng 	root->block_rsv = NULL;
11450b86a832SChris Mason 
11460b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11475d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1148eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1149eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1150199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1151199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1152d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11532ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11542ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11555d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1156eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1157199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1158f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11592ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11602ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11618287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1162a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1163e02119d5SChris Mason 	mutex_init(&root->log_mutex);
116431f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1165573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
11667237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11677237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11687237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11698b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11708b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11717237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11727237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11737237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11742ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11750700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
1176ea14b57fSDavid Sterba 	atomic_set(&root->will_be_snapshotted, 0);
11778ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1178eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11797237f183SYan Zheng 	root->log_transid = 0;
1180d1433debSMiao Xie 	root->log_transid_committed = -1;
1181257c62e1SChris Mason 	root->last_log_commit = 0;
11827c0260eeSJeff Mahoney 	if (!dummy)
118343eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
118443eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1185017e5369SChris Mason 
11863768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11873768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11886702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
11897c0260eeSJeff Mahoney 	if (!dummy)
11903f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
119106ea65a3SJosef Bacik 	else
119206ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
11934d775673SChris Mason 	root->root_key.objectid = objectid;
11940ee5dc67SAl Viro 	root->anon_dev = 0;
11958ea05e3aSAlexander Block 
11965f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1197370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
11983768f368SChris Mason }
11993768f368SChris Mason 
120074e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
120174e4d827SDavid Sterba 		gfp_t flags)
12026f07e42eSAl Viro {
120374e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12046f07e42eSAl Viro 	if (root)
12056f07e42eSAl Viro 		root->fs_info = fs_info;
12066f07e42eSAl Viro 	return root;
12076f07e42eSAl Viro }
12086f07e42eSAl Viro 
120906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121006ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1211da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
121206ea65a3SJosef Bacik {
121306ea65a3SJosef Bacik 	struct btrfs_root *root;
121406ea65a3SJosef Bacik 
12157c0260eeSJeff Mahoney 	if (!fs_info)
12167c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12177c0260eeSJeff Mahoney 
12187c0260eeSJeff Mahoney 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
121906ea65a3SJosef Bacik 	if (!root)
122006ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1221da17066cSJeff Mahoney 
1222b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1223da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1224faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
122506ea65a3SJosef Bacik 
122606ea65a3SJosef Bacik 	return root;
122706ea65a3SJosef Bacik }
122806ea65a3SJosef Bacik #endif
122906ea65a3SJosef Bacik 
123020897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
123120897f5cSArne Jansen 				     u64 objectid)
123220897f5cSArne Jansen {
12339b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
123420897f5cSArne Jansen 	struct extent_buffer *leaf;
123520897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
123620897f5cSArne Jansen 	struct btrfs_root *root;
123720897f5cSArne Jansen 	struct btrfs_key key;
1238b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
123920897f5cSArne Jansen 	int ret = 0;
124033d85fdaSQu Wenruo 	uuid_le uuid = NULL_UUID_LE;
124120897f5cSArne Jansen 
1242b89f6d1fSFilipe Manana 	/*
1243b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1244b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1245b89f6d1fSFilipe Manana 	 */
1246b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
124774e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1248b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
124920897f5cSArne Jansen 	if (!root)
125020897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
125120897f5cSArne Jansen 
1252da17066cSJeff Mahoney 	__setup_root(root, fs_info, objectid);
125320897f5cSArne Jansen 	root->root_key.objectid = objectid;
125420897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
125520897f5cSArne Jansen 	root->root_key.offset = 0;
125620897f5cSArne Jansen 
12574d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
125820897f5cSArne Jansen 	if (IS_ERR(leaf)) {
125920897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12601dd05682STsutomu Itoh 		leaf = NULL;
126120897f5cSArne Jansen 		goto fail;
126220897f5cSArne Jansen 	}
126320897f5cSArne Jansen 
126420897f5cSArne Jansen 	root->node = leaf;
126520897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
126620897f5cSArne Jansen 
126720897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
126827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
126920897f5cSArne Jansen 
127020897f5cSArne Jansen 	root->root_item.flags = 0;
127120897f5cSArne Jansen 	root->root_item.byte_limit = 0;
127220897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
127320897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
127420897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
127520897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
127620897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
127720897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
127820897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
127933d85fdaSQu Wenruo 	if (is_fstree(objectid))
12806463fe58SStefan Behrens 		uuid_le_gen(&uuid);
12816463fe58SStefan Behrens 	memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
128220897f5cSArne Jansen 	root->root_item.drop_level = 0;
128320897f5cSArne Jansen 
128420897f5cSArne Jansen 	key.objectid = objectid;
128520897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
128620897f5cSArne Jansen 	key.offset = 0;
128720897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
128820897f5cSArne Jansen 	if (ret)
128920897f5cSArne Jansen 		goto fail;
129020897f5cSArne Jansen 
129120897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
129220897f5cSArne Jansen 
129320897f5cSArne Jansen 	return root;
12941dd05682STsutomu Itoh 
12951dd05682STsutomu Itoh fail:
12961dd05682STsutomu Itoh 	if (leaf) {
12971dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
129859885b39STsutomu Itoh 		free_extent_buffer(root->commit_root);
12991dd05682STsutomu Itoh 		free_extent_buffer(leaf);
13001dd05682STsutomu Itoh 	}
13011dd05682STsutomu Itoh 	kfree(root);
13021dd05682STsutomu Itoh 
13031dd05682STsutomu Itoh 	return ERR_PTR(ret);
130420897f5cSArne Jansen }
130520897f5cSArne Jansen 
13067237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1307e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13080f7d52f4SChris Mason {
13090f7d52f4SChris Mason 	struct btrfs_root *root;
13107237f183SYan Zheng 	struct extent_buffer *leaf;
1311e02119d5SChris Mason 
131274e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1313e02119d5SChris Mason 	if (!root)
13147237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1315e02119d5SChris Mason 
1316da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1317e02119d5SChris Mason 
1318e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1319e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1320e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
132127cdeb70SMiao Xie 
13227237f183SYan Zheng 	/*
132327cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
132427cdeb70SMiao Xie 	 *
13257237f183SYan Zheng 	 * log trees do not get reference counted because they go away
13267237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
13277237f183SYan Zheng 	 * to file data extents, and those reference counts still get
13287237f183SYan Zheng 	 * updated (along with back refs to the log tree).
13297237f183SYan Zheng 	 */
1330e02119d5SChris Mason 
13314d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13324d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
13337237f183SYan Zheng 	if (IS_ERR(leaf)) {
13347237f183SYan Zheng 		kfree(root);
13357237f183SYan Zheng 		return ERR_CAST(leaf);
13367237f183SYan Zheng 	}
1337e02119d5SChris Mason 
13387237f183SYan Zheng 	root->node = leaf;
1339e02119d5SChris Mason 
1340e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1341e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13427237f183SYan Zheng 	return root;
13437237f183SYan Zheng }
13447237f183SYan Zheng 
13457237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13467237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13477237f183SYan Zheng {
13487237f183SYan Zheng 	struct btrfs_root *log_root;
13497237f183SYan Zheng 
13507237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13517237f183SYan Zheng 	if (IS_ERR(log_root))
13527237f183SYan Zheng 		return PTR_ERR(log_root);
13537237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13547237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13557237f183SYan Zheng 	return 0;
13567237f183SYan Zheng }
13577237f183SYan Zheng 
13587237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13597237f183SYan Zheng 		       struct btrfs_root *root)
13607237f183SYan Zheng {
13610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13627237f183SYan Zheng 	struct btrfs_root *log_root;
13637237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13647237f183SYan Zheng 
13650b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13667237f183SYan Zheng 	if (IS_ERR(log_root))
13677237f183SYan Zheng 		return PTR_ERR(log_root);
13687237f183SYan Zheng 
13697237f183SYan Zheng 	log_root->last_trans = trans->transid;
13707237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13717237f183SYan Zheng 
13727237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13733cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13743cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13753cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1376da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13770b246afaSJeff Mahoney 				     fs_info->nodesize);
13783cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13797237f183SYan Zheng 
13805d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13817237f183SYan Zheng 
13827237f183SYan Zheng 	WARN_ON(root->log_root);
13837237f183SYan Zheng 	root->log_root = log_root;
13847237f183SYan Zheng 	root->log_transid = 0;
1385d1433debSMiao Xie 	root->log_transid_committed = -1;
1386257c62e1SChris Mason 	root->last_log_commit = 0;
1387e02119d5SChris Mason 	return 0;
1388e02119d5SChris Mason }
1389e02119d5SChris Mason 
139035a3621bSStefan Behrens static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1391cb517eabSMiao Xie 					       struct btrfs_key *key)
1392e02119d5SChris Mason {
1393e02119d5SChris Mason 	struct btrfs_root *root;
1394e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
13950f7d52f4SChris Mason 	struct btrfs_path *path;
139684234f3aSYan Zheng 	u64 generation;
1397cb517eabSMiao Xie 	int ret;
1398581c1760SQu Wenruo 	int level;
1399cb517eabSMiao Xie 
1400cb517eabSMiao Xie 	path = btrfs_alloc_path();
1401cb517eabSMiao Xie 	if (!path)
1402cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
14030f7d52f4SChris Mason 
140474e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1405cb517eabSMiao Xie 	if (!root) {
1406cb517eabSMiao Xie 		ret = -ENOMEM;
1407cb517eabSMiao Xie 		goto alloc_fail;
14080f7d52f4SChris Mason 	}
14090f7d52f4SChris Mason 
1410da17066cSJeff Mahoney 	__setup_root(root, fs_info, key->objectid);
14110f7d52f4SChris Mason 
1412cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1413cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14140f7d52f4SChris Mason 	if (ret) {
141513a8a7c8SYan, Zheng 		if (ret > 0)
141613a8a7c8SYan, Zheng 			ret = -ENOENT;
1417cb517eabSMiao Xie 		goto find_fail;
14180f7d52f4SChris Mason 	}
141913a8a7c8SYan, Zheng 
142084234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1421581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14222ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14232ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1424581c1760SQu Wenruo 				     generation, level, NULL);
142564c043deSLiu Bo 	if (IS_ERR(root->node)) {
142664c043deSLiu Bo 		ret = PTR_ERR(root->node);
1427cb517eabSMiao Xie 		goto find_fail;
1428cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1429cb517eabSMiao Xie 		ret = -EIO;
143064c043deSLiu Bo 		free_extent_buffer(root->node);
143164c043deSLiu Bo 		goto find_fail;
1432416bc658SJosef Bacik 	}
14335d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
143413a8a7c8SYan, Zheng out:
1435cb517eabSMiao Xie 	btrfs_free_path(path);
1436cb517eabSMiao Xie 	return root;
1437cb517eabSMiao Xie 
1438cb517eabSMiao Xie find_fail:
1439cb517eabSMiao Xie 	kfree(root);
1440cb517eabSMiao Xie alloc_fail:
1441cb517eabSMiao Xie 	root = ERR_PTR(ret);
1442cb517eabSMiao Xie 	goto out;
1443cb517eabSMiao Xie }
1444cb517eabSMiao Xie 
1445cb517eabSMiao Xie struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1446cb517eabSMiao Xie 				      struct btrfs_key *location)
1447cb517eabSMiao Xie {
1448cb517eabSMiao Xie 	struct btrfs_root *root;
1449cb517eabSMiao Xie 
1450cb517eabSMiao Xie 	root = btrfs_read_tree_root(tree_root, location);
1451cb517eabSMiao Xie 	if (IS_ERR(root))
1452cb517eabSMiao Xie 		return root;
1453cb517eabSMiao Xie 
1454cb517eabSMiao Xie 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
145527cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
145608fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
145708fe4db1SLi Zefan 	}
145813a8a7c8SYan, Zheng 
14595eda7b5eSChris Mason 	return root;
14605eda7b5eSChris Mason }
14615eda7b5eSChris Mason 
1462cb517eabSMiao Xie int btrfs_init_fs_root(struct btrfs_root *root)
1463cb517eabSMiao Xie {
1464cb517eabSMiao Xie 	int ret;
14658257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
1466cb517eabSMiao Xie 
1467cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1468cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1469cb517eabSMiao Xie 					GFP_NOFS);
1470cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1471cb517eabSMiao Xie 		ret = -ENOMEM;
1472cb517eabSMiao Xie 		goto fail;
1473cb517eabSMiao Xie 	}
1474cb517eabSMiao Xie 
14758257b2dcSMiao Xie 	writers = btrfs_alloc_subvolume_writers();
14768257b2dcSMiao Xie 	if (IS_ERR(writers)) {
14778257b2dcSMiao Xie 		ret = PTR_ERR(writers);
14788257b2dcSMiao Xie 		goto fail;
14798257b2dcSMiao Xie 	}
14808257b2dcSMiao Xie 	root->subv_writers = writers;
14818257b2dcSMiao Xie 
1482cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
148357cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
148457cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1485cb517eabSMiao Xie 
1486cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1487cb517eabSMiao Xie 	if (ret)
1488876d2cf1SLiu Bo 		goto fail;
1489f32e48e9SChandan Rajendra 
1490f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1491f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1492f32e48e9SChandan Rajendra 					&root->highest_objectid);
1493f32e48e9SChandan Rajendra 	if (ret) {
1494f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1495876d2cf1SLiu Bo 		goto fail;
1496f32e48e9SChandan Rajendra 	}
1497f32e48e9SChandan Rajendra 
1498f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1499f32e48e9SChandan Rajendra 
1500f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1501f32e48e9SChandan Rajendra 
1502cb517eabSMiao Xie 	return 0;
1503cb517eabSMiao Xie fail:
150484db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1505cb517eabSMiao Xie 	return ret;
1506cb517eabSMiao Xie }
1507cb517eabSMiao Xie 
150835bbb97fSJeff Mahoney struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1509cb517eabSMiao Xie 					u64 root_id)
1510cb517eabSMiao Xie {
1511cb517eabSMiao Xie 	struct btrfs_root *root;
1512cb517eabSMiao Xie 
1513cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1514cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1515cb517eabSMiao Xie 				 (unsigned long)root_id);
1516cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1517cb517eabSMiao Xie 	return root;
1518cb517eabSMiao Xie }
1519cb517eabSMiao Xie 
1520cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1521cb517eabSMiao Xie 			 struct btrfs_root *root)
1522cb517eabSMiao Xie {
1523cb517eabSMiao Xie 	int ret;
1524cb517eabSMiao Xie 
1525e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1526cb517eabSMiao Xie 	if (ret)
1527cb517eabSMiao Xie 		return ret;
1528cb517eabSMiao Xie 
1529cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1530cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1531cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1532cb517eabSMiao Xie 				root);
1533cb517eabSMiao Xie 	if (ret == 0)
153427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1535cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1536cb517eabSMiao Xie 	radix_tree_preload_end();
1537cb517eabSMiao Xie 
1538cb517eabSMiao Xie 	return ret;
1539cb517eabSMiao Xie }
1540cb517eabSMiao Xie 
1541c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1542c00869f1SMiao Xie 				     struct btrfs_key *location,
1543c00869f1SMiao Xie 				     bool check_ref)
15445eda7b5eSChris Mason {
15455eda7b5eSChris Mason 	struct btrfs_root *root;
1546381cf658SDavid Sterba 	struct btrfs_path *path;
15471d4c08e0SDavid Sterba 	struct btrfs_key key;
15485eda7b5eSChris Mason 	int ret;
15495eda7b5eSChris Mason 
1550edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1551edbd8d4eSChris Mason 		return fs_info->tree_root;
1552edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1553edbd8d4eSChris Mason 		return fs_info->extent_root;
15548f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
15558f18cf13SChris Mason 		return fs_info->chunk_root;
15568f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
15578f18cf13SChris Mason 		return fs_info->dev_root;
15580403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
15590403e47eSYan Zheng 		return fs_info->csum_root;
1560bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1561bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1562bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
1563f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1564f7a81ea4SStefan Behrens 		return fs_info->uuid_root ? fs_info->uuid_root :
1565f7a81ea4SStefan Behrens 					    ERR_PTR(-ENOENT);
156670f6d82eSOmar Sandoval 	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
156770f6d82eSOmar Sandoval 		return fs_info->free_space_root ? fs_info->free_space_root :
156870f6d82eSOmar Sandoval 						  ERR_PTR(-ENOENT);
15694df27c4dSYan, Zheng again:
1570cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
157148475471SStefan Behrens 	if (root) {
1572c00869f1SMiao Xie 		if (check_ref && btrfs_root_refs(&root->root_item) == 0)
157348475471SStefan Behrens 			return ERR_PTR(-ENOENT);
15745eda7b5eSChris Mason 		return root;
157548475471SStefan Behrens 	}
15765eda7b5eSChris Mason 
1577cb517eabSMiao Xie 	root = btrfs_read_fs_root(fs_info->tree_root, location);
15785eda7b5eSChris Mason 	if (IS_ERR(root))
15795eda7b5eSChris Mason 		return root;
15803394e160SChris Mason 
1581c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1582d68fc57bSYan, Zheng 		ret = -ENOENT;
1583d68fc57bSYan, Zheng 		goto fail;
1584d68fc57bSYan, Zheng 	}
1585d68fc57bSYan, Zheng 
1586cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1587cb517eabSMiao Xie 	if (ret)
1588cb517eabSMiao Xie 		goto fail;
1589cb517eabSMiao Xie 
1590381cf658SDavid Sterba 	path = btrfs_alloc_path();
1591381cf658SDavid Sterba 	if (!path) {
1592381cf658SDavid Sterba 		ret = -ENOMEM;
1593381cf658SDavid Sterba 		goto fail;
1594381cf658SDavid Sterba 	}
15951d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15961d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
15971d4c08e0SDavid Sterba 	key.offset = location->objectid;
15981d4c08e0SDavid Sterba 
15991d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1600381cf658SDavid Sterba 	btrfs_free_path(path);
1601d68fc57bSYan, Zheng 	if (ret < 0)
1602d68fc57bSYan, Zheng 		goto fail;
1603d68fc57bSYan, Zheng 	if (ret == 0)
160427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1605d68fc57bSYan, Zheng 
1606cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16070f7d52f4SChris Mason 	if (ret) {
16084df27c4dSYan, Zheng 		if (ret == -EEXIST) {
160984db5ccfSDavid Sterba 			btrfs_free_fs_root(root);
16104df27c4dSYan, Zheng 			goto again;
16110f7d52f4SChris Mason 		}
16124df27c4dSYan, Zheng 		goto fail;
16134df27c4dSYan, Zheng 	}
1614edbd8d4eSChris Mason 	return root;
16154df27c4dSYan, Zheng fail:
161684db5ccfSDavid Sterba 	btrfs_free_fs_root(root);
16174df27c4dSYan, Zheng 	return ERR_PTR(ret);
1618edbd8d4eSChris Mason }
1619edbd8d4eSChris Mason 
162004160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
162104160088SChris Mason {
162204160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
162304160088SChris Mason 	int ret = 0;
162404160088SChris Mason 	struct btrfs_device *device;
162504160088SChris Mason 	struct backing_dev_info *bdi;
1626b7967db7SChris Mason 
16271f78160cSXiao Guangrong 	rcu_read_lock();
16281f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1629dfe25020SChris Mason 		if (!device->bdev)
1630dfe25020SChris Mason 			continue;
1631efa7c9f9SJan Kara 		bdi = device->bdev->bd_bdi;
1632ff9ea323STejun Heo 		if (bdi_congested(bdi, bdi_bits)) {
163304160088SChris Mason 			ret = 1;
163404160088SChris Mason 			break;
163504160088SChris Mason 		}
163604160088SChris Mason 	}
16371f78160cSXiao Guangrong 	rcu_read_unlock();
163804160088SChris Mason 	return ret;
163904160088SChris Mason }
164004160088SChris Mason 
16418b712842SChris Mason /*
16428b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16438b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16448b712842SChris Mason  */
16458b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1646ce9adaa5SChris Mason {
1647ce9adaa5SChris Mason 	struct bio *bio;
164897eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1649ce9adaa5SChris Mason 
165097eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1651ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16528b712842SChris Mason 
16534e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1654ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1655ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
16564246a0b6SChristoph Hellwig 	bio_endio(bio);
16579be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1658ce9adaa5SChris Mason }
165944b8bd7eSChris Mason 
1660a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1661a74a4b97SChris Mason {
1662a74a4b97SChris Mason 	struct btrfs_root *root = arg;
16630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1664d0278245SMiao Xie 	int again;
1665a74a4b97SChris Mason 
1666d6fd0ae2SOmar Sandoval 	while (1) {
1667d0278245SMiao Xie 		again = 0;
16689d1a2a3aSDavid Sterba 
1669fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1670fd340d0fSJosef Bacik 
1671d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16722ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1673d0278245SMiao Xie 			goto sleep;
1674d0278245SMiao Xie 
167590c711abSZygo Blaxell 		/*
167690c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
167790c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
167890c711abSZygo Blaxell 		 */
16790b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
168090c711abSZygo Blaxell 			goto sleep;
168190c711abSZygo Blaxell 
16820b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1683d0278245SMiao Xie 			goto sleep;
1684d0278245SMiao Xie 
1685dc7f370cSMiao Xie 		/*
1686dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1687dc7f370cSMiao Xie 		 * during the above check and trylock.
1688dc7f370cSMiao Xie 		 */
16892ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
16900b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1691dc7f370cSMiao Xie 			goto sleep;
1692dc7f370cSMiao Xie 		}
1693dc7f370cSMiao Xie 
16942ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1695c2d6cb16SFilipe Manana 
16969d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
16970b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1698a74a4b97SChris Mason 
1699d0278245SMiao Xie 		/*
170005323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
170105323cd1SMiao Xie 		 * needn't do anything special here.
1702d0278245SMiao Xie 		 */
17030b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
170467c5e7d4SFilipe Manana 
170567c5e7d4SFilipe Manana 		/*
170667c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
170767c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
170867c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
170967c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
171067c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
171167c5e7d4SFilipe Manana 		 * unused block groups.
171267c5e7d4SFilipe Manana 		 */
17130b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1714d0278245SMiao Xie sleep:
1715fd340d0fSJosef Bacik 		clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1716d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1717d6fd0ae2SOmar Sandoval 			kthread_parkme();
1718d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1719d6fd0ae2SOmar Sandoval 			return 0;
1720838fe188SJiri Kosina 		if (!again) {
1721a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1722a74a4b97SChris Mason 			schedule();
1723a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1724a74a4b97SChris Mason 		}
1725da288d28SFilipe Manana 	}
1726a74a4b97SChris Mason }
1727a74a4b97SChris Mason 
1728a74a4b97SChris Mason static int transaction_kthread(void *arg)
1729a74a4b97SChris Mason {
1730a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1732a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1733a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17348929ecfaSYan, Zheng 	u64 transid;
1735a944442cSAllen Pais 	time64_t now;
1736a74a4b97SChris Mason 	unsigned long delay;
1737914b2007SJan Kara 	bool cannot_commit;
1738a74a4b97SChris Mason 
1739a74a4b97SChris Mason 	do {
1740914b2007SJan Kara 		cannot_commit = false;
17410b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
17420b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1743a74a4b97SChris Mason 
17440b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17450b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1746a74a4b97SChris Mason 		if (!cur) {
17470b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1748a74a4b97SChris Mason 			goto sleep;
1749a74a4b97SChris Mason 		}
175031153d81SYan Zheng 
1751afd48513SArnd Bergmann 		now = ktime_get_seconds();
17523296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1753a514d638SQu Wenruo 		    !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
17548b87dc17SDavid Sterba 		    (now < cur->start_time ||
17550b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
17560b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1757a74a4b97SChris Mason 			delay = HZ * 5;
1758a74a4b97SChris Mason 			goto sleep;
1759a74a4b97SChris Mason 		}
17608929ecfaSYan, Zheng 		transid = cur->transid;
17610b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
176256bec294SChris Mason 
176379787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1764354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1765914b2007SJan Kara 		if (IS_ERR(trans)) {
1766354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1767914b2007SJan Kara 				cannot_commit = true;
176879787eaaSJeff Mahoney 			goto sleep;
1769914b2007SJan Kara 		}
17708929ecfaSYan, Zheng 		if (transid == trans->transid) {
17713a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
17728929ecfaSYan, Zheng 		} else {
17733a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
17748929ecfaSYan, Zheng 		}
1775a74a4b97SChris Mason sleep:
17760b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
17770b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1778a74a4b97SChris Mason 
17794e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
17800b246afaSJeff Mahoney 				      &fs_info->fs_state)))
17812ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
17828929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
17830b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1784914b2007SJan Kara 				 cannot_commit))
1785bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1786a74a4b97SChris Mason 	} while (!kthread_should_stop());
1787a74a4b97SChris Mason 	return 0;
1788a74a4b97SChris Mason }
1789a74a4b97SChris Mason 
1790af31f5e5SChris Mason /*
179101f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
179201f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
179301f0f9daSNikolay Borisov  * anything.
1794af31f5e5SChris Mason  *
1795af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1796af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1797af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1798af31f5e5SChris Mason  */
179901f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1800af31f5e5SChris Mason {
180101f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1802af31f5e5SChris Mason 	u64 cur;
1803af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1804af31f5e5SChris Mason 	int i;
1805af31f5e5SChris Mason 
1806af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1807af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1808af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1809af31f5e5SChris Mason 		if (cur == newest_gen)
181001f0f9daSNikolay Borisov 			return i;
1811af31f5e5SChris Mason 	}
1812af31f5e5SChris Mason 
181301f0f9daSNikolay Borisov 	return -EINVAL;
1814af31f5e5SChris Mason }
1815af31f5e5SChris Mason 
1816af31f5e5SChris Mason /*
1817af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1818af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1819af31f5e5SChris Mason  * done
1820af31f5e5SChris Mason  */
1821af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1822af31f5e5SChris Mason {
18236ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1824af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1825af31f5e5SChris Mason 
1826af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1827af31f5e5SChris Mason 
1828af31f5e5SChris Mason 	/*
1829af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1830af31f5e5SChris Mason 	 * regardless of which ones we use today
1831af31f5e5SChris Mason 	 */
1832af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1833af31f5e5SChris Mason 
1834af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1835af31f5e5SChris Mason 
1836af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1837af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1838af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1839af31f5e5SChris Mason 
1840af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1841af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1842af31f5e5SChris Mason 
1843af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1844af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1845af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1846af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1847af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1848af31f5e5SChris Mason 
1849af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1850af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1851af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1852af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1853af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1854af31f5e5SChris Mason 
18557c7e82a7SChris Mason 	/*
18567c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18577c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18587c7e82a7SChris Mason 	 */
18597c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18607c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18617c7e82a7SChris Mason 					 info->fs_root->node->start);
1862af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1863af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1864af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1865af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
18667c7e82a7SChris Mason 	}
1867af31f5e5SChris Mason 
1868af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1869af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1870af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1871af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1872af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1873af31f5e5SChris Mason 
1874af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1875af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1876af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1877af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1878af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1879af31f5e5SChris Mason 
1880af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1881af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1882af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1883af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1884af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1885af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1886af31f5e5SChris Mason 
1887af31f5e5SChris Mason 	/*
1888af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1889af31f5e5SChris Mason 	 * for the next commit
1890af31f5e5SChris Mason 	 */
1891af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1892af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1893af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1894af31f5e5SChris Mason }
1895af31f5e5SChris Mason 
1896af31f5e5SChris Mason /*
1897bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1898bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1899bd2336b2SNikolay Borisov  *
1900bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1901bd2336b2SNikolay Borisov  * priority - priority of backup root required
1902bd2336b2SNikolay Borisov  *
1903bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1904bd2336b2SNikolay Borisov  */
1905bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1906bd2336b2SNikolay Borisov {
1907bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1908bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1909bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1910bd2336b2SNikolay Borisov 
1911bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1912bd2336b2SNikolay Borisov 		if (priority == 0)
1913bd2336b2SNikolay Borisov 			return backup_index;
1914bd2336b2SNikolay Borisov 
1915bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1916bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1917bd2336b2SNikolay Borisov 	} else {
1918bd2336b2SNikolay Borisov 		return -EINVAL;
1919bd2336b2SNikolay Borisov 	}
1920bd2336b2SNikolay Borisov 
1921bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1922bd2336b2SNikolay Borisov 
1923bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1924bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1925bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1926bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1927bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1928bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1929bd2336b2SNikolay Borisov 
1930bd2336b2SNikolay Borisov 	/*
1931bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1932bd2336b2SNikolay Borisov 	 * need a fsck
1933bd2336b2SNikolay Borisov 	 */
1934bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1935bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1936bd2336b2SNikolay Borisov 
1937bd2336b2SNikolay Borisov 	return backup_index;
1938bd2336b2SNikolay Borisov }
1939bd2336b2SNikolay Borisov 
19407abadb64SLiu Bo /* helper to cleanup workers */
19417abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19427abadb64SLiu Bo {
1943dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1944afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
19455cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1946fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
1947fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
19488b110e39SMiao Xie 	btrfs_destroy_workqueue(fs_info->endio_repair_workers);
1949d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
1950fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1951fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19525b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1953e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1954736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
1955a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1956fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1957b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1958b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1959a9b9477dSFilipe Manana 	/*
1960a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1961a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1962a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1963a9b9477dSFilipe Manana 	 */
1964a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
1965a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
19667abadb64SLiu Bo }
19677abadb64SLiu Bo 
19682e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
19692e9f5954SRashika {
19702e9f5954SRashika 	if (root) {
19712e9f5954SRashika 		free_extent_buffer(root->node);
19722e9f5954SRashika 		free_extent_buffer(root->commit_root);
19732e9f5954SRashika 		root->node = NULL;
19742e9f5954SRashika 		root->commit_root = NULL;
19752e9f5954SRashika 	}
19762e9f5954SRashika }
19772e9f5954SRashika 
1978af31f5e5SChris Mason /* helper to cleanup tree roots */
19794273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1980af31f5e5SChris Mason {
19812e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1982655b09feSJosef Bacik 
19832e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
19842e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
19852e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
19862e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
19872e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
19884273eaffSAnand Jain 	if (free_chunk_root)
19892e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
199070f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
1991af31f5e5SChris Mason }
1992af31f5e5SChris Mason 
1993faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1994171f6537SJosef Bacik {
1995171f6537SJosef Bacik 	int ret;
1996171f6537SJosef Bacik 	struct btrfs_root *gang[8];
1997171f6537SJosef Bacik 	int i;
1998171f6537SJosef Bacik 
1999171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2000171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2001171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2002171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2003171f6537SJosef Bacik 
200427cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2005cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2006171f6537SJosef Bacik 		} else {
2007171f6537SJosef Bacik 			free_extent_buffer(gang[0]->node);
2008171f6537SJosef Bacik 			free_extent_buffer(gang[0]->commit_root);
2009b0feb9d9SMiao Xie 			btrfs_put_fs_root(gang[0]);
2010171f6537SJosef Bacik 		}
2011171f6537SJosef Bacik 	}
2012171f6537SJosef Bacik 
2013171f6537SJosef Bacik 	while (1) {
2014171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2015171f6537SJosef Bacik 					     (void **)gang, 0,
2016171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2017171f6537SJosef Bacik 		if (!ret)
2018171f6537SJosef Bacik 			break;
2019171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2020cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2021171f6537SJosef Bacik 	}
20221a4319ccSLiu Bo 
20231a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
20241a4319ccSLiu Bo 		btrfs_free_log_root_tree(NULL, fs_info);
20252ff7e61eSJeff Mahoney 		btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
20261a4319ccSLiu Bo 	}
2027171f6537SJosef Bacik }
2028af31f5e5SChris Mason 
2029638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2030638aa7edSEric Sandeen {
2031638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2032638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2033638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2034638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2035638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2036638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2037ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2038638aa7edSEric Sandeen }
2039638aa7edSEric Sandeen 
2040779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2041779a65a4SEric Sandeen {
2042779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2043779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2044779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2045779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2046779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2047779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2048779a65a4SEric Sandeen }
2049779a65a4SEric Sandeen 
20506bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2051f37938e0SEric Sandeen {
20522ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
20532ff7e61eSJeff Mahoney 
20542ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
20552ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2056f37938e0SEric Sandeen 	/*
2057f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2058f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2059f37938e0SEric Sandeen 	 * the devices in the system
2060f37938e0SEric Sandeen 	 */
20612ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
20622ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2063f37938e0SEric Sandeen 
20642ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
206543eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
206643eb5f29SQu Wenruo 			    IO_TREE_INODE_IO, inode);
20677b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
20682ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2069f37938e0SEric Sandeen 
20702ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2071f37938e0SEric Sandeen 
20722ff7e61eSJeff Mahoney 	BTRFS_I(inode)->root = fs_info->tree_root;
20732ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
20742ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
20752ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2076f37938e0SEric Sandeen }
2077f37938e0SEric Sandeen 
2078ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2079ad618368SEric Sandeen {
2080ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2081129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
20827f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2083ad618368SEric Sandeen }
2084ad618368SEric Sandeen 
2085f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2086f9e92e40SEric Sandeen {
2087f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2088f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2089f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2090f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2091f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2092f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2093d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2094f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2095f9e92e40SEric Sandeen }
2096f9e92e40SEric Sandeen 
20972a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
20982a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
20992a458198SEric Sandeen {
2100f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21016f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21022a458198SEric Sandeen 
21032a458198SEric Sandeen 	fs_info->workers =
2104cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2105cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21062a458198SEric Sandeen 
21072a458198SEric Sandeen 	fs_info->delalloc_workers =
2108cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2109cb001095SJeff Mahoney 				      flags, max_active, 2);
21102a458198SEric Sandeen 
21112a458198SEric Sandeen 	fs_info->flush_workers =
2112cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2113cb001095SJeff Mahoney 				      flags, max_active, 0);
21142a458198SEric Sandeen 
21152a458198SEric Sandeen 	fs_info->caching_workers =
2116cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21172a458198SEric Sandeen 
21182a458198SEric Sandeen 	fs_info->fixup_workers =
2119cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
21202a458198SEric Sandeen 
21212a458198SEric Sandeen 	/*
21222a458198SEric Sandeen 	 * endios are largely parallel and should have a very
21232a458198SEric Sandeen 	 * low idle thresh
21242a458198SEric Sandeen 	 */
21252a458198SEric Sandeen 	fs_info->endio_workers =
2126cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
21272a458198SEric Sandeen 	fs_info->endio_meta_workers =
2128cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2129cb001095SJeff Mahoney 				      max_active, 4);
21302a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2131cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2132cb001095SJeff Mahoney 				      max_active, 2);
21332a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2134cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2135cb001095SJeff Mahoney 				      max_active, 4);
21362a458198SEric Sandeen 	fs_info->endio_repair_workers =
2137cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
21382a458198SEric Sandeen 	fs_info->rmw_workers =
2139cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
21402a458198SEric Sandeen 	fs_info->endio_write_workers =
2141cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2142cb001095SJeff Mahoney 				      max_active, 2);
21432a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2144cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2145cb001095SJeff Mahoney 				      max_active, 0);
21462a458198SEric Sandeen 	fs_info->delayed_workers =
2147cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2148cb001095SJeff Mahoney 				      max_active, 0);
21492a458198SEric Sandeen 	fs_info->readahead_workers =
2150cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2151cb001095SJeff Mahoney 				      max_active, 2);
21522a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2153cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2154b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2155b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
21562a458198SEric Sandeen 
21572a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2158ba8a9d07SChris Mason 	      fs_info->flush_workers &&
21592a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
21602a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
21612a458198SEric Sandeen 	      fs_info->endio_repair_workers &&
21622a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
21632a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
21642a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
21652a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2166b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2167b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
21682a458198SEric Sandeen 		return -ENOMEM;
21692a458198SEric Sandeen 	}
21702a458198SEric Sandeen 
21712a458198SEric Sandeen 	return 0;
21722a458198SEric Sandeen }
21732a458198SEric Sandeen 
21746d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
21756d97c6e3SJohannes Thumshirn {
21766d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2177b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
21786d97c6e3SJohannes Thumshirn 
2179b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
21806d97c6e3SJohannes Thumshirn 
21816d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
21826d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2183b4e967beSDavid Sterba 			  csum_driver);
21846d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
21856d97c6e3SJohannes Thumshirn 	}
21866d97c6e3SJohannes Thumshirn 
21876d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
21886d97c6e3SJohannes Thumshirn 
21896d97c6e3SJohannes Thumshirn 	return 0;
21906d97c6e3SJohannes Thumshirn }
21916d97c6e3SJohannes Thumshirn 
21926d97c6e3SJohannes Thumshirn static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
21936d97c6e3SJohannes Thumshirn {
21946d97c6e3SJohannes Thumshirn 	crypto_free_shash(fs_info->csum_shash);
21956d97c6e3SJohannes Thumshirn }
21966d97c6e3SJohannes Thumshirn 
219763443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
219863443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
219963443bf5SEric Sandeen {
220063443bf5SEric Sandeen 	int ret;
220163443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
220263443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
220363443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2204581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
220563443bf5SEric Sandeen 
220663443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2207f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
220863443bf5SEric Sandeen 		return -EIO;
220963443bf5SEric Sandeen 	}
221063443bf5SEric Sandeen 
221174e4d827SDavid Sterba 	log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
221263443bf5SEric Sandeen 	if (!log_tree_root)
221363443bf5SEric Sandeen 		return -ENOMEM;
221463443bf5SEric Sandeen 
2215da17066cSJeff Mahoney 	__setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
221663443bf5SEric Sandeen 
22172ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
2218581c1760SQu Wenruo 					      fs_info->generation + 1,
2219581c1760SQu Wenruo 					      level, NULL);
222064c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2221f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22220eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
222364c043deSLiu Bo 		kfree(log_tree_root);
22240eeff236SLiu Bo 		return ret;
222564c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2226f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
222763443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
222863443bf5SEric Sandeen 		kfree(log_tree_root);
222963443bf5SEric Sandeen 		return -EIO;
223063443bf5SEric Sandeen 	}
223163443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
223263443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
223363443bf5SEric Sandeen 	if (ret) {
22340b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
223563443bf5SEric Sandeen 				      "Failed to recover log tree");
223663443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
223763443bf5SEric Sandeen 		kfree(log_tree_root);
223863443bf5SEric Sandeen 		return ret;
223963443bf5SEric Sandeen 	}
224063443bf5SEric Sandeen 
2241bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
22426bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
224363443bf5SEric Sandeen 		if (ret)
224463443bf5SEric Sandeen 			return ret;
224563443bf5SEric Sandeen 	}
224663443bf5SEric Sandeen 
224763443bf5SEric Sandeen 	return 0;
224863443bf5SEric Sandeen }
224963443bf5SEric Sandeen 
22506bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
22514bbcaa64SEric Sandeen {
22526bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2253a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
22544bbcaa64SEric Sandeen 	struct btrfs_key location;
22554bbcaa64SEric Sandeen 	int ret;
22564bbcaa64SEric Sandeen 
22576bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
22586bccf3abSJeff Mahoney 
22594bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
22604bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
22614bbcaa64SEric Sandeen 	location.offset = 0;
22624bbcaa64SEric Sandeen 
2263a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2264f50f4353SLiu Bo 	if (IS_ERR(root)) {
2265f50f4353SLiu Bo 		ret = PTR_ERR(root);
2266f50f4353SLiu Bo 		goto out;
2267f50f4353SLiu Bo 	}
2268a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2269a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
22704bbcaa64SEric Sandeen 
22714bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2272a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2273f50f4353SLiu Bo 	if (IS_ERR(root)) {
2274f50f4353SLiu Bo 		ret = PTR_ERR(root);
2275f50f4353SLiu Bo 		goto out;
2276f50f4353SLiu Bo 	}
2277a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2278a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
22794bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
22804bbcaa64SEric Sandeen 
22814bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2282a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2283f50f4353SLiu Bo 	if (IS_ERR(root)) {
2284f50f4353SLiu Bo 		ret = PTR_ERR(root);
2285f50f4353SLiu Bo 		goto out;
2286f50f4353SLiu Bo 	}
2287a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2288a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
22894bbcaa64SEric Sandeen 
22904bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2291a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2292a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2293a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2294afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2295a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
22964bbcaa64SEric Sandeen 	}
22974bbcaa64SEric Sandeen 
22984bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2299a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2300a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2301a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
23024bbcaa64SEric Sandeen 		if (ret != -ENOENT)
2303f50f4353SLiu Bo 			goto out;
23044bbcaa64SEric Sandeen 	} else {
2305a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2306a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
23074bbcaa64SEric Sandeen 	}
23084bbcaa64SEric Sandeen 
230970f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
231070f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
231170f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2312f50f4353SLiu Bo 		if (IS_ERR(root)) {
2313f50f4353SLiu Bo 			ret = PTR_ERR(root);
2314f50f4353SLiu Bo 			goto out;
2315f50f4353SLiu Bo 		}
231670f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
231770f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
231870f6d82eSOmar Sandoval 	}
231970f6d82eSOmar Sandoval 
23204bbcaa64SEric Sandeen 	return 0;
2321f50f4353SLiu Bo out:
2322f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2323f50f4353SLiu Bo 		   location.objectid, ret);
2324f50f4353SLiu Bo 	return ret;
23254bbcaa64SEric Sandeen }
23264bbcaa64SEric Sandeen 
2327069ec957SQu Wenruo /*
2328069ec957SQu Wenruo  * Real super block validation
2329069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2330069ec957SQu Wenruo  *
2331069ec957SQu Wenruo  * @sb:		super block to check
2332069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2333069ec957SQu Wenruo  * 		0	the primary (1st) sb
2334069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2335069ec957SQu Wenruo  * 	       -1	skip bytenr check
2336069ec957SQu Wenruo  */
2337069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2338069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
233921a852b0SQu Wenruo {
234021a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
234121a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
234221a852b0SQu Wenruo 	int ret = 0;
234321a852b0SQu Wenruo 
234421a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
234521a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
234621a852b0SQu Wenruo 		ret = -EINVAL;
234721a852b0SQu Wenruo 	}
234821a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
234921a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
235021a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
235121a852b0SQu Wenruo 		ret = -EINVAL;
235221a852b0SQu Wenruo 	}
235321a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
235421a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
235521a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
235621a852b0SQu Wenruo 		ret = -EINVAL;
235721a852b0SQu Wenruo 	}
235821a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
235921a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
236021a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
236121a852b0SQu Wenruo 		ret = -EINVAL;
236221a852b0SQu Wenruo 	}
236321a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
236421a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
236521a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
236621a852b0SQu Wenruo 		ret = -EINVAL;
236721a852b0SQu Wenruo 	}
236821a852b0SQu Wenruo 
236921a852b0SQu Wenruo 	/*
237021a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
237121a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
237221a852b0SQu Wenruo 	 */
237321a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
237421a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
237521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
237621a852b0SQu Wenruo 		ret = -EINVAL;
237721a852b0SQu Wenruo 	}
237821a852b0SQu Wenruo 	/* Only PAGE SIZE is supported yet */
237921a852b0SQu Wenruo 	if (sectorsize != PAGE_SIZE) {
238021a852b0SQu Wenruo 		btrfs_err(fs_info,
238121a852b0SQu Wenruo 			"sectorsize %llu not supported yet, only support %lu",
238221a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
238321a852b0SQu Wenruo 		ret = -EINVAL;
238421a852b0SQu Wenruo 	}
238521a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
238621a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
238721a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
238821a852b0SQu Wenruo 		ret = -EINVAL;
238921a852b0SQu Wenruo 	}
239021a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
239121a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
239221a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
239321a852b0SQu Wenruo 		ret = -EINVAL;
239421a852b0SQu Wenruo 	}
239521a852b0SQu Wenruo 
239621a852b0SQu Wenruo 	/* Root alignment check */
239721a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
239821a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
239921a852b0SQu Wenruo 			   btrfs_super_root(sb));
240021a852b0SQu Wenruo 		ret = -EINVAL;
240121a852b0SQu Wenruo 	}
240221a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
240321a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
240421a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
240521a852b0SQu Wenruo 		ret = -EINVAL;
240621a852b0SQu Wenruo 	}
240721a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
240821a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
240921a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
241021a852b0SQu Wenruo 		ret = -EINVAL;
241121a852b0SQu Wenruo 	}
241221a852b0SQu Wenruo 
2413de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
24147239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
241521a852b0SQu Wenruo 		btrfs_err(fs_info,
24167239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2417de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
241821a852b0SQu Wenruo 		ret = -EINVAL;
241921a852b0SQu Wenruo 	}
242021a852b0SQu Wenruo 
242121a852b0SQu Wenruo 	/*
242221a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
242321a852b0SQu Wenruo 	 * done later
242421a852b0SQu Wenruo 	 */
242521a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
242621a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
242721a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
242821a852b0SQu Wenruo 		ret = -EINVAL;
242921a852b0SQu Wenruo 	}
243021a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
243121a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
243221a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
243321a852b0SQu Wenruo 		ret = -EINVAL;
243421a852b0SQu Wenruo 	}
243521a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
243621a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
243721a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
243821a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
243921a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
244021a852b0SQu Wenruo 		ret = -EINVAL;
244121a852b0SQu Wenruo 	}
244221a852b0SQu Wenruo 
2443069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2444069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
244521a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
244621a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
244721a852b0SQu Wenruo 		ret = -EINVAL;
244821a852b0SQu Wenruo 	}
244921a852b0SQu Wenruo 
245021a852b0SQu Wenruo 	/*
245121a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
245221a852b0SQu Wenruo 	 * and one chunk
245321a852b0SQu Wenruo 	 */
245421a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
245521a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
245621a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
245721a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
245821a852b0SQu Wenruo 		ret = -EINVAL;
245921a852b0SQu Wenruo 	}
246021a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
246121a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
246221a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
246321a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
246421a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
246521a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
246621a852b0SQu Wenruo 		ret = -EINVAL;
246721a852b0SQu Wenruo 	}
246821a852b0SQu Wenruo 
246921a852b0SQu Wenruo 	/*
247021a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
247121a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
247221a852b0SQu Wenruo 	 */
247321a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
247421a852b0SQu Wenruo 		btrfs_warn(fs_info,
247521a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
247621a852b0SQu Wenruo 			btrfs_super_generation(sb),
247721a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
247821a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
247921a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
248021a852b0SQu Wenruo 		btrfs_warn(fs_info,
248121a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
248221a852b0SQu Wenruo 			btrfs_super_generation(sb),
248321a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
248421a852b0SQu Wenruo 
248521a852b0SQu Wenruo 	return ret;
248621a852b0SQu Wenruo }
248721a852b0SQu Wenruo 
2488069ec957SQu Wenruo /*
2489069ec957SQu Wenruo  * Validation of super block at mount time.
2490069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2491069ec957SQu Wenruo  * flags will be skipped.
2492069ec957SQu Wenruo  */
2493069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2494069ec957SQu Wenruo {
2495069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2496069ec957SQu Wenruo }
2497069ec957SQu Wenruo 
249875cb857dSQu Wenruo /*
249975cb857dSQu Wenruo  * Validation of super block at write time.
250075cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
250175cb857dSQu Wenruo  * overwritten soon.
250275cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
250375cb857dSQu Wenruo  */
250475cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
250575cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
250675cb857dSQu Wenruo {
250775cb857dSQu Wenruo 	int ret;
250875cb857dSQu Wenruo 
250975cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
251075cb857dSQu Wenruo 	if (ret < 0)
251175cb857dSQu Wenruo 		goto out;
2512e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
251375cb857dSQu Wenruo 		ret = -EUCLEAN;
251475cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
251575cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
251675cb857dSQu Wenruo 		goto out;
251775cb857dSQu Wenruo 	}
251875cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
251975cb857dSQu Wenruo 		ret = -EUCLEAN;
252075cb857dSQu Wenruo 		btrfs_err(fs_info,
252175cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
252275cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
252375cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
252475cb857dSQu Wenruo 		goto out;
252575cb857dSQu Wenruo 	}
252675cb857dSQu Wenruo out:
252775cb857dSQu Wenruo 	if (ret < 0)
252875cb857dSQu Wenruo 		btrfs_err(fs_info,
252975cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
253075cb857dSQu Wenruo 	return ret;
253175cb857dSQu Wenruo }
253275cb857dSQu Wenruo 
25336ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2534b8522a1eSNikolay Borisov {
25356ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2536b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2537b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2538b8522a1eSNikolay Borisov 	bool handle_error = false;
2539b8522a1eSNikolay Borisov 	int ret = 0;
2540b8522a1eSNikolay Borisov 	int i;
2541b8522a1eSNikolay Borisov 
2542b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2543b8522a1eSNikolay Borisov 		u64 generation;
2544b8522a1eSNikolay Borisov 		int level;
2545b8522a1eSNikolay Borisov 
2546b8522a1eSNikolay Borisov 		if (handle_error) {
2547b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2548b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2549b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2550b8522a1eSNikolay Borisov 
2551b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2552b8522a1eSNikolay Borisov 				break;
2553b8522a1eSNikolay Borisov 
2554b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2555b8522a1eSNikolay Borisov 
2556b8522a1eSNikolay Borisov 			/*
2557b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2558b8522a1eSNikolay Borisov 			 * valid
2559b8522a1eSNikolay Borisov 			 */
2560b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2561b8522a1eSNikolay Borisov 
2562b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2563b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2564b8522a1eSNikolay Borisov 
2565b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
25666ef108ddSNikolay Borisov 			backup_index = ret;
2567b8522a1eSNikolay Borisov 			if (ret < 0)
2568b8522a1eSNikolay Borisov 				return ret;
2569b8522a1eSNikolay Borisov 		}
2570b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2571b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2572b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
2573b8522a1eSNikolay Borisov 						  generation, level, NULL);
2574b8522a1eSNikolay Borisov 		if (IS_ERR(tree_root->node) ||
2575b8522a1eSNikolay Borisov 		    !extent_buffer_uptodate(tree_root->node)) {
2576b8522a1eSNikolay Borisov 			handle_error = true;
2577b8522a1eSNikolay Borisov 
2578b8522a1eSNikolay Borisov 			if (IS_ERR(tree_root->node))
2579b8522a1eSNikolay Borisov 				ret = PTR_ERR(tree_root->node);
2580b8522a1eSNikolay Borisov 			else if (!extent_buffer_uptodate(tree_root->node))
2581b8522a1eSNikolay Borisov 				ret = -EUCLEAN;
2582b8522a1eSNikolay Borisov 
2583b8522a1eSNikolay Borisov 			btrfs_warn(fs_info, "failed to read tree root");
2584b8522a1eSNikolay Borisov 			continue;
2585b8522a1eSNikolay Borisov 		}
2586b8522a1eSNikolay Borisov 
2587b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2588b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2589b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2590b8522a1eSNikolay Borisov 
2591336a0d8dSNikolay Borisov 		/*
2592336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2593336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2594336a0d8dSNikolay Borisov 		 */
2595b8522a1eSNikolay Borisov 		ret = btrfs_find_highest_objectid(tree_root,
2596b8522a1eSNikolay Borisov 						&tree_root->highest_objectid);
2597b8522a1eSNikolay Borisov 		if (ret < 0) {
2598b8522a1eSNikolay Borisov 			handle_error = true;
2599b8522a1eSNikolay Borisov 			continue;
2600b8522a1eSNikolay Borisov 		}
2601b8522a1eSNikolay Borisov 
2602b8522a1eSNikolay Borisov 		ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2603b8522a1eSNikolay Borisov 
2604b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2605b8522a1eSNikolay Borisov 		if (ret < 0) {
2606b8522a1eSNikolay Borisov 			handle_error = true;
2607b8522a1eSNikolay Borisov 			continue;
2608b8522a1eSNikolay Borisov 		}
2609b8522a1eSNikolay Borisov 
2610b8522a1eSNikolay Borisov 		/* All successful */
2611b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2612b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
26136ef108ddSNikolay Borisov 
26146ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26156ef108ddSNikolay Borisov 		if (backup_index < 0) {
26166ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26176ef108ddSNikolay Borisov 		} else {
26186ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26196ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26206ef108ddSNikolay Borisov 		}
2621b8522a1eSNikolay Borisov 		break;
2622b8522a1eSNikolay Borisov 	}
2623b8522a1eSNikolay Borisov 
2624b8522a1eSNikolay Borisov 	return ret;
2625b8522a1eSNikolay Borisov }
2626b8522a1eSNikolay Borisov 
2627b105e927SDavid Sterba int __cold open_ctree(struct super_block *sb,
2628dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
2629dfe25020SChris Mason 	       char *options)
2630eb60ceacSChris Mason {
2631db94535dSChris Mason 	u32 sectorsize;
2632db94535dSChris Mason 	u32 nodesize;
263387ee04ebSChris Mason 	u32 stripesize;
263484234f3aSYan Zheng 	u64 generation;
2635f2b636e8SJosef Bacik 	u64 features;
263651bce6c9SJohannes Thumshirn 	u16 csum_type;
26373de4586cSChris Mason 	struct btrfs_key location;
2638a061fc8dSChris Mason 	struct buffer_head *bh;
26394d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
2640815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2641f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
26424d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
2643eb60ceacSChris Mason 	int ret;
2644e58ca020SYan 	int err = -EINVAL;
26456675df31SOmar Sandoval 	int clear_free_space_tree = 0;
2646581c1760SQu Wenruo 	int level;
26474543df7eSChris Mason 
264874e4d827SDavid Sterba 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
264974e4d827SDavid Sterba 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2650cb517eabSMiao Xie 	if (!tree_root || !chunk_root) {
265139279cc3SChris Mason 		err = -ENOMEM;
265239279cc3SChris Mason 		goto fail;
265339279cc3SChris Mason 	}
265476dda93cSYan, Zheng 
265576dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
265676dda93cSYan, Zheng 	if (ret) {
265776dda93cSYan, Zheng 		err = ret;
265876dda93cSYan, Zheng 		goto fail;
265976dda93cSYan, Zheng 	}
266076dda93cSYan, Zheng 
26614297ff84SJosef Bacik 	ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
2662e2d84521SMiao Xie 	if (ret) {
2663e2d84521SMiao Xie 		err = ret;
26649e11ceeeSJan Kara 		goto fail_srcu;
2665e2d84521SMiao Xie 	}
26664297ff84SJosef Bacik 
26674297ff84SJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
26684297ff84SJosef Bacik 	if (ret) {
26694297ff84SJosef Bacik 		err = ret;
26704297ff84SJosef Bacik 		goto fail_dio_bytes;
26714297ff84SJosef Bacik 	}
267209cbfeafSKirill A. Shutemov 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2673e2d84521SMiao Xie 					(1 + ilog2(nr_cpu_ids));
2674e2d84521SMiao Xie 
2675908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2676963d678bSMiao Xie 	if (ret) {
2677963d678bSMiao Xie 		err = ret;
2678963d678bSMiao Xie 		goto fail_dirty_metadata_bytes;
2679963d678bSMiao Xie 	}
2680963d678bSMiao Xie 
26817f8d236aSDavid Sterba 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
26827f8d236aSDavid Sterba 			GFP_KERNEL);
2683c404e0dcSMiao Xie 	if (ret) {
2684c404e0dcSMiao Xie 		err = ret;
2685c404e0dcSMiao Xie 		goto fail_delalloc_bytes;
2686c404e0dcSMiao Xie 	}
2687c404e0dcSMiao Xie 
268876dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2689f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26908fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2691facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
269224bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2693eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
269411833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2695eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2696a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
269776dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
269824bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26994cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2700ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2701f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
270247ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2703f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2704d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
270567c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
27067585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2707573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2708de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
270919c00ddcSChris Mason 
27100b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
27116324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2712f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
271347ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2714c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
271566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
271666d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
271766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
271866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
271966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
272066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
272166d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2722ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2723ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2724ba2c4d4eSJosef Bacik 
2725771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
27264cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
27272fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2728034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2729fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2730e20d96d6SChris Mason 	fs_info->sb = sb;
273195ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27329ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27334cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2734a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2735f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27368b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2737f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
273890519d66SArne Jansen 	/* readahead state */
2739d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
274090519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2741fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2742c8b97818SChris Mason 
2743b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2744b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27450afbaf8cSChris Mason 
2746199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2747199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
274869fe2d75SJosef Bacik 
274969fe2d75SJosef Bacik 	fs_info->btree_inode = new_inode(sb);
275069fe2d75SJosef Bacik 	if (!fs_info->btree_inode) {
275169fe2d75SJosef Bacik 		err = -ENOMEM;
275269fe2d75SJosef Bacik 		goto fail_bio_counter;
275369fe2d75SJosef Bacik 	}
275469fe2d75SJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
275569fe2d75SJosef Bacik 
275616cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
275774e4d827SDavid Sterba 					GFP_KERNEL);
275816cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
275916cdcec7SMiao Xie 		err = -ENOMEM;
276016cdcec7SMiao Xie 		goto fail_iput;
276116cdcec7SMiao Xie 	}
276216cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
27633eaa2885SChris Mason 
2764638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
276521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
276621adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
276721adbd5cSStefan Behrens #endif
2768779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
276921c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2770a2de733cSArne Jansen 
27719f6d2510SDavid Sterba 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
27729f6d2510SDavid Sterba 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2773a061fc8dSChris Mason 
27746bccf3abSJeff Mahoney 	btrfs_init_btree_inode(fs_info);
277539279cc3SChris Mason 
2776e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
27776bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2778a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
2779925baeddSChris Mason 
278043eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &fs_info->freed_extents[0],
278143eb5f29SQu Wenruo 			    IO_TREE_FS_INFO_FREED_EXTENTS0, NULL);
278243eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &fs_info->freed_extents[1],
278343eb5f29SQu Wenruo 			    IO_TREE_FS_INFO_FREED_EXTENTS1, NULL);
278411833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2785afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2786509659cdSChris Mason 
27875a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
278879154b1bSChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2789925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2790a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2791a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27921bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27939e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2794c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
279576dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2796803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2797fa9c0d79SChris Mason 
2798ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2799f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2800b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2801416ac51dSArne Jansen 
2802fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2803fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2804fa9c0d79SChris Mason 
2805e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2806f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2807bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
28084854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2809034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
28103768f368SChris Mason 
2811da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2812da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2813da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2814da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2815da17066cSJeff Mahoney 
2816eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2817eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2818eede2bf3SOmar Sandoval 
28199e967495SFilipe Manana 	fs_info->send_in_progress = 0;
28209e967495SFilipe Manana 
282153b381b3SDavid Woodhouse 	ret = btrfs_alloc_stripe_hash_table(fs_info);
282253b381b3SDavid Woodhouse 	if (ret) {
282383c8266aSDavid Sterba 		err = ret;
282453b381b3SDavid Woodhouse 		goto fail_alloc;
282553b381b3SDavid Woodhouse 	}
282653b381b3SDavid Woodhouse 
2827da17066cSJeff Mahoney 	__setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
28287eccb903SChris Mason 
28293c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
28301104a885SDavid Sterba 
28311104a885SDavid Sterba 	/*
28321104a885SDavid Sterba 	 * Read super block and check the signature bytes only
28331104a885SDavid Sterba 	 */
2834a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
283592fc03fbSAnand Jain 	if (IS_ERR(bh)) {
283692fc03fbSAnand Jain 		err = PTR_ERR(bh);
283716cdcec7SMiao Xie 		goto fail_alloc;
283820b45077SDave Young 	}
283939279cc3SChris Mason 
28401104a885SDavid Sterba 	/*
28418dc3f22cSJohannes Thumshirn 	 * Verify the type first, if that or the the checksum value are
28428dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
28438dc3f22cSJohannes Thumshirn 	 */
284451bce6c9SJohannes Thumshirn 	csum_type = btrfs_super_csum_type((struct btrfs_super_block *)bh->b_data);
284551bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
28468dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
284751bce6c9SJohannes Thumshirn 			  csum_type);
28488dc3f22cSJohannes Thumshirn 		err = -EINVAL;
28498dc3f22cSJohannes Thumshirn 		brelse(bh);
28508dc3f22cSJohannes Thumshirn 		goto fail_alloc;
28518dc3f22cSJohannes Thumshirn 	}
28528dc3f22cSJohannes Thumshirn 
28536d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
28546d97c6e3SJohannes Thumshirn 	if (ret) {
28556d97c6e3SJohannes Thumshirn 		err = ret;
28566d97c6e3SJohannes Thumshirn 		goto fail_alloc;
28576d97c6e3SJohannes Thumshirn 	}
28586d97c6e3SJohannes Thumshirn 
28598dc3f22cSJohannes Thumshirn 	/*
28601104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
28611104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
28621104a885SDavid Sterba 	 */
2863ab8d0fc4SJeff Mahoney 	if (btrfs_check_super_csum(fs_info, bh->b_data)) {
286405135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
28651104a885SDavid Sterba 		err = -EINVAL;
2866b2acdddfSAnand Jain 		brelse(bh);
28676d97c6e3SJohannes Thumshirn 		goto fail_csum;
28681104a885SDavid Sterba 	}
28691104a885SDavid Sterba 
28701104a885SDavid Sterba 	/*
28711104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
28721104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
28731104a885SDavid Sterba 	 * the whole block of INFO_SIZE
28741104a885SDavid Sterba 	 */
28756c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2876a061fc8dSChris Mason 	brelse(bh);
28775f39d397SChris Mason 
2878fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
2879fbc6feaeSNikolay Borisov 
2880de37aa51SNikolay Borisov 	ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2881de37aa51SNikolay Borisov 		       BTRFS_FSID_SIZE));
2882de37aa51SNikolay Borisov 
28837239ff4bSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
2884de37aa51SNikolay Borisov 		ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
2885de37aa51SNikolay Borisov 				fs_info->super_copy->metadata_uuid,
2886de37aa51SNikolay Borisov 				BTRFS_FSID_SIZE));
28877239ff4bSNikolay Borisov 	}
28880b86a832SChris Mason 
2889fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
2890fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
2891fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
2892fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
2893fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
2894fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
2895fbc6feaeSNikolay Borisov 	}
2896fbc6feaeSNikolay Borisov 
2897fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2898fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
2899de37aa51SNikolay Borisov 
2900069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
29011104a885SDavid Sterba 	if (ret) {
290205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
29031104a885SDavid Sterba 		err = -EINVAL;
29046d97c6e3SJohannes Thumshirn 		goto fail_csum;
29051104a885SDavid Sterba 	}
29061104a885SDavid Sterba 
29070f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
29086d97c6e3SJohannes Thumshirn 		goto fail_csum;
29090f7d52f4SChris Mason 
2910acce952bSliubo 	/* check FS state, whether FS is broken. */
291187533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
291287533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2913acce952bSliubo 
291475e7cb7fSLiu Bo 	/*
291575e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
291675e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
291775e7cb7fSLiu Bo 	 */
291875e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
291975e7cb7fSLiu Bo 
29202ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
29212b82032cSYan Zheng 	if (ret) {
29222b82032cSYan Zheng 		err = ret;
29236d97c6e3SJohannes Thumshirn 		goto fail_csum;
29242b82032cSYan Zheng 	}
2925dfe25020SChris Mason 
2926f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2927f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2928f2b636e8SJosef Bacik 	if (features) {
292905135f59SDavid Sterba 		btrfs_err(fs_info,
293005135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
2931c1c9ff7cSGeert Uytterhoeven 		    features);
2932f2b636e8SJosef Bacik 		err = -EINVAL;
29336d97c6e3SJohannes Thumshirn 		goto fail_csum;
2934f2b636e8SJosef Bacik 	}
2935f2b636e8SJosef Bacik 
29365d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
29375d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
29380b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2939a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
29405c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
29415c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2942727011e0SChris Mason 
29433173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
294405135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
29453173a18fSJosef Bacik 
2946727011e0SChris Mason 	/*
2947727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2948727011e0SChris Mason 	 * they are bigger than the page size
2949727011e0SChris Mason 	 */
295009cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2951727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
295205135f59SDavid Sterba 			btrfs_info(fs_info,
295305135f59SDavid Sterba 				"flagging fs with big metadata feature");
2954727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2955727011e0SChris Mason 	}
2956727011e0SChris Mason 
2957bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2958bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2959b7f67055SChandan Rajendra 	stripesize = sectorsize;
2960707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2961963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2962bc3f116fSChris Mason 
2963da17066cSJeff Mahoney 	/* Cache block sizes */
2964da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
2965da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
2966da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
2967da17066cSJeff Mahoney 
2968bc3f116fSChris Mason 	/*
2969bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2970bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2971bc3f116fSChris Mason 	 */
2972bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2973707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
297405135f59SDavid Sterba 		btrfs_err(fs_info,
297505135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
297605135f59SDavid Sterba 			nodesize, sectorsize);
29776d97c6e3SJohannes Thumshirn 		goto fail_csum;
2978bc3f116fSChris Mason 	}
2979bc3f116fSChris Mason 
2980ceda0864SMiao Xie 	/*
2981ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
2982ceda0864SMiao Xie 	 * update the flag.
2983ceda0864SMiao Xie 	 */
29845d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
29855d4f98a2SYan Zheng 
2986f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2987f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2988bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
298905135f59SDavid Sterba 		btrfs_err(fs_info,
299005135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
2991c1c9ff7cSGeert Uytterhoeven 		       features);
2992f2b636e8SJosef Bacik 		err = -EINVAL;
29936d97c6e3SJohannes Thumshirn 		goto fail_csum;
2994f2b636e8SJosef Bacik 	}
299561d92c32SChris Mason 
29962a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
29972a458198SEric Sandeen 	if (ret) {
29982a458198SEric Sandeen 		err = ret;
29990dc3b84aSJosef Bacik 		goto fail_sb_buffer;
30000dc3b84aSJosef Bacik 	}
30014543df7eSChris Mason 
30029e11ceeeSJan Kara 	sb->s_bdi->congested_fn = btrfs_congested_fn;
30039e11ceeeSJan Kara 	sb->s_bdi->congested_data = fs_info;
30049e11ceeeSJan Kara 	sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
3005b5420237SNikolay Borisov 	sb->s_bdi->ra_pages = VM_READAHEAD_PAGES;
30069e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
30079e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
30084575c9ccSChris Mason 
3009a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3010a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3011de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3012db94535dSChris Mason 
3013925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
30146bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3015925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
301684eed90fSChris Mason 	if (ret) {
301705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
30185d4f98a2SYan Zheng 		goto fail_sb_buffer;
301984eed90fSChris Mason 	}
30200b86a832SChris Mason 
302184234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3022581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
30230b86a832SChris Mason 
3024da17066cSJeff Mahoney 	__setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
30250b86a832SChris Mason 
30262ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
30270b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
3028581c1760SQu Wenruo 					   generation, level, NULL);
302964c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
303064c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
303105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3032e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3033e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
303495ab1f64SZhao Lei 		chunk_root->node = NULL;
3035af31f5e5SChris Mason 		goto fail_tree_roots;
303683121942SDavid Woodhouse 	}
30375d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
30385d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
30390b86a832SChris Mason 
3040e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3041b308bc2fSGeert Uytterhoeven 	   btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
3042e17cade2SChris Mason 
30435b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
30442b82032cSYan Zheng 	if (ret) {
304505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3046af31f5e5SChris Mason 		goto fail_tree_roots;
30472b82032cSYan Zheng 	}
30480b86a832SChris Mason 
30498dabb742SStefan Behrens 	/*
30509b99b115SAnand Jain 	 * Keep the devid that is marked to be the target device for the
30519b99b115SAnand Jain 	 * device replace procedure
30528dabb742SStefan Behrens 	 */
30539b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 0);
3054dfe25020SChris Mason 
3055a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
305605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3057a6b0d5c8SChris Mason 		goto fail_tree_roots;
3058a6b0d5c8SChris Mason 	}
3059a6b0d5c8SChris Mason 
3060b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
30614bbcaa64SEric Sandeen 	if (ret)
3062b8522a1eSNikolay Borisov 		goto fail_tree_roots;
30638929ecfaSYan, Zheng 
3064cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3065cf90d884SQu Wenruo 	if (ret) {
3066cf90d884SQu Wenruo 		btrfs_err(fs_info,
3067cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3068cf90d884SQu Wenruo 			  ret);
3069cf90d884SQu Wenruo 		goto fail_block_groups;
3070cf90d884SQu Wenruo 	}
307168310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
307268310a5eSIlya Dryomov 	if (ret) {
307305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
307468310a5eSIlya Dryomov 		goto fail_block_groups;
307568310a5eSIlya Dryomov 	}
307668310a5eSIlya Dryomov 
3077733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3078733f4fbbSStefan Behrens 	if (ret) {
307905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3080733f4fbbSStefan Behrens 		goto fail_block_groups;
3081733f4fbbSStefan Behrens 	}
3082733f4fbbSStefan Behrens 
30838dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
30848dabb742SStefan Behrens 	if (ret) {
308505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
30868dabb742SStefan Behrens 		goto fail_block_groups;
30878dabb742SStefan Behrens 	}
30888dabb742SStefan Behrens 
30899b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 1);
30908dabb742SStefan Behrens 
3091c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3092b7c35e81SAnand Jain 	if (ret) {
309305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
309405135f59SDavid Sterba 				ret);
3095b7c35e81SAnand Jain 		goto fail_block_groups;
3096b7c35e81SAnand Jain 	}
3097b7c35e81SAnand Jain 
309896f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
30995ac1d209SJeff Mahoney 	if (ret) {
310005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3101b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
31025ac1d209SJeff Mahoney 	}
31035ac1d209SJeff Mahoney 
3104c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3105c59021f8Sliubo 	if (ret) {
310605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
31072365dd3cSAnand Jain 		goto fail_sysfs;
3108c59021f8Sliubo 	}
3109c59021f8Sliubo 
31105b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
31111b1d1f66SJosef Bacik 	if (ret) {
311205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
31132365dd3cSAnand Jain 		goto fail_sysfs;
31141b1d1f66SJosef Bacik 	}
31154330e183SQu Wenruo 
31166528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
311705135f59SDavid Sterba 		btrfs_warn(fs_info,
311852042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
31192365dd3cSAnand Jain 		goto fail_sysfs;
3120292fd7fcSStefan Behrens 	}
31219078a3e1SChris Mason 
3122a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3123a74a4b97SChris Mason 					       "btrfs-cleaner");
312457506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
31252365dd3cSAnand Jain 		goto fail_sysfs;
3126a74a4b97SChris Mason 
3127a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3128a74a4b97SChris Mason 						   tree_root,
3129a74a4b97SChris Mason 						   "btrfs-transaction");
313057506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
31313f157a2fSChris Mason 		goto fail_cleaner;
3132a74a4b97SChris Mason 
3133583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3134c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3135583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3136c289811cSChris Mason 	}
3137c289811cSChris Mason 
3138572d9ab7SDavid Sterba 	/*
313901327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3140572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3141572d9ab7SDavid Sterba 	 */
3142572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
31433818aea2SQu Wenruo 
314421adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
31450b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
31462ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
31470b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
314821adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
314921adbd5cSStefan Behrens 				    1 : 0,
315021adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
315121adbd5cSStefan Behrens 		if (ret)
315205135f59SDavid Sterba 			btrfs_warn(fs_info,
315305135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
315405135f59SDavid Sterba 				ret);
315521adbd5cSStefan Behrens 	}
315621adbd5cSStefan Behrens #endif
3157bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3158bcef60f2SArne Jansen 	if (ret)
3159bcef60f2SArne Jansen 		goto fail_trans_kthread;
316021adbd5cSStefan Behrens 
3161fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3162fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3163fd708b81SJosef Bacik 
316496da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
316596da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
31660b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3167e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
316863443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
316979787eaaSJeff Mahoney 		if (ret) {
317063443bf5SEric Sandeen 			err = ret;
317128c16cbbSWang Shilong 			goto fail_qgroup;
3172e556ce2cSYan Zheng 		}
3173e02119d5SChris Mason 	}
31741a40e23bSZheng Yan 
31756bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
317679787eaaSJeff Mahoney 	if (ret)
317728c16cbbSWang Shilong 		goto fail_qgroup;
317876dda93cSYan, Zheng 
3179bc98a42cSDavid Howells 	if (!sb_rdonly(sb)) {
3180d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
318144c44af2SIlya Dryomov 		if (ret)
318228c16cbbSWang Shilong 			goto fail_qgroup;
318390c711abSZygo Blaxell 
318490c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
31855d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
318690c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
3187d7ce5843SMiao Xie 		if (ret < 0) {
318805135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
318905135f59SDavid Sterba 					ret);
3190d7ce5843SMiao Xie 			err = -EINVAL;
3191bcef60f2SArne Jansen 			goto fail_qgroup;
3192d7ce5843SMiao Xie 		}
31937c2ca468SChris Mason 	}
31941a40e23bSZheng Yan 
31953de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
31963de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
3197cb517eabSMiao Xie 	location.offset = 0;
31983de4586cSChris Mason 
31993de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
32003140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
32013140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3202f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3203315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3204bcef60f2SArne Jansen 		goto fail_qgroup;
32053140c9a3SDan Carpenter 	}
3206c289811cSChris Mason 
3207bc98a42cSDavid Howells 	if (sb_rdonly(sb))
32082b6ba629SIlya Dryomov 		return 0;
32092b6ba629SIlya Dryomov 
3210f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3211f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32126675df31SOmar Sandoval 		clear_free_space_tree = 1;
32136675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
32146675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
32156675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
32166675df31SOmar Sandoval 		clear_free_space_tree = 1;
32176675df31SOmar Sandoval 	}
32186675df31SOmar Sandoval 
32196675df31SOmar Sandoval 	if (clear_free_space_tree) {
3220f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3221f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3222f8d468a1SOmar Sandoval 		if (ret) {
3223f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3224f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
32256bccf3abSJeff Mahoney 			close_ctree(fs_info);
3226f8d468a1SOmar Sandoval 			return ret;
3227f8d468a1SOmar Sandoval 		}
3228f8d468a1SOmar Sandoval 	}
3229f8d468a1SOmar Sandoval 
32300b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3231511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
323205135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3233511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3234511711afSChris Mason 		if (ret) {
323505135f59SDavid Sterba 			btrfs_warn(fs_info,
323605135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
32376bccf3abSJeff Mahoney 			close_ctree(fs_info);
3238511711afSChris Mason 			return ret;
3239511711afSChris Mason 		}
3240511711afSChris Mason 	}
3241511711afSChris Mason 
3242e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
32432b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
32442b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
32452b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
32466bccf3abSJeff Mahoney 		close_ctree(fs_info);
32472b6ba629SIlya Dryomov 		return ret;
32482b6ba629SIlya Dryomov 	}
3249e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
325059641015SIlya Dryomov 
32512b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
32522b6ba629SIlya Dryomov 	if (ret) {
325305135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
32546bccf3abSJeff Mahoney 		close_ctree(fs_info);
32552b6ba629SIlya Dryomov 		return ret;
3256e3acc2a6SJosef Bacik 	}
3257e3acc2a6SJosef Bacik 
32588dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
32598dabb742SStefan Behrens 	if (ret) {
326005135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
32616bccf3abSJeff Mahoney 		close_ctree(fs_info);
32628dabb742SStefan Behrens 		return ret;
32638dabb742SStefan Behrens 	}
32648dabb742SStefan Behrens 
3265b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3266b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3267b382a324SJan Schmidt 
32684bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
326905135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3270f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3271f7a81ea4SStefan Behrens 		if (ret) {
327205135f59SDavid Sterba 			btrfs_warn(fs_info,
327305135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
32746bccf3abSJeff Mahoney 			close_ctree(fs_info);
3275f7a81ea4SStefan Behrens 			return ret;
3276f7a81ea4SStefan Behrens 		}
32770b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
32784bbcaa64SEric Sandeen 		   fs_info->generation !=
32794bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
328005135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
328170f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
328270f80175SStefan Behrens 		if (ret) {
328305135f59SDavid Sterba 			btrfs_warn(fs_info,
328405135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
32856bccf3abSJeff Mahoney 			close_ctree(fs_info);
328670f80175SStefan Behrens 			return ret;
328770f80175SStefan Behrens 		}
328870f80175SStefan Behrens 	} else {
3289afcdd129SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3290f7a81ea4SStefan Behrens 	}
3291afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
329247ab2a6cSJosef Bacik 
32938dcddfa0SQu Wenruo 	/*
32948dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
32958dcddfa0SQu Wenruo 	 * no need to keep the flag
32968dcddfa0SQu Wenruo 	 */
32978dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
32988dcddfa0SQu Wenruo 
3299ad2b2c80SAl Viro 	return 0;
330039279cc3SChris Mason 
3301bcef60f2SArne Jansen fail_qgroup:
3302bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
33037c2ca468SChris Mason fail_trans_kthread:
33047c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
33052ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3306faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
33073f157a2fSChris Mason fail_cleaner:
3308a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
33097c2ca468SChris Mason 
33107c2ca468SChris Mason 	/*
33117c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
33127c2ca468SChris Mason 	 * kthreads
33137c2ca468SChris Mason 	 */
33147c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
33157c2ca468SChris Mason 
33162365dd3cSAnand Jain fail_sysfs:
33176618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
33182365dd3cSAnand Jain 
3319b7c35e81SAnand Jain fail_fsdev_sysfs:
3320b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3321b7c35e81SAnand Jain 
33221b1d1f66SJosef Bacik fail_block_groups:
332354067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3324af31f5e5SChris Mason 
3325af31f5e5SChris Mason fail_tree_roots:
33264273eaffSAnand Jain 	free_root_pointers(fs_info, true);
33272b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3328af31f5e5SChris Mason 
332939279cc3SChris Mason fail_sb_buffer:
33307abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
33315cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
33326d97c6e3SJohannes Thumshirn fail_csum:
33336d97c6e3SJohannes Thumshirn 	btrfs_free_csum_hash(fs_info);
333416cdcec7SMiao Xie fail_alloc:
33354543df7eSChris Mason fail_iput:
3336586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3337586e46e2SIlya Dryomov 
33384543df7eSChris Mason 	iput(fs_info->btree_inode);
3339c404e0dcSMiao Xie fail_bio_counter:
33407f8d236aSDavid Sterba 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
3341963d678bSMiao Xie fail_delalloc_bytes:
3342963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3343e2d84521SMiao Xie fail_dirty_metadata_bytes:
3344e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
33454297ff84SJosef Bacik fail_dio_bytes:
33464297ff84SJosef Bacik 	percpu_counter_destroy(&fs_info->dio_bytes);
334776dda93cSYan, Zheng fail_srcu:
334876dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
33497e662854SQinghuang Feng fail:
335053b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3351586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3352ad2b2c80SAl Viro 	return err;
3353eb60ceacSChris Mason }
3354663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3355eb60ceacSChris Mason 
3356f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3357f2984462SChris Mason {
3358f2984462SChris Mason 	if (uptodate) {
3359f2984462SChris Mason 		set_buffer_uptodate(bh);
3360f2984462SChris Mason 	} else {
3361442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
3362442a4f63SStefan Behrens 			bh->b_private;
3363442a4f63SStefan Behrens 
3364fb456252SJeff Mahoney 		btrfs_warn_rl_in_rcu(device->fs_info,
3365b14af3b4SDavid Sterba 				"lost page write due to IO error on %s",
3366606686eeSJosef Bacik 					  rcu_str_deref(device->name));
336701327610SNicholas D Steeves 		/* note, we don't set_buffer_write_io_error because we have
33681259ab75SChris Mason 		 * our own ways of dealing with the IO errors
33691259ab75SChris Mason 		 */
3370f2984462SChris Mason 		clear_buffer_uptodate(bh);
3371442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3372f2984462SChris Mason 	}
3373f2984462SChris Mason 	unlock_buffer(bh);
3374f2984462SChris Mason 	put_bh(bh);
3375f2984462SChris Mason }
3376f2984462SChris Mason 
337729c36d72SAnand Jain int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
337829c36d72SAnand Jain 			struct buffer_head **bh_ret)
337929c36d72SAnand Jain {
338029c36d72SAnand Jain 	struct buffer_head *bh;
338129c36d72SAnand Jain 	struct btrfs_super_block *super;
338229c36d72SAnand Jain 	u64 bytenr;
338329c36d72SAnand Jain 
338429c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
338529c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
338629c36d72SAnand Jain 		return -EINVAL;
338729c36d72SAnand Jain 
33889f6d2510SDavid Sterba 	bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
338929c36d72SAnand Jain 	/*
339029c36d72SAnand Jain 	 * If we fail to read from the underlying devices, as of now
339129c36d72SAnand Jain 	 * the best option we have is to mark it EIO.
339229c36d72SAnand Jain 	 */
339329c36d72SAnand Jain 	if (!bh)
339429c36d72SAnand Jain 		return -EIO;
339529c36d72SAnand Jain 
339629c36d72SAnand Jain 	super = (struct btrfs_super_block *)bh->b_data;
339729c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
339829c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
339929c36d72SAnand Jain 		brelse(bh);
340029c36d72SAnand Jain 		return -EINVAL;
340129c36d72SAnand Jain 	}
340229c36d72SAnand Jain 
340329c36d72SAnand Jain 	*bh_ret = bh;
340429c36d72SAnand Jain 	return 0;
340529c36d72SAnand Jain }
340629c36d72SAnand Jain 
340729c36d72SAnand Jain 
3408a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3409a512bbf8SYan Zheng {
3410a512bbf8SYan Zheng 	struct buffer_head *bh;
3411a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
3412a512bbf8SYan Zheng 	struct btrfs_super_block *super;
3413a512bbf8SYan Zheng 	int i;
3414a512bbf8SYan Zheng 	u64 transid = 0;
341592fc03fbSAnand Jain 	int ret = -EINVAL;
3416a512bbf8SYan Zheng 
3417a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3418a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3419a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3420a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3421a512bbf8SYan Zheng 	 */
3422a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
342329c36d72SAnand Jain 		ret = btrfs_read_dev_one_super(bdev, i, &bh);
342429c36d72SAnand Jain 		if (ret)
3425a512bbf8SYan Zheng 			continue;
3426a512bbf8SYan Zheng 
3427a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
3428a512bbf8SYan Zheng 
3429a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
3430a512bbf8SYan Zheng 			brelse(latest);
3431a512bbf8SYan Zheng 			latest = bh;
3432a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3433a512bbf8SYan Zheng 		} else {
3434a512bbf8SYan Zheng 			brelse(bh);
3435a512bbf8SYan Zheng 		}
3436a512bbf8SYan Zheng 	}
343792fc03fbSAnand Jain 
343892fc03fbSAnand Jain 	if (!latest)
343992fc03fbSAnand Jain 		return ERR_PTR(ret);
344092fc03fbSAnand Jain 
3441a512bbf8SYan Zheng 	return latest;
3442a512bbf8SYan Zheng }
3443a512bbf8SYan Zheng 
34444eedeb75SHisashi Hifumi /*
3445abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3446abbb3b8eSDavid Sterba  * buffer heads we write are pinned.
34474eedeb75SHisashi Hifumi  *
3448abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3449abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3450abbb3b8eSDavid Sterba  * same for write and wait phases.
34514eedeb75SHisashi Hifumi  *
3452abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or submission fails.
34534eedeb75SHisashi Hifumi  */
3454a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3455abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3456a512bbf8SYan Zheng {
3457d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3458d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3459a512bbf8SYan Zheng 	struct buffer_head *bh;
3460a512bbf8SYan Zheng 	int i;
3461a512bbf8SYan Zheng 	int ret;
3462a512bbf8SYan Zheng 	int errors = 0;
3463a512bbf8SYan Zheng 	u64 bytenr;
34641b9e619cSOmar Sandoval 	int op_flags;
3465a512bbf8SYan Zheng 
3466a512bbf8SYan Zheng 	if (max_mirrors == 0)
3467a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3468a512bbf8SYan Zheng 
3469d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3470d5178578SJohannes Thumshirn 
3471a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3472a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3473935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3474935e5cc9SMiao Xie 		    device->commit_total_bytes)
3475a512bbf8SYan Zheng 			break;
3476a512bbf8SYan Zheng 
3477a512bbf8SYan Zheng 		btrfs_set_super_bytenr(sb, bytenr);
3478a512bbf8SYan Zheng 
3479d5178578SJohannes Thumshirn 		crypto_shash_init(shash);
3480d5178578SJohannes Thumshirn 		crypto_shash_update(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3481abbb3b8eSDavid Sterba 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3482d5178578SJohannes Thumshirn 		crypto_shash_final(shash, sb->csum);
3483a512bbf8SYan Zheng 
3484abbb3b8eSDavid Sterba 		/* One reference for us, and we leave it for the caller */
34859f6d2510SDavid Sterba 		bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3486a512bbf8SYan Zheng 			      BTRFS_SUPER_INFO_SIZE);
3487634554dcSJosef Bacik 		if (!bh) {
3488fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3489f14d104dSDavid Sterba 			    "couldn't get super buffer head for bytenr %llu",
3490f14d104dSDavid Sterba 			    bytenr);
3491634554dcSJosef Bacik 			errors++;
3492634554dcSJosef Bacik 			continue;
3493634554dcSJosef Bacik 		}
3494634554dcSJosef Bacik 
3495a512bbf8SYan Zheng 		memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3496a512bbf8SYan Zheng 
34974eedeb75SHisashi Hifumi 		/* one reference for submit_bh */
3498a512bbf8SYan Zheng 		get_bh(bh);
34994eedeb75SHisashi Hifumi 
35004eedeb75SHisashi Hifumi 		set_buffer_uptodate(bh);
3501a512bbf8SYan Zheng 		lock_buffer(bh);
3502a512bbf8SYan Zheng 		bh->b_end_io = btrfs_end_buffer_write_sync;
3503442a4f63SStefan Behrens 		bh->b_private = device;
3504a512bbf8SYan Zheng 
3505387125fcSChris Mason 		/*
3506387125fcSChris Mason 		 * we fua the first super.  The others we allow
3507387125fcSChris Mason 		 * to go down lazy.
3508387125fcSChris Mason 		 */
35091b9e619cSOmar Sandoval 		op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
35101b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
35111b9e619cSOmar Sandoval 			op_flags |= REQ_FUA;
35121b9e619cSOmar Sandoval 		ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
35134eedeb75SHisashi Hifumi 		if (ret)
3514a512bbf8SYan Zheng 			errors++;
3515a512bbf8SYan Zheng 	}
3516a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3517a512bbf8SYan Zheng }
3518a512bbf8SYan Zheng 
3519387125fcSChris Mason /*
3520abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3521abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3522abbb3b8eSDavid Sterba  *
3523abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or not marked up to
3524abbb3b8eSDavid Sterba  * date.
3525abbb3b8eSDavid Sterba  */
3526abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3527abbb3b8eSDavid Sterba {
3528abbb3b8eSDavid Sterba 	struct buffer_head *bh;
3529abbb3b8eSDavid Sterba 	int i;
3530abbb3b8eSDavid Sterba 	int errors = 0;
3531b6a535faSHoward McLauchlan 	bool primary_failed = false;
3532abbb3b8eSDavid Sterba 	u64 bytenr;
3533abbb3b8eSDavid Sterba 
3534abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3535abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3536abbb3b8eSDavid Sterba 
3537abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3538abbb3b8eSDavid Sterba 		bytenr = btrfs_sb_offset(i);
3539abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3540abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3541abbb3b8eSDavid Sterba 			break;
3542abbb3b8eSDavid Sterba 
35439f6d2510SDavid Sterba 		bh = __find_get_block(device->bdev,
35449f6d2510SDavid Sterba 				      bytenr / BTRFS_BDEV_BLOCKSIZE,
3545abbb3b8eSDavid Sterba 				      BTRFS_SUPER_INFO_SIZE);
3546abbb3b8eSDavid Sterba 		if (!bh) {
3547abbb3b8eSDavid Sterba 			errors++;
3548b6a535faSHoward McLauchlan 			if (i == 0)
3549b6a535faSHoward McLauchlan 				primary_failed = true;
3550abbb3b8eSDavid Sterba 			continue;
3551abbb3b8eSDavid Sterba 		}
3552abbb3b8eSDavid Sterba 		wait_on_buffer(bh);
3553b6a535faSHoward McLauchlan 		if (!buffer_uptodate(bh)) {
3554abbb3b8eSDavid Sterba 			errors++;
3555b6a535faSHoward McLauchlan 			if (i == 0)
3556b6a535faSHoward McLauchlan 				primary_failed = true;
3557b6a535faSHoward McLauchlan 		}
3558abbb3b8eSDavid Sterba 
3559abbb3b8eSDavid Sterba 		/* drop our reference */
3560abbb3b8eSDavid Sterba 		brelse(bh);
3561abbb3b8eSDavid Sterba 
3562abbb3b8eSDavid Sterba 		/* drop the reference from the writing run */
3563abbb3b8eSDavid Sterba 		brelse(bh);
3564abbb3b8eSDavid Sterba 	}
3565abbb3b8eSDavid Sterba 
3566b6a535faSHoward McLauchlan 	/* log error, force error return */
3567b6a535faSHoward McLauchlan 	if (primary_failed) {
3568b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3569b6a535faSHoward McLauchlan 			  device->devid);
3570b6a535faSHoward McLauchlan 		return -1;
3571b6a535faSHoward McLauchlan 	}
3572b6a535faSHoward McLauchlan 
3573abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3574abbb3b8eSDavid Sterba }
3575abbb3b8eSDavid Sterba 
3576abbb3b8eSDavid Sterba /*
3577387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3578387125fcSChris Mason  * for the barrier when it is done
3579387125fcSChris Mason  */
35804246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3581387125fcSChris Mason {
3582387125fcSChris Mason 	complete(bio->bi_private);
3583387125fcSChris Mason }
3584387125fcSChris Mason 
3585387125fcSChris Mason /*
35864fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
35874fc6441aSAnand Jain  * done in the waiting counterpart.
3588387125fcSChris Mason  */
35894fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3590387125fcSChris Mason {
3591c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3592e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3593387125fcSChris Mason 
3594c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
35954fc6441aSAnand Jain 		return;
3596387125fcSChris Mason 
3597e0ae9994SDavid Sterba 	bio_reset(bio);
3598387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
359974d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
36008d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3601387125fcSChris Mason 	init_completion(&device->flush_wait);
3602387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3603387125fcSChris Mason 
360443a01111SLu Fengqi 	btrfsic_submit_bio(bio);
36051c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
36064fc6441aSAnand Jain }
3607387125fcSChris Mason 
36084fc6441aSAnand Jain /*
36094fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
36104fc6441aSAnand Jain  */
36118c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
36124fc6441aSAnand Jain {
36134fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
36144fc6441aSAnand Jain 
36151c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
361658efbc9fSOmar Sandoval 		return BLK_STS_OK;
36174fc6441aSAnand Jain 
36181c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
36192980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
36204fc6441aSAnand Jain 
36218c27cb35SLinus Torvalds 	return bio->bi_status;
3622387125fcSChris Mason }
3623387125fcSChris Mason 
3624d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3625401b41e5SAnand Jain {
36266528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3627401b41e5SAnand Jain 		return -EIO;
3628387125fcSChris Mason 	return 0;
3629387125fcSChris Mason }
3630387125fcSChris Mason 
3631387125fcSChris Mason /*
3632387125fcSChris Mason  * send an empty flush down to each device in parallel,
3633387125fcSChris Mason  * then wait for them
3634387125fcSChris Mason  */
3635387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3636387125fcSChris Mason {
3637387125fcSChris Mason 	struct list_head *head;
3638387125fcSChris Mason 	struct btrfs_device *dev;
36395af3e8ccSStefan Behrens 	int errors_wait = 0;
36404e4cbee9SChristoph Hellwig 	blk_status_t ret;
3641387125fcSChris Mason 
36421538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3643387125fcSChris Mason 	/* send down all the barriers */
3644387125fcSChris Mason 	head = &info->fs_devices->devices;
36451538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3646e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3647f88ba6a2SHidetoshi Seto 			continue;
3648cea7c8bfSAnand Jain 		if (!dev->bdev)
3649387125fcSChris Mason 			continue;
3650e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3651ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3652387125fcSChris Mason 			continue;
3653387125fcSChris Mason 
36544fc6441aSAnand Jain 		write_dev_flush(dev);
365558efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3656387125fcSChris Mason 	}
3657387125fcSChris Mason 
3658387125fcSChris Mason 	/* wait for all the barriers */
36591538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3660e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3661f88ba6a2SHidetoshi Seto 			continue;
3662387125fcSChris Mason 		if (!dev->bdev) {
36635af3e8ccSStefan Behrens 			errors_wait++;
3664387125fcSChris Mason 			continue;
3665387125fcSChris Mason 		}
3666e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3667ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3668387125fcSChris Mason 			continue;
3669387125fcSChris Mason 
36704fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3671401b41e5SAnand Jain 		if (ret) {
3672401b41e5SAnand Jain 			dev->last_flush_error = ret;
367366b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
367466b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
36755af3e8ccSStefan Behrens 			errors_wait++;
3676387125fcSChris Mason 		}
3677401b41e5SAnand Jain 	}
3678401b41e5SAnand Jain 
3679cea7c8bfSAnand Jain 	if (errors_wait) {
3680401b41e5SAnand Jain 		/*
3681401b41e5SAnand Jain 		 * At some point we need the status of all disks
3682401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3683401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3684401b41e5SAnand Jain 		 */
3685d10b82feSQu Wenruo 		return check_barrier_error(info);
3686401b41e5SAnand Jain 	}
3687387125fcSChris Mason 	return 0;
3688387125fcSChris Mason }
3689387125fcSChris Mason 
3690943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3691943c6e99SZhao Lei {
36928789f4feSZhao Lei 	int raid_type;
36938789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3694943c6e99SZhao Lei 
36958789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
36968789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
36978c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
36988789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
36998789f4feSZhao Lei 				    tolerated_failures);
3700943c6e99SZhao Lei 
37018789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
37028789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
37038789f4feSZhao Lei 			continue;
370441a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
37058789f4feSZhao Lei 			continue;
37068c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
37078789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
37088789f4feSZhao Lei 				    tolerated_failures);
37098789f4feSZhao Lei 	}
3710943c6e99SZhao Lei 
37118789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3712ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
37138789f4feSZhao Lei 		min_tolerated = 0;
37148789f4feSZhao Lei 	}
37158789f4feSZhao Lei 
37168789f4feSZhao Lei 	return min_tolerated;
3717943c6e99SZhao Lei }
3718943c6e99SZhao Lei 
3719eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3720f2984462SChris Mason {
3721e5e9a520SChris Mason 	struct list_head *head;
3722f2984462SChris Mason 	struct btrfs_device *dev;
3723a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3724f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3725f2984462SChris Mason 	int ret;
3726f2984462SChris Mason 	int do_barriers;
3727a236aed1SChris Mason 	int max_errors;
3728a236aed1SChris Mason 	int total_errors = 0;
3729a061fc8dSChris Mason 	u64 flags;
3730f2984462SChris Mason 
37310b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3732fed3b381SLiu Bo 
3733fed3b381SLiu Bo 	/*
3734fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3735fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3736fed3b381SLiu Bo 	 * been consistent on disk.
3737fed3b381SLiu Bo 	 */
3738fed3b381SLiu Bo 	if (max_mirrors == 0)
37390b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3740f2984462SChris Mason 
37410b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3742a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3743e5e9a520SChris Mason 
37440b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
37450b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
37460b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3747387125fcSChris Mason 
37485af3e8ccSStefan Behrens 	if (do_barriers) {
37490b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
37505af3e8ccSStefan Behrens 		if (ret) {
37515af3e8ccSStefan Behrens 			mutex_unlock(
37520b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
37530b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
37545af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
37555af3e8ccSStefan Behrens 			return ret;
37565af3e8ccSStefan Behrens 		}
37575af3e8ccSStefan Behrens 	}
3758387125fcSChris Mason 
37591538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3760dfe25020SChris Mason 		if (!dev->bdev) {
3761dfe25020SChris Mason 			total_errors++;
3762dfe25020SChris Mason 			continue;
3763dfe25020SChris Mason 		}
3764e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3765ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3766dfe25020SChris Mason 			continue;
3767dfe25020SChris Mason 
37682b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3769a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3770a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
37717df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3772935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3773ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3774ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3775a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3776a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3777a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3778a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
37797239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
37807239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
3781a512bbf8SYan Zheng 
3782a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3783a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3784f2984462SChris Mason 
378575cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
378675cb857dSQu Wenruo 		if (ret < 0) {
378775cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
378875cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
378975cb857dSQu Wenruo 				"unexpected superblock corruption detected");
379075cb857dSQu Wenruo 			return -EUCLEAN;
379175cb857dSQu Wenruo 		}
379275cb857dSQu Wenruo 
3793abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3794a236aed1SChris Mason 		if (ret)
3795a236aed1SChris Mason 			total_errors++;
3796f2984462SChris Mason 	}
3797a236aed1SChris Mason 	if (total_errors > max_errors) {
37980b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3799d397712bSChris Mason 			  total_errors);
38000b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
380179787eaaSJeff Mahoney 
38029d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
38030b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38040b246afaSJeff Mahoney 				      "%d errors while writing supers",
38050b246afaSJeff Mahoney 				      total_errors);
38069d565ba4SStefan Behrens 		return -EIO;
3807a236aed1SChris Mason 	}
3808f2984462SChris Mason 
3809a512bbf8SYan Zheng 	total_errors = 0;
38101538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3811dfe25020SChris Mason 		if (!dev->bdev)
3812dfe25020SChris Mason 			continue;
3813e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3814ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3815dfe25020SChris Mason 			continue;
3816dfe25020SChris Mason 
3817abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3818a512bbf8SYan Zheng 		if (ret)
38191259ab75SChris Mason 			total_errors++;
3820f2984462SChris Mason 	}
38210b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3822a236aed1SChris Mason 	if (total_errors > max_errors) {
38230b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38240b246afaSJeff Mahoney 				      "%d errors while writing supers",
38250b246afaSJeff Mahoney 				      total_errors);
382679787eaaSJeff Mahoney 		return -EIO;
3827a236aed1SChris Mason 	}
3828f2984462SChris Mason 	return 0;
3829f2984462SChris Mason }
3830f2984462SChris Mason 
3831cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3832cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3833cb517eabSMiao Xie 				  struct btrfs_root *root)
38342619ba1fSChris Mason {
38354df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
38362619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
38372619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
38384df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
383976dda93cSYan, Zheng 
384076dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
384176dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
384276dda93cSYan, Zheng 
38431c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
38443321719eSLiu Bo 		btrfs_free_log(NULL, root);
38451c1ea4f7SLiu Bo 		if (root->reloc_root) {
38461c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->node);
38471c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->commit_root);
38481c1ea4f7SLiu Bo 			btrfs_put_fs_root(root->reloc_root);
38491c1ea4f7SLiu Bo 			root->reloc_root = NULL;
38501c1ea4f7SLiu Bo 		}
38511c1ea4f7SLiu Bo 	}
38523321719eSLiu Bo 
3853faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3854581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3855faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3856581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
385784db5ccfSDavid Sterba 	btrfs_free_fs_root(root);
38584df27c4dSYan, Zheng }
38594df27c4dSYan, Zheng 
386084db5ccfSDavid Sterba void btrfs_free_fs_root(struct btrfs_root *root)
38614df27c4dSYan, Zheng {
386257cdc8dbSDavid Sterba 	iput(root->ino_cache_inode);
38634df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
38640ee5dc67SAl Viro 	if (root->anon_dev)
38650ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
38668257b2dcSMiao Xie 	if (root->subv_writers)
38678257b2dcSMiao Xie 		btrfs_free_subvolume_writers(root->subv_writers);
38685f39d397SChris Mason 	free_extent_buffer(root->node);
38695f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3870581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3871581bb050SLi Zefan 	kfree(root->free_ino_pinned);
3872b0feb9d9SMiao Xie 	btrfs_put_fs_root(root);
38732619ba1fSChris Mason }
38742619ba1fSChris Mason 
3875c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3876c146afadSYan Zheng {
3877c146afadSYan Zheng 	u64 root_objectid = 0;
3878c146afadSYan Zheng 	struct btrfs_root *gang[8];
387965d33fd7SQu Wenruo 	int i = 0;
388065d33fd7SQu Wenruo 	int err = 0;
388165d33fd7SQu Wenruo 	unsigned int ret = 0;
388265d33fd7SQu Wenruo 	int index;
3883c146afadSYan Zheng 
3884c146afadSYan Zheng 	while (1) {
388565d33fd7SQu Wenruo 		index = srcu_read_lock(&fs_info->subvol_srcu);
3886c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3887c146afadSYan Zheng 					     (void **)gang, root_objectid,
3888c146afadSYan Zheng 					     ARRAY_SIZE(gang));
388965d33fd7SQu Wenruo 		if (!ret) {
389065d33fd7SQu Wenruo 			srcu_read_unlock(&fs_info->subvol_srcu, index);
3891c146afadSYan Zheng 			break;
389265d33fd7SQu Wenruo 		}
38935d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
389466b4ffd1SJosef Bacik 
389565d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
389665d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
389765d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
389865d33fd7SQu Wenruo 				gang[i] = NULL;
389965d33fd7SQu Wenruo 				continue;
390065d33fd7SQu Wenruo 			}
390165d33fd7SQu Wenruo 			/* grab all the search result for later use */
390265d33fd7SQu Wenruo 			gang[i] = btrfs_grab_fs_root(gang[i]);
390365d33fd7SQu Wenruo 		}
390465d33fd7SQu Wenruo 		srcu_read_unlock(&fs_info->subvol_srcu, index);
390565d33fd7SQu Wenruo 
390665d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
390765d33fd7SQu Wenruo 			if (!gang[i])
390865d33fd7SQu Wenruo 				continue;
3909c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
391066b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
391166b4ffd1SJosef Bacik 			if (err)
391265d33fd7SQu Wenruo 				break;
391365d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
3914c146afadSYan Zheng 		}
3915c146afadSYan Zheng 		root_objectid++;
3916c146afadSYan Zheng 	}
391765d33fd7SQu Wenruo 
391865d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
391965d33fd7SQu Wenruo 	for (; i < ret; i++) {
392065d33fd7SQu Wenruo 		if (gang[i])
392165d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
392265d33fd7SQu Wenruo 	}
392365d33fd7SQu Wenruo 	return err;
3924c146afadSYan Zheng }
3925c146afadSYan Zheng 
39266bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3927c146afadSYan Zheng {
39286bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3929c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3930c146afadSYan Zheng 
39310b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
39322ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
39330b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
39340b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
3935c71bf099SYan, Zheng 
3936c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
39370b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
39380b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
3939c71bf099SYan, Zheng 
39407a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
39413612b495STsutomu Itoh 	if (IS_ERR(trans))
39423612b495STsutomu Itoh 		return PTR_ERR(trans);
39433a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
3944c146afadSYan Zheng }
3945c146afadSYan Zheng 
3946b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
3947eb60ceacSChris Mason {
3948c146afadSYan Zheng 	int ret;
3949e089f05cSChris Mason 
3950afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3951d6fd0ae2SOmar Sandoval 	/*
3952d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
3953d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
3954d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
3955d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
3956d6fd0ae2SOmar Sandoval 	 */
3957d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
3958a2135011SChris Mason 
39597343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
3960d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
39617343dd61SJustin Maggard 
3962803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3963803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3964803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3965803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3966803b2f54SStefan Behrens 
3967837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3968aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3969837d5b6eSIlya Dryomov 
39708dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
39718dabb742SStefan Behrens 
3972aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
39734cb5300bSChris Mason 
39744cb5300bSChris Mason 	/* wait for any defraggers to finish */
39754cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
39764cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
39774cb5300bSChris Mason 
39784cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
397926176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
39804cb5300bSChris Mason 
398121c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
398221c7e756SMiao Xie 
3983b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
3984b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
3985b0643e59SDennis Zhou 
3986bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
3987e44163e1SJeff Mahoney 		/*
3988d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
3989d6fd0ae2SOmar Sandoval 		 * unused block groups.
3990e44163e1SJeff Mahoney 		 */
39910b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
3992e44163e1SJeff Mahoney 
39936bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
3994d397712bSChris Mason 		if (ret)
399504892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
3996c146afadSYan Zheng 	}
3997ed2ff2cbSChris Mason 
3998af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
3999af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
40002ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4001acce952bSliubo 
4002e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4003e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
40048929ecfaSYan, Zheng 
4005e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4006afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4007f25784b3SYan Zheng 
400804892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4009fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4010bcef60f2SArne Jansen 
4011963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
401204892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4013963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4014b0c68f8bSChris Mason 	}
401531153d81SYan Zheng 
40164297ff84SJosef Bacik 	if (percpu_counter_sum(&fs_info->dio_bytes))
40174297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
40184297ff84SJosef Bacik 			   percpu_counter_sum(&fs_info->dio_bytes));
40194297ff84SJosef Bacik 
40206618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4021b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
40225ac1d209SJeff Mahoney 
4023faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
4024d10c5f31SChris Mason 
40251a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
40261a4319ccSLiu Bo 
4027de348ee0SWang Shilong 	/*
4028de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4029de348ee0SWang Shilong 	 * submit after we stopping all workers.
4030de348ee0SWang Shilong 	 */
4031de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
403296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
403396192499SJosef Bacik 
4034afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
40354273eaffSAnand Jain 	free_root_pointers(fs_info, true);
40369ad6b7bcSChris Mason 
40374e19443dSJosef Bacik 	/*
40384e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
40394e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
40404e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
40414e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
40424e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
40434e19443dSJosef Bacik 	 */
40444e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
40454e19443dSJosef Bacik 
404613e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4047d6bfde87SChris Mason 
404821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
40490b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
40502ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
405121adbd5cSStefan Behrens #endif
405221adbd5cSStefan Behrens 
40530b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
405468c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4055b248a415SChris Mason 
4056e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
4057963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
40584297ff84SJosef Bacik 	percpu_counter_destroy(&fs_info->dio_bytes);
40597f8d236aSDavid Sterba 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
406076dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
40610b86a832SChris Mason 
4062bfcea1c6SJohannes Thumshirn 	btrfs_free_csum_hash(fs_info);
406353b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
4064fd708b81SJosef Bacik 	btrfs_free_ref_cache(fs_info);
4065eb60ceacSChris Mason }
4066eb60ceacSChris Mason 
4067b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4068b9fab919SChris Mason 			  int atomic)
4069ccd467d6SChris Mason {
40701259ab75SChris Mason 	int ret;
4071727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
40721259ab75SChris Mason 
40730b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
40741259ab75SChris Mason 	if (!ret)
40751259ab75SChris Mason 		return ret;
40761259ab75SChris Mason 
40771259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4078b9fab919SChris Mason 				    parent_transid, atomic);
4079b9fab919SChris Mason 	if (ret == -EAGAIN)
4080b9fab919SChris Mason 		return ret;
40811259ab75SChris Mason 	return !ret;
40825f39d397SChris Mason }
40836702ed49SChris Mason 
40845f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
40855f39d397SChris Mason {
40860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
408706ea65a3SJosef Bacik 	struct btrfs_root *root;
40885f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4089b9473439SChris Mason 	int was_dirty;
4090b4ce94deSChris Mason 
409106ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
409206ea65a3SJosef Bacik 	/*
409306ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
409452042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
409506ea65a3SJosef Bacik 	 * outside of the sanity tests.
409606ea65a3SJosef Bacik 	 */
4097b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
409806ea65a3SJosef Bacik 		return;
409906ea65a3SJosef Bacik #endif
410006ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
41010b246afaSJeff Mahoney 	fs_info = root->fs_info;
4102b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
41030b246afaSJeff Mahoney 	if (transid != fs_info->generation)
41045d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
41050b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
41060b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4107e2d84521SMiao Xie 	if (!was_dirty)
4108104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4109e2d84521SMiao Xie 					 buf->len,
41100b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
41111f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
411269fc6cbbSQu Wenruo 	/*
411369fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
411469fc6cbbSQu Wenruo 	 * but item data not updated.
411569fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
411669fc6cbbSQu Wenruo 	 */
411769fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4118cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4119a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
41201f21ef0aSFilipe Manana 		ASSERT(0);
41211f21ef0aSFilipe Manana 	}
41221f21ef0aSFilipe Manana #endif
4123eb60ceacSChris Mason }
4124eb60ceacSChris Mason 
41252ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4126b53d3f5dSLiu Bo 					int flush_delayed)
412735b7e476SChris Mason {
4128188de649SChris Mason 	/*
4129188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4130188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4131188de649SChris Mason 	 */
4132e2d84521SMiao Xie 	int ret;
4133d6bfde87SChris Mason 
41346933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4135d6bfde87SChris Mason 		return;
4136d6bfde87SChris Mason 
4137b53d3f5dSLiu Bo 	if (flush_delayed)
41382ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
413916cdcec7SMiao Xie 
4140d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4141d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4142d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4143e2d84521SMiao Xie 	if (ret > 0) {
41440b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
414516cdcec7SMiao Xie 	}
414616cdcec7SMiao Xie }
414716cdcec7SMiao Xie 
41482ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
414916cdcec7SMiao Xie {
41502ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
415135b7e476SChris Mason }
4152b53d3f5dSLiu Bo 
41532ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4154b53d3f5dSLiu Bo {
41552ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4156d6bfde87SChris Mason }
41576b80053dSChris Mason 
4158581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4159581c1760SQu Wenruo 		      struct btrfs_key *first_key)
41606b80053dSChris Mason {
41615ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4162581c1760SQu Wenruo 					      level, first_key);
41636b80053dSChris Mason }
41640da5468fSChris Mason 
41652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4166acce952bSliubo {
4167fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4168fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4169fe816d0fSNikolay Borisov 
41700b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41712ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41720b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4173acce952bSliubo 
41740b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41750b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4176acce952bSliubo }
4177acce952bSliubo 
4178143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4179acce952bSliubo {
4180acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4181acce952bSliubo 
4182199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4183779880efSJosef Bacik 	/*
4184779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4185779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4186779880efSJosef Bacik 	 */
4187199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4188779880efSJosef Bacik 			    root_extent_list)
4189779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4190199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4191199c2a9cSMiao Xie }
4192199c2a9cSMiao Xie 
4193199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4194199c2a9cSMiao Xie {
4195199c2a9cSMiao Xie 	struct btrfs_root *root;
4196199c2a9cSMiao Xie 	struct list_head splice;
4197199c2a9cSMiao Xie 
4198199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4199199c2a9cSMiao Xie 
4200199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4201199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4202199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4203199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4204199c2a9cSMiao Xie 					ordered_root);
42051de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
42061de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4207199c2a9cSMiao Xie 
42082a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4209199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4210199c2a9cSMiao Xie 
42112a85d9caSLiu Bo 		cond_resched();
42122a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4213199c2a9cSMiao Xie 	}
4214199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
421574d5d229SJosef Bacik 
421674d5d229SJosef Bacik 	/*
421774d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
421874d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
421974d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
422074d5d229SJosef Bacik 	 * actually get run and error out properly.
422174d5d229SJosef Bacik 	 */
422274d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4223acce952bSliubo }
4224acce952bSliubo 
422535a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
42262ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4227acce952bSliubo {
4228acce952bSliubo 	struct rb_node *node;
4229acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4230acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4231acce952bSliubo 	int ret = 0;
4232acce952bSliubo 
4233acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4234acce952bSliubo 
4235acce952bSliubo 	spin_lock(&delayed_refs->lock);
4236d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4237cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
42380b246afaSJeff Mahoney 		btrfs_info(fs_info, "delayed_refs has NO entry");
4239acce952bSliubo 		return ret;
4240acce952bSliubo 	}
4241acce952bSliubo 
42425c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4243d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
42440e0adbcfSJosef Bacik 		struct rb_node *n;
4245e78417d1SJosef Bacik 		bool pin_bytes = false;
4246acce952bSliubo 
4247d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4248d7df2c79SJosef Bacik 				href_node);
42493069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4250b939d1abSJosef Bacik 			continue;
42513069bd26SJosef Bacik 
4252d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4253e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
42540e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
42550e0adbcfSJosef Bacik 				       ref_node);
4256d7df2c79SJosef Bacik 			ref->in_tree = 0;
4257e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
42580e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
42591d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
42601d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4261d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4262d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4263d7df2c79SJosef Bacik 		}
426454067ae9SJosef Bacik 		if (head->must_insert_reserved)
4265e78417d1SJosef Bacik 			pin_bytes = true;
426678a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4267fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4268d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4269acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4270e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4271acce952bSliubo 
4272d7df2c79SJosef Bacik 		if (pin_bytes)
4273d278850eSJosef Bacik 			btrfs_pin_extent(fs_info, head->bytenr,
4274d278850eSJosef Bacik 					 head->num_bytes, 1);
427531890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4276d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4277acce952bSliubo 		cond_resched();
4278acce952bSliubo 		spin_lock(&delayed_refs->lock);
4279acce952bSliubo 	}
428081f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4281acce952bSliubo 
4282acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4283acce952bSliubo 
4284acce952bSliubo 	return ret;
4285acce952bSliubo }
4286acce952bSliubo 
4287143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4288acce952bSliubo {
4289acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4290acce952bSliubo 	struct list_head splice;
4291acce952bSliubo 
4292acce952bSliubo 	INIT_LIST_HEAD(&splice);
4293acce952bSliubo 
4294eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4295eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4296acce952bSliubo 
4297acce952bSliubo 	while (!list_empty(&splice)) {
4298fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4299eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4300acce952bSliubo 					       delalloc_inodes);
4301fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4302eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4303acce952bSliubo 
4304fe816d0fSNikolay Borisov 		/*
4305fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4306fe816d0fSNikolay Borisov 		 * meanwhile.
4307fe816d0fSNikolay Borisov 		 */
4308fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4309fe816d0fSNikolay Borisov 		if (inode) {
4310fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4311fe816d0fSNikolay Borisov 			iput(inode);
4312fe816d0fSNikolay Borisov 		}
4313eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4314acce952bSliubo 	}
4315eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4316eb73c1b7SMiao Xie }
4317eb73c1b7SMiao Xie 
4318eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4319eb73c1b7SMiao Xie {
4320eb73c1b7SMiao Xie 	struct btrfs_root *root;
4321eb73c1b7SMiao Xie 	struct list_head splice;
4322eb73c1b7SMiao Xie 
4323eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4324eb73c1b7SMiao Xie 
4325eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4326eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4327eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4328eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4329eb73c1b7SMiao Xie 					 delalloc_root);
4330eb73c1b7SMiao Xie 		root = btrfs_grab_fs_root(root);
4331eb73c1b7SMiao Xie 		BUG_ON(!root);
4332eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4333eb73c1b7SMiao Xie 
4334eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
4335eb73c1b7SMiao Xie 		btrfs_put_fs_root(root);
4336eb73c1b7SMiao Xie 
4337eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4338eb73c1b7SMiao Xie 	}
4339eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4340acce952bSliubo }
4341acce952bSliubo 
43422ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4343acce952bSliubo 					struct extent_io_tree *dirty_pages,
4344acce952bSliubo 					int mark)
4345acce952bSliubo {
4346acce952bSliubo 	int ret;
4347acce952bSliubo 	struct extent_buffer *eb;
4348acce952bSliubo 	u64 start = 0;
4349acce952bSliubo 	u64 end;
4350acce952bSliubo 
4351acce952bSliubo 	while (1) {
4352acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4353e6138876SJosef Bacik 					    mark, NULL);
4354acce952bSliubo 		if (ret)
4355acce952bSliubo 			break;
4356acce952bSliubo 
435791166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4358acce952bSliubo 		while (start <= end) {
43590b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
43600b246afaSJeff Mahoney 			start += fs_info->nodesize;
4361fd8b2b61SJosef Bacik 			if (!eb)
4362acce952bSliubo 				continue;
4363fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4364acce952bSliubo 
4365fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4366fd8b2b61SJosef Bacik 					       &eb->bflags))
4367fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4368fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4369acce952bSliubo 		}
4370acce952bSliubo 	}
4371acce952bSliubo 
4372acce952bSliubo 	return ret;
4373acce952bSliubo }
4374acce952bSliubo 
43752ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4376acce952bSliubo 				       struct extent_io_tree *pinned_extents)
4377acce952bSliubo {
4378acce952bSliubo 	struct extent_io_tree *unpin;
4379acce952bSliubo 	u64 start;
4380acce952bSliubo 	u64 end;
4381acce952bSliubo 	int ret;
4382ed0eaa14SLiu Bo 	bool loop = true;
4383acce952bSliubo 
4384acce952bSliubo 	unpin = pinned_extents;
4385ed0eaa14SLiu Bo again:
4386acce952bSliubo 	while (1) {
43870e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
43880e6ec385SFilipe Manana 
4389fcd5e742SLu Fengqi 		/*
4390fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4391fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4392fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4393fcd5e742SLu Fengqi 		 * the same extent range.
4394fcd5e742SLu Fengqi 		 */
4395fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4396acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
43970e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4398fcd5e742SLu Fengqi 		if (ret) {
4399fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4400acce952bSliubo 			break;
4401fcd5e742SLu Fengqi 		}
4402acce952bSliubo 
44030e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
44040e6ec385SFilipe Manana 		free_extent_state(cached_state);
44052ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4406fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4407acce952bSliubo 		cond_resched();
4408acce952bSliubo 	}
4409acce952bSliubo 
4410ed0eaa14SLiu Bo 	if (loop) {
44110b246afaSJeff Mahoney 		if (unpin == &fs_info->freed_extents[0])
44120b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[1];
4413ed0eaa14SLiu Bo 		else
44140b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[0];
4415ed0eaa14SLiu Bo 		loop = false;
4416ed0eaa14SLiu Bo 		goto again;
4417ed0eaa14SLiu Bo 	}
4418ed0eaa14SLiu Bo 
4419acce952bSliubo 	return 0;
4420acce952bSliubo }
4421acce952bSliubo 
442232da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4423c79a1751SLiu Bo {
4424c79a1751SLiu Bo 	struct inode *inode;
4425c79a1751SLiu Bo 
4426c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4427c79a1751SLiu Bo 	if (inode) {
4428c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4429c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4430c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4431c79a1751SLiu Bo 		iput(inode);
4432c79a1751SLiu Bo 	}
4433c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4434c79a1751SLiu Bo }
4435c79a1751SLiu Bo 
4436c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
44372ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4438c79a1751SLiu Bo {
443932da5386SDavid Sterba 	struct btrfs_block_group *cache;
4440c79a1751SLiu Bo 
4441c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4442c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4443c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
444432da5386SDavid Sterba 					 struct btrfs_block_group,
4445c79a1751SLiu Bo 					 dirty_list);
4446c79a1751SLiu Bo 
4447c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4448c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4449c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4450c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4451c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4452c79a1751SLiu Bo 		}
4453c79a1751SLiu Bo 
4454c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4455c79a1751SLiu Bo 		spin_lock(&cache->lock);
4456c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4457c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4458c79a1751SLiu Bo 
4459c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4460c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4461ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4462c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4463c79a1751SLiu Bo 	}
4464c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4465c79a1751SLiu Bo 
446645ae2c18SNikolay Borisov 	/*
446745ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
446845ae2c18SNikolay Borisov 	 * to use it without any locking
446945ae2c18SNikolay Borisov 	 */
4470c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4471c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
447232da5386SDavid Sterba 					 struct btrfs_block_group,
4473c79a1751SLiu Bo 					 io_list);
4474c79a1751SLiu Bo 
4475c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4476c79a1751SLiu Bo 		spin_lock(&cache->lock);
4477c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4478c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4479c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4480c79a1751SLiu Bo 	}
4481c79a1751SLiu Bo }
4482c79a1751SLiu Bo 
448349b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
44842ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
448549b25e05SJeff Mahoney {
4486bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4487bbbf7243SNikolay Borisov 
44882ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4489c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4490c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4491c79a1751SLiu Bo 
4492bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4493bbbf7243SNikolay Borisov 				 post_commit_list) {
4494bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4495bbbf7243SNikolay Borisov 	}
4496bbbf7243SNikolay Borisov 
44972ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
449849b25e05SJeff Mahoney 
44994a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
45000b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
450149b25e05SJeff Mahoney 
45024a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
45030b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
450449b25e05SJeff Mahoney 
4505ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4506ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
450767cde344SMiao Xie 
45082ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
450949b25e05SJeff Mahoney 				     EXTENT_DIRTY);
45102ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info,
45110b246afaSJeff Mahoney 				    fs_info->pinned_extents);
451249b25e05SJeff Mahoney 
45134a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
45144a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
451549b25e05SJeff Mahoney }
451649b25e05SJeff Mahoney 
45172ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4518acce952bSliubo {
4519acce952bSliubo 	struct btrfs_transaction *t;
4520acce952bSliubo 
45210b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4522acce952bSliubo 
45230b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
45240b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
45250b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4526724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4527724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
45289b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
45290b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
45302ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4531724e2315SJosef Bacik 			btrfs_put_transaction(t);
45320b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4533724e2315SJosef Bacik 			continue;
4534724e2315SJosef Bacik 		}
45350b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4536724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
45370b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4538724e2315SJosef Bacik 			/*
4539724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4540724e2315SJosef Bacik 			 * handle open currently for this transaction.
4541724e2315SJosef Bacik 			 */
4542724e2315SJosef Bacik 			wait_event(t->writer_wait,
4543724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4544724e2315SJosef Bacik 		} else {
45450b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4546724e2315SJosef Bacik 		}
45472ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4548724e2315SJosef Bacik 
45490b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
45500b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
45510b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4552724e2315SJosef Bacik 		list_del_init(&t->list);
45530b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4554a4abeea4SJosef Bacik 
4555724e2315SJosef Bacik 		btrfs_put_transaction(t);
45562ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
45570b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4558724e2315SJosef Bacik 	}
45590b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
45600b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4561ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4562ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
45632ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
45640b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
45650b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4566acce952bSliubo 
4567acce952bSliubo 	return 0;
4568acce952bSliubo }
4569acce952bSliubo 
4570e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
45714d53dddbSDavid Sterba 	/* mandatory callbacks */
45720b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
45734d53dddbSDavid Sterba 	.readpage_end_io_hook = btree_readpage_end_io_hook,
45740da5468fSChris Mason };
4575