xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 84db5ccf)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6e20d96d6SChris Mason #include <linux/fs.h>
7d98237b3SChris Mason #include <linux/blkdev.h>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10d397712bSChris Mason #include <linux/buffer_head.h>
11ce9adaa5SChris Mason #include <linux/workqueue.h>
12a74a4b97SChris Mason #include <linux/kthread.h>
135a0e3ad6STejun Heo #include <linux/slab.h>
14784b4e29SChris Mason #include <linux/migrate.h>
157a36ddecSDavid Sterba #include <linux/ratelimit.h>
166463fe58SStefan Behrens #include <linux/uuid.h>
17803b2f54SStefan Behrens #include <linux/semaphore.h>
18540adea3SMasami Hiramatsu #include <linux/error-injection.h>
199678c543SNikolay Borisov #include <linux/crc32c.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
21eb60ceacSChris Mason #include "ctree.h"
22eb60ceacSChris Mason #include "disk-io.h"
23e089f05cSChris Mason #include "transaction.h"
240f7d52f4SChris Mason #include "btrfs_inode.h"
250b86a832SChris Mason #include "volumes.h"
26db94535dSChris Mason #include "print-tree.h"
27925baeddSChris Mason #include "locking.h"
28e02119d5SChris Mason #include "tree-log.h"
29fa9c0d79SChris Mason #include "free-space-cache.h"
3070f6d82eSOmar Sandoval #include "free-space-tree.h"
31581bb050SLi Zefan #include "inode-map.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41eb60ceacSChris Mason 
42de0022b9SJosef Bacik #ifdef CONFIG_X86
43de0022b9SJosef Bacik #include <asm/cpufeature.h>
44de0022b9SJosef Bacik #endif
45de0022b9SJosef Bacik 
46319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
47319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
48319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
50e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
52319e4d06SQu Wenruo 
53e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops;
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101d352ac68SChris Mason /*
102d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
103d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
104d352ac68SChris Mason  * just before they are sent down the IO stack.
105d352ac68SChris Mason  */
10644b8bd7eSChris Mason struct async_submit_bio {
107c6100a4bSJosef Bacik 	void *private_data;
10844b8bd7eSChris Mason 	struct bio *bio;
109a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11044b8bd7eSChris Mason 	int mirror_num;
111eaf25d93SChris Mason 	/*
112eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
113eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
114eaf25d93SChris Mason 	 */
115eaf25d93SChris Mason 	u64 bio_offset;
1168b712842SChris Mason 	struct btrfs_work work;
1174e4cbee9SChristoph Hellwig 	blk_status_t status;
11844b8bd7eSChris Mason };
11944b8bd7eSChris Mason 
12085d4e461SChris Mason /*
12185d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12285d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12385d4e461SChris Mason  * the level the eb occupies in the tree.
1244008c04aSChris Mason  *
12585d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
12685d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
12785d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
12885d4e461SChris Mason  * by btrfs_root->objectid.  This ensures that all special purpose roots
12985d4e461SChris Mason  * have separate keysets.
1304008c04aSChris Mason  *
13185d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13285d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13385d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
13685d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
13785d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
13885d4e461SChris Mason  *
13985d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14085d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14185d4e461SChris Mason  * needs update as well.
1424008c04aSChris Mason  */
1434008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1444008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1454008c04aSChris Mason #  error
1464008c04aSChris Mason # endif
14785d4e461SChris Mason 
14885d4e461SChris Mason static struct btrfs_lockdep_keyset {
14985d4e461SChris Mason 	u64			id;		/* root objectid */
15085d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
15185d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
15285d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
15385d4e461SChris Mason } btrfs_lockdep_keysets[] = {
15485d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
15585d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
15685d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
15785d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
15885d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
15985d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
16060b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
16185d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
16285d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
16385d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
16413fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
1656b20e0adSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	.name_stem = "free-space" },
16685d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1674008c04aSChris Mason };
16885d4e461SChris Mason 
16985d4e461SChris Mason void __init btrfs_init_lockdep(void)
17085d4e461SChris Mason {
17185d4e461SChris Mason 	int i, j;
17285d4e461SChris Mason 
17385d4e461SChris Mason 	/* initialize lockdep class names */
17485d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
17585d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
17685d4e461SChris Mason 
17785d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
17885d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
17985d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
18085d4e461SChris Mason 	}
18185d4e461SChris Mason }
18285d4e461SChris Mason 
18385d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18485d4e461SChris Mason 				    int level)
18585d4e461SChris Mason {
18685d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
18785d4e461SChris Mason 
18885d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
18985d4e461SChris Mason 
19085d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19185d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19285d4e461SChris Mason 		if (ks->id == objectid)
19385d4e461SChris Mason 			break;
19485d4e461SChris Mason 
19585d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
19685d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
19785d4e461SChris Mason }
19885d4e461SChris Mason 
1994008c04aSChris Mason #endif
2004008c04aSChris Mason 
201d352ac68SChris Mason /*
202d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
203d352ac68SChris Mason  * that covers the entire device
204d352ac68SChris Mason  */
2056af49dbdSDavid Sterba struct extent_map *btree_get_extent(struct btrfs_inode *inode,
206306e16ceSDavid Sterba 		struct page *page, size_t pg_offset, u64 start, u64 len,
2075f39d397SChris Mason 		int create)
2085f39d397SChris Mason {
2093ffbd68cSDavid Sterba 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
210fc4f21b1SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
2115f39d397SChris Mason 	struct extent_map *em;
2125f39d397SChris Mason 	int ret;
2135f39d397SChris Mason 
214890871beSChris Mason 	read_lock(&em_tree->lock);
215d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
216a061fc8dSChris Mason 	if (em) {
2170b246afaSJeff Mahoney 		em->bdev = fs_info->fs_devices->latest_bdev;
218890871beSChris Mason 		read_unlock(&em_tree->lock);
2195f39d397SChris Mason 		goto out;
220a061fc8dSChris Mason 	}
221890871beSChris Mason 	read_unlock(&em_tree->lock);
2227b13b7b1SChris Mason 
223172ddd60SDavid Sterba 	em = alloc_extent_map();
2245f39d397SChris Mason 	if (!em) {
2255f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2265f39d397SChris Mason 		goto out;
2275f39d397SChris Mason 	}
2285f39d397SChris Mason 	em->start = 0;
2290afbaf8cSChris Mason 	em->len = (u64)-1;
230c8b97818SChris Mason 	em->block_len = (u64)-1;
2315f39d397SChris Mason 	em->block_start = 0;
2320b246afaSJeff Mahoney 	em->bdev = fs_info->fs_devices->latest_bdev;
233d1310b2eSChris Mason 
234890871beSChris Mason 	write_lock(&em_tree->lock);
23509a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2365f39d397SChris Mason 	if (ret == -EEXIST) {
2375f39d397SChris Mason 		free_extent_map(em);
2387b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
239b4f359abSTsutomu Itoh 		if (!em)
2400433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2415f39d397SChris Mason 	} else if (ret) {
2427b13b7b1SChris Mason 		free_extent_map(em);
2430433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2445f39d397SChris Mason 	}
245890871beSChris Mason 	write_unlock(&em_tree->lock);
2467b13b7b1SChris Mason 
2475f39d397SChris Mason out:
2485f39d397SChris Mason 	return em;
2495f39d397SChris Mason }
2505f39d397SChris Mason 
2519ed57367SDavid Sterba u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
25219c00ddcSChris Mason {
2539678c543SNikolay Borisov 	return crc32c(seed, data, len);
25419c00ddcSChris Mason }
25519c00ddcSChris Mason 
2560b5e3dafSDomagoj Tršan void btrfs_csum_final(u32 crc, u8 *result)
25719c00ddcSChris Mason {
2587e75bf3fSDavid Sterba 	put_unaligned_le32(~crc, result);
25919c00ddcSChris Mason }
26019c00ddcSChris Mason 
261d352ac68SChris Mason /*
262d352ac68SChris Mason  * compute the csum for a btree block, and either verify it or write it
263d352ac68SChris Mason  * into the csum field of the block.
264d352ac68SChris Mason  */
26501d58472SDaniel Dressler static int csum_tree_block(struct btrfs_fs_info *fs_info,
26601d58472SDaniel Dressler 			   struct extent_buffer *buf,
26719c00ddcSChris Mason 			   int verify)
26819c00ddcSChris Mason {
26901d58472SDaniel Dressler 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
27071a63551SDavid Sterba 	char result[BTRFS_CSUM_SIZE];
27119c00ddcSChris Mason 	unsigned long len;
27219c00ddcSChris Mason 	unsigned long cur_len;
27319c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
27419c00ddcSChris Mason 	char *kaddr;
27519c00ddcSChris Mason 	unsigned long map_start;
27619c00ddcSChris Mason 	unsigned long map_len;
27719c00ddcSChris Mason 	int err;
27819c00ddcSChris Mason 	u32 crc = ~(u32)0;
27919c00ddcSChris Mason 
28019c00ddcSChris Mason 	len = buf->len - offset;
28119c00ddcSChris Mason 	while (len > 0) {
28219c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
283a6591715SChris Mason 					&kaddr, &map_start, &map_len);
284d397712bSChris Mason 		if (err)
2858bd98f0eSAlex Lyakas 			return err;
28619c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
287b0496686SLiu Bo 		crc = btrfs_csum_data(kaddr + offset - map_start,
28819c00ddcSChris Mason 				      crc, cur_len);
28919c00ddcSChris Mason 		len -= cur_len;
29019c00ddcSChris Mason 		offset += cur_len;
29119c00ddcSChris Mason 	}
29271a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
293607d432dSJosef Bacik 
29419c00ddcSChris Mason 	btrfs_csum_final(crc, result);
29519c00ddcSChris Mason 
29619c00ddcSChris Mason 	if (verify) {
297607d432dSJosef Bacik 		if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
298e4204dedSChris Mason 			u32 val;
299e4204dedSChris Mason 			u32 found = 0;
300607d432dSJosef Bacik 			memcpy(&found, result, csum_size);
301e4204dedSChris Mason 
302607d432dSJosef Bacik 			read_extent_buffer(buf, &val, 0, csum_size);
30394647322SDavid Sterba 			btrfs_warn_rl(fs_info,
3045d163e0eSJeff Mahoney 				"%s checksum verify failed on %llu wanted %X found %X level %d",
30501d58472SDaniel Dressler 				fs_info->sb->s_id, buf->start,
306c1c9ff7cSGeert Uytterhoeven 				val, found, btrfs_header_level(buf));
3078bd98f0eSAlex Lyakas 			return -EUCLEAN;
30819c00ddcSChris Mason 		}
30919c00ddcSChris Mason 	} else {
310607d432dSJosef Bacik 		write_extent_buffer(buf, result, 0, csum_size);
31119c00ddcSChris Mason 	}
31271a63551SDavid Sterba 
31319c00ddcSChris Mason 	return 0;
31419c00ddcSChris Mason }
31519c00ddcSChris Mason 
316d352ac68SChris Mason /*
317d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
318d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
319d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
320d352ac68SChris Mason  * in the wrong place.
321d352ac68SChris Mason  */
3221259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
323b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
324b9fab919SChris Mason 				 int atomic)
3251259ab75SChris Mason {
3262ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3271259ab75SChris Mason 	int ret;
3282755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
3291259ab75SChris Mason 
3301259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
3311259ab75SChris Mason 		return 0;
3321259ab75SChris Mason 
333b9fab919SChris Mason 	if (atomic)
334b9fab919SChris Mason 		return -EAGAIN;
335b9fab919SChris Mason 
336a26e8c9fSJosef Bacik 	if (need_lock) {
337a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
338a26e8c9fSJosef Bacik 		btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
339a26e8c9fSJosef Bacik 	}
340a26e8c9fSJosef Bacik 
3412ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
342ff13db41SDavid Sterba 			 &cached_state);
3430b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3441259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3451259ab75SChris Mason 		ret = 0;
3461259ab75SChris Mason 		goto out;
3471259ab75SChris Mason 	}
34894647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
34994647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
35094647322SDavid Sterba 			eb->start,
35129549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3521259ab75SChris Mason 	ret = 1;
353a26e8c9fSJosef Bacik 
354a26e8c9fSJosef Bacik 	/*
355a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
356a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
35701327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
358a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
359a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
360a26e8c9fSJosef Bacik 	 * making everybody very sad.
361a26e8c9fSJosef Bacik 	 */
362a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3630b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
36433958dc6SChris Mason out:
3652ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
366e43bbe5eSDavid Sterba 			     &cached_state);
367472b909fSJosef Bacik 	if (need_lock)
368a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3691259ab75SChris Mason 	return ret;
3701259ab75SChris Mason }
3711259ab75SChris Mason 
372d352ac68SChris Mason /*
3731104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3741104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3751104a885SDavid Sterba  */
376ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
377ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
3781104a885SDavid Sterba {
3791104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3801104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
3811104a885SDavid Sterba 	u16 csum_type = btrfs_super_csum_type(disk_sb);
3821104a885SDavid Sterba 	int ret = 0;
3831104a885SDavid Sterba 
3841104a885SDavid Sterba 	if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
3851104a885SDavid Sterba 		u32 crc = ~(u32)0;
386776c4a7cSNikolay Borisov 		char result[sizeof(crc)];
3871104a885SDavid Sterba 
3881104a885SDavid Sterba 		/*
3891104a885SDavid Sterba 		 * The super_block structure does not span the whole
3901104a885SDavid Sterba 		 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
39101327610SNicholas D Steeves 		 * is filled with zeros and is included in the checksum.
3921104a885SDavid Sterba 		 */
3931104a885SDavid Sterba 		crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
3941104a885SDavid Sterba 				crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3951104a885SDavid Sterba 		btrfs_csum_final(crc, result);
3961104a885SDavid Sterba 
397776c4a7cSNikolay Borisov 		if (memcmp(raw_disk_sb, result, sizeof(result)))
3981104a885SDavid Sterba 			ret = 1;
3991104a885SDavid Sterba 	}
4001104a885SDavid Sterba 
4011104a885SDavid Sterba 	if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
402ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "unsupported checksum algorithm %u",
4031104a885SDavid Sterba 				csum_type);
4041104a885SDavid Sterba 		ret = 1;
4051104a885SDavid Sterba 	}
4061104a885SDavid Sterba 
4071104a885SDavid Sterba 	return ret;
4081104a885SDavid Sterba }
4091104a885SDavid Sterba 
410581c1760SQu Wenruo static int verify_level_key(struct btrfs_fs_info *fs_info,
411581c1760SQu Wenruo 			    struct extent_buffer *eb, int level,
412ff76a864SLiu Bo 			    struct btrfs_key *first_key, u64 parent_transid)
413581c1760SQu Wenruo {
414581c1760SQu Wenruo 	int found_level;
415581c1760SQu Wenruo 	struct btrfs_key found_key;
416581c1760SQu Wenruo 	int ret;
417581c1760SQu Wenruo 
418581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
419581c1760SQu Wenruo 	if (found_level != level) {
420581c1760SQu Wenruo #ifdef CONFIG_BTRFS_DEBUG
421581c1760SQu Wenruo 		WARN_ON(1);
422581c1760SQu Wenruo 		btrfs_err(fs_info,
423581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
424581c1760SQu Wenruo 			  eb->start, level, found_level);
425581c1760SQu Wenruo #endif
426581c1760SQu Wenruo 		return -EIO;
427581c1760SQu Wenruo 	}
428581c1760SQu Wenruo 
429581c1760SQu Wenruo 	if (!first_key)
430581c1760SQu Wenruo 		return 0;
431581c1760SQu Wenruo 
4325d41be6fSQu Wenruo 	/*
4335d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
4345d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
4355d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
4365d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
4375d41be6fSQu Wenruo 	 */
4385d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
4395d41be6fSQu Wenruo 		return 0;
440581c1760SQu Wenruo 	if (found_level)
441581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
442581c1760SQu Wenruo 	else
443581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
444581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
445581c1760SQu Wenruo 
446581c1760SQu Wenruo #ifdef CONFIG_BTRFS_DEBUG
447581c1760SQu Wenruo 	if (ret) {
448581c1760SQu Wenruo 		WARN_ON(1);
449581c1760SQu Wenruo 		btrfs_err(fs_info,
450ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
451ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
452ff76a864SLiu Bo 			  first_key->type, first_key->offset,
453ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
454ff76a864SLiu Bo 			  found_key.offset);
455581c1760SQu Wenruo 	}
456581c1760SQu Wenruo #endif
457581c1760SQu Wenruo 	return ret;
458581c1760SQu Wenruo }
459581c1760SQu Wenruo 
4601104a885SDavid Sterba /*
461d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
462d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
463581c1760SQu Wenruo  *
464581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
465581c1760SQu Wenruo  * @level:		expected level, mandatory check
466581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
467d352ac68SChris Mason  */
4682ff7e61eSJeff Mahoney static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
469f188591eSChris Mason 					  struct extent_buffer *eb,
470581c1760SQu Wenruo 					  u64 parent_transid, int level,
471581c1760SQu Wenruo 					  struct btrfs_key *first_key)
472f188591eSChris Mason {
473f188591eSChris Mason 	struct extent_io_tree *io_tree;
474ea466794SJosef Bacik 	int failed = 0;
475f188591eSChris Mason 	int ret;
476f188591eSChris Mason 	int num_copies = 0;
477f188591eSChris Mason 	int mirror_num = 0;
478ea466794SJosef Bacik 	int failed_mirror = 0;
479f188591eSChris Mason 
480a826d6dcSJosef Bacik 	clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
4810b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
482f188591eSChris Mason 	while (1) {
4838436ea91SJosef Bacik 		ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
4846af49dbdSDavid Sterba 					       mirror_num);
485256dd1bbSStefan Behrens 		if (!ret) {
486581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
487b9fab919SChris Mason 						   parent_transid, 0))
488256dd1bbSStefan Behrens 				ret = -EIO;
489581c1760SQu Wenruo 			else if (verify_level_key(fs_info, eb, level,
490ff76a864SLiu Bo 						  first_key, parent_transid))
491581c1760SQu Wenruo 				ret = -EUCLEAN;
492581c1760SQu Wenruo 			else
493581c1760SQu Wenruo 				break;
494256dd1bbSStefan Behrens 		}
495d397712bSChris Mason 
496a826d6dcSJosef Bacik 		/*
497a826d6dcSJosef Bacik 		 * This buffer's crc is fine, but its contents are corrupted, so
498a826d6dcSJosef Bacik 		 * there is no reason to read the other copies, they won't be
499a826d6dcSJosef Bacik 		 * any less wrong.
500a826d6dcSJosef Bacik 		 */
501581c1760SQu Wenruo 		if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags) ||
502581c1760SQu Wenruo 		    ret == -EUCLEAN)
503ea466794SJosef Bacik 			break;
504ea466794SJosef Bacik 
5050b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
506f188591eSChris Mason 					      eb->start, eb->len);
5074235298eSChris Mason 		if (num_copies == 1)
508ea466794SJosef Bacik 			break;
5094235298eSChris Mason 
5105cf1ab56SJosef Bacik 		if (!failed_mirror) {
5115cf1ab56SJosef Bacik 			failed = 1;
5125cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
5135cf1ab56SJosef Bacik 		}
5145cf1ab56SJosef Bacik 
515f188591eSChris Mason 		mirror_num++;
516ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
517ea466794SJosef Bacik 			mirror_num++;
518ea466794SJosef Bacik 
5194235298eSChris Mason 		if (mirror_num > num_copies)
520ea466794SJosef Bacik 			break;
521f188591eSChris Mason 	}
522ea466794SJosef Bacik 
523c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
5242ff7e61eSJeff Mahoney 		repair_eb_io_failure(fs_info, eb, failed_mirror);
525ea466794SJosef Bacik 
526ea466794SJosef Bacik 	return ret;
527f188591eSChris Mason }
52819c00ddcSChris Mason 
529d352ac68SChris Mason /*
530d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
531d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
532d352ac68SChris Mason  */
533d397712bSChris Mason 
53401d58472SDaniel Dressler static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
53519c00ddcSChris Mason {
5364eee4fa4SMiao Xie 	u64 start = page_offset(page);
53719c00ddcSChris Mason 	u64 found_start;
53819c00ddcSChris Mason 	struct extent_buffer *eb;
539f188591eSChris Mason 
5404f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5414f2de97aSJosef Bacik 	if (page != eb->pages[0])
5424f2de97aSJosef Bacik 		return 0;
5430f805531SAlex Lyakas 
54419c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
5450f805531SAlex Lyakas 	/*
5460f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5470f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5480f805531SAlex Lyakas 	 */
5490f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5500f805531SAlex Lyakas 		return -EUCLEAN;
5510f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5520f805531SAlex Lyakas 		return -EUCLEAN;
5530f805531SAlex Lyakas 
5540f805531SAlex Lyakas 	ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
5550f805531SAlex Lyakas 			btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
5560f805531SAlex Lyakas 
5578bd98f0eSAlex Lyakas 	return csum_tree_block(fs_info, eb, 0);
55819c00ddcSChris Mason }
55919c00ddcSChris Mason 
56001d58472SDaniel Dressler static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
5612b82032cSYan Zheng 				 struct extent_buffer *eb)
5622b82032cSYan Zheng {
56301d58472SDaniel Dressler 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
56444880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
5652b82032cSYan Zheng 	int ret = 1;
5662b82032cSYan Zheng 
5670a4e5586SRoss Kirk 	read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
5682b82032cSYan Zheng 	while (fs_devices) {
5692b82032cSYan Zheng 		if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
5702b82032cSYan Zheng 			ret = 0;
5712b82032cSYan Zheng 			break;
5722b82032cSYan Zheng 		}
5732b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5742b82032cSYan Zheng 	}
5752b82032cSYan Zheng 	return ret;
5762b82032cSYan Zheng }
5772b82032cSYan Zheng 
578facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
579facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
580facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
581ce9adaa5SChris Mason {
582ce9adaa5SChris Mason 	u64 found_start;
583ce9adaa5SChris Mason 	int found_level;
584ce9adaa5SChris Mason 	struct extent_buffer *eb;
585ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
58602873e43SZhao Lei 	struct btrfs_fs_info *fs_info = root->fs_info;
587f188591eSChris Mason 	int ret = 0;
588727011e0SChris Mason 	int reads_done;
589ce9adaa5SChris Mason 
590ce9adaa5SChris Mason 	if (!page->private)
591ce9adaa5SChris Mason 		goto out;
592d397712bSChris Mason 
5934f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
594d397712bSChris Mason 
5950b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
5960b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
5970b32f4bbSJosef Bacik 	 */
5980b32f4bbSJosef Bacik 	extent_buffer_get(eb);
5990b32f4bbSJosef Bacik 
6000b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
601727011e0SChris Mason 	if (!reads_done)
602727011e0SChris Mason 		goto err;
603f188591eSChris Mason 
6045cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
605656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
606ea466794SJosef Bacik 		ret = -EIO;
607ea466794SJosef Bacik 		goto err;
608ea466794SJosef Bacik 	}
609ea466794SJosef Bacik 
610ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
611727011e0SChris Mason 	if (found_start != eb->start) {
612893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
613893bf4b1SSu Yue 			     eb->start, found_start);
614f188591eSChris Mason 		ret = -EIO;
615ce9adaa5SChris Mason 		goto err;
616ce9adaa5SChris Mason 	}
61702873e43SZhao Lei 	if (check_tree_block_fsid(fs_info, eb)) {
61802873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
61994647322SDavid Sterba 			     eb->start);
6201259ab75SChris Mason 		ret = -EIO;
6211259ab75SChris Mason 		goto err;
6221259ab75SChris Mason 	}
623ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6241c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
625893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
626893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
6271c24c3ceSJosef Bacik 		ret = -EIO;
6281c24c3ceSJosef Bacik 		goto err;
6291c24c3ceSJosef Bacik 	}
630ce9adaa5SChris Mason 
63185d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
63285d4e461SChris Mason 				       eb, found_level);
6334008c04aSChris Mason 
63402873e43SZhao Lei 	ret = csum_tree_block(fs_info, eb, 1);
6358bd98f0eSAlex Lyakas 	if (ret)
636a826d6dcSJosef Bacik 		goto err;
637a826d6dcSJosef Bacik 
638a826d6dcSJosef Bacik 	/*
639a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
640a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
641a826d6dcSJosef Bacik 	 * return -EIO.
642a826d6dcSJosef Bacik 	 */
6432f659546SQu Wenruo 	if (found_level == 0 && btrfs_check_leaf_full(fs_info, eb)) {
644a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
645a826d6dcSJosef Bacik 		ret = -EIO;
646a826d6dcSJosef Bacik 	}
647ce9adaa5SChris Mason 
6482f659546SQu Wenruo 	if (found_level > 0 && btrfs_check_node(fs_info, eb))
649053ab70fSLiu Bo 		ret = -EIO;
650053ab70fSLiu Bo 
6510b32f4bbSJosef Bacik 	if (!ret)
6520b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
653ce9adaa5SChris Mason err:
65479fb65a1SJosef Bacik 	if (reads_done &&
65579fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
656d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6574bb31e92SArne Jansen 
65853b381b3SDavid Woodhouse 	if (ret) {
65953b381b3SDavid Woodhouse 		/*
66053b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
66153b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
66253b381b3SDavid Woodhouse 		 * to decrement
66353b381b3SDavid Woodhouse 		 */
66453b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6650b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
66653b381b3SDavid Woodhouse 	}
6670b32f4bbSJosef Bacik 	free_extent_buffer(eb);
668ce9adaa5SChris Mason out:
669f188591eSChris Mason 	return ret;
670ce9adaa5SChris Mason }
671ce9adaa5SChris Mason 
672ea466794SJosef Bacik static int btree_io_failed_hook(struct page *page, int failed_mirror)
6734bb31e92SArne Jansen {
6744bb31e92SArne Jansen 	struct extent_buffer *eb;
6754bb31e92SArne Jansen 
6764f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
677656f30dbSFilipe Manana 	set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6785cf1ab56SJosef Bacik 	eb->read_mirror = failed_mirror;
67953b381b3SDavid Woodhouse 	atomic_dec(&eb->io_pages);
680ea466794SJosef Bacik 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
681d48d71aaSDavid Sterba 		btree_readahead_hook(eb, -EIO);
6824bb31e92SArne Jansen 	return -EIO;	/* we fixed nothing */
6834bb31e92SArne Jansen }
6844bb31e92SArne Jansen 
6854246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
686ce9adaa5SChris Mason {
68797eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
688ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6899e0af237SLiu Bo 	struct btrfs_workqueue *wq;
6909e0af237SLiu Bo 	btrfs_work_func_t func;
691ce9adaa5SChris Mason 
692ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
6934e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
694d20f7043SChris Mason 
69537226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
6969e0af237SLiu Bo 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
6979e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
6989e0af237SLiu Bo 			func = btrfs_endio_meta_write_helper;
6999e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
7009e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
7019e0af237SLiu Bo 			func = btrfs_freespace_write_helper;
7029e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7039e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7049e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
705d20f7043SChris Mason 		} else {
7069e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7079e0af237SLiu Bo 			func = btrfs_endio_write_helper;
708d20f7043SChris Mason 		}
7099e0af237SLiu Bo 	} else {
7108b110e39SMiao Xie 		if (unlikely(end_io_wq->metadata ==
7118b110e39SMiao Xie 			     BTRFS_WQ_ENDIO_DIO_REPAIR)) {
7128b110e39SMiao Xie 			wq = fs_info->endio_repair_workers;
7138b110e39SMiao Xie 			func = btrfs_endio_repair_helper;
7148b110e39SMiao Xie 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7159e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7169e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
7179e0af237SLiu Bo 		} else if (end_io_wq->metadata) {
7189e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
7199e0af237SLiu Bo 			func = btrfs_endio_meta_helper;
7209e0af237SLiu Bo 		} else {
7219e0af237SLiu Bo 			wq = fs_info->endio_workers;
7229e0af237SLiu Bo 			func = btrfs_endio_helper;
7239e0af237SLiu Bo 		}
7249e0af237SLiu Bo 	}
7259e0af237SLiu Bo 
7269e0af237SLiu Bo 	btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
7279e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
728ce9adaa5SChris Mason }
729ce9adaa5SChris Mason 
7304e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
731bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7320b86a832SChris Mason {
73397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7348b110e39SMiao Xie 
73597eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
736ce9adaa5SChris Mason 	if (!end_io_wq)
7374e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
738ce9adaa5SChris Mason 
739ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
740ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
74122c59948SChris Mason 	end_io_wq->info = info;
7424e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
743ce9adaa5SChris Mason 	end_io_wq->bio = bio;
74422c59948SChris Mason 	end_io_wq->metadata = metadata;
745ce9adaa5SChris Mason 
746ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
747ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
74822c59948SChris Mason 	return 0;
74922c59948SChris Mason }
75022c59948SChris Mason 
7514a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7524a69a410SChris Mason {
7534a69a410SChris Mason 	struct async_submit_bio *async;
7544e4cbee9SChristoph Hellwig 	blk_status_t ret;
7554a69a410SChris Mason 
7564a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
757c6100a4bSJosef Bacik 	ret = async->submit_bio_start(async->private_data, async->bio,
758eaf25d93SChris Mason 				      async->bio_offset);
75979787eaaSJeff Mahoney 	if (ret)
7604e4cbee9SChristoph Hellwig 		async->status = ret;
7614a69a410SChris Mason }
7624a69a410SChris Mason 
7634a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7648b712842SChris Mason {
7658b712842SChris Mason 	struct async_submit_bio *async;
7668b712842SChris Mason 
7678b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7684854ddd0SChris Mason 
769bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7704e4cbee9SChristoph Hellwig 	if (async->status) {
7714e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7724246a0b6SChristoph Hellwig 		bio_endio(async->bio);
77379787eaaSJeff Mahoney 		return;
77479787eaaSJeff Mahoney 	}
77579787eaaSJeff Mahoney 
776e288c080SDavid Sterba 	btrfs_submit_bio_done(async->private_data, async->bio, async->mirror_num);
7774a69a410SChris Mason }
7784a69a410SChris Mason 
7794a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7804a69a410SChris Mason {
7814a69a410SChris Mason 	struct async_submit_bio *async;
7824a69a410SChris Mason 
7834a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7848b712842SChris Mason 	kfree(async);
7858b712842SChris Mason }
7868b712842SChris Mason 
7878c27cb35SLinus Torvalds blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
788c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
789c6100a4bSJosef Bacik 				 u64 bio_offset, void *private_data,
790e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
79144b8bd7eSChris Mason {
79244b8bd7eSChris Mason 	struct async_submit_bio *async;
79344b8bd7eSChris Mason 
79444b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
79544b8bd7eSChris Mason 	if (!async)
7964e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
79744b8bd7eSChris Mason 
798c6100a4bSJosef Bacik 	async->private_data = private_data;
79944b8bd7eSChris Mason 	async->bio = bio;
80044b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8014a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8024a69a410SChris Mason 
8039e0af237SLiu Bo 	btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
8045cdc7ad3SQu Wenruo 			run_one_async_done, run_one_async_free);
8054a69a410SChris Mason 
806eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8078c8bee1dSChris Mason 
8084e4cbee9SChristoph Hellwig 	async->status = 0;
80979787eaaSJeff Mahoney 
81067f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8115cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
812d313d7a3SChris Mason 
8135cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
81444b8bd7eSChris Mason 	return 0;
81544b8bd7eSChris Mason }
81644b8bd7eSChris Mason 
8174e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
818ce3ed71aSChris Mason {
8192c30c71bSKent Overstreet 	struct bio_vec *bvec;
820ce3ed71aSChris Mason 	struct btrfs_root *root;
8212c30c71bSKent Overstreet 	int i, ret = 0;
822ce3ed71aSChris Mason 
823c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8242c30c71bSKent Overstreet 	bio_for_each_segment_all(bvec, bio, i) {
825ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
82601d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
82779787eaaSJeff Mahoney 		if (ret)
82879787eaaSJeff Mahoney 			break;
829ce3ed71aSChris Mason 	}
8302c30c71bSKent Overstreet 
8314e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
832ce3ed71aSChris Mason }
833ce3ed71aSChris Mason 
834d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
835eaf25d93SChris Mason 					     u64 bio_offset)
83622c59948SChris Mason {
8378b712842SChris Mason 	/*
8388b712842SChris Mason 	 * when we're called for a write, we're already in the async
8395443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8408b712842SChris Mason 	 */
84179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
84222c59948SChris Mason }
84322c59948SChris Mason 
84418fdc679SLiu Bo static int check_async_write(struct btrfs_inode *bi)
845de0022b9SJosef Bacik {
8466300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8476300463bSLiu Bo 		return 0;
848de0022b9SJosef Bacik #ifdef CONFIG_X86
849bc696ca0SBorislav Petkov 	if (static_cpu_has(X86_FEATURE_XMM4_2))
850de0022b9SJosef Bacik 		return 0;
851de0022b9SJosef Bacik #endif
852de0022b9SJosef Bacik 	return 1;
853de0022b9SJosef Bacik }
854de0022b9SJosef Bacik 
8558c27cb35SLinus Torvalds static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
856eaf25d93SChris Mason 					  int mirror_num, unsigned long bio_flags,
857eaf25d93SChris Mason 					  u64 bio_offset)
85844b8bd7eSChris Mason {
859c6100a4bSJosef Bacik 	struct inode *inode = private_data;
8600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
86118fdc679SLiu Bo 	int async = check_async_write(BTRFS_I(inode));
8624e4cbee9SChristoph Hellwig 	blk_status_t ret;
863cad321adSChris Mason 
86437226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
865cad321adSChris Mason 		/*
866cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
867cad321adSChris Mason 		 * can happen in the async kernel threads
868cad321adSChris Mason 		 */
8690b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8700b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8711d4284bdSChris Mason 		if (ret)
87261891923SStefan Behrens 			goto out_w_error;
8732ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
874de0022b9SJosef Bacik 	} else if (!async) {
875de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
876de0022b9SJosef Bacik 		if (ret)
87761891923SStefan Behrens 			goto out_w_error;
8782ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
87961891923SStefan Behrens 	} else {
880cad321adSChris Mason 		/*
88161891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
88261891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
883cad321adSChris Mason 		 */
884c6100a4bSJosef Bacik 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
885c6100a4bSJosef Bacik 					  bio_offset, private_data,
886e288c080SDavid Sterba 					  btree_submit_bio_start);
88744b8bd7eSChris Mason 	}
88844b8bd7eSChris Mason 
8894246a0b6SChristoph Hellwig 	if (ret)
8904246a0b6SChristoph Hellwig 		goto out_w_error;
8914246a0b6SChristoph Hellwig 	return 0;
8924246a0b6SChristoph Hellwig 
89361891923SStefan Behrens out_w_error:
8944e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
8954246a0b6SChristoph Hellwig 	bio_endio(bio);
89661891923SStefan Behrens 	return ret;
89761891923SStefan Behrens }
89861891923SStefan Behrens 
8993dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
900784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
901a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
902a6bc32b8SMel Gorman 			enum migrate_mode mode)
903784b4e29SChris Mason {
904784b4e29SChris Mason 	/*
905784b4e29SChris Mason 	 * we can't safely write a btree page from here,
906784b4e29SChris Mason 	 * we haven't done the locking hook
907784b4e29SChris Mason 	 */
908784b4e29SChris Mason 	if (PageDirty(page))
909784b4e29SChris Mason 		return -EAGAIN;
910784b4e29SChris Mason 	/*
911784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
912784b4e29SChris Mason 	 * We must have no buffers or drop them.
913784b4e29SChris Mason 	 */
914784b4e29SChris Mason 	if (page_has_private(page) &&
915784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
916784b4e29SChris Mason 		return -EAGAIN;
917a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
918784b4e29SChris Mason }
9193dd1462eSJan Beulich #endif
920784b4e29SChris Mason 
9210da5468fSChris Mason 
9220da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9230da5468fSChris Mason 			    struct writeback_control *wbc)
9240da5468fSChris Mason {
925e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
926e2d84521SMiao Xie 	int ret;
927e2d84521SMiao Xie 
928d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
929448d640bSChris Mason 
930448d640bSChris Mason 		if (wbc->for_kupdate)
931448d640bSChris Mason 			return 0;
932448d640bSChris Mason 
933e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
934b9473439SChris Mason 		/* this is a bit racy, but that's ok */
935d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
936d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
937d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
938e2d84521SMiao Xie 		if (ret < 0)
939793955bcSChris Mason 			return 0;
940793955bcSChris Mason 	}
9410b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9420da5468fSChris Mason }
9430da5468fSChris Mason 
944b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9455f39d397SChris Mason {
946d1310b2eSChris Mason 	struct extent_io_tree *tree;
947d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9488ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
9495f39d397SChris Mason }
9505f39d397SChris Mason 
95170dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9525f39d397SChris Mason {
95398509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
95498509cfcSChris Mason 		return 0;
9550c4e538bSDavid Sterba 
956f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
957d98237b3SChris Mason }
958d98237b3SChris Mason 
959d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
960d47992f8SLukas Czerner 				 unsigned int length)
961d98237b3SChris Mason {
962d1310b2eSChris Mason 	struct extent_io_tree *tree;
963d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9645f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9655f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9669ad6b7bcSChris Mason 	if (PagePrivate(page)) {
967efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
968efe120a0SFrank Holton 			   "page private not zero on page %llu",
969efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
9709ad6b7bcSChris Mason 		ClearPagePrivate(page);
9719ad6b7bcSChris Mason 		set_page_private(page, 0);
97209cbfeafSKirill A. Shutemov 		put_page(page);
9739ad6b7bcSChris Mason 	}
974d98237b3SChris Mason }
975d98237b3SChris Mason 
9760b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9770b32f4bbSJosef Bacik {
978bb146eb2SJosef Bacik #ifdef DEBUG
9790b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9800b32f4bbSJosef Bacik 
9810b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9820b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9830b32f4bbSJosef Bacik 	BUG_ON(!eb);
9840b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9850b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
9860b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
987bb146eb2SJosef Bacik #endif
9880b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
9890b32f4bbSJosef Bacik }
9900b32f4bbSJosef Bacik 
9917f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
992d98237b3SChris Mason 	.readpage	= btree_readpage,
9930da5468fSChris Mason 	.writepages	= btree_writepages,
9945f39d397SChris Mason 	.releasepage	= btree_releasepage,
9955f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
9965a92bc88SChris Mason #ifdef CONFIG_MIGRATION
997784b4e29SChris Mason 	.migratepage	= btree_migratepage,
9985a92bc88SChris Mason #endif
9990b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1000d98237b3SChris Mason };
1001123abc88SChris Mason 
10022ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1003090d1875SChris Mason {
10045f39d397SChris Mason 	struct extent_buffer *buf = NULL;
10052ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1006090d1875SChris Mason 
10072ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1008c871b0f2SLiu Bo 	if (IS_ERR(buf))
10096197d86eSDavid Sterba 		return;
1010d1310b2eSChris Mason 	read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
10116af49dbdSDavid Sterba 				 buf, WAIT_NONE, 0);
10125f39d397SChris Mason 	free_extent_buffer(buf);
1013090d1875SChris Mason }
1014090d1875SChris Mason 
10152ff7e61eSJeff Mahoney int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1016ab0fff03SArne Jansen 			 int mirror_num, struct extent_buffer **eb)
1017ab0fff03SArne Jansen {
1018ab0fff03SArne Jansen 	struct extent_buffer *buf = NULL;
10192ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1020ab0fff03SArne Jansen 	struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1021ab0fff03SArne Jansen 	int ret;
1022ab0fff03SArne Jansen 
10232ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1024c871b0f2SLiu Bo 	if (IS_ERR(buf))
1025ab0fff03SArne Jansen 		return 0;
1026ab0fff03SArne Jansen 
1027ab0fff03SArne Jansen 	set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1028ab0fff03SArne Jansen 
10298436ea91SJosef Bacik 	ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
10306af49dbdSDavid Sterba 				       mirror_num);
1031ab0fff03SArne Jansen 	if (ret) {
1032ab0fff03SArne Jansen 		free_extent_buffer(buf);
1033ab0fff03SArne Jansen 		return ret;
1034ab0fff03SArne Jansen 	}
1035ab0fff03SArne Jansen 
1036ab0fff03SArne Jansen 	if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1037ab0fff03SArne Jansen 		free_extent_buffer(buf);
1038ab0fff03SArne Jansen 		return -EIO;
10390b32f4bbSJosef Bacik 	} else if (extent_buffer_uptodate(buf)) {
1040ab0fff03SArne Jansen 		*eb = buf;
1041ab0fff03SArne Jansen 	} else {
1042ab0fff03SArne Jansen 		free_extent_buffer(buf);
1043ab0fff03SArne Jansen 	}
1044ab0fff03SArne Jansen 	return 0;
1045ab0fff03SArne Jansen }
1046ab0fff03SArne Jansen 
10472ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10482ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10490308af44SDavid Sterba 						u64 bytenr)
10500999df54SChris Mason {
10510b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10520b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10530b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
10540999df54SChris Mason }
10550999df54SChris Mason 
10560999df54SChris Mason 
1057e02119d5SChris Mason int btrfs_write_tree_block(struct extent_buffer *buf)
1058e02119d5SChris Mason {
1059727011e0SChris Mason 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
10608aa38c31SChristoph Hellwig 					buf->start + buf->len - 1);
1061e02119d5SChris Mason }
1062e02119d5SChris Mason 
10633189ff77SJeff Layton void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1064e02119d5SChris Mason {
10653189ff77SJeff Layton 	filemap_fdatawait_range(buf->pages[0]->mapping,
10668aa38c31SChristoph Hellwig 			        buf->start, buf->start + buf->len - 1);
1067e02119d5SChris Mason }
1068e02119d5SChris Mason 
1069581c1760SQu Wenruo /*
1070581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1071581c1760SQu Wenruo  * verification.
1072581c1760SQu Wenruo  *
1073581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1074581c1760SQu Wenruo  * @level:		expected level, mandatory check
1075581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1076581c1760SQu Wenruo  */
10772ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1078581c1760SQu Wenruo 				      u64 parent_transid, int level,
1079581c1760SQu Wenruo 				      struct btrfs_key *first_key)
1080e20d96d6SChris Mason {
10815f39d397SChris Mason 	struct extent_buffer *buf = NULL;
108219c00ddcSChris Mason 	int ret;
108319c00ddcSChris Mason 
10842ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1085c871b0f2SLiu Bo 	if (IS_ERR(buf))
1086c871b0f2SLiu Bo 		return buf;
1087e4204dedSChris Mason 
1088581c1760SQu Wenruo 	ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
1089581c1760SQu Wenruo 					     level, first_key);
10900f0fe8f7SFilipe David Borba Manana 	if (ret) {
10910f0fe8f7SFilipe David Borba Manana 		free_extent_buffer(buf);
109264c043deSLiu Bo 		return ERR_PTR(ret);
10930f0fe8f7SFilipe David Borba Manana 	}
10945f39d397SChris Mason 	return buf;
1095ce9adaa5SChris Mason 
1096eb60ceacSChris Mason }
1097eb60ceacSChris Mason 
10987c302b49SDavid Sterba void clean_tree_block(struct btrfs_fs_info *fs_info,
10995f39d397SChris Mason 		      struct extent_buffer *buf)
1100ed2ff2cbSChris Mason {
110155c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1102e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1103b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1104b4ce94deSChris Mason 
1105b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1106104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1107e2d84521SMiao Xie 						 -buf->len,
1108e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
1109b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
1110b9473439SChris Mason 			btrfs_set_lock_blocking(buf);
11110b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1112925baeddSChris Mason 		}
11135f39d397SChris Mason 	}
1114ed7b63ebSJosef Bacik }
11155f39d397SChris Mason 
11168257b2dcSMiao Xie static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
11178257b2dcSMiao Xie {
11188257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
11198257b2dcSMiao Xie 	int ret;
11208257b2dcSMiao Xie 
11218257b2dcSMiao Xie 	writers = kmalloc(sizeof(*writers), GFP_NOFS);
11228257b2dcSMiao Xie 	if (!writers)
11238257b2dcSMiao Xie 		return ERR_PTR(-ENOMEM);
11248257b2dcSMiao Xie 
11258a5a916dSJeff Mahoney 	ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
11268257b2dcSMiao Xie 	if (ret < 0) {
11278257b2dcSMiao Xie 		kfree(writers);
11288257b2dcSMiao Xie 		return ERR_PTR(ret);
11298257b2dcSMiao Xie 	}
11308257b2dcSMiao Xie 
11318257b2dcSMiao Xie 	init_waitqueue_head(&writers->wait);
11328257b2dcSMiao Xie 	return writers;
11338257b2dcSMiao Xie }
11348257b2dcSMiao Xie 
11358257b2dcSMiao Xie static void
11368257b2dcSMiao Xie btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
11378257b2dcSMiao Xie {
11388257b2dcSMiao Xie 	percpu_counter_destroy(&writers->counter);
11398257b2dcSMiao Xie 	kfree(writers);
11408257b2dcSMiao Xie }
11418257b2dcSMiao Xie 
1142da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1143e20d96d6SChris Mason 			 u64 objectid)
1144d97e63b6SChris Mason {
11457c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1146cfaa7295SChris Mason 	root->node = NULL;
1147a28ec197SChris Mason 	root->commit_root = NULL;
114827cdeb70SMiao Xie 	root->state = 0;
1149d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11500b86a832SChris Mason 
11510f7d52f4SChris Mason 	root->objectid = objectid;
11520f7d52f4SChris Mason 	root->last_trans = 0;
115313a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1154eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1155199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11566bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115716cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1158f0486c68SYan, Zheng 	root->block_rsv = NULL;
11590b86a832SChris Mason 
11600b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11615d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1162eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1163eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1164199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1165199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
11662ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11672ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11685d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1169eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1170199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1171f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11722ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11732ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11748287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1175a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1176e02119d5SChris Mason 	mutex_init(&root->log_mutex);
117731f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1178573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
11797237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11807237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11817237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11828b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11838b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11847237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11857237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11867237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11872ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11880700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
1189ea14b57fSDavid Sterba 	atomic_set(&root->will_be_snapshotted, 0);
11907237f183SYan Zheng 	root->log_transid = 0;
1191d1433debSMiao Xie 	root->log_transid_committed = -1;
1192257c62e1SChris Mason 	root->last_log_commit = 0;
11937c0260eeSJeff Mahoney 	if (!dummy)
1194c6100a4bSJosef Bacik 		extent_io_tree_init(&root->dirty_log_pages, NULL);
1195017e5369SChris Mason 
11963768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11973768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11986702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
11997c0260eeSJeff Mahoney 	if (!dummy)
12003f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
120106ea65a3SJosef Bacik 	else
120206ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
12034d775673SChris Mason 	root->root_key.objectid = objectid;
12040ee5dc67SAl Viro 	root->anon_dev = 0;
12058ea05e3aSAlexander Block 
12065f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
12073768f368SChris Mason }
12083768f368SChris Mason 
120974e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
121074e4d827SDavid Sterba 		gfp_t flags)
12116f07e42eSAl Viro {
121274e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12136f07e42eSAl Viro 	if (root)
12146f07e42eSAl Viro 		root->fs_info = fs_info;
12156f07e42eSAl Viro 	return root;
12166f07e42eSAl Viro }
12176f07e42eSAl Viro 
121806ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121906ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1220da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
122106ea65a3SJosef Bacik {
122206ea65a3SJosef Bacik 	struct btrfs_root *root;
122306ea65a3SJosef Bacik 
12247c0260eeSJeff Mahoney 	if (!fs_info)
12257c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12267c0260eeSJeff Mahoney 
12277c0260eeSJeff Mahoney 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
122806ea65a3SJosef Bacik 	if (!root)
122906ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1230da17066cSJeff Mahoney 
1231b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1232da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1233faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
123406ea65a3SJosef Bacik 
123506ea65a3SJosef Bacik 	return root;
123606ea65a3SJosef Bacik }
123706ea65a3SJosef Bacik #endif
123806ea65a3SJosef Bacik 
123920897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
124020897f5cSArne Jansen 				     struct btrfs_fs_info *fs_info,
124120897f5cSArne Jansen 				     u64 objectid)
124220897f5cSArne Jansen {
124320897f5cSArne Jansen 	struct extent_buffer *leaf;
124420897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
124520897f5cSArne Jansen 	struct btrfs_root *root;
124620897f5cSArne Jansen 	struct btrfs_key key;
124720897f5cSArne Jansen 	int ret = 0;
124833d85fdaSQu Wenruo 	uuid_le uuid = NULL_UUID_LE;
124920897f5cSArne Jansen 
125074e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
125120897f5cSArne Jansen 	if (!root)
125220897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
125320897f5cSArne Jansen 
1254da17066cSJeff Mahoney 	__setup_root(root, fs_info, objectid);
125520897f5cSArne Jansen 	root->root_key.objectid = objectid;
125620897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
125720897f5cSArne Jansen 	root->root_key.offset = 0;
125820897f5cSArne Jansen 
12594d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
126020897f5cSArne Jansen 	if (IS_ERR(leaf)) {
126120897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12621dd05682STsutomu Itoh 		leaf = NULL;
126320897f5cSArne Jansen 		goto fail;
126420897f5cSArne Jansen 	}
126520897f5cSArne Jansen 
126620897f5cSArne Jansen 	root->node = leaf;
126720897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
126820897f5cSArne Jansen 
126920897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
127027cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
127120897f5cSArne Jansen 
127220897f5cSArne Jansen 	root->root_item.flags = 0;
127320897f5cSArne Jansen 	root->root_item.byte_limit = 0;
127420897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
127520897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
127620897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
127720897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
127820897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
127920897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
128020897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
128133d85fdaSQu Wenruo 	if (is_fstree(objectid))
12826463fe58SStefan Behrens 		uuid_le_gen(&uuid);
12836463fe58SStefan Behrens 	memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
128420897f5cSArne Jansen 	root->root_item.drop_level = 0;
128520897f5cSArne Jansen 
128620897f5cSArne Jansen 	key.objectid = objectid;
128720897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
128820897f5cSArne Jansen 	key.offset = 0;
128920897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
129020897f5cSArne Jansen 	if (ret)
129120897f5cSArne Jansen 		goto fail;
129220897f5cSArne Jansen 
129320897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
129420897f5cSArne Jansen 
129520897f5cSArne Jansen 	return root;
12961dd05682STsutomu Itoh 
12971dd05682STsutomu Itoh fail:
12981dd05682STsutomu Itoh 	if (leaf) {
12991dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
130059885b39STsutomu Itoh 		free_extent_buffer(root->commit_root);
13011dd05682STsutomu Itoh 		free_extent_buffer(leaf);
13021dd05682STsutomu Itoh 	}
13031dd05682STsutomu Itoh 	kfree(root);
13041dd05682STsutomu Itoh 
13051dd05682STsutomu Itoh 	return ERR_PTR(ret);
130620897f5cSArne Jansen }
130720897f5cSArne Jansen 
13087237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1309e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13100f7d52f4SChris Mason {
13110f7d52f4SChris Mason 	struct btrfs_root *root;
13127237f183SYan Zheng 	struct extent_buffer *leaf;
1313e02119d5SChris Mason 
131474e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1315e02119d5SChris Mason 	if (!root)
13167237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1317e02119d5SChris Mason 
1318da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1319e02119d5SChris Mason 
1320e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1321e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1322e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
132327cdeb70SMiao Xie 
13247237f183SYan Zheng 	/*
132527cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
132627cdeb70SMiao Xie 	 *
13277237f183SYan Zheng 	 * log trees do not get reference counted because they go away
13287237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
13297237f183SYan Zheng 	 * to file data extents, and those reference counts still get
13307237f183SYan Zheng 	 * updated (along with back refs to the log tree).
13317237f183SYan Zheng 	 */
1332e02119d5SChris Mason 
13334d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13344d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
13357237f183SYan Zheng 	if (IS_ERR(leaf)) {
13367237f183SYan Zheng 		kfree(root);
13377237f183SYan Zheng 		return ERR_CAST(leaf);
13387237f183SYan Zheng 	}
1339e02119d5SChris Mason 
13407237f183SYan Zheng 	root->node = leaf;
1341e02119d5SChris Mason 
1342e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1343e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13447237f183SYan Zheng 	return root;
13457237f183SYan Zheng }
13467237f183SYan Zheng 
13477237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13487237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13497237f183SYan Zheng {
13507237f183SYan Zheng 	struct btrfs_root *log_root;
13517237f183SYan Zheng 
13527237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13537237f183SYan Zheng 	if (IS_ERR(log_root))
13547237f183SYan Zheng 		return PTR_ERR(log_root);
13557237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13567237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13577237f183SYan Zheng 	return 0;
13587237f183SYan Zheng }
13597237f183SYan Zheng 
13607237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13617237f183SYan Zheng 		       struct btrfs_root *root)
13627237f183SYan Zheng {
13630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13647237f183SYan Zheng 	struct btrfs_root *log_root;
13657237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13667237f183SYan Zheng 
13670b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13687237f183SYan Zheng 	if (IS_ERR(log_root))
13697237f183SYan Zheng 		return PTR_ERR(log_root);
13707237f183SYan Zheng 
13717237f183SYan Zheng 	log_root->last_trans = trans->transid;
13727237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13737237f183SYan Zheng 
13747237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13753cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13763cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13773cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1378da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13790b246afaSJeff Mahoney 				     fs_info->nodesize);
13803cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13817237f183SYan Zheng 
13825d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13837237f183SYan Zheng 
13847237f183SYan Zheng 	WARN_ON(root->log_root);
13857237f183SYan Zheng 	root->log_root = log_root;
13867237f183SYan Zheng 	root->log_transid = 0;
1387d1433debSMiao Xie 	root->log_transid_committed = -1;
1388257c62e1SChris Mason 	root->last_log_commit = 0;
1389e02119d5SChris Mason 	return 0;
1390e02119d5SChris Mason }
1391e02119d5SChris Mason 
139235a3621bSStefan Behrens static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1393cb517eabSMiao Xie 					       struct btrfs_key *key)
1394e02119d5SChris Mason {
1395e02119d5SChris Mason 	struct btrfs_root *root;
1396e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
13970f7d52f4SChris Mason 	struct btrfs_path *path;
139884234f3aSYan Zheng 	u64 generation;
1399cb517eabSMiao Xie 	int ret;
1400581c1760SQu Wenruo 	int level;
1401cb517eabSMiao Xie 
1402cb517eabSMiao Xie 	path = btrfs_alloc_path();
1403cb517eabSMiao Xie 	if (!path)
1404cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
14050f7d52f4SChris Mason 
140674e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1407cb517eabSMiao Xie 	if (!root) {
1408cb517eabSMiao Xie 		ret = -ENOMEM;
1409cb517eabSMiao Xie 		goto alloc_fail;
14100f7d52f4SChris Mason 	}
14110f7d52f4SChris Mason 
1412da17066cSJeff Mahoney 	__setup_root(root, fs_info, key->objectid);
14130f7d52f4SChris Mason 
1414cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1415cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14160f7d52f4SChris Mason 	if (ret) {
141713a8a7c8SYan, Zheng 		if (ret > 0)
141813a8a7c8SYan, Zheng 			ret = -ENOENT;
1419cb517eabSMiao Xie 		goto find_fail;
14200f7d52f4SChris Mason 	}
142113a8a7c8SYan, Zheng 
142284234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1423581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14242ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14252ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1426581c1760SQu Wenruo 				     generation, level, NULL);
142764c043deSLiu Bo 	if (IS_ERR(root->node)) {
142864c043deSLiu Bo 		ret = PTR_ERR(root->node);
1429cb517eabSMiao Xie 		goto find_fail;
1430cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1431cb517eabSMiao Xie 		ret = -EIO;
143264c043deSLiu Bo 		free_extent_buffer(root->node);
143364c043deSLiu Bo 		goto find_fail;
1434416bc658SJosef Bacik 	}
14355d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
143613a8a7c8SYan, Zheng out:
1437cb517eabSMiao Xie 	btrfs_free_path(path);
1438cb517eabSMiao Xie 	return root;
1439cb517eabSMiao Xie 
1440cb517eabSMiao Xie find_fail:
1441cb517eabSMiao Xie 	kfree(root);
1442cb517eabSMiao Xie alloc_fail:
1443cb517eabSMiao Xie 	root = ERR_PTR(ret);
1444cb517eabSMiao Xie 	goto out;
1445cb517eabSMiao Xie }
1446cb517eabSMiao Xie 
1447cb517eabSMiao Xie struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1448cb517eabSMiao Xie 				      struct btrfs_key *location)
1449cb517eabSMiao Xie {
1450cb517eabSMiao Xie 	struct btrfs_root *root;
1451cb517eabSMiao Xie 
1452cb517eabSMiao Xie 	root = btrfs_read_tree_root(tree_root, location);
1453cb517eabSMiao Xie 	if (IS_ERR(root))
1454cb517eabSMiao Xie 		return root;
1455cb517eabSMiao Xie 
1456cb517eabSMiao Xie 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
145727cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
145808fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
145908fe4db1SLi Zefan 	}
146013a8a7c8SYan, Zheng 
14615eda7b5eSChris Mason 	return root;
14625eda7b5eSChris Mason }
14635eda7b5eSChris Mason 
1464cb517eabSMiao Xie int btrfs_init_fs_root(struct btrfs_root *root)
1465cb517eabSMiao Xie {
1466cb517eabSMiao Xie 	int ret;
14678257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
1468cb517eabSMiao Xie 
1469cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1470cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1471cb517eabSMiao Xie 					GFP_NOFS);
1472cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1473cb517eabSMiao Xie 		ret = -ENOMEM;
1474cb517eabSMiao Xie 		goto fail;
1475cb517eabSMiao Xie 	}
1476cb517eabSMiao Xie 
14778257b2dcSMiao Xie 	writers = btrfs_alloc_subvolume_writers();
14788257b2dcSMiao Xie 	if (IS_ERR(writers)) {
14798257b2dcSMiao Xie 		ret = PTR_ERR(writers);
14808257b2dcSMiao Xie 		goto fail;
14818257b2dcSMiao Xie 	}
14828257b2dcSMiao Xie 	root->subv_writers = writers;
14838257b2dcSMiao Xie 
1484cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
148557cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
148657cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1487cb517eabSMiao Xie 
1488cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1489cb517eabSMiao Xie 	if (ret)
1490876d2cf1SLiu Bo 		goto fail;
1491f32e48e9SChandan Rajendra 
1492f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1493f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1494f32e48e9SChandan Rajendra 					&root->highest_objectid);
1495f32e48e9SChandan Rajendra 	if (ret) {
1496f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1497876d2cf1SLiu Bo 		goto fail;
1498f32e48e9SChandan Rajendra 	}
1499f32e48e9SChandan Rajendra 
1500f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1501f32e48e9SChandan Rajendra 
1502f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1503f32e48e9SChandan Rajendra 
1504cb517eabSMiao Xie 	return 0;
1505cb517eabSMiao Xie fail:
150684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1507cb517eabSMiao Xie 	return ret;
1508cb517eabSMiao Xie }
1509cb517eabSMiao Xie 
151035bbb97fSJeff Mahoney struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1511cb517eabSMiao Xie 					u64 root_id)
1512cb517eabSMiao Xie {
1513cb517eabSMiao Xie 	struct btrfs_root *root;
1514cb517eabSMiao Xie 
1515cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1516cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1517cb517eabSMiao Xie 				 (unsigned long)root_id);
1518cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1519cb517eabSMiao Xie 	return root;
1520cb517eabSMiao Xie }
1521cb517eabSMiao Xie 
1522cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1523cb517eabSMiao Xie 			 struct btrfs_root *root)
1524cb517eabSMiao Xie {
1525cb517eabSMiao Xie 	int ret;
1526cb517eabSMiao Xie 
1527e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1528cb517eabSMiao Xie 	if (ret)
1529cb517eabSMiao Xie 		return ret;
1530cb517eabSMiao Xie 
1531cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1532cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1533cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1534cb517eabSMiao Xie 				root);
1535cb517eabSMiao Xie 	if (ret == 0)
153627cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1537cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1538cb517eabSMiao Xie 	radix_tree_preload_end();
1539cb517eabSMiao Xie 
1540cb517eabSMiao Xie 	return ret;
1541cb517eabSMiao Xie }
1542cb517eabSMiao Xie 
1543c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1544c00869f1SMiao Xie 				     struct btrfs_key *location,
1545c00869f1SMiao Xie 				     bool check_ref)
15465eda7b5eSChris Mason {
15475eda7b5eSChris Mason 	struct btrfs_root *root;
1548381cf658SDavid Sterba 	struct btrfs_path *path;
15491d4c08e0SDavid Sterba 	struct btrfs_key key;
15505eda7b5eSChris Mason 	int ret;
15515eda7b5eSChris Mason 
1552edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1553edbd8d4eSChris Mason 		return fs_info->tree_root;
1554edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1555edbd8d4eSChris Mason 		return fs_info->extent_root;
15568f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
15578f18cf13SChris Mason 		return fs_info->chunk_root;
15588f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
15598f18cf13SChris Mason 		return fs_info->dev_root;
15600403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
15610403e47eSYan Zheng 		return fs_info->csum_root;
1562bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1563bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1564bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
1565f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1566f7a81ea4SStefan Behrens 		return fs_info->uuid_root ? fs_info->uuid_root :
1567f7a81ea4SStefan Behrens 					    ERR_PTR(-ENOENT);
156870f6d82eSOmar Sandoval 	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
156970f6d82eSOmar Sandoval 		return fs_info->free_space_root ? fs_info->free_space_root :
157070f6d82eSOmar Sandoval 						  ERR_PTR(-ENOENT);
15714df27c4dSYan, Zheng again:
1572cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
157348475471SStefan Behrens 	if (root) {
1574c00869f1SMiao Xie 		if (check_ref && btrfs_root_refs(&root->root_item) == 0)
157548475471SStefan Behrens 			return ERR_PTR(-ENOENT);
15765eda7b5eSChris Mason 		return root;
157748475471SStefan Behrens 	}
15785eda7b5eSChris Mason 
1579cb517eabSMiao Xie 	root = btrfs_read_fs_root(fs_info->tree_root, location);
15805eda7b5eSChris Mason 	if (IS_ERR(root))
15815eda7b5eSChris Mason 		return root;
15823394e160SChris Mason 
1583c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1584d68fc57bSYan, Zheng 		ret = -ENOENT;
1585d68fc57bSYan, Zheng 		goto fail;
1586d68fc57bSYan, Zheng 	}
1587d68fc57bSYan, Zheng 
1588cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1589cb517eabSMiao Xie 	if (ret)
1590cb517eabSMiao Xie 		goto fail;
1591cb517eabSMiao Xie 
1592381cf658SDavid Sterba 	path = btrfs_alloc_path();
1593381cf658SDavid Sterba 	if (!path) {
1594381cf658SDavid Sterba 		ret = -ENOMEM;
1595381cf658SDavid Sterba 		goto fail;
1596381cf658SDavid Sterba 	}
15971d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15981d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
15991d4c08e0SDavid Sterba 	key.offset = location->objectid;
16001d4c08e0SDavid Sterba 
16011d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1602381cf658SDavid Sterba 	btrfs_free_path(path);
1603d68fc57bSYan, Zheng 	if (ret < 0)
1604d68fc57bSYan, Zheng 		goto fail;
1605d68fc57bSYan, Zheng 	if (ret == 0)
160627cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1607d68fc57bSYan, Zheng 
1608cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16090f7d52f4SChris Mason 	if (ret) {
16104df27c4dSYan, Zheng 		if (ret == -EEXIST) {
161184db5ccfSDavid Sterba 			btrfs_free_fs_root(root);
16124df27c4dSYan, Zheng 			goto again;
16130f7d52f4SChris Mason 		}
16144df27c4dSYan, Zheng 		goto fail;
16154df27c4dSYan, Zheng 	}
1616edbd8d4eSChris Mason 	return root;
16174df27c4dSYan, Zheng fail:
161884db5ccfSDavid Sterba 	btrfs_free_fs_root(root);
16194df27c4dSYan, Zheng 	return ERR_PTR(ret);
1620edbd8d4eSChris Mason }
1621edbd8d4eSChris Mason 
162204160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
162304160088SChris Mason {
162404160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
162504160088SChris Mason 	int ret = 0;
162604160088SChris Mason 	struct btrfs_device *device;
162704160088SChris Mason 	struct backing_dev_info *bdi;
1628b7967db7SChris Mason 
16291f78160cSXiao Guangrong 	rcu_read_lock();
16301f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1631dfe25020SChris Mason 		if (!device->bdev)
1632dfe25020SChris Mason 			continue;
1633efa7c9f9SJan Kara 		bdi = device->bdev->bd_bdi;
1634ff9ea323STejun Heo 		if (bdi_congested(bdi, bdi_bits)) {
163504160088SChris Mason 			ret = 1;
163604160088SChris Mason 			break;
163704160088SChris Mason 		}
163804160088SChris Mason 	}
16391f78160cSXiao Guangrong 	rcu_read_unlock();
164004160088SChris Mason 	return ret;
164104160088SChris Mason }
164204160088SChris Mason 
16438b712842SChris Mason /*
16448b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16458b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16468b712842SChris Mason  */
16478b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1648ce9adaa5SChris Mason {
1649ce9adaa5SChris Mason 	struct bio *bio;
165097eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1651ce9adaa5SChris Mason 
165297eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1653ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16548b712842SChris Mason 
16554e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1656ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1657ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
165897eb6b69SDavid Sterba 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
16594246a0b6SChristoph Hellwig 	bio_endio(bio);
1660ce9adaa5SChris Mason }
166144b8bd7eSChris Mason 
1662a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1663a74a4b97SChris Mason {
1664a74a4b97SChris Mason 	struct btrfs_root *root = arg;
16650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1666d0278245SMiao Xie 	int again;
1667da288d28SFilipe Manana 	struct btrfs_trans_handle *trans;
1668a74a4b97SChris Mason 
1669a74a4b97SChris Mason 	do {
1670d0278245SMiao Xie 		again = 0;
16719d1a2a3aSDavid Sterba 
1672d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16732ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1674d0278245SMiao Xie 			goto sleep;
1675d0278245SMiao Xie 
167690c711abSZygo Blaxell 		/*
167790c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
167890c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
167990c711abSZygo Blaxell 		 */
16800b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
168190c711abSZygo Blaxell 			goto sleep;
168290c711abSZygo Blaxell 
16830b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1684d0278245SMiao Xie 			goto sleep;
1685d0278245SMiao Xie 
1686dc7f370cSMiao Xie 		/*
1687dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1688dc7f370cSMiao Xie 		 * during the above check and trylock.
1689dc7f370cSMiao Xie 		 */
16902ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
16910b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1692dc7f370cSMiao Xie 			goto sleep;
1693dc7f370cSMiao Xie 		}
1694dc7f370cSMiao Xie 
16950b246afaSJeff Mahoney 		mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
16962ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
16970b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
1698c2d6cb16SFilipe Manana 
16999d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
17000b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1701a74a4b97SChris Mason 
1702d0278245SMiao Xie 		/*
170305323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
170405323cd1SMiao Xie 		 * needn't do anything special here.
1705d0278245SMiao Xie 		 */
17060b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
170767c5e7d4SFilipe Manana 
170867c5e7d4SFilipe Manana 		/*
170967c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
171067c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
171167c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
171267c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
171367c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
171467c5e7d4SFilipe Manana 		 * unused block groups.
171567c5e7d4SFilipe Manana 		 */
17160b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1717d0278245SMiao Xie sleep:
1718838fe188SJiri Kosina 		if (!again) {
1719a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
17208929ecfaSYan, Zheng 			if (!kthread_should_stop())
1721a74a4b97SChris Mason 				schedule();
1722a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1723a74a4b97SChris Mason 		}
1724a74a4b97SChris Mason 	} while (!kthread_should_stop());
1725da288d28SFilipe Manana 
1726da288d28SFilipe Manana 	/*
1727da288d28SFilipe Manana 	 * Transaction kthread is stopped before us and wakes us up.
1728da288d28SFilipe Manana 	 * However we might have started a new transaction and COWed some
1729da288d28SFilipe Manana 	 * tree blocks when deleting unused block groups for example. So
1730da288d28SFilipe Manana 	 * make sure we commit the transaction we started to have a clean
1731da288d28SFilipe Manana 	 * shutdown when evicting the btree inode - if it has dirty pages
1732da288d28SFilipe Manana 	 * when we do the final iput() on it, eviction will trigger a
1733da288d28SFilipe Manana 	 * writeback for it which will fail with null pointer dereferences
1734da288d28SFilipe Manana 	 * since work queues and other resources were already released and
1735da288d28SFilipe Manana 	 * destroyed by the time the iput/eviction/writeback is made.
1736da288d28SFilipe Manana 	 */
1737da288d28SFilipe Manana 	trans = btrfs_attach_transaction(root);
1738da288d28SFilipe Manana 	if (IS_ERR(trans)) {
1739da288d28SFilipe Manana 		if (PTR_ERR(trans) != -ENOENT)
17400b246afaSJeff Mahoney 			btrfs_err(fs_info,
1741da288d28SFilipe Manana 				  "cleaner transaction attach returned %ld",
1742da288d28SFilipe Manana 				  PTR_ERR(trans));
1743da288d28SFilipe Manana 	} else {
1744da288d28SFilipe Manana 		int ret;
1745da288d28SFilipe Manana 
17463a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
1747da288d28SFilipe Manana 		if (ret)
17480b246afaSJeff Mahoney 			btrfs_err(fs_info,
1749da288d28SFilipe Manana 				  "cleaner open transaction commit returned %d",
1750da288d28SFilipe Manana 				  ret);
1751da288d28SFilipe Manana 	}
1752da288d28SFilipe Manana 
1753a74a4b97SChris Mason 	return 0;
1754a74a4b97SChris Mason }
1755a74a4b97SChris Mason 
1756a74a4b97SChris Mason static int transaction_kthread(void *arg)
1757a74a4b97SChris Mason {
1758a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1760a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1761a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17628929ecfaSYan, Zheng 	u64 transid;
1763a944442cSAllen Pais 	time64_t now;
1764a74a4b97SChris Mason 	unsigned long delay;
1765914b2007SJan Kara 	bool cannot_commit;
1766a74a4b97SChris Mason 
1767a74a4b97SChris Mason 	do {
1768914b2007SJan Kara 		cannot_commit = false;
17690b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
17700b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1771a74a4b97SChris Mason 
17720b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17730b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1774a74a4b97SChris Mason 		if (!cur) {
17750b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1776a74a4b97SChris Mason 			goto sleep;
1777a74a4b97SChris Mason 		}
177831153d81SYan Zheng 
1779afd48513SArnd Bergmann 		now = ktime_get_seconds();
17804a9d8bdeSMiao Xie 		if (cur->state < TRANS_STATE_BLOCKED &&
1781a514d638SQu Wenruo 		    !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
17828b87dc17SDavid Sterba 		    (now < cur->start_time ||
17830b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
17840b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1785a74a4b97SChris Mason 			delay = HZ * 5;
1786a74a4b97SChris Mason 			goto sleep;
1787a74a4b97SChris Mason 		}
17888929ecfaSYan, Zheng 		transid = cur->transid;
17890b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
179056bec294SChris Mason 
179179787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1792354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1793914b2007SJan Kara 		if (IS_ERR(trans)) {
1794354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1795914b2007SJan Kara 				cannot_commit = true;
179679787eaaSJeff Mahoney 			goto sleep;
1797914b2007SJan Kara 		}
17988929ecfaSYan, Zheng 		if (transid == trans->transid) {
17993a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
18008929ecfaSYan, Zheng 		} else {
18013a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18028929ecfaSYan, Zheng 		}
1803a74a4b97SChris Mason sleep:
18040b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
18050b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1806a74a4b97SChris Mason 
18074e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
18080b246afaSJeff Mahoney 				      &fs_info->fs_state)))
18092ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
18108929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
18110b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1812914b2007SJan Kara 				 cannot_commit))
1813bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1814a74a4b97SChris Mason 	} while (!kthread_should_stop());
1815a74a4b97SChris Mason 	return 0;
1816a74a4b97SChris Mason }
1817a74a4b97SChris Mason 
1818af31f5e5SChris Mason /*
1819af31f5e5SChris Mason  * this will find the highest generation in the array of
1820af31f5e5SChris Mason  * root backups.  The index of the highest array is returned,
1821af31f5e5SChris Mason  * or -1 if we can't find anything.
1822af31f5e5SChris Mason  *
1823af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1824af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1825af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1826af31f5e5SChris Mason  */
1827af31f5e5SChris Mason static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1828af31f5e5SChris Mason {
1829af31f5e5SChris Mason 	u64 cur;
1830af31f5e5SChris Mason 	int newest_index = -1;
1831af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1832af31f5e5SChris Mason 	int i;
1833af31f5e5SChris Mason 
1834af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1835af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1836af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1837af31f5e5SChris Mason 		if (cur == newest_gen)
1838af31f5e5SChris Mason 			newest_index = i;
1839af31f5e5SChris Mason 	}
1840af31f5e5SChris Mason 
1841af31f5e5SChris Mason 	/* check to see if we actually wrapped around */
1842af31f5e5SChris Mason 	if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1843af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots;
1844af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1845af31f5e5SChris Mason 		if (cur == newest_gen)
1846af31f5e5SChris Mason 			newest_index = 0;
1847af31f5e5SChris Mason 	}
1848af31f5e5SChris Mason 	return newest_index;
1849af31f5e5SChris Mason }
1850af31f5e5SChris Mason 
1851af31f5e5SChris Mason 
1852af31f5e5SChris Mason /*
1853af31f5e5SChris Mason  * find the oldest backup so we know where to store new entries
1854af31f5e5SChris Mason  * in the backup array.  This will set the backup_root_index
1855af31f5e5SChris Mason  * field in the fs_info struct
1856af31f5e5SChris Mason  */
1857af31f5e5SChris Mason static void find_oldest_super_backup(struct btrfs_fs_info *info,
1858af31f5e5SChris Mason 				     u64 newest_gen)
1859af31f5e5SChris Mason {
1860af31f5e5SChris Mason 	int newest_index = -1;
1861af31f5e5SChris Mason 
1862af31f5e5SChris Mason 	newest_index = find_newest_super_backup(info, newest_gen);
1863af31f5e5SChris Mason 	/* if there was garbage in there, just move along */
1864af31f5e5SChris Mason 	if (newest_index == -1) {
1865af31f5e5SChris Mason 		info->backup_root_index = 0;
1866af31f5e5SChris Mason 	} else {
1867af31f5e5SChris Mason 		info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1868af31f5e5SChris Mason 	}
1869af31f5e5SChris Mason }
1870af31f5e5SChris Mason 
1871af31f5e5SChris Mason /*
1872af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1873af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1874af31f5e5SChris Mason  * done
1875af31f5e5SChris Mason  */
1876af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1877af31f5e5SChris Mason {
1878af31f5e5SChris Mason 	int next_backup;
1879af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1880af31f5e5SChris Mason 	int last_backup;
1881af31f5e5SChris Mason 
1882af31f5e5SChris Mason 	next_backup = info->backup_root_index;
1883af31f5e5SChris Mason 	last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1884af31f5e5SChris Mason 		BTRFS_NUM_BACKUP_ROOTS;
1885af31f5e5SChris Mason 
1886af31f5e5SChris Mason 	/*
1887af31f5e5SChris Mason 	 * just overwrite the last backup if we're at the same generation
1888af31f5e5SChris Mason 	 * this happens only at umount
1889af31f5e5SChris Mason 	 */
1890af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + last_backup;
1891af31f5e5SChris Mason 	if (btrfs_backup_tree_root_gen(root_backup) ==
1892af31f5e5SChris Mason 	    btrfs_header_generation(info->tree_root->node))
1893af31f5e5SChris Mason 		next_backup = last_backup;
1894af31f5e5SChris Mason 
1895af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1896af31f5e5SChris Mason 
1897af31f5e5SChris Mason 	/*
1898af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1899af31f5e5SChris Mason 	 * regardless of which ones we use today
1900af31f5e5SChris Mason 	 */
1901af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1902af31f5e5SChris Mason 
1903af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1904af31f5e5SChris Mason 
1905af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1906af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1907af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1908af31f5e5SChris Mason 
1909af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1910af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1911af31f5e5SChris Mason 
1912af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1913af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1914af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1915af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1916af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1917af31f5e5SChris Mason 
1918af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1919af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1920af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1921af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1922af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1923af31f5e5SChris Mason 
19247c7e82a7SChris Mason 	/*
19257c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
19267c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
19277c7e82a7SChris Mason 	 */
19287c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
19297c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
19307c7e82a7SChris Mason 					 info->fs_root->node->start);
1931af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1932af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1933af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1934af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19357c7e82a7SChris Mason 	}
1936af31f5e5SChris Mason 
1937af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1938af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1939af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1940af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1941af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1942af31f5e5SChris Mason 
1943af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1944af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1945af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1946af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1947af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1948af31f5e5SChris Mason 
1949af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1950af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1951af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1952af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1953af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1954af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1955af31f5e5SChris Mason 
1956af31f5e5SChris Mason 	/*
1957af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1958af31f5e5SChris Mason 	 * for the next commit
1959af31f5e5SChris Mason 	 */
1960af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1961af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1962af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1963af31f5e5SChris Mason }
1964af31f5e5SChris Mason 
1965af31f5e5SChris Mason /*
1966af31f5e5SChris Mason  * this copies info out of the root backup array and back into
1967af31f5e5SChris Mason  * the in-memory super block.  It is meant to help iterate through
1968af31f5e5SChris Mason  * the array, so you send it the number of backups you've already
1969af31f5e5SChris Mason  * tried and the last backup index you used.
1970af31f5e5SChris Mason  *
1971af31f5e5SChris Mason  * this returns -1 when it has tried all the backups
1972af31f5e5SChris Mason  */
1973af31f5e5SChris Mason static noinline int next_root_backup(struct btrfs_fs_info *info,
1974af31f5e5SChris Mason 				     struct btrfs_super_block *super,
1975af31f5e5SChris Mason 				     int *num_backups_tried, int *backup_index)
1976af31f5e5SChris Mason {
1977af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1978af31f5e5SChris Mason 	int newest = *backup_index;
1979af31f5e5SChris Mason 
1980af31f5e5SChris Mason 	if (*num_backups_tried == 0) {
1981af31f5e5SChris Mason 		u64 gen = btrfs_super_generation(super);
1982af31f5e5SChris Mason 
1983af31f5e5SChris Mason 		newest = find_newest_super_backup(info, gen);
1984af31f5e5SChris Mason 		if (newest == -1)
1985af31f5e5SChris Mason 			return -1;
1986af31f5e5SChris Mason 
1987af31f5e5SChris Mason 		*backup_index = newest;
1988af31f5e5SChris Mason 		*num_backups_tried = 1;
1989af31f5e5SChris Mason 	} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1990af31f5e5SChris Mason 		/* we've tried all the backups, all done */
1991af31f5e5SChris Mason 		return -1;
1992af31f5e5SChris Mason 	} else {
1993af31f5e5SChris Mason 		/* jump to the next oldest backup */
1994af31f5e5SChris Mason 		newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1995af31f5e5SChris Mason 			BTRFS_NUM_BACKUP_ROOTS;
1996af31f5e5SChris Mason 		*backup_index = newest;
1997af31f5e5SChris Mason 		*num_backups_tried += 1;
1998af31f5e5SChris Mason 	}
1999af31f5e5SChris Mason 	root_backup = super->super_roots + newest;
2000af31f5e5SChris Mason 
2001af31f5e5SChris Mason 	btrfs_set_super_generation(super,
2002af31f5e5SChris Mason 				   btrfs_backup_tree_root_gen(root_backup));
2003af31f5e5SChris Mason 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2004af31f5e5SChris Mason 	btrfs_set_super_root_level(super,
2005af31f5e5SChris Mason 				   btrfs_backup_tree_root_level(root_backup));
2006af31f5e5SChris Mason 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2007af31f5e5SChris Mason 
2008af31f5e5SChris Mason 	/*
2009af31f5e5SChris Mason 	 * fixme: the total bytes and num_devices need to match or we should
2010af31f5e5SChris Mason 	 * need a fsck
2011af31f5e5SChris Mason 	 */
2012af31f5e5SChris Mason 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2013af31f5e5SChris Mason 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2014af31f5e5SChris Mason 	return 0;
2015af31f5e5SChris Mason }
2016af31f5e5SChris Mason 
20177abadb64SLiu Bo /* helper to cleanup workers */
20187abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20197abadb64SLiu Bo {
2020dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2021afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
20225cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2023fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2024fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
20258b110e39SMiao Xie 	btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2026d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2027fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2028fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2029a8c93d4eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->submit_workers);
20305b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2031e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2032736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2033a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2034fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2035a79b7d4bSChris Mason 	btrfs_destroy_workqueue(fs_info->extent_workers);
2036a9b9477dSFilipe Manana 	/*
2037a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2038a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2039a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2040a9b9477dSFilipe Manana 	 */
2041a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2042a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
20437abadb64SLiu Bo }
20447abadb64SLiu Bo 
20452e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20462e9f5954SRashika {
20472e9f5954SRashika 	if (root) {
20482e9f5954SRashika 		free_extent_buffer(root->node);
20492e9f5954SRashika 		free_extent_buffer(root->commit_root);
20502e9f5954SRashika 		root->node = NULL;
20512e9f5954SRashika 		root->commit_root = NULL;
20522e9f5954SRashika 	}
20532e9f5954SRashika }
20542e9f5954SRashika 
2055af31f5e5SChris Mason /* helper to cleanup tree roots */
2056af31f5e5SChris Mason static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2057af31f5e5SChris Mason {
20582e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2059655b09feSJosef Bacik 
20602e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
20612e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
20622e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
20632e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20642e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20652e9f5954SRashika 	if (chunk_root)
20662e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
206770f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2068af31f5e5SChris Mason }
2069af31f5e5SChris Mason 
2070faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2071171f6537SJosef Bacik {
2072171f6537SJosef Bacik 	int ret;
2073171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2074171f6537SJosef Bacik 	int i;
2075171f6537SJosef Bacik 
2076171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2077171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2078171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2079171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2080171f6537SJosef Bacik 
208127cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2082cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2083171f6537SJosef Bacik 		} else {
2084171f6537SJosef Bacik 			free_extent_buffer(gang[0]->node);
2085171f6537SJosef Bacik 			free_extent_buffer(gang[0]->commit_root);
2086b0feb9d9SMiao Xie 			btrfs_put_fs_root(gang[0]);
2087171f6537SJosef Bacik 		}
2088171f6537SJosef Bacik 	}
2089171f6537SJosef Bacik 
2090171f6537SJosef Bacik 	while (1) {
2091171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2092171f6537SJosef Bacik 					     (void **)gang, 0,
2093171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2094171f6537SJosef Bacik 		if (!ret)
2095171f6537SJosef Bacik 			break;
2096171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2097cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2098171f6537SJosef Bacik 	}
20991a4319ccSLiu Bo 
21001a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
21011a4319ccSLiu Bo 		btrfs_free_log_root_tree(NULL, fs_info);
21022ff7e61eSJeff Mahoney 		btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
21031a4319ccSLiu Bo 	}
2104171f6537SJosef Bacik }
2105af31f5e5SChris Mason 
2106638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2107638aa7edSEric Sandeen {
2108638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2109638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2110638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2111638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2112638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2113638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2114638aa7edSEric Sandeen 	fs_info->scrub_workers_refcnt = 0;
2115638aa7edSEric Sandeen }
2116638aa7edSEric Sandeen 
2117779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2118779a65a4SEric Sandeen {
2119779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2120779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2121779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2122779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2123779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2124779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2125779a65a4SEric Sandeen }
2126779a65a4SEric Sandeen 
21276bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2128f37938e0SEric Sandeen {
21292ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
21302ff7e61eSJeff Mahoney 
21312ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
21322ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2133f37938e0SEric Sandeen 	/*
2134f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2135f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2136f37938e0SEric Sandeen 	 * the devices in the system
2137f37938e0SEric Sandeen 	 */
21382ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
21392ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2140f37938e0SEric Sandeen 
21412ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2142c6100a4bSJosef Bacik 	extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
21432ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.track_uptodate = 0;
21442ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2145f37938e0SEric Sandeen 
21462ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2147f37938e0SEric Sandeen 
21482ff7e61eSJeff Mahoney 	BTRFS_I(inode)->root = fs_info->tree_root;
21492ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
21502ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
21512ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2152f37938e0SEric Sandeen }
2153f37938e0SEric Sandeen 
2154ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2155ad618368SEric Sandeen {
2156ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
215773beece9SLiu Bo 	rwlock_init(&fs_info->dev_replace.lock);
215873beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.read_locks, 0);
215973beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.blocking_readers, 0);
2160ad618368SEric Sandeen 	init_waitqueue_head(&fs_info->replace_wait);
216173beece9SLiu Bo 	init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
2162ad618368SEric Sandeen }
2163ad618368SEric Sandeen 
2164f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2165f9e92e40SEric Sandeen {
2166f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2167f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2168f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2169f9e92e40SEric Sandeen 	fs_info->qgroup_op_tree = RB_ROOT;
2170f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2171f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2172f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2173d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2174f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2175f9e92e40SEric Sandeen }
2176f9e92e40SEric Sandeen 
21772a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
21782a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
21792a458198SEric Sandeen {
2180f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21816f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21822a458198SEric Sandeen 
21832a458198SEric Sandeen 	fs_info->workers =
2184cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2185cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21862a458198SEric Sandeen 
21872a458198SEric Sandeen 	fs_info->delalloc_workers =
2188cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2189cb001095SJeff Mahoney 				      flags, max_active, 2);
21902a458198SEric Sandeen 
21912a458198SEric Sandeen 	fs_info->flush_workers =
2192cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2193cb001095SJeff Mahoney 				      flags, max_active, 0);
21942a458198SEric Sandeen 
21952a458198SEric Sandeen 	fs_info->caching_workers =
2196cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21972a458198SEric Sandeen 
21982a458198SEric Sandeen 	/*
21992a458198SEric Sandeen 	 * a higher idle thresh on the submit workers makes it much more
22002a458198SEric Sandeen 	 * likely that bios will be send down in a sane order to the
22012a458198SEric Sandeen 	 * devices
22022a458198SEric Sandeen 	 */
22032a458198SEric Sandeen 	fs_info->submit_workers =
2204cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "submit", flags,
22052a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
22062a458198SEric Sandeen 					    max_active), 64);
22072a458198SEric Sandeen 
22082a458198SEric Sandeen 	fs_info->fixup_workers =
2209cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
22102a458198SEric Sandeen 
22112a458198SEric Sandeen 	/*
22122a458198SEric Sandeen 	 * endios are largely parallel and should have a very
22132a458198SEric Sandeen 	 * low idle thresh
22142a458198SEric Sandeen 	 */
22152a458198SEric Sandeen 	fs_info->endio_workers =
2216cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
22172a458198SEric Sandeen 	fs_info->endio_meta_workers =
2218cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2219cb001095SJeff Mahoney 				      max_active, 4);
22202a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2221cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2222cb001095SJeff Mahoney 				      max_active, 2);
22232a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2224cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2225cb001095SJeff Mahoney 				      max_active, 4);
22262a458198SEric Sandeen 	fs_info->endio_repair_workers =
2227cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
22282a458198SEric Sandeen 	fs_info->rmw_workers =
2229cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
22302a458198SEric Sandeen 	fs_info->endio_write_workers =
2231cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2232cb001095SJeff Mahoney 				      max_active, 2);
22332a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2234cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2235cb001095SJeff Mahoney 				      max_active, 0);
22362a458198SEric Sandeen 	fs_info->delayed_workers =
2237cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2238cb001095SJeff Mahoney 				      max_active, 0);
22392a458198SEric Sandeen 	fs_info->readahead_workers =
2240cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2241cb001095SJeff Mahoney 				      max_active, 2);
22422a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2243cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
22442a458198SEric Sandeen 	fs_info->extent_workers =
2245cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
22462a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
22472a458198SEric Sandeen 					    max_active), 8);
22482a458198SEric Sandeen 
22492a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
22502a458198SEric Sandeen 	      fs_info->submit_workers && fs_info->flush_workers &&
22512a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
22522a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
22532a458198SEric Sandeen 	      fs_info->endio_repair_workers &&
22542a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
22552a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
22562a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
22572a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
22582a458198SEric Sandeen 	      fs_info->extent_workers &&
22592a458198SEric Sandeen 	      fs_info->qgroup_rescan_workers)) {
22602a458198SEric Sandeen 		return -ENOMEM;
22612a458198SEric Sandeen 	}
22622a458198SEric Sandeen 
22632a458198SEric Sandeen 	return 0;
22642a458198SEric Sandeen }
22652a458198SEric Sandeen 
226663443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
226763443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
226863443bf5SEric Sandeen {
226963443bf5SEric Sandeen 	int ret;
227063443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
227163443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
227263443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2273581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
227463443bf5SEric Sandeen 
227563443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2276f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
227763443bf5SEric Sandeen 		return -EIO;
227863443bf5SEric Sandeen 	}
227963443bf5SEric Sandeen 
228074e4d827SDavid Sterba 	log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
228163443bf5SEric Sandeen 	if (!log_tree_root)
228263443bf5SEric Sandeen 		return -ENOMEM;
228363443bf5SEric Sandeen 
2284da17066cSJeff Mahoney 	__setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
228563443bf5SEric Sandeen 
22862ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
2287581c1760SQu Wenruo 					      fs_info->generation + 1,
2288581c1760SQu Wenruo 					      level, NULL);
228964c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2290f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22910eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
229264c043deSLiu Bo 		kfree(log_tree_root);
22930eeff236SLiu Bo 		return ret;
229464c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2295f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
229663443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
229763443bf5SEric Sandeen 		kfree(log_tree_root);
229863443bf5SEric Sandeen 		return -EIO;
229963443bf5SEric Sandeen 	}
230063443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
230163443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
230263443bf5SEric Sandeen 	if (ret) {
23030b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
230463443bf5SEric Sandeen 				      "Failed to recover log tree");
230563443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
230663443bf5SEric Sandeen 		kfree(log_tree_root);
230763443bf5SEric Sandeen 		return ret;
230863443bf5SEric Sandeen 	}
230963443bf5SEric Sandeen 
2310bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
23116bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
231263443bf5SEric Sandeen 		if (ret)
231363443bf5SEric Sandeen 			return ret;
231463443bf5SEric Sandeen 	}
231563443bf5SEric Sandeen 
231663443bf5SEric Sandeen 	return 0;
231763443bf5SEric Sandeen }
231863443bf5SEric Sandeen 
23196bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
23204bbcaa64SEric Sandeen {
23216bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2322a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
23234bbcaa64SEric Sandeen 	struct btrfs_key location;
23244bbcaa64SEric Sandeen 	int ret;
23254bbcaa64SEric Sandeen 
23266bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
23276bccf3abSJeff Mahoney 
23284bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
23294bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
23304bbcaa64SEric Sandeen 	location.offset = 0;
23314bbcaa64SEric Sandeen 
2332a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2333f50f4353SLiu Bo 	if (IS_ERR(root)) {
2334f50f4353SLiu Bo 		ret = PTR_ERR(root);
2335f50f4353SLiu Bo 		goto out;
2336f50f4353SLiu Bo 	}
2337a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2338a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
23394bbcaa64SEric Sandeen 
23404bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2341a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2342f50f4353SLiu Bo 	if (IS_ERR(root)) {
2343f50f4353SLiu Bo 		ret = PTR_ERR(root);
2344f50f4353SLiu Bo 		goto out;
2345f50f4353SLiu Bo 	}
2346a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2347a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
23484bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
23494bbcaa64SEric Sandeen 
23504bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2351a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2352f50f4353SLiu Bo 	if (IS_ERR(root)) {
2353f50f4353SLiu Bo 		ret = PTR_ERR(root);
2354f50f4353SLiu Bo 		goto out;
2355f50f4353SLiu Bo 	}
2356a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2357a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
23584bbcaa64SEric Sandeen 
23594bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2360a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2361a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2362a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2363afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2364a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
23654bbcaa64SEric Sandeen 	}
23664bbcaa64SEric Sandeen 
23674bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2368a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2369a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2370a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
23714bbcaa64SEric Sandeen 		if (ret != -ENOENT)
2372f50f4353SLiu Bo 			goto out;
23734bbcaa64SEric Sandeen 	} else {
2374a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2375a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
23764bbcaa64SEric Sandeen 	}
23774bbcaa64SEric Sandeen 
237870f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
237970f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
238070f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2381f50f4353SLiu Bo 		if (IS_ERR(root)) {
2382f50f4353SLiu Bo 			ret = PTR_ERR(root);
2383f50f4353SLiu Bo 			goto out;
2384f50f4353SLiu Bo 		}
238570f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
238670f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
238770f6d82eSOmar Sandoval 	}
238870f6d82eSOmar Sandoval 
23894bbcaa64SEric Sandeen 	return 0;
2390f50f4353SLiu Bo out:
2391f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2392f50f4353SLiu Bo 		   location.objectid, ret);
2393f50f4353SLiu Bo 	return ret;
23944bbcaa64SEric Sandeen }
23954bbcaa64SEric Sandeen 
2396069ec957SQu Wenruo /*
2397069ec957SQu Wenruo  * Real super block validation
2398069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2399069ec957SQu Wenruo  *
2400069ec957SQu Wenruo  * @sb:		super block to check
2401069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2402069ec957SQu Wenruo  * 		0	the primary (1st) sb
2403069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2404069ec957SQu Wenruo  * 	       -1	skip bytenr check
2405069ec957SQu Wenruo  */
2406069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2407069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
240821a852b0SQu Wenruo {
240921a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
241021a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
241121a852b0SQu Wenruo 	int ret = 0;
241221a852b0SQu Wenruo 
241321a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
241421a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
241521a852b0SQu Wenruo 		ret = -EINVAL;
241621a852b0SQu Wenruo 	}
241721a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
241821a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
241921a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
242021a852b0SQu Wenruo 		ret = -EINVAL;
242121a852b0SQu Wenruo 	}
242221a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
242321a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
242421a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
242521a852b0SQu Wenruo 		ret = -EINVAL;
242621a852b0SQu Wenruo 	}
242721a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
242821a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
242921a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
243021a852b0SQu Wenruo 		ret = -EINVAL;
243121a852b0SQu Wenruo 	}
243221a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
243321a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
243421a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
243521a852b0SQu Wenruo 		ret = -EINVAL;
243621a852b0SQu Wenruo 	}
243721a852b0SQu Wenruo 
243821a852b0SQu Wenruo 	/*
243921a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
244021a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
244121a852b0SQu Wenruo 	 */
244221a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
244321a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
244421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
244521a852b0SQu Wenruo 		ret = -EINVAL;
244621a852b0SQu Wenruo 	}
244721a852b0SQu Wenruo 	/* Only PAGE SIZE is supported yet */
244821a852b0SQu Wenruo 	if (sectorsize != PAGE_SIZE) {
244921a852b0SQu Wenruo 		btrfs_err(fs_info,
245021a852b0SQu Wenruo 			"sectorsize %llu not supported yet, only support %lu",
245121a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
245221a852b0SQu Wenruo 		ret = -EINVAL;
245321a852b0SQu Wenruo 	}
245421a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
245521a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
245621a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
245721a852b0SQu Wenruo 		ret = -EINVAL;
245821a852b0SQu Wenruo 	}
245921a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
246021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
246121a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
246221a852b0SQu Wenruo 		ret = -EINVAL;
246321a852b0SQu Wenruo 	}
246421a852b0SQu Wenruo 
246521a852b0SQu Wenruo 	/* Root alignment check */
246621a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
246721a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
246821a852b0SQu Wenruo 			   btrfs_super_root(sb));
246921a852b0SQu Wenruo 		ret = -EINVAL;
247021a852b0SQu Wenruo 	}
247121a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
247221a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
247321a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
247421a852b0SQu Wenruo 		ret = -EINVAL;
247521a852b0SQu Wenruo 	}
247621a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
247721a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
247821a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
247921a852b0SQu Wenruo 		ret = -EINVAL;
248021a852b0SQu Wenruo 	}
248121a852b0SQu Wenruo 
248221a852b0SQu Wenruo 	if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_FSID_SIZE) != 0) {
248321a852b0SQu Wenruo 		btrfs_err(fs_info,
248421a852b0SQu Wenruo 			   "dev_item UUID does not match fsid: %pU != %pU",
248521a852b0SQu Wenruo 			   fs_info->fsid, sb->dev_item.fsid);
248621a852b0SQu Wenruo 		ret = -EINVAL;
248721a852b0SQu Wenruo 	}
248821a852b0SQu Wenruo 
248921a852b0SQu Wenruo 	/*
249021a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
249121a852b0SQu Wenruo 	 * done later
249221a852b0SQu Wenruo 	 */
249321a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
249421a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
249521a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
249621a852b0SQu Wenruo 		ret = -EINVAL;
249721a852b0SQu Wenruo 	}
249821a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
249921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
250021a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
250121a852b0SQu Wenruo 		ret = -EINVAL;
250221a852b0SQu Wenruo 	}
250321a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
250421a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
250521a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
250621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
250721a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
250821a852b0SQu Wenruo 		ret = -EINVAL;
250921a852b0SQu Wenruo 	}
251021a852b0SQu Wenruo 
2511069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2512069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
251321a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
251421a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
251521a852b0SQu Wenruo 		ret = -EINVAL;
251621a852b0SQu Wenruo 	}
251721a852b0SQu Wenruo 
251821a852b0SQu Wenruo 	/*
251921a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
252021a852b0SQu Wenruo 	 * and one chunk
252121a852b0SQu Wenruo 	 */
252221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
252321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
252421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
252521a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
252621a852b0SQu Wenruo 		ret = -EINVAL;
252721a852b0SQu Wenruo 	}
252821a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
252921a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
253021a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
253121a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
253221a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
253321a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
253421a852b0SQu Wenruo 		ret = -EINVAL;
253521a852b0SQu Wenruo 	}
253621a852b0SQu Wenruo 
253721a852b0SQu Wenruo 	/*
253821a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
253921a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
254021a852b0SQu Wenruo 	 */
254121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
254221a852b0SQu Wenruo 		btrfs_warn(fs_info,
254321a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
254421a852b0SQu Wenruo 			btrfs_super_generation(sb),
254521a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
254621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
254721a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
254821a852b0SQu Wenruo 		btrfs_warn(fs_info,
254921a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
255021a852b0SQu Wenruo 			btrfs_super_generation(sb),
255121a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
255221a852b0SQu Wenruo 
255321a852b0SQu Wenruo 	return ret;
255421a852b0SQu Wenruo }
255521a852b0SQu Wenruo 
2556069ec957SQu Wenruo /*
2557069ec957SQu Wenruo  * Validation of super block at mount time.
2558069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2559069ec957SQu Wenruo  * flags will be skipped.
2560069ec957SQu Wenruo  */
2561069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2562069ec957SQu Wenruo {
2563069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2564069ec957SQu Wenruo }
2565069ec957SQu Wenruo 
256675cb857dSQu Wenruo /*
256775cb857dSQu Wenruo  * Validation of super block at write time.
256875cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
256975cb857dSQu Wenruo  * overwritten soon.
257075cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
257175cb857dSQu Wenruo  */
257275cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
257375cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
257475cb857dSQu Wenruo {
257575cb857dSQu Wenruo 	int ret;
257675cb857dSQu Wenruo 
257775cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
257875cb857dSQu Wenruo 	if (ret < 0)
257975cb857dSQu Wenruo 		goto out;
258075cb857dSQu Wenruo 	if (btrfs_super_csum_type(sb) != BTRFS_CSUM_TYPE_CRC32) {
258175cb857dSQu Wenruo 		ret = -EUCLEAN;
258275cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
258375cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
258475cb857dSQu Wenruo 		goto out;
258575cb857dSQu Wenruo 	}
258675cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
258775cb857dSQu Wenruo 		ret = -EUCLEAN;
258875cb857dSQu Wenruo 		btrfs_err(fs_info,
258975cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
259075cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
259175cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
259275cb857dSQu Wenruo 		goto out;
259375cb857dSQu Wenruo 	}
259475cb857dSQu Wenruo out:
259575cb857dSQu Wenruo 	if (ret < 0)
259675cb857dSQu Wenruo 		btrfs_err(fs_info,
259775cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
259875cb857dSQu Wenruo 	return ret;
259975cb857dSQu Wenruo }
260075cb857dSQu Wenruo 
2601ad2b2c80SAl Viro int open_ctree(struct super_block *sb,
2602dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
2603dfe25020SChris Mason 	       char *options)
2604eb60ceacSChris Mason {
2605db94535dSChris Mason 	u32 sectorsize;
2606db94535dSChris Mason 	u32 nodesize;
260787ee04ebSChris Mason 	u32 stripesize;
260884234f3aSYan Zheng 	u64 generation;
2609f2b636e8SJosef Bacik 	u64 features;
26103de4586cSChris Mason 	struct btrfs_key location;
2611a061fc8dSChris Mason 	struct buffer_head *bh;
26124d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
2613815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2614f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
26154d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
2616eb60ceacSChris Mason 	int ret;
2617e58ca020SYan 	int err = -EINVAL;
2618af31f5e5SChris Mason 	int num_backups_tried = 0;
2619af31f5e5SChris Mason 	int backup_index = 0;
26206675df31SOmar Sandoval 	int clear_free_space_tree = 0;
2621581c1760SQu Wenruo 	int level;
26224543df7eSChris Mason 
262374e4d827SDavid Sterba 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
262474e4d827SDavid Sterba 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2625cb517eabSMiao Xie 	if (!tree_root || !chunk_root) {
262639279cc3SChris Mason 		err = -ENOMEM;
262739279cc3SChris Mason 		goto fail;
262839279cc3SChris Mason 	}
262976dda93cSYan, Zheng 
263076dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
263176dda93cSYan, Zheng 	if (ret) {
263276dda93cSYan, Zheng 		err = ret;
263376dda93cSYan, Zheng 		goto fail;
263476dda93cSYan, Zheng 	}
263576dda93cSYan, Zheng 
2636908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2637e2d84521SMiao Xie 	if (ret) {
2638e2d84521SMiao Xie 		err = ret;
26399e11ceeeSJan Kara 		goto fail_srcu;
2640e2d84521SMiao Xie 	}
264109cbfeafSKirill A. Shutemov 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2642e2d84521SMiao Xie 					(1 + ilog2(nr_cpu_ids));
2643e2d84521SMiao Xie 
2644908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2645963d678bSMiao Xie 	if (ret) {
2646963d678bSMiao Xie 		err = ret;
2647963d678bSMiao Xie 		goto fail_dirty_metadata_bytes;
2648963d678bSMiao Xie 	}
2649963d678bSMiao Xie 
2650908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2651c404e0dcSMiao Xie 	if (ret) {
2652c404e0dcSMiao Xie 		err = ret;
2653c404e0dcSMiao Xie 		goto fail_delalloc_bytes;
2654c404e0dcSMiao Xie 	}
2655c404e0dcSMiao Xie 
265676dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2657f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26588fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2659facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
266024bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2661eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
266211833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
266375cb379dSJeff Mahoney 	INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
266475cb379dSJeff Mahoney 	spin_lock_init(&fs_info->pending_raid_kobjs_lock);
2665eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2666a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
266776dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
266824bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26694cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2670f29021b2SJan Schmidt 	spin_lock_init(&fs_info->tree_mod_seq_lock);
2671ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2672fcebe456SJosef Bacik 	spin_lock_init(&fs_info->qgroup_op_lock);
2673f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
267447ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2675f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2676d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
267767c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
26787585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2679573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2680c2d6cb16SFilipe Manana 	mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2681de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
268219c00ddcSChris Mason 
26830b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
26846324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2685f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
268647ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
26870b86a832SChris Mason 	btrfs_mapping_init(&fs_info->mapping_tree);
268866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
268966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
269066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
269166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
269266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
269366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
269466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2695771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
26964cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2697fcebe456SJosef Bacik 	atomic_set(&fs_info->qgroup_op_seq, 0);
26982fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2699fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2700e20d96d6SChris Mason 	fs_info->sb = sb;
270195ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27029ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27034cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2704a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2705f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27068b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2707f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
270890519d66SArne Jansen 	/* readahead state */
2709d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
271090519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2711fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2712c8b97818SChris Mason 
2713b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2714b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27150afbaf8cSChris Mason 
2716199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2717199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
271869fe2d75SJosef Bacik 
271969fe2d75SJosef Bacik 	fs_info->btree_inode = new_inode(sb);
272069fe2d75SJosef Bacik 	if (!fs_info->btree_inode) {
272169fe2d75SJosef Bacik 		err = -ENOMEM;
272269fe2d75SJosef Bacik 		goto fail_bio_counter;
272369fe2d75SJosef Bacik 	}
272469fe2d75SJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
272569fe2d75SJosef Bacik 
272616cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
272774e4d827SDavid Sterba 					GFP_KERNEL);
272816cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
272916cdcec7SMiao Xie 		err = -ENOMEM;
273016cdcec7SMiao Xie 		goto fail_iput;
273116cdcec7SMiao Xie 	}
273216cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
27333eaa2885SChris Mason 
2734638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
273521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
273621adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
273721adbd5cSStefan Behrens #endif
2738779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
273921c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2740a2de733cSArne Jansen 
27419f6d2510SDavid Sterba 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
27429f6d2510SDavid Sterba 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2743a061fc8dSChris Mason 
27446bccf3abSJeff Mahoney 	btrfs_init_btree_inode(fs_info);
274539279cc3SChris Mason 
2746e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
27476bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2748a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
2749925baeddSChris Mason 
2750c6100a4bSJosef Bacik 	extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2751c6100a4bSJosef Bacik 	extent_io_tree_init(&fs_info->freed_extents[1], NULL);
275211833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2753afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2754509659cdSChris Mason 
27555a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
275679154b1bSChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2757925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2758a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2759a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27601bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27619e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2762c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
276376dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2764803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2765fa9c0d79SChris Mason 
2766ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2767f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2768416ac51dSArne Jansen 
2769fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2770fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2771fa9c0d79SChris Mason 
2772e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2773f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2774bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27754854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
27763768f368SChris Mason 
277704216820SFilipe Manana 	INIT_LIST_HEAD(&fs_info->pinned_chunks);
277804216820SFilipe Manana 
2779da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2780da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2781da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2782da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2783da17066cSJeff Mahoney 
278453b381b3SDavid Woodhouse 	ret = btrfs_alloc_stripe_hash_table(fs_info);
278553b381b3SDavid Woodhouse 	if (ret) {
278683c8266aSDavid Sterba 		err = ret;
278753b381b3SDavid Woodhouse 		goto fail_alloc;
278853b381b3SDavid Woodhouse 	}
278953b381b3SDavid Woodhouse 
2790da17066cSJeff Mahoney 	__setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
27917eccb903SChris Mason 
27923c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
27931104a885SDavid Sterba 
27941104a885SDavid Sterba 	/*
27951104a885SDavid Sterba 	 * Read super block and check the signature bytes only
27961104a885SDavid Sterba 	 */
2797a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
279892fc03fbSAnand Jain 	if (IS_ERR(bh)) {
279992fc03fbSAnand Jain 		err = PTR_ERR(bh);
280016cdcec7SMiao Xie 		goto fail_alloc;
280120b45077SDave Young 	}
280239279cc3SChris Mason 
28031104a885SDavid Sterba 	/*
28041104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
28051104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
28061104a885SDavid Sterba 	 */
2807ab8d0fc4SJeff Mahoney 	if (btrfs_check_super_csum(fs_info, bh->b_data)) {
280805135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
28091104a885SDavid Sterba 		err = -EINVAL;
2810b2acdddfSAnand Jain 		brelse(bh);
28111104a885SDavid Sterba 		goto fail_alloc;
28121104a885SDavid Sterba 	}
28131104a885SDavid Sterba 
28141104a885SDavid Sterba 	/*
28151104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
28161104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
28171104a885SDavid Sterba 	 * the whole block of INFO_SIZE
28181104a885SDavid Sterba 	 */
28196c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
28206c41761fSDavid Sterba 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
28216c41761fSDavid Sterba 	       sizeof(*fs_info->super_for_commit));
2822a061fc8dSChris Mason 	brelse(bh);
28235f39d397SChris Mason 
28246c41761fSDavid Sterba 	memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
28250b86a832SChris Mason 
2826069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
28271104a885SDavid Sterba 	if (ret) {
282805135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
28291104a885SDavid Sterba 		err = -EINVAL;
28301104a885SDavid Sterba 		goto fail_alloc;
28311104a885SDavid Sterba 	}
28321104a885SDavid Sterba 
28336c41761fSDavid Sterba 	disk_super = fs_info->super_copy;
28340f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
283516cdcec7SMiao Xie 		goto fail_alloc;
28360f7d52f4SChris Mason 
2837acce952bSliubo 	/* check FS state, whether FS is broken. */
283887533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
283987533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2840acce952bSliubo 
284175e7cb7fSLiu Bo 	/*
2842af31f5e5SChris Mason 	 * run through our array of backup supers and setup
2843af31f5e5SChris Mason 	 * our ring pointer to the oldest one
2844af31f5e5SChris Mason 	 */
2845af31f5e5SChris Mason 	generation = btrfs_super_generation(disk_super);
2846af31f5e5SChris Mason 	find_oldest_super_backup(fs_info, generation);
2847af31f5e5SChris Mason 
2848af31f5e5SChris Mason 	/*
284975e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
285075e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
285175e7cb7fSLiu Bo 	 */
285275e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
285375e7cb7fSLiu Bo 
28542ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
28552b82032cSYan Zheng 	if (ret) {
28562b82032cSYan Zheng 		err = ret;
285716cdcec7SMiao Xie 		goto fail_alloc;
28582b82032cSYan Zheng 	}
2859dfe25020SChris Mason 
2860f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2861f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2862f2b636e8SJosef Bacik 	if (features) {
286305135f59SDavid Sterba 		btrfs_err(fs_info,
286405135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
2865c1c9ff7cSGeert Uytterhoeven 		    features);
2866f2b636e8SJosef Bacik 		err = -EINVAL;
286716cdcec7SMiao Xie 		goto fail_alloc;
2868f2b636e8SJosef Bacik 	}
2869f2b636e8SJosef Bacik 
28705d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
28715d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
28720b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2873a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
28745c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
28755c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2876727011e0SChris Mason 
28773173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
287805135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
28793173a18fSJosef Bacik 
2880727011e0SChris Mason 	/*
2881727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2882727011e0SChris Mason 	 * they are bigger than the page size
2883727011e0SChris Mason 	 */
288409cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2885727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
288605135f59SDavid Sterba 			btrfs_info(fs_info,
288705135f59SDavid Sterba 				"flagging fs with big metadata feature");
2888727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2889727011e0SChris Mason 	}
2890727011e0SChris Mason 
2891bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2892bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2893b7f67055SChandan Rajendra 	stripesize = sectorsize;
2894707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2895963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2896bc3f116fSChris Mason 
2897da17066cSJeff Mahoney 	/* Cache block sizes */
2898da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
2899da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
2900da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
2901da17066cSJeff Mahoney 
2902bc3f116fSChris Mason 	/*
2903bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2904bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2905bc3f116fSChris Mason 	 */
2906bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2907707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
290805135f59SDavid Sterba 		btrfs_err(fs_info,
290905135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
291005135f59SDavid Sterba 			nodesize, sectorsize);
2911bc3f116fSChris Mason 		goto fail_alloc;
2912bc3f116fSChris Mason 	}
2913bc3f116fSChris Mason 
2914ceda0864SMiao Xie 	/*
2915ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
2916ceda0864SMiao Xie 	 * update the flag.
2917ceda0864SMiao Xie 	 */
29185d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
29195d4f98a2SYan Zheng 
2920f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2921f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2922bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
292305135f59SDavid Sterba 		btrfs_err(fs_info,
292405135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
2925c1c9ff7cSGeert Uytterhoeven 		       features);
2926f2b636e8SJosef Bacik 		err = -EINVAL;
292716cdcec7SMiao Xie 		goto fail_alloc;
2928f2b636e8SJosef Bacik 	}
292961d92c32SChris Mason 
29302a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
29312a458198SEric Sandeen 	if (ret) {
29322a458198SEric Sandeen 		err = ret;
29330dc3b84aSJosef Bacik 		goto fail_sb_buffer;
29340dc3b84aSJosef Bacik 	}
29354543df7eSChris Mason 
29369e11ceeeSJan Kara 	sb->s_bdi->congested_fn = btrfs_congested_fn;
29379e11ceeeSJan Kara 	sb->s_bdi->congested_data = fs_info;
29389e11ceeeSJan Kara 	sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2939d4417e22SNikolay Borisov 	sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
29409e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
29419e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
29424575c9ccSChris Mason 
2943a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
2944a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
2945ee87cf5eSAnand Jain 	memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
2946db94535dSChris Mason 
2947925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
29486bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
2949925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
295084eed90fSChris Mason 	if (ret) {
295105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
29525d4f98a2SYan Zheng 		goto fail_sb_buffer;
295384eed90fSChris Mason 	}
29540b86a832SChris Mason 
295584234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
2956581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
29570b86a832SChris Mason 
2958da17066cSJeff Mahoney 	__setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
29590b86a832SChris Mason 
29602ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
29610b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
2962581c1760SQu Wenruo 					   generation, level, NULL);
296364c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
296464c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
296505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
2966e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
2967e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
296895ab1f64SZhao Lei 		chunk_root->node = NULL;
2969af31f5e5SChris Mason 		goto fail_tree_roots;
297083121942SDavid Woodhouse 	}
29715d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
29725d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
29730b86a832SChris Mason 
2974e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2975b308bc2fSGeert Uytterhoeven 	   btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2976e17cade2SChris Mason 
29775b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
29782b82032cSYan Zheng 	if (ret) {
297905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
2980af31f5e5SChris Mason 		goto fail_tree_roots;
29812b82032cSYan Zheng 	}
29820b86a832SChris Mason 
29838dabb742SStefan Behrens 	/*
29849b99b115SAnand Jain 	 * Keep the devid that is marked to be the target device for the
29859b99b115SAnand Jain 	 * device replace procedure
29868dabb742SStefan Behrens 	 */
29879b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 0);
2988dfe25020SChris Mason 
2989a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
299005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
2991a6b0d5c8SChris Mason 		goto fail_tree_roots;
2992a6b0d5c8SChris Mason 	}
2993a6b0d5c8SChris Mason 
2994af31f5e5SChris Mason retry_root_backup:
299584234f3aSYan Zheng 	generation = btrfs_super_generation(disk_super);
2996581c1760SQu Wenruo 	level = btrfs_super_root_level(disk_super);
29970b86a832SChris Mason 
29982ff7e61eSJeff Mahoney 	tree_root->node = read_tree_block(fs_info,
2999db94535dSChris Mason 					  btrfs_super_root(disk_super),
3000581c1760SQu Wenruo 					  generation, level, NULL);
300164c043deSLiu Bo 	if (IS_ERR(tree_root->node) ||
300264c043deSLiu Bo 	    !extent_buffer_uptodate(tree_root->node)) {
300305135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to read tree root");
3004e5fffbacSchandan 		if (!IS_ERR(tree_root->node))
3005e5fffbacSchandan 			free_extent_buffer(tree_root->node);
300695ab1f64SZhao Lei 		tree_root->node = NULL;
3007af31f5e5SChris Mason 		goto recovery_tree_root;
300883121942SDavid Woodhouse 	}
3009af31f5e5SChris Mason 
30105d4f98a2SYan Zheng 	btrfs_set_root_node(&tree_root->root_item, tree_root->node);
30115d4f98a2SYan Zheng 	tree_root->commit_root = btrfs_root_node(tree_root);
301269e9c6c6SStefan Behrens 	btrfs_set_root_refs(&tree_root->root_item, 1);
3013db94535dSChris Mason 
3014f32e48e9SChandan Rajendra 	mutex_lock(&tree_root->objectid_mutex);
3015f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(tree_root,
3016f32e48e9SChandan Rajendra 					&tree_root->highest_objectid);
3017f32e48e9SChandan Rajendra 	if (ret) {
3018f32e48e9SChandan Rajendra 		mutex_unlock(&tree_root->objectid_mutex);
3019f32e48e9SChandan Rajendra 		goto recovery_tree_root;
3020f32e48e9SChandan Rajendra 	}
3021f32e48e9SChandan Rajendra 
3022f32e48e9SChandan Rajendra 	ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
3023f32e48e9SChandan Rajendra 
3024f32e48e9SChandan Rajendra 	mutex_unlock(&tree_root->objectid_mutex);
3025f32e48e9SChandan Rajendra 
30266bccf3abSJeff Mahoney 	ret = btrfs_read_roots(fs_info);
30274bbcaa64SEric Sandeen 	if (ret)
3028af31f5e5SChris Mason 		goto recovery_tree_root;
3029f7a81ea4SStefan Behrens 
30308929ecfaSYan, Zheng 	fs_info->generation = generation;
30318929ecfaSYan, Zheng 	fs_info->last_trans_committed = generation;
30328929ecfaSYan, Zheng 
303368310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
303468310a5eSIlya Dryomov 	if (ret) {
303505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
303668310a5eSIlya Dryomov 		goto fail_block_groups;
303768310a5eSIlya Dryomov 	}
303868310a5eSIlya Dryomov 
3039733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3040733f4fbbSStefan Behrens 	if (ret) {
304105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3042733f4fbbSStefan Behrens 		goto fail_block_groups;
3043733f4fbbSStefan Behrens 	}
3044733f4fbbSStefan Behrens 
30458dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
30468dabb742SStefan Behrens 	if (ret) {
304705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
30488dabb742SStefan Behrens 		goto fail_block_groups;
30498dabb742SStefan Behrens 	}
30508dabb742SStefan Behrens 
30519b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 1);
30528dabb742SStefan Behrens 
3053b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3054b7c35e81SAnand Jain 	if (ret) {
305505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
305605135f59SDavid Sterba 				ret);
3057b7c35e81SAnand Jain 		goto fail_block_groups;
3058b7c35e81SAnand Jain 	}
3059b7c35e81SAnand Jain 
3060b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_device(fs_devices);
3061b7c35e81SAnand Jain 	if (ret) {
306205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs device interface: %d",
306305135f59SDavid Sterba 				ret);
3064b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
3065b7c35e81SAnand Jain 	}
3066b7c35e81SAnand Jain 
306796f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
30685ac1d209SJeff Mahoney 	if (ret) {
306905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3070b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
30715ac1d209SJeff Mahoney 	}
30725ac1d209SJeff Mahoney 
3073c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3074c59021f8Sliubo 	if (ret) {
307505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
30762365dd3cSAnand Jain 		goto fail_sysfs;
3077c59021f8Sliubo 	}
3078c59021f8Sliubo 
30795b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
30801b1d1f66SJosef Bacik 	if (ret) {
308105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
30822365dd3cSAnand Jain 		goto fail_sysfs;
30831b1d1f66SJosef Bacik 	}
30844330e183SQu Wenruo 
30856528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
308605135f59SDavid Sterba 		btrfs_warn(fs_info,
30874330e183SQu Wenruo 		"writeable mount is not allowed due to too many missing devices");
30882365dd3cSAnand Jain 		goto fail_sysfs;
3089292fd7fcSStefan Behrens 	}
30909078a3e1SChris Mason 
3091a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3092a74a4b97SChris Mason 					       "btrfs-cleaner");
309357506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
30942365dd3cSAnand Jain 		goto fail_sysfs;
3095a74a4b97SChris Mason 
3096a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3097a74a4b97SChris Mason 						   tree_root,
3098a74a4b97SChris Mason 						   "btrfs-transaction");
309957506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
31003f157a2fSChris Mason 		goto fail_cleaner;
3101a74a4b97SChris Mason 
3102583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3103c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3104583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3105c289811cSChris Mason 	}
3106c289811cSChris Mason 
3107572d9ab7SDavid Sterba 	/*
310801327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3109572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3110572d9ab7SDavid Sterba 	 */
3111572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
31123818aea2SQu Wenruo 
311321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
31140b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
31152ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
31160b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
311721adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
311821adbd5cSStefan Behrens 				    1 : 0,
311921adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
312021adbd5cSStefan Behrens 		if (ret)
312105135f59SDavid Sterba 			btrfs_warn(fs_info,
312205135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
312305135f59SDavid Sterba 				ret);
312421adbd5cSStefan Behrens 	}
312521adbd5cSStefan Behrens #endif
3126bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3127bcef60f2SArne Jansen 	if (ret)
3128bcef60f2SArne Jansen 		goto fail_trans_kthread;
312921adbd5cSStefan Behrens 
3130fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3131fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3132fd708b81SJosef Bacik 
313396da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
313496da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
31350b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
313663443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
313779787eaaSJeff Mahoney 		if (ret) {
313863443bf5SEric Sandeen 			err = ret;
313928c16cbbSWang Shilong 			goto fail_qgroup;
3140e556ce2cSYan Zheng 		}
3141e02119d5SChris Mason 	}
31421a40e23bSZheng Yan 
31436bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
314479787eaaSJeff Mahoney 	if (ret)
314528c16cbbSWang Shilong 		goto fail_qgroup;
314676dda93cSYan, Zheng 
3147bc98a42cSDavid Howells 	if (!sb_rdonly(sb)) {
3148d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
314944c44af2SIlya Dryomov 		if (ret)
315028c16cbbSWang Shilong 			goto fail_qgroup;
315190c711abSZygo Blaxell 
315290c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
31535d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
315490c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
3155d7ce5843SMiao Xie 		if (ret < 0) {
315605135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
315705135f59SDavid Sterba 					ret);
3158d7ce5843SMiao Xie 			err = -EINVAL;
3159bcef60f2SArne Jansen 			goto fail_qgroup;
3160d7ce5843SMiao Xie 		}
31617c2ca468SChris Mason 	}
31621a40e23bSZheng Yan 
31633de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
31643de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
3165cb517eabSMiao Xie 	location.offset = 0;
31663de4586cSChris Mason 
31673de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
31683140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
31693140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3170f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3171bcef60f2SArne Jansen 		goto fail_qgroup;
31723140c9a3SDan Carpenter 	}
3173c289811cSChris Mason 
3174bc98a42cSDavid Howells 	if (sb_rdonly(sb))
31752b6ba629SIlya Dryomov 		return 0;
31762b6ba629SIlya Dryomov 
3177f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3178f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31796675df31SOmar Sandoval 		clear_free_space_tree = 1;
31806675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
31816675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
31826675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
31836675df31SOmar Sandoval 		clear_free_space_tree = 1;
31846675df31SOmar Sandoval 	}
31856675df31SOmar Sandoval 
31866675df31SOmar Sandoval 	if (clear_free_space_tree) {
3187f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3188f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3189f8d468a1SOmar Sandoval 		if (ret) {
3190f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3191f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
31926bccf3abSJeff Mahoney 			close_ctree(fs_info);
3193f8d468a1SOmar Sandoval 			return ret;
3194f8d468a1SOmar Sandoval 		}
3195f8d468a1SOmar Sandoval 	}
3196f8d468a1SOmar Sandoval 
31970b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3198511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
319905135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3200511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3201511711afSChris Mason 		if (ret) {
320205135f59SDavid Sterba 			btrfs_warn(fs_info,
320305135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
32046bccf3abSJeff Mahoney 			close_ctree(fs_info);
3205511711afSChris Mason 			return ret;
3206511711afSChris Mason 		}
3207511711afSChris Mason 	}
3208511711afSChris Mason 
3209e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
32102b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
32112b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
32122b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
32136bccf3abSJeff Mahoney 		close_ctree(fs_info);
32142b6ba629SIlya Dryomov 		return ret;
32152b6ba629SIlya Dryomov 	}
3216e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
321759641015SIlya Dryomov 
32182b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
32192b6ba629SIlya Dryomov 	if (ret) {
322005135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
32216bccf3abSJeff Mahoney 		close_ctree(fs_info);
32222b6ba629SIlya Dryomov 		return ret;
3223e3acc2a6SJosef Bacik 	}
3224e3acc2a6SJosef Bacik 
32258dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
32268dabb742SStefan Behrens 	if (ret) {
322705135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
32286bccf3abSJeff Mahoney 		close_ctree(fs_info);
32298dabb742SStefan Behrens 		return ret;
32308dabb742SStefan Behrens 	}
32318dabb742SStefan Behrens 
3232b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3233b382a324SJan Schmidt 
32344bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
323505135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3236f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3237f7a81ea4SStefan Behrens 		if (ret) {
323805135f59SDavid Sterba 			btrfs_warn(fs_info,
323905135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
32406bccf3abSJeff Mahoney 			close_ctree(fs_info);
3241f7a81ea4SStefan Behrens 			return ret;
3242f7a81ea4SStefan Behrens 		}
32430b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
32444bbcaa64SEric Sandeen 		   fs_info->generation !=
32454bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
324605135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
324770f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
324870f80175SStefan Behrens 		if (ret) {
324905135f59SDavid Sterba 			btrfs_warn(fs_info,
325005135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
32516bccf3abSJeff Mahoney 			close_ctree(fs_info);
325270f80175SStefan Behrens 			return ret;
325370f80175SStefan Behrens 		}
325470f80175SStefan Behrens 	} else {
3255afcdd129SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3256f7a81ea4SStefan Behrens 	}
3257afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
325847ab2a6cSJosef Bacik 
32598dcddfa0SQu Wenruo 	/*
32608dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
32618dcddfa0SQu Wenruo 	 * no need to keep the flag
32628dcddfa0SQu Wenruo 	 */
32638dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
32648dcddfa0SQu Wenruo 
3265ad2b2c80SAl Viro 	return 0;
326639279cc3SChris Mason 
3267bcef60f2SArne Jansen fail_qgroup:
3268bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
32697c2ca468SChris Mason fail_trans_kthread:
32707c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
32712ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3272faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
32733f157a2fSChris Mason fail_cleaner:
3274a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
32757c2ca468SChris Mason 
32767c2ca468SChris Mason 	/*
32777c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
32787c2ca468SChris Mason 	 * kthreads
32797c2ca468SChris Mason 	 */
32807c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
32817c2ca468SChris Mason 
32822365dd3cSAnand Jain fail_sysfs:
32836618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
32842365dd3cSAnand Jain 
3285b7c35e81SAnand Jain fail_fsdev_sysfs:
3286b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3287b7c35e81SAnand Jain 
32881b1d1f66SJosef Bacik fail_block_groups:
328954067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3290af31f5e5SChris Mason 
3291af31f5e5SChris Mason fail_tree_roots:
3292af31f5e5SChris Mason 	free_root_pointers(fs_info, 1);
32932b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3294af31f5e5SChris Mason 
329539279cc3SChris Mason fail_sb_buffer:
32967abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
32975cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
329816cdcec7SMiao Xie fail_alloc:
32994543df7eSChris Mason fail_iput:
3300586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3301586e46e2SIlya Dryomov 
33024543df7eSChris Mason 	iput(fs_info->btree_inode);
3303c404e0dcSMiao Xie fail_bio_counter:
3304c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
3305963d678bSMiao Xie fail_delalloc_bytes:
3306963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3307e2d84521SMiao Xie fail_dirty_metadata_bytes:
3308e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
330976dda93cSYan, Zheng fail_srcu:
331076dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
33117e662854SQinghuang Feng fail:
331253b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3313586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3314ad2b2c80SAl Viro 	return err;
3315af31f5e5SChris Mason 
3316af31f5e5SChris Mason recovery_tree_root:
33170b246afaSJeff Mahoney 	if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3318af31f5e5SChris Mason 		goto fail_tree_roots;
3319af31f5e5SChris Mason 
3320af31f5e5SChris Mason 	free_root_pointers(fs_info, 0);
3321af31f5e5SChris Mason 
3322af31f5e5SChris Mason 	/* don't use the log in recovery mode, it won't be valid */
3323af31f5e5SChris Mason 	btrfs_set_super_log_root(disk_super, 0);
3324af31f5e5SChris Mason 
3325af31f5e5SChris Mason 	/* we can't trust the free space cache either */
3326af31f5e5SChris Mason 	btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3327af31f5e5SChris Mason 
3328af31f5e5SChris Mason 	ret = next_root_backup(fs_info, fs_info->super_copy,
3329af31f5e5SChris Mason 			       &num_backups_tried, &backup_index);
3330af31f5e5SChris Mason 	if (ret == -1)
3331af31f5e5SChris Mason 		goto fail_block_groups;
3332af31f5e5SChris Mason 	goto retry_root_backup;
3333eb60ceacSChris Mason }
3334663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3335eb60ceacSChris Mason 
3336f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3337f2984462SChris Mason {
3338f2984462SChris Mason 	if (uptodate) {
3339f2984462SChris Mason 		set_buffer_uptodate(bh);
3340f2984462SChris Mason 	} else {
3341442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
3342442a4f63SStefan Behrens 			bh->b_private;
3343442a4f63SStefan Behrens 
3344fb456252SJeff Mahoney 		btrfs_warn_rl_in_rcu(device->fs_info,
3345b14af3b4SDavid Sterba 				"lost page write due to IO error on %s",
3346606686eeSJosef Bacik 					  rcu_str_deref(device->name));
334701327610SNicholas D Steeves 		/* note, we don't set_buffer_write_io_error because we have
33481259ab75SChris Mason 		 * our own ways of dealing with the IO errors
33491259ab75SChris Mason 		 */
3350f2984462SChris Mason 		clear_buffer_uptodate(bh);
3351442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3352f2984462SChris Mason 	}
3353f2984462SChris Mason 	unlock_buffer(bh);
3354f2984462SChris Mason 	put_bh(bh);
3355f2984462SChris Mason }
3356f2984462SChris Mason 
335729c36d72SAnand Jain int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
335829c36d72SAnand Jain 			struct buffer_head **bh_ret)
335929c36d72SAnand Jain {
336029c36d72SAnand Jain 	struct buffer_head *bh;
336129c36d72SAnand Jain 	struct btrfs_super_block *super;
336229c36d72SAnand Jain 	u64 bytenr;
336329c36d72SAnand Jain 
336429c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
336529c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
336629c36d72SAnand Jain 		return -EINVAL;
336729c36d72SAnand Jain 
33689f6d2510SDavid Sterba 	bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
336929c36d72SAnand Jain 	/*
337029c36d72SAnand Jain 	 * If we fail to read from the underlying devices, as of now
337129c36d72SAnand Jain 	 * the best option we have is to mark it EIO.
337229c36d72SAnand Jain 	 */
337329c36d72SAnand Jain 	if (!bh)
337429c36d72SAnand Jain 		return -EIO;
337529c36d72SAnand Jain 
337629c36d72SAnand Jain 	super = (struct btrfs_super_block *)bh->b_data;
337729c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
337829c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
337929c36d72SAnand Jain 		brelse(bh);
338029c36d72SAnand Jain 		return -EINVAL;
338129c36d72SAnand Jain 	}
338229c36d72SAnand Jain 
338329c36d72SAnand Jain 	*bh_ret = bh;
338429c36d72SAnand Jain 	return 0;
338529c36d72SAnand Jain }
338629c36d72SAnand Jain 
338729c36d72SAnand Jain 
3388a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3389a512bbf8SYan Zheng {
3390a512bbf8SYan Zheng 	struct buffer_head *bh;
3391a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
3392a512bbf8SYan Zheng 	struct btrfs_super_block *super;
3393a512bbf8SYan Zheng 	int i;
3394a512bbf8SYan Zheng 	u64 transid = 0;
339592fc03fbSAnand Jain 	int ret = -EINVAL;
3396a512bbf8SYan Zheng 
3397a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3398a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3399a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3400a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3401a512bbf8SYan Zheng 	 */
3402a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
340329c36d72SAnand Jain 		ret = btrfs_read_dev_one_super(bdev, i, &bh);
340429c36d72SAnand Jain 		if (ret)
3405a512bbf8SYan Zheng 			continue;
3406a512bbf8SYan Zheng 
3407a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
3408a512bbf8SYan Zheng 
3409a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
3410a512bbf8SYan Zheng 			brelse(latest);
3411a512bbf8SYan Zheng 			latest = bh;
3412a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3413a512bbf8SYan Zheng 		} else {
3414a512bbf8SYan Zheng 			brelse(bh);
3415a512bbf8SYan Zheng 		}
3416a512bbf8SYan Zheng 	}
341792fc03fbSAnand Jain 
341892fc03fbSAnand Jain 	if (!latest)
341992fc03fbSAnand Jain 		return ERR_PTR(ret);
342092fc03fbSAnand Jain 
3421a512bbf8SYan Zheng 	return latest;
3422a512bbf8SYan Zheng }
3423a512bbf8SYan Zheng 
34244eedeb75SHisashi Hifumi /*
3425abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3426abbb3b8eSDavid Sterba  * buffer heads we write are pinned.
34274eedeb75SHisashi Hifumi  *
3428abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3429abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3430abbb3b8eSDavid Sterba  * same for write and wait phases.
34314eedeb75SHisashi Hifumi  *
3432abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or submission fails.
34334eedeb75SHisashi Hifumi  */
3434a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3435abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3436a512bbf8SYan Zheng {
3437a512bbf8SYan Zheng 	struct buffer_head *bh;
3438a512bbf8SYan Zheng 	int i;
3439a512bbf8SYan Zheng 	int ret;
3440a512bbf8SYan Zheng 	int errors = 0;
3441a512bbf8SYan Zheng 	u32 crc;
3442a512bbf8SYan Zheng 	u64 bytenr;
34431b9e619cSOmar Sandoval 	int op_flags;
3444a512bbf8SYan Zheng 
3445a512bbf8SYan Zheng 	if (max_mirrors == 0)
3446a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3447a512bbf8SYan Zheng 
3448a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3449a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3450935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3451935e5cc9SMiao Xie 		    device->commit_total_bytes)
3452a512bbf8SYan Zheng 			break;
3453a512bbf8SYan Zheng 
3454a512bbf8SYan Zheng 		btrfs_set_super_bytenr(sb, bytenr);
3455a512bbf8SYan Zheng 
3456a512bbf8SYan Zheng 		crc = ~(u32)0;
3457abbb3b8eSDavid Sterba 		crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3458abbb3b8eSDavid Sterba 				      BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3459a512bbf8SYan Zheng 		btrfs_csum_final(crc, sb->csum);
3460a512bbf8SYan Zheng 
3461abbb3b8eSDavid Sterba 		/* One reference for us, and we leave it for the caller */
34629f6d2510SDavid Sterba 		bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3463a512bbf8SYan Zheng 			      BTRFS_SUPER_INFO_SIZE);
3464634554dcSJosef Bacik 		if (!bh) {
3465fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3466f14d104dSDavid Sterba 			    "couldn't get super buffer head for bytenr %llu",
3467f14d104dSDavid Sterba 			    bytenr);
3468634554dcSJosef Bacik 			errors++;
3469634554dcSJosef Bacik 			continue;
3470634554dcSJosef Bacik 		}
3471634554dcSJosef Bacik 
3472a512bbf8SYan Zheng 		memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3473a512bbf8SYan Zheng 
34744eedeb75SHisashi Hifumi 		/* one reference for submit_bh */
3475a512bbf8SYan Zheng 		get_bh(bh);
34764eedeb75SHisashi Hifumi 
34774eedeb75SHisashi Hifumi 		set_buffer_uptodate(bh);
3478a512bbf8SYan Zheng 		lock_buffer(bh);
3479a512bbf8SYan Zheng 		bh->b_end_io = btrfs_end_buffer_write_sync;
3480442a4f63SStefan Behrens 		bh->b_private = device;
3481a512bbf8SYan Zheng 
3482387125fcSChris Mason 		/*
3483387125fcSChris Mason 		 * we fua the first super.  The others we allow
3484387125fcSChris Mason 		 * to go down lazy.
3485387125fcSChris Mason 		 */
34861b9e619cSOmar Sandoval 		op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
34871b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
34881b9e619cSOmar Sandoval 			op_flags |= REQ_FUA;
34891b9e619cSOmar Sandoval 		ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
34904eedeb75SHisashi Hifumi 		if (ret)
3491a512bbf8SYan Zheng 			errors++;
3492a512bbf8SYan Zheng 	}
3493a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3494a512bbf8SYan Zheng }
3495a512bbf8SYan Zheng 
3496387125fcSChris Mason /*
3497abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3498abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3499abbb3b8eSDavid Sterba  *
3500abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or not marked up to
3501abbb3b8eSDavid Sterba  * date.
3502abbb3b8eSDavid Sterba  */
3503abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3504abbb3b8eSDavid Sterba {
3505abbb3b8eSDavid Sterba 	struct buffer_head *bh;
3506abbb3b8eSDavid Sterba 	int i;
3507abbb3b8eSDavid Sterba 	int errors = 0;
3508b6a535faSHoward McLauchlan 	bool primary_failed = false;
3509abbb3b8eSDavid Sterba 	u64 bytenr;
3510abbb3b8eSDavid Sterba 
3511abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3512abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3513abbb3b8eSDavid Sterba 
3514abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3515abbb3b8eSDavid Sterba 		bytenr = btrfs_sb_offset(i);
3516abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3517abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3518abbb3b8eSDavid Sterba 			break;
3519abbb3b8eSDavid Sterba 
35209f6d2510SDavid Sterba 		bh = __find_get_block(device->bdev,
35219f6d2510SDavid Sterba 				      bytenr / BTRFS_BDEV_BLOCKSIZE,
3522abbb3b8eSDavid Sterba 				      BTRFS_SUPER_INFO_SIZE);
3523abbb3b8eSDavid Sterba 		if (!bh) {
3524abbb3b8eSDavid Sterba 			errors++;
3525b6a535faSHoward McLauchlan 			if (i == 0)
3526b6a535faSHoward McLauchlan 				primary_failed = true;
3527abbb3b8eSDavid Sterba 			continue;
3528abbb3b8eSDavid Sterba 		}
3529abbb3b8eSDavid Sterba 		wait_on_buffer(bh);
3530b6a535faSHoward McLauchlan 		if (!buffer_uptodate(bh)) {
3531abbb3b8eSDavid Sterba 			errors++;
3532b6a535faSHoward McLauchlan 			if (i == 0)
3533b6a535faSHoward McLauchlan 				primary_failed = true;
3534b6a535faSHoward McLauchlan 		}
3535abbb3b8eSDavid Sterba 
3536abbb3b8eSDavid Sterba 		/* drop our reference */
3537abbb3b8eSDavid Sterba 		brelse(bh);
3538abbb3b8eSDavid Sterba 
3539abbb3b8eSDavid Sterba 		/* drop the reference from the writing run */
3540abbb3b8eSDavid Sterba 		brelse(bh);
3541abbb3b8eSDavid Sterba 	}
3542abbb3b8eSDavid Sterba 
3543b6a535faSHoward McLauchlan 	/* log error, force error return */
3544b6a535faSHoward McLauchlan 	if (primary_failed) {
3545b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3546b6a535faSHoward McLauchlan 			  device->devid);
3547b6a535faSHoward McLauchlan 		return -1;
3548b6a535faSHoward McLauchlan 	}
3549b6a535faSHoward McLauchlan 
3550abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3551abbb3b8eSDavid Sterba }
3552abbb3b8eSDavid Sterba 
3553abbb3b8eSDavid Sterba /*
3554387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3555387125fcSChris Mason  * for the barrier when it is done
3556387125fcSChris Mason  */
35574246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3558387125fcSChris Mason {
3559387125fcSChris Mason 	complete(bio->bi_private);
3560387125fcSChris Mason }
3561387125fcSChris Mason 
3562387125fcSChris Mason /*
35634fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
35644fc6441aSAnand Jain  * done in the waiting counterpart.
3565387125fcSChris Mason  */
35664fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3567387125fcSChris Mason {
3568c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3569e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3570387125fcSChris Mason 
3571c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
35724fc6441aSAnand Jain 		return;
3573387125fcSChris Mason 
3574e0ae9994SDavid Sterba 	bio_reset(bio);
3575387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
357674d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
35778d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3578387125fcSChris Mason 	init_completion(&device->flush_wait);
3579387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3580387125fcSChris Mason 
358143a01111SLu Fengqi 	btrfsic_submit_bio(bio);
35821c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
35834fc6441aSAnand Jain }
3584387125fcSChris Mason 
35854fc6441aSAnand Jain /*
35864fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
35874fc6441aSAnand Jain  */
35888c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
35894fc6441aSAnand Jain {
35904fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
35914fc6441aSAnand Jain 
35921c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
359358efbc9fSOmar Sandoval 		return BLK_STS_OK;
35944fc6441aSAnand Jain 
35951c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
35962980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
35974fc6441aSAnand Jain 
35988c27cb35SLinus Torvalds 	return bio->bi_status;
3599387125fcSChris Mason }
3600387125fcSChris Mason 
3601d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3602401b41e5SAnand Jain {
36036528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3604401b41e5SAnand Jain 		return -EIO;
3605387125fcSChris Mason 	return 0;
3606387125fcSChris Mason }
3607387125fcSChris Mason 
3608387125fcSChris Mason /*
3609387125fcSChris Mason  * send an empty flush down to each device in parallel,
3610387125fcSChris Mason  * then wait for them
3611387125fcSChris Mason  */
3612387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3613387125fcSChris Mason {
3614387125fcSChris Mason 	struct list_head *head;
3615387125fcSChris Mason 	struct btrfs_device *dev;
36165af3e8ccSStefan Behrens 	int errors_wait = 0;
36174e4cbee9SChristoph Hellwig 	blk_status_t ret;
3618387125fcSChris Mason 
36191538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3620387125fcSChris Mason 	/* send down all the barriers */
3621387125fcSChris Mason 	head = &info->fs_devices->devices;
36221538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3623e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3624f88ba6a2SHidetoshi Seto 			continue;
3625cea7c8bfSAnand Jain 		if (!dev->bdev)
3626387125fcSChris Mason 			continue;
3627e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3628ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3629387125fcSChris Mason 			continue;
3630387125fcSChris Mason 
36314fc6441aSAnand Jain 		write_dev_flush(dev);
363258efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3633387125fcSChris Mason 	}
3634387125fcSChris Mason 
3635387125fcSChris Mason 	/* wait for all the barriers */
36361538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3637e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3638f88ba6a2SHidetoshi Seto 			continue;
3639387125fcSChris Mason 		if (!dev->bdev) {
36405af3e8ccSStefan Behrens 			errors_wait++;
3641387125fcSChris Mason 			continue;
3642387125fcSChris Mason 		}
3643e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3644ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3645387125fcSChris Mason 			continue;
3646387125fcSChris Mason 
36474fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3648401b41e5SAnand Jain 		if (ret) {
3649401b41e5SAnand Jain 			dev->last_flush_error = ret;
365066b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
365166b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
36525af3e8ccSStefan Behrens 			errors_wait++;
3653387125fcSChris Mason 		}
3654401b41e5SAnand Jain 	}
3655401b41e5SAnand Jain 
3656cea7c8bfSAnand Jain 	if (errors_wait) {
3657401b41e5SAnand Jain 		/*
3658401b41e5SAnand Jain 		 * At some point we need the status of all disks
3659401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3660401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3661401b41e5SAnand Jain 		 */
3662d10b82feSQu Wenruo 		return check_barrier_error(info);
3663401b41e5SAnand Jain 	}
3664387125fcSChris Mason 	return 0;
3665387125fcSChris Mason }
3666387125fcSChris Mason 
3667943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3668943c6e99SZhao Lei {
36698789f4feSZhao Lei 	int raid_type;
36708789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3671943c6e99SZhao Lei 
36728789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
36738789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
36748789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
36758789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
36768789f4feSZhao Lei 				    tolerated_failures);
3677943c6e99SZhao Lei 
36788789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
36798789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
36808789f4feSZhao Lei 			continue;
368141a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
36828789f4feSZhao Lei 			continue;
36838789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
36848789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
36858789f4feSZhao Lei 				    tolerated_failures);
36868789f4feSZhao Lei 	}
3687943c6e99SZhao Lei 
36888789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3689ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
36908789f4feSZhao Lei 		min_tolerated = 0;
36918789f4feSZhao Lei 	}
36928789f4feSZhao Lei 
36938789f4feSZhao Lei 	return min_tolerated;
3694943c6e99SZhao Lei }
3695943c6e99SZhao Lei 
3696eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3697f2984462SChris Mason {
3698e5e9a520SChris Mason 	struct list_head *head;
3699f2984462SChris Mason 	struct btrfs_device *dev;
3700a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3701f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3702f2984462SChris Mason 	int ret;
3703f2984462SChris Mason 	int do_barriers;
3704a236aed1SChris Mason 	int max_errors;
3705a236aed1SChris Mason 	int total_errors = 0;
3706a061fc8dSChris Mason 	u64 flags;
3707f2984462SChris Mason 
37080b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3709fed3b381SLiu Bo 
3710fed3b381SLiu Bo 	/*
3711fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3712fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3713fed3b381SLiu Bo 	 * been consistent on disk.
3714fed3b381SLiu Bo 	 */
3715fed3b381SLiu Bo 	if (max_mirrors == 0)
37160b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3717f2984462SChris Mason 
37180b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3719a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3720e5e9a520SChris Mason 
37210b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
37220b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
37230b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3724387125fcSChris Mason 
37255af3e8ccSStefan Behrens 	if (do_barriers) {
37260b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
37275af3e8ccSStefan Behrens 		if (ret) {
37285af3e8ccSStefan Behrens 			mutex_unlock(
37290b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
37300b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
37315af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
37325af3e8ccSStefan Behrens 			return ret;
37335af3e8ccSStefan Behrens 		}
37345af3e8ccSStefan Behrens 	}
3735387125fcSChris Mason 
37361538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3737dfe25020SChris Mason 		if (!dev->bdev) {
3738dfe25020SChris Mason 			total_errors++;
3739dfe25020SChris Mason 			continue;
3740dfe25020SChris Mason 		}
3741e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3742ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3743dfe25020SChris Mason 			continue;
3744dfe25020SChris Mason 
37452b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3746a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3747a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
37487df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3749935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3750ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3751ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3752a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3753a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3754a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3755a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
375644880fdcSAnand Jain 		memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_FSID_SIZE);
3757a512bbf8SYan Zheng 
3758a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3759a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3760f2984462SChris Mason 
376175cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
376275cb857dSQu Wenruo 		if (ret < 0) {
376375cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
376475cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
376575cb857dSQu Wenruo 				"unexpected superblock corruption detected");
376675cb857dSQu Wenruo 			return -EUCLEAN;
376775cb857dSQu Wenruo 		}
376875cb857dSQu Wenruo 
3769abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3770a236aed1SChris Mason 		if (ret)
3771a236aed1SChris Mason 			total_errors++;
3772f2984462SChris Mason 	}
3773a236aed1SChris Mason 	if (total_errors > max_errors) {
37740b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3775d397712bSChris Mason 			  total_errors);
37760b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
377779787eaaSJeff Mahoney 
37789d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
37790b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
37800b246afaSJeff Mahoney 				      "%d errors while writing supers",
37810b246afaSJeff Mahoney 				      total_errors);
37829d565ba4SStefan Behrens 		return -EIO;
3783a236aed1SChris Mason 	}
3784f2984462SChris Mason 
3785a512bbf8SYan Zheng 	total_errors = 0;
37861538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3787dfe25020SChris Mason 		if (!dev->bdev)
3788dfe25020SChris Mason 			continue;
3789e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3790ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3791dfe25020SChris Mason 			continue;
3792dfe25020SChris Mason 
3793abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3794a512bbf8SYan Zheng 		if (ret)
37951259ab75SChris Mason 			total_errors++;
3796f2984462SChris Mason 	}
37970b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3798a236aed1SChris Mason 	if (total_errors > max_errors) {
37990b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
38000b246afaSJeff Mahoney 				      "%d errors while writing supers",
38010b246afaSJeff Mahoney 				      total_errors);
380279787eaaSJeff Mahoney 		return -EIO;
3803a236aed1SChris Mason 	}
3804f2984462SChris Mason 	return 0;
3805f2984462SChris Mason }
3806f2984462SChris Mason 
3807cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3808cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3809cb517eabSMiao Xie 				  struct btrfs_root *root)
38102619ba1fSChris Mason {
38114df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
38122619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
38132619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
38144df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
381576dda93cSYan, Zheng 
381676dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
381776dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
381876dda93cSYan, Zheng 
38191c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
38203321719eSLiu Bo 		btrfs_free_log(NULL, root);
38211c1ea4f7SLiu Bo 		if (root->reloc_root) {
38221c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->node);
38231c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->commit_root);
38241c1ea4f7SLiu Bo 			btrfs_put_fs_root(root->reloc_root);
38251c1ea4f7SLiu Bo 			root->reloc_root = NULL;
38261c1ea4f7SLiu Bo 		}
38271c1ea4f7SLiu Bo 	}
38283321719eSLiu Bo 
3829faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3830581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3831faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3832581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
383384db5ccfSDavid Sterba 	btrfs_free_fs_root(root);
38344df27c4dSYan, Zheng }
38354df27c4dSYan, Zheng 
383684db5ccfSDavid Sterba void btrfs_free_fs_root(struct btrfs_root *root)
38374df27c4dSYan, Zheng {
383857cdc8dbSDavid Sterba 	iput(root->ino_cache_inode);
38394df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
38400ee5dc67SAl Viro 	if (root->anon_dev)
38410ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
38428257b2dcSMiao Xie 	if (root->subv_writers)
38438257b2dcSMiao Xie 		btrfs_free_subvolume_writers(root->subv_writers);
38445f39d397SChris Mason 	free_extent_buffer(root->node);
38455f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3846581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3847581bb050SLi Zefan 	kfree(root->free_ino_pinned);
3848b0feb9d9SMiao Xie 	btrfs_put_fs_root(root);
38492619ba1fSChris Mason }
38502619ba1fSChris Mason 
3851c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3852c146afadSYan Zheng {
3853c146afadSYan Zheng 	u64 root_objectid = 0;
3854c146afadSYan Zheng 	struct btrfs_root *gang[8];
385565d33fd7SQu Wenruo 	int i = 0;
385665d33fd7SQu Wenruo 	int err = 0;
385765d33fd7SQu Wenruo 	unsigned int ret = 0;
385865d33fd7SQu Wenruo 	int index;
3859c146afadSYan Zheng 
3860c146afadSYan Zheng 	while (1) {
386165d33fd7SQu Wenruo 		index = srcu_read_lock(&fs_info->subvol_srcu);
3862c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3863c146afadSYan Zheng 					     (void **)gang, root_objectid,
3864c146afadSYan Zheng 					     ARRAY_SIZE(gang));
386565d33fd7SQu Wenruo 		if (!ret) {
386665d33fd7SQu Wenruo 			srcu_read_unlock(&fs_info->subvol_srcu, index);
3867c146afadSYan Zheng 			break;
386865d33fd7SQu Wenruo 		}
38695d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
387066b4ffd1SJosef Bacik 
387165d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
387265d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
387365d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
387465d33fd7SQu Wenruo 				gang[i] = NULL;
387565d33fd7SQu Wenruo 				continue;
387665d33fd7SQu Wenruo 			}
387765d33fd7SQu Wenruo 			/* grab all the search result for later use */
387865d33fd7SQu Wenruo 			gang[i] = btrfs_grab_fs_root(gang[i]);
387965d33fd7SQu Wenruo 		}
388065d33fd7SQu Wenruo 		srcu_read_unlock(&fs_info->subvol_srcu, index);
388165d33fd7SQu Wenruo 
388265d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
388365d33fd7SQu Wenruo 			if (!gang[i])
388465d33fd7SQu Wenruo 				continue;
3885c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
388666b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
388766b4ffd1SJosef Bacik 			if (err)
388865d33fd7SQu Wenruo 				break;
388965d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
3890c146afadSYan Zheng 		}
3891c146afadSYan Zheng 		root_objectid++;
3892c146afadSYan Zheng 	}
389365d33fd7SQu Wenruo 
389465d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
389565d33fd7SQu Wenruo 	for (; i < ret; i++) {
389665d33fd7SQu Wenruo 		if (gang[i])
389765d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
389865d33fd7SQu Wenruo 	}
389965d33fd7SQu Wenruo 	return err;
3900c146afadSYan Zheng }
3901c146afadSYan Zheng 
39026bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3903c146afadSYan Zheng {
39046bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3905c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3906c146afadSYan Zheng 
39070b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
39082ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
39090b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
39100b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
3911c71bf099SYan, Zheng 
3912c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
39130b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
39140b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
3915c71bf099SYan, Zheng 
39167a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
39173612b495STsutomu Itoh 	if (IS_ERR(trans))
39183612b495STsutomu Itoh 		return PTR_ERR(trans);
39193a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
3920c146afadSYan Zheng }
3921c146afadSYan Zheng 
39226bccf3abSJeff Mahoney void close_ctree(struct btrfs_fs_info *fs_info)
3923eb60ceacSChris Mason {
3924c146afadSYan Zheng 	int ret;
3925e089f05cSChris Mason 
3926afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3927a2135011SChris Mason 
39287343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
3929d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
39307343dd61SJustin Maggard 
3931803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3932803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3933803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3934803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3935803b2f54SStefan Behrens 
3936837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3937aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3938837d5b6eSIlya Dryomov 
39398dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
39408dabb742SStefan Behrens 
3941aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
39424cb5300bSChris Mason 
39434cb5300bSChris Mason 	/* wait for any defraggers to finish */
39444cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
39454cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
39464cb5300bSChris Mason 
39474cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
394826176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
39494cb5300bSChris Mason 
395021c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
395121c7e756SMiao Xie 
3952bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
3953e44163e1SJeff Mahoney 		/*
3954e44163e1SJeff Mahoney 		 * If the cleaner thread is stopped and there are
3955e44163e1SJeff Mahoney 		 * block groups queued for removal, the deletion will be
3956e44163e1SJeff Mahoney 		 * skipped when we quit the cleaner thread.
3957e44163e1SJeff Mahoney 		 */
39580b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
3959e44163e1SJeff Mahoney 
39606bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
3961d397712bSChris Mason 		if (ret)
396204892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
3963c146afadSYan Zheng 	}
3964ed2ff2cbSChris Mason 
3965af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
3966af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
39672ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
3968acce952bSliubo 
3969e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
3970e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
39718929ecfaSYan, Zheng 
3972afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
3973f25784b3SYan Zheng 
397404892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
3975fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
3976bcef60f2SArne Jansen 
3977963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
397804892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
3979963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
3980b0c68f8bSChris Mason 	}
398131153d81SYan Zheng 
39826618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
3983b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
39845ac1d209SJeff Mahoney 
3985faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
3986d10c5f31SChris Mason 
39871a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
39881a4319ccSLiu Bo 
3989de348ee0SWang Shilong 	/*
3990de348ee0SWang Shilong 	 * we must make sure there is not any read request to
3991de348ee0SWang Shilong 	 * submit after we stopping all workers.
3992de348ee0SWang Shilong 	 */
3993de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
399496192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
399596192499SJosef Bacik 
39965cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
39975cdd7db6SFilipe Manana 
3998afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
399913e6c37bSJosef Bacik 	free_root_pointers(fs_info, 1);
40009ad6b7bcSChris Mason 
400113e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4002d6bfde87SChris Mason 
400321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
40040b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
40052ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
400621adbd5cSStefan Behrens #endif
400721adbd5cSStefan Behrens 
4008dfe25020SChris Mason 	btrfs_close_devices(fs_info->fs_devices);
40090b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
4010b248a415SChris Mason 
4011e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
4012963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
4013c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
401476dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
40150b86a832SChris Mason 
401653b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
4017fd708b81SJosef Bacik 	btrfs_free_ref_cache(fs_info);
401853b381b3SDavid Woodhouse 
401904216820SFilipe Manana 	while (!list_empty(&fs_info->pinned_chunks)) {
402004216820SFilipe Manana 		struct extent_map *em;
402104216820SFilipe Manana 
402204216820SFilipe Manana 		em = list_first_entry(&fs_info->pinned_chunks,
402304216820SFilipe Manana 				      struct extent_map, list);
402404216820SFilipe Manana 		list_del_init(&em->list);
402504216820SFilipe Manana 		free_extent_map(em);
402604216820SFilipe Manana 	}
4027eb60ceacSChris Mason }
4028eb60ceacSChris Mason 
4029b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4030b9fab919SChris Mason 			  int atomic)
4031ccd467d6SChris Mason {
40321259ab75SChris Mason 	int ret;
4033727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
40341259ab75SChris Mason 
40350b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
40361259ab75SChris Mason 	if (!ret)
40371259ab75SChris Mason 		return ret;
40381259ab75SChris Mason 
40391259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4040b9fab919SChris Mason 				    parent_transid, atomic);
4041b9fab919SChris Mason 	if (ret == -EAGAIN)
4042b9fab919SChris Mason 		return ret;
40431259ab75SChris Mason 	return !ret;
40445f39d397SChris Mason }
40456702ed49SChris Mason 
40465f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
40475f39d397SChris Mason {
40480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
404906ea65a3SJosef Bacik 	struct btrfs_root *root;
40505f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4051b9473439SChris Mason 	int was_dirty;
4052b4ce94deSChris Mason 
405306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
405406ea65a3SJosef Bacik 	/*
405506ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
4056b0132a3bSNikolay Borisov 	 * enabled.  Normal people shouldn't be using umapped buffers as dirty
405706ea65a3SJosef Bacik 	 * outside of the sanity tests.
405806ea65a3SJosef Bacik 	 */
4059b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
406006ea65a3SJosef Bacik 		return;
406106ea65a3SJosef Bacik #endif
406206ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
40630b246afaSJeff Mahoney 	fs_info = root->fs_info;
4064b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
40650b246afaSJeff Mahoney 	if (transid != fs_info->generation)
40665d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
40670b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
40680b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4069e2d84521SMiao Xie 	if (!was_dirty)
4070104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4071e2d84521SMiao Xie 					 buf->len,
40720b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
40731f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
407469fc6cbbSQu Wenruo 	/*
407569fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
407669fc6cbbSQu Wenruo 	 * but item data not updated.
407769fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
407869fc6cbbSQu Wenruo 	 */
407969fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
40802f659546SQu Wenruo 	    btrfs_check_leaf_relaxed(fs_info, buf)) {
4081a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
40821f21ef0aSFilipe Manana 		ASSERT(0);
40831f21ef0aSFilipe Manana 	}
40841f21ef0aSFilipe Manana #endif
4085eb60ceacSChris Mason }
4086eb60ceacSChris Mason 
40872ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4088b53d3f5dSLiu Bo 					int flush_delayed)
408935b7e476SChris Mason {
4090188de649SChris Mason 	/*
4091188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4092188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4093188de649SChris Mason 	 */
4094e2d84521SMiao Xie 	int ret;
4095d6bfde87SChris Mason 
40966933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4097d6bfde87SChris Mason 		return;
4098d6bfde87SChris Mason 
4099b53d3f5dSLiu Bo 	if (flush_delayed)
41002ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
410116cdcec7SMiao Xie 
4102d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4103d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4104d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4105e2d84521SMiao Xie 	if (ret > 0) {
41060b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
410716cdcec7SMiao Xie 	}
410816cdcec7SMiao Xie }
410916cdcec7SMiao Xie 
41102ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
411116cdcec7SMiao Xie {
41122ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
411335b7e476SChris Mason }
4114b53d3f5dSLiu Bo 
41152ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4116b53d3f5dSLiu Bo {
41172ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4118d6bfde87SChris Mason }
41196b80053dSChris Mason 
4120581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4121581c1760SQu Wenruo 		      struct btrfs_key *first_key)
41226b80053dSChris Mason {
4123727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
41242ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41252ff7e61eSJeff Mahoney 
4126581c1760SQu Wenruo 	return btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
4127581c1760SQu Wenruo 					      level, first_key);
41286b80053dSChris Mason }
41290da5468fSChris Mason 
41302ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4131acce952bSliubo {
4132fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4133fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4134fe816d0fSNikolay Borisov 
41350b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41362ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41370b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4138acce952bSliubo 
41390b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41400b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4141acce952bSliubo }
4142acce952bSliubo 
4143143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4144acce952bSliubo {
4145acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4146acce952bSliubo 
4147199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4148779880efSJosef Bacik 	/*
4149779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4150779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4151779880efSJosef Bacik 	 */
4152199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4153779880efSJosef Bacik 			    root_extent_list)
4154779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4155199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4156199c2a9cSMiao Xie }
4157199c2a9cSMiao Xie 
4158199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4159199c2a9cSMiao Xie {
4160199c2a9cSMiao Xie 	struct btrfs_root *root;
4161199c2a9cSMiao Xie 	struct list_head splice;
4162199c2a9cSMiao Xie 
4163199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4164199c2a9cSMiao Xie 
4165199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4166199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4167199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4168199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4169199c2a9cSMiao Xie 					ordered_root);
41701de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
41711de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4172199c2a9cSMiao Xie 
41732a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4174199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4175199c2a9cSMiao Xie 
41762a85d9caSLiu Bo 		cond_resched();
41772a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4178199c2a9cSMiao Xie 	}
4179199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
4180acce952bSliubo }
4181acce952bSliubo 
418235a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
41832ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4184acce952bSliubo {
4185acce952bSliubo 	struct rb_node *node;
4186acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4187acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4188acce952bSliubo 	int ret = 0;
4189acce952bSliubo 
4190acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4191acce952bSliubo 
4192acce952bSliubo 	spin_lock(&delayed_refs->lock);
4193d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4194cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
41950b246afaSJeff Mahoney 		btrfs_info(fs_info, "delayed_refs has NO entry");
4196acce952bSliubo 		return ret;
4197acce952bSliubo 	}
4198acce952bSliubo 
4199d7df2c79SJosef Bacik 	while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4200d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
42010e0adbcfSJosef Bacik 		struct rb_node *n;
4202e78417d1SJosef Bacik 		bool pin_bytes = false;
4203acce952bSliubo 
4204d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4205d7df2c79SJosef Bacik 				href_node);
4206b939d1abSJosef Bacik 		if (!mutex_trylock(&head->mutex)) {
4207d278850eSJosef Bacik 			refcount_inc(&head->refs);
420879787eaaSJeff Mahoney 			spin_unlock(&delayed_refs->lock);
4209b939d1abSJosef Bacik 
4210acce952bSliubo 			mutex_lock(&head->mutex);
4211b939d1abSJosef Bacik 			mutex_unlock(&head->mutex);
4212d278850eSJosef Bacik 			btrfs_put_delayed_ref_head(head);
4213e18fca73SJosef Bacik 			spin_lock(&delayed_refs->lock);
4214b939d1abSJosef Bacik 			continue;
4215b939d1abSJosef Bacik 		}
4216d7df2c79SJosef Bacik 		spin_lock(&head->lock);
42170e0adbcfSJosef Bacik 		while ((n = rb_first(&head->ref_tree)) != NULL) {
42180e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
42190e0adbcfSJosef Bacik 				       ref_node);
4220d7df2c79SJosef Bacik 			ref->in_tree = 0;
42210e0adbcfSJosef Bacik 			rb_erase(&ref->ref_node, &head->ref_tree);
42220e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
42231d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
42241d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4225d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4226d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4227d7df2c79SJosef Bacik 		}
422854067ae9SJosef Bacik 		if (head->must_insert_reserved)
4229e78417d1SJosef Bacik 			pin_bytes = true;
423078a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4231acce952bSliubo 		delayed_refs->num_heads--;
4232d7df2c79SJosef Bacik 		if (head->processing == 0)
4233acce952bSliubo 			delayed_refs->num_heads_ready--;
4234d7df2c79SJosef Bacik 		atomic_dec(&delayed_refs->num_entries);
4235c46effa6SLiu Bo 		rb_erase(&head->href_node, &delayed_refs->href_root);
4236d278850eSJosef Bacik 		RB_CLEAR_NODE(&head->href_node);
4237d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4238acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4239e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4240acce952bSliubo 
4241d7df2c79SJosef Bacik 		if (pin_bytes)
4242d278850eSJosef Bacik 			btrfs_pin_extent(fs_info, head->bytenr,
4243d278850eSJosef Bacik 					 head->num_bytes, 1);
4244d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4245acce952bSliubo 		cond_resched();
4246acce952bSliubo 		spin_lock(&delayed_refs->lock);
4247acce952bSliubo 	}
4248acce952bSliubo 
4249acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4250acce952bSliubo 
4251acce952bSliubo 	return ret;
4252acce952bSliubo }
4253acce952bSliubo 
4254143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4255acce952bSliubo {
4256acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4257acce952bSliubo 	struct list_head splice;
4258acce952bSliubo 
4259acce952bSliubo 	INIT_LIST_HEAD(&splice);
4260acce952bSliubo 
4261eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4262eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4263acce952bSliubo 
4264acce952bSliubo 	while (!list_empty(&splice)) {
4265fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4266eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4267acce952bSliubo 					       delalloc_inodes);
4268fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4269eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4270acce952bSliubo 
4271fe816d0fSNikolay Borisov 		/*
4272fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4273fe816d0fSNikolay Borisov 		 * meanwhile.
4274fe816d0fSNikolay Borisov 		 */
4275fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4276fe816d0fSNikolay Borisov 		if (inode) {
4277fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4278fe816d0fSNikolay Borisov 			iput(inode);
4279fe816d0fSNikolay Borisov 		}
4280eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4281acce952bSliubo 	}
4282eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4283eb73c1b7SMiao Xie }
4284eb73c1b7SMiao Xie 
4285eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4286eb73c1b7SMiao Xie {
4287eb73c1b7SMiao Xie 	struct btrfs_root *root;
4288eb73c1b7SMiao Xie 	struct list_head splice;
4289eb73c1b7SMiao Xie 
4290eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4291eb73c1b7SMiao Xie 
4292eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4293eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4294eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4295eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4296eb73c1b7SMiao Xie 					 delalloc_root);
4297eb73c1b7SMiao Xie 		root = btrfs_grab_fs_root(root);
4298eb73c1b7SMiao Xie 		BUG_ON(!root);
4299eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4300eb73c1b7SMiao Xie 
4301eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
4302eb73c1b7SMiao Xie 		btrfs_put_fs_root(root);
4303eb73c1b7SMiao Xie 
4304eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4305eb73c1b7SMiao Xie 	}
4306eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4307acce952bSliubo }
4308acce952bSliubo 
43092ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4310acce952bSliubo 					struct extent_io_tree *dirty_pages,
4311acce952bSliubo 					int mark)
4312acce952bSliubo {
4313acce952bSliubo 	int ret;
4314acce952bSliubo 	struct extent_buffer *eb;
4315acce952bSliubo 	u64 start = 0;
4316acce952bSliubo 	u64 end;
4317acce952bSliubo 
4318acce952bSliubo 	while (1) {
4319acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4320e6138876SJosef Bacik 					    mark, NULL);
4321acce952bSliubo 		if (ret)
4322acce952bSliubo 			break;
4323acce952bSliubo 
432491166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4325acce952bSliubo 		while (start <= end) {
43260b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
43270b246afaSJeff Mahoney 			start += fs_info->nodesize;
4328fd8b2b61SJosef Bacik 			if (!eb)
4329acce952bSliubo 				continue;
4330fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4331acce952bSliubo 
4332fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4333fd8b2b61SJosef Bacik 					       &eb->bflags))
4334fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4335fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4336acce952bSliubo 		}
4337acce952bSliubo 	}
4338acce952bSliubo 
4339acce952bSliubo 	return ret;
4340acce952bSliubo }
4341acce952bSliubo 
43422ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4343acce952bSliubo 				       struct extent_io_tree *pinned_extents)
4344acce952bSliubo {
4345acce952bSliubo 	struct extent_io_tree *unpin;
4346acce952bSliubo 	u64 start;
4347acce952bSliubo 	u64 end;
4348acce952bSliubo 	int ret;
4349ed0eaa14SLiu Bo 	bool loop = true;
4350acce952bSliubo 
4351acce952bSliubo 	unpin = pinned_extents;
4352ed0eaa14SLiu Bo again:
4353acce952bSliubo 	while (1) {
4354acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
4355e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
4356acce952bSliubo 		if (ret)
4357acce952bSliubo 			break;
4358acce952bSliubo 
4359af6f8f60SDavid Sterba 		clear_extent_dirty(unpin, start, end);
43602ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4361acce952bSliubo 		cond_resched();
4362acce952bSliubo 	}
4363acce952bSliubo 
4364ed0eaa14SLiu Bo 	if (loop) {
43650b246afaSJeff Mahoney 		if (unpin == &fs_info->freed_extents[0])
43660b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[1];
4367ed0eaa14SLiu Bo 		else
43680b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[0];
4369ed0eaa14SLiu Bo 		loop = false;
4370ed0eaa14SLiu Bo 		goto again;
4371ed0eaa14SLiu Bo 	}
4372ed0eaa14SLiu Bo 
4373acce952bSliubo 	return 0;
4374acce952bSliubo }
4375acce952bSliubo 
4376c79a1751SLiu Bo static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4377c79a1751SLiu Bo {
4378c79a1751SLiu Bo 	struct inode *inode;
4379c79a1751SLiu Bo 
4380c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4381c79a1751SLiu Bo 	if (inode) {
4382c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4383c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4384c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4385c79a1751SLiu Bo 		iput(inode);
4386c79a1751SLiu Bo 	}
4387c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4388c79a1751SLiu Bo }
4389c79a1751SLiu Bo 
4390c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
43912ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4392c79a1751SLiu Bo {
4393c79a1751SLiu Bo 	struct btrfs_block_group_cache *cache;
4394c79a1751SLiu Bo 
4395c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4396c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4397c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
4398c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4399c79a1751SLiu Bo 					 dirty_list);
4400c79a1751SLiu Bo 
4401c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4402c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4403c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4404c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4405c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4406c79a1751SLiu Bo 		}
4407c79a1751SLiu Bo 
4408c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4409c79a1751SLiu Bo 		spin_lock(&cache->lock);
4410c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4411c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4412c79a1751SLiu Bo 
4413c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4414c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4415c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4416c79a1751SLiu Bo 	}
4417c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4418c79a1751SLiu Bo 
441945ae2c18SNikolay Borisov 	/*
442045ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
442145ae2c18SNikolay Borisov 	 * to use it without any locking
442245ae2c18SNikolay Borisov 	 */
4423c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4424c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
4425c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4426c79a1751SLiu Bo 					 io_list);
4427c79a1751SLiu Bo 
4428c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4429c79a1751SLiu Bo 		spin_lock(&cache->lock);
4430c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4431c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4432c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4433c79a1751SLiu Bo 	}
4434c79a1751SLiu Bo }
4435c79a1751SLiu Bo 
443649b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
44372ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
443849b25e05SJeff Mahoney {
44392ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4440c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4441c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4442c79a1751SLiu Bo 
44432ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
444449b25e05SJeff Mahoney 
44454a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
44460b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
444749b25e05SJeff Mahoney 
44484a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
44490b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
445049b25e05SJeff Mahoney 
4451ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4452ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
445367cde344SMiao Xie 
44542ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
445549b25e05SJeff Mahoney 				     EXTENT_DIRTY);
44562ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info,
44570b246afaSJeff Mahoney 				    fs_info->pinned_extents);
445849b25e05SJeff Mahoney 
44594a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
44604a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
446149b25e05SJeff Mahoney }
446249b25e05SJeff Mahoney 
44632ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4464acce952bSliubo {
4465acce952bSliubo 	struct btrfs_transaction *t;
4466acce952bSliubo 
44670b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4468acce952bSliubo 
44690b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
44700b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
44710b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4472724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4473724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
44749b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
44750b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
44762ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4477724e2315SJosef Bacik 			btrfs_put_transaction(t);
44780b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4479724e2315SJosef Bacik 			continue;
4480724e2315SJosef Bacik 		}
44810b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4482724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
44830b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4484724e2315SJosef Bacik 			/*
4485724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4486724e2315SJosef Bacik 			 * handle open currently for this transaction.
4487724e2315SJosef Bacik 			 */
4488724e2315SJosef Bacik 			wait_event(t->writer_wait,
4489724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4490724e2315SJosef Bacik 		} else {
44910b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4492724e2315SJosef Bacik 		}
44932ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4494724e2315SJosef Bacik 
44950b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
44960b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
44970b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4498724e2315SJosef Bacik 		list_del_init(&t->list);
44990b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4500a4abeea4SJosef Bacik 
4501724e2315SJosef Bacik 		btrfs_put_transaction(t);
45022ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
45030b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4504724e2315SJosef Bacik 	}
45050b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
45060b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4507ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4508ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
45092ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
45100b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
45110b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4512acce952bSliubo 
4513acce952bSliubo 	return 0;
4514acce952bSliubo }
4515acce952bSliubo 
4516e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
45174d53dddbSDavid Sterba 	/* mandatory callbacks */
45180b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
45194d53dddbSDavid Sterba 	.readpage_end_io_hook = btree_readpage_end_io_hook,
452020a7db8aSDavid Sterba 	.readpage_io_failed_hook = btree_io_failed_hook,
45214d53dddbSDavid Sterba 
45224d53dddbSDavid Sterba 	/* optional callbacks */
45230da5468fSChris Mason };
4524