xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 944d3f9f)
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;
548944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
54944880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
550944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5512b82032cSYan Zheng 
5529a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5539a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5547239ff4bSNikolay Borisov 	/*
555944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
556944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
557944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5587239ff4bSNikolay Borisov 	 */
559944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5607239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5617239ff4bSNikolay Borisov 	else
5627239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5637239ff4bSNikolay Borisov 
564944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
565944d3f9fSNikolay Borisov 		return 0;
566944d3f9fSNikolay Borisov 
567944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
568944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
569944d3f9fSNikolay Borisov 			return 0;
570944d3f9fSNikolay Borisov 
571944d3f9fSNikolay Borisov 	return 1;
5722b82032cSYan Zheng }
5732b82032cSYan Zheng 
574facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
575facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
576facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
577ce9adaa5SChris Mason {
578ce9adaa5SChris Mason 	u64 found_start;
579ce9adaa5SChris Mason 	int found_level;
580ce9adaa5SChris Mason 	struct extent_buffer *eb;
58115b6e8a8SDavid Sterba 	struct btrfs_fs_info *fs_info;
58215b6e8a8SDavid Sterba 	u16 csum_size;
583f188591eSChris Mason 	int ret = 0;
5842996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
585727011e0SChris Mason 	int reads_done;
586ce9adaa5SChris Mason 
587ce9adaa5SChris Mason 	if (!page->private)
588ce9adaa5SChris Mason 		goto out;
589d397712bSChris Mason 
5904f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
59115b6e8a8SDavid Sterba 	fs_info = eb->fs_info;
59215b6e8a8SDavid Sterba 	csum_size = btrfs_super_csum_size(fs_info->super_copy);
593d397712bSChris Mason 
5940b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
5950b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
5960b32f4bbSJosef Bacik 	 */
59767439dadSDavid Sterba 	atomic_inc(&eb->refs);
5980b32f4bbSJosef Bacik 
5990b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
600727011e0SChris Mason 	if (!reads_done)
601727011e0SChris Mason 		goto err;
602f188591eSChris Mason 
6035cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
604656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
605ea466794SJosef Bacik 		ret = -EIO;
606ea466794SJosef Bacik 		goto err;
607ea466794SJosef Bacik 	}
608ea466794SJosef Bacik 
609ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
610727011e0SChris Mason 	if (found_start != eb->start) {
611893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
612893bf4b1SSu Yue 			     eb->start, found_start);
613f188591eSChris Mason 		ret = -EIO;
614ce9adaa5SChris Mason 		goto err;
615ce9adaa5SChris Mason 	}
616b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
61702873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
61894647322SDavid Sterba 			     eb->start);
6191259ab75SChris Mason 		ret = -EIO;
6201259ab75SChris Mason 		goto err;
6211259ab75SChris Mason 	}
622ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6231c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
624893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
625893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
6261c24c3ceSJosef Bacik 		ret = -EIO;
6271c24c3ceSJosef Bacik 		goto err;
6281c24c3ceSJosef Bacik 	}
629ce9adaa5SChris Mason 
63085d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
63185d4e461SChris Mason 				       eb, found_level);
6324008c04aSChris Mason 
633c67b3892SDavid Sterba 	csum_tree_block(eb, result);
634a826d6dcSJosef Bacik 
6352996e1f8SJohannes Thumshirn 	if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
63635be8851SJohannes Thumshirn 		u8 val[BTRFS_CSUM_SIZE] = { 0 };
6372996e1f8SJohannes Thumshirn 
6382996e1f8SJohannes Thumshirn 		read_extent_buffer(eb, &val, 0, csum_size);
6392996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
64035be8851SJohannes Thumshirn 	"%s checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
6412996e1f8SJohannes Thumshirn 			      fs_info->sb->s_id, eb->start,
64235be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, val),
64335be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
64435be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
6452996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
6462996e1f8SJohannes Thumshirn 		goto err;
6472996e1f8SJohannes Thumshirn 	}
6482996e1f8SJohannes Thumshirn 
649a826d6dcSJosef Bacik 	/*
650a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
651a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
652a826d6dcSJosef Bacik 	 * return -EIO.
653a826d6dcSJosef Bacik 	 */
6541c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
655a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
656a826d6dcSJosef Bacik 		ret = -EIO;
657a826d6dcSJosef Bacik 	}
658ce9adaa5SChris Mason 
659813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
660053ab70fSLiu Bo 		ret = -EIO;
661053ab70fSLiu Bo 
6620b32f4bbSJosef Bacik 	if (!ret)
6630b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
66475391f0dSQu Wenruo 	else
66575391f0dSQu Wenruo 		btrfs_err(fs_info,
66675391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
66775391f0dSQu Wenruo 			  eb->start);
668ce9adaa5SChris Mason err:
66979fb65a1SJosef Bacik 	if (reads_done &&
67079fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
671d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6724bb31e92SArne Jansen 
67353b381b3SDavid Woodhouse 	if (ret) {
67453b381b3SDavid Woodhouse 		/*
67553b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
67653b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
67753b381b3SDavid Woodhouse 		 * to decrement
67853b381b3SDavid Woodhouse 		 */
67953b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6800b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
68153b381b3SDavid Woodhouse 	}
6820b32f4bbSJosef Bacik 	free_extent_buffer(eb);
683ce9adaa5SChris Mason out:
684f188591eSChris Mason 	return ret;
685ce9adaa5SChris Mason }
686ce9adaa5SChris Mason 
6874246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
688ce9adaa5SChris Mason {
68997eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
690ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6919e0af237SLiu Bo 	struct btrfs_workqueue *wq;
692ce9adaa5SChris Mason 
693ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
6944e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
695d20f7043SChris Mason 
69637226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
697a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
6989e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
699a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7009e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
701a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7029e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
703a0cac0ecSOmar Sandoval 		else
7049e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7059e0af237SLiu Bo 	} else {
7065c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7079e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
708a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7099e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
710a0cac0ecSOmar Sandoval 		else
7119e0af237SLiu Bo 			wq = fs_info->endio_workers;
7129e0af237SLiu Bo 	}
7139e0af237SLiu Bo 
714a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7159e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
716ce9adaa5SChris Mason }
717ce9adaa5SChris Mason 
7184e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
719bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7200b86a832SChris Mason {
72197eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7228b110e39SMiao Xie 
72397eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
724ce9adaa5SChris Mason 	if (!end_io_wq)
7254e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
726ce9adaa5SChris Mason 
727ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
728ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
72922c59948SChris Mason 	end_io_wq->info = info;
7304e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
731ce9adaa5SChris Mason 	end_io_wq->bio = bio;
73222c59948SChris Mason 	end_io_wq->metadata = metadata;
733ce9adaa5SChris Mason 
734ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
735ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
73622c59948SChris Mason 	return 0;
73722c59948SChris Mason }
73822c59948SChris Mason 
7394a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7404a69a410SChris Mason {
7414a69a410SChris Mason 	struct async_submit_bio *async;
7424e4cbee9SChristoph Hellwig 	blk_status_t ret;
7434a69a410SChris Mason 
7444a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
745c6100a4bSJosef Bacik 	ret = async->submit_bio_start(async->private_data, async->bio,
746eaf25d93SChris Mason 				      async->bio_offset);
74779787eaaSJeff Mahoney 	if (ret)
7484e4cbee9SChristoph Hellwig 		async->status = ret;
7494a69a410SChris Mason }
7504a69a410SChris Mason 
75106ea01b1SDavid Sterba /*
75206ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
75306ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
75406ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
75506ea01b1SDavid Sterba  *
75606ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
75706ea01b1SDavid Sterba  * inserted into the tree.
75806ea01b1SDavid Sterba  */
7594a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7608b712842SChris Mason {
7618b712842SChris Mason 	struct async_submit_bio *async;
76206ea01b1SDavid Sterba 	struct inode *inode;
76306ea01b1SDavid Sterba 	blk_status_t ret;
7648b712842SChris Mason 
7658b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
76606ea01b1SDavid Sterba 	inode = async->private_data;
7674854ddd0SChris Mason 
768bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7694e4cbee9SChristoph Hellwig 	if (async->status) {
7704e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7714246a0b6SChristoph Hellwig 		bio_endio(async->bio);
77279787eaaSJeff Mahoney 		return;
77379787eaaSJeff Mahoney 	}
77479787eaaSJeff Mahoney 
775ec39f769SChris Mason 	/*
776ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
777ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
778ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
779ec39f769SChris Mason 	 */
780ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
78108635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
78206ea01b1SDavid Sterba 	if (ret) {
78306ea01b1SDavid Sterba 		async->bio->bi_status = ret;
78406ea01b1SDavid Sterba 		bio_endio(async->bio);
78506ea01b1SDavid Sterba 	}
7864a69a410SChris Mason }
7874a69a410SChris Mason 
7884a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7894a69a410SChris Mason {
7904a69a410SChris Mason 	struct async_submit_bio *async;
7914a69a410SChris Mason 
7924a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7938b712842SChris Mason 	kfree(async);
7948b712842SChris Mason }
7958b712842SChris Mason 
7968c27cb35SLinus Torvalds blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
797c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
798c6100a4bSJosef Bacik 				 u64 bio_offset, void *private_data,
799e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
80044b8bd7eSChris Mason {
80144b8bd7eSChris Mason 	struct async_submit_bio *async;
80244b8bd7eSChris Mason 
80344b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
80444b8bd7eSChris Mason 	if (!async)
8054e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
80644b8bd7eSChris Mason 
807c6100a4bSJosef Bacik 	async->private_data = private_data;
80844b8bd7eSChris Mason 	async->bio = bio;
80944b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8104a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8114a69a410SChris Mason 
812a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
813a0cac0ecSOmar Sandoval 			run_one_async_free);
8144a69a410SChris Mason 
815eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8168c8bee1dSChris Mason 
8174e4cbee9SChristoph Hellwig 	async->status = 0;
81879787eaaSJeff Mahoney 
81967f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8205cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
821d313d7a3SChris Mason 
8225cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
82344b8bd7eSChris Mason 	return 0;
82444b8bd7eSChris Mason }
82544b8bd7eSChris Mason 
8264e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
827ce3ed71aSChris Mason {
8282c30c71bSKent Overstreet 	struct bio_vec *bvec;
829ce3ed71aSChris Mason 	struct btrfs_root *root;
8302b070cfeSChristoph Hellwig 	int ret = 0;
8316dc4f100SMing Lei 	struct bvec_iter_all iter_all;
832ce3ed71aSChris Mason 
833c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8342b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
835ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
83601d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
83779787eaaSJeff Mahoney 		if (ret)
83879787eaaSJeff Mahoney 			break;
839ce3ed71aSChris Mason 	}
8402c30c71bSKent Overstreet 
8414e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
842ce3ed71aSChris Mason }
843ce3ed71aSChris Mason 
844d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
845eaf25d93SChris Mason 					     u64 bio_offset)
84622c59948SChris Mason {
8478b712842SChris Mason 	/*
8488b712842SChris Mason 	 * when we're called for a write, we're already in the async
8495443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8508b712842SChris Mason 	 */
85179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
85222c59948SChris Mason }
85322c59948SChris Mason 
8549b4e675aSDavid Sterba static int check_async_write(struct btrfs_fs_info *fs_info,
8559b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
856de0022b9SJosef Bacik {
8576300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8586300463bSLiu Bo 		return 0;
8599b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
860de0022b9SJosef Bacik 		return 0;
861de0022b9SJosef Bacik 	return 1;
862de0022b9SJosef Bacik }
863de0022b9SJosef Bacik 
864a56b1c7bSNikolay Borisov static blk_status_t btree_submit_bio_hook(struct inode *inode, struct bio *bio,
86550489a57SNikolay Borisov 					  int mirror_num,
86650489a57SNikolay Borisov 					  unsigned long bio_flags)
86744b8bd7eSChris Mason {
8680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8699b4e675aSDavid Sterba 	int async = check_async_write(fs_info, BTRFS_I(inode));
8704e4cbee9SChristoph Hellwig 	blk_status_t ret;
871cad321adSChris Mason 
87237226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
873cad321adSChris Mason 		/*
874cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
875cad321adSChris Mason 		 * can happen in the async kernel threads
876cad321adSChris Mason 		 */
8770b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8780b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8791d4284bdSChris Mason 		if (ret)
88061891923SStefan Behrens 			goto out_w_error;
88108635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
882de0022b9SJosef Bacik 	} else if (!async) {
883de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
884de0022b9SJosef Bacik 		if (ret)
88561891923SStefan Behrens 			goto out_w_error;
88608635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
88761891923SStefan Behrens 	} else {
888cad321adSChris Mason 		/*
88961891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
89061891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
891cad321adSChris Mason 		 */
892c6100a4bSJosef Bacik 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
893e68f2ee7SNikolay Borisov 					  0, inode, btree_submit_bio_start);
89444b8bd7eSChris Mason 	}
89544b8bd7eSChris Mason 
8964246a0b6SChristoph Hellwig 	if (ret)
8974246a0b6SChristoph Hellwig 		goto out_w_error;
8984246a0b6SChristoph Hellwig 	return 0;
8994246a0b6SChristoph Hellwig 
90061891923SStefan Behrens out_w_error:
9014e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9024246a0b6SChristoph Hellwig 	bio_endio(bio);
90361891923SStefan Behrens 	return ret;
90461891923SStefan Behrens }
90561891923SStefan Behrens 
9063dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
907784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
908a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
909a6bc32b8SMel Gorman 			enum migrate_mode mode)
910784b4e29SChris Mason {
911784b4e29SChris Mason 	/*
912784b4e29SChris Mason 	 * we can't safely write a btree page from here,
913784b4e29SChris Mason 	 * we haven't done the locking hook
914784b4e29SChris Mason 	 */
915784b4e29SChris Mason 	if (PageDirty(page))
916784b4e29SChris Mason 		return -EAGAIN;
917784b4e29SChris Mason 	/*
918784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
919784b4e29SChris Mason 	 * We must have no buffers or drop them.
920784b4e29SChris Mason 	 */
921784b4e29SChris Mason 	if (page_has_private(page) &&
922784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
923784b4e29SChris Mason 		return -EAGAIN;
924a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
925784b4e29SChris Mason }
9263dd1462eSJan Beulich #endif
927784b4e29SChris Mason 
9280da5468fSChris Mason 
9290da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9300da5468fSChris Mason 			    struct writeback_control *wbc)
9310da5468fSChris Mason {
932e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
933e2d84521SMiao Xie 	int ret;
934e2d84521SMiao Xie 
935d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
936448d640bSChris Mason 
937448d640bSChris Mason 		if (wbc->for_kupdate)
938448d640bSChris Mason 			return 0;
939448d640bSChris Mason 
940e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
941b9473439SChris Mason 		/* this is a bit racy, but that's ok */
942d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
943d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
944d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
945e2d84521SMiao Xie 		if (ret < 0)
946793955bcSChris Mason 			return 0;
947793955bcSChris Mason 	}
9480b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9490da5468fSChris Mason }
9500da5468fSChris Mason 
951b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9525f39d397SChris Mason {
95371ad38b4SDavid Sterba 	return extent_read_full_page(page, btree_get_extent, 0);
9545f39d397SChris Mason }
9555f39d397SChris Mason 
95670dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9575f39d397SChris Mason {
95898509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
95998509cfcSChris Mason 		return 0;
9600c4e538bSDavid Sterba 
961f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
962d98237b3SChris Mason }
963d98237b3SChris Mason 
964d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
965d47992f8SLukas Czerner 				 unsigned int length)
966d98237b3SChris Mason {
967d1310b2eSChris Mason 	struct extent_io_tree *tree;
968d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9695f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9705f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9719ad6b7bcSChris Mason 	if (PagePrivate(page)) {
972efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
973efe120a0SFrank Holton 			   "page private not zero on page %llu",
974efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
975d1b89bc0SGuoqing Jiang 		detach_page_private(page);
9769ad6b7bcSChris Mason 	}
977d98237b3SChris Mason }
978d98237b3SChris Mason 
9790b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9800b32f4bbSJosef Bacik {
981bb146eb2SJosef Bacik #ifdef DEBUG
9820b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9830b32f4bbSJosef Bacik 
9840b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9850b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9860b32f4bbSJosef Bacik 	BUG_ON(!eb);
9870b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9880b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
9890b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
990bb146eb2SJosef Bacik #endif
9910b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
9920b32f4bbSJosef Bacik }
9930b32f4bbSJosef Bacik 
9947f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
995d98237b3SChris Mason 	.readpage	= btree_readpage,
9960da5468fSChris Mason 	.writepages	= btree_writepages,
9975f39d397SChris Mason 	.releasepage	= btree_releasepage,
9985f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
9995a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1000784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10015a92bc88SChris Mason #endif
10020b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1003d98237b3SChris Mason };
1004123abc88SChris Mason 
10052ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1006090d1875SChris Mason {
10075f39d397SChris Mason 	struct extent_buffer *buf = NULL;
1008537f38f0SNikolay Borisov 	int ret;
1009090d1875SChris Mason 
10102ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1011c871b0f2SLiu Bo 	if (IS_ERR(buf))
10126197d86eSDavid Sterba 		return;
1013537f38f0SNikolay Borisov 
1014c2ccfbc6SNikolay Borisov 	ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
1015537f38f0SNikolay Borisov 	if (ret < 0)
1016537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
1017537f38f0SNikolay Borisov 	else
10185f39d397SChris Mason 		free_extent_buffer(buf);
1019090d1875SChris Mason }
1020090d1875SChris Mason 
10212ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10222ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10230308af44SDavid Sterba 						u64 bytenr)
10240999df54SChris Mason {
10250b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10260b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10270b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
10280999df54SChris Mason }
10290999df54SChris Mason 
1030581c1760SQu Wenruo /*
1031581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1032581c1760SQu Wenruo  * verification.
1033581c1760SQu Wenruo  *
1034581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1035581c1760SQu Wenruo  * @level:		expected level, mandatory check
1036581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1037581c1760SQu Wenruo  */
10382ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1039581c1760SQu Wenruo 				      u64 parent_transid, int level,
1040581c1760SQu Wenruo 				      struct btrfs_key *first_key)
1041e20d96d6SChris Mason {
10425f39d397SChris Mason 	struct extent_buffer *buf = NULL;
104319c00ddcSChris Mason 	int ret;
104419c00ddcSChris Mason 
10452ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1046c871b0f2SLiu Bo 	if (IS_ERR(buf))
1047c871b0f2SLiu Bo 		return buf;
1048e4204dedSChris Mason 
10495ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1050581c1760SQu Wenruo 					     level, first_key);
10510f0fe8f7SFilipe David Borba Manana 	if (ret) {
1052537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
105364c043deSLiu Bo 		return ERR_PTR(ret);
10540f0fe8f7SFilipe David Borba Manana 	}
10555f39d397SChris Mason 	return buf;
1056ce9adaa5SChris Mason 
1057eb60ceacSChris Mason }
1058eb60ceacSChris Mason 
10596a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1060ed2ff2cbSChris Mason {
10616a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
106255c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1063e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1064b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1065b4ce94deSChris Mason 
1066b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1067104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1068e2d84521SMiao Xie 						 -buf->len,
1069e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
1070b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
10718bead258SDavid Sterba 			btrfs_set_lock_blocking_write(buf);
10720b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1073925baeddSChris Mason 		}
10745f39d397SChris Mason 	}
1075ed7b63ebSJosef Bacik }
10765f39d397SChris Mason 
1077da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1078e20d96d6SChris Mason 			 u64 objectid)
1079d97e63b6SChris Mason {
10807c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
108196dfcb46SJosef Bacik 	root->fs_info = fs_info;
1082cfaa7295SChris Mason 	root->node = NULL;
1083a28ec197SChris Mason 	root->commit_root = NULL;
108427cdeb70SMiao Xie 	root->state = 0;
1085d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
10860b86a832SChris Mason 
10870f7d52f4SChris Mason 	root->last_trans = 0;
108813a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1089eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1090199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
10916bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
109216cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1093f0486c68SYan, Zheng 	root->block_rsv = NULL;
10940b86a832SChris Mason 
10950b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
10965d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1097eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1098eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1099199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1100199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1101d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11022ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11032ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11045d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1105eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1106199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1107f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11082ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11092ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11108287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1111a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1112e02119d5SChris Mason 	mutex_init(&root->log_mutex);
111331f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1114573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1115c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11167237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11177237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11187237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11198b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11208b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11217237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11227237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11237237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11242ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11250700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11268ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1127eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11287237f183SYan Zheng 	root->log_transid = 0;
1129d1433debSMiao Xie 	root->log_transid_committed = -1;
1130257c62e1SChris Mason 	root->last_log_commit = 0;
1131e289f03eSFilipe Manana 	if (!dummy) {
113243eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
113343eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1134e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1135e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1136e289f03eSFilipe Manana 	}
1137017e5369SChris Mason 
11383768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11393768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11406702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
11414d775673SChris Mason 	root->root_key.objectid = objectid;
11420ee5dc67SAl Viro 	root->anon_dev = 0;
11438ea05e3aSAlexander Block 
11445f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1145370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1146bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1147bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1148bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1149bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1150bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1151bd647ce3SJosef Bacik #endif
11523768f368SChris Mason }
11533768f368SChris Mason 
115474e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
115596dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
11566f07e42eSAl Viro {
115774e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
11586f07e42eSAl Viro 	if (root)
115996dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
11606f07e42eSAl Viro 	return root;
11616f07e42eSAl Viro }
11626f07e42eSAl Viro 
116306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
116406ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1165da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
116606ea65a3SJosef Bacik {
116706ea65a3SJosef Bacik 	struct btrfs_root *root;
116806ea65a3SJosef Bacik 
11697c0260eeSJeff Mahoney 	if (!fs_info)
11707c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
11717c0260eeSJeff Mahoney 
117296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
117306ea65a3SJosef Bacik 	if (!root)
117406ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1175da17066cSJeff Mahoney 
1176b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1177faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
117806ea65a3SJosef Bacik 
117906ea65a3SJosef Bacik 	return root;
118006ea65a3SJosef Bacik }
118106ea65a3SJosef Bacik #endif
118206ea65a3SJosef Bacik 
118320897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
118420897f5cSArne Jansen 				     u64 objectid)
118520897f5cSArne Jansen {
11869b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
118720897f5cSArne Jansen 	struct extent_buffer *leaf;
118820897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
118920897f5cSArne Jansen 	struct btrfs_root *root;
119020897f5cSArne Jansen 	struct btrfs_key key;
1191b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
119220897f5cSArne Jansen 	int ret = 0;
119320897f5cSArne Jansen 
1194b89f6d1fSFilipe Manana 	/*
1195b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1196b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1197b89f6d1fSFilipe Manana 	 */
1198b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
119996dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1200b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
120120897f5cSArne Jansen 	if (!root)
120220897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
120320897f5cSArne Jansen 
120420897f5cSArne Jansen 	root->root_key.objectid = objectid;
120520897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
120620897f5cSArne Jansen 	root->root_key.offset = 0;
120720897f5cSArne Jansen 
12084d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
120920897f5cSArne Jansen 	if (IS_ERR(leaf)) {
121020897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12111dd05682STsutomu Itoh 		leaf = NULL;
121220897f5cSArne Jansen 		goto fail;
121320897f5cSArne Jansen 	}
121420897f5cSArne Jansen 
121520897f5cSArne Jansen 	root->node = leaf;
121620897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
121720897f5cSArne Jansen 
121820897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
121927cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
122020897f5cSArne Jansen 
122120897f5cSArne Jansen 	root->root_item.flags = 0;
122220897f5cSArne Jansen 	root->root_item.byte_limit = 0;
122320897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
122420897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
122520897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
122620897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
122720897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
122820897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
122920897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
123033d85fdaSQu Wenruo 	if (is_fstree(objectid))
1231807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1232807fc790SAndy Shevchenko 	else
1233807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
123420897f5cSArne Jansen 	root->root_item.drop_level = 0;
123520897f5cSArne Jansen 
123620897f5cSArne Jansen 	key.objectid = objectid;
123720897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
123820897f5cSArne Jansen 	key.offset = 0;
123920897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
124020897f5cSArne Jansen 	if (ret)
124120897f5cSArne Jansen 		goto fail;
124220897f5cSArne Jansen 
124320897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
124420897f5cSArne Jansen 
124520897f5cSArne Jansen 	return root;
12461dd05682STsutomu Itoh 
12471dd05682STsutomu Itoh fail:
12488c38938cSJosef Bacik 	if (leaf)
12491dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
125000246528SJosef Bacik 	btrfs_put_root(root);
12511dd05682STsutomu Itoh 
12521dd05682STsutomu Itoh 	return ERR_PTR(ret);
125320897f5cSArne Jansen }
125420897f5cSArne Jansen 
12557237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1256e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
12570f7d52f4SChris Mason {
12580f7d52f4SChris Mason 	struct btrfs_root *root;
12597237f183SYan Zheng 	struct extent_buffer *leaf;
1260e02119d5SChris Mason 
126196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1262e02119d5SChris Mason 	if (!root)
12637237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1264e02119d5SChris Mason 
1265e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1266e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1267e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
126827cdeb70SMiao Xie 
12697237f183SYan Zheng 	/*
127092a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
127127cdeb70SMiao Xie 	 *
127292a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
127392a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
127492a7cc42SQu Wenruo 	 *
127592a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
127692a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
12777237f183SYan Zheng 	 */
1278e02119d5SChris Mason 
12794d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12804d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
12817237f183SYan Zheng 	if (IS_ERR(leaf)) {
128200246528SJosef Bacik 		btrfs_put_root(root);
12837237f183SYan Zheng 		return ERR_CAST(leaf);
12847237f183SYan Zheng 	}
1285e02119d5SChris Mason 
12867237f183SYan Zheng 	root->node = leaf;
1287e02119d5SChris Mason 
1288e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1289e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12907237f183SYan Zheng 	return root;
12917237f183SYan Zheng }
12927237f183SYan Zheng 
12937237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
12947237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
12957237f183SYan Zheng {
12967237f183SYan Zheng 	struct btrfs_root *log_root;
12977237f183SYan Zheng 
12987237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
12997237f183SYan Zheng 	if (IS_ERR(log_root))
13007237f183SYan Zheng 		return PTR_ERR(log_root);
13017237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13027237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13037237f183SYan Zheng 	return 0;
13047237f183SYan Zheng }
13057237f183SYan Zheng 
13067237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13077237f183SYan Zheng 		       struct btrfs_root *root)
13087237f183SYan Zheng {
13090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13107237f183SYan Zheng 	struct btrfs_root *log_root;
13117237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13127237f183SYan Zheng 
13130b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13147237f183SYan Zheng 	if (IS_ERR(log_root))
13157237f183SYan Zheng 		return PTR_ERR(log_root);
13167237f183SYan Zheng 
13177237f183SYan Zheng 	log_root->last_trans = trans->transid;
13187237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13197237f183SYan Zheng 
13207237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13213cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13223cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13233cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1324da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13250b246afaSJeff Mahoney 				     fs_info->nodesize);
13263cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13277237f183SYan Zheng 
13285d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13297237f183SYan Zheng 
13307237f183SYan Zheng 	WARN_ON(root->log_root);
13317237f183SYan Zheng 	root->log_root = log_root;
13327237f183SYan Zheng 	root->log_transid = 0;
1333d1433debSMiao Xie 	root->log_transid_committed = -1;
1334257c62e1SChris Mason 	root->last_log_commit = 0;
1335e02119d5SChris Mason 	return 0;
1336e02119d5SChris Mason }
1337e02119d5SChris Mason 
133862a2c73eSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1339cb517eabSMiao Xie 					struct btrfs_key *key)
1340e02119d5SChris Mason {
1341e02119d5SChris Mason 	struct btrfs_root *root;
1342e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
13430f7d52f4SChris Mason 	struct btrfs_path *path;
134484234f3aSYan Zheng 	u64 generation;
1345cb517eabSMiao Xie 	int ret;
1346581c1760SQu Wenruo 	int level;
1347cb517eabSMiao Xie 
1348cb517eabSMiao Xie 	path = btrfs_alloc_path();
1349cb517eabSMiao Xie 	if (!path)
1350cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
13510f7d52f4SChris Mason 
135296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1353cb517eabSMiao Xie 	if (!root) {
1354cb517eabSMiao Xie 		ret = -ENOMEM;
1355cb517eabSMiao Xie 		goto alloc_fail;
13560f7d52f4SChris Mason 	}
13570f7d52f4SChris Mason 
1358cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1359cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
13600f7d52f4SChris Mason 	if (ret) {
136113a8a7c8SYan, Zheng 		if (ret > 0)
136213a8a7c8SYan, Zheng 			ret = -ENOENT;
1363cb517eabSMiao Xie 		goto find_fail;
13640f7d52f4SChris Mason 	}
136513a8a7c8SYan, Zheng 
136684234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1367581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
13682ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
13692ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1370581c1760SQu Wenruo 				     generation, level, NULL);
137164c043deSLiu Bo 	if (IS_ERR(root->node)) {
137264c043deSLiu Bo 		ret = PTR_ERR(root->node);
13738c38938cSJosef Bacik 		root->node = NULL;
1374cb517eabSMiao Xie 		goto find_fail;
1375cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1376cb517eabSMiao Xie 		ret = -EIO;
137764c043deSLiu Bo 		goto find_fail;
1378416bc658SJosef Bacik 	}
13795d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
138013a8a7c8SYan, Zheng out:
1381cb517eabSMiao Xie 	btrfs_free_path(path);
1382cb517eabSMiao Xie 	return root;
1383cb517eabSMiao Xie 
1384cb517eabSMiao Xie find_fail:
138500246528SJosef Bacik 	btrfs_put_root(root);
1386cb517eabSMiao Xie alloc_fail:
1387cb517eabSMiao Xie 	root = ERR_PTR(ret);
1388cb517eabSMiao Xie 	goto out;
1389cb517eabSMiao Xie }
1390cb517eabSMiao Xie 
13912dfb1e43SQu Wenruo /*
13922dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
13932dfb1e43SQu Wenruo  *
13942dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
13952dfb1e43SQu Wenruo  */
13962dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
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 
1419aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1420aeb935a4SQu Wenruo 	    root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
142192a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1422f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1423f39e4571SJosef Bacik 	}
1424f39e4571SJosef Bacik 
1425cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
142657cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
142757cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1428cb517eabSMiao Xie 
1429851fd730SQu Wenruo 	/*
1430851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1431851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1432851fd730SQu Wenruo 	 */
1433851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1434851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
14352dfb1e43SQu Wenruo 		if (!anon_dev) {
1436cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1437cb517eabSMiao Xie 			if (ret)
1438876d2cf1SLiu Bo 				goto fail;
14392dfb1e43SQu Wenruo 		} else {
14402dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
14412dfb1e43SQu Wenruo 		}
1442851fd730SQu Wenruo 	}
1443f32e48e9SChandan Rajendra 
1444f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1445f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1446f32e48e9SChandan Rajendra 					&root->highest_objectid);
1447f32e48e9SChandan Rajendra 	if (ret) {
1448f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1449876d2cf1SLiu Bo 		goto fail;
1450f32e48e9SChandan Rajendra 	}
1451f32e48e9SChandan Rajendra 
1452f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1453f32e48e9SChandan Rajendra 
1454f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1455f32e48e9SChandan Rajendra 
1456cb517eabSMiao Xie 	return 0;
1457cb517eabSMiao Xie fail:
145884db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1459cb517eabSMiao Xie 	return ret;
1460cb517eabSMiao Xie }
1461cb517eabSMiao Xie 
1462a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1463cb517eabSMiao Xie 					       u64 root_id)
1464cb517eabSMiao Xie {
1465cb517eabSMiao Xie 	struct btrfs_root *root;
1466cb517eabSMiao Xie 
1467cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1468cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1469cb517eabSMiao Xie 				 (unsigned long)root_id);
1470bc44d7c4SJosef Bacik 	if (root)
147100246528SJosef Bacik 		root = btrfs_grab_root(root);
1472cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1473cb517eabSMiao Xie 	return root;
1474cb517eabSMiao Xie }
1475cb517eabSMiao Xie 
1476cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1477cb517eabSMiao Xie 			 struct btrfs_root *root)
1478cb517eabSMiao Xie {
1479cb517eabSMiao Xie 	int ret;
1480cb517eabSMiao Xie 
1481e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1482cb517eabSMiao Xie 	if (ret)
1483cb517eabSMiao Xie 		return ret;
1484cb517eabSMiao Xie 
1485cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1486cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1487cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1488cb517eabSMiao Xie 				root);
1489af01d2e5SJosef Bacik 	if (ret == 0) {
149000246528SJosef Bacik 		btrfs_grab_root(root);
149127cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1492af01d2e5SJosef Bacik 	}
1493cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1494cb517eabSMiao Xie 	radix_tree_preload_end();
1495cb517eabSMiao Xie 
1496cb517eabSMiao Xie 	return ret;
1497cb517eabSMiao Xie }
1498cb517eabSMiao Xie 
1499bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1500bd647ce3SJosef Bacik {
1501bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1502bd647ce3SJosef Bacik 	struct btrfs_root *root;
1503bd647ce3SJosef Bacik 
1504bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1505bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1506bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1507bd647ce3SJosef Bacik 		btrfs_err(fs_info, "leaked root %llu-%llu refcount %d",
1508bd647ce3SJosef Bacik 			  root->root_key.objectid, root->root_key.offset,
1509bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1510bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
151100246528SJosef Bacik 			btrfs_put_root(root);
151200246528SJosef Bacik 		btrfs_put_root(root);
1513bd647ce3SJosef Bacik 	}
1514bd647ce3SJosef Bacik #endif
1515bd647ce3SJosef Bacik }
1516bd647ce3SJosef Bacik 
15170d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
15180d4b0463SJosef Bacik {
1519141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1520141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
1521141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dio_bytes);
1522141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1523141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1524141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1525141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
15260d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
15270d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
152800246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
152900246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
153000246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
153100246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
153200246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
153300246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
153400246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
153500246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
153600246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1537aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1538bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
15393fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
15400d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
15410d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
15420d4b0463SJosef Bacik 	kvfree(fs_info);
15430d4b0463SJosef Bacik }
15440d4b0463SJosef Bacik 
15450d4b0463SJosef Bacik 
15462dfb1e43SQu Wenruo /*
15472dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
15482dfb1e43SQu Wenruo  *
15492dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
15502dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
15512dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
15522dfb1e43SQu Wenruo  *
15532dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
15542dfb1e43SQu Wenruo  *
15552dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
15562dfb1e43SQu Wenruo  *	 same root objectid.
15572dfb1e43SQu Wenruo  *
15582dfb1e43SQu Wenruo  * @objectid:	root id
15592dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
15602dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
15612dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
15622dfb1e43SQu Wenruo  *		for orphan roots
15632dfb1e43SQu Wenruo  */
15642dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
15652dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
15662dfb1e43SQu Wenruo 					     bool check_ref)
15675eda7b5eSChris Mason {
15685eda7b5eSChris Mason 	struct btrfs_root *root;
1569381cf658SDavid Sterba 	struct btrfs_path *path;
15701d4c08e0SDavid Sterba 	struct btrfs_key key;
15715eda7b5eSChris Mason 	int ret;
15725eda7b5eSChris Mason 
157356e9357aSDavid Sterba 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
157400246528SJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
157556e9357aSDavid Sterba 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
157600246528SJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
157756e9357aSDavid Sterba 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
157800246528SJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
157956e9357aSDavid Sterba 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
158000246528SJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
158156e9357aSDavid Sterba 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
158200246528SJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
158356e9357aSDavid Sterba 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
158400246528SJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
1585bc44d7c4SJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
158656e9357aSDavid Sterba 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
158700246528SJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
1588bc44d7c4SJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
158956e9357aSDavid Sterba 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
159000246528SJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
1591bc44d7c4SJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
15924df27c4dSYan, Zheng again:
159356e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
159448475471SStefan Behrens 	if (root) {
15952dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
15962dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1597bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
159800246528SJosef Bacik 			btrfs_put_root(root);
159948475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1600bc44d7c4SJosef Bacik 		}
16015eda7b5eSChris Mason 		return root;
160248475471SStefan Behrens 	}
16035eda7b5eSChris Mason 
160456e9357aSDavid Sterba 	key.objectid = objectid;
160556e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
160656e9357aSDavid Sterba 	key.offset = (u64)-1;
160756e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16085eda7b5eSChris Mason 	if (IS_ERR(root))
16095eda7b5eSChris Mason 		return root;
16103394e160SChris Mason 
1611c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1612d68fc57bSYan, Zheng 		ret = -ENOENT;
1613d68fc57bSYan, Zheng 		goto fail;
1614d68fc57bSYan, Zheng 	}
1615d68fc57bSYan, Zheng 
16162dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1617cb517eabSMiao Xie 	if (ret)
1618cb517eabSMiao Xie 		goto fail;
1619cb517eabSMiao Xie 
1620381cf658SDavid Sterba 	path = btrfs_alloc_path();
1621381cf658SDavid Sterba 	if (!path) {
1622381cf658SDavid Sterba 		ret = -ENOMEM;
1623381cf658SDavid Sterba 		goto fail;
1624381cf658SDavid Sterba 	}
16251d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
16261d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
162756e9357aSDavid Sterba 	key.offset = objectid;
16281d4c08e0SDavid Sterba 
16291d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1630381cf658SDavid Sterba 	btrfs_free_path(path);
1631d68fc57bSYan, Zheng 	if (ret < 0)
1632d68fc57bSYan, Zheng 		goto fail;
1633d68fc57bSYan, Zheng 	if (ret == 0)
163427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1635d68fc57bSYan, Zheng 
1636cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16370f7d52f4SChris Mason 	if (ret) {
163800246528SJosef Bacik 		btrfs_put_root(root);
16394785e24fSJosef Bacik 		if (ret == -EEXIST)
16404df27c4dSYan, Zheng 			goto again;
16414df27c4dSYan, Zheng 		goto fail;
16424df27c4dSYan, Zheng 	}
1643edbd8d4eSChris Mason 	return root;
16444df27c4dSYan, Zheng fail:
16458c38938cSJosef Bacik 	btrfs_put_root(root);
16464df27c4dSYan, Zheng 	return ERR_PTR(ret);
1647edbd8d4eSChris Mason }
1648edbd8d4eSChris Mason 
16492dfb1e43SQu Wenruo /*
16502dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
16512dfb1e43SQu Wenruo  *
16522dfb1e43SQu Wenruo  * @objectid:	tree objectid
16532dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
16542dfb1e43SQu Wenruo  *		one reference
16552dfb1e43SQu Wenruo  */
16562dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
16572dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
16582dfb1e43SQu Wenruo {
16592dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
16602dfb1e43SQu Wenruo }
16612dfb1e43SQu Wenruo 
16622dfb1e43SQu Wenruo /*
16632dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
16642dfb1e43SQu Wenruo  * the anonymous block device id
16652dfb1e43SQu Wenruo  *
16662dfb1e43SQu Wenruo  * @objectid:	tree objectid
16672dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
16682dfb1e43SQu Wenruo  *		parameter value
16692dfb1e43SQu Wenruo  */
16702dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
16712dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
16722dfb1e43SQu Wenruo {
16732dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
16742dfb1e43SQu Wenruo }
16752dfb1e43SQu Wenruo 
16768b712842SChris Mason /*
16778b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16788b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16798b712842SChris Mason  */
16808b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1681ce9adaa5SChris Mason {
1682ce9adaa5SChris Mason 	struct bio *bio;
168397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1684ce9adaa5SChris Mason 
168597eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1686ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16878b712842SChris Mason 
16884e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1689ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1690ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
16914246a0b6SChristoph Hellwig 	bio_endio(bio);
16929be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1693ce9adaa5SChris Mason }
169444b8bd7eSChris Mason 
1695a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1696a74a4b97SChris Mason {
1697a74a4b97SChris Mason 	struct btrfs_root *root = arg;
16980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1699d0278245SMiao Xie 	int again;
1700a74a4b97SChris Mason 
1701d6fd0ae2SOmar Sandoval 	while (1) {
1702d0278245SMiao Xie 		again = 0;
17039d1a2a3aSDavid Sterba 
1704fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1705fd340d0fSJosef Bacik 
1706d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
17072ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1708d0278245SMiao Xie 			goto sleep;
1709d0278245SMiao Xie 
171090c711abSZygo Blaxell 		/*
171190c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
171290c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
171390c711abSZygo Blaxell 		 */
17140b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
171590c711abSZygo Blaxell 			goto sleep;
171690c711abSZygo Blaxell 
17170b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1718d0278245SMiao Xie 			goto sleep;
1719d0278245SMiao Xie 
1720dc7f370cSMiao Xie 		/*
1721dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1722dc7f370cSMiao Xie 		 * during the above check and trylock.
1723dc7f370cSMiao Xie 		 */
17242ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
17250b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1726dc7f370cSMiao Xie 			goto sleep;
1727dc7f370cSMiao Xie 		}
1728dc7f370cSMiao Xie 
17292ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1730c2d6cb16SFilipe Manana 
17319d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
17320b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1733a74a4b97SChris Mason 
1734d0278245SMiao Xie 		/*
173505323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
173605323cd1SMiao Xie 		 * needn't do anything special here.
1737d0278245SMiao Xie 		 */
17380b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
173967c5e7d4SFilipe Manana 
174067c5e7d4SFilipe Manana 		/*
174167c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
174267c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
174367c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
174467c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
174567c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
174667c5e7d4SFilipe Manana 		 * unused block groups.
174767c5e7d4SFilipe Manana 		 */
17480b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1749d0278245SMiao Xie sleep:
1750fd340d0fSJosef Bacik 		clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1751d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1752d6fd0ae2SOmar Sandoval 			kthread_parkme();
1753d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1754d6fd0ae2SOmar Sandoval 			return 0;
1755838fe188SJiri Kosina 		if (!again) {
1756a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1757a74a4b97SChris Mason 			schedule();
1758a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1759a74a4b97SChris Mason 		}
1760da288d28SFilipe Manana 	}
1761a74a4b97SChris Mason }
1762a74a4b97SChris Mason 
1763a74a4b97SChris Mason static int transaction_kthread(void *arg)
1764a74a4b97SChris Mason {
1765a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1767a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1768a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17698929ecfaSYan, Zheng 	u64 transid;
1770a944442cSAllen Pais 	time64_t now;
1771a74a4b97SChris Mason 	unsigned long delay;
1772914b2007SJan Kara 	bool cannot_commit;
1773a74a4b97SChris Mason 
1774a74a4b97SChris Mason 	do {
1775914b2007SJan Kara 		cannot_commit = false;
17760b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
17770b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1778a74a4b97SChris Mason 
17790b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17800b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1781a74a4b97SChris Mason 		if (!cur) {
17820b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1783a74a4b97SChris Mason 			goto sleep;
1784a74a4b97SChris Mason 		}
178531153d81SYan Zheng 
1786afd48513SArnd Bergmann 		now = ktime_get_seconds();
17873296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
17888b87dc17SDavid Sterba 		    (now < cur->start_time ||
17890b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
17900b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1791a74a4b97SChris Mason 			delay = HZ * 5;
1792a74a4b97SChris Mason 			goto sleep;
1793a74a4b97SChris Mason 		}
17948929ecfaSYan, Zheng 		transid = cur->transid;
17950b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
179656bec294SChris Mason 
179779787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1798354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1799914b2007SJan Kara 		if (IS_ERR(trans)) {
1800354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1801914b2007SJan Kara 				cannot_commit = true;
180279787eaaSJeff Mahoney 			goto sleep;
1803914b2007SJan Kara 		}
18048929ecfaSYan, Zheng 		if (transid == trans->transid) {
18053a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
18068929ecfaSYan, Zheng 		} else {
18073a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18088929ecfaSYan, Zheng 		}
1809a74a4b97SChris Mason sleep:
18100b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
18110b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1812a74a4b97SChris Mason 
18134e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
18140b246afaSJeff Mahoney 				      &fs_info->fs_state)))
18152ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
18168929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
18170b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1818914b2007SJan Kara 				 cannot_commit))
1819bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1820a74a4b97SChris Mason 	} while (!kthread_should_stop());
1821a74a4b97SChris Mason 	return 0;
1822a74a4b97SChris Mason }
1823a74a4b97SChris Mason 
1824af31f5e5SChris Mason /*
182501f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
182601f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
182701f0f9daSNikolay Borisov  * anything.
1828af31f5e5SChris Mason  *
1829af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1830af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1831af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1832af31f5e5SChris Mason  */
183301f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1834af31f5e5SChris Mason {
183501f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1836af31f5e5SChris Mason 	u64 cur;
1837af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1838af31f5e5SChris Mason 	int i;
1839af31f5e5SChris Mason 
1840af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1841af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1842af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1843af31f5e5SChris Mason 		if (cur == newest_gen)
184401f0f9daSNikolay Borisov 			return i;
1845af31f5e5SChris Mason 	}
1846af31f5e5SChris Mason 
184701f0f9daSNikolay Borisov 	return -EINVAL;
1848af31f5e5SChris Mason }
1849af31f5e5SChris Mason 
1850af31f5e5SChris Mason /*
1851af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1852af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1853af31f5e5SChris Mason  * done
1854af31f5e5SChris Mason  */
1855af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1856af31f5e5SChris Mason {
18576ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1858af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1859af31f5e5SChris Mason 
1860af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1861af31f5e5SChris Mason 
1862af31f5e5SChris Mason 	/*
1863af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1864af31f5e5SChris Mason 	 * regardless of which ones we use today
1865af31f5e5SChris Mason 	 */
1866af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1867af31f5e5SChris Mason 
1868af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1869af31f5e5SChris Mason 
1870af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1871af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1872af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1873af31f5e5SChris Mason 
1874af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1875af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1876af31f5e5SChris Mason 
1877af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1878af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1879af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1880af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1881af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1882af31f5e5SChris Mason 
1883af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1884af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1885af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1886af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1887af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1888af31f5e5SChris Mason 
18897c7e82a7SChris Mason 	/*
18907c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18917c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18927c7e82a7SChris Mason 	 */
18937c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18947c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18957c7e82a7SChris Mason 					 info->fs_root->node->start);
1896af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1897af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1898af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1899af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19007c7e82a7SChris Mason 	}
1901af31f5e5SChris Mason 
1902af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1903af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1904af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1905af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1906af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1907af31f5e5SChris Mason 
1908af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1909af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1910af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1911af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1912af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1913af31f5e5SChris Mason 
1914af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1915af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1916af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1917af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1918af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1919af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1920af31f5e5SChris Mason 
1921af31f5e5SChris Mason 	/*
1922af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1923af31f5e5SChris Mason 	 * for the next commit
1924af31f5e5SChris Mason 	 */
1925af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1926af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1927af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1928af31f5e5SChris Mason }
1929af31f5e5SChris Mason 
1930af31f5e5SChris Mason /*
1931bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1932bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1933bd2336b2SNikolay Borisov  *
1934bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1935bd2336b2SNikolay Borisov  * priority - priority of backup root required
1936bd2336b2SNikolay Borisov  *
1937bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1938bd2336b2SNikolay Borisov  */
1939bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1940bd2336b2SNikolay Borisov {
1941bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1942bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1943bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1944bd2336b2SNikolay Borisov 
1945bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1946bd2336b2SNikolay Borisov 		if (priority == 0)
1947bd2336b2SNikolay Borisov 			return backup_index;
1948bd2336b2SNikolay Borisov 
1949bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1950bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1951bd2336b2SNikolay Borisov 	} else {
1952bd2336b2SNikolay Borisov 		return -EINVAL;
1953bd2336b2SNikolay Borisov 	}
1954bd2336b2SNikolay Borisov 
1955bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1956bd2336b2SNikolay Borisov 
1957bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1958bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1959bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1960bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1961bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1962bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1963bd2336b2SNikolay Borisov 
1964bd2336b2SNikolay Borisov 	/*
1965bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1966bd2336b2SNikolay Borisov 	 * need a fsck
1967bd2336b2SNikolay Borisov 	 */
1968bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1969bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1970bd2336b2SNikolay Borisov 
1971bd2336b2SNikolay Borisov 	return backup_index;
1972bd2336b2SNikolay Borisov }
1973bd2336b2SNikolay Borisov 
19747abadb64SLiu Bo /* helper to cleanup workers */
19757abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19767abadb64SLiu Bo {
1977dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1978afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
19795cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1980fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
1981fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
1982d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
1983fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1984fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19855b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1986e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1987736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
1988a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1989fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1990b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1991b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1992a9b9477dSFilipe Manana 	/*
1993a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1994a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1995a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1996a9b9477dSFilipe Manana 	 */
1997a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
1998a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
19997abadb64SLiu Bo }
20007abadb64SLiu Bo 
20012e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20022e9f5954SRashika {
20032e9f5954SRashika 	if (root) {
20042e9f5954SRashika 		free_extent_buffer(root->node);
20052e9f5954SRashika 		free_extent_buffer(root->commit_root);
20062e9f5954SRashika 		root->node = NULL;
20072e9f5954SRashika 		root->commit_root = NULL;
20082e9f5954SRashika 	}
20092e9f5954SRashika }
20102e9f5954SRashika 
2011af31f5e5SChris Mason /* helper to cleanup tree roots */
20124273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2013af31f5e5SChris Mason {
20142e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2015655b09feSJosef Bacik 
20162e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
20172e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
20182e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
20192e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20202e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20218c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2022aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
20234273eaffSAnand Jain 	if (free_chunk_root)
20242e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
202570f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2026af31f5e5SChris Mason }
2027af31f5e5SChris Mason 
20288c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
20298c38938cSJosef Bacik {
20308c38938cSJosef Bacik 	if (!root)
20318c38938cSJosef Bacik 		return;
20328c38938cSJosef Bacik 
20338c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
20348c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
20351dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
20368c38938cSJosef Bacik 		if (root->anon_dev)
20378c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
20388c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2039923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
20408c38938cSJosef Bacik 		kfree(root->free_ino_ctl);
20418c38938cSJosef Bacik 		kfree(root->free_ino_pinned);
20428c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
20438c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
20448c38938cSJosef Bacik 		list_del_init(&root->leak_list);
20458c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
20468c38938cSJosef Bacik #endif
20478c38938cSJosef Bacik 		kfree(root);
20488c38938cSJosef Bacik 	}
20498c38938cSJosef Bacik }
20508c38938cSJosef Bacik 
2051faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2052171f6537SJosef Bacik {
2053171f6537SJosef Bacik 	int ret;
2054171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2055171f6537SJosef Bacik 	int i;
2056171f6537SJosef Bacik 
2057171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2058171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2059171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2060171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2061171f6537SJosef Bacik 
20628c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2063cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
206400246528SJosef Bacik 		btrfs_put_root(gang[0]);
2065171f6537SJosef Bacik 	}
2066171f6537SJosef Bacik 
2067171f6537SJosef Bacik 	while (1) {
2068171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2069171f6537SJosef Bacik 					     (void **)gang, 0,
2070171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2071171f6537SJosef Bacik 		if (!ret)
2072171f6537SJosef Bacik 			break;
2073171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2074cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2075171f6537SJosef Bacik 	}
2076171f6537SJosef Bacik }
2077af31f5e5SChris Mason 
2078638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2079638aa7edSEric Sandeen {
2080638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2081638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2082638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2083638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2084638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2085638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2086ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2087638aa7edSEric Sandeen }
2088638aa7edSEric Sandeen 
2089779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2090779a65a4SEric Sandeen {
2091779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2092779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2093779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2094779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2095779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2096779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2097779a65a4SEric Sandeen }
2098779a65a4SEric Sandeen 
20996bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2100f37938e0SEric Sandeen {
21012ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
21022ff7e61eSJeff Mahoney 
21032ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
21042ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2105f37938e0SEric Sandeen 	/*
2106f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2107f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2108f37938e0SEric Sandeen 	 * the devices in the system
2109f37938e0SEric Sandeen 	 */
21102ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
21112ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2112f37938e0SEric Sandeen 
21132ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
211443eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
211543eb5f29SQu Wenruo 			    IO_TREE_INODE_IO, inode);
21167b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
21172ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2118f37938e0SEric Sandeen 
21192ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2120f37938e0SEric Sandeen 
21215c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
21222ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
21232ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
21242ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2125f37938e0SEric Sandeen }
2126f37938e0SEric Sandeen 
2127ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2128ad618368SEric Sandeen {
2129ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2130129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
21317f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2132ad618368SEric Sandeen }
2133ad618368SEric Sandeen 
2134f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2135f9e92e40SEric Sandeen {
2136f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2137f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2138f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2139f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2140f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2141f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2142d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2143f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2144f9e92e40SEric Sandeen }
2145f9e92e40SEric Sandeen 
21462a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
21472a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
21482a458198SEric Sandeen {
2149f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21506f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21512a458198SEric Sandeen 
21522a458198SEric Sandeen 	fs_info->workers =
2153cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2154cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21552a458198SEric Sandeen 
21562a458198SEric Sandeen 	fs_info->delalloc_workers =
2157cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2158cb001095SJeff Mahoney 				      flags, max_active, 2);
21592a458198SEric Sandeen 
21602a458198SEric Sandeen 	fs_info->flush_workers =
2161cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2162cb001095SJeff Mahoney 				      flags, max_active, 0);
21632a458198SEric Sandeen 
21642a458198SEric Sandeen 	fs_info->caching_workers =
2165cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21662a458198SEric Sandeen 
21672a458198SEric Sandeen 	fs_info->fixup_workers =
2168cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
21692a458198SEric Sandeen 
21702a458198SEric Sandeen 	/*
21712a458198SEric Sandeen 	 * endios are largely parallel and should have a very
21722a458198SEric Sandeen 	 * low idle thresh
21732a458198SEric Sandeen 	 */
21742a458198SEric Sandeen 	fs_info->endio_workers =
2175cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
21762a458198SEric Sandeen 	fs_info->endio_meta_workers =
2177cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2178cb001095SJeff Mahoney 				      max_active, 4);
21792a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2180cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2181cb001095SJeff Mahoney 				      max_active, 2);
21822a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2183cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2184cb001095SJeff Mahoney 				      max_active, 4);
21852a458198SEric Sandeen 	fs_info->rmw_workers =
2186cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
21872a458198SEric Sandeen 	fs_info->endio_write_workers =
2188cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2189cb001095SJeff Mahoney 				      max_active, 2);
21902a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2191cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2192cb001095SJeff Mahoney 				      max_active, 0);
21932a458198SEric Sandeen 	fs_info->delayed_workers =
2194cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2195cb001095SJeff Mahoney 				      max_active, 0);
21962a458198SEric Sandeen 	fs_info->readahead_workers =
2197cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2198cb001095SJeff Mahoney 				      max_active, 2);
21992a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2200cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2201b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2202b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
22032a458198SEric Sandeen 
22042a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2205ba8a9d07SChris Mason 	      fs_info->flush_workers &&
22062a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
22072a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
22082a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
22092a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
22102a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
22112a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2212b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2213b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
22142a458198SEric Sandeen 		return -ENOMEM;
22152a458198SEric Sandeen 	}
22162a458198SEric Sandeen 
22172a458198SEric Sandeen 	return 0;
22182a458198SEric Sandeen }
22192a458198SEric Sandeen 
22206d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
22216d97c6e3SJohannes Thumshirn {
22226d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2223b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
22246d97c6e3SJohannes Thumshirn 
2225b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
22266d97c6e3SJohannes Thumshirn 
22276d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
22286d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2229b4e967beSDavid Sterba 			  csum_driver);
22306d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
22316d97c6e3SJohannes Thumshirn 	}
22326d97c6e3SJohannes Thumshirn 
22336d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
22346d97c6e3SJohannes Thumshirn 
22356d97c6e3SJohannes Thumshirn 	return 0;
22366d97c6e3SJohannes Thumshirn }
22376d97c6e3SJohannes Thumshirn 
223863443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
223963443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
224063443bf5SEric Sandeen {
224163443bf5SEric Sandeen 	int ret;
224263443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
224363443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
224463443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2245581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
224663443bf5SEric Sandeen 
224763443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2248f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
224963443bf5SEric Sandeen 		return -EIO;
225063443bf5SEric Sandeen 	}
225163443bf5SEric Sandeen 
225296dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
225396dfcb46SJosef Bacik 					 GFP_KERNEL);
225463443bf5SEric Sandeen 	if (!log_tree_root)
225563443bf5SEric Sandeen 		return -ENOMEM;
225663443bf5SEric Sandeen 
22572ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
2258581c1760SQu Wenruo 					      fs_info->generation + 1,
2259581c1760SQu Wenruo 					      level, NULL);
226064c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2261f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22620eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
22638c38938cSJosef Bacik 		log_tree_root->node = NULL;
226400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
22650eeff236SLiu Bo 		return ret;
226664c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2267f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
226800246528SJosef Bacik 		btrfs_put_root(log_tree_root);
226963443bf5SEric Sandeen 		return -EIO;
227063443bf5SEric Sandeen 	}
227163443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
227263443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
227363443bf5SEric Sandeen 	if (ret) {
22740b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
227563443bf5SEric Sandeen 				      "Failed to recover log tree");
227600246528SJosef Bacik 		btrfs_put_root(log_tree_root);
227763443bf5SEric Sandeen 		return ret;
227863443bf5SEric Sandeen 	}
227963443bf5SEric Sandeen 
2280bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
22816bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
228263443bf5SEric Sandeen 		if (ret)
228363443bf5SEric Sandeen 			return ret;
228463443bf5SEric Sandeen 	}
228563443bf5SEric Sandeen 
228663443bf5SEric Sandeen 	return 0;
228763443bf5SEric Sandeen }
228863443bf5SEric Sandeen 
22896bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
22904bbcaa64SEric Sandeen {
22916bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2292a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
22934bbcaa64SEric Sandeen 	struct btrfs_key location;
22944bbcaa64SEric Sandeen 	int ret;
22954bbcaa64SEric Sandeen 
22966bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
22976bccf3abSJeff Mahoney 
22984bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
22994bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
23004bbcaa64SEric Sandeen 	location.offset = 0;
23014bbcaa64SEric Sandeen 
2302a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2303f50f4353SLiu Bo 	if (IS_ERR(root)) {
2304f50f4353SLiu Bo 		ret = PTR_ERR(root);
2305f50f4353SLiu Bo 		goto out;
2306f50f4353SLiu Bo 	}
2307a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2308a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
23094bbcaa64SEric Sandeen 
23104bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2311a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2312f50f4353SLiu Bo 	if (IS_ERR(root)) {
2313f50f4353SLiu Bo 		ret = PTR_ERR(root);
2314f50f4353SLiu Bo 		goto out;
2315f50f4353SLiu Bo 	}
2316a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2317a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
23184bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
23194bbcaa64SEric Sandeen 
23204bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2321a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2322f50f4353SLiu Bo 	if (IS_ERR(root)) {
2323f50f4353SLiu Bo 		ret = PTR_ERR(root);
2324f50f4353SLiu Bo 		goto out;
2325f50f4353SLiu Bo 	}
2326a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2327a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
23284bbcaa64SEric Sandeen 
2329aeb935a4SQu Wenruo 	/*
2330aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2331aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2332aeb935a4SQu Wenruo 	 */
233356e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
233456e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2335aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
2336aeb935a4SQu Wenruo 		ret = PTR_ERR(root);
2337aeb935a4SQu Wenruo 		goto out;
2338aeb935a4SQu Wenruo 	}
2339aeb935a4SQu Wenruo 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2340aeb935a4SQu Wenruo 	fs_info->data_reloc_root = root;
2341aeb935a4SQu Wenruo 
23424bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2343a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2344a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2345a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2346afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2347a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
23484bbcaa64SEric Sandeen 	}
23494bbcaa64SEric Sandeen 
23504bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2351a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2352a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2353a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
23544bbcaa64SEric Sandeen 		if (ret != -ENOENT)
2355f50f4353SLiu Bo 			goto out;
23564bbcaa64SEric Sandeen 	} else {
2357a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2358a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
23594bbcaa64SEric Sandeen 	}
23604bbcaa64SEric Sandeen 
236170f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
236270f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
236370f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2364f50f4353SLiu Bo 		if (IS_ERR(root)) {
2365f50f4353SLiu Bo 			ret = PTR_ERR(root);
2366f50f4353SLiu Bo 			goto out;
2367f50f4353SLiu Bo 		}
236870f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
236970f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
237070f6d82eSOmar Sandoval 	}
237170f6d82eSOmar Sandoval 
23724bbcaa64SEric Sandeen 	return 0;
2373f50f4353SLiu Bo out:
2374f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2375f50f4353SLiu Bo 		   location.objectid, ret);
2376f50f4353SLiu Bo 	return ret;
23774bbcaa64SEric Sandeen }
23784bbcaa64SEric Sandeen 
2379069ec957SQu Wenruo /*
2380069ec957SQu Wenruo  * Real super block validation
2381069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2382069ec957SQu Wenruo  *
2383069ec957SQu Wenruo  * @sb:		super block to check
2384069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2385069ec957SQu Wenruo  * 		0	the primary (1st) sb
2386069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2387069ec957SQu Wenruo  * 	       -1	skip bytenr check
2388069ec957SQu Wenruo  */
2389069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2390069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
239121a852b0SQu Wenruo {
239221a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
239321a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
239421a852b0SQu Wenruo 	int ret = 0;
239521a852b0SQu Wenruo 
239621a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
239721a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
239821a852b0SQu Wenruo 		ret = -EINVAL;
239921a852b0SQu Wenruo 	}
240021a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
240121a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
240221a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
240321a852b0SQu Wenruo 		ret = -EINVAL;
240421a852b0SQu Wenruo 	}
240521a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
240621a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
240721a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
240821a852b0SQu Wenruo 		ret = -EINVAL;
240921a852b0SQu Wenruo 	}
241021a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
241121a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
241221a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
241321a852b0SQu Wenruo 		ret = -EINVAL;
241421a852b0SQu Wenruo 	}
241521a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
241621a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
241721a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
241821a852b0SQu Wenruo 		ret = -EINVAL;
241921a852b0SQu Wenruo 	}
242021a852b0SQu Wenruo 
242121a852b0SQu Wenruo 	/*
242221a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
242321a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
242421a852b0SQu Wenruo 	 */
242521a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
242621a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
242721a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
242821a852b0SQu Wenruo 		ret = -EINVAL;
242921a852b0SQu Wenruo 	}
243021a852b0SQu Wenruo 	/* Only PAGE SIZE is supported yet */
243121a852b0SQu Wenruo 	if (sectorsize != PAGE_SIZE) {
243221a852b0SQu Wenruo 		btrfs_err(fs_info,
243321a852b0SQu Wenruo 			"sectorsize %llu not supported yet, only support %lu",
243421a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
243521a852b0SQu Wenruo 		ret = -EINVAL;
243621a852b0SQu Wenruo 	}
243721a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
243821a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
243921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
244021a852b0SQu Wenruo 		ret = -EINVAL;
244121a852b0SQu Wenruo 	}
244221a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
244321a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
244421a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
244521a852b0SQu Wenruo 		ret = -EINVAL;
244621a852b0SQu Wenruo 	}
244721a852b0SQu Wenruo 
244821a852b0SQu Wenruo 	/* Root alignment check */
244921a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
245021a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
245121a852b0SQu Wenruo 			   btrfs_super_root(sb));
245221a852b0SQu Wenruo 		ret = -EINVAL;
245321a852b0SQu Wenruo 	}
245421a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
245521a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
245621a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
245721a852b0SQu Wenruo 		ret = -EINVAL;
245821a852b0SQu Wenruo 	}
245921a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
246021a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
246121a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
246221a852b0SQu Wenruo 		ret = -EINVAL;
246321a852b0SQu Wenruo 	}
246421a852b0SQu Wenruo 
2465de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
24667239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
246721a852b0SQu Wenruo 		btrfs_err(fs_info,
24687239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2469de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
247021a852b0SQu Wenruo 		ret = -EINVAL;
247121a852b0SQu Wenruo 	}
247221a852b0SQu Wenruo 
247321a852b0SQu Wenruo 	/*
247421a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
247521a852b0SQu Wenruo 	 * done later
247621a852b0SQu Wenruo 	 */
247721a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
247821a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
247921a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
248021a852b0SQu Wenruo 		ret = -EINVAL;
248121a852b0SQu Wenruo 	}
248221a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
248321a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
248421a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
248521a852b0SQu Wenruo 		ret = -EINVAL;
248621a852b0SQu Wenruo 	}
248721a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
248821a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
248921a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
249021a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
249121a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
249221a852b0SQu Wenruo 		ret = -EINVAL;
249321a852b0SQu Wenruo 	}
249421a852b0SQu Wenruo 
2495069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2496069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
249721a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
249821a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
249921a852b0SQu Wenruo 		ret = -EINVAL;
250021a852b0SQu Wenruo 	}
250121a852b0SQu Wenruo 
250221a852b0SQu Wenruo 	/*
250321a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
250421a852b0SQu Wenruo 	 * and one chunk
250521a852b0SQu Wenruo 	 */
250621a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
250721a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
250821a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
250921a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
251021a852b0SQu Wenruo 		ret = -EINVAL;
251121a852b0SQu Wenruo 	}
251221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
251321a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
251421a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
251521a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
251621a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
251721a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
251821a852b0SQu Wenruo 		ret = -EINVAL;
251921a852b0SQu Wenruo 	}
252021a852b0SQu Wenruo 
252121a852b0SQu Wenruo 	/*
252221a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
252321a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
252421a852b0SQu Wenruo 	 */
252521a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
252621a852b0SQu Wenruo 		btrfs_warn(fs_info,
252721a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
252821a852b0SQu Wenruo 			btrfs_super_generation(sb),
252921a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
253021a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
253121a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
253221a852b0SQu Wenruo 		btrfs_warn(fs_info,
253321a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
253421a852b0SQu Wenruo 			btrfs_super_generation(sb),
253521a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
253621a852b0SQu Wenruo 
253721a852b0SQu Wenruo 	return ret;
253821a852b0SQu Wenruo }
253921a852b0SQu Wenruo 
2540069ec957SQu Wenruo /*
2541069ec957SQu Wenruo  * Validation of super block at mount time.
2542069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2543069ec957SQu Wenruo  * flags will be skipped.
2544069ec957SQu Wenruo  */
2545069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2546069ec957SQu Wenruo {
2547069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2548069ec957SQu Wenruo }
2549069ec957SQu Wenruo 
255075cb857dSQu Wenruo /*
255175cb857dSQu Wenruo  * Validation of super block at write time.
255275cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
255375cb857dSQu Wenruo  * overwritten soon.
255475cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
255575cb857dSQu Wenruo  */
255675cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
255775cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
255875cb857dSQu Wenruo {
255975cb857dSQu Wenruo 	int ret;
256075cb857dSQu Wenruo 
256175cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
256275cb857dSQu Wenruo 	if (ret < 0)
256375cb857dSQu Wenruo 		goto out;
2564e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
256575cb857dSQu Wenruo 		ret = -EUCLEAN;
256675cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
256775cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
256875cb857dSQu Wenruo 		goto out;
256975cb857dSQu Wenruo 	}
257075cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
257175cb857dSQu Wenruo 		ret = -EUCLEAN;
257275cb857dSQu Wenruo 		btrfs_err(fs_info,
257375cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
257475cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
257575cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
257675cb857dSQu Wenruo 		goto out;
257775cb857dSQu Wenruo 	}
257875cb857dSQu Wenruo out:
257975cb857dSQu Wenruo 	if (ret < 0)
258075cb857dSQu Wenruo 		btrfs_err(fs_info,
258175cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
258275cb857dSQu Wenruo 	return ret;
258375cb857dSQu Wenruo }
258475cb857dSQu Wenruo 
25856ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2586b8522a1eSNikolay Borisov {
25876ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2588b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2589b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2590b8522a1eSNikolay Borisov 	bool handle_error = false;
2591b8522a1eSNikolay Borisov 	int ret = 0;
2592b8522a1eSNikolay Borisov 	int i;
2593b8522a1eSNikolay Borisov 
2594b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2595b8522a1eSNikolay Borisov 		u64 generation;
2596b8522a1eSNikolay Borisov 		int level;
2597b8522a1eSNikolay Borisov 
2598b8522a1eSNikolay Borisov 		if (handle_error) {
2599b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2600b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2601b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2602b8522a1eSNikolay Borisov 
2603b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2604b8522a1eSNikolay Borisov 				break;
2605b8522a1eSNikolay Borisov 
2606b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2607b8522a1eSNikolay Borisov 
2608b8522a1eSNikolay Borisov 			/*
2609b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2610b8522a1eSNikolay Borisov 			 * valid
2611b8522a1eSNikolay Borisov 			 */
2612b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2613b8522a1eSNikolay Borisov 
2614b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2615b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2616b8522a1eSNikolay Borisov 
2617b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
26186ef108ddSNikolay Borisov 			backup_index = ret;
2619b8522a1eSNikolay Borisov 			if (ret < 0)
2620b8522a1eSNikolay Borisov 				return ret;
2621b8522a1eSNikolay Borisov 		}
2622b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2623b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2624b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
2625b8522a1eSNikolay Borisov 						  generation, level, NULL);
2626b8522a1eSNikolay Borisov 		if (IS_ERR(tree_root->node) ||
2627b8522a1eSNikolay Borisov 		    !extent_buffer_uptodate(tree_root->node)) {
2628b8522a1eSNikolay Borisov 			handle_error = true;
2629b8522a1eSNikolay Borisov 
26300465337cSJosef Bacik 			if (IS_ERR(tree_root->node)) {
2631b8522a1eSNikolay Borisov 				ret = PTR_ERR(tree_root->node);
26320465337cSJosef Bacik 				tree_root->node = NULL;
26330465337cSJosef Bacik 			} else if (!extent_buffer_uptodate(tree_root->node)) {
2634b8522a1eSNikolay Borisov 				ret = -EUCLEAN;
26350465337cSJosef Bacik 			}
2636b8522a1eSNikolay Borisov 
2637b8522a1eSNikolay Borisov 			btrfs_warn(fs_info, "failed to read tree root");
2638b8522a1eSNikolay Borisov 			continue;
2639b8522a1eSNikolay Borisov 		}
2640b8522a1eSNikolay Borisov 
2641b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2642b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2643b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2644b8522a1eSNikolay Borisov 
2645336a0d8dSNikolay Borisov 		/*
2646336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2647336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2648336a0d8dSNikolay Borisov 		 */
2649b8522a1eSNikolay Borisov 		ret = btrfs_find_highest_objectid(tree_root,
2650b8522a1eSNikolay Borisov 						&tree_root->highest_objectid);
2651b8522a1eSNikolay Borisov 		if (ret < 0) {
2652b8522a1eSNikolay Borisov 			handle_error = true;
2653b8522a1eSNikolay Borisov 			continue;
2654b8522a1eSNikolay Borisov 		}
2655b8522a1eSNikolay Borisov 
2656b8522a1eSNikolay Borisov 		ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2657b8522a1eSNikolay Borisov 
2658b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2659b8522a1eSNikolay Borisov 		if (ret < 0) {
2660b8522a1eSNikolay Borisov 			handle_error = true;
2661b8522a1eSNikolay Borisov 			continue;
2662b8522a1eSNikolay Borisov 		}
2663b8522a1eSNikolay Borisov 
2664b8522a1eSNikolay Borisov 		/* All successful */
2665b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2666b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
26676ef108ddSNikolay Borisov 
26686ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26696ef108ddSNikolay Borisov 		if (backup_index < 0) {
26706ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26716ef108ddSNikolay Borisov 		} else {
26726ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26736ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26746ef108ddSNikolay Borisov 		}
2675b8522a1eSNikolay Borisov 		break;
2676b8522a1eSNikolay Borisov 	}
2677b8522a1eSNikolay Borisov 
2678b8522a1eSNikolay Borisov 	return ret;
2679b8522a1eSNikolay Borisov }
2680b8522a1eSNikolay Borisov 
26818260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2682eb60ceacSChris Mason {
268376dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2684f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26858fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2686facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
268724bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2688eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
268911833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2690eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2691a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
269276dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
269324bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26944cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2695ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2696f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
269747ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2698f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2699d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
270067c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
27017585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2702573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2703de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
270419c00ddcSChris Mason 
27050b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
27066324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2707f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
270847ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2709bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2710bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
27113fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
27123fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2713bd647ce3SJosef Bacik #endif
2714c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
271566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
271666d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
271766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
271866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
271966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
272066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
272166d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2722ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2723ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2724ba2c4d4eSJosef Bacik 
2725771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
27264cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
27272fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2728034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2729fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
273095ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27319ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27324cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2733a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2734f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27358b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2736f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
273790519d66SArne Jansen 	/* readahead state */
2738d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
273990519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2740fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2741c8b97818SChris Mason 
2742b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2743b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27440afbaf8cSChris Mason 
2745199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2746199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
274769fe2d75SJosef Bacik 
2748638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
274921adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
275021adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
275121adbd5cSStefan Behrens #endif
2752779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
275357056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2754a2de733cSArne Jansen 
27550f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
27566bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2757a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
27580f9dd46cSJosef Bacik 
2759fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2760fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2761afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
276239279cc3SChris Mason 
27635a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2764e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2765925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2766a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2767a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27681bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27699e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2770c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
277176dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2772803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2773fa9c0d79SChris Mason 
2774ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2775f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2776b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2777416ac51dSArne Jansen 
2778fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2779fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2780fa9c0d79SChris Mason 
2781e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2782f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2783bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27844854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2785034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
27863768f368SChris Mason 
2787da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2788da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2789da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2790da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2791da17066cSJeff Mahoney 
2792eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2793eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2794eede2bf3SOmar Sandoval 
27959e967495SFilipe Manana 	fs_info->send_in_progress = 0;
27968260edbaSJosef Bacik }
27978260edbaSJosef Bacik 
27988260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
27998260edbaSJosef Bacik {
28008260edbaSJosef Bacik 	int ret;
28018260edbaSJosef Bacik 
28028260edbaSJosef Bacik 	fs_info->sb = sb;
28038260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
28048260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
28059e967495SFilipe Manana 
2806c75e8394SJosef Bacik 	ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
2807ae18c37aSJosef Bacik 	if (ret)
2808ae18c37aSJosef Bacik 		return ret;
2809ae18c37aSJosef Bacik 
2810ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2811ae18c37aSJosef Bacik 	if (ret)
2812c75e8394SJosef Bacik 		return ret;
2813ae18c37aSJosef Bacik 
2814ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2815ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2816ae18c37aSJosef Bacik 
2817ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2818ae18c37aSJosef Bacik 	if (ret)
2819c75e8394SJosef Bacik 		return ret;
2820ae18c37aSJosef Bacik 
2821ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2822ae18c37aSJosef Bacik 			GFP_KERNEL);
2823ae18c37aSJosef Bacik 	if (ret)
2824c75e8394SJosef Bacik 		return ret;
2825ae18c37aSJosef Bacik 
2826ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2827ae18c37aSJosef Bacik 					GFP_KERNEL);
2828c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2829c75e8394SJosef Bacik 		return -ENOMEM;
2830ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2831ae18c37aSJosef Bacik 
2832c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2833ae18c37aSJosef Bacik }
2834ae18c37aSJosef Bacik 
283597f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
283697f4dd09SNikolay Borisov {
283797f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
283897f4dd09SNikolay Borisov 	int ret;
283997f4dd09SNikolay Borisov 
284097f4dd09SNikolay Borisov 	/*
284197f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
284297f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
284397f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
284497f4dd09SNikolay Borisov 	 */
284597f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
284697f4dd09SNikolay Borisov 	if (ret < 0) {
2847c94bec2cSJosef Bacik 		if (ret != -EINTR)
2848c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2849c94bec2cSJosef Bacik 				   ret);
285097f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
285197f4dd09SNikolay Borisov 		return ret;
285297f4dd09SNikolay Borisov 	}
285397f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
285497f4dd09SNikolay Borisov }
285597f4dd09SNikolay Borisov 
285697f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
285797f4dd09SNikolay Borisov {
285897f4dd09SNikolay Borisov 	struct task_struct *task;
285997f4dd09SNikolay Borisov 
286097f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
286197f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
286297f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
286397f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
286497f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
286597f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
286697f4dd09SNikolay Borisov 		return PTR_ERR(task);
286797f4dd09SNikolay Borisov 	}
286897f4dd09SNikolay Borisov 
286997f4dd09SNikolay Borisov 	return 0;
287097f4dd09SNikolay Borisov }
287197f4dd09SNikolay Borisov 
2872ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
2873ae18c37aSJosef Bacik 		      char *options)
2874ae18c37aSJosef Bacik {
2875ae18c37aSJosef Bacik 	u32 sectorsize;
2876ae18c37aSJosef Bacik 	u32 nodesize;
2877ae18c37aSJosef Bacik 	u32 stripesize;
2878ae18c37aSJosef Bacik 	u64 generation;
2879ae18c37aSJosef Bacik 	u64 features;
2880ae18c37aSJosef Bacik 	u16 csum_type;
2881ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
2882ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2883ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
2884ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
2885ae18c37aSJosef Bacik 	int ret;
2886ae18c37aSJosef Bacik 	int err = -EINVAL;
2887ae18c37aSJosef Bacik 	int clear_free_space_tree = 0;
2888ae18c37aSJosef Bacik 	int level;
2889ae18c37aSJosef Bacik 
28908260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
289153b381b3SDavid Woodhouse 	if (ret) {
289283c8266aSDavid Sterba 		err = ret;
2893ae18c37aSJosef Bacik 		goto fail;
289453b381b3SDavid Woodhouse 	}
289553b381b3SDavid Woodhouse 
2896ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
2897ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
2898ae18c37aSJosef Bacik 				     GFP_KERNEL);
2899ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
2900ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
2901ae18c37aSJosef Bacik 				      GFP_KERNEL);
2902ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
2903ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
2904ae18c37aSJosef Bacik 		err = -ENOMEM;
2905c75e8394SJosef Bacik 		goto fail;
2906ae18c37aSJosef Bacik 	}
2907ae18c37aSJosef Bacik 
2908ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
2909ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
2910ae18c37aSJosef Bacik 		err = -ENOMEM;
2911c75e8394SJosef Bacik 		goto fail;
2912ae18c37aSJosef Bacik 	}
2913ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2914ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
2915ae18c37aSJosef Bacik 
29163c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
29171104a885SDavid Sterba 
29181104a885SDavid Sterba 	/*
29191104a885SDavid Sterba 	 * Read super block and check the signature bytes only
29201104a885SDavid Sterba 	 */
29218f32380dSJohannes Thumshirn 	disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
29228f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
29238f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
292416cdcec7SMiao Xie 		goto fail_alloc;
292520b45077SDave Young 	}
292639279cc3SChris Mason 
29271104a885SDavid Sterba 	/*
2928260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
29298dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
29308dc3f22cSJohannes Thumshirn 	 */
29318f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
293251bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
29338dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
293451bce6c9SJohannes Thumshirn 			  csum_type);
29358dc3f22cSJohannes Thumshirn 		err = -EINVAL;
29368f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
29378dc3f22cSJohannes Thumshirn 		goto fail_alloc;
29388dc3f22cSJohannes Thumshirn 	}
29398dc3f22cSJohannes Thumshirn 
29406d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
29416d97c6e3SJohannes Thumshirn 	if (ret) {
29426d97c6e3SJohannes Thumshirn 		err = ret;
29438f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
29446d97c6e3SJohannes Thumshirn 		goto fail_alloc;
29456d97c6e3SJohannes Thumshirn 	}
29466d97c6e3SJohannes Thumshirn 
29478dc3f22cSJohannes Thumshirn 	/*
29481104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
29491104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
29501104a885SDavid Sterba 	 */
29518f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
295205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
29531104a885SDavid Sterba 		err = -EINVAL;
29548f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
2955141386e1SJosef Bacik 		goto fail_alloc;
29561104a885SDavid Sterba 	}
29571104a885SDavid Sterba 
29581104a885SDavid Sterba 	/*
29591104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
29601104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
29611104a885SDavid Sterba 	 * the whole block of INFO_SIZE
29621104a885SDavid Sterba 	 */
29638f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
29648f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
29655f39d397SChris Mason 
2966fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
2967fbc6feaeSNikolay Borisov 
2968de37aa51SNikolay Borisov 	ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2969de37aa51SNikolay Borisov 		       BTRFS_FSID_SIZE));
2970de37aa51SNikolay Borisov 
29717239ff4bSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
2972de37aa51SNikolay Borisov 		ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
2973de37aa51SNikolay Borisov 				fs_info->super_copy->metadata_uuid,
2974de37aa51SNikolay Borisov 				BTRFS_FSID_SIZE));
29757239ff4bSNikolay Borisov 	}
29760b86a832SChris Mason 
2977fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
2978fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
2979fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
2980fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
2981fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
2982fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
2983fbc6feaeSNikolay Borisov 	}
2984fbc6feaeSNikolay Borisov 
2985fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
2986fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
2987de37aa51SNikolay Borisov 
2988069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
29891104a885SDavid Sterba 	if (ret) {
299005135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
29911104a885SDavid Sterba 		err = -EINVAL;
2992141386e1SJosef Bacik 		goto fail_alloc;
29931104a885SDavid Sterba 	}
29941104a885SDavid Sterba 
29950f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
2996141386e1SJosef Bacik 		goto fail_alloc;
29970f7d52f4SChris Mason 
2998acce952bSliubo 	/* check FS state, whether FS is broken. */
299987533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
300087533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3001acce952bSliubo 
300275e7cb7fSLiu Bo 	/*
300375e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
300475e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
300575e7cb7fSLiu Bo 	 */
300675e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
300775e7cb7fSLiu Bo 
30082ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
30092b82032cSYan Zheng 	if (ret) {
30102b82032cSYan Zheng 		err = ret;
3011141386e1SJosef Bacik 		goto fail_alloc;
30122b82032cSYan Zheng 	}
3013dfe25020SChris Mason 
3014f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3015f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3016f2b636e8SJosef Bacik 	if (features) {
301705135f59SDavid Sterba 		btrfs_err(fs_info,
301805135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3019c1c9ff7cSGeert Uytterhoeven 		    features);
3020f2b636e8SJosef Bacik 		err = -EINVAL;
3021141386e1SJosef Bacik 		goto fail_alloc;
3022f2b636e8SJosef Bacik 	}
3023f2b636e8SJosef Bacik 
30245d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
30255d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
30260b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3027a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
30285c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
30295c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3030727011e0SChris Mason 
30313173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
303205135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
30333173a18fSJosef Bacik 
3034727011e0SChris Mason 	/*
3035727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
3036727011e0SChris Mason 	 * they are bigger than the page size
3037727011e0SChris Mason 	 */
303809cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
3039727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
304005135f59SDavid Sterba 			btrfs_info(fs_info,
304105135f59SDavid Sterba 				"flagging fs with big metadata feature");
3042727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3043727011e0SChris Mason 	}
3044727011e0SChris Mason 
3045bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
3046bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
3047b7f67055SChandan Rajendra 	stripesize = sectorsize;
3048707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3049963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3050bc3f116fSChris Mason 
3051da17066cSJeff Mahoney 	/* Cache block sizes */
3052da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
3053da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
3054da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
3055da17066cSJeff Mahoney 
3056bc3f116fSChris Mason 	/*
3057bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3058bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3059bc3f116fSChris Mason 	 */
3060bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3061707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
306205135f59SDavid Sterba 		btrfs_err(fs_info,
306305135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
306405135f59SDavid Sterba 			nodesize, sectorsize);
3065141386e1SJosef Bacik 		goto fail_alloc;
3066bc3f116fSChris Mason 	}
3067bc3f116fSChris Mason 
3068ceda0864SMiao Xie 	/*
3069ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3070ceda0864SMiao Xie 	 * update the flag.
3071ceda0864SMiao Xie 	 */
30725d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
30735d4f98a2SYan Zheng 
3074f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3075f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3076bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
307705135f59SDavid Sterba 		btrfs_err(fs_info,
307805135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3079c1c9ff7cSGeert Uytterhoeven 		       features);
3080f2b636e8SJosef Bacik 		err = -EINVAL;
3081141386e1SJosef Bacik 		goto fail_alloc;
3082f2b636e8SJosef Bacik 	}
308361d92c32SChris Mason 
30842a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
30852a458198SEric Sandeen 	if (ret) {
30862a458198SEric Sandeen 		err = ret;
30870dc3b84aSJosef Bacik 		goto fail_sb_buffer;
30880dc3b84aSJosef Bacik 	}
30894543df7eSChris Mason 
30909e11ceeeSJan Kara 	sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
3091b5420237SNikolay Borisov 	sb->s_bdi->ra_pages = VM_READAHEAD_PAGES;
30929e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
30939e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
30944575c9ccSChris Mason 
3095a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3096a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3097de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3098db94535dSChris Mason 
3099925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
31006bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3101925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
310284eed90fSChris Mason 	if (ret) {
310305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
31045d4f98a2SYan Zheng 		goto fail_sb_buffer;
310584eed90fSChris Mason 	}
31060b86a832SChris Mason 
310784234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3108581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
31090b86a832SChris Mason 
31102ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
31110b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
3112581c1760SQu Wenruo 					   generation, level, NULL);
311364c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
311464c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
311505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3116e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3117e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
311895ab1f64SZhao Lei 		chunk_root->node = NULL;
3119af31f5e5SChris Mason 		goto fail_tree_roots;
312083121942SDavid Woodhouse 	}
31215d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
31225d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
31230b86a832SChris Mason 
3124e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3125c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3126c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3127e17cade2SChris Mason 
31285b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
31292b82032cSYan Zheng 	if (ret) {
313005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3131af31f5e5SChris Mason 		goto fail_tree_roots;
31322b82032cSYan Zheng 	}
31330b86a832SChris Mason 
31348dabb742SStefan Behrens 	/*
31359b99b115SAnand Jain 	 * Keep the devid that is marked to be the target device for the
31369b99b115SAnand Jain 	 * device replace procedure
31378dabb742SStefan Behrens 	 */
31389b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 0);
3139dfe25020SChris Mason 
3140a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
314105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3142a6b0d5c8SChris Mason 		goto fail_tree_roots;
3143a6b0d5c8SChris Mason 	}
3144a6b0d5c8SChris Mason 
3145b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
31464bbcaa64SEric Sandeen 	if (ret)
3147b8522a1eSNikolay Borisov 		goto fail_tree_roots;
31488929ecfaSYan, Zheng 
314975ec1db8SJosef Bacik 	/*
315075ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
315175ec1db8SJosef Bacik 	 * check the generation here so we can set the
315275ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
315375ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
315475ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
315575ec1db8SJosef Bacik 	 * even though it was perfectly fine.
315675ec1db8SJosef Bacik 	 */
315775ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
315875ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
315975ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
316075ec1db8SJosef Bacik 
3161cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3162cf90d884SQu Wenruo 	if (ret) {
3163cf90d884SQu Wenruo 		btrfs_err(fs_info,
3164cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3165cf90d884SQu Wenruo 			  ret);
3166cf90d884SQu Wenruo 		goto fail_block_groups;
3167cf90d884SQu Wenruo 	}
316868310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
316968310a5eSIlya Dryomov 	if (ret) {
317005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
317168310a5eSIlya Dryomov 		goto fail_block_groups;
317268310a5eSIlya Dryomov 	}
317368310a5eSIlya Dryomov 
3174733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3175733f4fbbSStefan Behrens 	if (ret) {
317605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3177733f4fbbSStefan Behrens 		goto fail_block_groups;
3178733f4fbbSStefan Behrens 	}
3179733f4fbbSStefan Behrens 
31808dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
31818dabb742SStefan Behrens 	if (ret) {
318205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
31838dabb742SStefan Behrens 		goto fail_block_groups;
31848dabb742SStefan Behrens 	}
31858dabb742SStefan Behrens 
31869b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 1);
31878dabb742SStefan Behrens 
3188c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3189b7c35e81SAnand Jain 	if (ret) {
319005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
319105135f59SDavid Sterba 				ret);
3192b7c35e81SAnand Jain 		goto fail_block_groups;
3193b7c35e81SAnand Jain 	}
3194b7c35e81SAnand Jain 
319596f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
31965ac1d209SJeff Mahoney 	if (ret) {
319705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3198b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
31995ac1d209SJeff Mahoney 	}
32005ac1d209SJeff Mahoney 
3201c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3202c59021f8Sliubo 	if (ret) {
320305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
32042365dd3cSAnand Jain 		goto fail_sysfs;
3205c59021f8Sliubo 	}
3206c59021f8Sliubo 
32075b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
32081b1d1f66SJosef Bacik 	if (ret) {
320905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
32102365dd3cSAnand Jain 		goto fail_sysfs;
32111b1d1f66SJosef Bacik 	}
32124330e183SQu Wenruo 
32136528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
321405135f59SDavid Sterba 		btrfs_warn(fs_info,
321552042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
32162365dd3cSAnand Jain 		goto fail_sysfs;
3217292fd7fcSStefan Behrens 	}
32189078a3e1SChris Mason 
3219a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3220a74a4b97SChris Mason 					       "btrfs-cleaner");
322157506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
32222365dd3cSAnand Jain 		goto fail_sysfs;
3223a74a4b97SChris Mason 
3224a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3225a74a4b97SChris Mason 						   tree_root,
3226a74a4b97SChris Mason 						   "btrfs-transaction");
322757506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
32283f157a2fSChris Mason 		goto fail_cleaner;
3229a74a4b97SChris Mason 
3230583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3231c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3232583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3233c289811cSChris Mason 	}
3234c289811cSChris Mason 
3235572d9ab7SDavid Sterba 	/*
323601327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3237572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3238572d9ab7SDavid Sterba 	 */
3239572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
32403818aea2SQu Wenruo 
324121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
32420b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
32432ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
32440b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
324521adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
324621adbd5cSStefan Behrens 				    1 : 0,
324721adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
324821adbd5cSStefan Behrens 		if (ret)
324905135f59SDavid Sterba 			btrfs_warn(fs_info,
325005135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
325105135f59SDavid Sterba 				ret);
325221adbd5cSStefan Behrens 	}
325321adbd5cSStefan Behrens #endif
3254bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3255bcef60f2SArne Jansen 	if (ret)
3256bcef60f2SArne Jansen 		goto fail_trans_kthread;
325721adbd5cSStefan Behrens 
3258fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3259fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3260fd708b81SJosef Bacik 
326196da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
326296da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
32630b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3264e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
326563443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
326679787eaaSJeff Mahoney 		if (ret) {
326763443bf5SEric Sandeen 			err = ret;
326828c16cbbSWang Shilong 			goto fail_qgroup;
3269e556ce2cSYan Zheng 		}
3270e02119d5SChris Mason 	}
32711a40e23bSZheng Yan 
32726bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
327379787eaaSJeff Mahoney 	if (ret)
327428c16cbbSWang Shilong 		goto fail_qgroup;
327576dda93cSYan, Zheng 
3276bc98a42cSDavid Howells 	if (!sb_rdonly(sb)) {
3277d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
327844c44af2SIlya Dryomov 		if (ret)
327928c16cbbSWang Shilong 			goto fail_qgroup;
328090c711abSZygo Blaxell 
328190c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
32825d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
328390c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
3284d7ce5843SMiao Xie 		if (ret < 0) {
328505135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
328605135f59SDavid Sterba 					ret);
3287d7ce5843SMiao Xie 			err = -EINVAL;
3288bcef60f2SArne Jansen 			goto fail_qgroup;
3289d7ce5843SMiao Xie 		}
32907c2ca468SChris Mason 	}
32911a40e23bSZheng Yan 
329256e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
32933140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
32943140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3295f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3296315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3297bcef60f2SArne Jansen 		goto fail_qgroup;
32983140c9a3SDan Carpenter 	}
3299c289811cSChris Mason 
3300bc98a42cSDavid Howells 	if (sb_rdonly(sb))
33012b6ba629SIlya Dryomov 		return 0;
33022b6ba629SIlya Dryomov 
3303f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3304f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
33056675df31SOmar Sandoval 		clear_free_space_tree = 1;
33066675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
33076675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
33086675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
33096675df31SOmar Sandoval 		clear_free_space_tree = 1;
33106675df31SOmar Sandoval 	}
33116675df31SOmar Sandoval 
33126675df31SOmar Sandoval 	if (clear_free_space_tree) {
3313f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3314f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3315f8d468a1SOmar Sandoval 		if (ret) {
3316f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3317f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
33186bccf3abSJeff Mahoney 			close_ctree(fs_info);
3319f8d468a1SOmar Sandoval 			return ret;
3320f8d468a1SOmar Sandoval 		}
3321f8d468a1SOmar Sandoval 	}
3322f8d468a1SOmar Sandoval 
33230b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3324511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
332505135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3326511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3327511711afSChris Mason 		if (ret) {
332805135f59SDavid Sterba 			btrfs_warn(fs_info,
332905135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
33306bccf3abSJeff Mahoney 			close_ctree(fs_info);
3331511711afSChris Mason 			return ret;
3332511711afSChris Mason 		}
3333511711afSChris Mason 	}
3334511711afSChris Mason 
3335e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
33362b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
33372b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
33382b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
33396bccf3abSJeff Mahoney 		close_ctree(fs_info);
33402b6ba629SIlya Dryomov 		return ret;
33412b6ba629SIlya Dryomov 	}
3342e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
334359641015SIlya Dryomov 
33442b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
33452b6ba629SIlya Dryomov 	if (ret) {
334605135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
33476bccf3abSJeff Mahoney 		close_ctree(fs_info);
33482b6ba629SIlya Dryomov 		return ret;
3349e3acc2a6SJosef Bacik 	}
3350e3acc2a6SJosef Bacik 
33518dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
33528dabb742SStefan Behrens 	if (ret) {
335305135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
33546bccf3abSJeff Mahoney 		close_ctree(fs_info);
33558dabb742SStefan Behrens 		return ret;
33568dabb742SStefan Behrens 	}
33578dabb742SStefan Behrens 
3358b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3359b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3360b382a324SJan Schmidt 
33614bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
336205135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3363f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3364f7a81ea4SStefan Behrens 		if (ret) {
336505135f59SDavid Sterba 			btrfs_warn(fs_info,
336605135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
33676bccf3abSJeff Mahoney 			close_ctree(fs_info);
3368f7a81ea4SStefan Behrens 			return ret;
3369f7a81ea4SStefan Behrens 		}
33700b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
33714bbcaa64SEric Sandeen 		   fs_info->generation !=
33724bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
337305135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
337470f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
337570f80175SStefan Behrens 		if (ret) {
337605135f59SDavid Sterba 			btrfs_warn(fs_info,
337705135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
33786bccf3abSJeff Mahoney 			close_ctree(fs_info);
337970f80175SStefan Behrens 			return ret;
338070f80175SStefan Behrens 		}
3381f7a81ea4SStefan Behrens 	}
3382afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
338347ab2a6cSJosef Bacik 
33848dcddfa0SQu Wenruo 	/*
33858dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
33868dcddfa0SQu Wenruo 	 * no need to keep the flag
33878dcddfa0SQu Wenruo 	 */
33888dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
33898dcddfa0SQu Wenruo 
3390ad2b2c80SAl Viro 	return 0;
339139279cc3SChris Mason 
3392bcef60f2SArne Jansen fail_qgroup:
3393bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
33947c2ca468SChris Mason fail_trans_kthread:
33957c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
33962ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3397faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
33983f157a2fSChris Mason fail_cleaner:
3399a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
34007c2ca468SChris Mason 
34017c2ca468SChris Mason 	/*
34027c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
34037c2ca468SChris Mason 	 * kthreads
34047c2ca468SChris Mason 	 */
34057c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
34067c2ca468SChris Mason 
34072365dd3cSAnand Jain fail_sysfs:
34086618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
34092365dd3cSAnand Jain 
3410b7c35e81SAnand Jain fail_fsdev_sysfs:
3411b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3412b7c35e81SAnand Jain 
34131b1d1f66SJosef Bacik fail_block_groups:
341454067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3415af31f5e5SChris Mason 
3416af31f5e5SChris Mason fail_tree_roots:
34179e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
34189e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
34194273eaffSAnand Jain 	free_root_pointers(fs_info, true);
34202b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3421af31f5e5SChris Mason 
342239279cc3SChris Mason fail_sb_buffer:
34237abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
34245cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
342516cdcec7SMiao Xie fail_alloc:
3426586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3427586e46e2SIlya Dryomov 
34284543df7eSChris Mason 	iput(fs_info->btree_inode);
34297e662854SQinghuang Feng fail:
3430586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3431ad2b2c80SAl Viro 	return err;
3432eb60ceacSChris Mason }
3433663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3434eb60ceacSChris Mason 
3435314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3436f2984462SChris Mason {
3437314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3438314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3439314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3440314b6dd0SJohannes Thumshirn 	struct page *page;
3441442a4f63SStefan Behrens 
3442314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3443314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3444314b6dd0SJohannes Thumshirn 
3445314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3446fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3447314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3448314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3449314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3450314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3451314b6dd0SJohannes Thumshirn 			SetPageError(page);
3452314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3453314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3454314b6dd0SJohannes Thumshirn 		} else {
3455314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3456f2984462SChris Mason 		}
3457314b6dd0SJohannes Thumshirn 
3458314b6dd0SJohannes Thumshirn 		put_page(page);
3459314b6dd0SJohannes Thumshirn 		unlock_page(page);
3460314b6dd0SJohannes Thumshirn 	}
3461314b6dd0SJohannes Thumshirn 
3462314b6dd0SJohannes Thumshirn 	bio_put(bio);
3463f2984462SChris Mason }
3464f2984462SChris Mason 
34658f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
34668f32380dSJohannes Thumshirn 						   int copy_num)
346729c36d72SAnand Jain {
346829c36d72SAnand Jain 	struct btrfs_super_block *super;
34698f32380dSJohannes Thumshirn 	struct page *page;
347029c36d72SAnand Jain 	u64 bytenr;
34718f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
347229c36d72SAnand Jain 
347329c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
347429c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
34758f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
347629c36d72SAnand Jain 
34778f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
34788f32380dSJohannes Thumshirn 	if (IS_ERR(page))
34798f32380dSJohannes Thumshirn 		return ERR_CAST(page);
348029c36d72SAnand Jain 
34818f32380dSJohannes Thumshirn 	super = page_address(page);
348229c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
348329c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
34848f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
34858f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
348629c36d72SAnand Jain 	}
348729c36d72SAnand Jain 
34888f32380dSJohannes Thumshirn 	return super;
348929c36d72SAnand Jain }
349029c36d72SAnand Jain 
349129c36d72SAnand Jain 
34928f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3493a512bbf8SYan Zheng {
34948f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3495a512bbf8SYan Zheng 	int i;
3496a512bbf8SYan Zheng 	u64 transid = 0;
3497a512bbf8SYan Zheng 
3498a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3499a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3500a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3501a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3502a512bbf8SYan Zheng 	 */
3503a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
35048f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
35058f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3506a512bbf8SYan Zheng 			continue;
3507a512bbf8SYan Zheng 
3508a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
35098f32380dSJohannes Thumshirn 			if (latest)
35108f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
35118f32380dSJohannes Thumshirn 
35128f32380dSJohannes Thumshirn 			latest = super;
3513a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3514a512bbf8SYan Zheng 		}
3515a512bbf8SYan Zheng 	}
351692fc03fbSAnand Jain 
35178f32380dSJohannes Thumshirn 	return super;
3518a512bbf8SYan Zheng }
3519a512bbf8SYan Zheng 
35204eedeb75SHisashi Hifumi /*
3521abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3522314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
35234eedeb75SHisashi Hifumi  *
3524abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3525abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3526abbb3b8eSDavid Sterba  * same for write and wait phases.
35274eedeb75SHisashi Hifumi  *
3528314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
35294eedeb75SHisashi Hifumi  */
3530a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3531abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3532a512bbf8SYan Zheng {
3533d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3534314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3535d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3536a512bbf8SYan Zheng 	int i;
3537a512bbf8SYan Zheng 	int errors = 0;
3538a512bbf8SYan Zheng 	u64 bytenr;
3539a512bbf8SYan Zheng 
3540a512bbf8SYan Zheng 	if (max_mirrors == 0)
3541a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3542a512bbf8SYan Zheng 
3543d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3544d5178578SJohannes Thumshirn 
3545a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3546314b6dd0SJohannes Thumshirn 		struct page *page;
3547314b6dd0SJohannes Thumshirn 		struct bio *bio;
3548314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3549314b6dd0SJohannes Thumshirn 
3550a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3551935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3552935e5cc9SMiao Xie 		    device->commit_total_bytes)
3553a512bbf8SYan Zheng 			break;
3554a512bbf8SYan Zheng 
3555a512bbf8SYan Zheng 		btrfs_set_super_bytenr(sb, bytenr);
3556a512bbf8SYan Zheng 
3557fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3558fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3559fd08001fSEric Biggers 				    sb->csum);
3560a512bbf8SYan Zheng 
3561314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3562314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3563314b6dd0SJohannes Thumshirn 		if (!page) {
3564fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3565314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3566f14d104dSDavid Sterba 			    bytenr);
3567634554dcSJosef Bacik 			errors++;
3568634554dcSJosef Bacik 			continue;
3569634554dcSJosef Bacik 		}
3570634554dcSJosef Bacik 
3571314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3572314b6dd0SJohannes Thumshirn 		get_page(page);
3573a512bbf8SYan Zheng 
3574314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3575314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3576a512bbf8SYan Zheng 
3577387125fcSChris Mason 		/*
3578314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3579314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3580314b6dd0SJohannes Thumshirn 		 * checking.
3581387125fcSChris Mason 		 */
3582314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3583314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3584314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3585314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3586314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3587314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3588314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3589314b6dd0SJohannes Thumshirn 
3590314b6dd0SJohannes Thumshirn 		/*
3591314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3592314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3593314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3594314b6dd0SJohannes Thumshirn 		 */
3595314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
35961b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3597314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3598314b6dd0SJohannes Thumshirn 
3599314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
3600a512bbf8SYan Zheng 	}
3601a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3602a512bbf8SYan Zheng }
3603a512bbf8SYan Zheng 
3604387125fcSChris Mason /*
3605abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3606abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3607abbb3b8eSDavid Sterba  *
3608314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3609abbb3b8eSDavid Sterba  * date.
3610abbb3b8eSDavid Sterba  */
3611abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3612abbb3b8eSDavid Sterba {
3613abbb3b8eSDavid Sterba 	int i;
3614abbb3b8eSDavid Sterba 	int errors = 0;
3615b6a535faSHoward McLauchlan 	bool primary_failed = false;
3616abbb3b8eSDavid Sterba 	u64 bytenr;
3617abbb3b8eSDavid Sterba 
3618abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3619abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3620abbb3b8eSDavid Sterba 
3621abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3622314b6dd0SJohannes Thumshirn 		struct page *page;
3623314b6dd0SJohannes Thumshirn 
3624abbb3b8eSDavid Sterba 		bytenr = btrfs_sb_offset(i);
3625abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3626abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3627abbb3b8eSDavid Sterba 			break;
3628abbb3b8eSDavid Sterba 
3629314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3630314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3631314b6dd0SJohannes Thumshirn 		if (!page) {
3632abbb3b8eSDavid Sterba 			errors++;
3633b6a535faSHoward McLauchlan 			if (i == 0)
3634b6a535faSHoward McLauchlan 				primary_failed = true;
3635abbb3b8eSDavid Sterba 			continue;
3636abbb3b8eSDavid Sterba 		}
3637314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3638314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3639314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3640abbb3b8eSDavid Sterba 			errors++;
3641b6a535faSHoward McLauchlan 			if (i == 0)
3642b6a535faSHoward McLauchlan 				primary_failed = true;
3643b6a535faSHoward McLauchlan 		}
3644abbb3b8eSDavid Sterba 
3645314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3646314b6dd0SJohannes Thumshirn 		put_page(page);
3647abbb3b8eSDavid Sterba 
3648314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3649314b6dd0SJohannes Thumshirn 		put_page(page);
3650abbb3b8eSDavid Sterba 	}
3651abbb3b8eSDavid Sterba 
3652b6a535faSHoward McLauchlan 	/* log error, force error return */
3653b6a535faSHoward McLauchlan 	if (primary_failed) {
3654b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3655b6a535faSHoward McLauchlan 			  device->devid);
3656b6a535faSHoward McLauchlan 		return -1;
3657b6a535faSHoward McLauchlan 	}
3658b6a535faSHoward McLauchlan 
3659abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3660abbb3b8eSDavid Sterba }
3661abbb3b8eSDavid Sterba 
3662abbb3b8eSDavid Sterba /*
3663387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3664387125fcSChris Mason  * for the barrier when it is done
3665387125fcSChris Mason  */
36664246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3667387125fcSChris Mason {
3668387125fcSChris Mason 	complete(bio->bi_private);
3669387125fcSChris Mason }
3670387125fcSChris Mason 
3671387125fcSChris Mason /*
36724fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
36734fc6441aSAnand Jain  * done in the waiting counterpart.
3674387125fcSChris Mason  */
36754fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3676387125fcSChris Mason {
3677c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3678e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3679387125fcSChris Mason 
3680c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
36814fc6441aSAnand Jain 		return;
3682387125fcSChris Mason 
3683e0ae9994SDavid Sterba 	bio_reset(bio);
3684387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
368574d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
36868d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3687387125fcSChris Mason 	init_completion(&device->flush_wait);
3688387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3689387125fcSChris Mason 
369043a01111SLu Fengqi 	btrfsic_submit_bio(bio);
36911c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
36924fc6441aSAnand Jain }
3693387125fcSChris Mason 
36944fc6441aSAnand Jain /*
36954fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
36964fc6441aSAnand Jain  */
36978c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
36984fc6441aSAnand Jain {
36994fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
37004fc6441aSAnand Jain 
37011c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
370258efbc9fSOmar Sandoval 		return BLK_STS_OK;
37034fc6441aSAnand Jain 
37041c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
37052980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
37064fc6441aSAnand Jain 
37078c27cb35SLinus Torvalds 	return bio->bi_status;
3708387125fcSChris Mason }
3709387125fcSChris Mason 
3710d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3711401b41e5SAnand Jain {
37126528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3713401b41e5SAnand Jain 		return -EIO;
3714387125fcSChris Mason 	return 0;
3715387125fcSChris Mason }
3716387125fcSChris Mason 
3717387125fcSChris Mason /*
3718387125fcSChris Mason  * send an empty flush down to each device in parallel,
3719387125fcSChris Mason  * then wait for them
3720387125fcSChris Mason  */
3721387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3722387125fcSChris Mason {
3723387125fcSChris Mason 	struct list_head *head;
3724387125fcSChris Mason 	struct btrfs_device *dev;
37255af3e8ccSStefan Behrens 	int errors_wait = 0;
37264e4cbee9SChristoph Hellwig 	blk_status_t ret;
3727387125fcSChris Mason 
37281538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3729387125fcSChris Mason 	/* send down all the barriers */
3730387125fcSChris Mason 	head = &info->fs_devices->devices;
37311538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3732e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3733f88ba6a2SHidetoshi Seto 			continue;
3734cea7c8bfSAnand Jain 		if (!dev->bdev)
3735387125fcSChris Mason 			continue;
3736e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3737ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3738387125fcSChris Mason 			continue;
3739387125fcSChris Mason 
37404fc6441aSAnand Jain 		write_dev_flush(dev);
374158efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3742387125fcSChris Mason 	}
3743387125fcSChris Mason 
3744387125fcSChris Mason 	/* wait for all the barriers */
37451538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3746e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3747f88ba6a2SHidetoshi Seto 			continue;
3748387125fcSChris Mason 		if (!dev->bdev) {
37495af3e8ccSStefan Behrens 			errors_wait++;
3750387125fcSChris Mason 			continue;
3751387125fcSChris Mason 		}
3752e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3753ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3754387125fcSChris Mason 			continue;
3755387125fcSChris Mason 
37564fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3757401b41e5SAnand Jain 		if (ret) {
3758401b41e5SAnand Jain 			dev->last_flush_error = ret;
375966b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
376066b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
37615af3e8ccSStefan Behrens 			errors_wait++;
3762387125fcSChris Mason 		}
3763401b41e5SAnand Jain 	}
3764401b41e5SAnand Jain 
3765cea7c8bfSAnand Jain 	if (errors_wait) {
3766401b41e5SAnand Jain 		/*
3767401b41e5SAnand Jain 		 * At some point we need the status of all disks
3768401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3769401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3770401b41e5SAnand Jain 		 */
3771d10b82feSQu Wenruo 		return check_barrier_error(info);
3772401b41e5SAnand Jain 	}
3773387125fcSChris Mason 	return 0;
3774387125fcSChris Mason }
3775387125fcSChris Mason 
3776943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3777943c6e99SZhao Lei {
37788789f4feSZhao Lei 	int raid_type;
37798789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3780943c6e99SZhao Lei 
37818789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
37828789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
37838c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
37848789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
37858789f4feSZhao Lei 				    tolerated_failures);
3786943c6e99SZhao Lei 
37878789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
37888789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
37898789f4feSZhao Lei 			continue;
379041a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
37918789f4feSZhao Lei 			continue;
37928c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
37938789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
37948789f4feSZhao Lei 				    tolerated_failures);
37958789f4feSZhao Lei 	}
3796943c6e99SZhao Lei 
37978789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3798ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
37998789f4feSZhao Lei 		min_tolerated = 0;
38008789f4feSZhao Lei 	}
38018789f4feSZhao Lei 
38028789f4feSZhao Lei 	return min_tolerated;
3803943c6e99SZhao Lei }
3804943c6e99SZhao Lei 
3805eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3806f2984462SChris Mason {
3807e5e9a520SChris Mason 	struct list_head *head;
3808f2984462SChris Mason 	struct btrfs_device *dev;
3809a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3810f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3811f2984462SChris Mason 	int ret;
3812f2984462SChris Mason 	int do_barriers;
3813a236aed1SChris Mason 	int max_errors;
3814a236aed1SChris Mason 	int total_errors = 0;
3815a061fc8dSChris Mason 	u64 flags;
3816f2984462SChris Mason 
38170b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3818fed3b381SLiu Bo 
3819fed3b381SLiu Bo 	/*
3820fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3821fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3822fed3b381SLiu Bo 	 * been consistent on disk.
3823fed3b381SLiu Bo 	 */
3824fed3b381SLiu Bo 	if (max_mirrors == 0)
38250b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3826f2984462SChris Mason 
38270b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3828a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3829e5e9a520SChris Mason 
38300b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
38310b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
38320b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3833387125fcSChris Mason 
38345af3e8ccSStefan Behrens 	if (do_barriers) {
38350b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
38365af3e8ccSStefan Behrens 		if (ret) {
38375af3e8ccSStefan Behrens 			mutex_unlock(
38380b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
38390b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
38405af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
38415af3e8ccSStefan Behrens 			return ret;
38425af3e8ccSStefan Behrens 		}
38435af3e8ccSStefan Behrens 	}
3844387125fcSChris Mason 
38451538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3846dfe25020SChris Mason 		if (!dev->bdev) {
3847dfe25020SChris Mason 			total_errors++;
3848dfe25020SChris Mason 			continue;
3849dfe25020SChris Mason 		}
3850e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3851ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3852dfe25020SChris Mason 			continue;
3853dfe25020SChris Mason 
38542b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3855a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3856a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
38577df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3858935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3859ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3860ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3861a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3862a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3863a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3864a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
38657239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
38667239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
3867a512bbf8SYan Zheng 
3868a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3869a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3870f2984462SChris Mason 
387175cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
387275cb857dSQu Wenruo 		if (ret < 0) {
387375cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
387475cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
387575cb857dSQu Wenruo 				"unexpected superblock corruption detected");
387675cb857dSQu Wenruo 			return -EUCLEAN;
387775cb857dSQu Wenruo 		}
387875cb857dSQu Wenruo 
3879abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3880a236aed1SChris Mason 		if (ret)
3881a236aed1SChris Mason 			total_errors++;
3882f2984462SChris Mason 	}
3883a236aed1SChris Mason 	if (total_errors > max_errors) {
38840b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3885d397712bSChris Mason 			  total_errors);
38860b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
388779787eaaSJeff Mahoney 
38889d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
38890b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38900b246afaSJeff Mahoney 				      "%d errors while writing supers",
38910b246afaSJeff Mahoney 				      total_errors);
38929d565ba4SStefan Behrens 		return -EIO;
3893a236aed1SChris Mason 	}
3894f2984462SChris Mason 
3895a512bbf8SYan Zheng 	total_errors = 0;
38961538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3897dfe25020SChris Mason 		if (!dev->bdev)
3898dfe25020SChris Mason 			continue;
3899e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3900ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3901dfe25020SChris Mason 			continue;
3902dfe25020SChris Mason 
3903abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3904a512bbf8SYan Zheng 		if (ret)
39051259ab75SChris Mason 			total_errors++;
3906f2984462SChris Mason 	}
39070b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3908a236aed1SChris Mason 	if (total_errors > max_errors) {
39090b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
39100b246afaSJeff Mahoney 				      "%d errors while writing supers",
39110b246afaSJeff Mahoney 				      total_errors);
391279787eaaSJeff Mahoney 		return -EIO;
3913a236aed1SChris Mason 	}
3914f2984462SChris Mason 	return 0;
3915f2984462SChris Mason }
3916f2984462SChris Mason 
3917cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3918cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3919cb517eabSMiao Xie 				  struct btrfs_root *root)
39202619ba1fSChris Mason {
39214785e24fSJosef Bacik 	bool drop_ref = false;
39224785e24fSJosef Bacik 
39234df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
39242619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
39252619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
3926af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
39274785e24fSJosef Bacik 		drop_ref = true;
39284df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
392976dda93cSYan, Zheng 
39301c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3931ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
39321c1ea4f7SLiu Bo 		if (root->reloc_root) {
393300246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
39341c1ea4f7SLiu Bo 			root->reloc_root = NULL;
39351c1ea4f7SLiu Bo 		}
39361c1ea4f7SLiu Bo 	}
39373321719eSLiu Bo 
3938faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3939581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3940faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3941581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
39420e996e7fSJosef Bacik 	if (root->ino_cache_inode) {
39430e996e7fSJosef Bacik 		iput(root->ino_cache_inode);
39440e996e7fSJosef Bacik 		root->ino_cache_inode = NULL;
39450e996e7fSJosef Bacik 	}
39464785e24fSJosef Bacik 	if (drop_ref)
394700246528SJosef Bacik 		btrfs_put_root(root);
39482619ba1fSChris Mason }
39492619ba1fSChris Mason 
3950c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3951c146afadSYan Zheng {
3952c146afadSYan Zheng 	u64 root_objectid = 0;
3953c146afadSYan Zheng 	struct btrfs_root *gang[8];
395465d33fd7SQu Wenruo 	int i = 0;
395565d33fd7SQu Wenruo 	int err = 0;
395665d33fd7SQu Wenruo 	unsigned int ret = 0;
3957c146afadSYan Zheng 
3958c146afadSYan Zheng 	while (1) {
3959efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
3960c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3961c146afadSYan Zheng 					     (void **)gang, root_objectid,
3962c146afadSYan Zheng 					     ARRAY_SIZE(gang));
396365d33fd7SQu Wenruo 		if (!ret) {
3964efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
3965c146afadSYan Zheng 			break;
396665d33fd7SQu Wenruo 		}
39675d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
396866b4ffd1SJosef Bacik 
396965d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
397065d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
397165d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
397265d33fd7SQu Wenruo 				gang[i] = NULL;
397365d33fd7SQu Wenruo 				continue;
397465d33fd7SQu Wenruo 			}
397565d33fd7SQu Wenruo 			/* grab all the search result for later use */
397600246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
397765d33fd7SQu Wenruo 		}
3978efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
397965d33fd7SQu Wenruo 
398065d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
398165d33fd7SQu Wenruo 			if (!gang[i])
398265d33fd7SQu Wenruo 				continue;
3983c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
398466b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
398566b4ffd1SJosef Bacik 			if (err)
398665d33fd7SQu Wenruo 				break;
398700246528SJosef Bacik 			btrfs_put_root(gang[i]);
3988c146afadSYan Zheng 		}
3989c146afadSYan Zheng 		root_objectid++;
3990c146afadSYan Zheng 	}
399165d33fd7SQu Wenruo 
399265d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
399365d33fd7SQu Wenruo 	for (; i < ret; i++) {
399465d33fd7SQu Wenruo 		if (gang[i])
399500246528SJosef Bacik 			btrfs_put_root(gang[i]);
399665d33fd7SQu Wenruo 	}
399765d33fd7SQu Wenruo 	return err;
3998c146afadSYan Zheng }
3999c146afadSYan Zheng 
40006bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4001c146afadSYan Zheng {
40026bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4003c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4004c146afadSYan Zheng 
40050b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
40062ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
40070b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
40080b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4009c71bf099SYan, Zheng 
4010c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
40110b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
40120b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4013c71bf099SYan, Zheng 
40147a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
40153612b495STsutomu Itoh 	if (IS_ERR(trans))
40163612b495STsutomu Itoh 		return PTR_ERR(trans);
40173a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4018c146afadSYan Zheng }
4019c146afadSYan Zheng 
4020b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4021eb60ceacSChris Mason {
4022c146afadSYan Zheng 	int ret;
4023e089f05cSChris Mason 
4024afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4025d6fd0ae2SOmar Sandoval 	/*
4026d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4027d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4028d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4029d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4030d6fd0ae2SOmar Sandoval 	 */
4031d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4032a2135011SChris Mason 
40337343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4034d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
40357343dd61SJustin Maggard 
4036803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4037803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4038803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4039803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4040803b2f54SStefan Behrens 
4041837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4042aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4043837d5b6eSIlya Dryomov 
40448dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
40458dabb742SStefan Behrens 
4046aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
40474cb5300bSChris Mason 
40484cb5300bSChris Mason 	/* wait for any defraggers to finish */
40494cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
40504cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
40514cb5300bSChris Mason 
40524cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
405326176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
40544cb5300bSChris Mason 
405521c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
405657056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
405721c7e756SMiao Xie 
4058b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4059b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4060b0643e59SDennis Zhou 
4061bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4062e44163e1SJeff Mahoney 		/*
4063d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4064d6fd0ae2SOmar Sandoval 		 * unused block groups.
4065e44163e1SJeff Mahoney 		 */
40660b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4067e44163e1SJeff Mahoney 
4068f0cc2cd7SFilipe Manana 		/*
4069f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4070f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4071f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4072f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4073f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4074f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4075f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4076f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4077f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4078f0cc2cd7SFilipe Manana 		 */
4079f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4080f0cc2cd7SFilipe Manana 
40816bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4082d397712bSChris Mason 		if (ret)
408304892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4084c146afadSYan Zheng 	}
4085ed2ff2cbSChris Mason 
4086af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4087af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
40882ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4089acce952bSliubo 
4090e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4091e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
40928929ecfaSYan, Zheng 
4093e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4094afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4095f25784b3SYan Zheng 
40965958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
40975958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
40985958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
40995958253cSQu Wenruo 	}
41005958253cSQu Wenruo 
410104892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4102fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4103bcef60f2SArne Jansen 
4104963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
410504892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4106963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4107b0c68f8bSChris Mason 	}
410831153d81SYan Zheng 
41094297ff84SJosef Bacik 	if (percpu_counter_sum(&fs_info->dio_bytes))
41104297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
41114297ff84SJosef Bacik 			   percpu_counter_sum(&fs_info->dio_bytes));
41124297ff84SJosef Bacik 
41136618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4114b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
41155ac1d209SJeff Mahoney 
41161a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
41171a4319ccSLiu Bo 
4118de348ee0SWang Shilong 	/*
4119de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4120de348ee0SWang Shilong 	 * submit after we stopping all workers.
4121de348ee0SWang Shilong 	 */
4122de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
412396192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
412496192499SJosef Bacik 
4125afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
41264273eaffSAnand Jain 	free_root_pointers(fs_info, true);
41278c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
41289ad6b7bcSChris Mason 
41294e19443dSJosef Bacik 	/*
41304e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
41314e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
41324e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
41334e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
41344e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
41354e19443dSJosef Bacik 	 */
41364e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
41374e19443dSJosef Bacik 
413813e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4139d6bfde87SChris Mason 
414021adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
41410b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
41422ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
414321adbd5cSStefan Behrens #endif
414421adbd5cSStefan Behrens 
41450b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
414668c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4147eb60ceacSChris Mason }
4148eb60ceacSChris Mason 
4149b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4150b9fab919SChris Mason 			  int atomic)
4151ccd467d6SChris Mason {
41521259ab75SChris Mason 	int ret;
4153727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
41541259ab75SChris Mason 
41550b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
41561259ab75SChris Mason 	if (!ret)
41571259ab75SChris Mason 		return ret;
41581259ab75SChris Mason 
41591259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4160b9fab919SChris Mason 				    parent_transid, atomic);
4161b9fab919SChris Mason 	if (ret == -EAGAIN)
4162b9fab919SChris Mason 		return ret;
41631259ab75SChris Mason 	return !ret;
41645f39d397SChris Mason }
41656702ed49SChris Mason 
41665f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
41675f39d397SChris Mason {
41680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
416906ea65a3SJosef Bacik 	struct btrfs_root *root;
41705f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4171b9473439SChris Mason 	int was_dirty;
4172b4ce94deSChris Mason 
417306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
417406ea65a3SJosef Bacik 	/*
417506ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
417652042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
417706ea65a3SJosef Bacik 	 * outside of the sanity tests.
417806ea65a3SJosef Bacik 	 */
4179b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
418006ea65a3SJosef Bacik 		return;
418106ea65a3SJosef Bacik #endif
418206ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
41830b246afaSJeff Mahoney 	fs_info = root->fs_info;
4184b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
41850b246afaSJeff Mahoney 	if (transid != fs_info->generation)
41865d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
41870b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
41880b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4189e2d84521SMiao Xie 	if (!was_dirty)
4190104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4191e2d84521SMiao Xie 					 buf->len,
41920b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
41931f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
419469fc6cbbSQu Wenruo 	/*
419569fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
419669fc6cbbSQu Wenruo 	 * but item data not updated.
419769fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
419869fc6cbbSQu Wenruo 	 */
419969fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4200cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4201a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
42021f21ef0aSFilipe Manana 		ASSERT(0);
42031f21ef0aSFilipe Manana 	}
42041f21ef0aSFilipe Manana #endif
4205eb60ceacSChris Mason }
4206eb60ceacSChris Mason 
42072ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4208b53d3f5dSLiu Bo 					int flush_delayed)
420935b7e476SChris Mason {
4210188de649SChris Mason 	/*
4211188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4212188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4213188de649SChris Mason 	 */
4214e2d84521SMiao Xie 	int ret;
4215d6bfde87SChris Mason 
42166933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4217d6bfde87SChris Mason 		return;
4218d6bfde87SChris Mason 
4219b53d3f5dSLiu Bo 	if (flush_delayed)
42202ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
422116cdcec7SMiao Xie 
4222d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4223d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4224d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4225e2d84521SMiao Xie 	if (ret > 0) {
42260b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
422716cdcec7SMiao Xie 	}
422816cdcec7SMiao Xie }
422916cdcec7SMiao Xie 
42302ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
423116cdcec7SMiao Xie {
42322ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
423335b7e476SChris Mason }
4234b53d3f5dSLiu Bo 
42352ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4236b53d3f5dSLiu Bo {
42372ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4238d6bfde87SChris Mason }
42396b80053dSChris Mason 
4240581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4241581c1760SQu Wenruo 		      struct btrfs_key *first_key)
42426b80053dSChris Mason {
42435ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4244581c1760SQu Wenruo 					      level, first_key);
42456b80053dSChris Mason }
42460da5468fSChris Mason 
42472ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4248acce952bSliubo {
4249fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4250fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4251fe816d0fSNikolay Borisov 
42520b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
42532ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
42540b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4255acce952bSliubo 
42560b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
42570b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4258acce952bSliubo }
4259acce952bSliubo 
4260ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4261ef67963dSJosef Bacik {
4262ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4263ef67963dSJosef Bacik 	u64 root_objectid = 0;
4264ef67963dSJosef Bacik 	int ret;
4265ef67963dSJosef Bacik 
4266ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4267ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4268ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4269ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4270ef67963dSJosef Bacik 		int i;
4271ef67963dSJosef Bacik 
4272ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4273ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4274ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4275ef67963dSJosef Bacik 
4276ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4277ef67963dSJosef Bacik 			if (!gang[i])
4278ef67963dSJosef Bacik 				continue;
4279ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4280ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4281ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4282ef67963dSJosef Bacik 		}
4283ef67963dSJosef Bacik 		root_objectid++;
4284ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4285ef67963dSJosef Bacik 	}
4286ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4287ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4288ef67963dSJosef Bacik }
4289ef67963dSJosef Bacik 
4290143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4291acce952bSliubo {
4292acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4293acce952bSliubo 
4294199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4295779880efSJosef Bacik 	/*
4296779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4297779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4298779880efSJosef Bacik 	 */
4299199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4300779880efSJosef Bacik 			    root_extent_list)
4301779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4302199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4303199c2a9cSMiao Xie }
4304199c2a9cSMiao Xie 
4305199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4306199c2a9cSMiao Xie {
4307199c2a9cSMiao Xie 	struct btrfs_root *root;
4308199c2a9cSMiao Xie 	struct list_head splice;
4309199c2a9cSMiao Xie 
4310199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4311199c2a9cSMiao Xie 
4312199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4313199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4314199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4315199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4316199c2a9cSMiao Xie 					ordered_root);
43171de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
43181de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4319199c2a9cSMiao Xie 
43202a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4321199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4322199c2a9cSMiao Xie 
43232a85d9caSLiu Bo 		cond_resched();
43242a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4325199c2a9cSMiao Xie 	}
4326199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
432774d5d229SJosef Bacik 
432874d5d229SJosef Bacik 	/*
432974d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
433074d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
433174d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
433274d5d229SJosef Bacik 	 * actually get run and error out properly.
433374d5d229SJosef Bacik 	 */
433474d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4335acce952bSliubo }
4336acce952bSliubo 
433735a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
43382ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4339acce952bSliubo {
4340acce952bSliubo 	struct rb_node *node;
4341acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4342acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4343acce952bSliubo 	int ret = 0;
4344acce952bSliubo 
4345acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4346acce952bSliubo 
4347acce952bSliubo 	spin_lock(&delayed_refs->lock);
4348d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4349cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4350b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4351acce952bSliubo 		return ret;
4352acce952bSliubo 	}
4353acce952bSliubo 
43545c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4355d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
43560e0adbcfSJosef Bacik 		struct rb_node *n;
4357e78417d1SJosef Bacik 		bool pin_bytes = false;
4358acce952bSliubo 
4359d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4360d7df2c79SJosef Bacik 				href_node);
43613069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4362b939d1abSJosef Bacik 			continue;
43633069bd26SJosef Bacik 
4364d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4365e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
43660e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
43670e0adbcfSJosef Bacik 				       ref_node);
4368d7df2c79SJosef Bacik 			ref->in_tree = 0;
4369e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
43700e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
43711d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
43721d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4373d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4374d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4375d7df2c79SJosef Bacik 		}
437654067ae9SJosef Bacik 		if (head->must_insert_reserved)
4377e78417d1SJosef Bacik 			pin_bytes = true;
437878a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4379fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4380d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4381acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4382e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4383acce952bSliubo 
4384f603bb94SNikolay Borisov 		if (pin_bytes) {
4385f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4386f603bb94SNikolay Borisov 
4387f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4388f603bb94SNikolay Borisov 			BUG_ON(!cache);
4389f603bb94SNikolay Borisov 
4390f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4391f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4392f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4393f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4394f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4395f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4396f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4397f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4398f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4399f603bb94SNikolay Borisov 			percpu_counter_add_batch(
4400f603bb94SNikolay Borisov 				&cache->space_info->total_bytes_pinned,
4401f603bb94SNikolay Borisov 				head->num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4402f603bb94SNikolay Borisov 
4403f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4404f603bb94SNikolay Borisov 
4405f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4406f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4407f603bb94SNikolay Borisov 		}
440831890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4409d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4410acce952bSliubo 		cond_resched();
4411acce952bSliubo 		spin_lock(&delayed_refs->lock);
4412acce952bSliubo 	}
441381f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4414acce952bSliubo 
4415acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4416acce952bSliubo 
4417acce952bSliubo 	return ret;
4418acce952bSliubo }
4419acce952bSliubo 
4420143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4421acce952bSliubo {
4422acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4423acce952bSliubo 	struct list_head splice;
4424acce952bSliubo 
4425acce952bSliubo 	INIT_LIST_HEAD(&splice);
4426acce952bSliubo 
4427eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4428eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4429acce952bSliubo 
4430acce952bSliubo 	while (!list_empty(&splice)) {
4431fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4432eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4433acce952bSliubo 					       delalloc_inodes);
4434fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4435eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4436acce952bSliubo 
4437fe816d0fSNikolay Borisov 		/*
4438fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4439fe816d0fSNikolay Borisov 		 * meanwhile.
4440fe816d0fSNikolay Borisov 		 */
4441fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4442fe816d0fSNikolay Borisov 		if (inode) {
4443fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4444fe816d0fSNikolay Borisov 			iput(inode);
4445fe816d0fSNikolay Borisov 		}
4446eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4447acce952bSliubo 	}
4448eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4449eb73c1b7SMiao Xie }
4450eb73c1b7SMiao Xie 
4451eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4452eb73c1b7SMiao Xie {
4453eb73c1b7SMiao Xie 	struct btrfs_root *root;
4454eb73c1b7SMiao Xie 	struct list_head splice;
4455eb73c1b7SMiao Xie 
4456eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4457eb73c1b7SMiao Xie 
4458eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4459eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4460eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4461eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4462eb73c1b7SMiao Xie 					 delalloc_root);
446300246528SJosef Bacik 		root = btrfs_grab_root(root);
4464eb73c1b7SMiao Xie 		BUG_ON(!root);
4465eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4466eb73c1b7SMiao Xie 
4467eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
446800246528SJosef Bacik 		btrfs_put_root(root);
4469eb73c1b7SMiao Xie 
4470eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4471eb73c1b7SMiao Xie 	}
4472eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4473acce952bSliubo }
4474acce952bSliubo 
44752ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4476acce952bSliubo 					struct extent_io_tree *dirty_pages,
4477acce952bSliubo 					int mark)
4478acce952bSliubo {
4479acce952bSliubo 	int ret;
4480acce952bSliubo 	struct extent_buffer *eb;
4481acce952bSliubo 	u64 start = 0;
4482acce952bSliubo 	u64 end;
4483acce952bSliubo 
4484acce952bSliubo 	while (1) {
4485acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4486e6138876SJosef Bacik 					    mark, NULL);
4487acce952bSliubo 		if (ret)
4488acce952bSliubo 			break;
4489acce952bSliubo 
449091166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4491acce952bSliubo 		while (start <= end) {
44920b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
44930b246afaSJeff Mahoney 			start += fs_info->nodesize;
4494fd8b2b61SJosef Bacik 			if (!eb)
4495acce952bSliubo 				continue;
4496fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4497acce952bSliubo 
4498fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4499fd8b2b61SJosef Bacik 					       &eb->bflags))
4500fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4501fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4502acce952bSliubo 		}
4503acce952bSliubo 	}
4504acce952bSliubo 
4505acce952bSliubo 	return ret;
4506acce952bSliubo }
4507acce952bSliubo 
45082ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4509fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4510acce952bSliubo {
4511acce952bSliubo 	u64 start;
4512acce952bSliubo 	u64 end;
4513acce952bSliubo 	int ret;
4514acce952bSliubo 
4515acce952bSliubo 	while (1) {
45160e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
45170e6ec385SFilipe Manana 
4518fcd5e742SLu Fengqi 		/*
4519fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4520fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4521fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4522fcd5e742SLu Fengqi 		 * the same extent range.
4523fcd5e742SLu Fengqi 		 */
4524fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4525acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
45260e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4527fcd5e742SLu Fengqi 		if (ret) {
4528fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4529acce952bSliubo 			break;
4530fcd5e742SLu Fengqi 		}
4531acce952bSliubo 
45320e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
45330e6ec385SFilipe Manana 		free_extent_state(cached_state);
45342ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4535fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4536acce952bSliubo 		cond_resched();
4537acce952bSliubo 	}
4538acce952bSliubo 
4539acce952bSliubo 	return 0;
4540acce952bSliubo }
4541acce952bSliubo 
454232da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4543c79a1751SLiu Bo {
4544c79a1751SLiu Bo 	struct inode *inode;
4545c79a1751SLiu Bo 
4546c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4547c79a1751SLiu Bo 	if (inode) {
4548c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4549c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4550c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4551c79a1751SLiu Bo 		iput(inode);
4552c79a1751SLiu Bo 	}
4553bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4554c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4555c79a1751SLiu Bo }
4556c79a1751SLiu Bo 
4557c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
45582ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4559c79a1751SLiu Bo {
456032da5386SDavid Sterba 	struct btrfs_block_group *cache;
4561c79a1751SLiu Bo 
4562c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4563c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4564c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
456532da5386SDavid Sterba 					 struct btrfs_block_group,
4566c79a1751SLiu Bo 					 dirty_list);
4567c79a1751SLiu Bo 
4568c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4569c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4570c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4571c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4572c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4573c79a1751SLiu Bo 		}
4574c79a1751SLiu Bo 
4575c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4576c79a1751SLiu Bo 		spin_lock(&cache->lock);
4577c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4578c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4579c79a1751SLiu Bo 
4580c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4581c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4582ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4583c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4584c79a1751SLiu Bo 	}
4585c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4586c79a1751SLiu Bo 
458745ae2c18SNikolay Borisov 	/*
458845ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
458945ae2c18SNikolay Borisov 	 * to use it without any locking
459045ae2c18SNikolay Borisov 	 */
4591c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4592c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
459332da5386SDavid Sterba 					 struct btrfs_block_group,
4594c79a1751SLiu Bo 					 io_list);
4595c79a1751SLiu Bo 
4596c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4597c79a1751SLiu Bo 		spin_lock(&cache->lock);
4598c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4599c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4600c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4601c79a1751SLiu Bo 	}
4602c79a1751SLiu Bo }
4603c79a1751SLiu Bo 
460449b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
46052ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
460649b25e05SJeff Mahoney {
4607bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4608bbbf7243SNikolay Borisov 
46092ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4610c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4611c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4612c79a1751SLiu Bo 
4613bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4614bbbf7243SNikolay Borisov 				 post_commit_list) {
4615bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4616bbbf7243SNikolay Borisov 	}
4617bbbf7243SNikolay Borisov 
46182ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
461949b25e05SJeff Mahoney 
46204a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
46210b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
462249b25e05SJeff Mahoney 
46234a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
46240b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
462549b25e05SJeff Mahoney 
4626ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
462767cde344SMiao Xie 
46282ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
462949b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4630fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
463149b25e05SJeff Mahoney 
46324a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
46334a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
463449b25e05SJeff Mahoney }
463549b25e05SJeff Mahoney 
46362ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4637acce952bSliubo {
4638acce952bSliubo 	struct btrfs_transaction *t;
4639acce952bSliubo 
46400b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4641acce952bSliubo 
46420b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
46430b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
46440b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4645724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4646724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
46479b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
46480b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
46492ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4650724e2315SJosef Bacik 			btrfs_put_transaction(t);
46510b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4652724e2315SJosef Bacik 			continue;
4653724e2315SJosef Bacik 		}
46540b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4655724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
46560b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4657724e2315SJosef Bacik 			/*
4658724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4659724e2315SJosef Bacik 			 * handle open currently for this transaction.
4660724e2315SJosef Bacik 			 */
4661724e2315SJosef Bacik 			wait_event(t->writer_wait,
4662724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4663724e2315SJosef Bacik 		} else {
46640b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4665724e2315SJosef Bacik 		}
46662ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4667724e2315SJosef Bacik 
46680b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
46690b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
46700b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4671724e2315SJosef Bacik 		list_del_init(&t->list);
46720b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4673a4abeea4SJosef Bacik 
4674724e2315SJosef Bacik 		btrfs_put_transaction(t);
46752ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
46760b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4677724e2315SJosef Bacik 	}
46780b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
46790b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4680ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4681ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
46820b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4683ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
46840b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4685acce952bSliubo 
4686acce952bSliubo 	return 0;
4687acce952bSliubo }
4688acce952bSliubo 
4689e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
46904d53dddbSDavid Sterba 	/* mandatory callbacks */
46910b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
46924d53dddbSDavid Sterba 	.readpage_end_io_hook = btree_readpage_end_io_hook,
46930da5468fSChris Mason };
4694