xref: /openbmc/linux/fs/btrfs/disk-io.c (revision fd08001f)
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>
10ce9adaa5SChris Mason #include <linux/workqueue.h>
11a74a4b97SChris Mason #include <linux/kthread.h>
125a0e3ad6STejun Heo #include <linux/slab.h>
13784b4e29SChris Mason #include <linux/migrate.h>
147a36ddecSDavid Sterba #include <linux/ratelimit.h>
156463fe58SStefan Behrens #include <linux/uuid.h>
16803b2f54SStefan Behrens #include <linux/semaphore.h>
17540adea3SMasami Hiramatsu #include <linux/error-injection.h>
189678c543SNikolay Borisov #include <linux/crc32c.h>
19b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
216d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
24e089f05cSChris Mason #include "transaction.h"
250f7d52f4SChris Mason #include "btrfs_inode.h"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
32581bb050SLi Zefan #include "inode-map.h"
3321adbd5cSStefan Behrens #include "check-integrity.h"
34606686eeSJosef Bacik #include "rcu-string.h"
358dabb742SStefan Behrens #include "dev-replace.h"
3653b381b3SDavid Woodhouse #include "raid56.h"
375ac1d209SJeff Mahoney #include "sysfs.h"
38fcebe456SJosef Bacik #include "qgroup.h"
39ebb8765bSAnand Jain #include "compression.h"
40557ea5ddSQu Wenruo #include "tree-checker.h"
41fd708b81SJosef Bacik #include "ref-verify.h"
42aac0023cSJosef Bacik #include "block-group.h"
43b0643e59SDennis Zhou #include "discard.h"
44f603bb94SNikolay Borisov #include "space-info.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 
101141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
102141386e1SJosef Bacik {
103141386e1SJosef Bacik 	if (fs_info->csum_shash)
104141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
105141386e1SJosef Bacik }
106141386e1SJosef Bacik 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
109d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
110d352ac68SChris Mason  * just before they are sent down the IO stack.
111d352ac68SChris Mason  */
11244b8bd7eSChris Mason struct async_submit_bio {
113c6100a4bSJosef Bacik 	void *private_data;
11444b8bd7eSChris Mason 	struct bio *bio;
115a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11644b8bd7eSChris Mason 	int mirror_num;
117eaf25d93SChris Mason 	/*
118eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
119eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
120eaf25d93SChris Mason 	 */
121eaf25d93SChris Mason 	u64 bio_offset;
1228b712842SChris Mason 	struct btrfs_work work;
1234e4cbee9SChristoph Hellwig 	blk_status_t status;
12444b8bd7eSChris Mason };
12544b8bd7eSChris Mason 
12685d4e461SChris Mason /*
12785d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12885d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12985d4e461SChris Mason  * the level the eb occupies in the tree.
1304008c04aSChris Mason  *
13185d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13285d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13385d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1344fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1354fd786e6SMisono Tomohiro  * roots have separate keysets.
1364008c04aSChris Mason  *
13785d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13885d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13985d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1404008c04aSChris Mason  *
14185d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14285d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14385d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14485d4e461SChris Mason  *
14585d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14685d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14785d4e461SChris Mason  * needs update as well.
1484008c04aSChris Mason  */
1494008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1504008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1514008c04aSChris Mason #  error
1524008c04aSChris Mason # endif
15385d4e461SChris Mason 
15485d4e461SChris Mason static struct btrfs_lockdep_keyset {
15585d4e461SChris Mason 	u64			id;		/* root objectid */
15685d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
15785d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
15885d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
15985d4e461SChris Mason } btrfs_lockdep_keysets[] = {
16085d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
16185d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
16285d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
16385d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
16485d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
16585d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
16660b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
16785d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
16885d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
16985d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
17013fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
1716b20e0adSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	.name_stem = "free-space" },
17285d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1734008c04aSChris Mason };
17485d4e461SChris Mason 
17585d4e461SChris Mason void __init btrfs_init_lockdep(void)
17685d4e461SChris Mason {
17785d4e461SChris Mason 	int i, j;
17885d4e461SChris Mason 
17985d4e461SChris Mason 	/* initialize lockdep class names */
18085d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
18185d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
18285d4e461SChris Mason 
18385d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
18485d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
18585d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
18685d4e461SChris Mason 	}
18785d4e461SChris Mason }
18885d4e461SChris Mason 
18985d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
19085d4e461SChris Mason 				    int level)
19185d4e461SChris Mason {
19285d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19385d4e461SChris Mason 
19485d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19585d4e461SChris Mason 
19685d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19785d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19885d4e461SChris Mason 		if (ks->id == objectid)
19985d4e461SChris Mason 			break;
20085d4e461SChris Mason 
20185d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20285d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20385d4e461SChris Mason }
20485d4e461SChris Mason 
2054008c04aSChris Mason #endif
2064008c04aSChris Mason 
207d352ac68SChris Mason /*
208d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
209d352ac68SChris Mason  * that covers the entire device
210d352ac68SChris Mason  */
2116af49dbdSDavid Sterba struct extent_map *btree_get_extent(struct btrfs_inode *inode,
21239b07b5dSOmar Sandoval 				    struct page *page, size_t pg_offset,
21339b07b5dSOmar Sandoval 				    u64 start, u64 len)
2145f39d397SChris Mason {
215fc4f21b1SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
2165f39d397SChris Mason 	struct extent_map *em;
2175f39d397SChris Mason 	int ret;
2185f39d397SChris Mason 
219890871beSChris Mason 	read_lock(&em_tree->lock);
220d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
221a061fc8dSChris Mason 	if (em) {
222890871beSChris Mason 		read_unlock(&em_tree->lock);
2235f39d397SChris Mason 		goto out;
224a061fc8dSChris Mason 	}
225890871beSChris Mason 	read_unlock(&em_tree->lock);
2267b13b7b1SChris Mason 
227172ddd60SDavid Sterba 	em = alloc_extent_map();
2285f39d397SChris Mason 	if (!em) {
2295f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2305f39d397SChris Mason 		goto out;
2315f39d397SChris Mason 	}
2325f39d397SChris Mason 	em->start = 0;
2330afbaf8cSChris Mason 	em->len = (u64)-1;
234c8b97818SChris Mason 	em->block_len = (u64)-1;
2355f39d397SChris Mason 	em->block_start = 0;
236d1310b2eSChris Mason 
237890871beSChris Mason 	write_lock(&em_tree->lock);
23809a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2395f39d397SChris Mason 	if (ret == -EEXIST) {
2405f39d397SChris Mason 		free_extent_map(em);
2417b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
242b4f359abSTsutomu Itoh 		if (!em)
2430433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2445f39d397SChris Mason 	} else if (ret) {
2457b13b7b1SChris Mason 		free_extent_map(em);
2460433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2475f39d397SChris Mason 	}
248890871beSChris Mason 	write_unlock(&em_tree->lock);
2497b13b7b1SChris Mason 
2505f39d397SChris Mason out:
2515f39d397SChris Mason 	return em;
2525f39d397SChris Mason }
2535f39d397SChris Mason 
254d352ac68SChris Mason /*
2552996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
256d352ac68SChris Mason  */
257c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
25819c00ddcSChris Mason {
259d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
260e9be5a30SDavid Sterba 	const int num_pages = fs_info->nodesize >> PAGE_SHIFT;
261d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
26219c00ddcSChris Mason 	char *kaddr;
263e9be5a30SDavid Sterba 	int i;
264d5178578SJohannes Thumshirn 
265d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
266d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
267e9be5a30SDavid Sterba 	kaddr = page_address(buf->pages[0]);
268e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
269e9be5a30SDavid Sterba 			    PAGE_SIZE - BTRFS_CSUM_SIZE);
27019c00ddcSChris Mason 
271e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
272e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
273e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
27419c00ddcSChris Mason 	}
27571a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
276d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
27719c00ddcSChris Mason }
27819c00ddcSChris Mason 
279d352ac68SChris Mason /*
280d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
281d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
282d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
283d352ac68SChris Mason  * in the wrong place.
284d352ac68SChris Mason  */
2851259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
286b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
287b9fab919SChris Mason 				 int atomic)
2881259ab75SChris Mason {
2892ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2901259ab75SChris Mason 	int ret;
2912755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
2921259ab75SChris Mason 
2931259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
2941259ab75SChris Mason 		return 0;
2951259ab75SChris Mason 
296b9fab919SChris Mason 	if (atomic)
297b9fab919SChris Mason 		return -EAGAIN;
298b9fab919SChris Mason 
299a26e8c9fSJosef Bacik 	if (need_lock) {
300a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
301300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb);
302a26e8c9fSJosef Bacik 	}
303a26e8c9fSJosef Bacik 
3042ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
305ff13db41SDavid Sterba 			 &cached_state);
3060b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3071259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3081259ab75SChris Mason 		ret = 0;
3091259ab75SChris Mason 		goto out;
3101259ab75SChris Mason 	}
31194647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
31294647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
31394647322SDavid Sterba 			eb->start,
31429549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3151259ab75SChris Mason 	ret = 1;
316a26e8c9fSJosef Bacik 
317a26e8c9fSJosef Bacik 	/*
318a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
319a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
32001327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
321a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
322a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
323a26e8c9fSJosef Bacik 	 * making everybody very sad.
324a26e8c9fSJosef Bacik 	 */
325a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3260b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
32733958dc6SChris Mason out:
3282ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
329e43bbe5eSDavid Sterba 			     &cached_state);
330472b909fSJosef Bacik 	if (need_lock)
331a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3321259ab75SChris Mason 	return ret;
3331259ab75SChris Mason }
3341259ab75SChris Mason 
335e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
336e7e16f48SJohannes Thumshirn {
337e7e16f48SJohannes Thumshirn 	switch (csum_type) {
338e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
3393951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
3403831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
341352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
342e7e16f48SJohannes Thumshirn 		return true;
343e7e16f48SJohannes Thumshirn 	default:
344e7e16f48SJohannes Thumshirn 		return false;
345e7e16f48SJohannes Thumshirn 	}
346e7e16f48SJohannes Thumshirn }
347e7e16f48SJohannes Thumshirn 
348d352ac68SChris Mason /*
3491104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3501104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3511104a885SDavid Sterba  */
352ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
353ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
3541104a885SDavid Sterba {
3551104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3561104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
35751bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
358d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
359d5178578SJohannes Thumshirn 
360d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3611104a885SDavid Sterba 
3621104a885SDavid Sterba 	/*
3631104a885SDavid Sterba 	 * The super_block structure does not span the whole
36451bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
36551bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3661104a885SDavid Sterba 	 */
367fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
368fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3691104a885SDavid Sterba 
37051bce6c9SJohannes Thumshirn 	if (memcmp(disk_sb->csum, result, btrfs_super_csum_size(disk_sb)))
371e7e16f48SJohannes Thumshirn 		return 1;
3721104a885SDavid Sterba 
373e7e16f48SJohannes Thumshirn 	return 0;
3741104a885SDavid Sterba }
3751104a885SDavid Sterba 
376e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
377ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
378581c1760SQu Wenruo {
379e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
380581c1760SQu Wenruo 	int found_level;
381581c1760SQu Wenruo 	struct btrfs_key found_key;
382581c1760SQu Wenruo 	int ret;
383581c1760SQu Wenruo 
384581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
385581c1760SQu Wenruo 	if (found_level != level) {
38663489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
38763489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
388581c1760SQu Wenruo 		btrfs_err(fs_info,
389581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
390581c1760SQu Wenruo 			  eb->start, level, found_level);
391581c1760SQu Wenruo 		return -EIO;
392581c1760SQu Wenruo 	}
393581c1760SQu Wenruo 
394581c1760SQu Wenruo 	if (!first_key)
395581c1760SQu Wenruo 		return 0;
396581c1760SQu Wenruo 
3975d41be6fSQu Wenruo 	/*
3985d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3995d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
4005d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
4015d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
4025d41be6fSQu Wenruo 	 */
4035d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
4045d41be6fSQu Wenruo 		return 0;
40562fdaa52SQu Wenruo 
40662fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
40762fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
40862fdaa52SQu Wenruo 		btrfs_err(fs_info,
40962fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
41062fdaa52SQu Wenruo 			  eb->start);
41162fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
41262fdaa52SQu Wenruo 		return -EUCLEAN;
41362fdaa52SQu Wenruo 	}
41462fdaa52SQu Wenruo 
415581c1760SQu Wenruo 	if (found_level)
416581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
417581c1760SQu Wenruo 	else
418581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
419581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
420581c1760SQu Wenruo 
421581c1760SQu Wenruo 	if (ret) {
42263489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
42363489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
424581c1760SQu Wenruo 		btrfs_err(fs_info,
425ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
426ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
427ff76a864SLiu Bo 			  first_key->type, first_key->offset,
428ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
429ff76a864SLiu Bo 			  found_key.offset);
430581c1760SQu Wenruo 	}
431581c1760SQu Wenruo 	return ret;
432581c1760SQu Wenruo }
433581c1760SQu Wenruo 
4341104a885SDavid Sterba /*
435d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
436d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
437581c1760SQu Wenruo  *
438581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
439581c1760SQu Wenruo  * @level:		expected level, mandatory check
440581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
441d352ac68SChris Mason  */
4425ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
443581c1760SQu Wenruo 					  u64 parent_transid, int level,
444581c1760SQu Wenruo 					  struct btrfs_key *first_key)
445f188591eSChris Mason {
4465ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
447f188591eSChris Mason 	struct extent_io_tree *io_tree;
448ea466794SJosef Bacik 	int failed = 0;
449f188591eSChris Mason 	int ret;
450f188591eSChris Mason 	int num_copies = 0;
451f188591eSChris Mason 	int mirror_num = 0;
452ea466794SJosef Bacik 	int failed_mirror = 0;
453f188591eSChris Mason 
4540b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
455f188591eSChris Mason 	while (1) {
456f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
457c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
458256dd1bbSStefan Behrens 		if (!ret) {
459581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
460b9fab919SChris Mason 						   parent_transid, 0))
461256dd1bbSStefan Behrens 				ret = -EIO;
462e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
463ff76a864SLiu Bo 						first_key, parent_transid))
464581c1760SQu Wenruo 				ret = -EUCLEAN;
465581c1760SQu Wenruo 			else
466581c1760SQu Wenruo 				break;
467256dd1bbSStefan Behrens 		}
468d397712bSChris Mason 
4690b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
470f188591eSChris Mason 					      eb->start, eb->len);
4714235298eSChris Mason 		if (num_copies == 1)
472ea466794SJosef Bacik 			break;
4734235298eSChris Mason 
4745cf1ab56SJosef Bacik 		if (!failed_mirror) {
4755cf1ab56SJosef Bacik 			failed = 1;
4765cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4775cf1ab56SJosef Bacik 		}
4785cf1ab56SJosef Bacik 
479f188591eSChris Mason 		mirror_num++;
480ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
481ea466794SJosef Bacik 			mirror_num++;
482ea466794SJosef Bacik 
4834235298eSChris Mason 		if (mirror_num > num_copies)
484ea466794SJosef Bacik 			break;
485f188591eSChris Mason 	}
486ea466794SJosef Bacik 
487c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
48820a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
489ea466794SJosef Bacik 
490ea466794SJosef Bacik 	return ret;
491f188591eSChris Mason }
49219c00ddcSChris Mason 
493d352ac68SChris Mason /*
494d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
495d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
496d352ac68SChris Mason  */
497d397712bSChris Mason 
49801d58472SDaniel Dressler static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
49919c00ddcSChris Mason {
5004eee4fa4SMiao Xie 	u64 start = page_offset(page);
50119c00ddcSChris Mason 	u64 found_start;
5022996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
5032996e1f8SJohannes Thumshirn 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
50419c00ddcSChris Mason 	struct extent_buffer *eb;
5058d47a0d8SQu Wenruo 	int ret;
506f188591eSChris Mason 
5074f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5084f2de97aSJosef Bacik 	if (page != eb->pages[0])
5094f2de97aSJosef Bacik 		return 0;
5100f805531SAlex Lyakas 
51119c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
5120f805531SAlex Lyakas 	/*
5130f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5140f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5150f805531SAlex Lyakas 	 */
5160f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5170f805531SAlex Lyakas 		return -EUCLEAN;
5180f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5190f805531SAlex Lyakas 		return -EUCLEAN;
5200f805531SAlex Lyakas 
521de37aa51SNikolay Borisov 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
5229a8658e3SDavid Sterba 				    offsetof(struct btrfs_header, fsid),
5239a8658e3SDavid Sterba 				    BTRFS_FSID_SIZE) == 0);
5240f805531SAlex Lyakas 
525c67b3892SDavid Sterba 	csum_tree_block(eb, result);
5262996e1f8SJohannes Thumshirn 
5278d47a0d8SQu Wenruo 	if (btrfs_header_level(eb))
5288d47a0d8SQu Wenruo 		ret = btrfs_check_node(eb);
5298d47a0d8SQu Wenruo 	else
5308d47a0d8SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
5318d47a0d8SQu Wenruo 
5328d47a0d8SQu Wenruo 	if (ret < 0) {
533c06631b0SQu Wenruo 		btrfs_print_tree(eb, 0);
5348d47a0d8SQu Wenruo 		btrfs_err(fs_info,
5358d47a0d8SQu Wenruo 		"block=%llu write time tree block corruption detected",
5368d47a0d8SQu Wenruo 			  eb->start);
537c06631b0SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5388d47a0d8SQu Wenruo 		return ret;
5398d47a0d8SQu Wenruo 	}
5402996e1f8SJohannes Thumshirn 	write_extent_buffer(eb, result, 0, csum_size);
5418d47a0d8SQu Wenruo 
5422996e1f8SJohannes Thumshirn 	return 0;
54319c00ddcSChris Mason }
54419c00ddcSChris Mason 
545b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5462b82032cSYan Zheng {
547b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
54801d58472SDaniel Dressler 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
54944880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
5502b82032cSYan Zheng 	int ret = 1;
5512b82032cSYan Zheng 
5529a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5539a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5542b82032cSYan Zheng 	while (fs_devices) {
5557239ff4bSNikolay Borisov 		u8 *metadata_uuid;
5567239ff4bSNikolay Borisov 
5577239ff4bSNikolay Borisov 		/*
5587239ff4bSNikolay Borisov 		 * Checking the incompat flag is only valid for the current
5597239ff4bSNikolay Borisov 		 * fs. For seed devices it's forbidden to have their uuid
5607239ff4bSNikolay Borisov 		 * changed so reading ->fsid in this case is fine
5617239ff4bSNikolay Borisov 		 */
5627239ff4bSNikolay Borisov 		if (fs_devices == fs_info->fs_devices &&
5637239ff4bSNikolay Borisov 		    btrfs_fs_incompat(fs_info, METADATA_UUID))
5647239ff4bSNikolay Borisov 			metadata_uuid = fs_devices->metadata_uuid;
5657239ff4bSNikolay Borisov 		else
5667239ff4bSNikolay Borisov 			metadata_uuid = fs_devices->fsid;
5677239ff4bSNikolay Borisov 
5687239ff4bSNikolay Borisov 		if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE)) {
5692b82032cSYan Zheng 			ret = 0;
5702b82032cSYan Zheng 			break;
5712b82032cSYan Zheng 		}
5722b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5732b82032cSYan Zheng 	}
5742b82032cSYan Zheng 	return ret;
5752b82032cSYan Zheng }
5762b82032cSYan Zheng 
577facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
578facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
579facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
580ce9adaa5SChris Mason {
581ce9adaa5SChris Mason 	u64 found_start;
582ce9adaa5SChris Mason 	int found_level;
583ce9adaa5SChris Mason 	struct extent_buffer *eb;
58415b6e8a8SDavid Sterba 	struct btrfs_fs_info *fs_info;
58515b6e8a8SDavid Sterba 	u16 csum_size;
586f188591eSChris Mason 	int ret = 0;
5872996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
588727011e0SChris Mason 	int reads_done;
589ce9adaa5SChris Mason 
590ce9adaa5SChris Mason 	if (!page->private)
591ce9adaa5SChris Mason 		goto out;
592d397712bSChris Mason 
5934f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
59415b6e8a8SDavid Sterba 	fs_info = eb->fs_info;
59515b6e8a8SDavid Sterba 	csum_size = btrfs_super_csum_size(fs_info->super_copy);
596d397712bSChris Mason 
5970b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
5980b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
5990b32f4bbSJosef Bacik 	 */
60067439dadSDavid Sterba 	atomic_inc(&eb->refs);
6010b32f4bbSJosef Bacik 
6020b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
603727011e0SChris Mason 	if (!reads_done)
604727011e0SChris Mason 		goto err;
605f188591eSChris Mason 
6065cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
607656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
608ea466794SJosef Bacik 		ret = -EIO;
609ea466794SJosef Bacik 		goto err;
610ea466794SJosef Bacik 	}
611ea466794SJosef Bacik 
612ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
613727011e0SChris Mason 	if (found_start != eb->start) {
614893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
615893bf4b1SSu Yue 			     eb->start, found_start);
616f188591eSChris Mason 		ret = -EIO;
617ce9adaa5SChris Mason 		goto err;
618ce9adaa5SChris Mason 	}
619b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
62002873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
62194647322SDavid Sterba 			     eb->start);
6221259ab75SChris Mason 		ret = -EIO;
6231259ab75SChris Mason 		goto err;
6241259ab75SChris Mason 	}
625ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6261c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
627893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
628893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
6291c24c3ceSJosef Bacik 		ret = -EIO;
6301c24c3ceSJosef Bacik 		goto err;
6311c24c3ceSJosef Bacik 	}
632ce9adaa5SChris Mason 
63385d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
63485d4e461SChris Mason 				       eb, found_level);
6354008c04aSChris Mason 
636c67b3892SDavid Sterba 	csum_tree_block(eb, result);
637a826d6dcSJosef Bacik 
6382996e1f8SJohannes Thumshirn 	if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
6392996e1f8SJohannes Thumshirn 		u32 val;
6402996e1f8SJohannes Thumshirn 		u32 found = 0;
6412996e1f8SJohannes Thumshirn 
6422996e1f8SJohannes Thumshirn 		memcpy(&found, result, csum_size);
6432996e1f8SJohannes Thumshirn 
6442996e1f8SJohannes Thumshirn 		read_extent_buffer(eb, &val, 0, csum_size);
6452996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
6462996e1f8SJohannes Thumshirn 		"%s checksum verify failed on %llu wanted %x found %x level %d",
6472996e1f8SJohannes Thumshirn 			      fs_info->sb->s_id, eb->start,
6482996e1f8SJohannes Thumshirn 			      val, found, btrfs_header_level(eb));
6492996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
6502996e1f8SJohannes Thumshirn 		goto err;
6512996e1f8SJohannes Thumshirn 	}
6522996e1f8SJohannes Thumshirn 
653a826d6dcSJosef Bacik 	/*
654a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
655a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
656a826d6dcSJosef Bacik 	 * return -EIO.
657a826d6dcSJosef Bacik 	 */
6581c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
659a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
660a826d6dcSJosef Bacik 		ret = -EIO;
661a826d6dcSJosef Bacik 	}
662ce9adaa5SChris Mason 
663813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
664053ab70fSLiu Bo 		ret = -EIO;
665053ab70fSLiu Bo 
6660b32f4bbSJosef Bacik 	if (!ret)
6670b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
66875391f0dSQu Wenruo 	else
66975391f0dSQu Wenruo 		btrfs_err(fs_info,
67075391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
67175391f0dSQu Wenruo 			  eb->start);
672ce9adaa5SChris Mason err:
67379fb65a1SJosef Bacik 	if (reads_done &&
67479fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
675d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6764bb31e92SArne Jansen 
67753b381b3SDavid Woodhouse 	if (ret) {
67853b381b3SDavid Woodhouse 		/*
67953b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
68053b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
68153b381b3SDavid Woodhouse 		 * to decrement
68253b381b3SDavid Woodhouse 		 */
68353b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6840b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
68553b381b3SDavid Woodhouse 	}
6860b32f4bbSJosef Bacik 	free_extent_buffer(eb);
687ce9adaa5SChris Mason out:
688f188591eSChris Mason 	return ret;
689ce9adaa5SChris Mason }
690ce9adaa5SChris Mason 
6914246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
692ce9adaa5SChris Mason {
69397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
694ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6959e0af237SLiu Bo 	struct btrfs_workqueue *wq;
696ce9adaa5SChris Mason 
697ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
6984e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
699d20f7043SChris Mason 
70037226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
701a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7029e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
703a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7049e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
705a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7069e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
707a0cac0ecSOmar Sandoval 		else
7089e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7099e0af237SLiu Bo 	} else {
7105c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7119e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
712a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7139e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
714a0cac0ecSOmar Sandoval 		else
7159e0af237SLiu Bo 			wq = fs_info->endio_workers;
7169e0af237SLiu Bo 	}
7179e0af237SLiu Bo 
718a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7199e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
720ce9adaa5SChris Mason }
721ce9adaa5SChris Mason 
7224e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
723bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7240b86a832SChris Mason {
72597eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7268b110e39SMiao Xie 
72797eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
728ce9adaa5SChris Mason 	if (!end_io_wq)
7294e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
730ce9adaa5SChris Mason 
731ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
732ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
73322c59948SChris Mason 	end_io_wq->info = info;
7344e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
735ce9adaa5SChris Mason 	end_io_wq->bio = bio;
73622c59948SChris Mason 	end_io_wq->metadata = metadata;
737ce9adaa5SChris Mason 
738ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
739ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
74022c59948SChris Mason 	return 0;
74122c59948SChris Mason }
74222c59948SChris Mason 
7434a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7444a69a410SChris Mason {
7454a69a410SChris Mason 	struct async_submit_bio *async;
7464e4cbee9SChristoph Hellwig 	blk_status_t ret;
7474a69a410SChris Mason 
7484a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
749c6100a4bSJosef Bacik 	ret = async->submit_bio_start(async->private_data, async->bio,
750eaf25d93SChris Mason 				      async->bio_offset);
75179787eaaSJeff Mahoney 	if (ret)
7524e4cbee9SChristoph Hellwig 		async->status = ret;
7534a69a410SChris Mason }
7544a69a410SChris Mason 
75506ea01b1SDavid Sterba /*
75606ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
75706ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
75806ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
75906ea01b1SDavid Sterba  *
76006ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
76106ea01b1SDavid Sterba  * inserted into the tree.
76206ea01b1SDavid Sterba  */
7634a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7648b712842SChris Mason {
7658b712842SChris Mason 	struct async_submit_bio *async;
76606ea01b1SDavid Sterba 	struct inode *inode;
76706ea01b1SDavid Sterba 	blk_status_t ret;
7688b712842SChris Mason 
7698b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
77006ea01b1SDavid Sterba 	inode = async->private_data;
7714854ddd0SChris Mason 
772bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7734e4cbee9SChristoph Hellwig 	if (async->status) {
7744e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7754246a0b6SChristoph Hellwig 		bio_endio(async->bio);
77679787eaaSJeff Mahoney 		return;
77779787eaaSJeff Mahoney 	}
77879787eaaSJeff Mahoney 
779ec39f769SChris Mason 	/*
780ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
781ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
782ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
783ec39f769SChris Mason 	 */
784ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
78508635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
78606ea01b1SDavid Sterba 	if (ret) {
78706ea01b1SDavid Sterba 		async->bio->bi_status = ret;
78806ea01b1SDavid Sterba 		bio_endio(async->bio);
78906ea01b1SDavid Sterba 	}
7904a69a410SChris Mason }
7914a69a410SChris Mason 
7924a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7934a69a410SChris Mason {
7944a69a410SChris Mason 	struct async_submit_bio *async;
7954a69a410SChris Mason 
7964a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7978b712842SChris Mason 	kfree(async);
7988b712842SChris Mason }
7998b712842SChris Mason 
8008c27cb35SLinus Torvalds blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
801c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
802c6100a4bSJosef Bacik 				 u64 bio_offset, void *private_data,
803e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
80444b8bd7eSChris Mason {
80544b8bd7eSChris Mason 	struct async_submit_bio *async;
80644b8bd7eSChris Mason 
80744b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
80844b8bd7eSChris Mason 	if (!async)
8094e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
81044b8bd7eSChris Mason 
811c6100a4bSJosef Bacik 	async->private_data = private_data;
81244b8bd7eSChris Mason 	async->bio = bio;
81344b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8144a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8154a69a410SChris Mason 
816a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
817a0cac0ecSOmar Sandoval 			run_one_async_free);
8184a69a410SChris Mason 
819eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8208c8bee1dSChris Mason 
8214e4cbee9SChristoph Hellwig 	async->status = 0;
82279787eaaSJeff Mahoney 
82367f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8245cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
825d313d7a3SChris Mason 
8265cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
82744b8bd7eSChris Mason 	return 0;
82844b8bd7eSChris Mason }
82944b8bd7eSChris Mason 
8304e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
831ce3ed71aSChris Mason {
8322c30c71bSKent Overstreet 	struct bio_vec *bvec;
833ce3ed71aSChris Mason 	struct btrfs_root *root;
8342b070cfeSChristoph Hellwig 	int ret = 0;
8356dc4f100SMing Lei 	struct bvec_iter_all iter_all;
836ce3ed71aSChris Mason 
837c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8382b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
839ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
84001d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
84179787eaaSJeff Mahoney 		if (ret)
84279787eaaSJeff Mahoney 			break;
843ce3ed71aSChris Mason 	}
8442c30c71bSKent Overstreet 
8454e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
846ce3ed71aSChris Mason }
847ce3ed71aSChris Mason 
848d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
849eaf25d93SChris Mason 					     u64 bio_offset)
85022c59948SChris Mason {
8518b712842SChris Mason 	/*
8528b712842SChris Mason 	 * when we're called for a write, we're already in the async
8535443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8548b712842SChris Mason 	 */
85579787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
85622c59948SChris Mason }
85722c59948SChris Mason 
8589b4e675aSDavid Sterba static int check_async_write(struct btrfs_fs_info *fs_info,
8599b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
860de0022b9SJosef Bacik {
8616300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8626300463bSLiu Bo 		return 0;
8639b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
864de0022b9SJosef Bacik 		return 0;
865de0022b9SJosef Bacik 	return 1;
866de0022b9SJosef Bacik }
867de0022b9SJosef Bacik 
868a56b1c7bSNikolay Borisov static blk_status_t btree_submit_bio_hook(struct inode *inode, struct bio *bio,
86950489a57SNikolay Borisov 					  int mirror_num,
87050489a57SNikolay Borisov 					  unsigned long bio_flags)
87144b8bd7eSChris Mason {
8720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8739b4e675aSDavid Sterba 	int async = check_async_write(fs_info, BTRFS_I(inode));
8744e4cbee9SChristoph Hellwig 	blk_status_t ret;
875cad321adSChris Mason 
87637226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
877cad321adSChris Mason 		/*
878cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
879cad321adSChris Mason 		 * can happen in the async kernel threads
880cad321adSChris Mason 		 */
8810b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8820b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8831d4284bdSChris Mason 		if (ret)
88461891923SStefan Behrens 			goto out_w_error;
88508635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
886de0022b9SJosef Bacik 	} else if (!async) {
887de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
888de0022b9SJosef Bacik 		if (ret)
88961891923SStefan Behrens 			goto out_w_error;
89008635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
89161891923SStefan Behrens 	} else {
892cad321adSChris Mason 		/*
89361891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
89461891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
895cad321adSChris Mason 		 */
896c6100a4bSJosef Bacik 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
897e68f2ee7SNikolay Borisov 					  0, inode, btree_submit_bio_start);
89844b8bd7eSChris Mason 	}
89944b8bd7eSChris Mason 
9004246a0b6SChristoph Hellwig 	if (ret)
9014246a0b6SChristoph Hellwig 		goto out_w_error;
9024246a0b6SChristoph Hellwig 	return 0;
9034246a0b6SChristoph Hellwig 
90461891923SStefan Behrens out_w_error:
9054e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9064246a0b6SChristoph Hellwig 	bio_endio(bio);
90761891923SStefan Behrens 	return ret;
90861891923SStefan Behrens }
90961891923SStefan Behrens 
9103dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
911784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
912a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
913a6bc32b8SMel Gorman 			enum migrate_mode mode)
914784b4e29SChris Mason {
915784b4e29SChris Mason 	/*
916784b4e29SChris Mason 	 * we can't safely write a btree page from here,
917784b4e29SChris Mason 	 * we haven't done the locking hook
918784b4e29SChris Mason 	 */
919784b4e29SChris Mason 	if (PageDirty(page))
920784b4e29SChris Mason 		return -EAGAIN;
921784b4e29SChris Mason 	/*
922784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
923784b4e29SChris Mason 	 * We must have no buffers or drop them.
924784b4e29SChris Mason 	 */
925784b4e29SChris Mason 	if (page_has_private(page) &&
926784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
927784b4e29SChris Mason 		return -EAGAIN;
928a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
929784b4e29SChris Mason }
9303dd1462eSJan Beulich #endif
931784b4e29SChris Mason 
9320da5468fSChris Mason 
9330da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9340da5468fSChris Mason 			    struct writeback_control *wbc)
9350da5468fSChris Mason {
936e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
937e2d84521SMiao Xie 	int ret;
938e2d84521SMiao Xie 
939d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
940448d640bSChris Mason 
941448d640bSChris Mason 		if (wbc->for_kupdate)
942448d640bSChris Mason 			return 0;
943448d640bSChris Mason 
944e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
945b9473439SChris Mason 		/* this is a bit racy, but that's ok */
946d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
947d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
948d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
949e2d84521SMiao Xie 		if (ret < 0)
950793955bcSChris Mason 			return 0;
951793955bcSChris Mason 	}
9520b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9530da5468fSChris Mason }
9540da5468fSChris Mason 
955b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9565f39d397SChris Mason {
95771ad38b4SDavid Sterba 	return extent_read_full_page(page, btree_get_extent, 0);
9585f39d397SChris Mason }
9595f39d397SChris Mason 
96070dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9615f39d397SChris Mason {
96298509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
96398509cfcSChris Mason 		return 0;
9640c4e538bSDavid Sterba 
965f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
966d98237b3SChris Mason }
967d98237b3SChris Mason 
968d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
969d47992f8SLukas Czerner 				 unsigned int length)
970d98237b3SChris Mason {
971d1310b2eSChris Mason 	struct extent_io_tree *tree;
972d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9735f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9745f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9759ad6b7bcSChris Mason 	if (PagePrivate(page)) {
976efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
977efe120a0SFrank Holton 			   "page private not zero on page %llu",
978efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
9799ad6b7bcSChris Mason 		ClearPagePrivate(page);
9809ad6b7bcSChris Mason 		set_page_private(page, 0);
98109cbfeafSKirill A. Shutemov 		put_page(page);
9829ad6b7bcSChris Mason 	}
983d98237b3SChris Mason }
984d98237b3SChris Mason 
9850b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9860b32f4bbSJosef Bacik {
987bb146eb2SJosef Bacik #ifdef DEBUG
9880b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9890b32f4bbSJosef Bacik 
9900b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9910b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9920b32f4bbSJosef Bacik 	BUG_ON(!eb);
9930b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9940b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
9950b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
996bb146eb2SJosef Bacik #endif
9970b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
9980b32f4bbSJosef Bacik }
9990b32f4bbSJosef Bacik 
10007f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
1001d98237b3SChris Mason 	.readpage	= btree_readpage,
10020da5468fSChris Mason 	.writepages	= btree_writepages,
10035f39d397SChris Mason 	.releasepage	= btree_releasepage,
10045f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10055a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1006784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10075a92bc88SChris Mason #endif
10080b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1009d98237b3SChris Mason };
1010123abc88SChris Mason 
10112ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1012090d1875SChris Mason {
10135f39d397SChris Mason 	struct extent_buffer *buf = NULL;
1014537f38f0SNikolay Borisov 	int ret;
1015090d1875SChris Mason 
10162ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1017c871b0f2SLiu Bo 	if (IS_ERR(buf))
10186197d86eSDavid Sterba 		return;
1019537f38f0SNikolay Borisov 
1020c2ccfbc6SNikolay Borisov 	ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
1021537f38f0SNikolay Borisov 	if (ret < 0)
1022537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
1023537f38f0SNikolay Borisov 	else
10245f39d397SChris Mason 		free_extent_buffer(buf);
1025090d1875SChris Mason }
1026090d1875SChris Mason 
10272ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10282ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10290308af44SDavid Sterba 						u64 bytenr)
10300999df54SChris Mason {
10310b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10320b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10330b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
10340999df54SChris Mason }
10350999df54SChris Mason 
1036581c1760SQu Wenruo /*
1037581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1038581c1760SQu Wenruo  * verification.
1039581c1760SQu Wenruo  *
1040581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1041581c1760SQu Wenruo  * @level:		expected level, mandatory check
1042581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1043581c1760SQu Wenruo  */
10442ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1045581c1760SQu Wenruo 				      u64 parent_transid, int level,
1046581c1760SQu Wenruo 				      struct btrfs_key *first_key)
1047e20d96d6SChris Mason {
10485f39d397SChris Mason 	struct extent_buffer *buf = NULL;
104919c00ddcSChris Mason 	int ret;
105019c00ddcSChris Mason 
10512ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1052c871b0f2SLiu Bo 	if (IS_ERR(buf))
1053c871b0f2SLiu Bo 		return buf;
1054e4204dedSChris Mason 
10555ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1056581c1760SQu Wenruo 					     level, first_key);
10570f0fe8f7SFilipe David Borba Manana 	if (ret) {
1058537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
105964c043deSLiu Bo 		return ERR_PTR(ret);
10600f0fe8f7SFilipe David Borba Manana 	}
10615f39d397SChris Mason 	return buf;
1062ce9adaa5SChris Mason 
1063eb60ceacSChris Mason }
1064eb60ceacSChris Mason 
10656a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1066ed2ff2cbSChris Mason {
10676a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
106855c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1069e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1070b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1071b4ce94deSChris Mason 
1072b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1073104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1074e2d84521SMiao Xie 						 -buf->len,
1075e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
1076b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
10778bead258SDavid Sterba 			btrfs_set_lock_blocking_write(buf);
10780b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1079925baeddSChris Mason 		}
10805f39d397SChris Mason 	}
1081ed7b63ebSJosef Bacik }
10825f39d397SChris Mason 
1083da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1084e20d96d6SChris Mason 			 u64 objectid)
1085d97e63b6SChris Mason {
10867c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
108796dfcb46SJosef Bacik 	root->fs_info = fs_info;
1088cfaa7295SChris Mason 	root->node = NULL;
1089a28ec197SChris Mason 	root->commit_root = NULL;
109027cdeb70SMiao Xie 	root->state = 0;
1091d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
10920b86a832SChris Mason 
10930f7d52f4SChris Mason 	root->last_trans = 0;
109413a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1095eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1096199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
10976bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
109816cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1099f0486c68SYan, Zheng 	root->block_rsv = NULL;
11000b86a832SChris Mason 
11010b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11025d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1103eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1104eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1105199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1106199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1107d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11082ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11092ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11105d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1111eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1112199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1113f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11142ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11152ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11168287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1117a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1118e02119d5SChris Mason 	mutex_init(&root->log_mutex);
111931f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1120573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
11217237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11227237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11237237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11248b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11258b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11267237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11277237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11287237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11292ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11300700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11318ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1132eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11337237f183SYan Zheng 	root->log_transid = 0;
1134d1433debSMiao Xie 	root->log_transid_committed = -1;
1135257c62e1SChris Mason 	root->last_log_commit = 0;
11367c0260eeSJeff Mahoney 	if (!dummy)
113743eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
113843eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1139017e5369SChris Mason 
11403768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11413768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11426702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
11437c0260eeSJeff Mahoney 	if (!dummy)
11443f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
114506ea65a3SJosef Bacik 	else
114606ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
11474d775673SChris Mason 	root->root_key.objectid = objectid;
11480ee5dc67SAl Viro 	root->anon_dev = 0;
11498ea05e3aSAlexander Block 
11505f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1151370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1152bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1153bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1154bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1155bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1156bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1157bd647ce3SJosef Bacik #endif
11583768f368SChris Mason }
11593768f368SChris Mason 
116074e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
116196dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
11626f07e42eSAl Viro {
116374e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
11646f07e42eSAl Viro 	if (root)
116596dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
11666f07e42eSAl Viro 	return root;
11676f07e42eSAl Viro }
11686f07e42eSAl Viro 
116906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
117006ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1171da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
117206ea65a3SJosef Bacik {
117306ea65a3SJosef Bacik 	struct btrfs_root *root;
117406ea65a3SJosef Bacik 
11757c0260eeSJeff Mahoney 	if (!fs_info)
11767c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
11777c0260eeSJeff Mahoney 
117896dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
117906ea65a3SJosef Bacik 	if (!root)
118006ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1181da17066cSJeff Mahoney 
1182b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1183faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
118406ea65a3SJosef Bacik 
118506ea65a3SJosef Bacik 	return root;
118606ea65a3SJosef Bacik }
118706ea65a3SJosef Bacik #endif
118806ea65a3SJosef Bacik 
118920897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
119020897f5cSArne Jansen 				     u64 objectid)
119120897f5cSArne Jansen {
11929b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
119320897f5cSArne Jansen 	struct extent_buffer *leaf;
119420897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
119520897f5cSArne Jansen 	struct btrfs_root *root;
119620897f5cSArne Jansen 	struct btrfs_key key;
1197b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
119820897f5cSArne Jansen 	int ret = 0;
119920897f5cSArne Jansen 
1200b89f6d1fSFilipe Manana 	/*
1201b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1202b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1203b89f6d1fSFilipe Manana 	 */
1204b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
120596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1206b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
120720897f5cSArne Jansen 	if (!root)
120820897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
120920897f5cSArne Jansen 
121020897f5cSArne Jansen 	root->root_key.objectid = objectid;
121120897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
121220897f5cSArne Jansen 	root->root_key.offset = 0;
121320897f5cSArne Jansen 
12144d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
121520897f5cSArne Jansen 	if (IS_ERR(leaf)) {
121620897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12171dd05682STsutomu Itoh 		leaf = NULL;
121820897f5cSArne Jansen 		goto fail;
121920897f5cSArne Jansen 	}
122020897f5cSArne Jansen 
122120897f5cSArne Jansen 	root->node = leaf;
122220897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
122320897f5cSArne Jansen 
122420897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
122527cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
122620897f5cSArne Jansen 
122720897f5cSArne Jansen 	root->root_item.flags = 0;
122820897f5cSArne Jansen 	root->root_item.byte_limit = 0;
122920897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
123020897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
123120897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
123220897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
123320897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
123420897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
123520897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
123633d85fdaSQu Wenruo 	if (is_fstree(objectid))
1237807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1238807fc790SAndy Shevchenko 	else
1239807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
124020897f5cSArne Jansen 	root->root_item.drop_level = 0;
124120897f5cSArne Jansen 
124220897f5cSArne Jansen 	key.objectid = objectid;
124320897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
124420897f5cSArne Jansen 	key.offset = 0;
124520897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
124620897f5cSArne Jansen 	if (ret)
124720897f5cSArne Jansen 		goto fail;
124820897f5cSArne Jansen 
124920897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
125020897f5cSArne Jansen 
125120897f5cSArne Jansen 	return root;
12521dd05682STsutomu Itoh 
12531dd05682STsutomu Itoh fail:
12548c38938cSJosef Bacik 	if (leaf)
12551dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
125600246528SJosef Bacik 	btrfs_put_root(root);
12571dd05682STsutomu Itoh 
12581dd05682STsutomu Itoh 	return ERR_PTR(ret);
125920897f5cSArne Jansen }
126020897f5cSArne Jansen 
12617237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1262e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
12630f7d52f4SChris Mason {
12640f7d52f4SChris Mason 	struct btrfs_root *root;
12657237f183SYan Zheng 	struct extent_buffer *leaf;
1266e02119d5SChris Mason 
126796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1268e02119d5SChris Mason 	if (!root)
12697237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1270e02119d5SChris Mason 
1271e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1272e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1273e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
127427cdeb70SMiao Xie 
12757237f183SYan Zheng 	/*
127627cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
127727cdeb70SMiao Xie 	 *
12787237f183SYan Zheng 	 * log trees do not get reference counted because they go away
12797237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
12807237f183SYan Zheng 	 * to file data extents, and those reference counts still get
12817237f183SYan Zheng 	 * updated (along with back refs to the log tree).
12827237f183SYan Zheng 	 */
1283e02119d5SChris Mason 
12844d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12854d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
12867237f183SYan Zheng 	if (IS_ERR(leaf)) {
128700246528SJosef Bacik 		btrfs_put_root(root);
12887237f183SYan Zheng 		return ERR_CAST(leaf);
12897237f183SYan Zheng 	}
1290e02119d5SChris Mason 
12917237f183SYan Zheng 	root->node = leaf;
1292e02119d5SChris Mason 
1293e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1294e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12957237f183SYan Zheng 	return root;
12967237f183SYan Zheng }
12977237f183SYan Zheng 
12987237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
12997237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13007237f183SYan Zheng {
13017237f183SYan Zheng 	struct btrfs_root *log_root;
13027237f183SYan Zheng 
13037237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13047237f183SYan Zheng 	if (IS_ERR(log_root))
13057237f183SYan Zheng 		return PTR_ERR(log_root);
13067237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13077237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13087237f183SYan Zheng 	return 0;
13097237f183SYan Zheng }
13107237f183SYan Zheng 
13117237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13127237f183SYan Zheng 		       struct btrfs_root *root)
13137237f183SYan Zheng {
13140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13157237f183SYan Zheng 	struct btrfs_root *log_root;
13167237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13177237f183SYan Zheng 
13180b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13197237f183SYan Zheng 	if (IS_ERR(log_root))
13207237f183SYan Zheng 		return PTR_ERR(log_root);
13217237f183SYan Zheng 
13227237f183SYan Zheng 	log_root->last_trans = trans->transid;
13237237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13247237f183SYan Zheng 
13257237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13263cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13273cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13283cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1329da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13300b246afaSJeff Mahoney 				     fs_info->nodesize);
13313cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13327237f183SYan Zheng 
13335d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13347237f183SYan Zheng 
13357237f183SYan Zheng 	WARN_ON(root->log_root);
13367237f183SYan Zheng 	root->log_root = log_root;
13377237f183SYan Zheng 	root->log_transid = 0;
1338d1433debSMiao Xie 	root->log_transid_committed = -1;
1339257c62e1SChris Mason 	root->last_log_commit = 0;
1340e02119d5SChris Mason 	return 0;
1341e02119d5SChris Mason }
1342e02119d5SChris Mason 
134362a2c73eSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1344cb517eabSMiao Xie 					struct btrfs_key *key)
1345e02119d5SChris Mason {
1346e02119d5SChris Mason 	struct btrfs_root *root;
1347e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
13480f7d52f4SChris Mason 	struct btrfs_path *path;
134984234f3aSYan Zheng 	u64 generation;
1350cb517eabSMiao Xie 	int ret;
1351581c1760SQu Wenruo 	int level;
1352cb517eabSMiao Xie 
1353cb517eabSMiao Xie 	path = btrfs_alloc_path();
1354cb517eabSMiao Xie 	if (!path)
1355cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
13560f7d52f4SChris Mason 
135796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1358cb517eabSMiao Xie 	if (!root) {
1359cb517eabSMiao Xie 		ret = -ENOMEM;
1360cb517eabSMiao Xie 		goto alloc_fail;
13610f7d52f4SChris Mason 	}
13620f7d52f4SChris Mason 
1363cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1364cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
13650f7d52f4SChris Mason 	if (ret) {
136613a8a7c8SYan, Zheng 		if (ret > 0)
136713a8a7c8SYan, Zheng 			ret = -ENOENT;
1368cb517eabSMiao Xie 		goto find_fail;
13690f7d52f4SChris Mason 	}
137013a8a7c8SYan, Zheng 
137184234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1372581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
13732ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
13742ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1375581c1760SQu Wenruo 				     generation, level, NULL);
137664c043deSLiu Bo 	if (IS_ERR(root->node)) {
137764c043deSLiu Bo 		ret = PTR_ERR(root->node);
13788c38938cSJosef Bacik 		root->node = NULL;
1379cb517eabSMiao Xie 		goto find_fail;
1380cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1381cb517eabSMiao Xie 		ret = -EIO;
138264c043deSLiu Bo 		goto find_fail;
1383416bc658SJosef Bacik 	}
13845d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
138513a8a7c8SYan, Zheng out:
1386cb517eabSMiao Xie 	btrfs_free_path(path);
1387cb517eabSMiao Xie 	return root;
1388cb517eabSMiao Xie 
1389cb517eabSMiao Xie find_fail:
139000246528SJosef Bacik 	btrfs_put_root(root);
1391cb517eabSMiao Xie alloc_fail:
1392cb517eabSMiao Xie 	root = ERR_PTR(ret);
1393cb517eabSMiao Xie 	goto out;
1394cb517eabSMiao Xie }
1395cb517eabSMiao Xie 
1396a98db0f3SJosef Bacik static int btrfs_init_fs_root(struct btrfs_root *root)
1397cb517eabSMiao Xie {
1398cb517eabSMiao Xie 	int ret;
1399dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1400cb517eabSMiao Xie 
1401cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1402cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1403cb517eabSMiao Xie 					GFP_NOFS);
1404cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1405cb517eabSMiao Xie 		ret = -ENOMEM;
1406cb517eabSMiao Xie 		goto fail;
1407cb517eabSMiao Xie 	}
1408cb517eabSMiao Xie 
1409dcc3eb96SNikolay Borisov 	/*
1410dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1411dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1412dcc3eb96SNikolay Borisov 	 */
1413dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1414dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1415dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1416dcc3eb96SNikolay Borisov 	if (ret)
14178257b2dcSMiao Xie 		goto fail;
14188257b2dcSMiao Xie 
1419f39e4571SJosef Bacik 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1420f39e4571SJosef Bacik 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1421f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1422f39e4571SJosef Bacik 	}
1423f39e4571SJosef Bacik 
1424cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
142557cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
142657cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1427cb517eabSMiao Xie 
1428cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1429cb517eabSMiao Xie 	if (ret)
1430876d2cf1SLiu Bo 		goto fail;
1431f32e48e9SChandan Rajendra 
1432f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1433f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1434f32e48e9SChandan Rajendra 					&root->highest_objectid);
1435f32e48e9SChandan Rajendra 	if (ret) {
1436f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1437876d2cf1SLiu Bo 		goto fail;
1438f32e48e9SChandan Rajendra 	}
1439f32e48e9SChandan Rajendra 
1440f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1441f32e48e9SChandan Rajendra 
1442f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1443f32e48e9SChandan Rajendra 
1444cb517eabSMiao Xie 	return 0;
1445cb517eabSMiao Xie fail:
144684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1447cb517eabSMiao Xie 	return ret;
1448cb517eabSMiao Xie }
1449cb517eabSMiao Xie 
1450a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1451cb517eabSMiao Xie 					       u64 root_id)
1452cb517eabSMiao Xie {
1453cb517eabSMiao Xie 	struct btrfs_root *root;
1454cb517eabSMiao Xie 
1455cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1456cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1457cb517eabSMiao Xie 				 (unsigned long)root_id);
1458bc44d7c4SJosef Bacik 	if (root)
145900246528SJosef Bacik 		root = btrfs_grab_root(root);
1460cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1461cb517eabSMiao Xie 	return root;
1462cb517eabSMiao Xie }
1463cb517eabSMiao Xie 
1464cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1465cb517eabSMiao Xie 			 struct btrfs_root *root)
1466cb517eabSMiao Xie {
1467cb517eabSMiao Xie 	int ret;
1468cb517eabSMiao Xie 
1469e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1470cb517eabSMiao Xie 	if (ret)
1471cb517eabSMiao Xie 		return ret;
1472cb517eabSMiao Xie 
1473cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1474cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1475cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1476cb517eabSMiao Xie 				root);
1477af01d2e5SJosef Bacik 	if (ret == 0) {
147800246528SJosef Bacik 		btrfs_grab_root(root);
147927cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1480af01d2e5SJosef Bacik 	}
1481cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1482cb517eabSMiao Xie 	radix_tree_preload_end();
1483cb517eabSMiao Xie 
1484cb517eabSMiao Xie 	return ret;
1485cb517eabSMiao Xie }
1486cb517eabSMiao Xie 
1487bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1488bd647ce3SJosef Bacik {
1489bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1490bd647ce3SJosef Bacik 	struct btrfs_root *root;
1491bd647ce3SJosef Bacik 
1492bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1493bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1494bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1495bd647ce3SJosef Bacik 		btrfs_err(fs_info, "leaked root %llu-%llu refcount %d",
1496bd647ce3SJosef Bacik 			  root->root_key.objectid, root->root_key.offset,
1497bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1498bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
149900246528SJosef Bacik 			btrfs_put_root(root);
150000246528SJosef Bacik 		btrfs_put_root(root);
1501bd647ce3SJosef Bacik 	}
1502bd647ce3SJosef Bacik #endif
1503bd647ce3SJosef Bacik }
1504bd647ce3SJosef Bacik 
15050d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
15060d4b0463SJosef Bacik {
1507141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1508141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
1509141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dio_bytes);
1510141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1511141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1512141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1513141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
15140d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
15150d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
151600246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
151700246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
151800246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
151900246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
152000246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
152100246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
152200246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
152300246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
152400246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1525bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
15263fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
15270d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
15280d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
15290d4b0463SJosef Bacik 	kvfree(fs_info);
15300d4b0463SJosef Bacik }
15310d4b0463SJosef Bacik 
15320d4b0463SJosef Bacik 
1533c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1534c00869f1SMiao Xie 				     struct btrfs_key *location,
1535c00869f1SMiao Xie 				     bool check_ref)
15365eda7b5eSChris Mason {
15375eda7b5eSChris Mason 	struct btrfs_root *root;
1538381cf658SDavid Sterba 	struct btrfs_path *path;
15391d4c08e0SDavid Sterba 	struct btrfs_key key;
15405eda7b5eSChris Mason 	int ret;
15415eda7b5eSChris Mason 
1542edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
154300246528SJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
1544edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
154500246528SJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
15468f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
154700246528SJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
15488f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
154900246528SJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
15500403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
155100246528SJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
1552bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
155300246528SJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
1554bc44d7c4SJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
1555f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
155600246528SJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
1557bc44d7c4SJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
155870f6d82eSOmar Sandoval 	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
155900246528SJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
1560bc44d7c4SJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
15614df27c4dSYan, Zheng again:
1562cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
156348475471SStefan Behrens 	if (root) {
1564bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
156500246528SJosef Bacik 			btrfs_put_root(root);
156648475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1567bc44d7c4SJosef Bacik 		}
15685eda7b5eSChris Mason 		return root;
156948475471SStefan Behrens 	}
15705eda7b5eSChris Mason 
157183db2aadSJosef Bacik 	root = btrfs_read_tree_root(fs_info->tree_root, location);
15725eda7b5eSChris Mason 	if (IS_ERR(root))
15735eda7b5eSChris Mason 		return root;
15743394e160SChris Mason 
1575c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1576d68fc57bSYan, Zheng 		ret = -ENOENT;
1577d68fc57bSYan, Zheng 		goto fail;
1578d68fc57bSYan, Zheng 	}
1579d68fc57bSYan, Zheng 
1580cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1581cb517eabSMiao Xie 	if (ret)
1582cb517eabSMiao Xie 		goto fail;
1583cb517eabSMiao Xie 
1584381cf658SDavid Sterba 	path = btrfs_alloc_path();
1585381cf658SDavid Sterba 	if (!path) {
1586381cf658SDavid Sterba 		ret = -ENOMEM;
1587381cf658SDavid Sterba 		goto fail;
1588381cf658SDavid Sterba 	}
15891d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15901d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
15911d4c08e0SDavid Sterba 	key.offset = location->objectid;
15921d4c08e0SDavid Sterba 
15931d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1594381cf658SDavid Sterba 	btrfs_free_path(path);
1595d68fc57bSYan, Zheng 	if (ret < 0)
1596d68fc57bSYan, Zheng 		goto fail;
1597d68fc57bSYan, Zheng 	if (ret == 0)
159827cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1599d68fc57bSYan, Zheng 
1600cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16010f7d52f4SChris Mason 	if (ret) {
160200246528SJosef Bacik 		btrfs_put_root(root);
16034785e24fSJosef Bacik 		if (ret == -EEXIST)
16044df27c4dSYan, Zheng 			goto again;
16054df27c4dSYan, Zheng 		goto fail;
16064df27c4dSYan, Zheng 	}
1607edbd8d4eSChris Mason 	return root;
16084df27c4dSYan, Zheng fail:
16098c38938cSJosef Bacik 	btrfs_put_root(root);
16104df27c4dSYan, Zheng 	return ERR_PTR(ret);
1611edbd8d4eSChris Mason }
1612edbd8d4eSChris Mason 
161304160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
161404160088SChris Mason {
161504160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
161604160088SChris Mason 	int ret = 0;
161704160088SChris Mason 	struct btrfs_device *device;
161804160088SChris Mason 	struct backing_dev_info *bdi;
1619b7967db7SChris Mason 
16201f78160cSXiao Guangrong 	rcu_read_lock();
16211f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1622dfe25020SChris Mason 		if (!device->bdev)
1623dfe25020SChris Mason 			continue;
1624efa7c9f9SJan Kara 		bdi = device->bdev->bd_bdi;
1625ff9ea323STejun Heo 		if (bdi_congested(bdi, bdi_bits)) {
162604160088SChris Mason 			ret = 1;
162704160088SChris Mason 			break;
162804160088SChris Mason 		}
162904160088SChris Mason 	}
16301f78160cSXiao Guangrong 	rcu_read_unlock();
163104160088SChris Mason 	return ret;
163204160088SChris Mason }
163304160088SChris Mason 
16348b712842SChris Mason /*
16358b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16368b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16378b712842SChris Mason  */
16388b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1639ce9adaa5SChris Mason {
1640ce9adaa5SChris Mason 	struct bio *bio;
164197eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1642ce9adaa5SChris Mason 
164397eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1644ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16458b712842SChris Mason 
16464e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1647ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1648ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
16494246a0b6SChristoph Hellwig 	bio_endio(bio);
16509be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1651ce9adaa5SChris Mason }
165244b8bd7eSChris Mason 
1653a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1654a74a4b97SChris Mason {
1655a74a4b97SChris Mason 	struct btrfs_root *root = arg;
16560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1657d0278245SMiao Xie 	int again;
1658a74a4b97SChris Mason 
1659d6fd0ae2SOmar Sandoval 	while (1) {
1660d0278245SMiao Xie 		again = 0;
16619d1a2a3aSDavid Sterba 
1662fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1663fd340d0fSJosef Bacik 
1664d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16652ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1666d0278245SMiao Xie 			goto sleep;
1667d0278245SMiao Xie 
166890c711abSZygo Blaxell 		/*
166990c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
167090c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
167190c711abSZygo Blaxell 		 */
16720b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
167390c711abSZygo Blaxell 			goto sleep;
167490c711abSZygo Blaxell 
16750b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1676d0278245SMiao Xie 			goto sleep;
1677d0278245SMiao Xie 
1678dc7f370cSMiao Xie 		/*
1679dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1680dc7f370cSMiao Xie 		 * during the above check and trylock.
1681dc7f370cSMiao Xie 		 */
16822ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
16830b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1684dc7f370cSMiao Xie 			goto sleep;
1685dc7f370cSMiao Xie 		}
1686dc7f370cSMiao Xie 
16872ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1688c2d6cb16SFilipe Manana 
16899d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
16900b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1691a74a4b97SChris Mason 
1692d0278245SMiao Xie 		/*
169305323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
169405323cd1SMiao Xie 		 * needn't do anything special here.
1695d0278245SMiao Xie 		 */
16960b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
169767c5e7d4SFilipe Manana 
169867c5e7d4SFilipe Manana 		/*
169967c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
170067c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
170167c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
170267c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
170367c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
170467c5e7d4SFilipe Manana 		 * unused block groups.
170567c5e7d4SFilipe Manana 		 */
17060b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1707d0278245SMiao Xie sleep:
1708fd340d0fSJosef Bacik 		clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1709d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1710d6fd0ae2SOmar Sandoval 			kthread_parkme();
1711d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1712d6fd0ae2SOmar Sandoval 			return 0;
1713838fe188SJiri Kosina 		if (!again) {
1714a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1715a74a4b97SChris Mason 			schedule();
1716a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1717a74a4b97SChris Mason 		}
1718da288d28SFilipe Manana 	}
1719a74a4b97SChris Mason }
1720a74a4b97SChris Mason 
1721a74a4b97SChris Mason static int transaction_kthread(void *arg)
1722a74a4b97SChris Mason {
1723a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1725a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1726a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17278929ecfaSYan, Zheng 	u64 transid;
1728a944442cSAllen Pais 	time64_t now;
1729a74a4b97SChris Mason 	unsigned long delay;
1730914b2007SJan Kara 	bool cannot_commit;
1731a74a4b97SChris Mason 
1732a74a4b97SChris Mason 	do {
1733914b2007SJan Kara 		cannot_commit = false;
17340b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
17350b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1736a74a4b97SChris Mason 
17370b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17380b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1739a74a4b97SChris Mason 		if (!cur) {
17400b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1741a74a4b97SChris Mason 			goto sleep;
1742a74a4b97SChris Mason 		}
174331153d81SYan Zheng 
1744afd48513SArnd Bergmann 		now = ktime_get_seconds();
17453296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1746a514d638SQu Wenruo 		    !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
17478b87dc17SDavid Sterba 		    (now < cur->start_time ||
17480b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
17490b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1750a74a4b97SChris Mason 			delay = HZ * 5;
1751a74a4b97SChris Mason 			goto sleep;
1752a74a4b97SChris Mason 		}
17538929ecfaSYan, Zheng 		transid = cur->transid;
17540b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
175556bec294SChris Mason 
175679787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1757354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1758914b2007SJan Kara 		if (IS_ERR(trans)) {
1759354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1760914b2007SJan Kara 				cannot_commit = true;
176179787eaaSJeff Mahoney 			goto sleep;
1762914b2007SJan Kara 		}
17638929ecfaSYan, Zheng 		if (transid == trans->transid) {
17643a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
17658929ecfaSYan, Zheng 		} else {
17663a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
17678929ecfaSYan, Zheng 		}
1768a74a4b97SChris Mason sleep:
17690b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
17700b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1771a74a4b97SChris Mason 
17724e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
17730b246afaSJeff Mahoney 				      &fs_info->fs_state)))
17742ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
17758929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
17760b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1777914b2007SJan Kara 				 cannot_commit))
1778bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1779a74a4b97SChris Mason 	} while (!kthread_should_stop());
1780a74a4b97SChris Mason 	return 0;
1781a74a4b97SChris Mason }
1782a74a4b97SChris Mason 
1783af31f5e5SChris Mason /*
178401f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
178501f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
178601f0f9daSNikolay Borisov  * anything.
1787af31f5e5SChris Mason  *
1788af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1789af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1790af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1791af31f5e5SChris Mason  */
179201f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1793af31f5e5SChris Mason {
179401f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1795af31f5e5SChris Mason 	u64 cur;
1796af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1797af31f5e5SChris Mason 	int i;
1798af31f5e5SChris Mason 
1799af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1800af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1801af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1802af31f5e5SChris Mason 		if (cur == newest_gen)
180301f0f9daSNikolay Borisov 			return i;
1804af31f5e5SChris Mason 	}
1805af31f5e5SChris Mason 
180601f0f9daSNikolay Borisov 	return -EINVAL;
1807af31f5e5SChris Mason }
1808af31f5e5SChris Mason 
1809af31f5e5SChris Mason /*
1810af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1811af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1812af31f5e5SChris Mason  * done
1813af31f5e5SChris Mason  */
1814af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1815af31f5e5SChris Mason {
18166ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1817af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1818af31f5e5SChris Mason 
1819af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1820af31f5e5SChris Mason 
1821af31f5e5SChris Mason 	/*
1822af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1823af31f5e5SChris Mason 	 * regardless of which ones we use today
1824af31f5e5SChris Mason 	 */
1825af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1826af31f5e5SChris Mason 
1827af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1828af31f5e5SChris Mason 
1829af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1830af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1831af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1832af31f5e5SChris Mason 
1833af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1834af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1835af31f5e5SChris Mason 
1836af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1837af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1838af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1839af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1840af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1841af31f5e5SChris Mason 
1842af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1843af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1844af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1845af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1846af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1847af31f5e5SChris Mason 
18487c7e82a7SChris Mason 	/*
18497c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18507c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18517c7e82a7SChris Mason 	 */
18527c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18537c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18547c7e82a7SChris Mason 					 info->fs_root->node->start);
1855af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1856af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1857af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1858af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
18597c7e82a7SChris Mason 	}
1860af31f5e5SChris Mason 
1861af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1862af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1863af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1864af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1865af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1866af31f5e5SChris Mason 
1867af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1868af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1869af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1870af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1871af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1872af31f5e5SChris Mason 
1873af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1874af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1875af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1876af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1877af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1878af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1879af31f5e5SChris Mason 
1880af31f5e5SChris Mason 	/*
1881af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1882af31f5e5SChris Mason 	 * for the next commit
1883af31f5e5SChris Mason 	 */
1884af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1885af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1886af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1887af31f5e5SChris Mason }
1888af31f5e5SChris Mason 
1889af31f5e5SChris Mason /*
1890bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1891bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1892bd2336b2SNikolay Borisov  *
1893bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1894bd2336b2SNikolay Borisov  * priority - priority of backup root required
1895bd2336b2SNikolay Borisov  *
1896bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1897bd2336b2SNikolay Borisov  */
1898bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1899bd2336b2SNikolay Borisov {
1900bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1901bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1902bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1903bd2336b2SNikolay Borisov 
1904bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1905bd2336b2SNikolay Borisov 		if (priority == 0)
1906bd2336b2SNikolay Borisov 			return backup_index;
1907bd2336b2SNikolay Borisov 
1908bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1909bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1910bd2336b2SNikolay Borisov 	} else {
1911bd2336b2SNikolay Borisov 		return -EINVAL;
1912bd2336b2SNikolay Borisov 	}
1913bd2336b2SNikolay Borisov 
1914bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1915bd2336b2SNikolay Borisov 
1916bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1917bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1918bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1919bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1920bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1921bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1922bd2336b2SNikolay Borisov 
1923bd2336b2SNikolay Borisov 	/*
1924bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1925bd2336b2SNikolay Borisov 	 * need a fsck
1926bd2336b2SNikolay Borisov 	 */
1927bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1928bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1929bd2336b2SNikolay Borisov 
1930bd2336b2SNikolay Borisov 	return backup_index;
1931bd2336b2SNikolay Borisov }
1932bd2336b2SNikolay Borisov 
19337abadb64SLiu Bo /* helper to cleanup workers */
19347abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19357abadb64SLiu Bo {
1936dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1937afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
19385cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1939fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
1940fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
1941d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
1942fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1943fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19445b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1945e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1946736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
1947a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1948fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1949b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1950b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1951a9b9477dSFilipe Manana 	/*
1952a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1953a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1954a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1955a9b9477dSFilipe Manana 	 */
1956a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
1957a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
19587abadb64SLiu Bo }
19597abadb64SLiu Bo 
19602e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
19612e9f5954SRashika {
19622e9f5954SRashika 	if (root) {
19632e9f5954SRashika 		free_extent_buffer(root->node);
19642e9f5954SRashika 		free_extent_buffer(root->commit_root);
19652e9f5954SRashika 		root->node = NULL;
19662e9f5954SRashika 		root->commit_root = NULL;
19672e9f5954SRashika 	}
19682e9f5954SRashika }
19692e9f5954SRashika 
1970af31f5e5SChris Mason /* helper to cleanup tree roots */
19714273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1972af31f5e5SChris Mason {
19732e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1974655b09feSJosef Bacik 
19752e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
19762e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
19772e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
19782e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
19792e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
19808c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
19814273eaffSAnand Jain 	if (free_chunk_root)
19822e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
198370f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
1984af31f5e5SChris Mason }
1985af31f5e5SChris Mason 
19868c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
19878c38938cSJosef Bacik {
19888c38938cSJosef Bacik 	if (!root)
19898c38938cSJosef Bacik 		return;
19908c38938cSJosef Bacik 
19918c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
19928c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
19938c38938cSJosef Bacik 		if (root->anon_dev)
19948c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
19958c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
19968c38938cSJosef Bacik 		free_extent_buffer(root->node);
19978c38938cSJosef Bacik 		free_extent_buffer(root->commit_root);
19988c38938cSJosef Bacik 		kfree(root->free_ino_ctl);
19998c38938cSJosef Bacik 		kfree(root->free_ino_pinned);
20008c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
20018c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
20028c38938cSJosef Bacik 		list_del_init(&root->leak_list);
20038c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
20048c38938cSJosef Bacik #endif
20058c38938cSJosef Bacik 		kfree(root);
20068c38938cSJosef Bacik 	}
20078c38938cSJosef Bacik }
20088c38938cSJosef Bacik 
2009faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2010171f6537SJosef Bacik {
2011171f6537SJosef Bacik 	int ret;
2012171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2013171f6537SJosef Bacik 	int i;
2014171f6537SJosef Bacik 
2015171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2016171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2017171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2018171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2019171f6537SJosef Bacik 
20208c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2021cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
202200246528SJosef Bacik 		btrfs_put_root(gang[0]);
2023171f6537SJosef Bacik 	}
2024171f6537SJosef Bacik 
2025171f6537SJosef Bacik 	while (1) {
2026171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2027171f6537SJosef Bacik 					     (void **)gang, 0,
2028171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2029171f6537SJosef Bacik 		if (!ret)
2030171f6537SJosef Bacik 			break;
2031171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2032cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2033171f6537SJosef Bacik 	}
2034171f6537SJosef Bacik }
2035af31f5e5SChris Mason 
2036638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2037638aa7edSEric Sandeen {
2038638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2039638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2040638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2041638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2042638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2043638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2044ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2045638aa7edSEric Sandeen }
2046638aa7edSEric Sandeen 
2047779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2048779a65a4SEric Sandeen {
2049779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2050779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2051779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2052779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2053779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2054779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2055779a65a4SEric Sandeen }
2056779a65a4SEric Sandeen 
20576bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2058f37938e0SEric Sandeen {
20592ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
20602ff7e61eSJeff Mahoney 
20612ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
20622ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2063f37938e0SEric Sandeen 	/*
2064f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2065f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2066f37938e0SEric Sandeen 	 * the devices in the system
2067f37938e0SEric Sandeen 	 */
20682ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
20692ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2070f37938e0SEric Sandeen 
20712ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
207243eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
207343eb5f29SQu Wenruo 			    IO_TREE_INODE_IO, inode);
20747b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
20752ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2076f37938e0SEric Sandeen 
20772ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2078f37938e0SEric Sandeen 
20795c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
20802ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
20812ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
20822ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2083f37938e0SEric Sandeen }
2084f37938e0SEric Sandeen 
2085ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2086ad618368SEric Sandeen {
2087ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2088129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
20897f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2090ad618368SEric Sandeen }
2091ad618368SEric Sandeen 
2092f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2093f9e92e40SEric Sandeen {
2094f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2095f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2096f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2097f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2098f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2099f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2100d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2101f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2102f9e92e40SEric Sandeen }
2103f9e92e40SEric Sandeen 
21042a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
21052a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
21062a458198SEric Sandeen {
2107f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21086f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21092a458198SEric Sandeen 
21102a458198SEric Sandeen 	fs_info->workers =
2111cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2112cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21132a458198SEric Sandeen 
21142a458198SEric Sandeen 	fs_info->delalloc_workers =
2115cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2116cb001095SJeff Mahoney 				      flags, max_active, 2);
21172a458198SEric Sandeen 
21182a458198SEric Sandeen 	fs_info->flush_workers =
2119cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2120cb001095SJeff Mahoney 				      flags, max_active, 0);
21212a458198SEric Sandeen 
21222a458198SEric Sandeen 	fs_info->caching_workers =
2123cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21242a458198SEric Sandeen 
21252a458198SEric Sandeen 	fs_info->fixup_workers =
2126cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
21272a458198SEric Sandeen 
21282a458198SEric Sandeen 	/*
21292a458198SEric Sandeen 	 * endios are largely parallel and should have a very
21302a458198SEric Sandeen 	 * low idle thresh
21312a458198SEric Sandeen 	 */
21322a458198SEric Sandeen 	fs_info->endio_workers =
2133cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
21342a458198SEric Sandeen 	fs_info->endio_meta_workers =
2135cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2136cb001095SJeff Mahoney 				      max_active, 4);
21372a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2138cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2139cb001095SJeff Mahoney 				      max_active, 2);
21402a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2141cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2142cb001095SJeff Mahoney 				      max_active, 4);
21432a458198SEric Sandeen 	fs_info->rmw_workers =
2144cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
21452a458198SEric Sandeen 	fs_info->endio_write_workers =
2146cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2147cb001095SJeff Mahoney 				      max_active, 2);
21482a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2149cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2150cb001095SJeff Mahoney 				      max_active, 0);
21512a458198SEric Sandeen 	fs_info->delayed_workers =
2152cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2153cb001095SJeff Mahoney 				      max_active, 0);
21542a458198SEric Sandeen 	fs_info->readahead_workers =
2155cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2156cb001095SJeff Mahoney 				      max_active, 2);
21572a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2158cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2159b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2160b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
21612a458198SEric Sandeen 
21622a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2163ba8a9d07SChris Mason 	      fs_info->flush_workers &&
21642a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
21652a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
21662a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
21672a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
21682a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
21692a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2170b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2171b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
21722a458198SEric Sandeen 		return -ENOMEM;
21732a458198SEric Sandeen 	}
21742a458198SEric Sandeen 
21752a458198SEric Sandeen 	return 0;
21762a458198SEric Sandeen }
21772a458198SEric Sandeen 
21786d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
21796d97c6e3SJohannes Thumshirn {
21806d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2181b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
21826d97c6e3SJohannes Thumshirn 
2183b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
21846d97c6e3SJohannes Thumshirn 
21856d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
21866d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2187b4e967beSDavid Sterba 			  csum_driver);
21886d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
21896d97c6e3SJohannes Thumshirn 	}
21906d97c6e3SJohannes Thumshirn 
21916d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
21926d97c6e3SJohannes Thumshirn 
21936d97c6e3SJohannes Thumshirn 	return 0;
21946d97c6e3SJohannes Thumshirn }
21956d97c6e3SJohannes Thumshirn 
219663443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
219763443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
219863443bf5SEric Sandeen {
219963443bf5SEric Sandeen 	int ret;
220063443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
220163443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
220263443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2203581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
220463443bf5SEric Sandeen 
220563443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2206f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
220763443bf5SEric Sandeen 		return -EIO;
220863443bf5SEric Sandeen 	}
220963443bf5SEric Sandeen 
221096dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
221196dfcb46SJosef Bacik 					 GFP_KERNEL);
221263443bf5SEric Sandeen 	if (!log_tree_root)
221363443bf5SEric Sandeen 		return -ENOMEM;
221463443bf5SEric Sandeen 
22152ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
2216581c1760SQu Wenruo 					      fs_info->generation + 1,
2217581c1760SQu Wenruo 					      level, NULL);
221864c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2219f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22200eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
22218c38938cSJosef Bacik 		log_tree_root->node = NULL;
222200246528SJosef Bacik 		btrfs_put_root(log_tree_root);
22230eeff236SLiu Bo 		return ret;
222464c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2225f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
222600246528SJosef Bacik 		btrfs_put_root(log_tree_root);
222763443bf5SEric Sandeen 		return -EIO;
222863443bf5SEric Sandeen 	}
222963443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
223063443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
223163443bf5SEric Sandeen 	if (ret) {
22320b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
223363443bf5SEric Sandeen 				      "Failed to recover log tree");
223400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
223563443bf5SEric Sandeen 		return ret;
223663443bf5SEric Sandeen 	}
223763443bf5SEric Sandeen 
2238bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
22396bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
224063443bf5SEric Sandeen 		if (ret)
224163443bf5SEric Sandeen 			return ret;
224263443bf5SEric Sandeen 	}
224363443bf5SEric Sandeen 
224463443bf5SEric Sandeen 	return 0;
224563443bf5SEric Sandeen }
224663443bf5SEric Sandeen 
22476bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
22484bbcaa64SEric Sandeen {
22496bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2250a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
22514bbcaa64SEric Sandeen 	struct btrfs_key location;
22524bbcaa64SEric Sandeen 	int ret;
22534bbcaa64SEric Sandeen 
22546bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
22556bccf3abSJeff Mahoney 
22564bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
22574bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
22584bbcaa64SEric Sandeen 	location.offset = 0;
22594bbcaa64SEric Sandeen 
2260a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2261f50f4353SLiu Bo 	if (IS_ERR(root)) {
2262f50f4353SLiu Bo 		ret = PTR_ERR(root);
2263f50f4353SLiu Bo 		goto out;
2264f50f4353SLiu Bo 	}
2265a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2266a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
22674bbcaa64SEric Sandeen 
22684bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2269a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2270f50f4353SLiu Bo 	if (IS_ERR(root)) {
2271f50f4353SLiu Bo 		ret = PTR_ERR(root);
2272f50f4353SLiu Bo 		goto out;
2273f50f4353SLiu Bo 	}
2274a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2275a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
22764bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
22774bbcaa64SEric Sandeen 
22784bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2279a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2280f50f4353SLiu Bo 	if (IS_ERR(root)) {
2281f50f4353SLiu Bo 		ret = PTR_ERR(root);
2282f50f4353SLiu Bo 		goto out;
2283f50f4353SLiu Bo 	}
2284a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2285a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
22864bbcaa64SEric Sandeen 
22874bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2288a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2289a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2290a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2291afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2292a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
22934bbcaa64SEric Sandeen 	}
22944bbcaa64SEric Sandeen 
22954bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2296a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2297a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2298a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
22994bbcaa64SEric Sandeen 		if (ret != -ENOENT)
2300f50f4353SLiu Bo 			goto out;
23014bbcaa64SEric Sandeen 	} else {
2302a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2303a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
23044bbcaa64SEric Sandeen 	}
23054bbcaa64SEric Sandeen 
230670f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
230770f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
230870f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2309f50f4353SLiu Bo 		if (IS_ERR(root)) {
2310f50f4353SLiu Bo 			ret = PTR_ERR(root);
2311f50f4353SLiu Bo 			goto out;
2312f50f4353SLiu Bo 		}
231370f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
231470f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
231570f6d82eSOmar Sandoval 	}
231670f6d82eSOmar Sandoval 
23174bbcaa64SEric Sandeen 	return 0;
2318f50f4353SLiu Bo out:
2319f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2320f50f4353SLiu Bo 		   location.objectid, ret);
2321f50f4353SLiu Bo 	return ret;
23224bbcaa64SEric Sandeen }
23234bbcaa64SEric Sandeen 
2324069ec957SQu Wenruo /*
2325069ec957SQu Wenruo  * Real super block validation
2326069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2327069ec957SQu Wenruo  *
2328069ec957SQu Wenruo  * @sb:		super block to check
2329069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2330069ec957SQu Wenruo  * 		0	the primary (1st) sb
2331069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2332069ec957SQu Wenruo  * 	       -1	skip bytenr check
2333069ec957SQu Wenruo  */
2334069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2335069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
233621a852b0SQu Wenruo {
233721a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
233821a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
233921a852b0SQu Wenruo 	int ret = 0;
234021a852b0SQu Wenruo 
234121a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
234221a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
234321a852b0SQu Wenruo 		ret = -EINVAL;
234421a852b0SQu Wenruo 	}
234521a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
234621a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
234721a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
234821a852b0SQu Wenruo 		ret = -EINVAL;
234921a852b0SQu Wenruo 	}
235021a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
235121a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
235221a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
235321a852b0SQu Wenruo 		ret = -EINVAL;
235421a852b0SQu Wenruo 	}
235521a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
235621a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
235721a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
235821a852b0SQu Wenruo 		ret = -EINVAL;
235921a852b0SQu Wenruo 	}
236021a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
236121a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
236221a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
236321a852b0SQu Wenruo 		ret = -EINVAL;
236421a852b0SQu Wenruo 	}
236521a852b0SQu Wenruo 
236621a852b0SQu Wenruo 	/*
236721a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
236821a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
236921a852b0SQu Wenruo 	 */
237021a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
237121a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
237221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
237321a852b0SQu Wenruo 		ret = -EINVAL;
237421a852b0SQu Wenruo 	}
237521a852b0SQu Wenruo 	/* Only PAGE SIZE is supported yet */
237621a852b0SQu Wenruo 	if (sectorsize != PAGE_SIZE) {
237721a852b0SQu Wenruo 		btrfs_err(fs_info,
237821a852b0SQu Wenruo 			"sectorsize %llu not supported yet, only support %lu",
237921a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
238021a852b0SQu Wenruo 		ret = -EINVAL;
238121a852b0SQu Wenruo 	}
238221a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
238321a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
238421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
238521a852b0SQu Wenruo 		ret = -EINVAL;
238621a852b0SQu Wenruo 	}
238721a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
238821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
238921a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
239021a852b0SQu Wenruo 		ret = -EINVAL;
239121a852b0SQu Wenruo 	}
239221a852b0SQu Wenruo 
239321a852b0SQu Wenruo 	/* Root alignment check */
239421a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
239521a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
239621a852b0SQu Wenruo 			   btrfs_super_root(sb));
239721a852b0SQu Wenruo 		ret = -EINVAL;
239821a852b0SQu Wenruo 	}
239921a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
240021a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
240121a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
240221a852b0SQu Wenruo 		ret = -EINVAL;
240321a852b0SQu Wenruo 	}
240421a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
240521a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
240621a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
240721a852b0SQu Wenruo 		ret = -EINVAL;
240821a852b0SQu Wenruo 	}
240921a852b0SQu Wenruo 
2410de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
24117239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
241221a852b0SQu Wenruo 		btrfs_err(fs_info,
24137239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2414de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
241521a852b0SQu Wenruo 		ret = -EINVAL;
241621a852b0SQu Wenruo 	}
241721a852b0SQu Wenruo 
241821a852b0SQu Wenruo 	/*
241921a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
242021a852b0SQu Wenruo 	 * done later
242121a852b0SQu Wenruo 	 */
242221a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
242321a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
242421a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
242521a852b0SQu Wenruo 		ret = -EINVAL;
242621a852b0SQu Wenruo 	}
242721a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
242821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
242921a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
243021a852b0SQu Wenruo 		ret = -EINVAL;
243121a852b0SQu Wenruo 	}
243221a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
243321a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
243421a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
243521a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
243621a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
243721a852b0SQu Wenruo 		ret = -EINVAL;
243821a852b0SQu Wenruo 	}
243921a852b0SQu Wenruo 
2440069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2441069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
244221a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
244321a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
244421a852b0SQu Wenruo 		ret = -EINVAL;
244521a852b0SQu Wenruo 	}
244621a852b0SQu Wenruo 
244721a852b0SQu Wenruo 	/*
244821a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
244921a852b0SQu Wenruo 	 * and one chunk
245021a852b0SQu Wenruo 	 */
245121a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
245221a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
245321a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
245421a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
245521a852b0SQu Wenruo 		ret = -EINVAL;
245621a852b0SQu Wenruo 	}
245721a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
245821a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
245921a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
246021a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
246121a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
246221a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
246321a852b0SQu Wenruo 		ret = -EINVAL;
246421a852b0SQu Wenruo 	}
246521a852b0SQu Wenruo 
246621a852b0SQu Wenruo 	/*
246721a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
246821a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
246921a852b0SQu Wenruo 	 */
247021a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
247121a852b0SQu Wenruo 		btrfs_warn(fs_info,
247221a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
247321a852b0SQu Wenruo 			btrfs_super_generation(sb),
247421a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
247521a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
247621a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
247721a852b0SQu Wenruo 		btrfs_warn(fs_info,
247821a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
247921a852b0SQu Wenruo 			btrfs_super_generation(sb),
248021a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
248121a852b0SQu Wenruo 
248221a852b0SQu Wenruo 	return ret;
248321a852b0SQu Wenruo }
248421a852b0SQu Wenruo 
2485069ec957SQu Wenruo /*
2486069ec957SQu Wenruo  * Validation of super block at mount time.
2487069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2488069ec957SQu Wenruo  * flags will be skipped.
2489069ec957SQu Wenruo  */
2490069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2491069ec957SQu Wenruo {
2492069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2493069ec957SQu Wenruo }
2494069ec957SQu Wenruo 
249575cb857dSQu Wenruo /*
249675cb857dSQu Wenruo  * Validation of super block at write time.
249775cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
249875cb857dSQu Wenruo  * overwritten soon.
249975cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
250075cb857dSQu Wenruo  */
250175cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
250275cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
250375cb857dSQu Wenruo {
250475cb857dSQu Wenruo 	int ret;
250575cb857dSQu Wenruo 
250675cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
250775cb857dSQu Wenruo 	if (ret < 0)
250875cb857dSQu Wenruo 		goto out;
2509e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
251075cb857dSQu Wenruo 		ret = -EUCLEAN;
251175cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
251275cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
251375cb857dSQu Wenruo 		goto out;
251475cb857dSQu Wenruo 	}
251575cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
251675cb857dSQu Wenruo 		ret = -EUCLEAN;
251775cb857dSQu Wenruo 		btrfs_err(fs_info,
251875cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
251975cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
252075cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
252175cb857dSQu Wenruo 		goto out;
252275cb857dSQu Wenruo 	}
252375cb857dSQu Wenruo out:
252475cb857dSQu Wenruo 	if (ret < 0)
252575cb857dSQu Wenruo 		btrfs_err(fs_info,
252675cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
252775cb857dSQu Wenruo 	return ret;
252875cb857dSQu Wenruo }
252975cb857dSQu Wenruo 
25306ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2531b8522a1eSNikolay Borisov {
25326ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2533b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2534b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2535b8522a1eSNikolay Borisov 	bool handle_error = false;
2536b8522a1eSNikolay Borisov 	int ret = 0;
2537b8522a1eSNikolay Borisov 	int i;
2538b8522a1eSNikolay Borisov 
2539b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2540b8522a1eSNikolay Borisov 		u64 generation;
2541b8522a1eSNikolay Borisov 		int level;
2542b8522a1eSNikolay Borisov 
2543b8522a1eSNikolay Borisov 		if (handle_error) {
2544b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2545b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2546b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2547b8522a1eSNikolay Borisov 
2548b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2549b8522a1eSNikolay Borisov 				break;
2550b8522a1eSNikolay Borisov 
2551b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2552b8522a1eSNikolay Borisov 
2553b8522a1eSNikolay Borisov 			/*
2554b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2555b8522a1eSNikolay Borisov 			 * valid
2556b8522a1eSNikolay Borisov 			 */
2557b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2558b8522a1eSNikolay Borisov 
2559b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2560b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2561b8522a1eSNikolay Borisov 
2562b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
25636ef108ddSNikolay Borisov 			backup_index = ret;
2564b8522a1eSNikolay Borisov 			if (ret < 0)
2565b8522a1eSNikolay Borisov 				return ret;
2566b8522a1eSNikolay Borisov 		}
2567b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2568b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2569b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
2570b8522a1eSNikolay Borisov 						  generation, level, NULL);
2571b8522a1eSNikolay Borisov 		if (IS_ERR(tree_root->node) ||
2572b8522a1eSNikolay Borisov 		    !extent_buffer_uptodate(tree_root->node)) {
2573b8522a1eSNikolay Borisov 			handle_error = true;
2574b8522a1eSNikolay Borisov 
2575b8522a1eSNikolay Borisov 			if (IS_ERR(tree_root->node))
2576b8522a1eSNikolay Borisov 				ret = PTR_ERR(tree_root->node);
2577b8522a1eSNikolay Borisov 			else if (!extent_buffer_uptodate(tree_root->node))
2578b8522a1eSNikolay Borisov 				ret = -EUCLEAN;
2579b8522a1eSNikolay Borisov 
2580b8522a1eSNikolay Borisov 			btrfs_warn(fs_info, "failed to read tree root");
2581b8522a1eSNikolay Borisov 			continue;
2582b8522a1eSNikolay Borisov 		}
2583b8522a1eSNikolay Borisov 
2584b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2585b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2586b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2587b8522a1eSNikolay Borisov 
2588336a0d8dSNikolay Borisov 		/*
2589336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2590336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2591336a0d8dSNikolay Borisov 		 */
2592b8522a1eSNikolay Borisov 		ret = btrfs_find_highest_objectid(tree_root,
2593b8522a1eSNikolay Borisov 						&tree_root->highest_objectid);
2594b8522a1eSNikolay Borisov 		if (ret < 0) {
2595b8522a1eSNikolay Borisov 			handle_error = true;
2596b8522a1eSNikolay Borisov 			continue;
2597b8522a1eSNikolay Borisov 		}
2598b8522a1eSNikolay Borisov 
2599b8522a1eSNikolay Borisov 		ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2600b8522a1eSNikolay Borisov 
2601b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2602b8522a1eSNikolay Borisov 		if (ret < 0) {
2603b8522a1eSNikolay Borisov 			handle_error = true;
2604b8522a1eSNikolay Borisov 			continue;
2605b8522a1eSNikolay Borisov 		}
2606b8522a1eSNikolay Borisov 
2607b8522a1eSNikolay Borisov 		/* All successful */
2608b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2609b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
26106ef108ddSNikolay Borisov 
26116ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26126ef108ddSNikolay Borisov 		if (backup_index < 0) {
26136ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26146ef108ddSNikolay Borisov 		} else {
26156ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26166ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26176ef108ddSNikolay Borisov 		}
2618b8522a1eSNikolay Borisov 		break;
2619b8522a1eSNikolay Borisov 	}
2620b8522a1eSNikolay Borisov 
2621b8522a1eSNikolay Borisov 	return ret;
2622b8522a1eSNikolay Borisov }
2623b8522a1eSNikolay Borisov 
26248260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2625eb60ceacSChris Mason {
262676dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2627f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26288fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2629facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
263024bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2631eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
263211833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2633eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2634a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
263576dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
263624bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26374cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2638ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2639f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
264047ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2641f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2642d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
264367c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
26447585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2645573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2646de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
264719c00ddcSChris Mason 
26480b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
26496324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2650f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
265147ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2652bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2653bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
26543fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
26553fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2656bd647ce3SJosef Bacik #endif
2657c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
265866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
265966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
266066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
266166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
266266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
266366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
266466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2665ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2666ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2667ba2c4d4eSJosef Bacik 
2668771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
26694cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
26702fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2671034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2672fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
267395ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
26749ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
26754cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2676a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2677f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
26788b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2679f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
268090519d66SArne Jansen 	/* readahead state */
2681d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
268290519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2683fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2684c8b97818SChris Mason 
2685b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2686b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
26870afbaf8cSChris Mason 
2688199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2689199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
269069fe2d75SJosef Bacik 
2691638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
269221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
269321adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
269421adbd5cSStefan Behrens #endif
2695779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
269621c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2697a2de733cSArne Jansen 
26980f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
26996bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2700a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
27010f9dd46cSJosef Bacik 
2702fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2703fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2704afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
270539279cc3SChris Mason 
27065a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2707e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2708925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2709a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2710a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27111bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27129e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2713c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
271476dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2715803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2716fa9c0d79SChris Mason 
2717ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2718f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2719b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2720416ac51dSArne Jansen 
2721fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2722fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2723fa9c0d79SChris Mason 
2724e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2725f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2726bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27274854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2728034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
27293768f368SChris Mason 
2730da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2731da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2732da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2733da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2734da17066cSJeff Mahoney 
2735eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2736eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2737eede2bf3SOmar Sandoval 
27389e967495SFilipe Manana 	fs_info->send_in_progress = 0;
27398260edbaSJosef Bacik }
27408260edbaSJosef Bacik 
27418260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
27428260edbaSJosef Bacik {
27438260edbaSJosef Bacik 	int ret;
27448260edbaSJosef Bacik 
27458260edbaSJosef Bacik 	fs_info->sb = sb;
27468260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
27478260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
27489e967495SFilipe Manana 
2749c75e8394SJosef Bacik 	ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
2750ae18c37aSJosef Bacik 	if (ret)
2751ae18c37aSJosef Bacik 		return ret;
2752ae18c37aSJosef Bacik 
2753ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2754ae18c37aSJosef Bacik 	if (ret)
2755c75e8394SJosef Bacik 		return ret;
2756ae18c37aSJosef Bacik 
2757ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2758ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2759ae18c37aSJosef Bacik 
2760ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2761ae18c37aSJosef Bacik 	if (ret)
2762c75e8394SJosef Bacik 		return ret;
2763ae18c37aSJosef Bacik 
2764ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2765ae18c37aSJosef Bacik 			GFP_KERNEL);
2766ae18c37aSJosef Bacik 	if (ret)
2767c75e8394SJosef Bacik 		return ret;
2768ae18c37aSJosef Bacik 
2769ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2770ae18c37aSJosef Bacik 					GFP_KERNEL);
2771c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2772c75e8394SJosef Bacik 		return -ENOMEM;
2773ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2774ae18c37aSJosef Bacik 
2775c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2776ae18c37aSJosef Bacik }
2777ae18c37aSJosef Bacik 
277897f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
277997f4dd09SNikolay Borisov {
278097f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
278197f4dd09SNikolay Borisov 	int ret;
278297f4dd09SNikolay Borisov 
278397f4dd09SNikolay Borisov 	/*
278497f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
278597f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
278697f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
278797f4dd09SNikolay Borisov 	 */
278897f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
278997f4dd09SNikolay Borisov 	if (ret < 0) {
2790c94bec2cSJosef Bacik 		if (ret != -EINTR)
2791c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2792c94bec2cSJosef Bacik 				   ret);
279397f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
279497f4dd09SNikolay Borisov 		return ret;
279597f4dd09SNikolay Borisov 	}
279697f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
279797f4dd09SNikolay Borisov }
279897f4dd09SNikolay Borisov 
279997f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
280097f4dd09SNikolay Borisov {
280197f4dd09SNikolay Borisov 	struct task_struct *task;
280297f4dd09SNikolay Borisov 
280397f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
280497f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
280597f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
280697f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
280797f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
280897f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
280997f4dd09SNikolay Borisov 		return PTR_ERR(task);
281097f4dd09SNikolay Borisov 	}
281197f4dd09SNikolay Borisov 
281297f4dd09SNikolay Borisov 	return 0;
281397f4dd09SNikolay Borisov }
281497f4dd09SNikolay Borisov 
2815ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
2816ae18c37aSJosef Bacik 		      char *options)
2817ae18c37aSJosef Bacik {
2818ae18c37aSJosef Bacik 	u32 sectorsize;
2819ae18c37aSJosef Bacik 	u32 nodesize;
2820ae18c37aSJosef Bacik 	u32 stripesize;
2821ae18c37aSJosef Bacik 	u64 generation;
2822ae18c37aSJosef Bacik 	u64 features;
2823ae18c37aSJosef Bacik 	u16 csum_type;
2824ae18c37aSJosef Bacik 	struct btrfs_key location;
2825ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
2826ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2827ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
2828ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
2829ae18c37aSJosef Bacik 	int ret;
2830ae18c37aSJosef Bacik 	int err = -EINVAL;
2831ae18c37aSJosef Bacik 	int clear_free_space_tree = 0;
2832ae18c37aSJosef Bacik 	int level;
2833ae18c37aSJosef Bacik 
28348260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
283553b381b3SDavid Woodhouse 	if (ret) {
283683c8266aSDavid Sterba 		err = ret;
2837ae18c37aSJosef Bacik 		goto fail;
283853b381b3SDavid Woodhouse 	}
283953b381b3SDavid Woodhouse 
2840ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
2841ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
2842ae18c37aSJosef Bacik 				     GFP_KERNEL);
2843ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
2844ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
2845ae18c37aSJosef Bacik 				      GFP_KERNEL);
2846ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
2847ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
2848ae18c37aSJosef Bacik 		err = -ENOMEM;
2849c75e8394SJosef Bacik 		goto fail;
2850ae18c37aSJosef Bacik 	}
2851ae18c37aSJosef Bacik 
2852ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
2853ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
2854ae18c37aSJosef Bacik 		err = -ENOMEM;
2855c75e8394SJosef Bacik 		goto fail;
2856ae18c37aSJosef Bacik 	}
2857ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2858ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
2859ae18c37aSJosef Bacik 
28603c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
28611104a885SDavid Sterba 
28621104a885SDavid Sterba 	/*
28631104a885SDavid Sterba 	 * Read super block and check the signature bytes only
28641104a885SDavid Sterba 	 */
28658f32380dSJohannes Thumshirn 	disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
28668f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
28678f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
286816cdcec7SMiao Xie 		goto fail_alloc;
286920b45077SDave Young 	}
287039279cc3SChris Mason 
28711104a885SDavid Sterba 	/*
28728dc3f22cSJohannes Thumshirn 	 * Verify the type first, if that or the the checksum value are
28738dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
28748dc3f22cSJohannes Thumshirn 	 */
28758f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
287651bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
28778dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
287851bce6c9SJohannes Thumshirn 			  csum_type);
28798dc3f22cSJohannes Thumshirn 		err = -EINVAL;
28808f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
28818dc3f22cSJohannes Thumshirn 		goto fail_alloc;
28828dc3f22cSJohannes Thumshirn 	}
28838dc3f22cSJohannes Thumshirn 
28846d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
28856d97c6e3SJohannes Thumshirn 	if (ret) {
28866d97c6e3SJohannes Thumshirn 		err = ret;
28878f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
28886d97c6e3SJohannes Thumshirn 		goto fail_alloc;
28896d97c6e3SJohannes Thumshirn 	}
28906d97c6e3SJohannes Thumshirn 
28918dc3f22cSJohannes Thumshirn 	/*
28921104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
28931104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
28941104a885SDavid Sterba 	 */
28958f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
289605135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
28971104a885SDavid Sterba 		err = -EINVAL;
28988f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
2899141386e1SJosef Bacik 		goto fail_alloc;
29001104a885SDavid Sterba 	}
29011104a885SDavid Sterba 
29021104a885SDavid Sterba 	/*
29031104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
29041104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
29051104a885SDavid Sterba 	 * the whole block of INFO_SIZE
29061104a885SDavid Sterba 	 */
29078f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
29088f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
29095f39d397SChris Mason 
2910fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
2911fbc6feaeSNikolay Borisov 
2912de37aa51SNikolay Borisov 	ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2913de37aa51SNikolay Borisov 		       BTRFS_FSID_SIZE));
2914de37aa51SNikolay Borisov 
29157239ff4bSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
2916de37aa51SNikolay Borisov 		ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
2917de37aa51SNikolay Borisov 				fs_info->super_copy->metadata_uuid,
2918de37aa51SNikolay Borisov 				BTRFS_FSID_SIZE));
29197239ff4bSNikolay Borisov 	}
29200b86a832SChris Mason 
2921fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
2922fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
2923fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
2924fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
2925fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
2926fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
2927fbc6feaeSNikolay Borisov 	}
2928fbc6feaeSNikolay Borisov 
2929fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2930fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
2931de37aa51SNikolay Borisov 
2932069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
29331104a885SDavid Sterba 	if (ret) {
293405135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
29351104a885SDavid Sterba 		err = -EINVAL;
2936141386e1SJosef Bacik 		goto fail_alloc;
29371104a885SDavid Sterba 	}
29381104a885SDavid Sterba 
29390f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
2940141386e1SJosef Bacik 		goto fail_alloc;
29410f7d52f4SChris Mason 
2942acce952bSliubo 	/* check FS state, whether FS is broken. */
294387533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
294487533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2945acce952bSliubo 
294675e7cb7fSLiu Bo 	/*
294775e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
294875e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
294975e7cb7fSLiu Bo 	 */
295075e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
295175e7cb7fSLiu Bo 
29522ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
29532b82032cSYan Zheng 	if (ret) {
29542b82032cSYan Zheng 		err = ret;
2955141386e1SJosef Bacik 		goto fail_alloc;
29562b82032cSYan Zheng 	}
2957dfe25020SChris Mason 
2958f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2959f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2960f2b636e8SJosef Bacik 	if (features) {
296105135f59SDavid Sterba 		btrfs_err(fs_info,
296205135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
2963c1c9ff7cSGeert Uytterhoeven 		    features);
2964f2b636e8SJosef Bacik 		err = -EINVAL;
2965141386e1SJosef Bacik 		goto fail_alloc;
2966f2b636e8SJosef Bacik 	}
2967f2b636e8SJosef Bacik 
29685d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
29695d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
29700b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2971a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
29725c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
29735c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2974727011e0SChris Mason 
29753173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
297605135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
29773173a18fSJosef Bacik 
2978727011e0SChris Mason 	/*
2979727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2980727011e0SChris Mason 	 * they are bigger than the page size
2981727011e0SChris Mason 	 */
298209cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2983727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
298405135f59SDavid Sterba 			btrfs_info(fs_info,
298505135f59SDavid Sterba 				"flagging fs with big metadata feature");
2986727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2987727011e0SChris Mason 	}
2988727011e0SChris Mason 
2989bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2990bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2991b7f67055SChandan Rajendra 	stripesize = sectorsize;
2992707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2993963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2994bc3f116fSChris Mason 
2995da17066cSJeff Mahoney 	/* Cache block sizes */
2996da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
2997da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
2998da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
2999da17066cSJeff Mahoney 
3000bc3f116fSChris Mason 	/*
3001bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3002bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3003bc3f116fSChris Mason 	 */
3004bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3005707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
300605135f59SDavid Sterba 		btrfs_err(fs_info,
300705135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
300805135f59SDavid Sterba 			nodesize, sectorsize);
3009141386e1SJosef Bacik 		goto fail_alloc;
3010bc3f116fSChris Mason 	}
3011bc3f116fSChris Mason 
3012ceda0864SMiao Xie 	/*
3013ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3014ceda0864SMiao Xie 	 * update the flag.
3015ceda0864SMiao Xie 	 */
30165d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
30175d4f98a2SYan Zheng 
3018f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3019f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3020bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
302105135f59SDavid Sterba 		btrfs_err(fs_info,
302205135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3023c1c9ff7cSGeert Uytterhoeven 		       features);
3024f2b636e8SJosef Bacik 		err = -EINVAL;
3025141386e1SJosef Bacik 		goto fail_alloc;
3026f2b636e8SJosef Bacik 	}
302761d92c32SChris Mason 
30282a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
30292a458198SEric Sandeen 	if (ret) {
30302a458198SEric Sandeen 		err = ret;
30310dc3b84aSJosef Bacik 		goto fail_sb_buffer;
30320dc3b84aSJosef Bacik 	}
30334543df7eSChris Mason 
30349e11ceeeSJan Kara 	sb->s_bdi->congested_fn = btrfs_congested_fn;
30359e11ceeeSJan Kara 	sb->s_bdi->congested_data = fs_info;
30369e11ceeeSJan Kara 	sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
3037b5420237SNikolay Borisov 	sb->s_bdi->ra_pages = VM_READAHEAD_PAGES;
30389e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
30399e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
30404575c9ccSChris Mason 
3041a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3042a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3043de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3044db94535dSChris Mason 
3045925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
30466bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3047925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
304884eed90fSChris Mason 	if (ret) {
304905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
30505d4f98a2SYan Zheng 		goto fail_sb_buffer;
305184eed90fSChris Mason 	}
30520b86a832SChris Mason 
305384234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3054581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
30550b86a832SChris Mason 
30562ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
30570b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
3058581c1760SQu Wenruo 					   generation, level, NULL);
305964c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
306064c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
306105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3062e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3063e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
306495ab1f64SZhao Lei 		chunk_root->node = NULL;
3065af31f5e5SChris Mason 		goto fail_tree_roots;
306683121942SDavid Woodhouse 	}
30675d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
30685d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
30690b86a832SChris Mason 
3070e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3071c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3072c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3073e17cade2SChris Mason 
30745b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
30752b82032cSYan Zheng 	if (ret) {
307605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3077af31f5e5SChris Mason 		goto fail_tree_roots;
30782b82032cSYan Zheng 	}
30790b86a832SChris Mason 
30808dabb742SStefan Behrens 	/*
30819b99b115SAnand Jain 	 * Keep the devid that is marked to be the target device for the
30829b99b115SAnand Jain 	 * device replace procedure
30838dabb742SStefan Behrens 	 */
30849b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 0);
3085dfe25020SChris Mason 
3086a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
308705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3088a6b0d5c8SChris Mason 		goto fail_tree_roots;
3089a6b0d5c8SChris Mason 	}
3090a6b0d5c8SChris Mason 
3091b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
30924bbcaa64SEric Sandeen 	if (ret)
3093b8522a1eSNikolay Borisov 		goto fail_tree_roots;
30948929ecfaSYan, Zheng 
309575ec1db8SJosef Bacik 	/*
309675ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
309775ec1db8SJosef Bacik 	 * check the generation here so we can set the
309875ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
309975ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
310075ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
310175ec1db8SJosef Bacik 	 * even though it was perfectly fine.
310275ec1db8SJosef Bacik 	 */
310375ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
310475ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
310575ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
310675ec1db8SJosef Bacik 
3107cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3108cf90d884SQu Wenruo 	if (ret) {
3109cf90d884SQu Wenruo 		btrfs_err(fs_info,
3110cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3111cf90d884SQu Wenruo 			  ret);
3112cf90d884SQu Wenruo 		goto fail_block_groups;
3113cf90d884SQu Wenruo 	}
311468310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
311568310a5eSIlya Dryomov 	if (ret) {
311605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
311768310a5eSIlya Dryomov 		goto fail_block_groups;
311868310a5eSIlya Dryomov 	}
311968310a5eSIlya Dryomov 
3120733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3121733f4fbbSStefan Behrens 	if (ret) {
312205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3123733f4fbbSStefan Behrens 		goto fail_block_groups;
3124733f4fbbSStefan Behrens 	}
3125733f4fbbSStefan Behrens 
31268dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
31278dabb742SStefan Behrens 	if (ret) {
312805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
31298dabb742SStefan Behrens 		goto fail_block_groups;
31308dabb742SStefan Behrens 	}
31318dabb742SStefan Behrens 
31329b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 1);
31338dabb742SStefan Behrens 
3134c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3135b7c35e81SAnand Jain 	if (ret) {
313605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
313705135f59SDavid Sterba 				ret);
3138b7c35e81SAnand Jain 		goto fail_block_groups;
3139b7c35e81SAnand Jain 	}
3140b7c35e81SAnand Jain 
314196f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
31425ac1d209SJeff Mahoney 	if (ret) {
314305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3144b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
31455ac1d209SJeff Mahoney 	}
31465ac1d209SJeff Mahoney 
3147c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3148c59021f8Sliubo 	if (ret) {
314905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
31502365dd3cSAnand Jain 		goto fail_sysfs;
3151c59021f8Sliubo 	}
3152c59021f8Sliubo 
31535b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
31541b1d1f66SJosef Bacik 	if (ret) {
315505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
31562365dd3cSAnand Jain 		goto fail_sysfs;
31571b1d1f66SJosef Bacik 	}
31584330e183SQu Wenruo 
31596528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
316005135f59SDavid Sterba 		btrfs_warn(fs_info,
316152042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
31622365dd3cSAnand Jain 		goto fail_sysfs;
3163292fd7fcSStefan Behrens 	}
31649078a3e1SChris Mason 
3165a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3166a74a4b97SChris Mason 					       "btrfs-cleaner");
316757506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
31682365dd3cSAnand Jain 		goto fail_sysfs;
3169a74a4b97SChris Mason 
3170a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3171a74a4b97SChris Mason 						   tree_root,
3172a74a4b97SChris Mason 						   "btrfs-transaction");
317357506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
31743f157a2fSChris Mason 		goto fail_cleaner;
3175a74a4b97SChris Mason 
3176583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3177c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3178583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3179c289811cSChris Mason 	}
3180c289811cSChris Mason 
3181572d9ab7SDavid Sterba 	/*
318201327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3183572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3184572d9ab7SDavid Sterba 	 */
3185572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
31863818aea2SQu Wenruo 
318721adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
31880b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
31892ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
31900b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
319121adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
319221adbd5cSStefan Behrens 				    1 : 0,
319321adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
319421adbd5cSStefan Behrens 		if (ret)
319505135f59SDavid Sterba 			btrfs_warn(fs_info,
319605135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
319705135f59SDavid Sterba 				ret);
319821adbd5cSStefan Behrens 	}
319921adbd5cSStefan Behrens #endif
3200bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3201bcef60f2SArne Jansen 	if (ret)
3202bcef60f2SArne Jansen 		goto fail_trans_kthread;
320321adbd5cSStefan Behrens 
3204fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3205fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3206fd708b81SJosef Bacik 
320796da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
320896da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
32090b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3210e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
321163443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
321279787eaaSJeff Mahoney 		if (ret) {
321363443bf5SEric Sandeen 			err = ret;
321428c16cbbSWang Shilong 			goto fail_qgroup;
3215e556ce2cSYan Zheng 		}
3216e02119d5SChris Mason 	}
32171a40e23bSZheng Yan 
32186bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
321979787eaaSJeff Mahoney 	if (ret)
322028c16cbbSWang Shilong 		goto fail_qgroup;
322176dda93cSYan, Zheng 
3222bc98a42cSDavid Howells 	if (!sb_rdonly(sb)) {
3223d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
322444c44af2SIlya Dryomov 		if (ret)
322528c16cbbSWang Shilong 			goto fail_qgroup;
322690c711abSZygo Blaxell 
322790c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
32285d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
322990c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
3230d7ce5843SMiao Xie 		if (ret < 0) {
323105135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
323205135f59SDavid Sterba 					ret);
3233d7ce5843SMiao Xie 			err = -EINVAL;
3234bcef60f2SArne Jansen 			goto fail_qgroup;
3235d7ce5843SMiao Xie 		}
32367c2ca468SChris Mason 	}
32371a40e23bSZheng Yan 
32383de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
32393de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
3240cb517eabSMiao Xie 	location.offset = 0;
32413de4586cSChris Mason 
32423619c94fSJosef Bacik 	fs_info->fs_root = btrfs_get_fs_root(fs_info, &location, true);
32433140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
32443140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3245f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3246315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3247bcef60f2SArne Jansen 		goto fail_qgroup;
32483140c9a3SDan Carpenter 	}
3249c289811cSChris Mason 
3250bc98a42cSDavid Howells 	if (sb_rdonly(sb))
32512b6ba629SIlya Dryomov 		return 0;
32522b6ba629SIlya Dryomov 
3253f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3254f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32556675df31SOmar Sandoval 		clear_free_space_tree = 1;
32566675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
32576675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
32586675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
32596675df31SOmar Sandoval 		clear_free_space_tree = 1;
32606675df31SOmar Sandoval 	}
32616675df31SOmar Sandoval 
32626675df31SOmar Sandoval 	if (clear_free_space_tree) {
3263f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3264f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3265f8d468a1SOmar Sandoval 		if (ret) {
3266f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3267f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
32686bccf3abSJeff Mahoney 			close_ctree(fs_info);
3269f8d468a1SOmar Sandoval 			return ret;
3270f8d468a1SOmar Sandoval 		}
3271f8d468a1SOmar Sandoval 	}
3272f8d468a1SOmar Sandoval 
32730b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3274511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
327505135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3276511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3277511711afSChris Mason 		if (ret) {
327805135f59SDavid Sterba 			btrfs_warn(fs_info,
327905135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
32806bccf3abSJeff Mahoney 			close_ctree(fs_info);
3281511711afSChris Mason 			return ret;
3282511711afSChris Mason 		}
3283511711afSChris Mason 	}
3284511711afSChris Mason 
3285e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
32862b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
32872b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
32882b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
32896bccf3abSJeff Mahoney 		close_ctree(fs_info);
32902b6ba629SIlya Dryomov 		return ret;
32912b6ba629SIlya Dryomov 	}
3292e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
329359641015SIlya Dryomov 
32942b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
32952b6ba629SIlya Dryomov 	if (ret) {
329605135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
32976bccf3abSJeff Mahoney 		close_ctree(fs_info);
32982b6ba629SIlya Dryomov 		return ret;
3299e3acc2a6SJosef Bacik 	}
3300e3acc2a6SJosef Bacik 
33018dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
33028dabb742SStefan Behrens 	if (ret) {
330305135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
33046bccf3abSJeff Mahoney 		close_ctree(fs_info);
33058dabb742SStefan Behrens 		return ret;
33068dabb742SStefan Behrens 	}
33078dabb742SStefan Behrens 
3308b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3309b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3310b382a324SJan Schmidt 
33114bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
331205135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3313f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3314f7a81ea4SStefan Behrens 		if (ret) {
331505135f59SDavid Sterba 			btrfs_warn(fs_info,
331605135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
33176bccf3abSJeff Mahoney 			close_ctree(fs_info);
3318f7a81ea4SStefan Behrens 			return ret;
3319f7a81ea4SStefan Behrens 		}
33200b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
33214bbcaa64SEric Sandeen 		   fs_info->generation !=
33224bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
332305135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
332470f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
332570f80175SStefan Behrens 		if (ret) {
332605135f59SDavid Sterba 			btrfs_warn(fs_info,
332705135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
33286bccf3abSJeff Mahoney 			close_ctree(fs_info);
332970f80175SStefan Behrens 			return ret;
333070f80175SStefan Behrens 		}
3331f7a81ea4SStefan Behrens 	}
3332afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
333347ab2a6cSJosef Bacik 
33348dcddfa0SQu Wenruo 	/*
33358dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
33368dcddfa0SQu Wenruo 	 * no need to keep the flag
33378dcddfa0SQu Wenruo 	 */
33388dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
33398dcddfa0SQu Wenruo 
3340ad2b2c80SAl Viro 	return 0;
334139279cc3SChris Mason 
3342bcef60f2SArne Jansen fail_qgroup:
3343bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
33447c2ca468SChris Mason fail_trans_kthread:
33457c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
33462ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3347faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
33483f157a2fSChris Mason fail_cleaner:
3349a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
33507c2ca468SChris Mason 
33517c2ca468SChris Mason 	/*
33527c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
33537c2ca468SChris Mason 	 * kthreads
33547c2ca468SChris Mason 	 */
33557c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
33567c2ca468SChris Mason 
33572365dd3cSAnand Jain fail_sysfs:
33586618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
33592365dd3cSAnand Jain 
3360b7c35e81SAnand Jain fail_fsdev_sysfs:
3361b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3362b7c35e81SAnand Jain 
33631b1d1f66SJosef Bacik fail_block_groups:
336454067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3365af31f5e5SChris Mason 
3366af31f5e5SChris Mason fail_tree_roots:
33674273eaffSAnand Jain 	free_root_pointers(fs_info, true);
33682b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3369af31f5e5SChris Mason 
337039279cc3SChris Mason fail_sb_buffer:
33717abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
33725cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
337316cdcec7SMiao Xie fail_alloc:
3374586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3375586e46e2SIlya Dryomov 
33764543df7eSChris Mason 	iput(fs_info->btree_inode);
33777e662854SQinghuang Feng fail:
3378586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3379ad2b2c80SAl Viro 	return err;
3380eb60ceacSChris Mason }
3381663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3382eb60ceacSChris Mason 
3383314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3384f2984462SChris Mason {
3385314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3386314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3387314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3388314b6dd0SJohannes Thumshirn 	struct page *page;
3389442a4f63SStefan Behrens 
3390314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3391314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3392314b6dd0SJohannes Thumshirn 
3393314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3394fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3395314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3396314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3397314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3398314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3399314b6dd0SJohannes Thumshirn 			SetPageError(page);
3400314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3401314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3402314b6dd0SJohannes Thumshirn 		} else {
3403314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3404f2984462SChris Mason 		}
3405314b6dd0SJohannes Thumshirn 
3406314b6dd0SJohannes Thumshirn 		put_page(page);
3407314b6dd0SJohannes Thumshirn 		unlock_page(page);
3408314b6dd0SJohannes Thumshirn 	}
3409314b6dd0SJohannes Thumshirn 
3410314b6dd0SJohannes Thumshirn 	bio_put(bio);
3411f2984462SChris Mason }
3412f2984462SChris Mason 
34138f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
34148f32380dSJohannes Thumshirn 						   int copy_num)
341529c36d72SAnand Jain {
341629c36d72SAnand Jain 	struct btrfs_super_block *super;
34178f32380dSJohannes Thumshirn 	struct page *page;
341829c36d72SAnand Jain 	u64 bytenr;
34198f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
342029c36d72SAnand Jain 
342129c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
342229c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
34238f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
342429c36d72SAnand Jain 
34258f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
34268f32380dSJohannes Thumshirn 	if (IS_ERR(page))
34278f32380dSJohannes Thumshirn 		return ERR_CAST(page);
342829c36d72SAnand Jain 
34298f32380dSJohannes Thumshirn 	super = page_address(page);
343029c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
343129c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
34328f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
34338f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
343429c36d72SAnand Jain 	}
343529c36d72SAnand Jain 
34368f32380dSJohannes Thumshirn 	return super;
343729c36d72SAnand Jain }
343829c36d72SAnand Jain 
343929c36d72SAnand Jain 
34408f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3441a512bbf8SYan Zheng {
34428f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3443a512bbf8SYan Zheng 	int i;
3444a512bbf8SYan Zheng 	u64 transid = 0;
3445a512bbf8SYan Zheng 
3446a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3447a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3448a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3449a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3450a512bbf8SYan Zheng 	 */
3451a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
34528f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
34538f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3454a512bbf8SYan Zheng 			continue;
3455a512bbf8SYan Zheng 
3456a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
34578f32380dSJohannes Thumshirn 			if (latest)
34588f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
34598f32380dSJohannes Thumshirn 
34608f32380dSJohannes Thumshirn 			latest = super;
3461a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3462a512bbf8SYan Zheng 		}
3463a512bbf8SYan Zheng 	}
346492fc03fbSAnand Jain 
34658f32380dSJohannes Thumshirn 	return super;
3466a512bbf8SYan Zheng }
3467a512bbf8SYan Zheng 
34684eedeb75SHisashi Hifumi /*
3469abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3470314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
34714eedeb75SHisashi Hifumi  *
3472abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3473abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3474abbb3b8eSDavid Sterba  * same for write and wait phases.
34754eedeb75SHisashi Hifumi  *
3476314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
34774eedeb75SHisashi Hifumi  */
3478a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3479abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3480a512bbf8SYan Zheng {
3481d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3482314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3483d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3484a512bbf8SYan Zheng 	int i;
3485a512bbf8SYan Zheng 	int errors = 0;
3486a512bbf8SYan Zheng 	u64 bytenr;
3487a512bbf8SYan Zheng 
3488a512bbf8SYan Zheng 	if (max_mirrors == 0)
3489a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3490a512bbf8SYan Zheng 
3491d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3492d5178578SJohannes Thumshirn 
3493a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3494314b6dd0SJohannes Thumshirn 		struct page *page;
3495314b6dd0SJohannes Thumshirn 		struct bio *bio;
3496314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3497314b6dd0SJohannes Thumshirn 
3498a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3499935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3500935e5cc9SMiao Xie 		    device->commit_total_bytes)
3501a512bbf8SYan Zheng 			break;
3502a512bbf8SYan Zheng 
3503a512bbf8SYan Zheng 		btrfs_set_super_bytenr(sb, bytenr);
3504a512bbf8SYan Zheng 
3505fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3506fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3507fd08001fSEric Biggers 				    sb->csum);
3508a512bbf8SYan Zheng 
3509314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3510314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3511314b6dd0SJohannes Thumshirn 		if (!page) {
3512fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3513314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3514f14d104dSDavid Sterba 			    bytenr);
3515634554dcSJosef Bacik 			errors++;
3516634554dcSJosef Bacik 			continue;
3517634554dcSJosef Bacik 		}
3518634554dcSJosef Bacik 
3519314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3520314b6dd0SJohannes Thumshirn 		get_page(page);
3521a512bbf8SYan Zheng 
3522314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3523314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3524a512bbf8SYan Zheng 
3525387125fcSChris Mason 		/*
3526314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3527314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3528314b6dd0SJohannes Thumshirn 		 * checking.
3529387125fcSChris Mason 		 */
3530314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3531314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3532314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3533314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3534314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3535314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3536314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3537314b6dd0SJohannes Thumshirn 
3538314b6dd0SJohannes Thumshirn 		/*
3539314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3540314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3541314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3542314b6dd0SJohannes Thumshirn 		 */
3543314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
35441b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3545314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3546314b6dd0SJohannes Thumshirn 
3547314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
3548a512bbf8SYan Zheng 	}
3549a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3550a512bbf8SYan Zheng }
3551a512bbf8SYan Zheng 
3552387125fcSChris Mason /*
3553abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3554abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3555abbb3b8eSDavid Sterba  *
3556314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3557abbb3b8eSDavid Sterba  * date.
3558abbb3b8eSDavid Sterba  */
3559abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3560abbb3b8eSDavid Sterba {
3561abbb3b8eSDavid Sterba 	int i;
3562abbb3b8eSDavid Sterba 	int errors = 0;
3563b6a535faSHoward McLauchlan 	bool primary_failed = false;
3564abbb3b8eSDavid Sterba 	u64 bytenr;
3565abbb3b8eSDavid Sterba 
3566abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3567abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3568abbb3b8eSDavid Sterba 
3569abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3570314b6dd0SJohannes Thumshirn 		struct page *page;
3571314b6dd0SJohannes Thumshirn 
3572abbb3b8eSDavid Sterba 		bytenr = btrfs_sb_offset(i);
3573abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3574abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3575abbb3b8eSDavid Sterba 			break;
3576abbb3b8eSDavid Sterba 
3577314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3578314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3579314b6dd0SJohannes Thumshirn 		if (!page) {
3580abbb3b8eSDavid Sterba 			errors++;
3581b6a535faSHoward McLauchlan 			if (i == 0)
3582b6a535faSHoward McLauchlan 				primary_failed = true;
3583abbb3b8eSDavid Sterba 			continue;
3584abbb3b8eSDavid Sterba 		}
3585314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3586314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3587314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3588abbb3b8eSDavid Sterba 			errors++;
3589b6a535faSHoward McLauchlan 			if (i == 0)
3590b6a535faSHoward McLauchlan 				primary_failed = true;
3591b6a535faSHoward McLauchlan 		}
3592abbb3b8eSDavid Sterba 
3593314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3594314b6dd0SJohannes Thumshirn 		put_page(page);
3595abbb3b8eSDavid Sterba 
3596314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3597314b6dd0SJohannes Thumshirn 		put_page(page);
3598abbb3b8eSDavid Sterba 	}
3599abbb3b8eSDavid Sterba 
3600b6a535faSHoward McLauchlan 	/* log error, force error return */
3601b6a535faSHoward McLauchlan 	if (primary_failed) {
3602b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3603b6a535faSHoward McLauchlan 			  device->devid);
3604b6a535faSHoward McLauchlan 		return -1;
3605b6a535faSHoward McLauchlan 	}
3606b6a535faSHoward McLauchlan 
3607abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3608abbb3b8eSDavid Sterba }
3609abbb3b8eSDavid Sterba 
3610abbb3b8eSDavid Sterba /*
3611387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3612387125fcSChris Mason  * for the barrier when it is done
3613387125fcSChris Mason  */
36144246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3615387125fcSChris Mason {
3616387125fcSChris Mason 	complete(bio->bi_private);
3617387125fcSChris Mason }
3618387125fcSChris Mason 
3619387125fcSChris Mason /*
36204fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
36214fc6441aSAnand Jain  * done in the waiting counterpart.
3622387125fcSChris Mason  */
36234fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3624387125fcSChris Mason {
3625c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3626e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3627387125fcSChris Mason 
3628c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
36294fc6441aSAnand Jain 		return;
3630387125fcSChris Mason 
3631e0ae9994SDavid Sterba 	bio_reset(bio);
3632387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
363374d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
36348d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3635387125fcSChris Mason 	init_completion(&device->flush_wait);
3636387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3637387125fcSChris Mason 
363843a01111SLu Fengqi 	btrfsic_submit_bio(bio);
36391c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
36404fc6441aSAnand Jain }
3641387125fcSChris Mason 
36424fc6441aSAnand Jain /*
36434fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
36444fc6441aSAnand Jain  */
36458c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
36464fc6441aSAnand Jain {
36474fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
36484fc6441aSAnand Jain 
36491c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
365058efbc9fSOmar Sandoval 		return BLK_STS_OK;
36514fc6441aSAnand Jain 
36521c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
36532980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
36544fc6441aSAnand Jain 
36558c27cb35SLinus Torvalds 	return bio->bi_status;
3656387125fcSChris Mason }
3657387125fcSChris Mason 
3658d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3659401b41e5SAnand Jain {
36606528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3661401b41e5SAnand Jain 		return -EIO;
3662387125fcSChris Mason 	return 0;
3663387125fcSChris Mason }
3664387125fcSChris Mason 
3665387125fcSChris Mason /*
3666387125fcSChris Mason  * send an empty flush down to each device in parallel,
3667387125fcSChris Mason  * then wait for them
3668387125fcSChris Mason  */
3669387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3670387125fcSChris Mason {
3671387125fcSChris Mason 	struct list_head *head;
3672387125fcSChris Mason 	struct btrfs_device *dev;
36735af3e8ccSStefan Behrens 	int errors_wait = 0;
36744e4cbee9SChristoph Hellwig 	blk_status_t ret;
3675387125fcSChris Mason 
36761538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3677387125fcSChris Mason 	/* send down all the barriers */
3678387125fcSChris Mason 	head = &info->fs_devices->devices;
36791538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3680e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3681f88ba6a2SHidetoshi Seto 			continue;
3682cea7c8bfSAnand Jain 		if (!dev->bdev)
3683387125fcSChris Mason 			continue;
3684e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3685ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3686387125fcSChris Mason 			continue;
3687387125fcSChris Mason 
36884fc6441aSAnand Jain 		write_dev_flush(dev);
368958efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3690387125fcSChris Mason 	}
3691387125fcSChris Mason 
3692387125fcSChris Mason 	/* wait for all the barriers */
36931538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3694e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3695f88ba6a2SHidetoshi Seto 			continue;
3696387125fcSChris Mason 		if (!dev->bdev) {
36975af3e8ccSStefan Behrens 			errors_wait++;
3698387125fcSChris Mason 			continue;
3699387125fcSChris Mason 		}
3700e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3701ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3702387125fcSChris Mason 			continue;
3703387125fcSChris Mason 
37044fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3705401b41e5SAnand Jain 		if (ret) {
3706401b41e5SAnand Jain 			dev->last_flush_error = ret;
370766b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
370866b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
37095af3e8ccSStefan Behrens 			errors_wait++;
3710387125fcSChris Mason 		}
3711401b41e5SAnand Jain 	}
3712401b41e5SAnand Jain 
3713cea7c8bfSAnand Jain 	if (errors_wait) {
3714401b41e5SAnand Jain 		/*
3715401b41e5SAnand Jain 		 * At some point we need the status of all disks
3716401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3717401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3718401b41e5SAnand Jain 		 */
3719d10b82feSQu Wenruo 		return check_barrier_error(info);
3720401b41e5SAnand Jain 	}
3721387125fcSChris Mason 	return 0;
3722387125fcSChris Mason }
3723387125fcSChris Mason 
3724943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3725943c6e99SZhao Lei {
37268789f4feSZhao Lei 	int raid_type;
37278789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3728943c6e99SZhao Lei 
37298789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
37308789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
37318c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
37328789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
37338789f4feSZhao Lei 				    tolerated_failures);
3734943c6e99SZhao Lei 
37358789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
37368789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
37378789f4feSZhao Lei 			continue;
373841a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
37398789f4feSZhao Lei 			continue;
37408c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
37418789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
37428789f4feSZhao Lei 				    tolerated_failures);
37438789f4feSZhao Lei 	}
3744943c6e99SZhao Lei 
37458789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3746ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
37478789f4feSZhao Lei 		min_tolerated = 0;
37488789f4feSZhao Lei 	}
37498789f4feSZhao Lei 
37508789f4feSZhao Lei 	return min_tolerated;
3751943c6e99SZhao Lei }
3752943c6e99SZhao Lei 
3753eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3754f2984462SChris Mason {
3755e5e9a520SChris Mason 	struct list_head *head;
3756f2984462SChris Mason 	struct btrfs_device *dev;
3757a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3758f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3759f2984462SChris Mason 	int ret;
3760f2984462SChris Mason 	int do_barriers;
3761a236aed1SChris Mason 	int max_errors;
3762a236aed1SChris Mason 	int total_errors = 0;
3763a061fc8dSChris Mason 	u64 flags;
3764f2984462SChris Mason 
37650b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3766fed3b381SLiu Bo 
3767fed3b381SLiu Bo 	/*
3768fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3769fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3770fed3b381SLiu Bo 	 * been consistent on disk.
3771fed3b381SLiu Bo 	 */
3772fed3b381SLiu Bo 	if (max_mirrors == 0)
37730b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3774f2984462SChris Mason 
37750b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3776a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3777e5e9a520SChris Mason 
37780b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
37790b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
37800b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3781387125fcSChris Mason 
37825af3e8ccSStefan Behrens 	if (do_barriers) {
37830b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
37845af3e8ccSStefan Behrens 		if (ret) {
37855af3e8ccSStefan Behrens 			mutex_unlock(
37860b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
37870b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
37885af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
37895af3e8ccSStefan Behrens 			return ret;
37905af3e8ccSStefan Behrens 		}
37915af3e8ccSStefan Behrens 	}
3792387125fcSChris Mason 
37931538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3794dfe25020SChris Mason 		if (!dev->bdev) {
3795dfe25020SChris Mason 			total_errors++;
3796dfe25020SChris Mason 			continue;
3797dfe25020SChris Mason 		}
3798e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3799ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3800dfe25020SChris Mason 			continue;
3801dfe25020SChris Mason 
38022b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3803a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3804a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
38057df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3806935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3807ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3808ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3809a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3810a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3811a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3812a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
38137239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
38147239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
3815a512bbf8SYan Zheng 
3816a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3817a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3818f2984462SChris Mason 
381975cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
382075cb857dSQu Wenruo 		if (ret < 0) {
382175cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
382275cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
382375cb857dSQu Wenruo 				"unexpected superblock corruption detected");
382475cb857dSQu Wenruo 			return -EUCLEAN;
382575cb857dSQu Wenruo 		}
382675cb857dSQu Wenruo 
3827abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3828a236aed1SChris Mason 		if (ret)
3829a236aed1SChris Mason 			total_errors++;
3830f2984462SChris Mason 	}
3831a236aed1SChris Mason 	if (total_errors > max_errors) {
38320b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3833d397712bSChris Mason 			  total_errors);
38340b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
383579787eaaSJeff Mahoney 
38369d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
38370b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38380b246afaSJeff Mahoney 				      "%d errors while writing supers",
38390b246afaSJeff Mahoney 				      total_errors);
38409d565ba4SStefan Behrens 		return -EIO;
3841a236aed1SChris Mason 	}
3842f2984462SChris Mason 
3843a512bbf8SYan Zheng 	total_errors = 0;
38441538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3845dfe25020SChris Mason 		if (!dev->bdev)
3846dfe25020SChris Mason 			continue;
3847e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3848ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3849dfe25020SChris Mason 			continue;
3850dfe25020SChris Mason 
3851abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3852a512bbf8SYan Zheng 		if (ret)
38531259ab75SChris Mason 			total_errors++;
3854f2984462SChris Mason 	}
38550b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3856a236aed1SChris Mason 	if (total_errors > max_errors) {
38570b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38580b246afaSJeff Mahoney 				      "%d errors while writing supers",
38590b246afaSJeff Mahoney 				      total_errors);
386079787eaaSJeff Mahoney 		return -EIO;
3861a236aed1SChris Mason 	}
3862f2984462SChris Mason 	return 0;
3863f2984462SChris Mason }
3864f2984462SChris Mason 
3865cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3866cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3867cb517eabSMiao Xie 				  struct btrfs_root *root)
38682619ba1fSChris Mason {
38694785e24fSJosef Bacik 	bool drop_ref = false;
38704785e24fSJosef Bacik 
38714df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
38722619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
38732619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
3874af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
38754785e24fSJosef Bacik 		drop_ref = true;
38764df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
387776dda93cSYan, Zheng 
38781c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3879ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
38801c1ea4f7SLiu Bo 		if (root->reloc_root) {
388100246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
38821c1ea4f7SLiu Bo 			root->reloc_root = NULL;
38831c1ea4f7SLiu Bo 		}
38841c1ea4f7SLiu Bo 	}
38853321719eSLiu Bo 
3886faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3887581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3888faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3889581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
38900e996e7fSJosef Bacik 	if (root->ino_cache_inode) {
38910e996e7fSJosef Bacik 		iput(root->ino_cache_inode);
38920e996e7fSJosef Bacik 		root->ino_cache_inode = NULL;
38930e996e7fSJosef Bacik 	}
38944785e24fSJosef Bacik 	if (drop_ref)
389500246528SJosef Bacik 		btrfs_put_root(root);
38962619ba1fSChris Mason }
38972619ba1fSChris Mason 
3898c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3899c146afadSYan Zheng {
3900c146afadSYan Zheng 	u64 root_objectid = 0;
3901c146afadSYan Zheng 	struct btrfs_root *gang[8];
390265d33fd7SQu Wenruo 	int i = 0;
390365d33fd7SQu Wenruo 	int err = 0;
390465d33fd7SQu Wenruo 	unsigned int ret = 0;
3905c146afadSYan Zheng 
3906c146afadSYan Zheng 	while (1) {
3907efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
3908c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3909c146afadSYan Zheng 					     (void **)gang, root_objectid,
3910c146afadSYan Zheng 					     ARRAY_SIZE(gang));
391165d33fd7SQu Wenruo 		if (!ret) {
3912efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
3913c146afadSYan Zheng 			break;
391465d33fd7SQu Wenruo 		}
39155d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
391666b4ffd1SJosef Bacik 
391765d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
391865d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
391965d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
392065d33fd7SQu Wenruo 				gang[i] = NULL;
392165d33fd7SQu Wenruo 				continue;
392265d33fd7SQu Wenruo 			}
392365d33fd7SQu Wenruo 			/* grab all the search result for later use */
392400246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
392565d33fd7SQu Wenruo 		}
3926efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
392765d33fd7SQu Wenruo 
392865d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
392965d33fd7SQu Wenruo 			if (!gang[i])
393065d33fd7SQu Wenruo 				continue;
3931c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
393266b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
393366b4ffd1SJosef Bacik 			if (err)
393465d33fd7SQu Wenruo 				break;
393500246528SJosef Bacik 			btrfs_put_root(gang[i]);
3936c146afadSYan Zheng 		}
3937c146afadSYan Zheng 		root_objectid++;
3938c146afadSYan Zheng 	}
393965d33fd7SQu Wenruo 
394065d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
394165d33fd7SQu Wenruo 	for (; i < ret; i++) {
394265d33fd7SQu Wenruo 		if (gang[i])
394300246528SJosef Bacik 			btrfs_put_root(gang[i]);
394465d33fd7SQu Wenruo 	}
394565d33fd7SQu Wenruo 	return err;
3946c146afadSYan Zheng }
3947c146afadSYan Zheng 
39486bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3949c146afadSYan Zheng {
39506bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3951c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3952c146afadSYan Zheng 
39530b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
39542ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
39550b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
39560b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
3957c71bf099SYan, Zheng 
3958c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
39590b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
39600b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
3961c71bf099SYan, Zheng 
39627a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
39633612b495STsutomu Itoh 	if (IS_ERR(trans))
39643612b495STsutomu Itoh 		return PTR_ERR(trans);
39653a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
3966c146afadSYan Zheng }
3967c146afadSYan Zheng 
3968b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
3969eb60ceacSChris Mason {
3970c146afadSYan Zheng 	int ret;
3971e089f05cSChris Mason 
3972afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3973d6fd0ae2SOmar Sandoval 	/*
3974d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
3975d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
3976d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
3977d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
3978d6fd0ae2SOmar Sandoval 	 */
3979d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
3980a2135011SChris Mason 
39817343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
3982d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
39837343dd61SJustin Maggard 
3984803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3985803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3986803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3987803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3988803b2f54SStefan Behrens 
3989837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3990aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3991837d5b6eSIlya Dryomov 
39928dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
39938dabb742SStefan Behrens 
3994aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
39954cb5300bSChris Mason 
39964cb5300bSChris Mason 	/* wait for any defraggers to finish */
39974cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
39984cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
39994cb5300bSChris Mason 
40004cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
400126176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
40024cb5300bSChris Mason 
400321c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
400421c7e756SMiao Xie 
4005b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4006b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4007b0643e59SDennis Zhou 
4008bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4009e44163e1SJeff Mahoney 		/*
4010d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4011d6fd0ae2SOmar Sandoval 		 * unused block groups.
4012e44163e1SJeff Mahoney 		 */
40130b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4014e44163e1SJeff Mahoney 
4015f0cc2cd7SFilipe Manana 		/*
4016f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4017f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4018f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4019f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4020f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4021f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4022f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4023f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4024f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4025f0cc2cd7SFilipe Manana 		 */
4026f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4027f0cc2cd7SFilipe Manana 
40286bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4029d397712bSChris Mason 		if (ret)
403004892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4031c146afadSYan Zheng 	}
4032ed2ff2cbSChris Mason 
4033af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4034af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
40352ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4036acce952bSliubo 
4037e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4038e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
40398929ecfaSYan, Zheng 
4040e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4041afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4042f25784b3SYan Zheng 
404304892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4044fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4045bcef60f2SArne Jansen 
4046963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
404704892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4048963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4049b0c68f8bSChris Mason 	}
405031153d81SYan Zheng 
40514297ff84SJosef Bacik 	if (percpu_counter_sum(&fs_info->dio_bytes))
40524297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
40534297ff84SJosef Bacik 			   percpu_counter_sum(&fs_info->dio_bytes));
40544297ff84SJosef Bacik 
40556618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4056b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
40575ac1d209SJeff Mahoney 
40581a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
40591a4319ccSLiu Bo 
4060de348ee0SWang Shilong 	/*
4061de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4062de348ee0SWang Shilong 	 * submit after we stopping all workers.
4063de348ee0SWang Shilong 	 */
4064de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
406596192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
406696192499SJosef Bacik 
4067afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
40684273eaffSAnand Jain 	free_root_pointers(fs_info, true);
40698c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
40709ad6b7bcSChris Mason 
40714e19443dSJosef Bacik 	/*
40724e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
40734e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
40744e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
40754e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
40764e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
40774e19443dSJosef Bacik 	 */
40784e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
40794e19443dSJosef Bacik 
408013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4081d6bfde87SChris Mason 
408221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
40830b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
40842ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
408521adbd5cSStefan Behrens #endif
408621adbd5cSStefan Behrens 
40870b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
408868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4089eb60ceacSChris Mason }
4090eb60ceacSChris Mason 
4091b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4092b9fab919SChris Mason 			  int atomic)
4093ccd467d6SChris Mason {
40941259ab75SChris Mason 	int ret;
4095727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
40961259ab75SChris Mason 
40970b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
40981259ab75SChris Mason 	if (!ret)
40991259ab75SChris Mason 		return ret;
41001259ab75SChris Mason 
41011259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4102b9fab919SChris Mason 				    parent_transid, atomic);
4103b9fab919SChris Mason 	if (ret == -EAGAIN)
4104b9fab919SChris Mason 		return ret;
41051259ab75SChris Mason 	return !ret;
41065f39d397SChris Mason }
41076702ed49SChris Mason 
41085f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
41095f39d397SChris Mason {
41100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
411106ea65a3SJosef Bacik 	struct btrfs_root *root;
41125f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4113b9473439SChris Mason 	int was_dirty;
4114b4ce94deSChris Mason 
411506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
411606ea65a3SJosef Bacik 	/*
411706ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
411852042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
411906ea65a3SJosef Bacik 	 * outside of the sanity tests.
412006ea65a3SJosef Bacik 	 */
4121b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
412206ea65a3SJosef Bacik 		return;
412306ea65a3SJosef Bacik #endif
412406ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
41250b246afaSJeff Mahoney 	fs_info = root->fs_info;
4126b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
41270b246afaSJeff Mahoney 	if (transid != fs_info->generation)
41285d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
41290b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
41300b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4131e2d84521SMiao Xie 	if (!was_dirty)
4132104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4133e2d84521SMiao Xie 					 buf->len,
41340b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
41351f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
413669fc6cbbSQu Wenruo 	/*
413769fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
413869fc6cbbSQu Wenruo 	 * but item data not updated.
413969fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
414069fc6cbbSQu Wenruo 	 */
414169fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4142cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4143a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
41441f21ef0aSFilipe Manana 		ASSERT(0);
41451f21ef0aSFilipe Manana 	}
41461f21ef0aSFilipe Manana #endif
4147eb60ceacSChris Mason }
4148eb60ceacSChris Mason 
41492ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4150b53d3f5dSLiu Bo 					int flush_delayed)
415135b7e476SChris Mason {
4152188de649SChris Mason 	/*
4153188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4154188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4155188de649SChris Mason 	 */
4156e2d84521SMiao Xie 	int ret;
4157d6bfde87SChris Mason 
41586933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4159d6bfde87SChris Mason 		return;
4160d6bfde87SChris Mason 
4161b53d3f5dSLiu Bo 	if (flush_delayed)
41622ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
416316cdcec7SMiao Xie 
4164d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4165d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4166d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4167e2d84521SMiao Xie 	if (ret > 0) {
41680b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
416916cdcec7SMiao Xie 	}
417016cdcec7SMiao Xie }
417116cdcec7SMiao Xie 
41722ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
417316cdcec7SMiao Xie {
41742ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
417535b7e476SChris Mason }
4176b53d3f5dSLiu Bo 
41772ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4178b53d3f5dSLiu Bo {
41792ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4180d6bfde87SChris Mason }
41816b80053dSChris Mason 
4182581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4183581c1760SQu Wenruo 		      struct btrfs_key *first_key)
41846b80053dSChris Mason {
41855ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4186581c1760SQu Wenruo 					      level, first_key);
41876b80053dSChris Mason }
41880da5468fSChris Mason 
41892ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4190acce952bSliubo {
4191fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4192fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4193fe816d0fSNikolay Borisov 
41940b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41952ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41960b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4197acce952bSliubo 
41980b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41990b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4200acce952bSliubo }
4201acce952bSliubo 
4202ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4203ef67963dSJosef Bacik {
4204ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4205ef67963dSJosef Bacik 	u64 root_objectid = 0;
4206ef67963dSJosef Bacik 	int ret;
4207ef67963dSJosef Bacik 
4208ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4209ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4210ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4211ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4212ef67963dSJosef Bacik 		int i;
4213ef67963dSJosef Bacik 
4214ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4215ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4216ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4217ef67963dSJosef Bacik 
4218ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4219ef67963dSJosef Bacik 			if (!gang[i])
4220ef67963dSJosef Bacik 				continue;
4221ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4222ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4223ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4224ef67963dSJosef Bacik 		}
4225ef67963dSJosef Bacik 		root_objectid++;
4226ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4227ef67963dSJosef Bacik 	}
4228ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4229ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4230ef67963dSJosef Bacik }
4231ef67963dSJosef Bacik 
4232143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4233acce952bSliubo {
4234acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4235acce952bSliubo 
4236199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4237779880efSJosef Bacik 	/*
4238779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4239779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4240779880efSJosef Bacik 	 */
4241199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4242779880efSJosef Bacik 			    root_extent_list)
4243779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4244199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4245199c2a9cSMiao Xie }
4246199c2a9cSMiao Xie 
4247199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4248199c2a9cSMiao Xie {
4249199c2a9cSMiao Xie 	struct btrfs_root *root;
4250199c2a9cSMiao Xie 	struct list_head splice;
4251199c2a9cSMiao Xie 
4252199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4253199c2a9cSMiao Xie 
4254199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4255199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4256199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4257199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4258199c2a9cSMiao Xie 					ordered_root);
42591de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
42601de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4261199c2a9cSMiao Xie 
42622a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4263199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4264199c2a9cSMiao Xie 
42652a85d9caSLiu Bo 		cond_resched();
42662a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4267199c2a9cSMiao Xie 	}
4268199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
426974d5d229SJosef Bacik 
427074d5d229SJosef Bacik 	/*
427174d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
427274d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
427374d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
427474d5d229SJosef Bacik 	 * actually get run and error out properly.
427574d5d229SJosef Bacik 	 */
427674d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4277acce952bSliubo }
4278acce952bSliubo 
427935a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
42802ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4281acce952bSliubo {
4282acce952bSliubo 	struct rb_node *node;
4283acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4284acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4285acce952bSliubo 	int ret = 0;
4286acce952bSliubo 
4287acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4288acce952bSliubo 
4289acce952bSliubo 	spin_lock(&delayed_refs->lock);
4290d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4291cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4292b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4293acce952bSliubo 		return ret;
4294acce952bSliubo 	}
4295acce952bSliubo 
42965c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4297d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
42980e0adbcfSJosef Bacik 		struct rb_node *n;
4299e78417d1SJosef Bacik 		bool pin_bytes = false;
4300acce952bSliubo 
4301d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4302d7df2c79SJosef Bacik 				href_node);
43033069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4304b939d1abSJosef Bacik 			continue;
43053069bd26SJosef Bacik 
4306d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4307e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
43080e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
43090e0adbcfSJosef Bacik 				       ref_node);
4310d7df2c79SJosef Bacik 			ref->in_tree = 0;
4311e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
43120e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
43131d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
43141d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4315d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4316d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4317d7df2c79SJosef Bacik 		}
431854067ae9SJosef Bacik 		if (head->must_insert_reserved)
4319e78417d1SJosef Bacik 			pin_bytes = true;
432078a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4321fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4322d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4323acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4324e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4325acce952bSliubo 
4326f603bb94SNikolay Borisov 		if (pin_bytes) {
4327f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4328f603bb94SNikolay Borisov 
4329f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4330f603bb94SNikolay Borisov 			BUG_ON(!cache);
4331f603bb94SNikolay Borisov 
4332f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4333f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4334f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4335f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4336f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4337f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4338f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4339f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4340f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4341f603bb94SNikolay Borisov 			percpu_counter_add_batch(
4342f603bb94SNikolay Borisov 				&cache->space_info->total_bytes_pinned,
4343f603bb94SNikolay Borisov 				head->num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4344f603bb94SNikolay Borisov 
4345f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4346f603bb94SNikolay Borisov 
4347f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4348f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4349f603bb94SNikolay Borisov 		}
435031890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4351d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4352acce952bSliubo 		cond_resched();
4353acce952bSliubo 		spin_lock(&delayed_refs->lock);
4354acce952bSliubo 	}
435581f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4356acce952bSliubo 
4357acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4358acce952bSliubo 
4359acce952bSliubo 	return ret;
4360acce952bSliubo }
4361acce952bSliubo 
4362143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4363acce952bSliubo {
4364acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4365acce952bSliubo 	struct list_head splice;
4366acce952bSliubo 
4367acce952bSliubo 	INIT_LIST_HEAD(&splice);
4368acce952bSliubo 
4369eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4370eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4371acce952bSliubo 
4372acce952bSliubo 	while (!list_empty(&splice)) {
4373fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4374eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4375acce952bSliubo 					       delalloc_inodes);
4376fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4377eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4378acce952bSliubo 
4379fe816d0fSNikolay Borisov 		/*
4380fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4381fe816d0fSNikolay Borisov 		 * meanwhile.
4382fe816d0fSNikolay Borisov 		 */
4383fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4384fe816d0fSNikolay Borisov 		if (inode) {
4385fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4386fe816d0fSNikolay Borisov 			iput(inode);
4387fe816d0fSNikolay Borisov 		}
4388eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4389acce952bSliubo 	}
4390eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4391eb73c1b7SMiao Xie }
4392eb73c1b7SMiao Xie 
4393eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4394eb73c1b7SMiao Xie {
4395eb73c1b7SMiao Xie 	struct btrfs_root *root;
4396eb73c1b7SMiao Xie 	struct list_head splice;
4397eb73c1b7SMiao Xie 
4398eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4399eb73c1b7SMiao Xie 
4400eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4401eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4402eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4403eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4404eb73c1b7SMiao Xie 					 delalloc_root);
440500246528SJosef Bacik 		root = btrfs_grab_root(root);
4406eb73c1b7SMiao Xie 		BUG_ON(!root);
4407eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4408eb73c1b7SMiao Xie 
4409eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
441000246528SJosef Bacik 		btrfs_put_root(root);
4411eb73c1b7SMiao Xie 
4412eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4413eb73c1b7SMiao Xie 	}
4414eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4415acce952bSliubo }
4416acce952bSliubo 
44172ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4418acce952bSliubo 					struct extent_io_tree *dirty_pages,
4419acce952bSliubo 					int mark)
4420acce952bSliubo {
4421acce952bSliubo 	int ret;
4422acce952bSliubo 	struct extent_buffer *eb;
4423acce952bSliubo 	u64 start = 0;
4424acce952bSliubo 	u64 end;
4425acce952bSliubo 
4426acce952bSliubo 	while (1) {
4427acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4428e6138876SJosef Bacik 					    mark, NULL);
4429acce952bSliubo 		if (ret)
4430acce952bSliubo 			break;
4431acce952bSliubo 
443291166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4433acce952bSliubo 		while (start <= end) {
44340b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
44350b246afaSJeff Mahoney 			start += fs_info->nodesize;
4436fd8b2b61SJosef Bacik 			if (!eb)
4437acce952bSliubo 				continue;
4438fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4439acce952bSliubo 
4440fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4441fd8b2b61SJosef Bacik 					       &eb->bflags))
4442fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4443fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4444acce952bSliubo 		}
4445acce952bSliubo 	}
4446acce952bSliubo 
4447acce952bSliubo 	return ret;
4448acce952bSliubo }
4449acce952bSliubo 
44502ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4451fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4452acce952bSliubo {
4453acce952bSliubo 	u64 start;
4454acce952bSliubo 	u64 end;
4455acce952bSliubo 	int ret;
4456acce952bSliubo 
4457acce952bSliubo 	while (1) {
44580e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
44590e6ec385SFilipe Manana 
4460fcd5e742SLu Fengqi 		/*
4461fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4462fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4463fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4464fcd5e742SLu Fengqi 		 * the same extent range.
4465fcd5e742SLu Fengqi 		 */
4466fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4467acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
44680e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4469fcd5e742SLu Fengqi 		if (ret) {
4470fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4471acce952bSliubo 			break;
4472fcd5e742SLu Fengqi 		}
4473acce952bSliubo 
44740e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
44750e6ec385SFilipe Manana 		free_extent_state(cached_state);
44762ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4477fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4478acce952bSliubo 		cond_resched();
4479acce952bSliubo 	}
4480acce952bSliubo 
4481acce952bSliubo 	return 0;
4482acce952bSliubo }
4483acce952bSliubo 
448432da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4485c79a1751SLiu Bo {
4486c79a1751SLiu Bo 	struct inode *inode;
4487c79a1751SLiu Bo 
4488c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4489c79a1751SLiu Bo 	if (inode) {
4490c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4491c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4492c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4493c79a1751SLiu Bo 		iput(inode);
4494c79a1751SLiu Bo 	}
4495c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4496c79a1751SLiu Bo }
4497c79a1751SLiu Bo 
4498c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
44992ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4500c79a1751SLiu Bo {
450132da5386SDavid Sterba 	struct btrfs_block_group *cache;
4502c79a1751SLiu Bo 
4503c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4504c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4505c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
450632da5386SDavid Sterba 					 struct btrfs_block_group,
4507c79a1751SLiu Bo 					 dirty_list);
4508c79a1751SLiu Bo 
4509c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4510c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4511c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4512c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4513c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4514c79a1751SLiu Bo 		}
4515c79a1751SLiu Bo 
4516c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4517c79a1751SLiu Bo 		spin_lock(&cache->lock);
4518c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4519c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4520c79a1751SLiu Bo 
4521c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4522c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4523ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4524c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4525c79a1751SLiu Bo 	}
4526c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4527c79a1751SLiu Bo 
452845ae2c18SNikolay Borisov 	/*
452945ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
453045ae2c18SNikolay Borisov 	 * to use it without any locking
453145ae2c18SNikolay Borisov 	 */
4532c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4533c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
453432da5386SDavid Sterba 					 struct btrfs_block_group,
4535c79a1751SLiu Bo 					 io_list);
4536c79a1751SLiu Bo 
4537c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4538c79a1751SLiu Bo 		spin_lock(&cache->lock);
4539c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4540c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4541c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4542c79a1751SLiu Bo 	}
4543c79a1751SLiu Bo }
4544c79a1751SLiu Bo 
454549b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
45462ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
454749b25e05SJeff Mahoney {
4548bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4549bbbf7243SNikolay Borisov 
45502ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4551c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4552c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4553c79a1751SLiu Bo 
4554bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4555bbbf7243SNikolay Borisov 				 post_commit_list) {
4556bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4557bbbf7243SNikolay Borisov 	}
4558bbbf7243SNikolay Borisov 
45592ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
456049b25e05SJeff Mahoney 
45614a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
45620b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
456349b25e05SJeff Mahoney 
45644a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
45650b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
456649b25e05SJeff Mahoney 
4567ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
456867cde344SMiao Xie 
45692ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
457049b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4571fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
457249b25e05SJeff Mahoney 
45734a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
45744a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
457549b25e05SJeff Mahoney }
457649b25e05SJeff Mahoney 
45772ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4578acce952bSliubo {
4579acce952bSliubo 	struct btrfs_transaction *t;
4580acce952bSliubo 
45810b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4582acce952bSliubo 
45830b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
45840b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
45850b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4586724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4587724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
45889b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
45890b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
45902ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4591724e2315SJosef Bacik 			btrfs_put_transaction(t);
45920b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4593724e2315SJosef Bacik 			continue;
4594724e2315SJosef Bacik 		}
45950b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4596724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
45970b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4598724e2315SJosef Bacik 			/*
4599724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4600724e2315SJosef Bacik 			 * handle open currently for this transaction.
4601724e2315SJosef Bacik 			 */
4602724e2315SJosef Bacik 			wait_event(t->writer_wait,
4603724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4604724e2315SJosef Bacik 		} else {
46050b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4606724e2315SJosef Bacik 		}
46072ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4608724e2315SJosef Bacik 
46090b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
46100b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
46110b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4612724e2315SJosef Bacik 		list_del_init(&t->list);
46130b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4614a4abeea4SJosef Bacik 
4615724e2315SJosef Bacik 		btrfs_put_transaction(t);
46162ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
46170b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4618724e2315SJosef Bacik 	}
46190b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
46200b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4621ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4622ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
46230b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4624ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
46250b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4626acce952bSliubo 
4627acce952bSliubo 	return 0;
4628acce952bSliubo }
4629acce952bSliubo 
4630e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
46314d53dddbSDavid Sterba 	/* mandatory callbacks */
46320b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
46334d53dddbSDavid Sterba 	.readpage_end_io_hook = btree_readpage_end_io_hook,
46340da5468fSChris Mason };
4635