xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 41a6e891)
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>
887cbda5cSChris Mason #include <linux/scatterlist.h>
922b0ebdaSChris Mason #include <linux/swap.h>
100f7d52f4SChris Mason #include <linux/radix-tree.h>
1135b7e476SChris Mason #include <linux/writeback.h>
12d397712bSChris Mason #include <linux/buffer_head.h>
13ce9adaa5SChris Mason #include <linux/workqueue.h>
14a74a4b97SChris Mason #include <linux/kthread.h>
155a0e3ad6STejun Heo #include <linux/slab.h>
16784b4e29SChris Mason #include <linux/migrate.h>
177a36ddecSDavid Sterba #include <linux/ratelimit.h>
186463fe58SStefan Behrens #include <linux/uuid.h>
19803b2f54SStefan Behrens #include <linux/semaphore.h>
20540adea3SMasami Hiramatsu #include <linux/error-injection.h>
219678c543SNikolay Borisov #include <linux/crc32c.h>
227e75bf3fSDavid Sterba #include <asm/unaligned.h>
23eb60ceacSChris Mason #include "ctree.h"
24eb60ceacSChris Mason #include "disk-io.h"
25e089f05cSChris Mason #include "transaction.h"
260f7d52f4SChris Mason #include "btrfs_inode.h"
270b86a832SChris Mason #include "volumes.h"
28db94535dSChris Mason #include "print-tree.h"
29925baeddSChris Mason #include "locking.h"
30e02119d5SChris Mason #include "tree-log.h"
31fa9c0d79SChris Mason #include "free-space-cache.h"
3270f6d82eSOmar Sandoval #include "free-space-tree.h"
33581bb050SLi Zefan #include "inode-map.h"
3421adbd5cSStefan Behrens #include "check-integrity.h"
35606686eeSJosef Bacik #include "rcu-string.h"
368dabb742SStefan Behrens #include "dev-replace.h"
3753b381b3SDavid Woodhouse #include "raid56.h"
385ac1d209SJeff Mahoney #include "sysfs.h"
39fcebe456SJosef Bacik #include "qgroup.h"
40ebb8765bSAnand Jain #include "compression.h"
41557ea5ddSQu Wenruo #include "tree-checker.h"
42fd708b81SJosef Bacik #include "ref-verify.h"
43eb60ceacSChris Mason 
44de0022b9SJosef Bacik #ifdef CONFIG_X86
45de0022b9SJosef Bacik #include <asm/cpufeature.h>
46de0022b9SJosef Bacik #endif
47de0022b9SJosef Bacik 
48319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
49319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
51319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
53e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
54319e4d06SQu Wenruo 
55e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops;
568b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
574df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root);
583d3a126aSDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info);
59143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
60acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
612ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
62143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
632ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
64acce952bSliubo 					struct extent_io_tree *dirty_pages,
65acce952bSliubo 					int mark);
662ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
67acce952bSliubo 				       struct extent_io_tree *pinned_extents);
682ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
692ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
70ce9adaa5SChris Mason 
71d352ac68SChris Mason /*
7297eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
7397eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
74d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
75d352ac68SChris Mason  */
7697eb6b69SDavid Sterba struct btrfs_end_io_wq {
77ce9adaa5SChris Mason 	struct bio *bio;
78ce9adaa5SChris Mason 	bio_end_io_t *end_io;
79ce9adaa5SChris Mason 	void *private;
80ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
814e4cbee9SChristoph Hellwig 	blk_status_t status;
82bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
838b712842SChris Mason 	struct btrfs_work work;
84ce9adaa5SChris Mason };
850da5468fSChris Mason 
8697eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8797eb6b69SDavid Sterba 
8897eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8997eb6b69SDavid Sterba {
9097eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
9197eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
9297eb6b69SDavid Sterba 					0,
93fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9497eb6b69SDavid Sterba 					NULL);
9597eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9697eb6b69SDavid Sterba 		return -ENOMEM;
9797eb6b69SDavid Sterba 	return 0;
9897eb6b69SDavid Sterba }
9997eb6b69SDavid Sterba 
100e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
10197eb6b69SDavid Sterba {
10297eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
10397eb6b69SDavid Sterba }
10497eb6b69SDavid Sterba 
105d352ac68SChris Mason /*
106d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
107d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
108d352ac68SChris Mason  * just before they are sent down the IO stack.
109d352ac68SChris Mason  */
11044b8bd7eSChris Mason struct async_submit_bio {
111c6100a4bSJosef Bacik 	void *private_data;
112c6100a4bSJosef Bacik 	struct btrfs_fs_info *fs_info;
11344b8bd7eSChris Mason 	struct bio *bio;
114a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
115a758781dSDavid Sterba 	extent_submit_bio_done_t *submit_bio_done;
11644b8bd7eSChris Mason 	int mirror_num;
117c8b97818SChris Mason 	unsigned long bio_flags;
118eaf25d93SChris Mason 	/*
119eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
120eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
121eaf25d93SChris Mason 	 */
122eaf25d93SChris Mason 	u64 bio_offset;
1238b712842SChris Mason 	struct btrfs_work work;
1244e4cbee9SChristoph Hellwig 	blk_status_t status;
12544b8bd7eSChris Mason };
12644b8bd7eSChris Mason 
12785d4e461SChris Mason /*
12885d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12985d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
13085d4e461SChris Mason  * the level the eb occupies in the tree.
1314008c04aSChris Mason  *
13285d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13385d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13485d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
13585d4e461SChris Mason  * by btrfs_root->objectid.  This ensures that all special purpose roots
13685d4e461SChris Mason  * have separate keysets.
1374008c04aSChris Mason  *
13885d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13985d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
14085d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1414008c04aSChris Mason  *
14285d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14385d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14485d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14585d4e461SChris Mason  *
14685d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14785d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14885d4e461SChris Mason  * needs update as well.
1494008c04aSChris Mason  */
1504008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1514008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1524008c04aSChris Mason #  error
1534008c04aSChris Mason # endif
15485d4e461SChris Mason 
15585d4e461SChris Mason static struct btrfs_lockdep_keyset {
15685d4e461SChris Mason 	u64			id;		/* root objectid */
15785d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
15885d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
15985d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
16085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
16185d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
16285d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
16385d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
16485d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
16585d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
16685d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
16760b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
16885d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
16985d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
17085d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
17113fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
1726b20e0adSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	.name_stem = "free-space" },
17385d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1744008c04aSChris Mason };
17585d4e461SChris Mason 
17685d4e461SChris Mason void __init btrfs_init_lockdep(void)
17785d4e461SChris Mason {
17885d4e461SChris Mason 	int i, j;
17985d4e461SChris Mason 
18085d4e461SChris Mason 	/* initialize lockdep class names */
18185d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
18285d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
18385d4e461SChris Mason 
18485d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
18585d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
18685d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
18785d4e461SChris Mason 	}
18885d4e461SChris Mason }
18985d4e461SChris Mason 
19085d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
19185d4e461SChris Mason 				    int level)
19285d4e461SChris Mason {
19385d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19485d4e461SChris Mason 
19585d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19685d4e461SChris Mason 
19785d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19885d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19985d4e461SChris Mason 		if (ks->id == objectid)
20085d4e461SChris Mason 			break;
20185d4e461SChris Mason 
20285d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20385d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20485d4e461SChris Mason }
20585d4e461SChris Mason 
2064008c04aSChris Mason #endif
2074008c04aSChris Mason 
208d352ac68SChris Mason /*
209d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
210d352ac68SChris Mason  * that covers the entire device
211d352ac68SChris Mason  */
2126af49dbdSDavid Sterba struct extent_map *btree_get_extent(struct btrfs_inode *inode,
213306e16ceSDavid Sterba 		struct page *page, size_t pg_offset, u64 start, u64 len,
2145f39d397SChris Mason 		int create)
2155f39d397SChris Mason {
216fc4f21b1SNikolay Borisov 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
217fc4f21b1SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
2185f39d397SChris Mason 	struct extent_map *em;
2195f39d397SChris Mason 	int ret;
2205f39d397SChris Mason 
221890871beSChris Mason 	read_lock(&em_tree->lock);
222d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
223a061fc8dSChris Mason 	if (em) {
2240b246afaSJeff Mahoney 		em->bdev = fs_info->fs_devices->latest_bdev;
225890871beSChris Mason 		read_unlock(&em_tree->lock);
2265f39d397SChris Mason 		goto out;
227a061fc8dSChris Mason 	}
228890871beSChris Mason 	read_unlock(&em_tree->lock);
2297b13b7b1SChris Mason 
230172ddd60SDavid Sterba 	em = alloc_extent_map();
2315f39d397SChris Mason 	if (!em) {
2325f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2335f39d397SChris Mason 		goto out;
2345f39d397SChris Mason 	}
2355f39d397SChris Mason 	em->start = 0;
2360afbaf8cSChris Mason 	em->len = (u64)-1;
237c8b97818SChris Mason 	em->block_len = (u64)-1;
2385f39d397SChris Mason 	em->block_start = 0;
2390b246afaSJeff Mahoney 	em->bdev = fs_info->fs_devices->latest_bdev;
240d1310b2eSChris Mason 
241890871beSChris Mason 	write_lock(&em_tree->lock);
24209a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2435f39d397SChris Mason 	if (ret == -EEXIST) {
2445f39d397SChris Mason 		free_extent_map(em);
2457b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
246b4f359abSTsutomu Itoh 		if (!em)
2470433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2485f39d397SChris Mason 	} else if (ret) {
2497b13b7b1SChris Mason 		free_extent_map(em);
2500433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2515f39d397SChris Mason 	}
252890871beSChris Mason 	write_unlock(&em_tree->lock);
2537b13b7b1SChris Mason 
2545f39d397SChris Mason out:
2555f39d397SChris Mason 	return em;
2565f39d397SChris Mason }
2575f39d397SChris Mason 
2589ed57367SDavid Sterba u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
25919c00ddcSChris Mason {
2609678c543SNikolay Borisov 	return crc32c(seed, data, len);
26119c00ddcSChris Mason }
26219c00ddcSChris Mason 
2630b5e3dafSDomagoj Tršan void btrfs_csum_final(u32 crc, u8 *result)
26419c00ddcSChris Mason {
2657e75bf3fSDavid Sterba 	put_unaligned_le32(~crc, result);
26619c00ddcSChris Mason }
26719c00ddcSChris Mason 
268d352ac68SChris Mason /*
269d352ac68SChris Mason  * compute the csum for a btree block, and either verify it or write it
270d352ac68SChris Mason  * into the csum field of the block.
271d352ac68SChris Mason  */
27201d58472SDaniel Dressler static int csum_tree_block(struct btrfs_fs_info *fs_info,
27301d58472SDaniel Dressler 			   struct extent_buffer *buf,
27419c00ddcSChris Mason 			   int verify)
27519c00ddcSChris Mason {
27601d58472SDaniel Dressler 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
27771a63551SDavid Sterba 	char result[BTRFS_CSUM_SIZE];
27819c00ddcSChris Mason 	unsigned long len;
27919c00ddcSChris Mason 	unsigned long cur_len;
28019c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
28119c00ddcSChris Mason 	char *kaddr;
28219c00ddcSChris Mason 	unsigned long map_start;
28319c00ddcSChris Mason 	unsigned long map_len;
28419c00ddcSChris Mason 	int err;
28519c00ddcSChris Mason 	u32 crc = ~(u32)0;
28619c00ddcSChris Mason 
28719c00ddcSChris Mason 	len = buf->len - offset;
28819c00ddcSChris Mason 	while (len > 0) {
28919c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
290a6591715SChris Mason 					&kaddr, &map_start, &map_len);
291d397712bSChris Mason 		if (err)
2928bd98f0eSAlex Lyakas 			return err;
29319c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
294b0496686SLiu Bo 		crc = btrfs_csum_data(kaddr + offset - map_start,
29519c00ddcSChris Mason 				      crc, cur_len);
29619c00ddcSChris Mason 		len -= cur_len;
29719c00ddcSChris Mason 		offset += cur_len;
29819c00ddcSChris Mason 	}
29971a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
300607d432dSJosef Bacik 
30119c00ddcSChris Mason 	btrfs_csum_final(crc, result);
30219c00ddcSChris Mason 
30319c00ddcSChris Mason 	if (verify) {
304607d432dSJosef Bacik 		if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
305e4204dedSChris Mason 			u32 val;
306e4204dedSChris Mason 			u32 found = 0;
307607d432dSJosef Bacik 			memcpy(&found, result, csum_size);
308e4204dedSChris Mason 
309607d432dSJosef Bacik 			read_extent_buffer(buf, &val, 0, csum_size);
31094647322SDavid Sterba 			btrfs_warn_rl(fs_info,
3115d163e0eSJeff Mahoney 				"%s checksum verify failed on %llu wanted %X found %X level %d",
31201d58472SDaniel Dressler 				fs_info->sb->s_id, buf->start,
313c1c9ff7cSGeert Uytterhoeven 				val, found, btrfs_header_level(buf));
3148bd98f0eSAlex Lyakas 			return -EUCLEAN;
31519c00ddcSChris Mason 		}
31619c00ddcSChris Mason 	} else {
317607d432dSJosef Bacik 		write_extent_buffer(buf, result, 0, csum_size);
31819c00ddcSChris Mason 	}
31971a63551SDavid Sterba 
32019c00ddcSChris Mason 	return 0;
32119c00ddcSChris Mason }
32219c00ddcSChris Mason 
323d352ac68SChris Mason /*
324d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
325d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
326d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
327d352ac68SChris Mason  * in the wrong place.
328d352ac68SChris Mason  */
3291259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
330b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
331b9fab919SChris Mason 				 int atomic)
3321259ab75SChris Mason {
3332ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3341259ab75SChris Mason 	int ret;
3352755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
3361259ab75SChris Mason 
3371259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
3381259ab75SChris Mason 		return 0;
3391259ab75SChris Mason 
340b9fab919SChris Mason 	if (atomic)
341b9fab919SChris Mason 		return -EAGAIN;
342b9fab919SChris Mason 
343a26e8c9fSJosef Bacik 	if (need_lock) {
344a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
345a26e8c9fSJosef Bacik 		btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
346a26e8c9fSJosef Bacik 	}
347a26e8c9fSJosef Bacik 
3482ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
349ff13db41SDavid Sterba 			 &cached_state);
3500b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3511259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3521259ab75SChris Mason 		ret = 0;
3531259ab75SChris Mason 		goto out;
3541259ab75SChris Mason 	}
35594647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
35694647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
35794647322SDavid Sterba 			eb->start,
35829549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3591259ab75SChris Mason 	ret = 1;
360a26e8c9fSJosef Bacik 
361a26e8c9fSJosef Bacik 	/*
362a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
363a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
36401327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
365a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
366a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
367a26e8c9fSJosef Bacik 	 * making everybody very sad.
368a26e8c9fSJosef Bacik 	 */
369a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3700b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
37133958dc6SChris Mason out:
3722ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
373e43bbe5eSDavid Sterba 			     &cached_state);
374472b909fSJosef Bacik 	if (need_lock)
375a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3761259ab75SChris Mason 	return ret;
3771259ab75SChris Mason }
3781259ab75SChris Mason 
379d352ac68SChris Mason /*
3801104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3811104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3821104a885SDavid Sterba  */
383ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
384ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
3851104a885SDavid Sterba {
3861104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3871104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
3881104a885SDavid Sterba 	u16 csum_type = btrfs_super_csum_type(disk_sb);
3891104a885SDavid Sterba 	int ret = 0;
3901104a885SDavid Sterba 
3911104a885SDavid Sterba 	if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
3921104a885SDavid Sterba 		u32 crc = ~(u32)0;
393776c4a7cSNikolay Borisov 		char result[sizeof(crc)];
3941104a885SDavid Sterba 
3951104a885SDavid Sterba 		/*
3961104a885SDavid Sterba 		 * The super_block structure does not span the whole
3971104a885SDavid Sterba 		 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
39801327610SNicholas D Steeves 		 * is filled with zeros and is included in the checksum.
3991104a885SDavid Sterba 		 */
4001104a885SDavid Sterba 		crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
4011104a885SDavid Sterba 				crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
4021104a885SDavid Sterba 		btrfs_csum_final(crc, result);
4031104a885SDavid Sterba 
404776c4a7cSNikolay Borisov 		if (memcmp(raw_disk_sb, result, sizeof(result)))
4051104a885SDavid Sterba 			ret = 1;
4061104a885SDavid Sterba 	}
4071104a885SDavid Sterba 
4081104a885SDavid Sterba 	if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
409ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "unsupported checksum algorithm %u",
4101104a885SDavid Sterba 				csum_type);
4111104a885SDavid Sterba 		ret = 1;
4121104a885SDavid Sterba 	}
4131104a885SDavid Sterba 
4141104a885SDavid Sterba 	return ret;
4151104a885SDavid Sterba }
4161104a885SDavid Sterba 
417581c1760SQu Wenruo static int verify_level_key(struct btrfs_fs_info *fs_info,
418581c1760SQu Wenruo 			    struct extent_buffer *eb, int level,
419581c1760SQu Wenruo 			    struct btrfs_key *first_key)
420581c1760SQu Wenruo {
421581c1760SQu Wenruo 	int found_level;
422581c1760SQu Wenruo 	struct btrfs_key found_key;
423581c1760SQu Wenruo 	int ret;
424581c1760SQu Wenruo 
425581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
426581c1760SQu Wenruo 	if (found_level != level) {
427581c1760SQu Wenruo #ifdef CONFIG_BTRFS_DEBUG
428581c1760SQu Wenruo 		WARN_ON(1);
429581c1760SQu Wenruo 		btrfs_err(fs_info,
430581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
431581c1760SQu Wenruo 			  eb->start, level, found_level);
432581c1760SQu Wenruo #endif
433581c1760SQu Wenruo 		return -EIO;
434581c1760SQu Wenruo 	}
435581c1760SQu Wenruo 
436581c1760SQu Wenruo 	if (!first_key)
437581c1760SQu Wenruo 		return 0;
438581c1760SQu Wenruo 
4395d41be6fSQu Wenruo 	/*
4405d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
4415d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
4425d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
4435d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
4445d41be6fSQu Wenruo 	 */
4455d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
4465d41be6fSQu Wenruo 		return 0;
447581c1760SQu Wenruo 	if (found_level)
448581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
449581c1760SQu Wenruo 	else
450581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
451581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
452581c1760SQu Wenruo 
453581c1760SQu Wenruo #ifdef CONFIG_BTRFS_DEBUG
454581c1760SQu Wenruo 	if (ret) {
455581c1760SQu Wenruo 		WARN_ON(1);
456581c1760SQu Wenruo 		btrfs_err(fs_info,
457581c1760SQu Wenruo "tree first key mismatch detected, bytenr=%llu key expected=(%llu, %u, %llu) has=(%llu, %u, %llu)",
458581c1760SQu Wenruo 			  eb->start, first_key->objectid, first_key->type,
459581c1760SQu Wenruo 			  first_key->offset, found_key.objectid,
460581c1760SQu Wenruo 			  found_key.type, found_key.offset);
461581c1760SQu Wenruo 	}
462581c1760SQu Wenruo #endif
463581c1760SQu Wenruo 	return ret;
464581c1760SQu Wenruo }
465581c1760SQu Wenruo 
4661104a885SDavid Sterba /*
467d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
468d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
469581c1760SQu Wenruo  *
470581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
471581c1760SQu Wenruo  * @level:		expected level, mandatory check
472581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
473d352ac68SChris Mason  */
4742ff7e61eSJeff Mahoney static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
475f188591eSChris Mason 					  struct extent_buffer *eb,
476581c1760SQu Wenruo 					  u64 parent_transid, int level,
477581c1760SQu Wenruo 					  struct btrfs_key *first_key)
478f188591eSChris Mason {
479f188591eSChris Mason 	struct extent_io_tree *io_tree;
480ea466794SJosef Bacik 	int failed = 0;
481f188591eSChris Mason 	int ret;
482f188591eSChris Mason 	int num_copies = 0;
483f188591eSChris Mason 	int mirror_num = 0;
484ea466794SJosef Bacik 	int failed_mirror = 0;
485f188591eSChris Mason 
486a826d6dcSJosef Bacik 	clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
4870b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
488f188591eSChris Mason 	while (1) {
4898436ea91SJosef Bacik 		ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
4906af49dbdSDavid Sterba 					       mirror_num);
491256dd1bbSStefan Behrens 		if (!ret) {
492581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
493b9fab919SChris Mason 						   parent_transid, 0))
494256dd1bbSStefan Behrens 				ret = -EIO;
495581c1760SQu Wenruo 			else if (verify_level_key(fs_info, eb, level,
496581c1760SQu Wenruo 						  first_key))
497581c1760SQu Wenruo 				ret = -EUCLEAN;
498581c1760SQu Wenruo 			else
499581c1760SQu Wenruo 				break;
500256dd1bbSStefan Behrens 		}
501d397712bSChris Mason 
502a826d6dcSJosef Bacik 		/*
503a826d6dcSJosef Bacik 		 * This buffer's crc is fine, but its contents are corrupted, so
504a826d6dcSJosef Bacik 		 * there is no reason to read the other copies, they won't be
505a826d6dcSJosef Bacik 		 * any less wrong.
506a826d6dcSJosef Bacik 		 */
507581c1760SQu Wenruo 		if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags) ||
508581c1760SQu Wenruo 		    ret == -EUCLEAN)
509ea466794SJosef Bacik 			break;
510ea466794SJosef Bacik 
5110b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
512f188591eSChris Mason 					      eb->start, eb->len);
5134235298eSChris Mason 		if (num_copies == 1)
514ea466794SJosef Bacik 			break;
5154235298eSChris Mason 
5165cf1ab56SJosef Bacik 		if (!failed_mirror) {
5175cf1ab56SJosef Bacik 			failed = 1;
5185cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
5195cf1ab56SJosef Bacik 		}
5205cf1ab56SJosef Bacik 
521f188591eSChris Mason 		mirror_num++;
522ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
523ea466794SJosef Bacik 			mirror_num++;
524ea466794SJosef Bacik 
5254235298eSChris Mason 		if (mirror_num > num_copies)
526ea466794SJosef Bacik 			break;
527f188591eSChris Mason 	}
528ea466794SJosef Bacik 
529c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
5302ff7e61eSJeff Mahoney 		repair_eb_io_failure(fs_info, eb, failed_mirror);
531ea466794SJosef Bacik 
532ea466794SJosef Bacik 	return ret;
533f188591eSChris Mason }
53419c00ddcSChris Mason 
535d352ac68SChris Mason /*
536d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
537d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
538d352ac68SChris Mason  */
539d397712bSChris Mason 
54001d58472SDaniel Dressler static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
54119c00ddcSChris Mason {
5424eee4fa4SMiao Xie 	u64 start = page_offset(page);
54319c00ddcSChris Mason 	u64 found_start;
54419c00ddcSChris Mason 	struct extent_buffer *eb;
545f188591eSChris Mason 
5464f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5474f2de97aSJosef Bacik 	if (page != eb->pages[0])
5484f2de97aSJosef Bacik 		return 0;
5490f805531SAlex Lyakas 
55019c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
5510f805531SAlex Lyakas 	/*
5520f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5530f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5540f805531SAlex Lyakas 	 */
5550f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5560f805531SAlex Lyakas 		return -EUCLEAN;
5570f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5580f805531SAlex Lyakas 		return -EUCLEAN;
5590f805531SAlex Lyakas 
5600f805531SAlex Lyakas 	ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
5610f805531SAlex Lyakas 			btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
5620f805531SAlex Lyakas 
5638bd98f0eSAlex Lyakas 	return csum_tree_block(fs_info, eb, 0);
56419c00ddcSChris Mason }
56519c00ddcSChris Mason 
56601d58472SDaniel Dressler static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
5672b82032cSYan Zheng 				 struct extent_buffer *eb)
5682b82032cSYan Zheng {
56901d58472SDaniel Dressler 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
57044880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
5712b82032cSYan Zheng 	int ret = 1;
5722b82032cSYan Zheng 
5730a4e5586SRoss Kirk 	read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
5742b82032cSYan Zheng 	while (fs_devices) {
5752b82032cSYan Zheng 		if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
5762b82032cSYan Zheng 			ret = 0;
5772b82032cSYan Zheng 			break;
5782b82032cSYan Zheng 		}
5792b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5802b82032cSYan Zheng 	}
5812b82032cSYan Zheng 	return ret;
5822b82032cSYan Zheng }
5832b82032cSYan Zheng 
584facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
585facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
586facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
587ce9adaa5SChris Mason {
588ce9adaa5SChris Mason 	u64 found_start;
589ce9adaa5SChris Mason 	int found_level;
590ce9adaa5SChris Mason 	struct extent_buffer *eb;
591ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
59202873e43SZhao Lei 	struct btrfs_fs_info *fs_info = root->fs_info;
593f188591eSChris Mason 	int ret = 0;
594727011e0SChris Mason 	int reads_done;
595ce9adaa5SChris Mason 
596ce9adaa5SChris Mason 	if (!page->private)
597ce9adaa5SChris Mason 		goto out;
598d397712bSChris Mason 
5994f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
600d397712bSChris Mason 
6010b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
6020b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
6030b32f4bbSJosef Bacik 	 */
6040b32f4bbSJosef Bacik 	extent_buffer_get(eb);
6050b32f4bbSJosef Bacik 
6060b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
607727011e0SChris Mason 	if (!reads_done)
608727011e0SChris Mason 		goto err;
609f188591eSChris Mason 
6105cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
611656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
612ea466794SJosef Bacik 		ret = -EIO;
613ea466794SJosef Bacik 		goto err;
614ea466794SJosef Bacik 	}
615ea466794SJosef Bacik 
616ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
617727011e0SChris Mason 	if (found_start != eb->start) {
61802873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad tree block start %llu %llu",
61994647322SDavid Sterba 			     found_start, eb->start);
620f188591eSChris Mason 		ret = -EIO;
621ce9adaa5SChris Mason 		goto err;
622ce9adaa5SChris Mason 	}
62302873e43SZhao Lei 	if (check_tree_block_fsid(fs_info, eb)) {
62402873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
62594647322SDavid Sterba 			     eb->start);
6261259ab75SChris Mason 		ret = -EIO;
6271259ab75SChris Mason 		goto err;
6281259ab75SChris Mason 	}
629ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6301c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
63102873e43SZhao Lei 		btrfs_err(fs_info, "bad tree block level %d",
6321c24c3ceSJosef Bacik 			  (int)btrfs_header_level(eb));
6331c24c3ceSJosef Bacik 		ret = -EIO;
6341c24c3ceSJosef Bacik 		goto err;
6351c24c3ceSJosef Bacik 	}
636ce9adaa5SChris Mason 
63785d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
63885d4e461SChris Mason 				       eb, found_level);
6394008c04aSChris Mason 
64002873e43SZhao Lei 	ret = csum_tree_block(fs_info, eb, 1);
6418bd98f0eSAlex Lyakas 	if (ret)
642a826d6dcSJosef Bacik 		goto err;
643a826d6dcSJosef Bacik 
644a826d6dcSJosef Bacik 	/*
645a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
646a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
647a826d6dcSJosef Bacik 	 * return -EIO.
648a826d6dcSJosef Bacik 	 */
6492f659546SQu Wenruo 	if (found_level == 0 && btrfs_check_leaf_full(fs_info, eb)) {
650a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
651a826d6dcSJosef Bacik 		ret = -EIO;
652a826d6dcSJosef Bacik 	}
653ce9adaa5SChris Mason 
6542f659546SQu Wenruo 	if (found_level > 0 && btrfs_check_node(fs_info, eb))
655053ab70fSLiu Bo 		ret = -EIO;
656053ab70fSLiu Bo 
6570b32f4bbSJosef Bacik 	if (!ret)
6580b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
659ce9adaa5SChris Mason err:
66079fb65a1SJosef Bacik 	if (reads_done &&
66179fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
662d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6634bb31e92SArne Jansen 
66453b381b3SDavid Woodhouse 	if (ret) {
66553b381b3SDavid Woodhouse 		/*
66653b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
66753b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
66853b381b3SDavid Woodhouse 		 * to decrement
66953b381b3SDavid Woodhouse 		 */
67053b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6710b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
67253b381b3SDavid Woodhouse 	}
6730b32f4bbSJosef Bacik 	free_extent_buffer(eb);
674ce9adaa5SChris Mason out:
675f188591eSChris Mason 	return ret;
676ce9adaa5SChris Mason }
677ce9adaa5SChris Mason 
678ea466794SJosef Bacik static int btree_io_failed_hook(struct page *page, int failed_mirror)
6794bb31e92SArne Jansen {
6804bb31e92SArne Jansen 	struct extent_buffer *eb;
6814bb31e92SArne Jansen 
6824f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
683656f30dbSFilipe Manana 	set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
6845cf1ab56SJosef Bacik 	eb->read_mirror = failed_mirror;
68553b381b3SDavid Woodhouse 	atomic_dec(&eb->io_pages);
686ea466794SJosef Bacik 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
687d48d71aaSDavid Sterba 		btree_readahead_hook(eb, -EIO);
6884bb31e92SArne Jansen 	return -EIO;	/* we fixed nothing */
6894bb31e92SArne Jansen }
6904bb31e92SArne Jansen 
6914246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
692ce9adaa5SChris Mason {
69397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
694ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6959e0af237SLiu Bo 	struct btrfs_workqueue *wq;
6969e0af237SLiu Bo 	btrfs_work_func_t func;
697ce9adaa5SChris Mason 
698ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
6994e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
700d20f7043SChris Mason 
70137226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
7029e0af237SLiu Bo 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
7039e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
7049e0af237SLiu Bo 			func = btrfs_endio_meta_write_helper;
7059e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
7069e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
7079e0af237SLiu Bo 			func = btrfs_freespace_write_helper;
7089e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7099e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7109e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
711d20f7043SChris Mason 		} else {
7129e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7139e0af237SLiu Bo 			func = btrfs_endio_write_helper;
714d20f7043SChris Mason 		}
7159e0af237SLiu Bo 	} else {
7168b110e39SMiao Xie 		if (unlikely(end_io_wq->metadata ==
7178b110e39SMiao Xie 			     BTRFS_WQ_ENDIO_DIO_REPAIR)) {
7188b110e39SMiao Xie 			wq = fs_info->endio_repair_workers;
7198b110e39SMiao Xie 			func = btrfs_endio_repair_helper;
7208b110e39SMiao Xie 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7219e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7229e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
7239e0af237SLiu Bo 		} else if (end_io_wq->metadata) {
7249e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
7259e0af237SLiu Bo 			func = btrfs_endio_meta_helper;
7269e0af237SLiu Bo 		} else {
7279e0af237SLiu Bo 			wq = fs_info->endio_workers;
7289e0af237SLiu Bo 			func = btrfs_endio_helper;
7299e0af237SLiu Bo 		}
7309e0af237SLiu Bo 	}
7319e0af237SLiu Bo 
7329e0af237SLiu Bo 	btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
7339e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
734ce9adaa5SChris Mason }
735ce9adaa5SChris Mason 
7364e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
737bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7380b86a832SChris Mason {
73997eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7408b110e39SMiao Xie 
74197eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
742ce9adaa5SChris Mason 	if (!end_io_wq)
7434e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
744ce9adaa5SChris Mason 
745ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
746ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
74722c59948SChris Mason 	end_io_wq->info = info;
7484e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
749ce9adaa5SChris Mason 	end_io_wq->bio = bio;
75022c59948SChris Mason 	end_io_wq->metadata = metadata;
751ce9adaa5SChris Mason 
752ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
753ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
75422c59948SChris Mason 	return 0;
75522c59948SChris Mason }
75622c59948SChris Mason 
7574a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7584a69a410SChris Mason {
7594a69a410SChris Mason 	struct async_submit_bio *async;
7604e4cbee9SChristoph Hellwig 	blk_status_t ret;
7614a69a410SChris Mason 
7624a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
763c6100a4bSJosef Bacik 	ret = async->submit_bio_start(async->private_data, async->bio,
764eaf25d93SChris Mason 				      async->bio_offset);
76579787eaaSJeff Mahoney 	if (ret)
7664e4cbee9SChristoph Hellwig 		async->status = ret;
7674a69a410SChris Mason }
7684a69a410SChris Mason 
7694a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7708b712842SChris Mason {
7718b712842SChris Mason 	struct async_submit_bio *async;
7728b712842SChris Mason 
7738b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7744854ddd0SChris Mason 
775bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7764e4cbee9SChristoph Hellwig 	if (async->status) {
7774e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7784246a0b6SChristoph Hellwig 		bio_endio(async->bio);
77979787eaaSJeff Mahoney 		return;
78079787eaaSJeff Mahoney 	}
78179787eaaSJeff Mahoney 
7826c553435SDavid Sterba 	async->submit_bio_done(async->private_data, async->bio, async->mirror_num);
7834a69a410SChris Mason }
7844a69a410SChris Mason 
7854a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7864a69a410SChris Mason {
7874a69a410SChris Mason 	struct async_submit_bio *async;
7884a69a410SChris Mason 
7894a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7908b712842SChris Mason 	kfree(async);
7918b712842SChris Mason }
7928b712842SChris Mason 
7938c27cb35SLinus Torvalds blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
794c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
795c6100a4bSJosef Bacik 				 u64 bio_offset, void *private_data,
796a758781dSDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start,
797a758781dSDavid Sterba 				 extent_submit_bio_done_t *submit_bio_done)
79844b8bd7eSChris Mason {
79944b8bd7eSChris Mason 	struct async_submit_bio *async;
80044b8bd7eSChris Mason 
80144b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
80244b8bd7eSChris Mason 	if (!async)
8034e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
80444b8bd7eSChris Mason 
805c6100a4bSJosef Bacik 	async->private_data = private_data;
806c6100a4bSJosef Bacik 	async->fs_info = fs_info;
80744b8bd7eSChris Mason 	async->bio = bio;
80844b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8094a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8104a69a410SChris Mason 	async->submit_bio_done = submit_bio_done;
8114a69a410SChris Mason 
8129e0af237SLiu Bo 	btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
8135cdc7ad3SQu Wenruo 			run_one_async_done, run_one_async_free);
8144a69a410SChris Mason 
815c8b97818SChris Mason 	async->bio_flags = bio_flags;
816eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8178c8bee1dSChris Mason 
8184e4cbee9SChristoph Hellwig 	async->status = 0;
81979787eaaSJeff Mahoney 
82067f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8215cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
822d313d7a3SChris Mason 
8235cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
82444b8bd7eSChris Mason 	return 0;
82544b8bd7eSChris Mason }
82644b8bd7eSChris Mason 
8274e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
828ce3ed71aSChris Mason {
8292c30c71bSKent Overstreet 	struct bio_vec *bvec;
830ce3ed71aSChris Mason 	struct btrfs_root *root;
8312c30c71bSKent Overstreet 	int i, ret = 0;
832ce3ed71aSChris Mason 
833c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8342c30c71bSKent Overstreet 	bio_for_each_segment_all(bvec, bio, i) {
835ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
83601d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
83779787eaaSJeff Mahoney 		if (ret)
83879787eaaSJeff Mahoney 			break;
839ce3ed71aSChris Mason 	}
8402c30c71bSKent Overstreet 
8414e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
842ce3ed71aSChris Mason }
843ce3ed71aSChris Mason 
844d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
845eaf25d93SChris Mason 					     u64 bio_offset)
84622c59948SChris Mason {
8478b712842SChris Mason 	/*
8488b712842SChris Mason 	 * when we're called for a write, we're already in the async
8495443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8508b712842SChris Mason 	 */
85179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
85222c59948SChris Mason }
85322c59948SChris Mason 
854d0ee3934SDavid Sterba static blk_status_t btree_submit_bio_done(void *private_data, struct bio *bio,
8556c553435SDavid Sterba 					    int mirror_num)
8564a69a410SChris Mason {
857c6100a4bSJosef Bacik 	struct inode *inode = private_data;
8584e4cbee9SChristoph Hellwig 	blk_status_t ret;
85961891923SStefan Behrens 
8608b712842SChris Mason 	/*
8614a69a410SChris Mason 	 * when we're called for a write, we're already in the async
8624a69a410SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8638b712842SChris Mason 	 */
8642ff7e61eSJeff Mahoney 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), bio, mirror_num, 1);
8654246a0b6SChristoph Hellwig 	if (ret) {
8664e4cbee9SChristoph Hellwig 		bio->bi_status = ret;
8674246a0b6SChristoph Hellwig 		bio_endio(bio);
8684246a0b6SChristoph Hellwig 	}
86961891923SStefan Behrens 	return ret;
8700b86a832SChris Mason }
8710b86a832SChris Mason 
87218fdc679SLiu Bo static int check_async_write(struct btrfs_inode *bi)
873de0022b9SJosef Bacik {
8746300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8756300463bSLiu Bo 		return 0;
876de0022b9SJosef Bacik #ifdef CONFIG_X86
877bc696ca0SBorislav Petkov 	if (static_cpu_has(X86_FEATURE_XMM4_2))
878de0022b9SJosef Bacik 		return 0;
879de0022b9SJosef Bacik #endif
880de0022b9SJosef Bacik 	return 1;
881de0022b9SJosef Bacik }
882de0022b9SJosef Bacik 
8838c27cb35SLinus Torvalds static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
884eaf25d93SChris Mason 					  int mirror_num, unsigned long bio_flags,
885eaf25d93SChris Mason 					  u64 bio_offset)
88644b8bd7eSChris Mason {
887c6100a4bSJosef Bacik 	struct inode *inode = private_data;
8880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
88918fdc679SLiu Bo 	int async = check_async_write(BTRFS_I(inode));
8904e4cbee9SChristoph Hellwig 	blk_status_t ret;
891cad321adSChris Mason 
89237226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
893cad321adSChris Mason 		/*
894cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
895cad321adSChris Mason 		 * can happen in the async kernel threads
896cad321adSChris Mason 		 */
8970b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8980b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8991d4284bdSChris Mason 		if (ret)
90061891923SStefan Behrens 			goto out_w_error;
9012ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
902de0022b9SJosef Bacik 	} else if (!async) {
903de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
904de0022b9SJosef Bacik 		if (ret)
90561891923SStefan Behrens 			goto out_w_error;
9062ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
90761891923SStefan Behrens 	} else {
908cad321adSChris Mason 		/*
90961891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
91061891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
911cad321adSChris Mason 		 */
912c6100a4bSJosef Bacik 		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
913c6100a4bSJosef Bacik 					  bio_offset, private_data,
914d0ee3934SDavid Sterba 					  btree_submit_bio_start,
915d0ee3934SDavid Sterba 					  btree_submit_bio_done);
91644b8bd7eSChris Mason 	}
91744b8bd7eSChris Mason 
9184246a0b6SChristoph Hellwig 	if (ret)
9194246a0b6SChristoph Hellwig 		goto out_w_error;
9204246a0b6SChristoph Hellwig 	return 0;
9214246a0b6SChristoph Hellwig 
92261891923SStefan Behrens out_w_error:
9234e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9244246a0b6SChristoph Hellwig 	bio_endio(bio);
92561891923SStefan Behrens 	return ret;
92661891923SStefan Behrens }
92761891923SStefan Behrens 
9283dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
929784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
930a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
931a6bc32b8SMel Gorman 			enum migrate_mode mode)
932784b4e29SChris Mason {
933784b4e29SChris Mason 	/*
934784b4e29SChris Mason 	 * we can't safely write a btree page from here,
935784b4e29SChris Mason 	 * we haven't done the locking hook
936784b4e29SChris Mason 	 */
937784b4e29SChris Mason 	if (PageDirty(page))
938784b4e29SChris Mason 		return -EAGAIN;
939784b4e29SChris Mason 	/*
940784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
941784b4e29SChris Mason 	 * We must have no buffers or drop them.
942784b4e29SChris Mason 	 */
943784b4e29SChris Mason 	if (page_has_private(page) &&
944784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
945784b4e29SChris Mason 		return -EAGAIN;
946a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
947784b4e29SChris Mason }
9483dd1462eSJan Beulich #endif
949784b4e29SChris Mason 
9500da5468fSChris Mason 
9510da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9520da5468fSChris Mason 			    struct writeback_control *wbc)
9530da5468fSChris Mason {
954e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
955e2d84521SMiao Xie 	int ret;
956e2d84521SMiao Xie 
957d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
958448d640bSChris Mason 
959448d640bSChris Mason 		if (wbc->for_kupdate)
960448d640bSChris Mason 			return 0;
961448d640bSChris Mason 
962e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
963b9473439SChris Mason 		/* this is a bit racy, but that's ok */
964e2d84521SMiao Xie 		ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
965e2d84521SMiao Xie 					     BTRFS_DIRTY_METADATA_THRESH);
966e2d84521SMiao Xie 		if (ret < 0)
967793955bcSChris Mason 			return 0;
968793955bcSChris Mason 	}
9690b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9700da5468fSChris Mason }
9710da5468fSChris Mason 
972b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9735f39d397SChris Mason {
974d1310b2eSChris Mason 	struct extent_io_tree *tree;
975d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9768ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
9775f39d397SChris Mason }
9785f39d397SChris Mason 
97970dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9805f39d397SChris Mason {
98198509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
98298509cfcSChris Mason 		return 0;
9830c4e538bSDavid Sterba 
984f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
985d98237b3SChris Mason }
986d98237b3SChris Mason 
987d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
988d47992f8SLukas Czerner 				 unsigned int length)
989d98237b3SChris Mason {
990d1310b2eSChris Mason 	struct extent_io_tree *tree;
991d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9925f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9935f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9949ad6b7bcSChris Mason 	if (PagePrivate(page)) {
995efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
996efe120a0SFrank Holton 			   "page private not zero on page %llu",
997efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
9989ad6b7bcSChris Mason 		ClearPagePrivate(page);
9999ad6b7bcSChris Mason 		set_page_private(page, 0);
100009cbfeafSKirill A. Shutemov 		put_page(page);
10019ad6b7bcSChris Mason 	}
1002d98237b3SChris Mason }
1003d98237b3SChris Mason 
10040b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10050b32f4bbSJosef Bacik {
1006bb146eb2SJosef Bacik #ifdef DEBUG
10070b32f4bbSJosef Bacik 	struct extent_buffer *eb;
10080b32f4bbSJosef Bacik 
10090b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
10100b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
10110b32f4bbSJosef Bacik 	BUG_ON(!eb);
10120b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10130b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
10140b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
1015bb146eb2SJosef Bacik #endif
10160b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10170b32f4bbSJosef Bacik }
10180b32f4bbSJosef Bacik 
10197f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
1020d98237b3SChris Mason 	.readpage	= btree_readpage,
10210da5468fSChris Mason 	.writepages	= btree_writepages,
10225f39d397SChris Mason 	.releasepage	= btree_releasepage,
10235f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10245a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1025784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10265a92bc88SChris Mason #endif
10270b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1028d98237b3SChris Mason };
1029123abc88SChris Mason 
10302ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1031090d1875SChris Mason {
10325f39d397SChris Mason 	struct extent_buffer *buf = NULL;
10332ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1034090d1875SChris Mason 
10352ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1036c871b0f2SLiu Bo 	if (IS_ERR(buf))
10376197d86eSDavid Sterba 		return;
1038d1310b2eSChris Mason 	read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
10396af49dbdSDavid Sterba 				 buf, WAIT_NONE, 0);
10405f39d397SChris Mason 	free_extent_buffer(buf);
1041090d1875SChris Mason }
1042090d1875SChris Mason 
10432ff7e61eSJeff Mahoney int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1044ab0fff03SArne Jansen 			 int mirror_num, struct extent_buffer **eb)
1045ab0fff03SArne Jansen {
1046ab0fff03SArne Jansen 	struct extent_buffer *buf = NULL;
10472ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1048ab0fff03SArne Jansen 	struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1049ab0fff03SArne Jansen 	int ret;
1050ab0fff03SArne Jansen 
10512ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1052c871b0f2SLiu Bo 	if (IS_ERR(buf))
1053ab0fff03SArne Jansen 		return 0;
1054ab0fff03SArne Jansen 
1055ab0fff03SArne Jansen 	set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1056ab0fff03SArne Jansen 
10578436ea91SJosef Bacik 	ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
10586af49dbdSDavid Sterba 				       mirror_num);
1059ab0fff03SArne Jansen 	if (ret) {
1060ab0fff03SArne Jansen 		free_extent_buffer(buf);
1061ab0fff03SArne Jansen 		return ret;
1062ab0fff03SArne Jansen 	}
1063ab0fff03SArne Jansen 
1064ab0fff03SArne Jansen 	if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1065ab0fff03SArne Jansen 		free_extent_buffer(buf);
1066ab0fff03SArne Jansen 		return -EIO;
10670b32f4bbSJosef Bacik 	} else if (extent_buffer_uptodate(buf)) {
1068ab0fff03SArne Jansen 		*eb = buf;
1069ab0fff03SArne Jansen 	} else {
1070ab0fff03SArne Jansen 		free_extent_buffer(buf);
1071ab0fff03SArne Jansen 	}
1072ab0fff03SArne Jansen 	return 0;
1073ab0fff03SArne Jansen }
1074ab0fff03SArne Jansen 
10752ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10762ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10770308af44SDavid Sterba 						u64 bytenr)
10780999df54SChris Mason {
10790b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10800b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10810b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
10820999df54SChris Mason }
10830999df54SChris Mason 
10840999df54SChris Mason 
1085e02119d5SChris Mason int btrfs_write_tree_block(struct extent_buffer *buf)
1086e02119d5SChris Mason {
1087727011e0SChris Mason 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
10888aa38c31SChristoph Hellwig 					buf->start + buf->len - 1);
1089e02119d5SChris Mason }
1090e02119d5SChris Mason 
10913189ff77SJeff Layton void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1092e02119d5SChris Mason {
10933189ff77SJeff Layton 	filemap_fdatawait_range(buf->pages[0]->mapping,
10948aa38c31SChristoph Hellwig 			        buf->start, buf->start + buf->len - 1);
1095e02119d5SChris Mason }
1096e02119d5SChris Mason 
1097581c1760SQu Wenruo /*
1098581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1099581c1760SQu Wenruo  * verification.
1100581c1760SQu Wenruo  *
1101581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1102581c1760SQu Wenruo  * @level:		expected level, mandatory check
1103581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1104581c1760SQu Wenruo  */
11052ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1106581c1760SQu Wenruo 				      u64 parent_transid, int level,
1107581c1760SQu Wenruo 				      struct btrfs_key *first_key)
1108e20d96d6SChris Mason {
11095f39d397SChris Mason 	struct extent_buffer *buf = NULL;
111019c00ddcSChris Mason 	int ret;
111119c00ddcSChris Mason 
11122ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1113c871b0f2SLiu Bo 	if (IS_ERR(buf))
1114c871b0f2SLiu Bo 		return buf;
1115e4204dedSChris Mason 
1116581c1760SQu Wenruo 	ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
1117581c1760SQu Wenruo 					     level, first_key);
11180f0fe8f7SFilipe David Borba Manana 	if (ret) {
11190f0fe8f7SFilipe David Borba Manana 		free_extent_buffer(buf);
112064c043deSLiu Bo 		return ERR_PTR(ret);
11210f0fe8f7SFilipe David Borba Manana 	}
11225f39d397SChris Mason 	return buf;
1123ce9adaa5SChris Mason 
1124eb60ceacSChris Mason }
1125eb60ceacSChris Mason 
11267c302b49SDavid Sterba void clean_tree_block(struct btrfs_fs_info *fs_info,
11275f39d397SChris Mason 		      struct extent_buffer *buf)
1128ed2ff2cbSChris Mason {
112955c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1130e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1131b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1132b4ce94deSChris Mason 
1133b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1134104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1135e2d84521SMiao Xie 						 -buf->len,
1136e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
1137b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
1138b9473439SChris Mason 			btrfs_set_lock_blocking(buf);
11390b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1140925baeddSChris Mason 		}
11415f39d397SChris Mason 	}
1142ed7b63ebSJosef Bacik }
11435f39d397SChris Mason 
11448257b2dcSMiao Xie static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
11458257b2dcSMiao Xie {
11468257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
11478257b2dcSMiao Xie 	int ret;
11488257b2dcSMiao Xie 
11498257b2dcSMiao Xie 	writers = kmalloc(sizeof(*writers), GFP_NOFS);
11508257b2dcSMiao Xie 	if (!writers)
11518257b2dcSMiao Xie 		return ERR_PTR(-ENOMEM);
11528257b2dcSMiao Xie 
11538a5a916dSJeff Mahoney 	ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
11548257b2dcSMiao Xie 	if (ret < 0) {
11558257b2dcSMiao Xie 		kfree(writers);
11568257b2dcSMiao Xie 		return ERR_PTR(ret);
11578257b2dcSMiao Xie 	}
11588257b2dcSMiao Xie 
11598257b2dcSMiao Xie 	init_waitqueue_head(&writers->wait);
11608257b2dcSMiao Xie 	return writers;
11618257b2dcSMiao Xie }
11628257b2dcSMiao Xie 
11638257b2dcSMiao Xie static void
11648257b2dcSMiao Xie btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
11658257b2dcSMiao Xie {
11668257b2dcSMiao Xie 	percpu_counter_destroy(&writers->counter);
11678257b2dcSMiao Xie 	kfree(writers);
11688257b2dcSMiao Xie }
11698257b2dcSMiao Xie 
1170da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1171e20d96d6SChris Mason 			 u64 objectid)
1172d97e63b6SChris Mason {
11737c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1174cfaa7295SChris Mason 	root->node = NULL;
1175a28ec197SChris Mason 	root->commit_root = NULL;
117627cdeb70SMiao Xie 	root->state = 0;
1177d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11780b86a832SChris Mason 
11790f7d52f4SChris Mason 	root->objectid = objectid;
11800f7d52f4SChris Mason 	root->last_trans = 0;
118113a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1182eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1183199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
118458176a96SJosef Bacik 	root->name = NULL;
11856bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
118616cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1187f0486c68SYan, Zheng 	root->block_rsv = NULL;
1188d68fc57bSYan, Zheng 	root->orphan_block_rsv = NULL;
11890b86a832SChris Mason 
11900b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11915d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1192eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1193eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1194199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1195199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
11962ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11972ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
1198d68fc57bSYan, Zheng 	spin_lock_init(&root->orphan_lock);
11995d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1200eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1201199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1202f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
12032ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
12042ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
12058287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1206a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1207e02119d5SChris Mason 	mutex_init(&root->log_mutex);
120831f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1209573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
12107237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
12117237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
12127237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
12138b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
12148b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
12157237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
12167237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
12177237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
12182ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
12198a35d95fSJosef Bacik 	atomic_set(&root->orphan_inodes, 0);
12200700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
1221ea14b57fSDavid Sterba 	atomic_set(&root->will_be_snapshotted, 0);
12227237f183SYan Zheng 	root->log_transid = 0;
1223d1433debSMiao Xie 	root->log_transid_committed = -1;
1224257c62e1SChris Mason 	root->last_log_commit = 0;
12257c0260eeSJeff Mahoney 	if (!dummy)
1226c6100a4bSJosef Bacik 		extent_io_tree_init(&root->dirty_log_pages, NULL);
1227017e5369SChris Mason 
12283768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
12293768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
12306702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
12317c0260eeSJeff Mahoney 	if (!dummy)
12323f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
123306ea65a3SJosef Bacik 	else
123406ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
12354d775673SChris Mason 	root->root_key.objectid = objectid;
12360ee5dc67SAl Viro 	root->anon_dev = 0;
12378ea05e3aSAlexander Block 
12385f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
12393768f368SChris Mason }
12403768f368SChris Mason 
124174e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
124274e4d827SDavid Sterba 		gfp_t flags)
12436f07e42eSAl Viro {
124474e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12456f07e42eSAl Viro 	if (root)
12466f07e42eSAl Viro 		root->fs_info = fs_info;
12476f07e42eSAl Viro 	return root;
12486f07e42eSAl Viro }
12496f07e42eSAl Viro 
125006ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
125106ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1252da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
125306ea65a3SJosef Bacik {
125406ea65a3SJosef Bacik 	struct btrfs_root *root;
125506ea65a3SJosef Bacik 
12567c0260eeSJeff Mahoney 	if (!fs_info)
12577c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12587c0260eeSJeff Mahoney 
12597c0260eeSJeff Mahoney 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
126006ea65a3SJosef Bacik 	if (!root)
126106ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1262da17066cSJeff Mahoney 
1263b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1264da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1265faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
126606ea65a3SJosef Bacik 
126706ea65a3SJosef Bacik 	return root;
126806ea65a3SJosef Bacik }
126906ea65a3SJosef Bacik #endif
127006ea65a3SJosef Bacik 
127120897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
127220897f5cSArne Jansen 				     struct btrfs_fs_info *fs_info,
127320897f5cSArne Jansen 				     u64 objectid)
127420897f5cSArne Jansen {
127520897f5cSArne Jansen 	struct extent_buffer *leaf;
127620897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
127720897f5cSArne Jansen 	struct btrfs_root *root;
127820897f5cSArne Jansen 	struct btrfs_key key;
127920897f5cSArne Jansen 	int ret = 0;
128033d85fdaSQu Wenruo 	uuid_le uuid = NULL_UUID_LE;
128120897f5cSArne Jansen 
128274e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
128320897f5cSArne Jansen 	if (!root)
128420897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
128520897f5cSArne Jansen 
1286da17066cSJeff Mahoney 	__setup_root(root, fs_info, objectid);
128720897f5cSArne Jansen 	root->root_key.objectid = objectid;
128820897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
128920897f5cSArne Jansen 	root->root_key.offset = 0;
129020897f5cSArne Jansen 
12914d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
129220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
129320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12941dd05682STsutomu Itoh 		leaf = NULL;
129520897f5cSArne Jansen 		goto fail;
129620897f5cSArne Jansen 	}
129720897f5cSArne Jansen 
1298b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
129920897f5cSArne Jansen 	btrfs_set_header_bytenr(leaf, leaf->start);
130020897f5cSArne Jansen 	btrfs_set_header_generation(leaf, trans->transid);
130120897f5cSArne Jansen 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
130220897f5cSArne Jansen 	btrfs_set_header_owner(leaf, objectid);
130320897f5cSArne Jansen 	root->node = leaf;
130420897f5cSArne Jansen 
1305d24ee97bSDavid Sterba 	write_extent_buffer_fsid(leaf, fs_info->fsid);
1306d24ee97bSDavid Sterba 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
130720897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
130820897f5cSArne Jansen 
130920897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
131027cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
131120897f5cSArne Jansen 
131220897f5cSArne Jansen 	root->root_item.flags = 0;
131320897f5cSArne Jansen 	root->root_item.byte_limit = 0;
131420897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
131520897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
131620897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
131720897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
131820897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
131920897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
132020897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
132133d85fdaSQu Wenruo 	if (is_fstree(objectid))
13226463fe58SStefan Behrens 		uuid_le_gen(&uuid);
13236463fe58SStefan Behrens 	memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
132420897f5cSArne Jansen 	root->root_item.drop_level = 0;
132520897f5cSArne Jansen 
132620897f5cSArne Jansen 	key.objectid = objectid;
132720897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
132820897f5cSArne Jansen 	key.offset = 0;
132920897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
133020897f5cSArne Jansen 	if (ret)
133120897f5cSArne Jansen 		goto fail;
133220897f5cSArne Jansen 
133320897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
133420897f5cSArne Jansen 
133520897f5cSArne Jansen 	return root;
13361dd05682STsutomu Itoh 
13371dd05682STsutomu Itoh fail:
13381dd05682STsutomu Itoh 	if (leaf) {
13391dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
134059885b39STsutomu Itoh 		free_extent_buffer(root->commit_root);
13411dd05682STsutomu Itoh 		free_extent_buffer(leaf);
13421dd05682STsutomu Itoh 	}
13431dd05682STsutomu Itoh 	kfree(root);
13441dd05682STsutomu Itoh 
13451dd05682STsutomu Itoh 	return ERR_PTR(ret);
134620897f5cSArne Jansen }
134720897f5cSArne Jansen 
13487237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1349e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13500f7d52f4SChris Mason {
13510f7d52f4SChris Mason 	struct btrfs_root *root;
13527237f183SYan Zheng 	struct extent_buffer *leaf;
1353e02119d5SChris Mason 
135474e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1355e02119d5SChris Mason 	if (!root)
13567237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1357e02119d5SChris Mason 
1358da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1359e02119d5SChris Mason 
1360e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1361e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1362e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
136327cdeb70SMiao Xie 
13647237f183SYan Zheng 	/*
136527cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
136627cdeb70SMiao Xie 	 *
13677237f183SYan Zheng 	 * log trees do not get reference counted because they go away
13687237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
13697237f183SYan Zheng 	 * to file data extents, and those reference counts still get
13707237f183SYan Zheng 	 * updated (along with back refs to the log tree).
13717237f183SYan Zheng 	 */
1372e02119d5SChris Mason 
13734d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13744d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
13757237f183SYan Zheng 	if (IS_ERR(leaf)) {
13767237f183SYan Zheng 		kfree(root);
13777237f183SYan Zheng 		return ERR_CAST(leaf);
13787237f183SYan Zheng 	}
1379e02119d5SChris Mason 
1380b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
13815d4f98a2SYan Zheng 	btrfs_set_header_bytenr(leaf, leaf->start);
13825d4f98a2SYan Zheng 	btrfs_set_header_generation(leaf, trans->transid);
13835d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
13845d4f98a2SYan Zheng 	btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
13857237f183SYan Zheng 	root->node = leaf;
1386e02119d5SChris Mason 
13870b246afaSJeff Mahoney 	write_extent_buffer_fsid(root->node, fs_info->fsid);
1388e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1389e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13907237f183SYan Zheng 	return root;
13917237f183SYan Zheng }
13927237f183SYan Zheng 
13937237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13947237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13957237f183SYan Zheng {
13967237f183SYan Zheng 	struct btrfs_root *log_root;
13977237f183SYan Zheng 
13987237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13997237f183SYan Zheng 	if (IS_ERR(log_root))
14007237f183SYan Zheng 		return PTR_ERR(log_root);
14017237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
14027237f183SYan Zheng 	fs_info->log_root_tree = log_root;
14037237f183SYan Zheng 	return 0;
14047237f183SYan Zheng }
14057237f183SYan Zheng 
14067237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
14077237f183SYan Zheng 		       struct btrfs_root *root)
14087237f183SYan Zheng {
14090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14107237f183SYan Zheng 	struct btrfs_root *log_root;
14117237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
14127237f183SYan Zheng 
14130b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
14147237f183SYan Zheng 	if (IS_ERR(log_root))
14157237f183SYan Zheng 		return PTR_ERR(log_root);
14167237f183SYan Zheng 
14177237f183SYan Zheng 	log_root->last_trans = trans->transid;
14187237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14197237f183SYan Zheng 
14207237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14213cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14223cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14233cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1424da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
14250b246afaSJeff Mahoney 				     fs_info->nodesize);
14263cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14277237f183SYan Zheng 
14285d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14297237f183SYan Zheng 
14307237f183SYan Zheng 	WARN_ON(root->log_root);
14317237f183SYan Zheng 	root->log_root = log_root;
14327237f183SYan Zheng 	root->log_transid = 0;
1433d1433debSMiao Xie 	root->log_transid_committed = -1;
1434257c62e1SChris Mason 	root->last_log_commit = 0;
1435e02119d5SChris Mason 	return 0;
1436e02119d5SChris Mason }
1437e02119d5SChris Mason 
143835a3621bSStefan Behrens static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1439cb517eabSMiao Xie 					       struct btrfs_key *key)
1440e02119d5SChris Mason {
1441e02119d5SChris Mason 	struct btrfs_root *root;
1442e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
14430f7d52f4SChris Mason 	struct btrfs_path *path;
144484234f3aSYan Zheng 	u64 generation;
1445cb517eabSMiao Xie 	int ret;
1446581c1760SQu Wenruo 	int level;
1447cb517eabSMiao Xie 
1448cb517eabSMiao Xie 	path = btrfs_alloc_path();
1449cb517eabSMiao Xie 	if (!path)
1450cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
14510f7d52f4SChris Mason 
145274e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1453cb517eabSMiao Xie 	if (!root) {
1454cb517eabSMiao Xie 		ret = -ENOMEM;
1455cb517eabSMiao Xie 		goto alloc_fail;
14560f7d52f4SChris Mason 	}
14570f7d52f4SChris Mason 
1458da17066cSJeff Mahoney 	__setup_root(root, fs_info, key->objectid);
14590f7d52f4SChris Mason 
1460cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1461cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14620f7d52f4SChris Mason 	if (ret) {
146313a8a7c8SYan, Zheng 		if (ret > 0)
146413a8a7c8SYan, Zheng 			ret = -ENOENT;
1465cb517eabSMiao Xie 		goto find_fail;
14660f7d52f4SChris Mason 	}
146713a8a7c8SYan, Zheng 
146884234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1469581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14702ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14712ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1472581c1760SQu Wenruo 				     generation, level, NULL);
147364c043deSLiu Bo 	if (IS_ERR(root->node)) {
147464c043deSLiu Bo 		ret = PTR_ERR(root->node);
1475cb517eabSMiao Xie 		goto find_fail;
1476cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1477cb517eabSMiao Xie 		ret = -EIO;
147864c043deSLiu Bo 		free_extent_buffer(root->node);
147964c043deSLiu Bo 		goto find_fail;
1480416bc658SJosef Bacik 	}
14815d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
148213a8a7c8SYan, Zheng out:
1483cb517eabSMiao Xie 	btrfs_free_path(path);
1484cb517eabSMiao Xie 	return root;
1485cb517eabSMiao Xie 
1486cb517eabSMiao Xie find_fail:
1487cb517eabSMiao Xie 	kfree(root);
1488cb517eabSMiao Xie alloc_fail:
1489cb517eabSMiao Xie 	root = ERR_PTR(ret);
1490cb517eabSMiao Xie 	goto out;
1491cb517eabSMiao Xie }
1492cb517eabSMiao Xie 
1493cb517eabSMiao Xie struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1494cb517eabSMiao Xie 				      struct btrfs_key *location)
1495cb517eabSMiao Xie {
1496cb517eabSMiao Xie 	struct btrfs_root *root;
1497cb517eabSMiao Xie 
1498cb517eabSMiao Xie 	root = btrfs_read_tree_root(tree_root, location);
1499cb517eabSMiao Xie 	if (IS_ERR(root))
1500cb517eabSMiao Xie 		return root;
1501cb517eabSMiao Xie 
1502cb517eabSMiao Xie 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
150327cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
150408fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
150508fe4db1SLi Zefan 	}
150613a8a7c8SYan, Zheng 
15075eda7b5eSChris Mason 	return root;
15085eda7b5eSChris Mason }
15095eda7b5eSChris Mason 
1510cb517eabSMiao Xie int btrfs_init_fs_root(struct btrfs_root *root)
1511cb517eabSMiao Xie {
1512cb517eabSMiao Xie 	int ret;
15138257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
1514cb517eabSMiao Xie 
1515cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1516cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1517cb517eabSMiao Xie 					GFP_NOFS);
1518cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1519cb517eabSMiao Xie 		ret = -ENOMEM;
1520cb517eabSMiao Xie 		goto fail;
1521cb517eabSMiao Xie 	}
1522cb517eabSMiao Xie 
15238257b2dcSMiao Xie 	writers = btrfs_alloc_subvolume_writers();
15248257b2dcSMiao Xie 	if (IS_ERR(writers)) {
15258257b2dcSMiao Xie 		ret = PTR_ERR(writers);
15268257b2dcSMiao Xie 		goto fail;
15278257b2dcSMiao Xie 	}
15288257b2dcSMiao Xie 	root->subv_writers = writers;
15298257b2dcSMiao Xie 
1530cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
153157cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
153257cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1533cb517eabSMiao Xie 
1534cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1535cb517eabSMiao Xie 	if (ret)
1536876d2cf1SLiu Bo 		goto fail;
1537f32e48e9SChandan Rajendra 
1538f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1539f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1540f32e48e9SChandan Rajendra 					&root->highest_objectid);
1541f32e48e9SChandan Rajendra 	if (ret) {
1542f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1543876d2cf1SLiu Bo 		goto fail;
1544f32e48e9SChandan Rajendra 	}
1545f32e48e9SChandan Rajendra 
1546f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1547f32e48e9SChandan Rajendra 
1548f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1549f32e48e9SChandan Rajendra 
1550cb517eabSMiao Xie 	return 0;
1551cb517eabSMiao Xie fail:
1552876d2cf1SLiu Bo 	/* the caller is responsible to call free_fs_root */
1553cb517eabSMiao Xie 	return ret;
1554cb517eabSMiao Xie }
1555cb517eabSMiao Xie 
155635bbb97fSJeff Mahoney struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1557cb517eabSMiao Xie 					u64 root_id)
1558cb517eabSMiao Xie {
1559cb517eabSMiao Xie 	struct btrfs_root *root;
1560cb517eabSMiao Xie 
1561cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1562cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1563cb517eabSMiao Xie 				 (unsigned long)root_id);
1564cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1565cb517eabSMiao Xie 	return root;
1566cb517eabSMiao Xie }
1567cb517eabSMiao Xie 
1568cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1569cb517eabSMiao Xie 			 struct btrfs_root *root)
1570cb517eabSMiao Xie {
1571cb517eabSMiao Xie 	int ret;
1572cb517eabSMiao Xie 
1573e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1574cb517eabSMiao Xie 	if (ret)
1575cb517eabSMiao Xie 		return ret;
1576cb517eabSMiao Xie 
1577cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1578cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1579cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1580cb517eabSMiao Xie 				root);
1581cb517eabSMiao Xie 	if (ret == 0)
158227cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1583cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1584cb517eabSMiao Xie 	radix_tree_preload_end();
1585cb517eabSMiao Xie 
1586cb517eabSMiao Xie 	return ret;
1587cb517eabSMiao Xie }
1588cb517eabSMiao Xie 
1589c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1590c00869f1SMiao Xie 				     struct btrfs_key *location,
1591c00869f1SMiao Xie 				     bool check_ref)
15925eda7b5eSChris Mason {
15935eda7b5eSChris Mason 	struct btrfs_root *root;
1594381cf658SDavid Sterba 	struct btrfs_path *path;
15951d4c08e0SDavid Sterba 	struct btrfs_key key;
15965eda7b5eSChris Mason 	int ret;
15975eda7b5eSChris Mason 
1598edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1599edbd8d4eSChris Mason 		return fs_info->tree_root;
1600edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1601edbd8d4eSChris Mason 		return fs_info->extent_root;
16028f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
16038f18cf13SChris Mason 		return fs_info->chunk_root;
16048f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
16058f18cf13SChris Mason 		return fs_info->dev_root;
16060403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
16070403e47eSYan Zheng 		return fs_info->csum_root;
1608bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1609bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1610bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
1611f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1612f7a81ea4SStefan Behrens 		return fs_info->uuid_root ? fs_info->uuid_root :
1613f7a81ea4SStefan Behrens 					    ERR_PTR(-ENOENT);
161470f6d82eSOmar Sandoval 	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
161570f6d82eSOmar Sandoval 		return fs_info->free_space_root ? fs_info->free_space_root :
161670f6d82eSOmar Sandoval 						  ERR_PTR(-ENOENT);
16174df27c4dSYan, Zheng again:
1618cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
161948475471SStefan Behrens 	if (root) {
1620c00869f1SMiao Xie 		if (check_ref && btrfs_root_refs(&root->root_item) == 0)
162148475471SStefan Behrens 			return ERR_PTR(-ENOENT);
16225eda7b5eSChris Mason 		return root;
162348475471SStefan Behrens 	}
16245eda7b5eSChris Mason 
1625cb517eabSMiao Xie 	root = btrfs_read_fs_root(fs_info->tree_root, location);
16265eda7b5eSChris Mason 	if (IS_ERR(root))
16275eda7b5eSChris Mason 		return root;
16283394e160SChris Mason 
1629c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1630d68fc57bSYan, Zheng 		ret = -ENOENT;
1631d68fc57bSYan, Zheng 		goto fail;
1632d68fc57bSYan, Zheng 	}
1633d68fc57bSYan, Zheng 
1634cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1635cb517eabSMiao Xie 	if (ret)
1636cb517eabSMiao Xie 		goto fail;
1637cb517eabSMiao Xie 
1638381cf658SDavid Sterba 	path = btrfs_alloc_path();
1639381cf658SDavid Sterba 	if (!path) {
1640381cf658SDavid Sterba 		ret = -ENOMEM;
1641381cf658SDavid Sterba 		goto fail;
1642381cf658SDavid Sterba 	}
16431d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
16441d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
16451d4c08e0SDavid Sterba 	key.offset = location->objectid;
16461d4c08e0SDavid Sterba 
16471d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1648381cf658SDavid Sterba 	btrfs_free_path(path);
1649d68fc57bSYan, Zheng 	if (ret < 0)
1650d68fc57bSYan, Zheng 		goto fail;
1651d68fc57bSYan, Zheng 	if (ret == 0)
165227cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1653d68fc57bSYan, Zheng 
1654cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16550f7d52f4SChris Mason 	if (ret) {
16564df27c4dSYan, Zheng 		if (ret == -EEXIST) {
16574df27c4dSYan, Zheng 			free_fs_root(root);
16584df27c4dSYan, Zheng 			goto again;
16590f7d52f4SChris Mason 		}
16604df27c4dSYan, Zheng 		goto fail;
16614df27c4dSYan, Zheng 	}
1662edbd8d4eSChris Mason 	return root;
16634df27c4dSYan, Zheng fail:
16644df27c4dSYan, Zheng 	free_fs_root(root);
16654df27c4dSYan, Zheng 	return ERR_PTR(ret);
1666edbd8d4eSChris Mason }
1667edbd8d4eSChris Mason 
166804160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
166904160088SChris Mason {
167004160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
167104160088SChris Mason 	int ret = 0;
167204160088SChris Mason 	struct btrfs_device *device;
167304160088SChris Mason 	struct backing_dev_info *bdi;
1674b7967db7SChris Mason 
16751f78160cSXiao Guangrong 	rcu_read_lock();
16761f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1677dfe25020SChris Mason 		if (!device->bdev)
1678dfe25020SChris Mason 			continue;
1679efa7c9f9SJan Kara 		bdi = device->bdev->bd_bdi;
1680ff9ea323STejun Heo 		if (bdi_congested(bdi, bdi_bits)) {
168104160088SChris Mason 			ret = 1;
168204160088SChris Mason 			break;
168304160088SChris Mason 		}
168404160088SChris Mason 	}
16851f78160cSXiao Guangrong 	rcu_read_unlock();
168604160088SChris Mason 	return ret;
168704160088SChris Mason }
168804160088SChris Mason 
16898b712842SChris Mason /*
16908b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16918b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16928b712842SChris Mason  */
16938b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1694ce9adaa5SChris Mason {
1695ce9adaa5SChris Mason 	struct bio *bio;
169697eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1697ce9adaa5SChris Mason 
169897eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1699ce9adaa5SChris Mason 	bio = end_io_wq->bio;
17008b712842SChris Mason 
17014e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1702ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1703ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
170497eb6b69SDavid Sterba 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
17054246a0b6SChristoph Hellwig 	bio_endio(bio);
1706ce9adaa5SChris Mason }
170744b8bd7eSChris Mason 
1708a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1709a74a4b97SChris Mason {
1710a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17110b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1712d0278245SMiao Xie 	int again;
1713da288d28SFilipe Manana 	struct btrfs_trans_handle *trans;
1714a74a4b97SChris Mason 
1715a74a4b97SChris Mason 	do {
1716d0278245SMiao Xie 		again = 0;
17179d1a2a3aSDavid Sterba 
1718d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
17192ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1720d0278245SMiao Xie 			goto sleep;
1721d0278245SMiao Xie 
172290c711abSZygo Blaxell 		/*
172390c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
172490c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
172590c711abSZygo Blaxell 		 */
17260b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
172790c711abSZygo Blaxell 			goto sleep;
172890c711abSZygo Blaxell 
17290b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1730d0278245SMiao Xie 			goto sleep;
1731d0278245SMiao Xie 
1732dc7f370cSMiao Xie 		/*
1733dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1734dc7f370cSMiao Xie 		 * during the above check and trylock.
1735dc7f370cSMiao Xie 		 */
17362ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
17370b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1738dc7f370cSMiao Xie 			goto sleep;
1739dc7f370cSMiao Xie 		}
1740dc7f370cSMiao Xie 
17410b246afaSJeff Mahoney 		mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
17422ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
17430b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
1744c2d6cb16SFilipe Manana 
17459d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
17460b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1747a74a4b97SChris Mason 
1748d0278245SMiao Xie 		/*
174905323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
175005323cd1SMiao Xie 		 * needn't do anything special here.
1751d0278245SMiao Xie 		 */
17520b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
175367c5e7d4SFilipe Manana 
175467c5e7d4SFilipe Manana 		/*
175567c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
175667c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
175767c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
175867c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
175967c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
176067c5e7d4SFilipe Manana 		 * unused block groups.
176167c5e7d4SFilipe Manana 		 */
17620b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1763d0278245SMiao Xie sleep:
1764838fe188SJiri Kosina 		if (!again) {
1765a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
17668929ecfaSYan, Zheng 			if (!kthread_should_stop())
1767a74a4b97SChris Mason 				schedule();
1768a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1769a74a4b97SChris Mason 		}
1770a74a4b97SChris Mason 	} while (!kthread_should_stop());
1771da288d28SFilipe Manana 
1772da288d28SFilipe Manana 	/*
1773da288d28SFilipe Manana 	 * Transaction kthread is stopped before us and wakes us up.
1774da288d28SFilipe Manana 	 * However we might have started a new transaction and COWed some
1775da288d28SFilipe Manana 	 * tree blocks when deleting unused block groups for example. So
1776da288d28SFilipe Manana 	 * make sure we commit the transaction we started to have a clean
1777da288d28SFilipe Manana 	 * shutdown when evicting the btree inode - if it has dirty pages
1778da288d28SFilipe Manana 	 * when we do the final iput() on it, eviction will trigger a
1779da288d28SFilipe Manana 	 * writeback for it which will fail with null pointer dereferences
1780da288d28SFilipe Manana 	 * since work queues and other resources were already released and
1781da288d28SFilipe Manana 	 * destroyed by the time the iput/eviction/writeback is made.
1782da288d28SFilipe Manana 	 */
1783da288d28SFilipe Manana 	trans = btrfs_attach_transaction(root);
1784da288d28SFilipe Manana 	if (IS_ERR(trans)) {
1785da288d28SFilipe Manana 		if (PTR_ERR(trans) != -ENOENT)
17860b246afaSJeff Mahoney 			btrfs_err(fs_info,
1787da288d28SFilipe Manana 				  "cleaner transaction attach returned %ld",
1788da288d28SFilipe Manana 				  PTR_ERR(trans));
1789da288d28SFilipe Manana 	} else {
1790da288d28SFilipe Manana 		int ret;
1791da288d28SFilipe Manana 
17923a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
1793da288d28SFilipe Manana 		if (ret)
17940b246afaSJeff Mahoney 			btrfs_err(fs_info,
1795da288d28SFilipe Manana 				  "cleaner open transaction commit returned %d",
1796da288d28SFilipe Manana 				  ret);
1797da288d28SFilipe Manana 	}
1798da288d28SFilipe Manana 
1799a74a4b97SChris Mason 	return 0;
1800a74a4b97SChris Mason }
1801a74a4b97SChris Mason 
1802a74a4b97SChris Mason static int transaction_kthread(void *arg)
1803a74a4b97SChris Mason {
1804a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1806a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1807a74a4b97SChris Mason 	struct btrfs_transaction *cur;
18088929ecfaSYan, Zheng 	u64 transid;
1809a74a4b97SChris Mason 	unsigned long now;
1810a74a4b97SChris Mason 	unsigned long delay;
1811914b2007SJan Kara 	bool cannot_commit;
1812a74a4b97SChris Mason 
1813a74a4b97SChris Mason 	do {
1814914b2007SJan Kara 		cannot_commit = false;
18150b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
18160b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1817a74a4b97SChris Mason 
18180b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
18190b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1820a74a4b97SChris Mason 		if (!cur) {
18210b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1822a74a4b97SChris Mason 			goto sleep;
1823a74a4b97SChris Mason 		}
182431153d81SYan Zheng 
1825a74a4b97SChris Mason 		now = get_seconds();
18264a9d8bdeSMiao Xie 		if (cur->state < TRANS_STATE_BLOCKED &&
1827a514d638SQu Wenruo 		    !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
18288b87dc17SDavid Sterba 		    (now < cur->start_time ||
18290b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
18300b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1831a74a4b97SChris Mason 			delay = HZ * 5;
1832a74a4b97SChris Mason 			goto sleep;
1833a74a4b97SChris Mason 		}
18348929ecfaSYan, Zheng 		transid = cur->transid;
18350b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
183656bec294SChris Mason 
183779787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1838354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1839914b2007SJan Kara 		if (IS_ERR(trans)) {
1840354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1841914b2007SJan Kara 				cannot_commit = true;
184279787eaaSJeff Mahoney 			goto sleep;
1843914b2007SJan Kara 		}
18448929ecfaSYan, Zheng 		if (transid == trans->transid) {
18453a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
18468929ecfaSYan, Zheng 		} else {
18473a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18488929ecfaSYan, Zheng 		}
1849a74a4b97SChris Mason sleep:
18500b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
18510b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1852a74a4b97SChris Mason 
18534e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
18540b246afaSJeff Mahoney 				      &fs_info->fs_state)))
18552ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
18568929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
18570b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1858914b2007SJan Kara 				 cannot_commit))
1859bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1860a74a4b97SChris Mason 	} while (!kthread_should_stop());
1861a74a4b97SChris Mason 	return 0;
1862a74a4b97SChris Mason }
1863a74a4b97SChris Mason 
1864af31f5e5SChris Mason /*
1865af31f5e5SChris Mason  * this will find the highest generation in the array of
1866af31f5e5SChris Mason  * root backups.  The index of the highest array is returned,
1867af31f5e5SChris Mason  * or -1 if we can't find anything.
1868af31f5e5SChris Mason  *
1869af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1870af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1871af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1872af31f5e5SChris Mason  */
1873af31f5e5SChris Mason static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1874af31f5e5SChris Mason {
1875af31f5e5SChris Mason 	u64 cur;
1876af31f5e5SChris Mason 	int newest_index = -1;
1877af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1878af31f5e5SChris Mason 	int i;
1879af31f5e5SChris Mason 
1880af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1881af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1882af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1883af31f5e5SChris Mason 		if (cur == newest_gen)
1884af31f5e5SChris Mason 			newest_index = i;
1885af31f5e5SChris Mason 	}
1886af31f5e5SChris Mason 
1887af31f5e5SChris Mason 	/* check to see if we actually wrapped around */
1888af31f5e5SChris Mason 	if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1889af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots;
1890af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1891af31f5e5SChris Mason 		if (cur == newest_gen)
1892af31f5e5SChris Mason 			newest_index = 0;
1893af31f5e5SChris Mason 	}
1894af31f5e5SChris Mason 	return newest_index;
1895af31f5e5SChris Mason }
1896af31f5e5SChris Mason 
1897af31f5e5SChris Mason 
1898af31f5e5SChris Mason /*
1899af31f5e5SChris Mason  * find the oldest backup so we know where to store new entries
1900af31f5e5SChris Mason  * in the backup array.  This will set the backup_root_index
1901af31f5e5SChris Mason  * field in the fs_info struct
1902af31f5e5SChris Mason  */
1903af31f5e5SChris Mason static void find_oldest_super_backup(struct btrfs_fs_info *info,
1904af31f5e5SChris Mason 				     u64 newest_gen)
1905af31f5e5SChris Mason {
1906af31f5e5SChris Mason 	int newest_index = -1;
1907af31f5e5SChris Mason 
1908af31f5e5SChris Mason 	newest_index = find_newest_super_backup(info, newest_gen);
1909af31f5e5SChris Mason 	/* if there was garbage in there, just move along */
1910af31f5e5SChris Mason 	if (newest_index == -1) {
1911af31f5e5SChris Mason 		info->backup_root_index = 0;
1912af31f5e5SChris Mason 	} else {
1913af31f5e5SChris Mason 		info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1914af31f5e5SChris Mason 	}
1915af31f5e5SChris Mason }
1916af31f5e5SChris Mason 
1917af31f5e5SChris Mason /*
1918af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1919af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1920af31f5e5SChris Mason  * done
1921af31f5e5SChris Mason  */
1922af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1923af31f5e5SChris Mason {
1924af31f5e5SChris Mason 	int next_backup;
1925af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1926af31f5e5SChris Mason 	int last_backup;
1927af31f5e5SChris Mason 
1928af31f5e5SChris Mason 	next_backup = info->backup_root_index;
1929af31f5e5SChris Mason 	last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1930af31f5e5SChris Mason 		BTRFS_NUM_BACKUP_ROOTS;
1931af31f5e5SChris Mason 
1932af31f5e5SChris Mason 	/*
1933af31f5e5SChris Mason 	 * just overwrite the last backup if we're at the same generation
1934af31f5e5SChris Mason 	 * this happens only at umount
1935af31f5e5SChris Mason 	 */
1936af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + last_backup;
1937af31f5e5SChris Mason 	if (btrfs_backup_tree_root_gen(root_backup) ==
1938af31f5e5SChris Mason 	    btrfs_header_generation(info->tree_root->node))
1939af31f5e5SChris Mason 		next_backup = last_backup;
1940af31f5e5SChris Mason 
1941af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1942af31f5e5SChris Mason 
1943af31f5e5SChris Mason 	/*
1944af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1945af31f5e5SChris Mason 	 * regardless of which ones we use today
1946af31f5e5SChris Mason 	 */
1947af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1948af31f5e5SChris Mason 
1949af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1950af31f5e5SChris Mason 
1951af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1952af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1953af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1954af31f5e5SChris Mason 
1955af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1956af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1957af31f5e5SChris Mason 
1958af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1959af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1960af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1961af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1962af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1963af31f5e5SChris Mason 
1964af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1965af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1966af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1967af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1968af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1969af31f5e5SChris Mason 
19707c7e82a7SChris Mason 	/*
19717c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
19727c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
19737c7e82a7SChris Mason 	 */
19747c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
19757c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
19767c7e82a7SChris Mason 					 info->fs_root->node->start);
1977af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1978af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1979af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1980af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19817c7e82a7SChris Mason 	}
1982af31f5e5SChris Mason 
1983af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1984af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1985af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1986af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1987af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1988af31f5e5SChris Mason 
1989af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1990af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1991af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1992af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1993af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1994af31f5e5SChris Mason 
1995af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1996af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1997af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1998af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1999af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2000af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2001af31f5e5SChris Mason 
2002af31f5e5SChris Mason 	/*
2003af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2004af31f5e5SChris Mason 	 * for the next commit
2005af31f5e5SChris Mason 	 */
2006af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2007af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2008af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2009af31f5e5SChris Mason }
2010af31f5e5SChris Mason 
2011af31f5e5SChris Mason /*
2012af31f5e5SChris Mason  * this copies info out of the root backup array and back into
2013af31f5e5SChris Mason  * the in-memory super block.  It is meant to help iterate through
2014af31f5e5SChris Mason  * the array, so you send it the number of backups you've already
2015af31f5e5SChris Mason  * tried and the last backup index you used.
2016af31f5e5SChris Mason  *
2017af31f5e5SChris Mason  * this returns -1 when it has tried all the backups
2018af31f5e5SChris Mason  */
2019af31f5e5SChris Mason static noinline int next_root_backup(struct btrfs_fs_info *info,
2020af31f5e5SChris Mason 				     struct btrfs_super_block *super,
2021af31f5e5SChris Mason 				     int *num_backups_tried, int *backup_index)
2022af31f5e5SChris Mason {
2023af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2024af31f5e5SChris Mason 	int newest = *backup_index;
2025af31f5e5SChris Mason 
2026af31f5e5SChris Mason 	if (*num_backups_tried == 0) {
2027af31f5e5SChris Mason 		u64 gen = btrfs_super_generation(super);
2028af31f5e5SChris Mason 
2029af31f5e5SChris Mason 		newest = find_newest_super_backup(info, gen);
2030af31f5e5SChris Mason 		if (newest == -1)
2031af31f5e5SChris Mason 			return -1;
2032af31f5e5SChris Mason 
2033af31f5e5SChris Mason 		*backup_index = newest;
2034af31f5e5SChris Mason 		*num_backups_tried = 1;
2035af31f5e5SChris Mason 	} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2036af31f5e5SChris Mason 		/* we've tried all the backups, all done */
2037af31f5e5SChris Mason 		return -1;
2038af31f5e5SChris Mason 	} else {
2039af31f5e5SChris Mason 		/* jump to the next oldest backup */
2040af31f5e5SChris Mason 		newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2041af31f5e5SChris Mason 			BTRFS_NUM_BACKUP_ROOTS;
2042af31f5e5SChris Mason 		*backup_index = newest;
2043af31f5e5SChris Mason 		*num_backups_tried += 1;
2044af31f5e5SChris Mason 	}
2045af31f5e5SChris Mason 	root_backup = super->super_roots + newest;
2046af31f5e5SChris Mason 
2047af31f5e5SChris Mason 	btrfs_set_super_generation(super,
2048af31f5e5SChris Mason 				   btrfs_backup_tree_root_gen(root_backup));
2049af31f5e5SChris Mason 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2050af31f5e5SChris Mason 	btrfs_set_super_root_level(super,
2051af31f5e5SChris Mason 				   btrfs_backup_tree_root_level(root_backup));
2052af31f5e5SChris Mason 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2053af31f5e5SChris Mason 
2054af31f5e5SChris Mason 	/*
2055af31f5e5SChris Mason 	 * fixme: the total bytes and num_devices need to match or we should
2056af31f5e5SChris Mason 	 * need a fsck
2057af31f5e5SChris Mason 	 */
2058af31f5e5SChris Mason 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2059af31f5e5SChris Mason 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2060af31f5e5SChris Mason 	return 0;
2061af31f5e5SChris Mason }
2062af31f5e5SChris Mason 
20637abadb64SLiu Bo /* helper to cleanup workers */
20647abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20657abadb64SLiu Bo {
2066dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2067afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
20685cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2069fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2070fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
20718b110e39SMiao Xie 	btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2072d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2073fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2074fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2075a8c93d4eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->submit_workers);
20765b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2077e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2078736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2079a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2080fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2081a79b7d4bSChris Mason 	btrfs_destroy_workqueue(fs_info->extent_workers);
2082a9b9477dSFilipe Manana 	/*
2083a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2084a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2085a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2086a9b9477dSFilipe Manana 	 */
2087a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2088a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
20897abadb64SLiu Bo }
20907abadb64SLiu Bo 
20912e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20922e9f5954SRashika {
20932e9f5954SRashika 	if (root) {
20942e9f5954SRashika 		free_extent_buffer(root->node);
20952e9f5954SRashika 		free_extent_buffer(root->commit_root);
20962e9f5954SRashika 		root->node = NULL;
20972e9f5954SRashika 		root->commit_root = NULL;
20982e9f5954SRashika 	}
20992e9f5954SRashika }
21002e9f5954SRashika 
2101af31f5e5SChris Mason /* helper to cleanup tree roots */
2102af31f5e5SChris Mason static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2103af31f5e5SChris Mason {
21042e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2105655b09feSJosef Bacik 
21062e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21072e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
21082e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
21092e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21102e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21112e9f5954SRashika 	if (chunk_root)
21122e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
211370f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2114af31f5e5SChris Mason }
2115af31f5e5SChris Mason 
2116faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2117171f6537SJosef Bacik {
2118171f6537SJosef Bacik 	int ret;
2119171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2120171f6537SJosef Bacik 	int i;
2121171f6537SJosef Bacik 
2122171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2123171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2124171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2125171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2126171f6537SJosef Bacik 
212727cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2128cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2129171f6537SJosef Bacik 		} else {
2130171f6537SJosef Bacik 			free_extent_buffer(gang[0]->node);
2131171f6537SJosef Bacik 			free_extent_buffer(gang[0]->commit_root);
2132b0feb9d9SMiao Xie 			btrfs_put_fs_root(gang[0]);
2133171f6537SJosef Bacik 		}
2134171f6537SJosef Bacik 	}
2135171f6537SJosef Bacik 
2136171f6537SJosef Bacik 	while (1) {
2137171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2138171f6537SJosef Bacik 					     (void **)gang, 0,
2139171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2140171f6537SJosef Bacik 		if (!ret)
2141171f6537SJosef Bacik 			break;
2142171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2143cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2144171f6537SJosef Bacik 	}
21451a4319ccSLiu Bo 
21461a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
21471a4319ccSLiu Bo 		btrfs_free_log_root_tree(NULL, fs_info);
21482ff7e61eSJeff Mahoney 		btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
21491a4319ccSLiu Bo 	}
2150171f6537SJosef Bacik }
2151af31f5e5SChris Mason 
2152638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2153638aa7edSEric Sandeen {
2154638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2155638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2156638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2157638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2158638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2159638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2160638aa7edSEric Sandeen 	fs_info->scrub_workers_refcnt = 0;
2161638aa7edSEric Sandeen }
2162638aa7edSEric Sandeen 
2163779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2164779a65a4SEric Sandeen {
2165779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2166779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2167779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2168779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2169779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2170779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2171779a65a4SEric Sandeen }
2172779a65a4SEric Sandeen 
21736bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2174f37938e0SEric Sandeen {
21752ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
21762ff7e61eSJeff Mahoney 
21772ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
21782ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2179f37938e0SEric Sandeen 	/*
2180f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2181f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2182f37938e0SEric Sandeen 	 * the devices in the system
2183f37938e0SEric Sandeen 	 */
21842ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
21852ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2186f37938e0SEric Sandeen 
21872ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2188c6100a4bSJosef Bacik 	extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
21892ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.track_uptodate = 0;
21902ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2191f37938e0SEric Sandeen 
21922ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2193f37938e0SEric Sandeen 
21942ff7e61eSJeff Mahoney 	BTRFS_I(inode)->root = fs_info->tree_root;
21952ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
21962ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
21972ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2198f37938e0SEric Sandeen }
2199f37938e0SEric Sandeen 
2200ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2201ad618368SEric Sandeen {
2202ad618368SEric Sandeen 	fs_info->dev_replace.lock_owner = 0;
2203ad618368SEric Sandeen 	atomic_set(&fs_info->dev_replace.nesting_level, 0);
2204ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
220573beece9SLiu Bo 	rwlock_init(&fs_info->dev_replace.lock);
220673beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.read_locks, 0);
220773beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.blocking_readers, 0);
2208ad618368SEric Sandeen 	init_waitqueue_head(&fs_info->replace_wait);
220973beece9SLiu Bo 	init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
2210ad618368SEric Sandeen }
2211ad618368SEric Sandeen 
2212f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2213f9e92e40SEric Sandeen {
2214f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2215f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2216f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2217f9e92e40SEric Sandeen 	fs_info->qgroup_op_tree = RB_ROOT;
2218f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2219f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2220f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2221d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2222f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2223f9e92e40SEric Sandeen }
2224f9e92e40SEric Sandeen 
22252a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
22262a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
22272a458198SEric Sandeen {
2228f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22296f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22302a458198SEric Sandeen 
22312a458198SEric Sandeen 	fs_info->workers =
2232cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2233cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22342a458198SEric Sandeen 
22352a458198SEric Sandeen 	fs_info->delalloc_workers =
2236cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2237cb001095SJeff Mahoney 				      flags, max_active, 2);
22382a458198SEric Sandeen 
22392a458198SEric Sandeen 	fs_info->flush_workers =
2240cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2241cb001095SJeff Mahoney 				      flags, max_active, 0);
22422a458198SEric Sandeen 
22432a458198SEric Sandeen 	fs_info->caching_workers =
2244cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
22452a458198SEric Sandeen 
22462a458198SEric Sandeen 	/*
22472a458198SEric Sandeen 	 * a higher idle thresh on the submit workers makes it much more
22482a458198SEric Sandeen 	 * likely that bios will be send down in a sane order to the
22492a458198SEric Sandeen 	 * devices
22502a458198SEric Sandeen 	 */
22512a458198SEric Sandeen 	fs_info->submit_workers =
2252cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "submit", flags,
22532a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
22542a458198SEric Sandeen 					    max_active), 64);
22552a458198SEric Sandeen 
22562a458198SEric Sandeen 	fs_info->fixup_workers =
2257cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
22582a458198SEric Sandeen 
22592a458198SEric Sandeen 	/*
22602a458198SEric Sandeen 	 * endios are largely parallel and should have a very
22612a458198SEric Sandeen 	 * low idle thresh
22622a458198SEric Sandeen 	 */
22632a458198SEric Sandeen 	fs_info->endio_workers =
2264cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
22652a458198SEric Sandeen 	fs_info->endio_meta_workers =
2266cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2267cb001095SJeff Mahoney 				      max_active, 4);
22682a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2269cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2270cb001095SJeff Mahoney 				      max_active, 2);
22712a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2272cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2273cb001095SJeff Mahoney 				      max_active, 4);
22742a458198SEric Sandeen 	fs_info->endio_repair_workers =
2275cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
22762a458198SEric Sandeen 	fs_info->rmw_workers =
2277cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
22782a458198SEric Sandeen 	fs_info->endio_write_workers =
2279cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2280cb001095SJeff Mahoney 				      max_active, 2);
22812a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2282cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2283cb001095SJeff Mahoney 				      max_active, 0);
22842a458198SEric Sandeen 	fs_info->delayed_workers =
2285cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2286cb001095SJeff Mahoney 				      max_active, 0);
22872a458198SEric Sandeen 	fs_info->readahead_workers =
2288cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2289cb001095SJeff Mahoney 				      max_active, 2);
22902a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2291cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
22922a458198SEric Sandeen 	fs_info->extent_workers =
2293cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
22942a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
22952a458198SEric Sandeen 					    max_active), 8);
22962a458198SEric Sandeen 
22972a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
22982a458198SEric Sandeen 	      fs_info->submit_workers && fs_info->flush_workers &&
22992a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
23002a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
23012a458198SEric Sandeen 	      fs_info->endio_repair_workers &&
23022a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
23032a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
23042a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
23052a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
23062a458198SEric Sandeen 	      fs_info->extent_workers &&
23072a458198SEric Sandeen 	      fs_info->qgroup_rescan_workers)) {
23082a458198SEric Sandeen 		return -ENOMEM;
23092a458198SEric Sandeen 	}
23102a458198SEric Sandeen 
23112a458198SEric Sandeen 	return 0;
23122a458198SEric Sandeen }
23132a458198SEric Sandeen 
231463443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
231563443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
231663443bf5SEric Sandeen {
231763443bf5SEric Sandeen 	int ret;
231863443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
231963443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
232063443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2321581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
232263443bf5SEric Sandeen 
232363443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2324f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
232563443bf5SEric Sandeen 		return -EIO;
232663443bf5SEric Sandeen 	}
232763443bf5SEric Sandeen 
232874e4d827SDavid Sterba 	log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
232963443bf5SEric Sandeen 	if (!log_tree_root)
233063443bf5SEric Sandeen 		return -ENOMEM;
233163443bf5SEric Sandeen 
2332da17066cSJeff Mahoney 	__setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
233363443bf5SEric Sandeen 
23342ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
2335581c1760SQu Wenruo 					      fs_info->generation + 1,
2336581c1760SQu Wenruo 					      level, NULL);
233764c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2338f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
23390eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
234064c043deSLiu Bo 		kfree(log_tree_root);
23410eeff236SLiu Bo 		return ret;
234264c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2343f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
234463443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
234563443bf5SEric Sandeen 		kfree(log_tree_root);
234663443bf5SEric Sandeen 		return -EIO;
234763443bf5SEric Sandeen 	}
234863443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
234963443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
235063443bf5SEric Sandeen 	if (ret) {
23510b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
235263443bf5SEric Sandeen 				      "Failed to recover log tree");
235363443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
235463443bf5SEric Sandeen 		kfree(log_tree_root);
235563443bf5SEric Sandeen 		return ret;
235663443bf5SEric Sandeen 	}
235763443bf5SEric Sandeen 
2358bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
23596bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
236063443bf5SEric Sandeen 		if (ret)
236163443bf5SEric Sandeen 			return ret;
236263443bf5SEric Sandeen 	}
236363443bf5SEric Sandeen 
236463443bf5SEric Sandeen 	return 0;
236563443bf5SEric Sandeen }
236663443bf5SEric Sandeen 
23676bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
23684bbcaa64SEric Sandeen {
23696bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2370a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
23714bbcaa64SEric Sandeen 	struct btrfs_key location;
23724bbcaa64SEric Sandeen 	int ret;
23734bbcaa64SEric Sandeen 
23746bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
23756bccf3abSJeff Mahoney 
23764bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
23774bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
23784bbcaa64SEric Sandeen 	location.offset = 0;
23794bbcaa64SEric Sandeen 
2380a4f3d2c4SDavid Sterba 	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 	}
2385a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2386a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
23874bbcaa64SEric Sandeen 
23884bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2389a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2390f50f4353SLiu Bo 	if (IS_ERR(root)) {
2391f50f4353SLiu Bo 		ret = PTR_ERR(root);
2392f50f4353SLiu Bo 		goto out;
2393f50f4353SLiu Bo 	}
2394a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2395a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
23964bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
23974bbcaa64SEric Sandeen 
23984bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2399a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2400f50f4353SLiu Bo 	if (IS_ERR(root)) {
2401f50f4353SLiu Bo 		ret = PTR_ERR(root);
2402f50f4353SLiu Bo 		goto out;
2403f50f4353SLiu Bo 	}
2404a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2405a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
24064bbcaa64SEric Sandeen 
24074bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2408a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2409a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2410a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2411afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2412a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
24134bbcaa64SEric Sandeen 	}
24144bbcaa64SEric Sandeen 
24154bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2416a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2417a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2418a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
24194bbcaa64SEric Sandeen 		if (ret != -ENOENT)
2420f50f4353SLiu Bo 			goto out;
24214bbcaa64SEric Sandeen 	} else {
2422a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2423a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
24244bbcaa64SEric Sandeen 	}
24254bbcaa64SEric Sandeen 
242670f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
242770f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
242870f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2429f50f4353SLiu Bo 		if (IS_ERR(root)) {
2430f50f4353SLiu Bo 			ret = PTR_ERR(root);
2431f50f4353SLiu Bo 			goto out;
2432f50f4353SLiu Bo 		}
243370f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
243470f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
243570f6d82eSOmar Sandoval 	}
243670f6d82eSOmar Sandoval 
24374bbcaa64SEric Sandeen 	return 0;
2438f50f4353SLiu Bo out:
2439f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2440f50f4353SLiu Bo 		   location.objectid, ret);
2441f50f4353SLiu Bo 	return ret;
24424bbcaa64SEric Sandeen }
24434bbcaa64SEric Sandeen 
2444ad2b2c80SAl Viro int open_ctree(struct super_block *sb,
2445dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
2446dfe25020SChris Mason 	       char *options)
2447eb60ceacSChris Mason {
2448db94535dSChris Mason 	u32 sectorsize;
2449db94535dSChris Mason 	u32 nodesize;
245087ee04ebSChris Mason 	u32 stripesize;
245184234f3aSYan Zheng 	u64 generation;
2452f2b636e8SJosef Bacik 	u64 features;
24533de4586cSChris Mason 	struct btrfs_key location;
2454a061fc8dSChris Mason 	struct buffer_head *bh;
24554d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
2456815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2457f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
24584d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
2459eb60ceacSChris Mason 	int ret;
2460e58ca020SYan 	int err = -EINVAL;
2461af31f5e5SChris Mason 	int num_backups_tried = 0;
2462af31f5e5SChris Mason 	int backup_index = 0;
24636675df31SOmar Sandoval 	int clear_free_space_tree = 0;
2464581c1760SQu Wenruo 	int level;
24654543df7eSChris Mason 
246674e4d827SDavid Sterba 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
246774e4d827SDavid Sterba 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2468cb517eabSMiao Xie 	if (!tree_root || !chunk_root) {
246939279cc3SChris Mason 		err = -ENOMEM;
247039279cc3SChris Mason 		goto fail;
247139279cc3SChris Mason 	}
247276dda93cSYan, Zheng 
247376dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
247476dda93cSYan, Zheng 	if (ret) {
247576dda93cSYan, Zheng 		err = ret;
247676dda93cSYan, Zheng 		goto fail;
247776dda93cSYan, Zheng 	}
247876dda93cSYan, Zheng 
2479908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2480e2d84521SMiao Xie 	if (ret) {
2481e2d84521SMiao Xie 		err = ret;
24829e11ceeeSJan Kara 		goto fail_srcu;
2483e2d84521SMiao Xie 	}
248409cbfeafSKirill A. Shutemov 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2485e2d84521SMiao Xie 					(1 + ilog2(nr_cpu_ids));
2486e2d84521SMiao Xie 
2487908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2488963d678bSMiao Xie 	if (ret) {
2489963d678bSMiao Xie 		err = ret;
2490963d678bSMiao Xie 		goto fail_dirty_metadata_bytes;
2491963d678bSMiao Xie 	}
2492963d678bSMiao Xie 
2493908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2494c404e0dcSMiao Xie 	if (ret) {
2495c404e0dcSMiao Xie 		err = ret;
2496c404e0dcSMiao Xie 		goto fail_delalloc_bytes;
2497c404e0dcSMiao Xie 	}
2498c404e0dcSMiao Xie 
249976dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2500f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
25018fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2502facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
250324bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2504eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
250511833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
250675cb379dSJeff Mahoney 	INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
250775cb379dSJeff Mahoney 	spin_lock_init(&fs_info->pending_raid_kobjs_lock);
2508eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2509a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
251076dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
251124bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
25124cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2513f29021b2SJan Schmidt 	spin_lock_init(&fs_info->tree_mod_seq_lock);
2514ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2515fcebe456SJosef Bacik 	spin_lock_init(&fs_info->qgroup_op_lock);
2516f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
251747ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2518f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2519d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
252067c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
25217585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2522573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2523c2d6cb16SFilipe Manana 	mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2524de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
252519c00ddcSChris Mason 
25260b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
25276324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2528f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
252947ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
25300b86a832SChris Mason 	btrfs_mapping_init(&fs_info->mapping_tree);
253166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
253266d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
253366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
253466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
253566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
253666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
253766d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2538771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
25394cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2540fcebe456SJosef Bacik 	atomic_set(&fs_info->qgroup_op_seq, 0);
25412fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2542fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2543e20d96d6SChris Mason 	fs_info->sb = sb;
254495ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
25459ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
25464cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2547a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2548f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
25498b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2550f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
255190519d66SArne Jansen 	/* readahead state */
2552d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
255390519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2554fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2555c8b97818SChris Mason 
2556b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2557b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
25580afbaf8cSChris Mason 
2559199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2560199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
256169fe2d75SJosef Bacik 
256269fe2d75SJosef Bacik 	fs_info->btree_inode = new_inode(sb);
256369fe2d75SJosef Bacik 	if (!fs_info->btree_inode) {
256469fe2d75SJosef Bacik 		err = -ENOMEM;
256569fe2d75SJosef Bacik 		goto fail_bio_counter;
256669fe2d75SJosef Bacik 	}
256769fe2d75SJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
256869fe2d75SJosef Bacik 
256916cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
257074e4d827SDavid Sterba 					GFP_KERNEL);
257116cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
257216cdcec7SMiao Xie 		err = -ENOMEM;
257316cdcec7SMiao Xie 		goto fail_iput;
257416cdcec7SMiao Xie 	}
257516cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
25763eaa2885SChris Mason 
2577638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
257821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
257921adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
258021adbd5cSStefan Behrens #endif
2581779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
258221c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2583a2de733cSArne Jansen 
25849f6d2510SDavid Sterba 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
25859f6d2510SDavid Sterba 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2586a061fc8dSChris Mason 
25876bccf3abSJeff Mahoney 	btrfs_init_btree_inode(fs_info);
258839279cc3SChris Mason 
2589e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
25906bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2591a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
2592925baeddSChris Mason 
2593c6100a4bSJosef Bacik 	extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2594c6100a4bSJosef Bacik 	extent_io_tree_init(&fs_info->freed_extents[1], NULL);
259511833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2596afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2597509659cdSChris Mason 
25985a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
259979154b1bSChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2600925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2601a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2602a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
26031bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
26049e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2605c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
260676dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2607803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2608fa9c0d79SChris Mason 
2609ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2610f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2611416ac51dSArne Jansen 
2612fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2613fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2614fa9c0d79SChris Mason 
2615e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2616f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2617bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
26184854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
26193768f368SChris Mason 
262004216820SFilipe Manana 	INIT_LIST_HEAD(&fs_info->pinned_chunks);
262104216820SFilipe Manana 
2622da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2623da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2624da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2625da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2626da17066cSJeff Mahoney 
262753b381b3SDavid Woodhouse 	ret = btrfs_alloc_stripe_hash_table(fs_info);
262853b381b3SDavid Woodhouse 	if (ret) {
262983c8266aSDavid Sterba 		err = ret;
263053b381b3SDavid Woodhouse 		goto fail_alloc;
263153b381b3SDavid Woodhouse 	}
263253b381b3SDavid Woodhouse 
2633da17066cSJeff Mahoney 	__setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
26347eccb903SChris Mason 
26353c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
26361104a885SDavid Sterba 
26371104a885SDavid Sterba 	/*
26381104a885SDavid Sterba 	 * Read super block and check the signature bytes only
26391104a885SDavid Sterba 	 */
2640a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
264192fc03fbSAnand Jain 	if (IS_ERR(bh)) {
264292fc03fbSAnand Jain 		err = PTR_ERR(bh);
264316cdcec7SMiao Xie 		goto fail_alloc;
264420b45077SDave Young 	}
264539279cc3SChris Mason 
26461104a885SDavid Sterba 	/*
26471104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
26481104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
26491104a885SDavid Sterba 	 */
2650ab8d0fc4SJeff Mahoney 	if (btrfs_check_super_csum(fs_info, bh->b_data)) {
265105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
26521104a885SDavid Sterba 		err = -EINVAL;
2653b2acdddfSAnand Jain 		brelse(bh);
26541104a885SDavid Sterba 		goto fail_alloc;
26551104a885SDavid Sterba 	}
26561104a885SDavid Sterba 
26571104a885SDavid Sterba 	/*
26581104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
26591104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
26601104a885SDavid Sterba 	 * the whole block of INFO_SIZE
26611104a885SDavid Sterba 	 */
26626c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
26636c41761fSDavid Sterba 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
26646c41761fSDavid Sterba 	       sizeof(*fs_info->super_for_commit));
2665a061fc8dSChris Mason 	brelse(bh);
26665f39d397SChris Mason 
26676c41761fSDavid Sterba 	memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
26680b86a832SChris Mason 
26693d3a126aSDavid Sterba 	ret = btrfs_check_super_valid(fs_info);
26701104a885SDavid Sterba 	if (ret) {
267105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
26721104a885SDavid Sterba 		err = -EINVAL;
26731104a885SDavid Sterba 		goto fail_alloc;
26741104a885SDavid Sterba 	}
26751104a885SDavid Sterba 
26766c41761fSDavid Sterba 	disk_super = fs_info->super_copy;
26770f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
267816cdcec7SMiao Xie 		goto fail_alloc;
26790f7d52f4SChris Mason 
2680acce952bSliubo 	/* check FS state, whether FS is broken. */
268187533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
268287533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2683acce952bSliubo 
268475e7cb7fSLiu Bo 	/*
2685af31f5e5SChris Mason 	 * run through our array of backup supers and setup
2686af31f5e5SChris Mason 	 * our ring pointer to the oldest one
2687af31f5e5SChris Mason 	 */
2688af31f5e5SChris Mason 	generation = btrfs_super_generation(disk_super);
2689af31f5e5SChris Mason 	find_oldest_super_backup(fs_info, generation);
2690af31f5e5SChris Mason 
2691af31f5e5SChris Mason 	/*
269275e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
269375e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
269475e7cb7fSLiu Bo 	 */
269575e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
269675e7cb7fSLiu Bo 
26972ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
26982b82032cSYan Zheng 	if (ret) {
26992b82032cSYan Zheng 		err = ret;
270016cdcec7SMiao Xie 		goto fail_alloc;
27012b82032cSYan Zheng 	}
2702dfe25020SChris Mason 
2703f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2704f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2705f2b636e8SJosef Bacik 	if (features) {
270605135f59SDavid Sterba 		btrfs_err(fs_info,
270705135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
2708c1c9ff7cSGeert Uytterhoeven 		    features);
2709f2b636e8SJosef Bacik 		err = -EINVAL;
271016cdcec7SMiao Xie 		goto fail_alloc;
2711f2b636e8SJosef Bacik 	}
2712f2b636e8SJosef Bacik 
27135d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
27145d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
27150b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2716a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
27175c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
27185c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2719727011e0SChris Mason 
27203173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
272105135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
27223173a18fSJosef Bacik 
2723727011e0SChris Mason 	/*
2724727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2725727011e0SChris Mason 	 * they are bigger than the page size
2726727011e0SChris Mason 	 */
272709cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2728727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
272905135f59SDavid Sterba 			btrfs_info(fs_info,
273005135f59SDavid Sterba 				"flagging fs with big metadata feature");
2731727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2732727011e0SChris Mason 	}
2733727011e0SChris Mason 
2734bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2735bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2736b7f67055SChandan Rajendra 	stripesize = sectorsize;
2737707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2738963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2739bc3f116fSChris Mason 
2740da17066cSJeff Mahoney 	/* Cache block sizes */
2741da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
2742da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
2743da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
2744da17066cSJeff Mahoney 
2745bc3f116fSChris Mason 	/*
2746bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2747bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2748bc3f116fSChris Mason 	 */
2749bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2750707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
275105135f59SDavid Sterba 		btrfs_err(fs_info,
275205135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
275305135f59SDavid Sterba 			nodesize, sectorsize);
2754bc3f116fSChris Mason 		goto fail_alloc;
2755bc3f116fSChris Mason 	}
2756bc3f116fSChris Mason 
2757ceda0864SMiao Xie 	/*
2758ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
2759ceda0864SMiao Xie 	 * update the flag.
2760ceda0864SMiao Xie 	 */
27615d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
27625d4f98a2SYan Zheng 
2763f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2764f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2765bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
276605135f59SDavid Sterba 		btrfs_err(fs_info,
276705135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
2768c1c9ff7cSGeert Uytterhoeven 		       features);
2769f2b636e8SJosef Bacik 		err = -EINVAL;
277016cdcec7SMiao Xie 		goto fail_alloc;
2771f2b636e8SJosef Bacik 	}
277261d92c32SChris Mason 
27732a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
27742a458198SEric Sandeen 	if (ret) {
27752a458198SEric Sandeen 		err = ret;
27760dc3b84aSJosef Bacik 		goto fail_sb_buffer;
27770dc3b84aSJosef Bacik 	}
27784543df7eSChris Mason 
27799e11ceeeSJan Kara 	sb->s_bdi->congested_fn = btrfs_congested_fn;
27809e11ceeeSJan Kara 	sb->s_bdi->congested_data = fs_info;
27819e11ceeeSJan Kara 	sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2782d4417e22SNikolay Borisov 	sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
27839e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
27849e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
27854575c9ccSChris Mason 
2786a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
2787a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
2788ee87cf5eSAnand Jain 	memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
2789db94535dSChris Mason 
2790925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
27916bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
2792925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
279384eed90fSChris Mason 	if (ret) {
279405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
27955d4f98a2SYan Zheng 		goto fail_sb_buffer;
279684eed90fSChris Mason 	}
27970b86a832SChris Mason 
279884234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
2799581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
28000b86a832SChris Mason 
2801da17066cSJeff Mahoney 	__setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
28020b86a832SChris Mason 
28032ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
28040b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
2805581c1760SQu Wenruo 					   generation, level, NULL);
280664c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
280764c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
280805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
2809e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
2810e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
281195ab1f64SZhao Lei 		chunk_root->node = NULL;
2812af31f5e5SChris Mason 		goto fail_tree_roots;
281383121942SDavid Woodhouse 	}
28145d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
28155d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
28160b86a832SChris Mason 
2817e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2818b308bc2fSGeert Uytterhoeven 	   btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2819e17cade2SChris Mason 
28205b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
28212b82032cSYan Zheng 	if (ret) {
282205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
2823af31f5e5SChris Mason 		goto fail_tree_roots;
28242b82032cSYan Zheng 	}
28250b86a832SChris Mason 
28268dabb742SStefan Behrens 	/*
28279b99b115SAnand Jain 	 * Keep the devid that is marked to be the target device for the
28289b99b115SAnand Jain 	 * device replace procedure
28298dabb742SStefan Behrens 	 */
28309b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 0);
2831dfe25020SChris Mason 
2832a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
283305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
2834a6b0d5c8SChris Mason 		goto fail_tree_roots;
2835a6b0d5c8SChris Mason 	}
2836a6b0d5c8SChris Mason 
2837af31f5e5SChris Mason retry_root_backup:
283884234f3aSYan Zheng 	generation = btrfs_super_generation(disk_super);
2839581c1760SQu Wenruo 	level = btrfs_super_root_level(disk_super);
28400b86a832SChris Mason 
28412ff7e61eSJeff Mahoney 	tree_root->node = read_tree_block(fs_info,
2842db94535dSChris Mason 					  btrfs_super_root(disk_super),
2843581c1760SQu Wenruo 					  generation, level, NULL);
284464c043deSLiu Bo 	if (IS_ERR(tree_root->node) ||
284564c043deSLiu Bo 	    !extent_buffer_uptodate(tree_root->node)) {
284605135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to read tree root");
2847e5fffbacSchandan 		if (!IS_ERR(tree_root->node))
2848e5fffbacSchandan 			free_extent_buffer(tree_root->node);
284995ab1f64SZhao Lei 		tree_root->node = NULL;
2850af31f5e5SChris Mason 		goto recovery_tree_root;
285183121942SDavid Woodhouse 	}
2852af31f5e5SChris Mason 
28535d4f98a2SYan Zheng 	btrfs_set_root_node(&tree_root->root_item, tree_root->node);
28545d4f98a2SYan Zheng 	tree_root->commit_root = btrfs_root_node(tree_root);
285569e9c6c6SStefan Behrens 	btrfs_set_root_refs(&tree_root->root_item, 1);
2856db94535dSChris Mason 
2857f32e48e9SChandan Rajendra 	mutex_lock(&tree_root->objectid_mutex);
2858f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(tree_root,
2859f32e48e9SChandan Rajendra 					&tree_root->highest_objectid);
2860f32e48e9SChandan Rajendra 	if (ret) {
2861f32e48e9SChandan Rajendra 		mutex_unlock(&tree_root->objectid_mutex);
2862f32e48e9SChandan Rajendra 		goto recovery_tree_root;
2863f32e48e9SChandan Rajendra 	}
2864f32e48e9SChandan Rajendra 
2865f32e48e9SChandan Rajendra 	ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2866f32e48e9SChandan Rajendra 
2867f32e48e9SChandan Rajendra 	mutex_unlock(&tree_root->objectid_mutex);
2868f32e48e9SChandan Rajendra 
28696bccf3abSJeff Mahoney 	ret = btrfs_read_roots(fs_info);
28704bbcaa64SEric Sandeen 	if (ret)
2871af31f5e5SChris Mason 		goto recovery_tree_root;
2872f7a81ea4SStefan Behrens 
28738929ecfaSYan, Zheng 	fs_info->generation = generation;
28748929ecfaSYan, Zheng 	fs_info->last_trans_committed = generation;
28758929ecfaSYan, Zheng 
287668310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
287768310a5eSIlya Dryomov 	if (ret) {
287805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
287968310a5eSIlya Dryomov 		goto fail_block_groups;
288068310a5eSIlya Dryomov 	}
288168310a5eSIlya Dryomov 
2882733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
2883733f4fbbSStefan Behrens 	if (ret) {
288405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
2885733f4fbbSStefan Behrens 		goto fail_block_groups;
2886733f4fbbSStefan Behrens 	}
2887733f4fbbSStefan Behrens 
28888dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
28898dabb742SStefan Behrens 	if (ret) {
289005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
28918dabb742SStefan Behrens 		goto fail_block_groups;
28928dabb742SStefan Behrens 	}
28938dabb742SStefan Behrens 
28949b99b115SAnand Jain 	btrfs_free_extra_devids(fs_devices, 1);
28958dabb742SStefan Behrens 
2896b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
2897b7c35e81SAnand Jain 	if (ret) {
289805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
289905135f59SDavid Sterba 				ret);
2900b7c35e81SAnand Jain 		goto fail_block_groups;
2901b7c35e81SAnand Jain 	}
2902b7c35e81SAnand Jain 
2903b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_device(fs_devices);
2904b7c35e81SAnand Jain 	if (ret) {
290505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs device interface: %d",
290605135f59SDavid Sterba 				ret);
2907b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
2908b7c35e81SAnand Jain 	}
2909b7c35e81SAnand Jain 
291096f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
29115ac1d209SJeff Mahoney 	if (ret) {
291205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
2913b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
29145ac1d209SJeff Mahoney 	}
29155ac1d209SJeff Mahoney 
2916c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
2917c59021f8Sliubo 	if (ret) {
291805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
29192365dd3cSAnand Jain 		goto fail_sysfs;
2920c59021f8Sliubo 	}
2921c59021f8Sliubo 
29225b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
29231b1d1f66SJosef Bacik 	if (ret) {
292405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
29252365dd3cSAnand Jain 		goto fail_sysfs;
29261b1d1f66SJosef Bacik 	}
29274330e183SQu Wenruo 
29286528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
292905135f59SDavid Sterba 		btrfs_warn(fs_info,
29304330e183SQu Wenruo 		"writeable mount is not allowed due to too many missing devices");
29312365dd3cSAnand Jain 		goto fail_sysfs;
2932292fd7fcSStefan Behrens 	}
29339078a3e1SChris Mason 
2934a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2935a74a4b97SChris Mason 					       "btrfs-cleaner");
293657506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
29372365dd3cSAnand Jain 		goto fail_sysfs;
2938a74a4b97SChris Mason 
2939a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
2940a74a4b97SChris Mason 						   tree_root,
2941a74a4b97SChris Mason 						   "btrfs-transaction");
294257506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
29433f157a2fSChris Mason 		goto fail_cleaner;
2944a74a4b97SChris Mason 
2945583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
2946c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
2947583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
2948c289811cSChris Mason 	}
2949c289811cSChris Mason 
2950572d9ab7SDavid Sterba 	/*
295101327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
2952572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
2953572d9ab7SDavid Sterba 	 */
2954572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
29553818aea2SQu Wenruo 
295621adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
29570b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
29582ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
29590b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
296021adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
296121adbd5cSStefan Behrens 				    1 : 0,
296221adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
296321adbd5cSStefan Behrens 		if (ret)
296405135f59SDavid Sterba 			btrfs_warn(fs_info,
296505135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
296605135f59SDavid Sterba 				ret);
296721adbd5cSStefan Behrens 	}
296821adbd5cSStefan Behrens #endif
2969bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
2970bcef60f2SArne Jansen 	if (ret)
2971bcef60f2SArne Jansen 		goto fail_trans_kthread;
297221adbd5cSStefan Behrens 
2973fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
2974fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
2975fd708b81SJosef Bacik 
297696da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
297796da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
29780b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
297963443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
298079787eaaSJeff Mahoney 		if (ret) {
298163443bf5SEric Sandeen 			err = ret;
298228c16cbbSWang Shilong 			goto fail_qgroup;
2983e556ce2cSYan Zheng 		}
2984e02119d5SChris Mason 	}
29851a40e23bSZheng Yan 
29866bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
298779787eaaSJeff Mahoney 	if (ret)
298828c16cbbSWang Shilong 		goto fail_qgroup;
298976dda93cSYan, Zheng 
2990bc98a42cSDavid Howells 	if (!sb_rdonly(sb)) {
2991d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
299244c44af2SIlya Dryomov 		if (ret)
299328c16cbbSWang Shilong 			goto fail_qgroup;
299490c711abSZygo Blaxell 
299590c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
29965d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
299790c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
2998d7ce5843SMiao Xie 		if (ret < 0) {
299905135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
300005135f59SDavid Sterba 					ret);
3001d7ce5843SMiao Xie 			err = -EINVAL;
3002bcef60f2SArne Jansen 			goto fail_qgroup;
3003d7ce5843SMiao Xie 		}
30047c2ca468SChris Mason 	}
30051a40e23bSZheng Yan 
30063de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
30073de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
3008cb517eabSMiao Xie 	location.offset = 0;
30093de4586cSChris Mason 
30103de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
30113140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
30123140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3013f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3014bcef60f2SArne Jansen 		goto fail_qgroup;
30153140c9a3SDan Carpenter 	}
3016c289811cSChris Mason 
3017bc98a42cSDavid Howells 	if (sb_rdonly(sb))
30182b6ba629SIlya Dryomov 		return 0;
30192b6ba629SIlya Dryomov 
3020f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3021f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
30226675df31SOmar Sandoval 		clear_free_space_tree = 1;
30236675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
30246675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
30256675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
30266675df31SOmar Sandoval 		clear_free_space_tree = 1;
30276675df31SOmar Sandoval 	}
30286675df31SOmar Sandoval 
30296675df31SOmar Sandoval 	if (clear_free_space_tree) {
3030f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3031f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3032f8d468a1SOmar Sandoval 		if (ret) {
3033f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3034f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
30356bccf3abSJeff Mahoney 			close_ctree(fs_info);
3036f8d468a1SOmar Sandoval 			return ret;
3037f8d468a1SOmar Sandoval 		}
3038f8d468a1SOmar Sandoval 	}
3039f8d468a1SOmar Sandoval 
30400b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3041511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
304205135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3043511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3044511711afSChris Mason 		if (ret) {
304505135f59SDavid Sterba 			btrfs_warn(fs_info,
304605135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
30476bccf3abSJeff Mahoney 			close_ctree(fs_info);
3048511711afSChris Mason 			return ret;
3049511711afSChris Mason 		}
3050511711afSChris Mason 	}
3051511711afSChris Mason 
3052e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
30532b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
30542b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
30552b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
30566bccf3abSJeff Mahoney 		close_ctree(fs_info);
30572b6ba629SIlya Dryomov 		return ret;
30582b6ba629SIlya Dryomov 	}
3059e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
306059641015SIlya Dryomov 
30612b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
30622b6ba629SIlya Dryomov 	if (ret) {
306305135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
30646bccf3abSJeff Mahoney 		close_ctree(fs_info);
30652b6ba629SIlya Dryomov 		return ret;
3066e3acc2a6SJosef Bacik 	}
3067e3acc2a6SJosef Bacik 
30688dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
30698dabb742SStefan Behrens 	if (ret) {
307005135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
30716bccf3abSJeff Mahoney 		close_ctree(fs_info);
30728dabb742SStefan Behrens 		return ret;
30738dabb742SStefan Behrens 	}
30748dabb742SStefan Behrens 
3075b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3076b382a324SJan Schmidt 
30774bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
307805135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3079f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3080f7a81ea4SStefan Behrens 		if (ret) {
308105135f59SDavid Sterba 			btrfs_warn(fs_info,
308205135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
30836bccf3abSJeff Mahoney 			close_ctree(fs_info);
3084f7a81ea4SStefan Behrens 			return ret;
3085f7a81ea4SStefan Behrens 		}
30860b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
30874bbcaa64SEric Sandeen 		   fs_info->generation !=
30884bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
308905135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
309070f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
309170f80175SStefan Behrens 		if (ret) {
309205135f59SDavid Sterba 			btrfs_warn(fs_info,
309305135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
30946bccf3abSJeff Mahoney 			close_ctree(fs_info);
309570f80175SStefan Behrens 			return ret;
309670f80175SStefan Behrens 		}
309770f80175SStefan Behrens 	} else {
3098afcdd129SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3099f7a81ea4SStefan Behrens 	}
3100afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
310147ab2a6cSJosef Bacik 
31028dcddfa0SQu Wenruo 	/*
31038dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
31048dcddfa0SQu Wenruo 	 * no need to keep the flag
31058dcddfa0SQu Wenruo 	 */
31068dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
31078dcddfa0SQu Wenruo 
3108ad2b2c80SAl Viro 	return 0;
310939279cc3SChris Mason 
3110bcef60f2SArne Jansen fail_qgroup:
3111bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
31127c2ca468SChris Mason fail_trans_kthread:
31137c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
31142ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3115faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
31163f157a2fSChris Mason fail_cleaner:
3117a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
31187c2ca468SChris Mason 
31197c2ca468SChris Mason 	/*
31207c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
31217c2ca468SChris Mason 	 * kthreads
31227c2ca468SChris Mason 	 */
31237c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
31247c2ca468SChris Mason 
31252365dd3cSAnand Jain fail_sysfs:
31266618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
31272365dd3cSAnand Jain 
3128b7c35e81SAnand Jain fail_fsdev_sysfs:
3129b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3130b7c35e81SAnand Jain 
31311b1d1f66SJosef Bacik fail_block_groups:
313254067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3133af31f5e5SChris Mason 
3134af31f5e5SChris Mason fail_tree_roots:
3135af31f5e5SChris Mason 	free_root_pointers(fs_info, 1);
31362b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3137af31f5e5SChris Mason 
313839279cc3SChris Mason fail_sb_buffer:
31397abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
31405cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
314116cdcec7SMiao Xie fail_alloc:
31424543df7eSChris Mason fail_iput:
3143586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3144586e46e2SIlya Dryomov 
31454543df7eSChris Mason 	iput(fs_info->btree_inode);
3146c404e0dcSMiao Xie fail_bio_counter:
3147c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
3148963d678bSMiao Xie fail_delalloc_bytes:
3149963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3150e2d84521SMiao Xie fail_dirty_metadata_bytes:
3151e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
315276dda93cSYan, Zheng fail_srcu:
315376dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
31547e662854SQinghuang Feng fail:
315553b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3156586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3157ad2b2c80SAl Viro 	return err;
3158af31f5e5SChris Mason 
3159af31f5e5SChris Mason recovery_tree_root:
31600b246afaSJeff Mahoney 	if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3161af31f5e5SChris Mason 		goto fail_tree_roots;
3162af31f5e5SChris Mason 
3163af31f5e5SChris Mason 	free_root_pointers(fs_info, 0);
3164af31f5e5SChris Mason 
3165af31f5e5SChris Mason 	/* don't use the log in recovery mode, it won't be valid */
3166af31f5e5SChris Mason 	btrfs_set_super_log_root(disk_super, 0);
3167af31f5e5SChris Mason 
3168af31f5e5SChris Mason 	/* we can't trust the free space cache either */
3169af31f5e5SChris Mason 	btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3170af31f5e5SChris Mason 
3171af31f5e5SChris Mason 	ret = next_root_backup(fs_info, fs_info->super_copy,
3172af31f5e5SChris Mason 			       &num_backups_tried, &backup_index);
3173af31f5e5SChris Mason 	if (ret == -1)
3174af31f5e5SChris Mason 		goto fail_block_groups;
3175af31f5e5SChris Mason 	goto retry_root_backup;
3176eb60ceacSChris Mason }
3177663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3178eb60ceacSChris Mason 
3179f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3180f2984462SChris Mason {
3181f2984462SChris Mason 	if (uptodate) {
3182f2984462SChris Mason 		set_buffer_uptodate(bh);
3183f2984462SChris Mason 	} else {
3184442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
3185442a4f63SStefan Behrens 			bh->b_private;
3186442a4f63SStefan Behrens 
3187fb456252SJeff Mahoney 		btrfs_warn_rl_in_rcu(device->fs_info,
3188b14af3b4SDavid Sterba 				"lost page write due to IO error on %s",
3189606686eeSJosef Bacik 					  rcu_str_deref(device->name));
319001327610SNicholas D Steeves 		/* note, we don't set_buffer_write_io_error because we have
31911259ab75SChris Mason 		 * our own ways of dealing with the IO errors
31921259ab75SChris Mason 		 */
3193f2984462SChris Mason 		clear_buffer_uptodate(bh);
3194442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3195f2984462SChris Mason 	}
3196f2984462SChris Mason 	unlock_buffer(bh);
3197f2984462SChris Mason 	put_bh(bh);
3198f2984462SChris Mason }
3199f2984462SChris Mason 
320029c36d72SAnand Jain int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
320129c36d72SAnand Jain 			struct buffer_head **bh_ret)
320229c36d72SAnand Jain {
320329c36d72SAnand Jain 	struct buffer_head *bh;
320429c36d72SAnand Jain 	struct btrfs_super_block *super;
320529c36d72SAnand Jain 	u64 bytenr;
320629c36d72SAnand Jain 
320729c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
320829c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
320929c36d72SAnand Jain 		return -EINVAL;
321029c36d72SAnand Jain 
32119f6d2510SDavid Sterba 	bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
321229c36d72SAnand Jain 	/*
321329c36d72SAnand Jain 	 * If we fail to read from the underlying devices, as of now
321429c36d72SAnand Jain 	 * the best option we have is to mark it EIO.
321529c36d72SAnand Jain 	 */
321629c36d72SAnand Jain 	if (!bh)
321729c36d72SAnand Jain 		return -EIO;
321829c36d72SAnand Jain 
321929c36d72SAnand Jain 	super = (struct btrfs_super_block *)bh->b_data;
322029c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
322129c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
322229c36d72SAnand Jain 		brelse(bh);
322329c36d72SAnand Jain 		return -EINVAL;
322429c36d72SAnand Jain 	}
322529c36d72SAnand Jain 
322629c36d72SAnand Jain 	*bh_ret = bh;
322729c36d72SAnand Jain 	return 0;
322829c36d72SAnand Jain }
322929c36d72SAnand Jain 
323029c36d72SAnand Jain 
3231a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3232a512bbf8SYan Zheng {
3233a512bbf8SYan Zheng 	struct buffer_head *bh;
3234a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
3235a512bbf8SYan Zheng 	struct btrfs_super_block *super;
3236a512bbf8SYan Zheng 	int i;
3237a512bbf8SYan Zheng 	u64 transid = 0;
323892fc03fbSAnand Jain 	int ret = -EINVAL;
3239a512bbf8SYan Zheng 
3240a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3241a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3242a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3243a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3244a512bbf8SYan Zheng 	 */
3245a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
324629c36d72SAnand Jain 		ret = btrfs_read_dev_one_super(bdev, i, &bh);
324729c36d72SAnand Jain 		if (ret)
3248a512bbf8SYan Zheng 			continue;
3249a512bbf8SYan Zheng 
3250a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
3251a512bbf8SYan Zheng 
3252a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
3253a512bbf8SYan Zheng 			brelse(latest);
3254a512bbf8SYan Zheng 			latest = bh;
3255a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3256a512bbf8SYan Zheng 		} else {
3257a512bbf8SYan Zheng 			brelse(bh);
3258a512bbf8SYan Zheng 		}
3259a512bbf8SYan Zheng 	}
326092fc03fbSAnand Jain 
326192fc03fbSAnand Jain 	if (!latest)
326292fc03fbSAnand Jain 		return ERR_PTR(ret);
326392fc03fbSAnand Jain 
3264a512bbf8SYan Zheng 	return latest;
3265a512bbf8SYan Zheng }
3266a512bbf8SYan Zheng 
32674eedeb75SHisashi Hifumi /*
3268abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3269abbb3b8eSDavid Sterba  * buffer heads we write are pinned.
32704eedeb75SHisashi Hifumi  *
3271abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3272abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3273abbb3b8eSDavid Sterba  * same for write and wait phases.
32744eedeb75SHisashi Hifumi  *
3275abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or submission fails.
32764eedeb75SHisashi Hifumi  */
3277a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3278abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3279a512bbf8SYan Zheng {
3280a512bbf8SYan Zheng 	struct buffer_head *bh;
3281a512bbf8SYan Zheng 	int i;
3282a512bbf8SYan Zheng 	int ret;
3283a512bbf8SYan Zheng 	int errors = 0;
3284a512bbf8SYan Zheng 	u32 crc;
3285a512bbf8SYan Zheng 	u64 bytenr;
32861b9e619cSOmar Sandoval 	int op_flags;
3287a512bbf8SYan Zheng 
3288a512bbf8SYan Zheng 	if (max_mirrors == 0)
3289a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3290a512bbf8SYan Zheng 
3291a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3292a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3293935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3294935e5cc9SMiao Xie 		    device->commit_total_bytes)
3295a512bbf8SYan Zheng 			break;
3296a512bbf8SYan Zheng 
3297a512bbf8SYan Zheng 		btrfs_set_super_bytenr(sb, bytenr);
3298a512bbf8SYan Zheng 
3299a512bbf8SYan Zheng 		crc = ~(u32)0;
3300abbb3b8eSDavid Sterba 		crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3301abbb3b8eSDavid Sterba 				      BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3302a512bbf8SYan Zheng 		btrfs_csum_final(crc, sb->csum);
3303a512bbf8SYan Zheng 
3304abbb3b8eSDavid Sterba 		/* One reference for us, and we leave it for the caller */
33059f6d2510SDavid Sterba 		bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3306a512bbf8SYan Zheng 			      BTRFS_SUPER_INFO_SIZE);
3307634554dcSJosef Bacik 		if (!bh) {
3308fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3309f14d104dSDavid Sterba 			    "couldn't get super buffer head for bytenr %llu",
3310f14d104dSDavid Sterba 			    bytenr);
3311634554dcSJosef Bacik 			errors++;
3312634554dcSJosef Bacik 			continue;
3313634554dcSJosef Bacik 		}
3314634554dcSJosef Bacik 
3315a512bbf8SYan Zheng 		memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3316a512bbf8SYan Zheng 
33174eedeb75SHisashi Hifumi 		/* one reference for submit_bh */
3318a512bbf8SYan Zheng 		get_bh(bh);
33194eedeb75SHisashi Hifumi 
33204eedeb75SHisashi Hifumi 		set_buffer_uptodate(bh);
3321a512bbf8SYan Zheng 		lock_buffer(bh);
3322a512bbf8SYan Zheng 		bh->b_end_io = btrfs_end_buffer_write_sync;
3323442a4f63SStefan Behrens 		bh->b_private = device;
3324a512bbf8SYan Zheng 
3325387125fcSChris Mason 		/*
3326387125fcSChris Mason 		 * we fua the first super.  The others we allow
3327387125fcSChris Mason 		 * to go down lazy.
3328387125fcSChris Mason 		 */
33291b9e619cSOmar Sandoval 		op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
33301b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
33311b9e619cSOmar Sandoval 			op_flags |= REQ_FUA;
33321b9e619cSOmar Sandoval 		ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
33334eedeb75SHisashi Hifumi 		if (ret)
3334a512bbf8SYan Zheng 			errors++;
3335a512bbf8SYan Zheng 	}
3336a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3337a512bbf8SYan Zheng }
3338a512bbf8SYan Zheng 
3339387125fcSChris Mason /*
3340abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3341abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3342abbb3b8eSDavid Sterba  *
3343abbb3b8eSDavid Sterba  * Return number of errors when buffer head is not found or not marked up to
3344abbb3b8eSDavid Sterba  * date.
3345abbb3b8eSDavid Sterba  */
3346abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3347abbb3b8eSDavid Sterba {
3348abbb3b8eSDavid Sterba 	struct buffer_head *bh;
3349abbb3b8eSDavid Sterba 	int i;
3350abbb3b8eSDavid Sterba 	int errors = 0;
3351b6a535faSHoward McLauchlan 	bool primary_failed = false;
3352abbb3b8eSDavid Sterba 	u64 bytenr;
3353abbb3b8eSDavid Sterba 
3354abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3355abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3356abbb3b8eSDavid Sterba 
3357abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3358abbb3b8eSDavid Sterba 		bytenr = btrfs_sb_offset(i);
3359abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3360abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3361abbb3b8eSDavid Sterba 			break;
3362abbb3b8eSDavid Sterba 
33639f6d2510SDavid Sterba 		bh = __find_get_block(device->bdev,
33649f6d2510SDavid Sterba 				      bytenr / BTRFS_BDEV_BLOCKSIZE,
3365abbb3b8eSDavid Sterba 				      BTRFS_SUPER_INFO_SIZE);
3366abbb3b8eSDavid Sterba 		if (!bh) {
3367abbb3b8eSDavid Sterba 			errors++;
3368b6a535faSHoward McLauchlan 			if (i == 0)
3369b6a535faSHoward McLauchlan 				primary_failed = true;
3370abbb3b8eSDavid Sterba 			continue;
3371abbb3b8eSDavid Sterba 		}
3372abbb3b8eSDavid Sterba 		wait_on_buffer(bh);
3373b6a535faSHoward McLauchlan 		if (!buffer_uptodate(bh)) {
3374abbb3b8eSDavid Sterba 			errors++;
3375b6a535faSHoward McLauchlan 			if (i == 0)
3376b6a535faSHoward McLauchlan 				primary_failed = true;
3377b6a535faSHoward McLauchlan 		}
3378abbb3b8eSDavid Sterba 
3379abbb3b8eSDavid Sterba 		/* drop our reference */
3380abbb3b8eSDavid Sterba 		brelse(bh);
3381abbb3b8eSDavid Sterba 
3382abbb3b8eSDavid Sterba 		/* drop the reference from the writing run */
3383abbb3b8eSDavid Sterba 		brelse(bh);
3384abbb3b8eSDavid Sterba 	}
3385abbb3b8eSDavid Sterba 
3386b6a535faSHoward McLauchlan 	/* log error, force error return */
3387b6a535faSHoward McLauchlan 	if (primary_failed) {
3388b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3389b6a535faSHoward McLauchlan 			  device->devid);
3390b6a535faSHoward McLauchlan 		return -1;
3391b6a535faSHoward McLauchlan 	}
3392b6a535faSHoward McLauchlan 
3393abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3394abbb3b8eSDavid Sterba }
3395abbb3b8eSDavid Sterba 
3396abbb3b8eSDavid Sterba /*
3397387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3398387125fcSChris Mason  * for the barrier when it is done
3399387125fcSChris Mason  */
34004246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3401387125fcSChris Mason {
3402387125fcSChris Mason 	complete(bio->bi_private);
3403387125fcSChris Mason }
3404387125fcSChris Mason 
3405387125fcSChris Mason /*
34064fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
34074fc6441aSAnand Jain  * done in the waiting counterpart.
3408387125fcSChris Mason  */
34094fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3410387125fcSChris Mason {
3411c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3412e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3413387125fcSChris Mason 
3414c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
34154fc6441aSAnand Jain 		return;
3416387125fcSChris Mason 
3417e0ae9994SDavid Sterba 	bio_reset(bio);
3418387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
341974d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
34208d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3421387125fcSChris Mason 	init_completion(&device->flush_wait);
3422387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3423387125fcSChris Mason 
342443a01111SLu Fengqi 	btrfsic_submit_bio(bio);
34251c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
34264fc6441aSAnand Jain }
3427387125fcSChris Mason 
34284fc6441aSAnand Jain /*
34294fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
34304fc6441aSAnand Jain  */
34318c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
34324fc6441aSAnand Jain {
34334fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
34344fc6441aSAnand Jain 
34351c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
343658efbc9fSOmar Sandoval 		return BLK_STS_OK;
34374fc6441aSAnand Jain 
34381c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
34392980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
34404fc6441aSAnand Jain 
34418c27cb35SLinus Torvalds 	return bio->bi_status;
3442387125fcSChris Mason }
3443387125fcSChris Mason 
3444d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3445401b41e5SAnand Jain {
34466528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3447401b41e5SAnand Jain 		return -EIO;
3448387125fcSChris Mason 	return 0;
3449387125fcSChris Mason }
3450387125fcSChris Mason 
3451387125fcSChris Mason /*
3452387125fcSChris Mason  * send an empty flush down to each device in parallel,
3453387125fcSChris Mason  * then wait for them
3454387125fcSChris Mason  */
3455387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3456387125fcSChris Mason {
3457387125fcSChris Mason 	struct list_head *head;
3458387125fcSChris Mason 	struct btrfs_device *dev;
34595af3e8ccSStefan Behrens 	int errors_wait = 0;
34604e4cbee9SChristoph Hellwig 	blk_status_t ret;
3461387125fcSChris Mason 
34621538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3463387125fcSChris Mason 	/* send down all the barriers */
3464387125fcSChris Mason 	head = &info->fs_devices->devices;
34651538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3466e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3467f88ba6a2SHidetoshi Seto 			continue;
3468cea7c8bfSAnand Jain 		if (!dev->bdev)
3469387125fcSChris Mason 			continue;
3470e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3471ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3472387125fcSChris Mason 			continue;
3473387125fcSChris Mason 
34744fc6441aSAnand Jain 		write_dev_flush(dev);
347558efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3476387125fcSChris Mason 	}
3477387125fcSChris Mason 
3478387125fcSChris Mason 	/* wait for all the barriers */
34791538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3480e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3481f88ba6a2SHidetoshi Seto 			continue;
3482387125fcSChris Mason 		if (!dev->bdev) {
34835af3e8ccSStefan Behrens 			errors_wait++;
3484387125fcSChris Mason 			continue;
3485387125fcSChris Mason 		}
3486e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3487ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3488387125fcSChris Mason 			continue;
3489387125fcSChris Mason 
34904fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3491401b41e5SAnand Jain 		if (ret) {
3492401b41e5SAnand Jain 			dev->last_flush_error = ret;
349366b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
349466b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
34955af3e8ccSStefan Behrens 			errors_wait++;
3496387125fcSChris Mason 		}
3497401b41e5SAnand Jain 	}
3498401b41e5SAnand Jain 
3499cea7c8bfSAnand Jain 	if (errors_wait) {
3500401b41e5SAnand Jain 		/*
3501401b41e5SAnand Jain 		 * At some point we need the status of all disks
3502401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3503401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3504401b41e5SAnand Jain 		 */
3505d10b82feSQu Wenruo 		return check_barrier_error(info);
3506401b41e5SAnand Jain 	}
3507387125fcSChris Mason 	return 0;
3508387125fcSChris Mason }
3509387125fcSChris Mason 
3510943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3511943c6e99SZhao Lei {
35128789f4feSZhao Lei 	int raid_type;
35138789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3514943c6e99SZhao Lei 
35158789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
35168789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
35178789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
35188789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
35198789f4feSZhao Lei 				    tolerated_failures);
3520943c6e99SZhao Lei 
35218789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
35228789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
35238789f4feSZhao Lei 			continue;
352441a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
35258789f4feSZhao Lei 			continue;
35268789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
35278789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
35288789f4feSZhao Lei 				    tolerated_failures);
35298789f4feSZhao Lei 	}
3530943c6e99SZhao Lei 
35318789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3532ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
35338789f4feSZhao Lei 		min_tolerated = 0;
35348789f4feSZhao Lei 	}
35358789f4feSZhao Lei 
35368789f4feSZhao Lei 	return min_tolerated;
3537943c6e99SZhao Lei }
3538943c6e99SZhao Lei 
3539eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3540f2984462SChris Mason {
3541e5e9a520SChris Mason 	struct list_head *head;
3542f2984462SChris Mason 	struct btrfs_device *dev;
3543a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3544f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3545f2984462SChris Mason 	int ret;
3546f2984462SChris Mason 	int do_barriers;
3547a236aed1SChris Mason 	int max_errors;
3548a236aed1SChris Mason 	int total_errors = 0;
3549a061fc8dSChris Mason 	u64 flags;
3550f2984462SChris Mason 
35510b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3552fed3b381SLiu Bo 
3553fed3b381SLiu Bo 	/*
3554fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3555fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3556fed3b381SLiu Bo 	 * been consistent on disk.
3557fed3b381SLiu Bo 	 */
3558fed3b381SLiu Bo 	if (max_mirrors == 0)
35590b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3560f2984462SChris Mason 
35610b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3562a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3563e5e9a520SChris Mason 
35640b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
35650b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
35660b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3567387125fcSChris Mason 
35685af3e8ccSStefan Behrens 	if (do_barriers) {
35690b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
35705af3e8ccSStefan Behrens 		if (ret) {
35715af3e8ccSStefan Behrens 			mutex_unlock(
35720b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
35730b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
35745af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
35755af3e8ccSStefan Behrens 			return ret;
35765af3e8ccSStefan Behrens 		}
35775af3e8ccSStefan Behrens 	}
3578387125fcSChris Mason 
35791538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3580dfe25020SChris Mason 		if (!dev->bdev) {
3581dfe25020SChris Mason 			total_errors++;
3582dfe25020SChris Mason 			continue;
3583dfe25020SChris Mason 		}
3584e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3585ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3586dfe25020SChris Mason 			continue;
3587dfe25020SChris Mason 
35882b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3589a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3590a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
35917df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3592935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3593ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3594ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3595a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3596a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3597a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3598a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
359944880fdcSAnand Jain 		memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_FSID_SIZE);
3600a512bbf8SYan Zheng 
3601a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3602a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3603f2984462SChris Mason 
3604abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3605a236aed1SChris Mason 		if (ret)
3606a236aed1SChris Mason 			total_errors++;
3607f2984462SChris Mason 	}
3608a236aed1SChris Mason 	if (total_errors > max_errors) {
36090b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3610d397712bSChris Mason 			  total_errors);
36110b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
361279787eaaSJeff Mahoney 
36139d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
36140b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
36150b246afaSJeff Mahoney 				      "%d errors while writing supers",
36160b246afaSJeff Mahoney 				      total_errors);
36179d565ba4SStefan Behrens 		return -EIO;
3618a236aed1SChris Mason 	}
3619f2984462SChris Mason 
3620a512bbf8SYan Zheng 	total_errors = 0;
36211538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3622dfe25020SChris Mason 		if (!dev->bdev)
3623dfe25020SChris Mason 			continue;
3624e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3625ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3626dfe25020SChris Mason 			continue;
3627dfe25020SChris Mason 
3628abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3629a512bbf8SYan Zheng 		if (ret)
36301259ab75SChris Mason 			total_errors++;
3631f2984462SChris Mason 	}
36320b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3633a236aed1SChris Mason 	if (total_errors > max_errors) {
36340b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
36350b246afaSJeff Mahoney 				      "%d errors while writing supers",
36360b246afaSJeff Mahoney 				      total_errors);
363779787eaaSJeff Mahoney 		return -EIO;
3638a236aed1SChris Mason 	}
3639f2984462SChris Mason 	return 0;
3640f2984462SChris Mason }
3641f2984462SChris Mason 
3642cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3643cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3644cb517eabSMiao Xie 				  struct btrfs_root *root)
36452619ba1fSChris Mason {
36464df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
36472619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
36482619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
36494df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
365076dda93cSYan, Zheng 
365176dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
365276dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
365376dda93cSYan, Zheng 
36541c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
36553321719eSLiu Bo 		btrfs_free_log(NULL, root);
36561c1ea4f7SLiu Bo 		if (root->reloc_root) {
36571c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->node);
36581c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->commit_root);
36591c1ea4f7SLiu Bo 			btrfs_put_fs_root(root->reloc_root);
36601c1ea4f7SLiu Bo 			root->reloc_root = NULL;
36611c1ea4f7SLiu Bo 		}
36621c1ea4f7SLiu Bo 	}
36633321719eSLiu Bo 
3664faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3665581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3666faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3667581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
36684df27c4dSYan, Zheng 	free_fs_root(root);
36694df27c4dSYan, Zheng }
36704df27c4dSYan, Zheng 
36714df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root)
36724df27c4dSYan, Zheng {
367357cdc8dbSDavid Sterba 	iput(root->ino_cache_inode);
36744df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
36752ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(root->fs_info, root->orphan_block_rsv);
36761cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
36770ee5dc67SAl Viro 	if (root->anon_dev)
36780ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
36798257b2dcSMiao Xie 	if (root->subv_writers)
36808257b2dcSMiao Xie 		btrfs_free_subvolume_writers(root->subv_writers);
36815f39d397SChris Mason 	free_extent_buffer(root->node);
36825f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3683581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3684581bb050SLi Zefan 	kfree(root->free_ino_pinned);
368558176a96SJosef Bacik 	kfree(root->name);
3686b0feb9d9SMiao Xie 	btrfs_put_fs_root(root);
36872619ba1fSChris Mason }
36882619ba1fSChris Mason 
3689cb517eabSMiao Xie void btrfs_free_fs_root(struct btrfs_root *root)
3690cb517eabSMiao Xie {
3691cb517eabSMiao Xie 	free_fs_root(root);
3692cfaa7295SChris Mason }
3693cfaa7295SChris Mason 
3694c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3695c146afadSYan Zheng {
3696c146afadSYan Zheng 	u64 root_objectid = 0;
3697c146afadSYan Zheng 	struct btrfs_root *gang[8];
369865d33fd7SQu Wenruo 	int i = 0;
369965d33fd7SQu Wenruo 	int err = 0;
370065d33fd7SQu Wenruo 	unsigned int ret = 0;
370165d33fd7SQu Wenruo 	int index;
3702c146afadSYan Zheng 
3703c146afadSYan Zheng 	while (1) {
370465d33fd7SQu Wenruo 		index = srcu_read_lock(&fs_info->subvol_srcu);
3705c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3706c146afadSYan Zheng 					     (void **)gang, root_objectid,
3707c146afadSYan Zheng 					     ARRAY_SIZE(gang));
370865d33fd7SQu Wenruo 		if (!ret) {
370965d33fd7SQu Wenruo 			srcu_read_unlock(&fs_info->subvol_srcu, index);
3710c146afadSYan Zheng 			break;
371165d33fd7SQu Wenruo 		}
37125d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
371366b4ffd1SJosef Bacik 
371465d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
371565d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
371665d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
371765d33fd7SQu Wenruo 				gang[i] = NULL;
371865d33fd7SQu Wenruo 				continue;
371965d33fd7SQu Wenruo 			}
372065d33fd7SQu Wenruo 			/* grab all the search result for later use */
372165d33fd7SQu Wenruo 			gang[i] = btrfs_grab_fs_root(gang[i]);
372265d33fd7SQu Wenruo 		}
372365d33fd7SQu Wenruo 		srcu_read_unlock(&fs_info->subvol_srcu, index);
372465d33fd7SQu Wenruo 
372565d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
372665d33fd7SQu Wenruo 			if (!gang[i])
372765d33fd7SQu Wenruo 				continue;
3728c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
372966b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
373066b4ffd1SJosef Bacik 			if (err)
373165d33fd7SQu Wenruo 				break;
373265d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
3733c146afadSYan Zheng 		}
3734c146afadSYan Zheng 		root_objectid++;
3735c146afadSYan Zheng 	}
373665d33fd7SQu Wenruo 
373765d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
373865d33fd7SQu Wenruo 	for (; i < ret; i++) {
373965d33fd7SQu Wenruo 		if (gang[i])
374065d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
374165d33fd7SQu Wenruo 	}
374265d33fd7SQu Wenruo 	return err;
3743c146afadSYan Zheng }
3744c146afadSYan Zheng 
37456bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3746c146afadSYan Zheng {
37476bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3748c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3749c146afadSYan Zheng 
37500b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
37512ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
37520b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
37530b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
3754c71bf099SYan, Zheng 
3755c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
37560b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
37570b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
3758c71bf099SYan, Zheng 
37597a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
37603612b495STsutomu Itoh 	if (IS_ERR(trans))
37613612b495STsutomu Itoh 		return PTR_ERR(trans);
37623a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
3763c146afadSYan Zheng }
3764c146afadSYan Zheng 
37656bccf3abSJeff Mahoney void close_ctree(struct btrfs_fs_info *fs_info)
3766eb60ceacSChris Mason {
37676bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3768c146afadSYan Zheng 	int ret;
3769e089f05cSChris Mason 
3770afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3771a2135011SChris Mason 
37727343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
3773d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
37747343dd61SJustin Maggard 
3775803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3776803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3777803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3778803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3779803b2f54SStefan Behrens 
3780837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3781aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3782837d5b6eSIlya Dryomov 
37838dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
37848dabb742SStefan Behrens 
3785aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
37864cb5300bSChris Mason 
37874cb5300bSChris Mason 	/* wait for any defraggers to finish */
37884cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
37894cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
37904cb5300bSChris Mason 
37914cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
379226176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
37934cb5300bSChris Mason 
379421c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
379521c7e756SMiao Xie 
3796bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
3797e44163e1SJeff Mahoney 		/*
3798e44163e1SJeff Mahoney 		 * If the cleaner thread is stopped and there are
3799e44163e1SJeff Mahoney 		 * block groups queued for removal, the deletion will be
3800e44163e1SJeff Mahoney 		 * skipped when we quit the cleaner thread.
3801e44163e1SJeff Mahoney 		 */
38020b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
3803e44163e1SJeff Mahoney 
38046bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
3805d397712bSChris Mason 		if (ret)
380604892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
3807c146afadSYan Zheng 	}
3808ed2ff2cbSChris Mason 
3809af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
3810af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
38112ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
3812acce952bSliubo 
3813e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
3814e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
38158929ecfaSYan, Zheng 
3816afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
3817f25784b3SYan Zheng 
381804892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
3819fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
3820bcef60f2SArne Jansen 
3821963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
382204892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
3823963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
3824b0c68f8bSChris Mason 	}
382531153d81SYan Zheng 
38266618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
3827b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
38285ac1d209SJeff Mahoney 
3829faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
3830d10c5f31SChris Mason 
38311a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
38321a4319ccSLiu Bo 
3833de348ee0SWang Shilong 	/*
3834de348ee0SWang Shilong 	 * we must make sure there is not any read request to
3835de348ee0SWang Shilong 	 * submit after we stopping all workers.
3836de348ee0SWang Shilong 	 */
3837de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
383896192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
383996192499SJosef Bacik 
38405cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
38415cdd7db6SFilipe Manana 
3842afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
384313e6c37bSJosef Bacik 	free_root_pointers(fs_info, 1);
38449ad6b7bcSChris Mason 
384513e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
3846d6bfde87SChris Mason 
384721adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
38480b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
38492ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
385021adbd5cSStefan Behrens #endif
385121adbd5cSStefan Behrens 
3852dfe25020SChris Mason 	btrfs_close_devices(fs_info->fs_devices);
38530b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3854b248a415SChris Mason 
3855e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3856963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3857c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
385876dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
38590b86a832SChris Mason 
386053b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3861fd708b81SJosef Bacik 	btrfs_free_ref_cache(fs_info);
386253b381b3SDavid Woodhouse 
3863cdfb080eSChris Mason 	__btrfs_free_block_rsv(root->orphan_block_rsv);
38641cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
386504216820SFilipe Manana 
386604216820SFilipe Manana 	while (!list_empty(&fs_info->pinned_chunks)) {
386704216820SFilipe Manana 		struct extent_map *em;
386804216820SFilipe Manana 
386904216820SFilipe Manana 		em = list_first_entry(&fs_info->pinned_chunks,
387004216820SFilipe Manana 				      struct extent_map, list);
387104216820SFilipe Manana 		list_del_init(&em->list);
387204216820SFilipe Manana 		free_extent_map(em);
387304216820SFilipe Manana 	}
3874eb60ceacSChris Mason }
3875eb60ceacSChris Mason 
3876b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
3877b9fab919SChris Mason 			  int atomic)
3878ccd467d6SChris Mason {
38791259ab75SChris Mason 	int ret;
3880727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
38811259ab75SChris Mason 
38820b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
38831259ab75SChris Mason 	if (!ret)
38841259ab75SChris Mason 		return ret;
38851259ab75SChris Mason 
38861259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
3887b9fab919SChris Mason 				    parent_transid, atomic);
3888b9fab919SChris Mason 	if (ret == -EAGAIN)
3889b9fab919SChris Mason 		return ret;
38901259ab75SChris Mason 	return !ret;
38915f39d397SChris Mason }
38926702ed49SChris Mason 
38935f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
38945f39d397SChris Mason {
38950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
389606ea65a3SJosef Bacik 	struct btrfs_root *root;
38975f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
3898b9473439SChris Mason 	int was_dirty;
3899b4ce94deSChris Mason 
390006ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
390106ea65a3SJosef Bacik 	/*
390206ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
390306ea65a3SJosef Bacik 	 * enabled.  Normal people shouldn't be marking dummy buffers as dirty
390406ea65a3SJosef Bacik 	 * outside of the sanity tests.
390506ea65a3SJosef Bacik 	 */
390606ea65a3SJosef Bacik 	if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
390706ea65a3SJosef Bacik 		return;
390806ea65a3SJosef Bacik #endif
390906ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
39100b246afaSJeff Mahoney 	fs_info = root->fs_info;
3911b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
39120b246afaSJeff Mahoney 	if (transid != fs_info->generation)
39135d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
39140b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
39150b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
3916e2d84521SMiao Xie 	if (!was_dirty)
3917104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
3918e2d84521SMiao Xie 					 buf->len,
39190b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
39201f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
392169fc6cbbSQu Wenruo 	/*
392269fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
392369fc6cbbSQu Wenruo 	 * but item data not updated.
392469fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
392569fc6cbbSQu Wenruo 	 */
392669fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
39272f659546SQu Wenruo 	    btrfs_check_leaf_relaxed(fs_info, buf)) {
3928a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
39291f21ef0aSFilipe Manana 		ASSERT(0);
39301f21ef0aSFilipe Manana 	}
39311f21ef0aSFilipe Manana #endif
3932eb60ceacSChris Mason }
3933eb60ceacSChris Mason 
39342ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
3935b53d3f5dSLiu Bo 					int flush_delayed)
393635b7e476SChris Mason {
3937188de649SChris Mason 	/*
3938188de649SChris Mason 	 * looks as though older kernels can get into trouble with
3939188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
3940188de649SChris Mason 	 */
3941e2d84521SMiao Xie 	int ret;
3942d6bfde87SChris Mason 
39436933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
3944d6bfde87SChris Mason 		return;
3945d6bfde87SChris Mason 
3946b53d3f5dSLiu Bo 	if (flush_delayed)
39472ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
394816cdcec7SMiao Xie 
39490b246afaSJeff Mahoney 	ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
3950e2d84521SMiao Xie 				     BTRFS_DIRTY_METADATA_THRESH);
3951e2d84521SMiao Xie 	if (ret > 0) {
39520b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
395316cdcec7SMiao Xie 	}
395416cdcec7SMiao Xie }
395516cdcec7SMiao Xie 
39562ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
395716cdcec7SMiao Xie {
39582ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
395935b7e476SChris Mason }
3960b53d3f5dSLiu Bo 
39612ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
3962b53d3f5dSLiu Bo {
39632ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
3964d6bfde87SChris Mason }
39656b80053dSChris Mason 
3966581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
3967581c1760SQu Wenruo 		      struct btrfs_key *first_key)
39686b80053dSChris Mason {
3969727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
39702ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
39712ff7e61eSJeff Mahoney 
3972581c1760SQu Wenruo 	return btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
3973581c1760SQu Wenruo 					      level, first_key);
39746b80053dSChris Mason }
39750da5468fSChris Mason 
39763d3a126aSDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info)
3977acce952bSliubo {
3978c926093eSDavid Sterba 	struct btrfs_super_block *sb = fs_info->super_copy;
3979319e4d06SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
3980319e4d06SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
3981c926093eSDavid Sterba 	int ret = 0;
3982c926093eSDavid Sterba 
3983319e4d06SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
3984ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "no valid FS found");
3985319e4d06SQu Wenruo 		ret = -EINVAL;
3986319e4d06SQu Wenruo 	}
39876f794e3cSAnand Jain 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
39886f794e3cSAnand Jain 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
3989319e4d06SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
39906f794e3cSAnand Jain 		ret = -EINVAL;
39916f794e3cSAnand Jain 	}
399221e7626bSDavid Sterba 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
3993ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
399421e7626bSDavid Sterba 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
3995c926093eSDavid Sterba 		ret = -EINVAL;
3996c926093eSDavid Sterba 	}
399721e7626bSDavid Sterba 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
3998ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
399921e7626bSDavid Sterba 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
4000c926093eSDavid Sterba 		ret = -EINVAL;
4001c926093eSDavid Sterba 	}
400221e7626bSDavid Sterba 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
4003ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
400421e7626bSDavid Sterba 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
4005c926093eSDavid Sterba 		ret = -EINVAL;
4006c926093eSDavid Sterba 	}
4007c926093eSDavid Sterba 
40081104a885SDavid Sterba 	/*
4009319e4d06SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
4010319e4d06SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
40111104a885SDavid Sterba 	 */
4012319e4d06SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
4013319e4d06SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4014ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
401575d6ad38SDavid Sterba 		ret = -EINVAL;
401675d6ad38SDavid Sterba 	}
4017319e4d06SQu Wenruo 	/* Only PAGE SIZE is supported yet */
401809cbfeafSKirill A. Shutemov 	if (sectorsize != PAGE_SIZE) {
4019ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info,
4020ab8d0fc4SJeff Mahoney 			"sectorsize %llu not supported yet, only support %lu",
402109cbfeafSKirill A. Shutemov 			sectorsize, PAGE_SIZE);
4022319e4d06SQu Wenruo 		ret = -EINVAL;
4023319e4d06SQu Wenruo 	}
4024319e4d06SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
4025319e4d06SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4026ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
4027319e4d06SQu Wenruo 		ret = -EINVAL;
4028319e4d06SQu Wenruo 	}
4029319e4d06SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
4030ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
4031ab8d0fc4SJeff Mahoney 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
4032319e4d06SQu Wenruo 		ret = -EINVAL;
4033319e4d06SQu Wenruo 	}
4034319e4d06SQu Wenruo 
4035319e4d06SQu Wenruo 	/* Root alignment check */
4036319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
4037ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
4038319e4d06SQu Wenruo 			   btrfs_super_root(sb));
4039319e4d06SQu Wenruo 		ret = -EINVAL;
4040319e4d06SQu Wenruo 	}
4041319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
4042ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
4043319e4d06SQu Wenruo 			   btrfs_super_chunk_root(sb));
4044319e4d06SQu Wenruo 		ret = -EINVAL;
4045319e4d06SQu Wenruo 	}
4046319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
4047ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
4048319e4d06SQu Wenruo 			   btrfs_super_log_root(sb));
404975d6ad38SDavid Sterba 		ret = -EINVAL;
405075d6ad38SDavid Sterba 	}
405175d6ad38SDavid Sterba 
405244880fdcSAnand Jain 	if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_FSID_SIZE) != 0) {
4053ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info,
4054ab8d0fc4SJeff Mahoney 			   "dev_item UUID does not match fsid: %pU != %pU",
4055c926093eSDavid Sterba 			   fs_info->fsid, sb->dev_item.fsid);
4056c926093eSDavid Sterba 		ret = -EINVAL;
4057c926093eSDavid Sterba 	}
4058c926093eSDavid Sterba 
4059c926093eSDavid Sterba 	/*
4060c926093eSDavid Sterba 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
4061c926093eSDavid Sterba 	 * done later
4062c926093eSDavid Sterba 	 */
406399e3ecfcSLiu Bo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
406499e3ecfcSLiu Bo 		btrfs_err(fs_info, "bytes_used is too small %llu",
406599e3ecfcSLiu Bo 			  btrfs_super_bytes_used(sb));
406699e3ecfcSLiu Bo 		ret = -EINVAL;
406799e3ecfcSLiu Bo 	}
4068b7f67055SChandan Rajendra 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
406999e3ecfcSLiu Bo 		btrfs_err(fs_info, "invalid stripesize %u",
407099e3ecfcSLiu Bo 			  btrfs_super_stripesize(sb));
407199e3ecfcSLiu Bo 		ret = -EINVAL;
407299e3ecfcSLiu Bo 	}
407321e7626bSDavid Sterba 	if (btrfs_super_num_devices(sb) > (1UL << 31))
4074ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
407521e7626bSDavid Sterba 			   btrfs_super_num_devices(sb));
407675d6ad38SDavid Sterba 	if (btrfs_super_num_devices(sb) == 0) {
4077ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "number of devices is 0");
407875d6ad38SDavid Sterba 		ret = -EINVAL;
407975d6ad38SDavid Sterba 	}
4080c926093eSDavid Sterba 
408121e7626bSDavid Sterba 	if (btrfs_super_bytenr(sb) != BTRFS_SUPER_INFO_OFFSET) {
4082ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
408321e7626bSDavid Sterba 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
4084c926093eSDavid Sterba 		ret = -EINVAL;
4085c926093eSDavid Sterba 	}
4086c926093eSDavid Sterba 
4087c926093eSDavid Sterba 	/*
4088ce7fca5fSDavid Sterba 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
4089ce7fca5fSDavid Sterba 	 * and one chunk
4090ce7fca5fSDavid Sterba 	 */
4091ce7fca5fSDavid Sterba 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4092ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "system chunk array too big %u > %u",
4093ce7fca5fSDavid Sterba 			  btrfs_super_sys_array_size(sb),
4094ce7fca5fSDavid Sterba 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
4095ce7fca5fSDavid Sterba 		ret = -EINVAL;
4096ce7fca5fSDavid Sterba 	}
4097ce7fca5fSDavid Sterba 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
4098ce7fca5fSDavid Sterba 			+ sizeof(struct btrfs_chunk)) {
4099ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
4100ce7fca5fSDavid Sterba 			  btrfs_super_sys_array_size(sb),
4101ce7fca5fSDavid Sterba 			  sizeof(struct btrfs_disk_key)
4102ce7fca5fSDavid Sterba 			  + sizeof(struct btrfs_chunk));
4103ce7fca5fSDavid Sterba 		ret = -EINVAL;
4104ce7fca5fSDavid Sterba 	}
4105ce7fca5fSDavid Sterba 
4106ce7fca5fSDavid Sterba 	/*
4107c926093eSDavid Sterba 	 * The generation is a global counter, we'll trust it more than the others
4108c926093eSDavid Sterba 	 * but it's still possible that it's the one that's wrong.
4109c926093eSDavid Sterba 	 */
411021e7626bSDavid Sterba 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
4111ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info,
4112ab8d0fc4SJeff Mahoney 			"suspicious: generation < chunk_root_generation: %llu < %llu",
4113ab8d0fc4SJeff Mahoney 			btrfs_super_generation(sb),
4114ab8d0fc4SJeff Mahoney 			btrfs_super_chunk_root_generation(sb));
411521e7626bSDavid Sterba 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
411621e7626bSDavid Sterba 	    && btrfs_super_cache_generation(sb) != (u64)-1)
4117ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info,
4118ab8d0fc4SJeff Mahoney 			"suspicious: generation < cache_generation: %llu < %llu",
4119ab8d0fc4SJeff Mahoney 			btrfs_super_generation(sb),
4120ab8d0fc4SJeff Mahoney 			btrfs_super_cache_generation(sb));
4121c926093eSDavid Sterba 
4122c926093eSDavid Sterba 	return ret;
4123fcd1f065SDavid Sterba }
4124fcd1f065SDavid Sterba 
41252ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4126acce952bSliubo {
4127fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4128fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4129fe816d0fSNikolay Borisov 
41300b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41312ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41320b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4133acce952bSliubo 
41340b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41350b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4136acce952bSliubo }
4137acce952bSliubo 
4138143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4139acce952bSliubo {
4140acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4141acce952bSliubo 
4142199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4143779880efSJosef Bacik 	/*
4144779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4145779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4146779880efSJosef Bacik 	 */
4147199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4148779880efSJosef Bacik 			    root_extent_list)
4149779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4150199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4151199c2a9cSMiao Xie }
4152199c2a9cSMiao Xie 
4153199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4154199c2a9cSMiao Xie {
4155199c2a9cSMiao Xie 	struct btrfs_root *root;
4156199c2a9cSMiao Xie 	struct list_head splice;
4157199c2a9cSMiao Xie 
4158199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4159199c2a9cSMiao Xie 
4160199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4161199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4162199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4163199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4164199c2a9cSMiao Xie 					ordered_root);
41651de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
41661de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4167199c2a9cSMiao Xie 
41682a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4169199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4170199c2a9cSMiao Xie 
41712a85d9caSLiu Bo 		cond_resched();
41722a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4173199c2a9cSMiao Xie 	}
4174199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
4175acce952bSliubo }
4176acce952bSliubo 
417735a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
41782ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4179acce952bSliubo {
4180acce952bSliubo 	struct rb_node *node;
4181acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4182acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4183acce952bSliubo 	int ret = 0;
4184acce952bSliubo 
4185acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4186acce952bSliubo 
4187acce952bSliubo 	spin_lock(&delayed_refs->lock);
4188d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4189cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
41900b246afaSJeff Mahoney 		btrfs_info(fs_info, "delayed_refs has NO entry");
4191acce952bSliubo 		return ret;
4192acce952bSliubo 	}
4193acce952bSliubo 
4194d7df2c79SJosef Bacik 	while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4195d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
41960e0adbcfSJosef Bacik 		struct rb_node *n;
4197e78417d1SJosef Bacik 		bool pin_bytes = false;
4198acce952bSliubo 
4199d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4200d7df2c79SJosef Bacik 				href_node);
4201b939d1abSJosef Bacik 		if (!mutex_trylock(&head->mutex)) {
4202d278850eSJosef Bacik 			refcount_inc(&head->refs);
420379787eaaSJeff Mahoney 			spin_unlock(&delayed_refs->lock);
4204b939d1abSJosef Bacik 
4205acce952bSliubo 			mutex_lock(&head->mutex);
4206b939d1abSJosef Bacik 			mutex_unlock(&head->mutex);
4207d278850eSJosef Bacik 			btrfs_put_delayed_ref_head(head);
4208e18fca73SJosef Bacik 			spin_lock(&delayed_refs->lock);
4209b939d1abSJosef Bacik 			continue;
4210b939d1abSJosef Bacik 		}
4211d7df2c79SJosef Bacik 		spin_lock(&head->lock);
42120e0adbcfSJosef Bacik 		while ((n = rb_first(&head->ref_tree)) != NULL) {
42130e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
42140e0adbcfSJosef Bacik 				       ref_node);
4215d7df2c79SJosef Bacik 			ref->in_tree = 0;
42160e0adbcfSJosef Bacik 			rb_erase(&ref->ref_node, &head->ref_tree);
42170e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
42181d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
42191d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4220d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4221d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4222d7df2c79SJosef Bacik 		}
422354067ae9SJosef Bacik 		if (head->must_insert_reserved)
4224e78417d1SJosef Bacik 			pin_bytes = true;
422578a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4226acce952bSliubo 		delayed_refs->num_heads--;
4227d7df2c79SJosef Bacik 		if (head->processing == 0)
4228acce952bSliubo 			delayed_refs->num_heads_ready--;
4229d7df2c79SJosef Bacik 		atomic_dec(&delayed_refs->num_entries);
4230c46effa6SLiu Bo 		rb_erase(&head->href_node, &delayed_refs->href_root);
4231d278850eSJosef Bacik 		RB_CLEAR_NODE(&head->href_node);
4232d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4233acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4234e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4235acce952bSliubo 
4236d7df2c79SJosef Bacik 		if (pin_bytes)
4237d278850eSJosef Bacik 			btrfs_pin_extent(fs_info, head->bytenr,
4238d278850eSJosef Bacik 					 head->num_bytes, 1);
4239d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4240acce952bSliubo 		cond_resched();
4241acce952bSliubo 		spin_lock(&delayed_refs->lock);
4242acce952bSliubo 	}
4243acce952bSliubo 
4244acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4245acce952bSliubo 
4246acce952bSliubo 	return ret;
4247acce952bSliubo }
4248acce952bSliubo 
4249143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4250acce952bSliubo {
4251acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4252acce952bSliubo 	struct list_head splice;
4253acce952bSliubo 
4254acce952bSliubo 	INIT_LIST_HEAD(&splice);
4255acce952bSliubo 
4256eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4257eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4258acce952bSliubo 
4259acce952bSliubo 	while (!list_empty(&splice)) {
4260fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4261eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4262acce952bSliubo 					       delalloc_inodes);
4263fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4264eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4265acce952bSliubo 
4266fe816d0fSNikolay Borisov 		/*
4267fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4268fe816d0fSNikolay Borisov 		 * meanwhile.
4269fe816d0fSNikolay Borisov 		 */
4270fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4271fe816d0fSNikolay Borisov 		if (inode) {
4272fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4273fe816d0fSNikolay Borisov 			iput(inode);
4274fe816d0fSNikolay Borisov 		}
4275eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4276acce952bSliubo 	}
4277eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4278eb73c1b7SMiao Xie }
4279eb73c1b7SMiao Xie 
4280eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4281eb73c1b7SMiao Xie {
4282eb73c1b7SMiao Xie 	struct btrfs_root *root;
4283eb73c1b7SMiao Xie 	struct list_head splice;
4284eb73c1b7SMiao Xie 
4285eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4286eb73c1b7SMiao Xie 
4287eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4288eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4289eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4290eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4291eb73c1b7SMiao Xie 					 delalloc_root);
4292eb73c1b7SMiao Xie 		root = btrfs_grab_fs_root(root);
4293eb73c1b7SMiao Xie 		BUG_ON(!root);
4294eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4295eb73c1b7SMiao Xie 
4296eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
4297eb73c1b7SMiao Xie 		btrfs_put_fs_root(root);
4298eb73c1b7SMiao Xie 
4299eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4300eb73c1b7SMiao Xie 	}
4301eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4302acce952bSliubo }
4303acce952bSliubo 
43042ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4305acce952bSliubo 					struct extent_io_tree *dirty_pages,
4306acce952bSliubo 					int mark)
4307acce952bSliubo {
4308acce952bSliubo 	int ret;
4309acce952bSliubo 	struct extent_buffer *eb;
4310acce952bSliubo 	u64 start = 0;
4311acce952bSliubo 	u64 end;
4312acce952bSliubo 
4313acce952bSliubo 	while (1) {
4314acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4315e6138876SJosef Bacik 					    mark, NULL);
4316acce952bSliubo 		if (ret)
4317acce952bSliubo 			break;
4318acce952bSliubo 
431991166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4320acce952bSliubo 		while (start <= end) {
43210b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
43220b246afaSJeff Mahoney 			start += fs_info->nodesize;
4323fd8b2b61SJosef Bacik 			if (!eb)
4324acce952bSliubo 				continue;
4325fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4326acce952bSliubo 
4327fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4328fd8b2b61SJosef Bacik 					       &eb->bflags))
4329fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4330fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4331acce952bSliubo 		}
4332acce952bSliubo 	}
4333acce952bSliubo 
4334acce952bSliubo 	return ret;
4335acce952bSliubo }
4336acce952bSliubo 
43372ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4338acce952bSliubo 				       struct extent_io_tree *pinned_extents)
4339acce952bSliubo {
4340acce952bSliubo 	struct extent_io_tree *unpin;
4341acce952bSliubo 	u64 start;
4342acce952bSliubo 	u64 end;
4343acce952bSliubo 	int ret;
4344ed0eaa14SLiu Bo 	bool loop = true;
4345acce952bSliubo 
4346acce952bSliubo 	unpin = pinned_extents;
4347ed0eaa14SLiu Bo again:
4348acce952bSliubo 	while (1) {
4349acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
4350e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
4351acce952bSliubo 		if (ret)
4352acce952bSliubo 			break;
4353acce952bSliubo 
4354af6f8f60SDavid Sterba 		clear_extent_dirty(unpin, start, end);
43552ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4356acce952bSliubo 		cond_resched();
4357acce952bSliubo 	}
4358acce952bSliubo 
4359ed0eaa14SLiu Bo 	if (loop) {
43600b246afaSJeff Mahoney 		if (unpin == &fs_info->freed_extents[0])
43610b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[1];
4362ed0eaa14SLiu Bo 		else
43630b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[0];
4364ed0eaa14SLiu Bo 		loop = false;
4365ed0eaa14SLiu Bo 		goto again;
4366ed0eaa14SLiu Bo 	}
4367ed0eaa14SLiu Bo 
4368acce952bSliubo 	return 0;
4369acce952bSliubo }
4370acce952bSliubo 
4371c79a1751SLiu Bo static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4372c79a1751SLiu Bo {
4373c79a1751SLiu Bo 	struct inode *inode;
4374c79a1751SLiu Bo 
4375c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4376c79a1751SLiu Bo 	if (inode) {
4377c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4378c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4379c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4380c79a1751SLiu Bo 		iput(inode);
4381c79a1751SLiu Bo 	}
4382c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4383c79a1751SLiu Bo }
4384c79a1751SLiu Bo 
4385c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
43862ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4387c79a1751SLiu Bo {
4388c79a1751SLiu Bo 	struct btrfs_block_group_cache *cache;
4389c79a1751SLiu Bo 
4390c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4391c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4392c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
4393c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4394c79a1751SLiu Bo 					 dirty_list);
4395c79a1751SLiu Bo 
4396c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4397c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4398c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4399c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4400c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4401c79a1751SLiu Bo 		}
4402c79a1751SLiu Bo 
4403c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4404c79a1751SLiu Bo 		spin_lock(&cache->lock);
4405c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4406c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4407c79a1751SLiu Bo 
4408c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4409c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4410c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4411c79a1751SLiu Bo 	}
4412c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4413c79a1751SLiu Bo 
441445ae2c18SNikolay Borisov 	/*
441545ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
441645ae2c18SNikolay Borisov 	 * to use it without any locking
441745ae2c18SNikolay Borisov 	 */
4418c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4419c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
4420c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4421c79a1751SLiu Bo 					 io_list);
4422c79a1751SLiu Bo 
4423c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4424c79a1751SLiu Bo 		spin_lock(&cache->lock);
4425c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4426c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4427c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4428c79a1751SLiu Bo 	}
4429c79a1751SLiu Bo }
4430c79a1751SLiu Bo 
443149b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
44322ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
443349b25e05SJeff Mahoney {
44342ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4435c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4436c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4437c79a1751SLiu Bo 
44382ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
443949b25e05SJeff Mahoney 
44404a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
44410b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
444249b25e05SJeff Mahoney 
44434a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
44440b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
444549b25e05SJeff Mahoney 
4446ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4447ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
444867cde344SMiao Xie 
44492ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
445049b25e05SJeff Mahoney 				     EXTENT_DIRTY);
44512ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info,
44520b246afaSJeff Mahoney 				    fs_info->pinned_extents);
445349b25e05SJeff Mahoney 
44544a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
44554a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
445649b25e05SJeff Mahoney }
445749b25e05SJeff Mahoney 
44582ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4459acce952bSliubo {
4460acce952bSliubo 	struct btrfs_transaction *t;
4461acce952bSliubo 
44620b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4463acce952bSliubo 
44640b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
44650b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
44660b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4467724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4468724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
44699b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
44700b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
44712ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4472724e2315SJosef Bacik 			btrfs_put_transaction(t);
44730b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4474724e2315SJosef Bacik 			continue;
4475724e2315SJosef Bacik 		}
44760b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4477724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
44780b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4479724e2315SJosef Bacik 			/*
4480724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4481724e2315SJosef Bacik 			 * handle open currently for this transaction.
4482724e2315SJosef Bacik 			 */
4483724e2315SJosef Bacik 			wait_event(t->writer_wait,
4484724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4485724e2315SJosef Bacik 		} else {
44860b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4487724e2315SJosef Bacik 		}
44882ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4489724e2315SJosef Bacik 
44900b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
44910b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
44920b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4493724e2315SJosef Bacik 		list_del_init(&t->list);
44940b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4495a4abeea4SJosef Bacik 
4496724e2315SJosef Bacik 		btrfs_put_transaction(t);
44972ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
44980b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4499724e2315SJosef Bacik 	}
45000b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
45010b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4502ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4503ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
45042ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
45050b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
45060b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4507acce952bSliubo 
4508acce952bSliubo 	return 0;
4509acce952bSliubo }
4510acce952bSliubo 
4511c6100a4bSJosef Bacik static struct btrfs_fs_info *btree_fs_info(void *private_data)
4512c6100a4bSJosef Bacik {
4513c6100a4bSJosef Bacik 	struct inode *inode = private_data;
4514c6100a4bSJosef Bacik 	return btrfs_sb(inode->i_sb);
4515c6100a4bSJosef Bacik }
4516c6100a4bSJosef Bacik 
4517e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
45184d53dddbSDavid Sterba 	/* mandatory callbacks */
45190b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
45204d53dddbSDavid Sterba 	.readpage_end_io_hook = btree_readpage_end_io_hook,
4521239b14b3SChris Mason 	/* note we're sharing with inode.c for the merge bio hook */
4522239b14b3SChris Mason 	.merge_bio_hook = btrfs_merge_bio_hook,
452320a7db8aSDavid Sterba 	.readpage_io_failed_hook = btree_io_failed_hook,
4524c6100a4bSJosef Bacik 	.set_range_writeback = btrfs_set_range_writeback,
4525c6100a4bSJosef Bacik 	.tree_fs_info = btree_fs_info,
45264d53dddbSDavid Sterba 
45274d53dddbSDavid Sterba 	/* optional callbacks */
45280da5468fSChris Mason };
4529