xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 5cdd7db6)
16cbd5570SChris Mason /*
26cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
36cbd5570SChris Mason  *
46cbd5570SChris Mason  * This program is free software; you can redistribute it and/or
56cbd5570SChris Mason  * modify it under the terms of the GNU General Public
66cbd5570SChris Mason  * License v2 as published by the Free Software Foundation.
76cbd5570SChris Mason  *
86cbd5570SChris Mason  * This program is distributed in the hope that it will be useful,
96cbd5570SChris Mason  * but WITHOUT ANY WARRANTY; without even the implied warranty of
106cbd5570SChris Mason  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
116cbd5570SChris Mason  * General Public License for more details.
126cbd5570SChris Mason  *
136cbd5570SChris Mason  * You should have received a copy of the GNU General Public
146cbd5570SChris Mason  * License along with this program; if not, write to the
156cbd5570SChris Mason  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
166cbd5570SChris Mason  * Boston, MA 021110-1307, USA.
176cbd5570SChris Mason  */
186cbd5570SChris Mason 
19e20d96d6SChris Mason #include <linux/fs.h>
20d98237b3SChris Mason #include <linux/blkdev.h>
2187cbda5cSChris Mason #include <linux/scatterlist.h>
2222b0ebdaSChris Mason #include <linux/swap.h>
230f7d52f4SChris Mason #include <linux/radix-tree.h>
2435b7e476SChris Mason #include <linux/writeback.h>
25d397712bSChris Mason #include <linux/buffer_head.h>
26ce9adaa5SChris Mason #include <linux/workqueue.h>
27a74a4b97SChris Mason #include <linux/kthread.h>
285a0e3ad6STejun Heo #include <linux/slab.h>
29784b4e29SChris Mason #include <linux/migrate.h>
307a36ddecSDavid Sterba #include <linux/ratelimit.h>
316463fe58SStefan Behrens #include <linux/uuid.h>
32803b2f54SStefan Behrens #include <linux/semaphore.h>
337e75bf3fSDavid Sterba #include <asm/unaligned.h>
34eb60ceacSChris Mason #include "ctree.h"
35eb60ceacSChris Mason #include "disk-io.h"
360b947affSFilipe David Borba Manana #include "hash.h"
37e089f05cSChris Mason #include "transaction.h"
380f7d52f4SChris Mason #include "btrfs_inode.h"
390b86a832SChris Mason #include "volumes.h"
40db94535dSChris Mason #include "print-tree.h"
41925baeddSChris Mason #include "locking.h"
42e02119d5SChris Mason #include "tree-log.h"
43fa9c0d79SChris Mason #include "free-space-cache.h"
4470f6d82eSOmar Sandoval #include "free-space-tree.h"
45581bb050SLi Zefan #include "inode-map.h"
4621adbd5cSStefan Behrens #include "check-integrity.h"
47606686eeSJosef Bacik #include "rcu-string.h"
488dabb742SStefan Behrens #include "dev-replace.h"
4953b381b3SDavid Woodhouse #include "raid56.h"
505ac1d209SJeff Mahoney #include "sysfs.h"
51fcebe456SJosef Bacik #include "qgroup.h"
52ebb8765bSAnand Jain #include "compression.h"
53eb60ceacSChris Mason 
54de0022b9SJosef Bacik #ifdef CONFIG_X86
55de0022b9SJosef Bacik #include <asm/cpufeature.h>
56de0022b9SJosef Bacik #endif
57de0022b9SJosef Bacik 
58319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
59319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
60319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
61319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
62319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_METADUMP)
63319e4d06SQu Wenruo 
64e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops;
658b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
664df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root);
673d3a126aSDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info);
68143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
69acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
702ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
71143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
722ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
73acce952bSliubo 					struct extent_io_tree *dirty_pages,
74acce952bSliubo 					int mark);
752ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
76acce952bSliubo 				       struct extent_io_tree *pinned_extents);
772ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
782ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
79ce9adaa5SChris Mason 
80d352ac68SChris Mason /*
8197eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
8297eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
83d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
84d352ac68SChris Mason  */
8597eb6b69SDavid Sterba struct btrfs_end_io_wq {
86ce9adaa5SChris Mason 	struct bio *bio;
87ce9adaa5SChris Mason 	bio_end_io_t *end_io;
88ce9adaa5SChris Mason 	void *private;
89ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
90ce9adaa5SChris Mason 	int error;
91bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
92ce9adaa5SChris Mason 	struct list_head list;
938b712842SChris Mason 	struct btrfs_work work;
94ce9adaa5SChris Mason };
950da5468fSChris Mason 
9697eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
9797eb6b69SDavid Sterba 
9897eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
9997eb6b69SDavid Sterba {
10097eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
10197eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
10297eb6b69SDavid Sterba 					0,
103fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
10497eb6b69SDavid Sterba 					NULL);
10597eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
10697eb6b69SDavid Sterba 		return -ENOMEM;
10797eb6b69SDavid Sterba 	return 0;
10897eb6b69SDavid Sterba }
10997eb6b69SDavid Sterba 
11097eb6b69SDavid Sterba void btrfs_end_io_wq_exit(void)
11197eb6b69SDavid Sterba {
11297eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
11397eb6b69SDavid Sterba }
11497eb6b69SDavid Sterba 
115d352ac68SChris Mason /*
116d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
117d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
118d352ac68SChris Mason  * just before they are sent down the IO stack.
119d352ac68SChris Mason  */
12044b8bd7eSChris Mason struct async_submit_bio {
12144b8bd7eSChris Mason 	struct inode *inode;
12244b8bd7eSChris Mason 	struct bio *bio;
12344b8bd7eSChris Mason 	struct list_head list;
1244a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_start;
1254a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_done;
12644b8bd7eSChris Mason 	int mirror_num;
127c8b97818SChris Mason 	unsigned long bio_flags;
128eaf25d93SChris Mason 	/*
129eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
130eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
131eaf25d93SChris Mason 	 */
132eaf25d93SChris Mason 	u64 bio_offset;
1338b712842SChris Mason 	struct btrfs_work work;
13479787eaaSJeff Mahoney 	int error;
13544b8bd7eSChris Mason };
13644b8bd7eSChris Mason 
13785d4e461SChris Mason /*
13885d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
13985d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
14085d4e461SChris Mason  * the level the eb occupies in the tree.
1414008c04aSChris Mason  *
14285d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
14385d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
14485d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
14585d4e461SChris Mason  * by btrfs_root->objectid.  This ensures that all special purpose roots
14685d4e461SChris Mason  * have separate keysets.
1474008c04aSChris Mason  *
14885d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
14985d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
15085d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1514008c04aSChris Mason  *
15285d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
15385d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
15485d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
15585d4e461SChris Mason  *
15685d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
15785d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
15885d4e461SChris Mason  * needs update as well.
1594008c04aSChris Mason  */
1604008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1614008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1624008c04aSChris Mason #  error
1634008c04aSChris Mason # endif
16485d4e461SChris Mason 
16585d4e461SChris Mason static struct btrfs_lockdep_keyset {
16685d4e461SChris Mason 	u64			id;		/* root objectid */
16785d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
16885d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
16985d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
17085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
17185d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
17285d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
17385d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
17485d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
17585d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
17685d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
17760b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
17885d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
17985d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
18085d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
18113fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
1826b20e0adSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	.name_stem = "free-space" },
18385d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1844008c04aSChris Mason };
18585d4e461SChris Mason 
18685d4e461SChris Mason void __init btrfs_init_lockdep(void)
18785d4e461SChris Mason {
18885d4e461SChris Mason 	int i, j;
18985d4e461SChris Mason 
19085d4e461SChris Mason 	/* initialize lockdep class names */
19185d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
19285d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
19385d4e461SChris Mason 
19485d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
19585d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
19685d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
19785d4e461SChris Mason 	}
19885d4e461SChris Mason }
19985d4e461SChris Mason 
20085d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
20185d4e461SChris Mason 				    int level)
20285d4e461SChris Mason {
20385d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
20485d4e461SChris Mason 
20585d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
20685d4e461SChris Mason 
20785d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
20885d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
20985d4e461SChris Mason 		if (ks->id == objectid)
21085d4e461SChris Mason 			break;
21185d4e461SChris Mason 
21285d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
21385d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
21485d4e461SChris Mason }
21585d4e461SChris Mason 
2164008c04aSChris Mason #endif
2174008c04aSChris Mason 
218d352ac68SChris Mason /*
219d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
220d352ac68SChris Mason  * that covers the entire device
221d352ac68SChris Mason  */
222b2950863SChristoph Hellwig static struct extent_map *btree_get_extent(struct inode *inode,
223306e16ceSDavid Sterba 		struct page *page, size_t pg_offset, u64 start, u64 len,
2245f39d397SChris Mason 		int create)
2255f39d397SChris Mason {
2260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2275f39d397SChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2285f39d397SChris Mason 	struct extent_map *em;
2295f39d397SChris Mason 	int ret;
2305f39d397SChris Mason 
231890871beSChris Mason 	read_lock(&em_tree->lock);
232d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
233a061fc8dSChris Mason 	if (em) {
2340b246afaSJeff Mahoney 		em->bdev = fs_info->fs_devices->latest_bdev;
235890871beSChris Mason 		read_unlock(&em_tree->lock);
2365f39d397SChris Mason 		goto out;
237a061fc8dSChris Mason 	}
238890871beSChris Mason 	read_unlock(&em_tree->lock);
2397b13b7b1SChris Mason 
240172ddd60SDavid Sterba 	em = alloc_extent_map();
2415f39d397SChris Mason 	if (!em) {
2425f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2435f39d397SChris Mason 		goto out;
2445f39d397SChris Mason 	}
2455f39d397SChris Mason 	em->start = 0;
2460afbaf8cSChris Mason 	em->len = (u64)-1;
247c8b97818SChris Mason 	em->block_len = (u64)-1;
2485f39d397SChris Mason 	em->block_start = 0;
2490b246afaSJeff Mahoney 	em->bdev = fs_info->fs_devices->latest_bdev;
250d1310b2eSChris Mason 
251890871beSChris Mason 	write_lock(&em_tree->lock);
25209a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2535f39d397SChris Mason 	if (ret == -EEXIST) {
2545f39d397SChris Mason 		free_extent_map(em);
2557b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
256b4f359abSTsutomu Itoh 		if (!em)
2570433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2585f39d397SChris Mason 	} else if (ret) {
2597b13b7b1SChris Mason 		free_extent_map(em);
2600433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2615f39d397SChris Mason 	}
262890871beSChris Mason 	write_unlock(&em_tree->lock);
2637b13b7b1SChris Mason 
2645f39d397SChris Mason out:
2655f39d397SChris Mason 	return em;
2665f39d397SChris Mason }
2675f39d397SChris Mason 
268b0496686SLiu Bo u32 btrfs_csum_data(char *data, u32 seed, size_t len)
26919c00ddcSChris Mason {
2700b947affSFilipe David Borba Manana 	return btrfs_crc32c(seed, data, len);
27119c00ddcSChris Mason }
27219c00ddcSChris Mason 
2730b5e3dafSDomagoj Tršan void btrfs_csum_final(u32 crc, u8 *result)
27419c00ddcSChris Mason {
2757e75bf3fSDavid Sterba 	put_unaligned_le32(~crc, result);
27619c00ddcSChris Mason }
27719c00ddcSChris Mason 
278d352ac68SChris Mason /*
279d352ac68SChris Mason  * compute the csum for a btree block, and either verify it or write it
280d352ac68SChris Mason  * into the csum field of the block.
281d352ac68SChris Mason  */
28201d58472SDaniel Dressler static int csum_tree_block(struct btrfs_fs_info *fs_info,
28301d58472SDaniel Dressler 			   struct extent_buffer *buf,
28419c00ddcSChris Mason 			   int verify)
28519c00ddcSChris Mason {
28601d58472SDaniel Dressler 	u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
287607d432dSJosef Bacik 	char *result = NULL;
28819c00ddcSChris Mason 	unsigned long len;
28919c00ddcSChris Mason 	unsigned long cur_len;
29019c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
29119c00ddcSChris Mason 	char *kaddr;
29219c00ddcSChris Mason 	unsigned long map_start;
29319c00ddcSChris Mason 	unsigned long map_len;
29419c00ddcSChris Mason 	int err;
29519c00ddcSChris Mason 	u32 crc = ~(u32)0;
296607d432dSJosef Bacik 	unsigned long inline_result;
29719c00ddcSChris Mason 
29819c00ddcSChris Mason 	len = buf->len - offset;
29919c00ddcSChris Mason 	while (len > 0) {
30019c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
301a6591715SChris Mason 					&kaddr, &map_start, &map_len);
302d397712bSChris Mason 		if (err)
3038bd98f0eSAlex Lyakas 			return err;
30419c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
305b0496686SLiu Bo 		crc = btrfs_csum_data(kaddr + offset - map_start,
30619c00ddcSChris Mason 				      crc, cur_len);
30719c00ddcSChris Mason 		len -= cur_len;
30819c00ddcSChris Mason 		offset += cur_len;
30919c00ddcSChris Mason 	}
310607d432dSJosef Bacik 	if (csum_size > sizeof(inline_result)) {
31131e818feSDavid Sterba 		result = kzalloc(csum_size, GFP_NOFS);
312607d432dSJosef Bacik 		if (!result)
3138bd98f0eSAlex Lyakas 			return -ENOMEM;
314607d432dSJosef Bacik 	} else {
315607d432dSJosef Bacik 		result = (char *)&inline_result;
316607d432dSJosef Bacik 	}
317607d432dSJosef Bacik 
31819c00ddcSChris Mason 	btrfs_csum_final(crc, result);
31919c00ddcSChris Mason 
32019c00ddcSChris Mason 	if (verify) {
321607d432dSJosef Bacik 		if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
322e4204dedSChris Mason 			u32 val;
323e4204dedSChris Mason 			u32 found = 0;
324607d432dSJosef Bacik 			memcpy(&found, result, csum_size);
325e4204dedSChris Mason 
326607d432dSJosef Bacik 			read_extent_buffer(buf, &val, 0, csum_size);
32794647322SDavid Sterba 			btrfs_warn_rl(fs_info,
3285d163e0eSJeff Mahoney 				"%s checksum verify failed on %llu wanted %X found %X level %d",
32901d58472SDaniel Dressler 				fs_info->sb->s_id, buf->start,
330c1c9ff7cSGeert Uytterhoeven 				val, found, btrfs_header_level(buf));
331607d432dSJosef Bacik 			if (result != (char *)&inline_result)
332607d432dSJosef Bacik 				kfree(result);
3338bd98f0eSAlex Lyakas 			return -EUCLEAN;
33419c00ddcSChris Mason 		}
33519c00ddcSChris Mason 	} else {
336607d432dSJosef Bacik 		write_extent_buffer(buf, result, 0, csum_size);
33719c00ddcSChris Mason 	}
338607d432dSJosef Bacik 	if (result != (char *)&inline_result)
339607d432dSJosef Bacik 		kfree(result);
34019c00ddcSChris Mason 	return 0;
34119c00ddcSChris Mason }
34219c00ddcSChris Mason 
343d352ac68SChris Mason /*
344d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
345d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
346d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
347d352ac68SChris Mason  * in the wrong place.
348d352ac68SChris Mason  */
3491259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
350b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
351b9fab919SChris Mason 				 int atomic)
3521259ab75SChris Mason {
3532ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3541259ab75SChris Mason 	int ret;
3552755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
3561259ab75SChris Mason 
3571259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
3581259ab75SChris Mason 		return 0;
3591259ab75SChris Mason 
360b9fab919SChris Mason 	if (atomic)
361b9fab919SChris Mason 		return -EAGAIN;
362b9fab919SChris Mason 
363a26e8c9fSJosef Bacik 	if (need_lock) {
364a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
365a26e8c9fSJosef Bacik 		btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
366a26e8c9fSJosef Bacik 	}
367a26e8c9fSJosef Bacik 
3682ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
369ff13db41SDavid Sterba 			 &cached_state);
3700b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3711259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3721259ab75SChris Mason 		ret = 0;
3731259ab75SChris Mason 		goto out;
3741259ab75SChris Mason 	}
37594647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
37694647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
37794647322SDavid Sterba 			eb->start,
37829549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3791259ab75SChris Mason 	ret = 1;
380a26e8c9fSJosef Bacik 
381a26e8c9fSJosef Bacik 	/*
382a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
383a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
38401327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
385a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
386a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
387a26e8c9fSJosef Bacik 	 * making everybody very sad.
388a26e8c9fSJosef Bacik 	 */
389a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3900b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
39133958dc6SChris Mason out:
3922ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
3932ac55d41SJosef Bacik 			     &cached_state, GFP_NOFS);
394472b909fSJosef Bacik 	if (need_lock)
395a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3961259ab75SChris Mason 	return ret;
3971259ab75SChris Mason }
3981259ab75SChris Mason 
399d352ac68SChris Mason /*
4001104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
4011104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
4021104a885SDavid Sterba  */
403ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
404ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
4051104a885SDavid Sterba {
4061104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
4071104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
4081104a885SDavid Sterba 	u16 csum_type = btrfs_super_csum_type(disk_sb);
4091104a885SDavid Sterba 	int ret = 0;
4101104a885SDavid Sterba 
4111104a885SDavid Sterba 	if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
4121104a885SDavid Sterba 		u32 crc = ~(u32)0;
4131104a885SDavid Sterba 		const int csum_size = sizeof(crc);
4141104a885SDavid Sterba 		char result[csum_size];
4151104a885SDavid Sterba 
4161104a885SDavid Sterba 		/*
4171104a885SDavid Sterba 		 * The super_block structure does not span the whole
4181104a885SDavid Sterba 		 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
41901327610SNicholas D Steeves 		 * is filled with zeros and is included in the checksum.
4201104a885SDavid Sterba 		 */
4211104a885SDavid Sterba 		crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
4221104a885SDavid Sterba 				crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
4231104a885SDavid Sterba 		btrfs_csum_final(crc, result);
4241104a885SDavid Sterba 
4251104a885SDavid Sterba 		if (memcmp(raw_disk_sb, result, csum_size))
4261104a885SDavid Sterba 			ret = 1;
4271104a885SDavid Sterba 	}
4281104a885SDavid Sterba 
4291104a885SDavid Sterba 	if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
430ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "unsupported checksum algorithm %u",
4311104a885SDavid Sterba 				csum_type);
4321104a885SDavid Sterba 		ret = 1;
4331104a885SDavid Sterba 	}
4341104a885SDavid Sterba 
4351104a885SDavid Sterba 	return ret;
4361104a885SDavid Sterba }
4371104a885SDavid Sterba 
4381104a885SDavid Sterba /*
439d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
440d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
441d352ac68SChris Mason  */
4422ff7e61eSJeff Mahoney static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
443f188591eSChris Mason 					  struct extent_buffer *eb,
4448436ea91SJosef Bacik 					  u64 parent_transid)
445f188591eSChris Mason {
446f188591eSChris Mason 	struct extent_io_tree *io_tree;
447ea466794SJosef Bacik 	int failed = 0;
448f188591eSChris Mason 	int ret;
449f188591eSChris Mason 	int num_copies = 0;
450f188591eSChris Mason 	int mirror_num = 0;
451ea466794SJosef Bacik 	int failed_mirror = 0;
452f188591eSChris Mason 
453a826d6dcSJosef Bacik 	clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
4540b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
455f188591eSChris Mason 	while (1) {
4568436ea91SJosef Bacik 		ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
457f188591eSChris Mason 					       btree_get_extent, mirror_num);
458256dd1bbSStefan Behrens 		if (!ret) {
459256dd1bbSStefan Behrens 			if (!verify_parent_transid(io_tree, eb,
460b9fab919SChris Mason 						   parent_transid, 0))
461ea466794SJosef Bacik 				break;
462256dd1bbSStefan Behrens 			else
463256dd1bbSStefan Behrens 				ret = -EIO;
464256dd1bbSStefan Behrens 		}
465d397712bSChris Mason 
466a826d6dcSJosef Bacik 		/*
467a826d6dcSJosef Bacik 		 * This buffer's crc is fine, but its contents are corrupted, so
468a826d6dcSJosef Bacik 		 * there is no reason to read the other copies, they won't be
469a826d6dcSJosef Bacik 		 * any less wrong.
470a826d6dcSJosef Bacik 		 */
471a826d6dcSJosef Bacik 		if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
472ea466794SJosef Bacik 			break;
473ea466794SJosef Bacik 
4740b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
475f188591eSChris Mason 					      eb->start, eb->len);
4764235298eSChris Mason 		if (num_copies == 1)
477ea466794SJosef Bacik 			break;
4784235298eSChris Mason 
4795cf1ab56SJosef Bacik 		if (!failed_mirror) {
4805cf1ab56SJosef Bacik 			failed = 1;
4815cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4825cf1ab56SJosef Bacik 		}
4835cf1ab56SJosef Bacik 
484f188591eSChris Mason 		mirror_num++;
485ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
486ea466794SJosef Bacik 			mirror_num++;
487ea466794SJosef Bacik 
4884235298eSChris Mason 		if (mirror_num > num_copies)
489ea466794SJosef Bacik 			break;
490f188591eSChris Mason 	}
491ea466794SJosef Bacik 
492c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
4932ff7e61eSJeff Mahoney 		repair_eb_io_failure(fs_info, eb, failed_mirror);
494ea466794SJosef Bacik 
495ea466794SJosef Bacik 	return ret;
496f188591eSChris Mason }
49719c00ddcSChris Mason 
498d352ac68SChris Mason /*
499d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
500d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
501d352ac68SChris Mason  */
502d397712bSChris Mason 
50301d58472SDaniel Dressler static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
50419c00ddcSChris Mason {
5054eee4fa4SMiao Xie 	u64 start = page_offset(page);
50619c00ddcSChris Mason 	u64 found_start;
50719c00ddcSChris Mason 	struct extent_buffer *eb;
508f188591eSChris Mason 
5094f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5104f2de97aSJosef Bacik 	if (page != eb->pages[0])
5114f2de97aSJosef Bacik 		return 0;
5120f805531SAlex Lyakas 
51319c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
5140f805531SAlex Lyakas 	/*
5150f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5160f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5170f805531SAlex Lyakas 	 */
5180f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5190f805531SAlex Lyakas 		return -EUCLEAN;
5200f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5210f805531SAlex Lyakas 		return -EUCLEAN;
5220f805531SAlex Lyakas 
5230f805531SAlex Lyakas 	ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
5240f805531SAlex Lyakas 			btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
5250f805531SAlex Lyakas 
5268bd98f0eSAlex Lyakas 	return csum_tree_block(fs_info, eb, 0);
52719c00ddcSChris Mason }
52819c00ddcSChris Mason 
52901d58472SDaniel Dressler static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
5302b82032cSYan Zheng 				 struct extent_buffer *eb)
5312b82032cSYan Zheng {
53201d58472SDaniel Dressler 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
5332b82032cSYan Zheng 	u8 fsid[BTRFS_UUID_SIZE];
5342b82032cSYan Zheng 	int ret = 1;
5352b82032cSYan Zheng 
5360a4e5586SRoss Kirk 	read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
5372b82032cSYan Zheng 	while (fs_devices) {
5382b82032cSYan Zheng 		if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
5392b82032cSYan Zheng 			ret = 0;
5402b82032cSYan Zheng 			break;
5412b82032cSYan Zheng 		}
5422b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5432b82032cSYan Zheng 	}
5442b82032cSYan Zheng 	return ret;
5452b82032cSYan Zheng }
5462b82032cSYan Zheng 
547a826d6dcSJosef Bacik #define CORRUPT(reason, eb, root, slot)					\
5480b246afaSJeff Mahoney 	btrfs_crit(root->fs_info,					\
5490b246afaSJeff Mahoney 		   "corrupt %s, %s: block=%llu, root=%llu, slot=%d",	\
5506b722c17SLiu Bo 		   btrfs_header_level(eb) == 0 ? "leaf" : "node",	\
5516b722c17SLiu Bo 		   reason, btrfs_header_bytenr(eb), root->objectid, slot)
552a826d6dcSJosef Bacik 
553a826d6dcSJosef Bacik static noinline int check_leaf(struct btrfs_root *root,
554a826d6dcSJosef Bacik 			       struct extent_buffer *leaf)
555a826d6dcSJosef Bacik {
5560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
557a826d6dcSJosef Bacik 	struct btrfs_key key;
558a826d6dcSJosef Bacik 	struct btrfs_key leaf_key;
559a826d6dcSJosef Bacik 	u32 nritems = btrfs_header_nritems(leaf);
560a826d6dcSJosef Bacik 	int slot;
561a826d6dcSJosef Bacik 
562f177d739SFilipe Manana 	/*
563f177d739SFilipe Manana 	 * Extent buffers from a relocation tree have a owner field that
564f177d739SFilipe Manana 	 * corresponds to the subvolume tree they are based on. So just from an
565f177d739SFilipe Manana 	 * extent buffer alone we can not find out what is the id of the
566f177d739SFilipe Manana 	 * corresponding subvolume tree, so we can not figure out if the extent
567f177d739SFilipe Manana 	 * buffer corresponds to the root of the relocation tree or not. So skip
568f177d739SFilipe Manana 	 * this check for relocation trees.
569f177d739SFilipe Manana 	 */
570f177d739SFilipe Manana 	if (nritems == 0 && !btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_RELOC)) {
5711ba98d08SLiu Bo 		struct btrfs_root *check_root;
5721ba98d08SLiu Bo 
5731ba98d08SLiu Bo 		key.objectid = btrfs_header_owner(leaf);
5741ba98d08SLiu Bo 		key.type = BTRFS_ROOT_ITEM_KEY;
5751ba98d08SLiu Bo 		key.offset = (u64)-1;
5761ba98d08SLiu Bo 
5770b246afaSJeff Mahoney 		check_root = btrfs_get_fs_root(fs_info, &key, false);
5781ba98d08SLiu Bo 		/*
5791ba98d08SLiu Bo 		 * The only reason we also check NULL here is that during
5801ba98d08SLiu Bo 		 * open_ctree() some roots has not yet been set up.
5811ba98d08SLiu Bo 		 */
5821ba98d08SLiu Bo 		if (!IS_ERR_OR_NULL(check_root)) {
583ef85b25eSLiu Bo 			struct extent_buffer *eb;
584ef85b25eSLiu Bo 
585ef85b25eSLiu Bo 			eb = btrfs_root_node(check_root);
5861ba98d08SLiu Bo 			/* if leaf is the root, then it's fine */
587ef85b25eSLiu Bo 			if (leaf != eb) {
5881ba98d08SLiu Bo 				CORRUPT("non-root leaf's nritems is 0",
589ef85b25eSLiu Bo 					leaf, check_root, 0);
590ef85b25eSLiu Bo 				free_extent_buffer(eb);
5911ba98d08SLiu Bo 				return -EIO;
5921ba98d08SLiu Bo 			}
593ef85b25eSLiu Bo 			free_extent_buffer(eb);
5941ba98d08SLiu Bo 		}
595a826d6dcSJosef Bacik 		return 0;
5961ba98d08SLiu Bo 	}
597a826d6dcSJosef Bacik 
598f177d739SFilipe Manana 	if (nritems == 0)
599f177d739SFilipe Manana 		return 0;
600f177d739SFilipe Manana 
601a826d6dcSJosef Bacik 	/* Check the 0 item */
602a826d6dcSJosef Bacik 	if (btrfs_item_offset_nr(leaf, 0) + btrfs_item_size_nr(leaf, 0) !=
6030b246afaSJeff Mahoney 	    BTRFS_LEAF_DATA_SIZE(fs_info)) {
604a826d6dcSJosef Bacik 		CORRUPT("invalid item offset size pair", leaf, root, 0);
605a826d6dcSJosef Bacik 		return -EIO;
606a826d6dcSJosef Bacik 	}
607a826d6dcSJosef Bacik 
608a826d6dcSJosef Bacik 	/*
609a826d6dcSJosef Bacik 	 * Check to make sure each items keys are in the correct order and their
610a826d6dcSJosef Bacik 	 * offsets make sense.  We only have to loop through nritems-1 because
611a826d6dcSJosef Bacik 	 * we check the current slot against the next slot, which verifies the
612a826d6dcSJosef Bacik 	 * next slot's offset+size makes sense and that the current's slot
613a826d6dcSJosef Bacik 	 * offset is correct.
614a826d6dcSJosef Bacik 	 */
615a826d6dcSJosef Bacik 	for (slot = 0; slot < nritems - 1; slot++) {
616a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &leaf_key, slot);
617a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &key, slot + 1);
618a826d6dcSJosef Bacik 
619a826d6dcSJosef Bacik 		/* Make sure the keys are in the right order */
620a826d6dcSJosef Bacik 		if (btrfs_comp_cpu_keys(&leaf_key, &key) >= 0) {
621a826d6dcSJosef Bacik 			CORRUPT("bad key order", leaf, root, slot);
622a826d6dcSJosef Bacik 			return -EIO;
623a826d6dcSJosef Bacik 		}
624a826d6dcSJosef Bacik 
625a826d6dcSJosef Bacik 		/*
626a826d6dcSJosef Bacik 		 * Make sure the offset and ends are right, remember that the
627a826d6dcSJosef Bacik 		 * item data starts at the end of the leaf and grows towards the
628a826d6dcSJosef Bacik 		 * front.
629a826d6dcSJosef Bacik 		 */
630a826d6dcSJosef Bacik 		if (btrfs_item_offset_nr(leaf, slot) !=
631a826d6dcSJosef Bacik 			btrfs_item_end_nr(leaf, slot + 1)) {
632a826d6dcSJosef Bacik 			CORRUPT("slot offset bad", leaf, root, slot);
633a826d6dcSJosef Bacik 			return -EIO;
634a826d6dcSJosef Bacik 		}
635a826d6dcSJosef Bacik 
636a826d6dcSJosef Bacik 		/*
637a826d6dcSJosef Bacik 		 * Check to make sure that we don't point outside of the leaf,
638a826d6dcSJosef Bacik 		 * just in case all the items are consistent to each other, but
639a826d6dcSJosef Bacik 		 * all point outside of the leaf.
640a826d6dcSJosef Bacik 		 */
641a826d6dcSJosef Bacik 		if (btrfs_item_end_nr(leaf, slot) >
6420b246afaSJeff Mahoney 		    BTRFS_LEAF_DATA_SIZE(fs_info)) {
643a826d6dcSJosef Bacik 			CORRUPT("slot end outside of leaf", leaf, root, slot);
644a826d6dcSJosef Bacik 			return -EIO;
645a826d6dcSJosef Bacik 		}
646a826d6dcSJosef Bacik 	}
647a826d6dcSJosef Bacik 
648a826d6dcSJosef Bacik 	return 0;
649a826d6dcSJosef Bacik }
650a826d6dcSJosef Bacik 
651053ab70fSLiu Bo static int check_node(struct btrfs_root *root, struct extent_buffer *node)
652053ab70fSLiu Bo {
653053ab70fSLiu Bo 	unsigned long nr = btrfs_header_nritems(node);
6546b722c17SLiu Bo 	struct btrfs_key key, next_key;
6556b722c17SLiu Bo 	int slot;
6566b722c17SLiu Bo 	u64 bytenr;
6576b722c17SLiu Bo 	int ret = 0;
658053ab70fSLiu Bo 
659da17066cSJeff Mahoney 	if (nr == 0 || nr > BTRFS_NODEPTRS_PER_BLOCK(root->fs_info)) {
660053ab70fSLiu Bo 		btrfs_crit(root->fs_info,
661053ab70fSLiu Bo 			   "corrupt node: block %llu root %llu nritems %lu",
662053ab70fSLiu Bo 			   node->start, root->objectid, nr);
663053ab70fSLiu Bo 		return -EIO;
664053ab70fSLiu Bo 	}
6656b722c17SLiu Bo 
6666b722c17SLiu Bo 	for (slot = 0; slot < nr - 1; slot++) {
6676b722c17SLiu Bo 		bytenr = btrfs_node_blockptr(node, slot);
6686b722c17SLiu Bo 		btrfs_node_key_to_cpu(node, &key, slot);
6696b722c17SLiu Bo 		btrfs_node_key_to_cpu(node, &next_key, slot + 1);
6706b722c17SLiu Bo 
6716b722c17SLiu Bo 		if (!bytenr) {
6726b722c17SLiu Bo 			CORRUPT("invalid item slot", node, root, slot);
6736b722c17SLiu Bo 			ret = -EIO;
6746b722c17SLiu Bo 			goto out;
6756b722c17SLiu Bo 		}
6766b722c17SLiu Bo 
6776b722c17SLiu Bo 		if (btrfs_comp_cpu_keys(&key, &next_key) >= 0) {
6786b722c17SLiu Bo 			CORRUPT("bad key order", node, root, slot);
6796b722c17SLiu Bo 			ret = -EIO;
6806b722c17SLiu Bo 			goto out;
6816b722c17SLiu Bo 		}
6826b722c17SLiu Bo 	}
6836b722c17SLiu Bo out:
6846b722c17SLiu Bo 	return ret;
685053ab70fSLiu Bo }
686053ab70fSLiu Bo 
687facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
688facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
689facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
690ce9adaa5SChris Mason {
691ce9adaa5SChris Mason 	u64 found_start;
692ce9adaa5SChris Mason 	int found_level;
693ce9adaa5SChris Mason 	struct extent_buffer *eb;
694ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
69502873e43SZhao Lei 	struct btrfs_fs_info *fs_info = root->fs_info;
696f188591eSChris Mason 	int ret = 0;
697727011e0SChris Mason 	int reads_done;
698ce9adaa5SChris Mason 
699ce9adaa5SChris Mason 	if (!page->private)
700ce9adaa5SChris Mason 		goto out;
701d397712bSChris Mason 
7024f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
703d397712bSChris Mason 
7040b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
7050b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
7060b32f4bbSJosef Bacik 	 */
7070b32f4bbSJosef Bacik 	extent_buffer_get(eb);
7080b32f4bbSJosef Bacik 
7090b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
710727011e0SChris Mason 	if (!reads_done)
711727011e0SChris Mason 		goto err;
712f188591eSChris Mason 
7135cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
714656f30dbSFilipe Manana 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
715ea466794SJosef Bacik 		ret = -EIO;
716ea466794SJosef Bacik 		goto err;
717ea466794SJosef Bacik 	}
718ea466794SJosef Bacik 
719ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
720727011e0SChris Mason 	if (found_start != eb->start) {
72102873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad tree block start %llu %llu",
72294647322SDavid Sterba 			     found_start, eb->start);
723f188591eSChris Mason 		ret = -EIO;
724ce9adaa5SChris Mason 		goto err;
725ce9adaa5SChris Mason 	}
72602873e43SZhao Lei 	if (check_tree_block_fsid(fs_info, eb)) {
72702873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
72894647322SDavid Sterba 			     eb->start);
7291259ab75SChris Mason 		ret = -EIO;
7301259ab75SChris Mason 		goto err;
7311259ab75SChris Mason 	}
732ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
7331c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
73402873e43SZhao Lei 		btrfs_err(fs_info, "bad tree block level %d",
7351c24c3ceSJosef Bacik 			  (int)btrfs_header_level(eb));
7361c24c3ceSJosef Bacik 		ret = -EIO;
7371c24c3ceSJosef Bacik 		goto err;
7381c24c3ceSJosef Bacik 	}
739ce9adaa5SChris Mason 
74085d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
74185d4e461SChris Mason 				       eb, found_level);
7424008c04aSChris Mason 
74302873e43SZhao Lei 	ret = csum_tree_block(fs_info, eb, 1);
7448bd98f0eSAlex Lyakas 	if (ret)
745a826d6dcSJosef Bacik 		goto err;
746a826d6dcSJosef Bacik 
747a826d6dcSJosef Bacik 	/*
748a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
749a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
750a826d6dcSJosef Bacik 	 * return -EIO.
751a826d6dcSJosef Bacik 	 */
752a826d6dcSJosef Bacik 	if (found_level == 0 && check_leaf(root, eb)) {
753a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
754a826d6dcSJosef Bacik 		ret = -EIO;
755a826d6dcSJosef Bacik 	}
756ce9adaa5SChris Mason 
757053ab70fSLiu Bo 	if (found_level > 0 && check_node(root, eb))
758053ab70fSLiu Bo 		ret = -EIO;
759053ab70fSLiu Bo 
7600b32f4bbSJosef Bacik 	if (!ret)
7610b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
762ce9adaa5SChris Mason err:
76379fb65a1SJosef Bacik 	if (reads_done &&
76479fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
765fc2e901fSDavid Sterba 		btree_readahead_hook(fs_info, eb, ret);
7664bb31e92SArne Jansen 
76753b381b3SDavid Woodhouse 	if (ret) {
76853b381b3SDavid Woodhouse 		/*
76953b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
77053b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
77153b381b3SDavid Woodhouse 		 * to decrement
77253b381b3SDavid Woodhouse 		 */
77353b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7740b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
77553b381b3SDavid Woodhouse 	}
7760b32f4bbSJosef Bacik 	free_extent_buffer(eb);
777ce9adaa5SChris Mason out:
778f188591eSChris Mason 	return ret;
779ce9adaa5SChris Mason }
780ce9adaa5SChris Mason 
781ea466794SJosef Bacik static int btree_io_failed_hook(struct page *page, int failed_mirror)
7824bb31e92SArne Jansen {
7834bb31e92SArne Jansen 	struct extent_buffer *eb;
7844bb31e92SArne Jansen 
7854f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
786656f30dbSFilipe Manana 	set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
7875cf1ab56SJosef Bacik 	eb->read_mirror = failed_mirror;
78853b381b3SDavid Woodhouse 	atomic_dec(&eb->io_pages);
789ea466794SJosef Bacik 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
790fc2e901fSDavid Sterba 		btree_readahead_hook(eb->fs_info, eb, -EIO);
7914bb31e92SArne Jansen 	return -EIO;	/* we fixed nothing */
7924bb31e92SArne Jansen }
7934bb31e92SArne Jansen 
7944246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
795ce9adaa5SChris Mason {
79697eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
797ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7989e0af237SLiu Bo 	struct btrfs_workqueue *wq;
7999e0af237SLiu Bo 	btrfs_work_func_t func;
800ce9adaa5SChris Mason 
801ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
8024246a0b6SChristoph Hellwig 	end_io_wq->error = bio->bi_error;
803d20f7043SChris Mason 
80437226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
8059e0af237SLiu Bo 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
8069e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
8079e0af237SLiu Bo 			func = btrfs_endio_meta_write_helper;
8089e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
8099e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
8109e0af237SLiu Bo 			func = btrfs_freespace_write_helper;
8119e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
8129e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
8139e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
814d20f7043SChris Mason 		} else {
8159e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
8169e0af237SLiu Bo 			func = btrfs_endio_write_helper;
817d20f7043SChris Mason 		}
8189e0af237SLiu Bo 	} else {
8198b110e39SMiao Xie 		if (unlikely(end_io_wq->metadata ==
8208b110e39SMiao Xie 			     BTRFS_WQ_ENDIO_DIO_REPAIR)) {
8218b110e39SMiao Xie 			wq = fs_info->endio_repair_workers;
8228b110e39SMiao Xie 			func = btrfs_endio_repair_helper;
8238b110e39SMiao Xie 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
8249e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
8259e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
8269e0af237SLiu Bo 		} else if (end_io_wq->metadata) {
8279e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
8289e0af237SLiu Bo 			func = btrfs_endio_meta_helper;
8299e0af237SLiu Bo 		} else {
8309e0af237SLiu Bo 			wq = fs_info->endio_workers;
8319e0af237SLiu Bo 			func = btrfs_endio_helper;
8329e0af237SLiu Bo 		}
8339e0af237SLiu Bo 	}
8349e0af237SLiu Bo 
8359e0af237SLiu Bo 	btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
8369e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
837ce9adaa5SChris Mason }
838ce9adaa5SChris Mason 
83922c59948SChris Mason int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
840bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
8410b86a832SChris Mason {
84297eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
8438b110e39SMiao Xie 
84497eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
845ce9adaa5SChris Mason 	if (!end_io_wq)
846ce9adaa5SChris Mason 		return -ENOMEM;
847ce9adaa5SChris Mason 
848ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
849ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
85022c59948SChris Mason 	end_io_wq->info = info;
851ce9adaa5SChris Mason 	end_io_wq->error = 0;
852ce9adaa5SChris Mason 	end_io_wq->bio = bio;
85322c59948SChris Mason 	end_io_wq->metadata = metadata;
854ce9adaa5SChris Mason 
855ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
856ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
85722c59948SChris Mason 	return 0;
85822c59948SChris Mason }
85922c59948SChris Mason 
860b64a2851SChris Mason unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
8614854ddd0SChris Mason {
8624854ddd0SChris Mason 	unsigned long limit = min_t(unsigned long,
8635cdc7ad3SQu Wenruo 				    info->thread_pool_size,
8644854ddd0SChris Mason 				    info->fs_devices->open_devices);
8654854ddd0SChris Mason 	return 256 * limit;
8664854ddd0SChris Mason }
8674854ddd0SChris Mason 
8684a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
8694a69a410SChris Mason {
8704a69a410SChris Mason 	struct async_submit_bio *async;
87179787eaaSJeff Mahoney 	int ret;
8724a69a410SChris Mason 
8734a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
87481a75f67SMike Christie 	ret = async->submit_bio_start(async->inode, async->bio,
875eaf25d93SChris Mason 				      async->mirror_num, async->bio_flags,
876eaf25d93SChris Mason 				      async->bio_offset);
87779787eaaSJeff Mahoney 	if (ret)
87879787eaaSJeff Mahoney 		async->error = ret;
8794a69a410SChris Mason }
8804a69a410SChris Mason 
8814a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
8828b712842SChris Mason {
8838b712842SChris Mason 	struct btrfs_fs_info *fs_info;
8848b712842SChris Mason 	struct async_submit_bio *async;
8854854ddd0SChris Mason 	int limit;
8868b712842SChris Mason 
8878b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8888b712842SChris Mason 	fs_info = BTRFS_I(async->inode)->root->fs_info;
8894854ddd0SChris Mason 
890b64a2851SChris Mason 	limit = btrfs_async_submit_limit(fs_info);
8914854ddd0SChris Mason 	limit = limit * 2 / 3;
8924854ddd0SChris Mason 
893ee863954SDavid Sterba 	/*
894ee863954SDavid Sterba 	 * atomic_dec_return implies a barrier for waitqueue_active
895ee863954SDavid Sterba 	 */
89666657b31SJosef Bacik 	if (atomic_dec_return(&fs_info->nr_async_submits) < limit &&
897b64a2851SChris Mason 	    waitqueue_active(&fs_info->async_submit_wait))
8984854ddd0SChris Mason 		wake_up(&fs_info->async_submit_wait);
8994854ddd0SChris Mason 
900bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
90179787eaaSJeff Mahoney 	if (async->error) {
9024246a0b6SChristoph Hellwig 		async->bio->bi_error = async->error;
9034246a0b6SChristoph Hellwig 		bio_endio(async->bio);
90479787eaaSJeff Mahoney 		return;
90579787eaaSJeff Mahoney 	}
90679787eaaSJeff Mahoney 
90781a75f67SMike Christie 	async->submit_bio_done(async->inode, async->bio, async->mirror_num,
90881a75f67SMike Christie 			       async->bio_flags, async->bio_offset);
9094a69a410SChris Mason }
9104a69a410SChris Mason 
9114a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
9124a69a410SChris Mason {
9134a69a410SChris Mason 	struct async_submit_bio *async;
9144a69a410SChris Mason 
9154a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
9168b712842SChris Mason 	kfree(async);
9178b712842SChris Mason }
9188b712842SChris Mason 
91944b8bd7eSChris Mason int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
92081a75f67SMike Christie 			struct bio *bio, int mirror_num,
921c8b97818SChris Mason 			unsigned long bio_flags,
922eaf25d93SChris Mason 			u64 bio_offset,
9234a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_start,
9244a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_done)
92544b8bd7eSChris Mason {
92644b8bd7eSChris Mason 	struct async_submit_bio *async;
92744b8bd7eSChris Mason 
92844b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
92944b8bd7eSChris Mason 	if (!async)
93044b8bd7eSChris Mason 		return -ENOMEM;
93144b8bd7eSChris Mason 
93244b8bd7eSChris Mason 	async->inode = inode;
93344b8bd7eSChris Mason 	async->bio = bio;
93444b8bd7eSChris Mason 	async->mirror_num = mirror_num;
9354a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
9364a69a410SChris Mason 	async->submit_bio_done = submit_bio_done;
9374a69a410SChris Mason 
9389e0af237SLiu Bo 	btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
9395cdc7ad3SQu Wenruo 			run_one_async_done, run_one_async_free);
9404a69a410SChris Mason 
941c8b97818SChris Mason 	async->bio_flags = bio_flags;
942eaf25d93SChris Mason 	async->bio_offset = bio_offset;
9438c8bee1dSChris Mason 
94479787eaaSJeff Mahoney 	async->error = 0;
94579787eaaSJeff Mahoney 
946cb03c743SChris Mason 	atomic_inc(&fs_info->nr_async_submits);
947d313d7a3SChris Mason 
94867f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
9495cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
950d313d7a3SChris Mason 
9515cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
9529473f16cSChris Mason 
953771ed689SChris Mason 	while (atomic_read(&fs_info->async_submit_draining) &&
954771ed689SChris Mason 	      atomic_read(&fs_info->nr_async_submits)) {
955771ed689SChris Mason 		wait_event(fs_info->async_submit_wait,
956771ed689SChris Mason 			   (atomic_read(&fs_info->nr_async_submits) == 0));
957771ed689SChris Mason 	}
958771ed689SChris Mason 
95944b8bd7eSChris Mason 	return 0;
96044b8bd7eSChris Mason }
96144b8bd7eSChris Mason 
962ce3ed71aSChris Mason static int btree_csum_one_bio(struct bio *bio)
963ce3ed71aSChris Mason {
9642c30c71bSKent Overstreet 	struct bio_vec *bvec;
965ce3ed71aSChris Mason 	struct btrfs_root *root;
9662c30c71bSKent Overstreet 	int i, ret = 0;
967ce3ed71aSChris Mason 
9682c30c71bSKent Overstreet 	bio_for_each_segment_all(bvec, bio, i) {
969ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
97001d58472SDaniel Dressler 		ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
97179787eaaSJeff Mahoney 		if (ret)
97279787eaaSJeff Mahoney 			break;
973ce3ed71aSChris Mason 	}
9742c30c71bSKent Overstreet 
97579787eaaSJeff Mahoney 	return ret;
976ce3ed71aSChris Mason }
977ce3ed71aSChris Mason 
97881a75f67SMike Christie static int __btree_submit_bio_start(struct inode *inode, struct bio *bio,
97981a75f67SMike Christie 				    int mirror_num, unsigned long bio_flags,
980eaf25d93SChris Mason 				    u64 bio_offset)
98122c59948SChris Mason {
9828b712842SChris Mason 	/*
9838b712842SChris Mason 	 * when we're called for a write, we're already in the async
9845443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
9858b712842SChris Mason 	 */
98679787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
98722c59948SChris Mason }
98822c59948SChris Mason 
98981a75f67SMike Christie static int __btree_submit_bio_done(struct inode *inode, struct bio *bio,
990eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
991eaf25d93SChris Mason 				 u64 bio_offset)
9924a69a410SChris Mason {
99361891923SStefan Behrens 	int ret;
99461891923SStefan Behrens 
9958b712842SChris Mason 	/*
9964a69a410SChris Mason 	 * when we're called for a write, we're already in the async
9974a69a410SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
9988b712842SChris Mason 	 */
9992ff7e61eSJeff Mahoney 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), bio, mirror_num, 1);
10004246a0b6SChristoph Hellwig 	if (ret) {
10014246a0b6SChristoph Hellwig 		bio->bi_error = ret;
10024246a0b6SChristoph Hellwig 		bio_endio(bio);
10034246a0b6SChristoph Hellwig 	}
100461891923SStefan Behrens 	return ret;
10050b86a832SChris Mason }
10060b86a832SChris Mason 
1007e27f6265SDavid Sterba static int check_async_write(unsigned long bio_flags)
1008de0022b9SJosef Bacik {
1009de0022b9SJosef Bacik 	if (bio_flags & EXTENT_BIO_TREE_LOG)
1010de0022b9SJosef Bacik 		return 0;
1011de0022b9SJosef Bacik #ifdef CONFIG_X86
1012bc696ca0SBorislav Petkov 	if (static_cpu_has(X86_FEATURE_XMM4_2))
1013de0022b9SJosef Bacik 		return 0;
1014de0022b9SJosef Bacik #endif
1015de0022b9SJosef Bacik 	return 1;
1016de0022b9SJosef Bacik }
1017de0022b9SJosef Bacik 
101881a75f67SMike Christie static int btree_submit_bio_hook(struct inode *inode, struct bio *bio,
1019eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
1020eaf25d93SChris Mason 				 u64 bio_offset)
102144b8bd7eSChris Mason {
10220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1023e27f6265SDavid Sterba 	int async = check_async_write(bio_flags);
10244a69a410SChris Mason 	int ret;
1025cad321adSChris Mason 
102637226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
1027cad321adSChris Mason 		/*
1028cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
1029cad321adSChris Mason 		 * can happen in the async kernel threads
1030cad321adSChris Mason 		 */
10310b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
10320b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
10331d4284bdSChris Mason 		if (ret)
103461891923SStefan Behrens 			goto out_w_error;
10352ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1036de0022b9SJosef Bacik 	} else if (!async) {
1037de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
1038de0022b9SJosef Bacik 		if (ret)
103961891923SStefan Behrens 			goto out_w_error;
10402ff7e61eSJeff Mahoney 		ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
104161891923SStefan Behrens 	} else {
1042cad321adSChris Mason 		/*
104361891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
104461891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
1045cad321adSChris Mason 		 */
10460b246afaSJeff Mahoney 		ret = btrfs_wq_submit_bio(fs_info, inode, bio, mirror_num, 0,
1047eaf25d93SChris Mason 					  bio_offset,
10484a69a410SChris Mason 					  __btree_submit_bio_start,
10494a69a410SChris Mason 					  __btree_submit_bio_done);
105044b8bd7eSChris Mason 	}
105144b8bd7eSChris Mason 
10524246a0b6SChristoph Hellwig 	if (ret)
10534246a0b6SChristoph Hellwig 		goto out_w_error;
10544246a0b6SChristoph Hellwig 	return 0;
10554246a0b6SChristoph Hellwig 
105661891923SStefan Behrens out_w_error:
10574246a0b6SChristoph Hellwig 	bio->bi_error = ret;
10584246a0b6SChristoph Hellwig 	bio_endio(bio);
105961891923SStefan Behrens 	return ret;
106061891923SStefan Behrens }
106161891923SStefan Behrens 
10623dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
1063784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
1064a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
1065a6bc32b8SMel Gorman 			enum migrate_mode mode)
1066784b4e29SChris Mason {
1067784b4e29SChris Mason 	/*
1068784b4e29SChris Mason 	 * we can't safely write a btree page from here,
1069784b4e29SChris Mason 	 * we haven't done the locking hook
1070784b4e29SChris Mason 	 */
1071784b4e29SChris Mason 	if (PageDirty(page))
1072784b4e29SChris Mason 		return -EAGAIN;
1073784b4e29SChris Mason 	/*
1074784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
1075784b4e29SChris Mason 	 * We must have no buffers or drop them.
1076784b4e29SChris Mason 	 */
1077784b4e29SChris Mason 	if (page_has_private(page) &&
1078784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
1079784b4e29SChris Mason 		return -EAGAIN;
1080a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
1081784b4e29SChris Mason }
10823dd1462eSJan Beulich #endif
1083784b4e29SChris Mason 
10840da5468fSChris Mason 
10850da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
10860da5468fSChris Mason 			    struct writeback_control *wbc)
10870da5468fSChris Mason {
1088e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
1089e2d84521SMiao Xie 	int ret;
1090e2d84521SMiao Xie 
1091d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
1092448d640bSChris Mason 
1093448d640bSChris Mason 		if (wbc->for_kupdate)
1094448d640bSChris Mason 			return 0;
1095448d640bSChris Mason 
1096e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
1097b9473439SChris Mason 		/* this is a bit racy, but that's ok */
1098e2d84521SMiao Xie 		ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
1099e2d84521SMiao Xie 					     BTRFS_DIRTY_METADATA_THRESH);
1100e2d84521SMiao Xie 		if (ret < 0)
1101793955bcSChris Mason 			return 0;
1102793955bcSChris Mason 	}
11030b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
11040da5468fSChris Mason }
11050da5468fSChris Mason 
1106b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
11075f39d397SChris Mason {
1108d1310b2eSChris Mason 	struct extent_io_tree *tree;
1109d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
11108ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
11115f39d397SChris Mason }
11125f39d397SChris Mason 
111370dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
11145f39d397SChris Mason {
111598509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
111698509cfcSChris Mason 		return 0;
11170c4e538bSDavid Sterba 
1118f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1119d98237b3SChris Mason }
1120d98237b3SChris Mason 
1121d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1122d47992f8SLukas Czerner 				 unsigned int length)
1123d98237b3SChris Mason {
1124d1310b2eSChris Mason 	struct extent_io_tree *tree;
1125d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
11265f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
11275f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
11289ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1129efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1130efe120a0SFrank Holton 			   "page private not zero on page %llu",
1131efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
11329ad6b7bcSChris Mason 		ClearPagePrivate(page);
11339ad6b7bcSChris Mason 		set_page_private(page, 0);
113409cbfeafSKirill A. Shutemov 		put_page(page);
11359ad6b7bcSChris Mason 	}
1136d98237b3SChris Mason }
1137d98237b3SChris Mason 
11380b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
11390b32f4bbSJosef Bacik {
1140bb146eb2SJosef Bacik #ifdef DEBUG
11410b32f4bbSJosef Bacik 	struct extent_buffer *eb;
11420b32f4bbSJosef Bacik 
11430b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
11440b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
11450b32f4bbSJosef Bacik 	BUG_ON(!eb);
11460b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
11470b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
11480b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
1149bb146eb2SJosef Bacik #endif
11500b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
11510b32f4bbSJosef Bacik }
11520b32f4bbSJosef Bacik 
11537f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
1154d98237b3SChris Mason 	.readpage	= btree_readpage,
11550da5468fSChris Mason 	.writepages	= btree_writepages,
11565f39d397SChris Mason 	.releasepage	= btree_releasepage,
11575f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
11585a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1159784b4e29SChris Mason 	.migratepage	= btree_migratepage,
11605a92bc88SChris Mason #endif
11610b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1162d98237b3SChris Mason };
1163123abc88SChris Mason 
11642ff7e61eSJeff Mahoney void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1165090d1875SChris Mason {
11665f39d397SChris Mason 	struct extent_buffer *buf = NULL;
11672ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1168090d1875SChris Mason 
11692ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1170c871b0f2SLiu Bo 	if (IS_ERR(buf))
11716197d86eSDavid Sterba 		return;
1172d1310b2eSChris Mason 	read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
11738436ea91SJosef Bacik 				 buf, WAIT_NONE, btree_get_extent, 0);
11745f39d397SChris Mason 	free_extent_buffer(buf);
1175090d1875SChris Mason }
1176090d1875SChris Mason 
11772ff7e61eSJeff Mahoney int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1178ab0fff03SArne Jansen 			 int mirror_num, struct extent_buffer **eb)
1179ab0fff03SArne Jansen {
1180ab0fff03SArne Jansen 	struct extent_buffer *buf = NULL;
11812ff7e61eSJeff Mahoney 	struct inode *btree_inode = fs_info->btree_inode;
1182ab0fff03SArne Jansen 	struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1183ab0fff03SArne Jansen 	int ret;
1184ab0fff03SArne Jansen 
11852ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1186c871b0f2SLiu Bo 	if (IS_ERR(buf))
1187ab0fff03SArne Jansen 		return 0;
1188ab0fff03SArne Jansen 
1189ab0fff03SArne Jansen 	set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1190ab0fff03SArne Jansen 
11918436ea91SJosef Bacik 	ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
1192ab0fff03SArne Jansen 				       btree_get_extent, mirror_num);
1193ab0fff03SArne Jansen 	if (ret) {
1194ab0fff03SArne Jansen 		free_extent_buffer(buf);
1195ab0fff03SArne Jansen 		return ret;
1196ab0fff03SArne Jansen 	}
1197ab0fff03SArne Jansen 
1198ab0fff03SArne Jansen 	if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1199ab0fff03SArne Jansen 		free_extent_buffer(buf);
1200ab0fff03SArne Jansen 		return -EIO;
12010b32f4bbSJosef Bacik 	} else if (extent_buffer_uptodate(buf)) {
1202ab0fff03SArne Jansen 		*eb = buf;
1203ab0fff03SArne Jansen 	} else {
1204ab0fff03SArne Jansen 		free_extent_buffer(buf);
1205ab0fff03SArne Jansen 	}
1206ab0fff03SArne Jansen 	return 0;
1207ab0fff03SArne Jansen }
1208ab0fff03SArne Jansen 
12092ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
12102ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
12110308af44SDavid Sterba 						u64 bytenr)
12120999df54SChris Mason {
12130b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
12140b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
12150b246afaSJeff Mahoney 	return alloc_extent_buffer(fs_info, bytenr);
12160999df54SChris Mason }
12170999df54SChris Mason 
12180999df54SChris Mason 
1219e02119d5SChris Mason int btrfs_write_tree_block(struct extent_buffer *buf)
1220e02119d5SChris Mason {
1221727011e0SChris Mason 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
12228aa38c31SChristoph Hellwig 					buf->start + buf->len - 1);
1223e02119d5SChris Mason }
1224e02119d5SChris Mason 
1225e02119d5SChris Mason int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1226e02119d5SChris Mason {
1227727011e0SChris Mason 	return filemap_fdatawait_range(buf->pages[0]->mapping,
12288aa38c31SChristoph Hellwig 				       buf->start, buf->start + buf->len - 1);
1229e02119d5SChris Mason }
1230e02119d5SChris Mason 
12312ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1232ce86cd59SDavid Sterba 				      u64 parent_transid)
1233e20d96d6SChris Mason {
12345f39d397SChris Mason 	struct extent_buffer *buf = NULL;
123519c00ddcSChris Mason 	int ret;
123619c00ddcSChris Mason 
12372ff7e61eSJeff Mahoney 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
1238c871b0f2SLiu Bo 	if (IS_ERR(buf))
1239c871b0f2SLiu Bo 		return buf;
1240e4204dedSChris Mason 
12412ff7e61eSJeff Mahoney 	ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid);
12420f0fe8f7SFilipe David Borba Manana 	if (ret) {
12430f0fe8f7SFilipe David Borba Manana 		free_extent_buffer(buf);
124464c043deSLiu Bo 		return ERR_PTR(ret);
12450f0fe8f7SFilipe David Borba Manana 	}
12465f39d397SChris Mason 	return buf;
1247ce9adaa5SChris Mason 
1248eb60ceacSChris Mason }
1249eb60ceacSChris Mason 
12507c302b49SDavid Sterba void clean_tree_block(struct btrfs_fs_info *fs_info,
12515f39d397SChris Mason 		      struct extent_buffer *buf)
1252ed2ff2cbSChris Mason {
125355c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1254e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1255b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1256b4ce94deSChris Mason 
1257b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1258e2d84521SMiao Xie 			__percpu_counter_add(&fs_info->dirty_metadata_bytes,
1259e2d84521SMiao Xie 					     -buf->len,
1260e2d84521SMiao Xie 					     fs_info->dirty_metadata_batch);
1261b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
1262b9473439SChris Mason 			btrfs_set_lock_blocking(buf);
12630b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1264925baeddSChris Mason 		}
12655f39d397SChris Mason 	}
1266ed7b63ebSJosef Bacik }
12675f39d397SChris Mason 
12688257b2dcSMiao Xie static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
12698257b2dcSMiao Xie {
12708257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
12718257b2dcSMiao Xie 	int ret;
12728257b2dcSMiao Xie 
12738257b2dcSMiao Xie 	writers = kmalloc(sizeof(*writers), GFP_NOFS);
12748257b2dcSMiao Xie 	if (!writers)
12758257b2dcSMiao Xie 		return ERR_PTR(-ENOMEM);
12768257b2dcSMiao Xie 
1277908c7f19STejun Heo 	ret = percpu_counter_init(&writers->counter, 0, GFP_KERNEL);
12788257b2dcSMiao Xie 	if (ret < 0) {
12798257b2dcSMiao Xie 		kfree(writers);
12808257b2dcSMiao Xie 		return ERR_PTR(ret);
12818257b2dcSMiao Xie 	}
12828257b2dcSMiao Xie 
12838257b2dcSMiao Xie 	init_waitqueue_head(&writers->wait);
12848257b2dcSMiao Xie 	return writers;
12858257b2dcSMiao Xie }
12868257b2dcSMiao Xie 
12878257b2dcSMiao Xie static void
12888257b2dcSMiao Xie btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
12898257b2dcSMiao Xie {
12908257b2dcSMiao Xie 	percpu_counter_destroy(&writers->counter);
12918257b2dcSMiao Xie 	kfree(writers);
12928257b2dcSMiao Xie }
12938257b2dcSMiao Xie 
1294da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1295e20d96d6SChris Mason 			 u64 objectid)
1296d97e63b6SChris Mason {
12977c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1298cfaa7295SChris Mason 	root->node = NULL;
1299a28ec197SChris Mason 	root->commit_root = NULL;
130027cdeb70SMiao Xie 	root->state = 0;
1301d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
13020b86a832SChris Mason 
13030f7d52f4SChris Mason 	root->objectid = objectid;
13040f7d52f4SChris Mason 	root->last_trans = 0;
130513a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1306eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1307199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
130858176a96SJosef Bacik 	root->name = NULL;
13096bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
131016cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1311f0486c68SYan, Zheng 	root->block_rsv = NULL;
1312d68fc57bSYan, Zheng 	root->orphan_block_rsv = NULL;
13130b86a832SChris Mason 
13140b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
13155d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1316eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1317eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1318199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1319199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
13202ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
13212ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
1322d68fc57bSYan, Zheng 	spin_lock_init(&root->orphan_lock);
13235d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1324eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1325199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1326f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
13272ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
13282ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
1329a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1330e02119d5SChris Mason 	mutex_init(&root->log_mutex);
133131f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1332573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
13337237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
13347237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
13357237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
13368b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
13378b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
13387237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
13397237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
13407237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
13412ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
13428a35d95fSJosef Bacik 	atomic_set(&root->orphan_inodes, 0);
1343b0feb9d9SMiao Xie 	atomic_set(&root->refs, 1);
13448257b2dcSMiao Xie 	atomic_set(&root->will_be_snapshoted, 0);
134555eeaf05SQu Wenruo 	atomic_set(&root->qgroup_meta_rsv, 0);
13467237f183SYan Zheng 	root->log_transid = 0;
1347d1433debSMiao Xie 	root->log_transid_committed = -1;
1348257c62e1SChris Mason 	root->last_log_commit = 0;
13497c0260eeSJeff Mahoney 	if (!dummy)
1350d0c803c4SChris Mason 		extent_io_tree_init(&root->dirty_log_pages,
1351f993c883SDavid Sterba 				     fs_info->btree_inode->i_mapping);
1352017e5369SChris Mason 
13533768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
13543768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
13556702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
13567c0260eeSJeff Mahoney 	if (!dummy)
13573f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
135806ea65a3SJosef Bacik 	else
135906ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
13604d775673SChris Mason 	root->root_key.objectid = objectid;
13610ee5dc67SAl Viro 	root->anon_dev = 0;
13628ea05e3aSAlexander Block 
13635f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
13643768f368SChris Mason }
13653768f368SChris Mason 
136674e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
136774e4d827SDavid Sterba 		gfp_t flags)
13686f07e42eSAl Viro {
136974e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
13706f07e42eSAl Viro 	if (root)
13716f07e42eSAl Viro 		root->fs_info = fs_info;
13726f07e42eSAl Viro 	return root;
13736f07e42eSAl Viro }
13746f07e42eSAl Viro 
137506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
137606ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1377da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
137806ea65a3SJosef Bacik {
137906ea65a3SJosef Bacik 	struct btrfs_root *root;
138006ea65a3SJosef Bacik 
13817c0260eeSJeff Mahoney 	if (!fs_info)
13827c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
13837c0260eeSJeff Mahoney 
13847c0260eeSJeff Mahoney 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
138506ea65a3SJosef Bacik 	if (!root)
138606ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1387da17066cSJeff Mahoney 
1388b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1389da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1390faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
139106ea65a3SJosef Bacik 
139206ea65a3SJosef Bacik 	return root;
139306ea65a3SJosef Bacik }
139406ea65a3SJosef Bacik #endif
139506ea65a3SJosef Bacik 
139620897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
139720897f5cSArne Jansen 				     struct btrfs_fs_info *fs_info,
139820897f5cSArne Jansen 				     u64 objectid)
139920897f5cSArne Jansen {
140020897f5cSArne Jansen 	struct extent_buffer *leaf;
140120897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
140220897f5cSArne Jansen 	struct btrfs_root *root;
140320897f5cSArne Jansen 	struct btrfs_key key;
140420897f5cSArne Jansen 	int ret = 0;
14056463fe58SStefan Behrens 	uuid_le uuid;
140620897f5cSArne Jansen 
140774e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_KERNEL);
140820897f5cSArne Jansen 	if (!root)
140920897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
141020897f5cSArne Jansen 
1411da17066cSJeff Mahoney 	__setup_root(root, fs_info, objectid);
141220897f5cSArne Jansen 	root->root_key.objectid = objectid;
141320897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
141420897f5cSArne Jansen 	root->root_key.offset = 0;
141520897f5cSArne Jansen 
14164d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
141720897f5cSArne Jansen 	if (IS_ERR(leaf)) {
141820897f5cSArne Jansen 		ret = PTR_ERR(leaf);
14191dd05682STsutomu Itoh 		leaf = NULL;
142020897f5cSArne Jansen 		goto fail;
142120897f5cSArne Jansen 	}
142220897f5cSArne Jansen 
1423b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
142420897f5cSArne Jansen 	btrfs_set_header_bytenr(leaf, leaf->start);
142520897f5cSArne Jansen 	btrfs_set_header_generation(leaf, trans->transid);
142620897f5cSArne Jansen 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
142720897f5cSArne Jansen 	btrfs_set_header_owner(leaf, objectid);
142820897f5cSArne Jansen 	root->node = leaf;
142920897f5cSArne Jansen 
1430d24ee97bSDavid Sterba 	write_extent_buffer_fsid(leaf, fs_info->fsid);
1431d24ee97bSDavid Sterba 	write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
143220897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
143320897f5cSArne Jansen 
143420897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
143527cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
143620897f5cSArne Jansen 
143720897f5cSArne Jansen 	root->root_item.flags = 0;
143820897f5cSArne Jansen 	root->root_item.byte_limit = 0;
143920897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
144020897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
144120897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
144220897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
144320897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
144420897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
144520897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
14466463fe58SStefan Behrens 	uuid_le_gen(&uuid);
14476463fe58SStefan Behrens 	memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
144820897f5cSArne Jansen 	root->root_item.drop_level = 0;
144920897f5cSArne Jansen 
145020897f5cSArne Jansen 	key.objectid = objectid;
145120897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
145220897f5cSArne Jansen 	key.offset = 0;
145320897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
145420897f5cSArne Jansen 	if (ret)
145520897f5cSArne Jansen 		goto fail;
145620897f5cSArne Jansen 
145720897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
145820897f5cSArne Jansen 
145920897f5cSArne Jansen 	return root;
14601dd05682STsutomu Itoh 
14611dd05682STsutomu Itoh fail:
14621dd05682STsutomu Itoh 	if (leaf) {
14631dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
146459885b39STsutomu Itoh 		free_extent_buffer(root->commit_root);
14651dd05682STsutomu Itoh 		free_extent_buffer(leaf);
14661dd05682STsutomu Itoh 	}
14671dd05682STsutomu Itoh 	kfree(root);
14681dd05682STsutomu Itoh 
14691dd05682STsutomu Itoh 	return ERR_PTR(ret);
147020897f5cSArne Jansen }
147120897f5cSArne Jansen 
14727237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1473e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
14740f7d52f4SChris Mason {
14750f7d52f4SChris Mason 	struct btrfs_root *root;
14767237f183SYan Zheng 	struct extent_buffer *leaf;
1477e02119d5SChris Mason 
147874e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1479e02119d5SChris Mason 	if (!root)
14807237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1481e02119d5SChris Mason 
1482da17066cSJeff Mahoney 	__setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1483e02119d5SChris Mason 
1484e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1485e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1486e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
148727cdeb70SMiao Xie 
14887237f183SYan Zheng 	/*
148927cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
149027cdeb70SMiao Xie 	 *
14917237f183SYan Zheng 	 * log trees do not get reference counted because they go away
14927237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
14937237f183SYan Zheng 	 * to file data extents, and those reference counts still get
14947237f183SYan Zheng 	 * updated (along with back refs to the log tree).
14957237f183SYan Zheng 	 */
1496e02119d5SChris Mason 
14974d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
14984d75f8a9SDavid Sterba 			NULL, 0, 0, 0);
14997237f183SYan Zheng 	if (IS_ERR(leaf)) {
15007237f183SYan Zheng 		kfree(root);
15017237f183SYan Zheng 		return ERR_CAST(leaf);
15027237f183SYan Zheng 	}
1503e02119d5SChris Mason 
1504b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
15055d4f98a2SYan Zheng 	btrfs_set_header_bytenr(leaf, leaf->start);
15065d4f98a2SYan Zheng 	btrfs_set_header_generation(leaf, trans->transid);
15075d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
15085d4f98a2SYan Zheng 	btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
15097237f183SYan Zheng 	root->node = leaf;
1510e02119d5SChris Mason 
15110b246afaSJeff Mahoney 	write_extent_buffer_fsid(root->node, fs_info->fsid);
1512e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1513e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
15147237f183SYan Zheng 	return root;
15157237f183SYan Zheng }
15167237f183SYan Zheng 
15177237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
15187237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
15197237f183SYan Zheng {
15207237f183SYan Zheng 	struct btrfs_root *log_root;
15217237f183SYan Zheng 
15227237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
15237237f183SYan Zheng 	if (IS_ERR(log_root))
15247237f183SYan Zheng 		return PTR_ERR(log_root);
15257237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
15267237f183SYan Zheng 	fs_info->log_root_tree = log_root;
15277237f183SYan Zheng 	return 0;
15287237f183SYan Zheng }
15297237f183SYan Zheng 
15307237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
15317237f183SYan Zheng 		       struct btrfs_root *root)
15327237f183SYan Zheng {
15330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15347237f183SYan Zheng 	struct btrfs_root *log_root;
15357237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
15367237f183SYan Zheng 
15370b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
15387237f183SYan Zheng 	if (IS_ERR(log_root))
15397237f183SYan Zheng 		return PTR_ERR(log_root);
15407237f183SYan Zheng 
15417237f183SYan Zheng 	log_root->last_trans = trans->transid;
15427237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
15437237f183SYan Zheng 
15447237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
15453cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
15463cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
15473cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1548da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
15490b246afaSJeff Mahoney 				     fs_info->nodesize);
15503cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
15517237f183SYan Zheng 
15525d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
15537237f183SYan Zheng 
15547237f183SYan Zheng 	WARN_ON(root->log_root);
15557237f183SYan Zheng 	root->log_root = log_root;
15567237f183SYan Zheng 	root->log_transid = 0;
1557d1433debSMiao Xie 	root->log_transid_committed = -1;
1558257c62e1SChris Mason 	root->last_log_commit = 0;
1559e02119d5SChris Mason 	return 0;
1560e02119d5SChris Mason }
1561e02119d5SChris Mason 
156235a3621bSStefan Behrens static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1563cb517eabSMiao Xie 					       struct btrfs_key *key)
1564e02119d5SChris Mason {
1565e02119d5SChris Mason 	struct btrfs_root *root;
1566e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
15670f7d52f4SChris Mason 	struct btrfs_path *path;
156884234f3aSYan Zheng 	u64 generation;
1569cb517eabSMiao Xie 	int ret;
1570cb517eabSMiao Xie 
1571cb517eabSMiao Xie 	path = btrfs_alloc_path();
1572cb517eabSMiao Xie 	if (!path)
1573cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
15740f7d52f4SChris Mason 
157574e4d827SDavid Sterba 	root = btrfs_alloc_root(fs_info, GFP_NOFS);
1576cb517eabSMiao Xie 	if (!root) {
1577cb517eabSMiao Xie 		ret = -ENOMEM;
1578cb517eabSMiao Xie 		goto alloc_fail;
15790f7d52f4SChris Mason 	}
15800f7d52f4SChris Mason 
1581da17066cSJeff Mahoney 	__setup_root(root, fs_info, key->objectid);
15820f7d52f4SChris Mason 
1583cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1584cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
15850f7d52f4SChris Mason 	if (ret) {
158613a8a7c8SYan, Zheng 		if (ret > 0)
158713a8a7c8SYan, Zheng 			ret = -ENOENT;
1588cb517eabSMiao Xie 		goto find_fail;
15890f7d52f4SChris Mason 	}
159013a8a7c8SYan, Zheng 
159184234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
15922ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
15932ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
1594ce86cd59SDavid Sterba 				     generation);
159564c043deSLiu Bo 	if (IS_ERR(root->node)) {
159664c043deSLiu Bo 		ret = PTR_ERR(root->node);
1597cb517eabSMiao Xie 		goto find_fail;
1598cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1599cb517eabSMiao Xie 		ret = -EIO;
160064c043deSLiu Bo 		free_extent_buffer(root->node);
160164c043deSLiu Bo 		goto find_fail;
1602416bc658SJosef Bacik 	}
16035d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
160413a8a7c8SYan, Zheng out:
1605cb517eabSMiao Xie 	btrfs_free_path(path);
1606cb517eabSMiao Xie 	return root;
1607cb517eabSMiao Xie 
1608cb517eabSMiao Xie find_fail:
1609cb517eabSMiao Xie 	kfree(root);
1610cb517eabSMiao Xie alloc_fail:
1611cb517eabSMiao Xie 	root = ERR_PTR(ret);
1612cb517eabSMiao Xie 	goto out;
1613cb517eabSMiao Xie }
1614cb517eabSMiao Xie 
1615cb517eabSMiao Xie struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1616cb517eabSMiao Xie 				      struct btrfs_key *location)
1617cb517eabSMiao Xie {
1618cb517eabSMiao Xie 	struct btrfs_root *root;
1619cb517eabSMiao Xie 
1620cb517eabSMiao Xie 	root = btrfs_read_tree_root(tree_root, location);
1621cb517eabSMiao Xie 	if (IS_ERR(root))
1622cb517eabSMiao Xie 		return root;
1623cb517eabSMiao Xie 
1624cb517eabSMiao Xie 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
162527cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
162608fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
162708fe4db1SLi Zefan 	}
162813a8a7c8SYan, Zheng 
16295eda7b5eSChris Mason 	return root;
16305eda7b5eSChris Mason }
16315eda7b5eSChris Mason 
1632cb517eabSMiao Xie int btrfs_init_fs_root(struct btrfs_root *root)
1633cb517eabSMiao Xie {
1634cb517eabSMiao Xie 	int ret;
16358257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
1636cb517eabSMiao Xie 
1637cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1638cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1639cb517eabSMiao Xie 					GFP_NOFS);
1640cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1641cb517eabSMiao Xie 		ret = -ENOMEM;
1642cb517eabSMiao Xie 		goto fail;
1643cb517eabSMiao Xie 	}
1644cb517eabSMiao Xie 
16458257b2dcSMiao Xie 	writers = btrfs_alloc_subvolume_writers();
16468257b2dcSMiao Xie 	if (IS_ERR(writers)) {
16478257b2dcSMiao Xie 		ret = PTR_ERR(writers);
16488257b2dcSMiao Xie 		goto fail;
16498257b2dcSMiao Xie 	}
16508257b2dcSMiao Xie 	root->subv_writers = writers;
16518257b2dcSMiao Xie 
1652cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
165357cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
165457cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1655cb517eabSMiao Xie 
1656cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1657cb517eabSMiao Xie 	if (ret)
1658876d2cf1SLiu Bo 		goto fail;
1659f32e48e9SChandan Rajendra 
1660f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1661f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(root,
1662f32e48e9SChandan Rajendra 					&root->highest_objectid);
1663f32e48e9SChandan Rajendra 	if (ret) {
1664f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1665876d2cf1SLiu Bo 		goto fail;
1666f32e48e9SChandan Rajendra 	}
1667f32e48e9SChandan Rajendra 
1668f32e48e9SChandan Rajendra 	ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1669f32e48e9SChandan Rajendra 
1670f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1671f32e48e9SChandan Rajendra 
1672cb517eabSMiao Xie 	return 0;
1673cb517eabSMiao Xie fail:
1674876d2cf1SLiu Bo 	/* the caller is responsible to call free_fs_root */
1675cb517eabSMiao Xie 	return ret;
1676cb517eabSMiao Xie }
1677cb517eabSMiao Xie 
167835bbb97fSJeff Mahoney struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1679cb517eabSMiao Xie 					u64 root_id)
1680cb517eabSMiao Xie {
1681cb517eabSMiao Xie 	struct btrfs_root *root;
1682cb517eabSMiao Xie 
1683cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1684cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1685cb517eabSMiao Xie 				 (unsigned long)root_id);
1686cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1687cb517eabSMiao Xie 	return root;
1688cb517eabSMiao Xie }
1689cb517eabSMiao Xie 
1690cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1691cb517eabSMiao Xie 			 struct btrfs_root *root)
1692cb517eabSMiao Xie {
1693cb517eabSMiao Xie 	int ret;
1694cb517eabSMiao Xie 
1695e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1696cb517eabSMiao Xie 	if (ret)
1697cb517eabSMiao Xie 		return ret;
1698cb517eabSMiao Xie 
1699cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1700cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1701cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1702cb517eabSMiao Xie 				root);
1703cb517eabSMiao Xie 	if (ret == 0)
170427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1705cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1706cb517eabSMiao Xie 	radix_tree_preload_end();
1707cb517eabSMiao Xie 
1708cb517eabSMiao Xie 	return ret;
1709cb517eabSMiao Xie }
1710cb517eabSMiao Xie 
1711c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1712c00869f1SMiao Xie 				     struct btrfs_key *location,
1713c00869f1SMiao Xie 				     bool check_ref)
17145eda7b5eSChris Mason {
17155eda7b5eSChris Mason 	struct btrfs_root *root;
1716381cf658SDavid Sterba 	struct btrfs_path *path;
17171d4c08e0SDavid Sterba 	struct btrfs_key key;
17185eda7b5eSChris Mason 	int ret;
17195eda7b5eSChris Mason 
1720edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1721edbd8d4eSChris Mason 		return fs_info->tree_root;
1722edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1723edbd8d4eSChris Mason 		return fs_info->extent_root;
17248f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
17258f18cf13SChris Mason 		return fs_info->chunk_root;
17268f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
17278f18cf13SChris Mason 		return fs_info->dev_root;
17280403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
17290403e47eSYan Zheng 		return fs_info->csum_root;
1730bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1731bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1732bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
1733f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1734f7a81ea4SStefan Behrens 		return fs_info->uuid_root ? fs_info->uuid_root :
1735f7a81ea4SStefan Behrens 					    ERR_PTR(-ENOENT);
173670f6d82eSOmar Sandoval 	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
173770f6d82eSOmar Sandoval 		return fs_info->free_space_root ? fs_info->free_space_root :
173870f6d82eSOmar Sandoval 						  ERR_PTR(-ENOENT);
17394df27c4dSYan, Zheng again:
1740cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
174148475471SStefan Behrens 	if (root) {
1742c00869f1SMiao Xie 		if (check_ref && btrfs_root_refs(&root->root_item) == 0)
174348475471SStefan Behrens 			return ERR_PTR(-ENOENT);
17445eda7b5eSChris Mason 		return root;
174548475471SStefan Behrens 	}
17465eda7b5eSChris Mason 
1747cb517eabSMiao Xie 	root = btrfs_read_fs_root(fs_info->tree_root, location);
17485eda7b5eSChris Mason 	if (IS_ERR(root))
17495eda7b5eSChris Mason 		return root;
17503394e160SChris Mason 
1751c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1752d68fc57bSYan, Zheng 		ret = -ENOENT;
1753d68fc57bSYan, Zheng 		goto fail;
1754d68fc57bSYan, Zheng 	}
1755d68fc57bSYan, Zheng 
1756cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1757cb517eabSMiao Xie 	if (ret)
1758cb517eabSMiao Xie 		goto fail;
1759cb517eabSMiao Xie 
1760381cf658SDavid Sterba 	path = btrfs_alloc_path();
1761381cf658SDavid Sterba 	if (!path) {
1762381cf658SDavid Sterba 		ret = -ENOMEM;
1763381cf658SDavid Sterba 		goto fail;
1764381cf658SDavid Sterba 	}
17651d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
17661d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
17671d4c08e0SDavid Sterba 	key.offset = location->objectid;
17681d4c08e0SDavid Sterba 
17691d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1770381cf658SDavid Sterba 	btrfs_free_path(path);
1771d68fc57bSYan, Zheng 	if (ret < 0)
1772d68fc57bSYan, Zheng 		goto fail;
1773d68fc57bSYan, Zheng 	if (ret == 0)
177427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1775d68fc57bSYan, Zheng 
1776cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17770f7d52f4SChris Mason 	if (ret) {
17784df27c4dSYan, Zheng 		if (ret == -EEXIST) {
17794df27c4dSYan, Zheng 			free_fs_root(root);
17804df27c4dSYan, Zheng 			goto again;
17810f7d52f4SChris Mason 		}
17824df27c4dSYan, Zheng 		goto fail;
17834df27c4dSYan, Zheng 	}
1784edbd8d4eSChris Mason 	return root;
17854df27c4dSYan, Zheng fail:
17864df27c4dSYan, Zheng 	free_fs_root(root);
17874df27c4dSYan, Zheng 	return ERR_PTR(ret);
1788edbd8d4eSChris Mason }
1789edbd8d4eSChris Mason 
179004160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
179104160088SChris Mason {
179204160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
179304160088SChris Mason 	int ret = 0;
179404160088SChris Mason 	struct btrfs_device *device;
179504160088SChris Mason 	struct backing_dev_info *bdi;
1796b7967db7SChris Mason 
17971f78160cSXiao Guangrong 	rcu_read_lock();
17981f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1799dfe25020SChris Mason 		if (!device->bdev)
1800dfe25020SChris Mason 			continue;
180104160088SChris Mason 		bdi = blk_get_backing_dev_info(device->bdev);
1802ff9ea323STejun Heo 		if (bdi_congested(bdi, bdi_bits)) {
180304160088SChris Mason 			ret = 1;
180404160088SChris Mason 			break;
180504160088SChris Mason 		}
180604160088SChris Mason 	}
18071f78160cSXiao Guangrong 	rcu_read_unlock();
180804160088SChris Mason 	return ret;
180904160088SChris Mason }
181004160088SChris Mason 
181104160088SChris Mason static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
181204160088SChris Mason {
1813ad081f14SJens Axboe 	int err;
1814ad081f14SJens Axboe 
1815b4caecd4SChristoph Hellwig 	err = bdi_setup_and_register(bdi, "btrfs");
1816ad081f14SJens Axboe 	if (err)
1817ad081f14SJens Axboe 		return err;
1818ad081f14SJens Axboe 
181909cbfeafSKirill A. Shutemov 	bdi->ra_pages = VM_MAX_READAHEAD * 1024 / PAGE_SIZE;
182004160088SChris Mason 	bdi->congested_fn	= btrfs_congested_fn;
182104160088SChris Mason 	bdi->congested_data	= info;
1822da2f0f74SChris Mason 	bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
182304160088SChris Mason 	return 0;
182404160088SChris Mason }
182504160088SChris Mason 
18268b712842SChris Mason /*
18278b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
18288b712842SChris Mason  * functions.  This is where read checksum verification actually happens
18298b712842SChris Mason  */
18308b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1831ce9adaa5SChris Mason {
1832ce9adaa5SChris Mason 	struct bio *bio;
183397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1834ce9adaa5SChris Mason 
183597eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1836ce9adaa5SChris Mason 	bio = end_io_wq->bio;
18378b712842SChris Mason 
18384246a0b6SChristoph Hellwig 	bio->bi_error = end_io_wq->error;
1839ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1840ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
184197eb6b69SDavid Sterba 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
18424246a0b6SChristoph Hellwig 	bio_endio(bio);
1843ce9adaa5SChris Mason }
184444b8bd7eSChris Mason 
1845a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1846a74a4b97SChris Mason {
1847a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1849d0278245SMiao Xie 	int again;
1850da288d28SFilipe Manana 	struct btrfs_trans_handle *trans;
1851a74a4b97SChris Mason 
1852a74a4b97SChris Mason 	do {
1853d0278245SMiao Xie 		again = 0;
18549d1a2a3aSDavid Sterba 
1855d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18562ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1857d0278245SMiao Xie 			goto sleep;
1858d0278245SMiao Xie 
185990c711abSZygo Blaxell 		/*
186090c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
186190c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
186290c711abSZygo Blaxell 		 */
18630b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
186490c711abSZygo Blaxell 			goto sleep;
186590c711abSZygo Blaxell 
18660b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1867d0278245SMiao Xie 			goto sleep;
1868d0278245SMiao Xie 
1869dc7f370cSMiao Xie 		/*
1870dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1871dc7f370cSMiao Xie 		 * during the above check and trylock.
1872dc7f370cSMiao Xie 		 */
18732ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18740b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1875dc7f370cSMiao Xie 			goto sleep;
1876dc7f370cSMiao Xie 		}
1877dc7f370cSMiao Xie 
18780b246afaSJeff Mahoney 		mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
18792ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
18800b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
1881c2d6cb16SFilipe Manana 
18829d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
18830b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1884a74a4b97SChris Mason 
1885d0278245SMiao Xie 		/*
188605323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
188705323cd1SMiao Xie 		 * needn't do anything special here.
1888d0278245SMiao Xie 		 */
18890b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
189067c5e7d4SFilipe Manana 
189167c5e7d4SFilipe Manana 		/*
189267c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
189367c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
189467c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
189567c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
189667c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
189767c5e7d4SFilipe Manana 		 * unused block groups.
189867c5e7d4SFilipe Manana 		 */
18990b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1900d0278245SMiao Xie sleep:
1901838fe188SJiri Kosina 		if (!again) {
1902a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
19038929ecfaSYan, Zheng 			if (!kthread_should_stop())
1904a74a4b97SChris Mason 				schedule();
1905a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1906a74a4b97SChris Mason 		}
1907a74a4b97SChris Mason 	} while (!kthread_should_stop());
1908da288d28SFilipe Manana 
1909da288d28SFilipe Manana 	/*
1910da288d28SFilipe Manana 	 * Transaction kthread is stopped before us and wakes us up.
1911da288d28SFilipe Manana 	 * However we might have started a new transaction and COWed some
1912da288d28SFilipe Manana 	 * tree blocks when deleting unused block groups for example. So
1913da288d28SFilipe Manana 	 * make sure we commit the transaction we started to have a clean
1914da288d28SFilipe Manana 	 * shutdown when evicting the btree inode - if it has dirty pages
1915da288d28SFilipe Manana 	 * when we do the final iput() on it, eviction will trigger a
1916da288d28SFilipe Manana 	 * writeback for it which will fail with null pointer dereferences
1917da288d28SFilipe Manana 	 * since work queues and other resources were already released and
1918da288d28SFilipe Manana 	 * destroyed by the time the iput/eviction/writeback is made.
1919da288d28SFilipe Manana 	 */
1920da288d28SFilipe Manana 	trans = btrfs_attach_transaction(root);
1921da288d28SFilipe Manana 	if (IS_ERR(trans)) {
1922da288d28SFilipe Manana 		if (PTR_ERR(trans) != -ENOENT)
19230b246afaSJeff Mahoney 			btrfs_err(fs_info,
1924da288d28SFilipe Manana 				  "cleaner transaction attach returned %ld",
1925da288d28SFilipe Manana 				  PTR_ERR(trans));
1926da288d28SFilipe Manana 	} else {
1927da288d28SFilipe Manana 		int ret;
1928da288d28SFilipe Manana 
19293a45bb20SJeff Mahoney 		ret = btrfs_commit_transaction(trans);
1930da288d28SFilipe Manana 		if (ret)
19310b246afaSJeff Mahoney 			btrfs_err(fs_info,
1932da288d28SFilipe Manana 				  "cleaner open transaction commit returned %d",
1933da288d28SFilipe Manana 				  ret);
1934da288d28SFilipe Manana 	}
1935da288d28SFilipe Manana 
1936a74a4b97SChris Mason 	return 0;
1937a74a4b97SChris Mason }
1938a74a4b97SChris Mason 
1939a74a4b97SChris Mason static int transaction_kthread(void *arg)
1940a74a4b97SChris Mason {
1941a74a4b97SChris Mason 	struct btrfs_root *root = arg;
19420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1943a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1944a74a4b97SChris Mason 	struct btrfs_transaction *cur;
19458929ecfaSYan, Zheng 	u64 transid;
1946a74a4b97SChris Mason 	unsigned long now;
1947a74a4b97SChris Mason 	unsigned long delay;
1948914b2007SJan Kara 	bool cannot_commit;
1949a74a4b97SChris Mason 
1950a74a4b97SChris Mason 	do {
1951914b2007SJan Kara 		cannot_commit = false;
19520b246afaSJeff Mahoney 		delay = HZ * fs_info->commit_interval;
19530b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1954a74a4b97SChris Mason 
19550b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
19560b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1957a74a4b97SChris Mason 		if (!cur) {
19580b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1959a74a4b97SChris Mason 			goto sleep;
1960a74a4b97SChris Mason 		}
196131153d81SYan Zheng 
1962a74a4b97SChris Mason 		now = get_seconds();
19634a9d8bdeSMiao Xie 		if (cur->state < TRANS_STATE_BLOCKED &&
19648b87dc17SDavid Sterba 		    (now < cur->start_time ||
19650b246afaSJeff Mahoney 		     now - cur->start_time < fs_info->commit_interval)) {
19660b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1967a74a4b97SChris Mason 			delay = HZ * 5;
1968a74a4b97SChris Mason 			goto sleep;
1969a74a4b97SChris Mason 		}
19708929ecfaSYan, Zheng 		transid = cur->transid;
19710b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
197256bec294SChris Mason 
197379787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1974354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1975914b2007SJan Kara 		if (IS_ERR(trans)) {
1976354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1977914b2007SJan Kara 				cannot_commit = true;
197879787eaaSJeff Mahoney 			goto sleep;
1979914b2007SJan Kara 		}
19808929ecfaSYan, Zheng 		if (transid == trans->transid) {
19813a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19828929ecfaSYan, Zheng 		} else {
19833a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19848929ecfaSYan, Zheng 		}
1985a74a4b97SChris Mason sleep:
19860b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19870b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1988a74a4b97SChris Mason 
19894e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
19900b246afaSJeff Mahoney 				      &fs_info->fs_state)))
19912ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
1992a74a4b97SChris Mason 		set_current_state(TASK_INTERRUPTIBLE);
19938929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19940b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1995914b2007SJan Kara 				 cannot_commit))
1996a74a4b97SChris Mason 			schedule_timeout(delay);
1997a74a4b97SChris Mason 		__set_current_state(TASK_RUNNING);
1998a74a4b97SChris Mason 	} while (!kthread_should_stop());
1999a74a4b97SChris Mason 	return 0;
2000a74a4b97SChris Mason }
2001a74a4b97SChris Mason 
2002af31f5e5SChris Mason /*
2003af31f5e5SChris Mason  * this will find the highest generation in the array of
2004af31f5e5SChris Mason  * root backups.  The index of the highest array is returned,
2005af31f5e5SChris Mason  * or -1 if we can't find anything.
2006af31f5e5SChris Mason  *
2007af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
2008af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
2009af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
2010af31f5e5SChris Mason  */
2011af31f5e5SChris Mason static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
2012af31f5e5SChris Mason {
2013af31f5e5SChris Mason 	u64 cur;
2014af31f5e5SChris Mason 	int newest_index = -1;
2015af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2016af31f5e5SChris Mason 	int i;
2017af31f5e5SChris Mason 
2018af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2019af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
2020af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
2021af31f5e5SChris Mason 		if (cur == newest_gen)
2022af31f5e5SChris Mason 			newest_index = i;
2023af31f5e5SChris Mason 	}
2024af31f5e5SChris Mason 
2025af31f5e5SChris Mason 	/* check to see if we actually wrapped around */
2026af31f5e5SChris Mason 	if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
2027af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots;
2028af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
2029af31f5e5SChris Mason 		if (cur == newest_gen)
2030af31f5e5SChris Mason 			newest_index = 0;
2031af31f5e5SChris Mason 	}
2032af31f5e5SChris Mason 	return newest_index;
2033af31f5e5SChris Mason }
2034af31f5e5SChris Mason 
2035af31f5e5SChris Mason 
2036af31f5e5SChris Mason /*
2037af31f5e5SChris Mason  * find the oldest backup so we know where to store new entries
2038af31f5e5SChris Mason  * in the backup array.  This will set the backup_root_index
2039af31f5e5SChris Mason  * field in the fs_info struct
2040af31f5e5SChris Mason  */
2041af31f5e5SChris Mason static void find_oldest_super_backup(struct btrfs_fs_info *info,
2042af31f5e5SChris Mason 				     u64 newest_gen)
2043af31f5e5SChris Mason {
2044af31f5e5SChris Mason 	int newest_index = -1;
2045af31f5e5SChris Mason 
2046af31f5e5SChris Mason 	newest_index = find_newest_super_backup(info, newest_gen);
2047af31f5e5SChris Mason 	/* if there was garbage in there, just move along */
2048af31f5e5SChris Mason 	if (newest_index == -1) {
2049af31f5e5SChris Mason 		info->backup_root_index = 0;
2050af31f5e5SChris Mason 	} else {
2051af31f5e5SChris Mason 		info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
2052af31f5e5SChris Mason 	}
2053af31f5e5SChris Mason }
2054af31f5e5SChris Mason 
2055af31f5e5SChris Mason /*
2056af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
2057af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
2058af31f5e5SChris Mason  * done
2059af31f5e5SChris Mason  */
2060af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
2061af31f5e5SChris Mason {
2062af31f5e5SChris Mason 	int next_backup;
2063af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2064af31f5e5SChris Mason 	int last_backup;
2065af31f5e5SChris Mason 
2066af31f5e5SChris Mason 	next_backup = info->backup_root_index;
2067af31f5e5SChris Mason 	last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
2068af31f5e5SChris Mason 		BTRFS_NUM_BACKUP_ROOTS;
2069af31f5e5SChris Mason 
2070af31f5e5SChris Mason 	/*
2071af31f5e5SChris Mason 	 * just overwrite the last backup if we're at the same generation
2072af31f5e5SChris Mason 	 * this happens only at umount
2073af31f5e5SChris Mason 	 */
2074af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + last_backup;
2075af31f5e5SChris Mason 	if (btrfs_backup_tree_root_gen(root_backup) ==
2076af31f5e5SChris Mason 	    btrfs_header_generation(info->tree_root->node))
2077af31f5e5SChris Mason 		next_backup = last_backup;
2078af31f5e5SChris Mason 
2079af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2080af31f5e5SChris Mason 
2081af31f5e5SChris Mason 	/*
2082af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2083af31f5e5SChris Mason 	 * regardless of which ones we use today
2084af31f5e5SChris Mason 	 */
2085af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2086af31f5e5SChris Mason 
2087af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2088af31f5e5SChris Mason 
2089af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2090af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2091af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2092af31f5e5SChris Mason 
2093af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2094af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2095af31f5e5SChris Mason 
2096af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2097af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2098af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2099af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2100af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2101af31f5e5SChris Mason 
2102af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
2103af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
2104af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
2105af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
2106af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
2107af31f5e5SChris Mason 
21087c7e82a7SChris Mason 	/*
21097c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
21107c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
21117c7e82a7SChris Mason 	 */
21127c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
21137c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
21147c7e82a7SChris Mason 					 info->fs_root->node->start);
2115af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2116af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2117af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2118af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
21197c7e82a7SChris Mason 	}
2120af31f5e5SChris Mason 
2121af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2122af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2123af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2124af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2125af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2126af31f5e5SChris Mason 
2127af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
2128af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
2129af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
2130af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
2131af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
2132af31f5e5SChris Mason 
2133af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2134af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2135af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2136af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2137af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2138af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2139af31f5e5SChris Mason 
2140af31f5e5SChris Mason 	/*
2141af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2142af31f5e5SChris Mason 	 * for the next commit
2143af31f5e5SChris Mason 	 */
2144af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2145af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2146af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2147af31f5e5SChris Mason }
2148af31f5e5SChris Mason 
2149af31f5e5SChris Mason /*
2150af31f5e5SChris Mason  * this copies info out of the root backup array and back into
2151af31f5e5SChris Mason  * the in-memory super block.  It is meant to help iterate through
2152af31f5e5SChris Mason  * the array, so you send it the number of backups you've already
2153af31f5e5SChris Mason  * tried and the last backup index you used.
2154af31f5e5SChris Mason  *
2155af31f5e5SChris Mason  * this returns -1 when it has tried all the backups
2156af31f5e5SChris Mason  */
2157af31f5e5SChris Mason static noinline int next_root_backup(struct btrfs_fs_info *info,
2158af31f5e5SChris Mason 				     struct btrfs_super_block *super,
2159af31f5e5SChris Mason 				     int *num_backups_tried, int *backup_index)
2160af31f5e5SChris Mason {
2161af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2162af31f5e5SChris Mason 	int newest = *backup_index;
2163af31f5e5SChris Mason 
2164af31f5e5SChris Mason 	if (*num_backups_tried == 0) {
2165af31f5e5SChris Mason 		u64 gen = btrfs_super_generation(super);
2166af31f5e5SChris Mason 
2167af31f5e5SChris Mason 		newest = find_newest_super_backup(info, gen);
2168af31f5e5SChris Mason 		if (newest == -1)
2169af31f5e5SChris Mason 			return -1;
2170af31f5e5SChris Mason 
2171af31f5e5SChris Mason 		*backup_index = newest;
2172af31f5e5SChris Mason 		*num_backups_tried = 1;
2173af31f5e5SChris Mason 	} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2174af31f5e5SChris Mason 		/* we've tried all the backups, all done */
2175af31f5e5SChris Mason 		return -1;
2176af31f5e5SChris Mason 	} else {
2177af31f5e5SChris Mason 		/* jump to the next oldest backup */
2178af31f5e5SChris Mason 		newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2179af31f5e5SChris Mason 			BTRFS_NUM_BACKUP_ROOTS;
2180af31f5e5SChris Mason 		*backup_index = newest;
2181af31f5e5SChris Mason 		*num_backups_tried += 1;
2182af31f5e5SChris Mason 	}
2183af31f5e5SChris Mason 	root_backup = super->super_roots + newest;
2184af31f5e5SChris Mason 
2185af31f5e5SChris Mason 	btrfs_set_super_generation(super,
2186af31f5e5SChris Mason 				   btrfs_backup_tree_root_gen(root_backup));
2187af31f5e5SChris Mason 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2188af31f5e5SChris Mason 	btrfs_set_super_root_level(super,
2189af31f5e5SChris Mason 				   btrfs_backup_tree_root_level(root_backup));
2190af31f5e5SChris Mason 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2191af31f5e5SChris Mason 
2192af31f5e5SChris Mason 	/*
2193af31f5e5SChris Mason 	 * fixme: the total bytes and num_devices need to match or we should
2194af31f5e5SChris Mason 	 * need a fsck
2195af31f5e5SChris Mason 	 */
2196af31f5e5SChris Mason 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2197af31f5e5SChris Mason 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2198af31f5e5SChris Mason 	return 0;
2199af31f5e5SChris Mason }
2200af31f5e5SChris Mason 
22017abadb64SLiu Bo /* helper to cleanup workers */
22027abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
22037abadb64SLiu Bo {
2204dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2205afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
22065cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2207fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2208fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2209fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
22108b110e39SMiao Xie 	btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2211d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2212fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2213fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2214fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2215a8c93d4eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->submit_workers);
22165b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2217e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2218736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2219a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2220fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2221a79b7d4bSChris Mason 	btrfs_destroy_workqueue(fs_info->extent_workers);
22227abadb64SLiu Bo }
22237abadb64SLiu Bo 
22242e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
22252e9f5954SRashika {
22262e9f5954SRashika 	if (root) {
22272e9f5954SRashika 		free_extent_buffer(root->node);
22282e9f5954SRashika 		free_extent_buffer(root->commit_root);
22292e9f5954SRashika 		root->node = NULL;
22302e9f5954SRashika 		root->commit_root = NULL;
22312e9f5954SRashika 	}
22322e9f5954SRashika }
22332e9f5954SRashika 
2234af31f5e5SChris Mason /* helper to cleanup tree roots */
2235af31f5e5SChris Mason static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2236af31f5e5SChris Mason {
22372e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2238655b09feSJosef Bacik 
22392e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
22402e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
22412e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
22422e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
22432e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
22442e9f5954SRashika 	if (chunk_root)
22452e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
224670f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2247af31f5e5SChris Mason }
2248af31f5e5SChris Mason 
2249faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2250171f6537SJosef Bacik {
2251171f6537SJosef Bacik 	int ret;
2252171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2253171f6537SJosef Bacik 	int i;
2254171f6537SJosef Bacik 
2255171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2256171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2257171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2258171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2259171f6537SJosef Bacik 
226027cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2261cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2262171f6537SJosef Bacik 		} else {
2263171f6537SJosef Bacik 			free_extent_buffer(gang[0]->node);
2264171f6537SJosef Bacik 			free_extent_buffer(gang[0]->commit_root);
2265b0feb9d9SMiao Xie 			btrfs_put_fs_root(gang[0]);
2266171f6537SJosef Bacik 		}
2267171f6537SJosef Bacik 	}
2268171f6537SJosef Bacik 
2269171f6537SJosef Bacik 	while (1) {
2270171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2271171f6537SJosef Bacik 					     (void **)gang, 0,
2272171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2273171f6537SJosef Bacik 		if (!ret)
2274171f6537SJosef Bacik 			break;
2275171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2276cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2277171f6537SJosef Bacik 	}
22781a4319ccSLiu Bo 
22791a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
22801a4319ccSLiu Bo 		btrfs_free_log_root_tree(NULL, fs_info);
22812ff7e61eSJeff Mahoney 		btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
22821a4319ccSLiu Bo 	}
2283171f6537SJosef Bacik }
2284af31f5e5SChris Mason 
2285638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2286638aa7edSEric Sandeen {
2287638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2288638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2289638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2290638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2291638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2292638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2293638aa7edSEric Sandeen 	fs_info->scrub_workers_refcnt = 0;
2294638aa7edSEric Sandeen }
2295638aa7edSEric Sandeen 
2296779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2297779a65a4SEric Sandeen {
2298779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2299779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2300779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_running, 0);
2301779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2302779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2303779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2304779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2305779a65a4SEric Sandeen }
2306779a65a4SEric Sandeen 
23076bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2308f37938e0SEric Sandeen {
23092ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
23102ff7e61eSJeff Mahoney 
23112ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
23122ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2313f37938e0SEric Sandeen 	/*
2314f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2315f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2316f37938e0SEric Sandeen 	 * the devices in the system
2317f37938e0SEric Sandeen 	 */
23182ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
23192ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2320f37938e0SEric Sandeen 
23212ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
23222ff7e61eSJeff Mahoney 	extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode->i_mapping);
23232ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.track_uptodate = 0;
23242ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2325f37938e0SEric Sandeen 
23262ff7e61eSJeff Mahoney 	BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2327f37938e0SEric Sandeen 
23282ff7e61eSJeff Mahoney 	BTRFS_I(inode)->root = fs_info->tree_root;
23292ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
23302ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
23312ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2332f37938e0SEric Sandeen }
2333f37938e0SEric Sandeen 
2334ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2335ad618368SEric Sandeen {
2336ad618368SEric Sandeen 	fs_info->dev_replace.lock_owner = 0;
2337ad618368SEric Sandeen 	atomic_set(&fs_info->dev_replace.nesting_level, 0);
2338ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
233973beece9SLiu Bo 	rwlock_init(&fs_info->dev_replace.lock);
234073beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.read_locks, 0);
234173beece9SLiu Bo 	atomic_set(&fs_info->dev_replace.blocking_readers, 0);
2342ad618368SEric Sandeen 	init_waitqueue_head(&fs_info->replace_wait);
234373beece9SLiu Bo 	init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
2344ad618368SEric Sandeen }
2345ad618368SEric Sandeen 
2346f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2347f9e92e40SEric Sandeen {
2348f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2349f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2350f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2351f9e92e40SEric Sandeen 	fs_info->qgroup_op_tree = RB_ROOT;
2352f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2353f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2354f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2355d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2356f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2357f9e92e40SEric Sandeen }
2358f9e92e40SEric Sandeen 
23592a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
23602a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
23612a458198SEric Sandeen {
23622a458198SEric Sandeen 	int max_active = fs_info->thread_pool_size;
23636f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
23642a458198SEric Sandeen 
23652a458198SEric Sandeen 	fs_info->workers =
2366cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2367cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
23682a458198SEric Sandeen 
23692a458198SEric Sandeen 	fs_info->delalloc_workers =
2370cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2371cb001095SJeff Mahoney 				      flags, max_active, 2);
23722a458198SEric Sandeen 
23732a458198SEric Sandeen 	fs_info->flush_workers =
2374cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2375cb001095SJeff Mahoney 				      flags, max_active, 0);
23762a458198SEric Sandeen 
23772a458198SEric Sandeen 	fs_info->caching_workers =
2378cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
23792a458198SEric Sandeen 
23802a458198SEric Sandeen 	/*
23812a458198SEric Sandeen 	 * a higher idle thresh on the submit workers makes it much more
23822a458198SEric Sandeen 	 * likely that bios will be send down in a sane order to the
23832a458198SEric Sandeen 	 * devices
23842a458198SEric Sandeen 	 */
23852a458198SEric Sandeen 	fs_info->submit_workers =
2386cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "submit", flags,
23872a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
23882a458198SEric Sandeen 					    max_active), 64);
23892a458198SEric Sandeen 
23902a458198SEric Sandeen 	fs_info->fixup_workers =
2391cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23922a458198SEric Sandeen 
23932a458198SEric Sandeen 	/*
23942a458198SEric Sandeen 	 * endios are largely parallel and should have a very
23952a458198SEric Sandeen 	 * low idle thresh
23962a458198SEric Sandeen 	 */
23972a458198SEric Sandeen 	fs_info->endio_workers =
2398cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
23992a458198SEric Sandeen 	fs_info->endio_meta_workers =
2400cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2401cb001095SJeff Mahoney 				      max_active, 4);
24022a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2403cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2404cb001095SJeff Mahoney 				      max_active, 2);
24052a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2406cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2407cb001095SJeff Mahoney 				      max_active, 4);
24082a458198SEric Sandeen 	fs_info->endio_repair_workers =
2409cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
24102a458198SEric Sandeen 	fs_info->rmw_workers =
2411cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
24122a458198SEric Sandeen 	fs_info->endio_write_workers =
2413cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2414cb001095SJeff Mahoney 				      max_active, 2);
24152a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2416cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2417cb001095SJeff Mahoney 				      max_active, 0);
24182a458198SEric Sandeen 	fs_info->delayed_workers =
2419cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2420cb001095SJeff Mahoney 				      max_active, 0);
24212a458198SEric Sandeen 	fs_info->readahead_workers =
2422cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2423cb001095SJeff Mahoney 				      max_active, 2);
24242a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2425cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
24262a458198SEric Sandeen 	fs_info->extent_workers =
2427cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
24282a458198SEric Sandeen 				      min_t(u64, fs_devices->num_devices,
24292a458198SEric Sandeen 					    max_active), 8);
24302a458198SEric Sandeen 
24312a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
24322a458198SEric Sandeen 	      fs_info->submit_workers && fs_info->flush_workers &&
24332a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
24342a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
24352a458198SEric Sandeen 	      fs_info->endio_repair_workers &&
24362a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
24372a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
24382a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
24392a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
24402a458198SEric Sandeen 	      fs_info->extent_workers &&
24412a458198SEric Sandeen 	      fs_info->qgroup_rescan_workers)) {
24422a458198SEric Sandeen 		return -ENOMEM;
24432a458198SEric Sandeen 	}
24442a458198SEric Sandeen 
24452a458198SEric Sandeen 	return 0;
24462a458198SEric Sandeen }
24472a458198SEric Sandeen 
244863443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
244963443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
245063443bf5SEric Sandeen {
245163443bf5SEric Sandeen 	int ret;
245263443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
245363443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
245463443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
245563443bf5SEric Sandeen 
245663443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2457f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
245863443bf5SEric Sandeen 		return -EIO;
245963443bf5SEric Sandeen 	}
246063443bf5SEric Sandeen 
246174e4d827SDavid Sterba 	log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
246263443bf5SEric Sandeen 	if (!log_tree_root)
246363443bf5SEric Sandeen 		return -ENOMEM;
246463443bf5SEric Sandeen 
2465da17066cSJeff Mahoney 	__setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
246663443bf5SEric Sandeen 
24672ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
246863443bf5SEric Sandeen 					      fs_info->generation + 1);
246964c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2470f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
24710eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
247264c043deSLiu Bo 		kfree(log_tree_root);
24730eeff236SLiu Bo 		return ret;
247464c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2475f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
247663443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
247763443bf5SEric Sandeen 		kfree(log_tree_root);
247863443bf5SEric Sandeen 		return -EIO;
247963443bf5SEric Sandeen 	}
248063443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
248163443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
248263443bf5SEric Sandeen 	if (ret) {
24830b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
248463443bf5SEric Sandeen 				      "Failed to recover log tree");
248563443bf5SEric Sandeen 		free_extent_buffer(log_tree_root->node);
248663443bf5SEric Sandeen 		kfree(log_tree_root);
248763443bf5SEric Sandeen 		return ret;
248863443bf5SEric Sandeen 	}
248963443bf5SEric Sandeen 
249063443bf5SEric Sandeen 	if (fs_info->sb->s_flags & MS_RDONLY) {
24916bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
249263443bf5SEric Sandeen 		if (ret)
249363443bf5SEric Sandeen 			return ret;
249463443bf5SEric Sandeen 	}
249563443bf5SEric Sandeen 
249663443bf5SEric Sandeen 	return 0;
249763443bf5SEric Sandeen }
249863443bf5SEric Sandeen 
24996bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
25004bbcaa64SEric Sandeen {
25016bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2502a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
25034bbcaa64SEric Sandeen 	struct btrfs_key location;
25044bbcaa64SEric Sandeen 	int ret;
25054bbcaa64SEric Sandeen 
25066bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
25076bccf3abSJeff Mahoney 
25084bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
25094bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
25104bbcaa64SEric Sandeen 	location.offset = 0;
25114bbcaa64SEric Sandeen 
2512a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2513a4f3d2c4SDavid Sterba 	if (IS_ERR(root))
2514a4f3d2c4SDavid Sterba 		return PTR_ERR(root);
2515a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2516a4f3d2c4SDavid Sterba 	fs_info->extent_root = root;
25174bbcaa64SEric Sandeen 
25184bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2519a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2520a4f3d2c4SDavid Sterba 	if (IS_ERR(root))
2521a4f3d2c4SDavid Sterba 		return PTR_ERR(root);
2522a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2523a4f3d2c4SDavid Sterba 	fs_info->dev_root = root;
25244bbcaa64SEric Sandeen 	btrfs_init_devices_late(fs_info);
25254bbcaa64SEric Sandeen 
25264bbcaa64SEric Sandeen 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2527a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2528a4f3d2c4SDavid Sterba 	if (IS_ERR(root))
2529a4f3d2c4SDavid Sterba 		return PTR_ERR(root);
2530a4f3d2c4SDavid Sterba 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2531a4f3d2c4SDavid Sterba 	fs_info->csum_root = root;
25324bbcaa64SEric Sandeen 
25334bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2534a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2535a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2536a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2537afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2538a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25394bbcaa64SEric Sandeen 	}
25404bbcaa64SEric Sandeen 
25414bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2542a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2543a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
2544a4f3d2c4SDavid Sterba 		ret = PTR_ERR(root);
25454bbcaa64SEric Sandeen 		if (ret != -ENOENT)
25464bbcaa64SEric Sandeen 			return ret;
25474bbcaa64SEric Sandeen 	} else {
2548a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2549a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25504bbcaa64SEric Sandeen 	}
25514bbcaa64SEric Sandeen 
255270f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
255370f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
255470f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
255570f6d82eSOmar Sandoval 		if (IS_ERR(root))
255670f6d82eSOmar Sandoval 			return PTR_ERR(root);
255770f6d82eSOmar Sandoval 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
255870f6d82eSOmar Sandoval 		fs_info->free_space_root = root;
255970f6d82eSOmar Sandoval 	}
256070f6d82eSOmar Sandoval 
25614bbcaa64SEric Sandeen 	return 0;
25624bbcaa64SEric Sandeen }
25634bbcaa64SEric Sandeen 
2564ad2b2c80SAl Viro int open_ctree(struct super_block *sb,
2565dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
2566dfe25020SChris Mason 	       char *options)
2567eb60ceacSChris Mason {
2568db94535dSChris Mason 	u32 sectorsize;
2569db94535dSChris Mason 	u32 nodesize;
257087ee04ebSChris Mason 	u32 stripesize;
257184234f3aSYan Zheng 	u64 generation;
2572f2b636e8SJosef Bacik 	u64 features;
25733de4586cSChris Mason 	struct btrfs_key location;
2574a061fc8dSChris Mason 	struct buffer_head *bh;
25754d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
2576815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2577f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
25784d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
2579eb60ceacSChris Mason 	int ret;
2580e58ca020SYan 	int err = -EINVAL;
2581af31f5e5SChris Mason 	int num_backups_tried = 0;
2582af31f5e5SChris Mason 	int backup_index = 0;
25835cdc7ad3SQu Wenruo 	int max_active;
25846675df31SOmar Sandoval 	int clear_free_space_tree = 0;
25854543df7eSChris Mason 
258674e4d827SDavid Sterba 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
258774e4d827SDavid Sterba 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2588cb517eabSMiao Xie 	if (!tree_root || !chunk_root) {
258939279cc3SChris Mason 		err = -ENOMEM;
259039279cc3SChris Mason 		goto fail;
259139279cc3SChris Mason 	}
259276dda93cSYan, Zheng 
259376dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
259476dda93cSYan, Zheng 	if (ret) {
259576dda93cSYan, Zheng 		err = ret;
259676dda93cSYan, Zheng 		goto fail;
259776dda93cSYan, Zheng 	}
259876dda93cSYan, Zheng 
259976dda93cSYan, Zheng 	ret = setup_bdi(fs_info, &fs_info->bdi);
260076dda93cSYan, Zheng 	if (ret) {
260176dda93cSYan, Zheng 		err = ret;
260276dda93cSYan, Zheng 		goto fail_srcu;
260376dda93cSYan, Zheng 	}
260476dda93cSYan, Zheng 
2605908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2606e2d84521SMiao Xie 	if (ret) {
2607e2d84521SMiao Xie 		err = ret;
2608e2d84521SMiao Xie 		goto fail_bdi;
2609e2d84521SMiao Xie 	}
261009cbfeafSKirill A. Shutemov 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2611e2d84521SMiao Xie 					(1 + ilog2(nr_cpu_ids));
2612e2d84521SMiao Xie 
2613908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2614963d678bSMiao Xie 	if (ret) {
2615963d678bSMiao Xie 		err = ret;
2616963d678bSMiao Xie 		goto fail_dirty_metadata_bytes;
2617963d678bSMiao Xie 	}
2618963d678bSMiao Xie 
2619908c7f19STejun Heo 	ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2620c404e0dcSMiao Xie 	if (ret) {
2621c404e0dcSMiao Xie 		err = ret;
2622c404e0dcSMiao Xie 		goto fail_delalloc_bytes;
2623c404e0dcSMiao Xie 	}
2624c404e0dcSMiao Xie 
262576dda93cSYan, Zheng 	fs_info->btree_inode = new_inode(sb);
262676dda93cSYan, Zheng 	if (!fs_info->btree_inode) {
262776dda93cSYan, Zheng 		err = -ENOMEM;
2628c404e0dcSMiao Xie 		goto fail_bio_counter;
262976dda93cSYan, Zheng 	}
263076dda93cSYan, Zheng 
2631a6591715SChris Mason 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
26321561dedaSMiao Xie 
263376dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2634f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26358fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2636facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
263724bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2638eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
263911833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2640eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2641a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
264276dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
264324bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26444cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
26452bf64758SJosef Bacik 	spin_lock_init(&fs_info->free_chunk_lock);
2646f29021b2SJan Schmidt 	spin_lock_init(&fs_info->tree_mod_seq_lock);
2647ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2648fcebe456SJosef Bacik 	spin_lock_init(&fs_info->qgroup_op_lock);
2649f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
265047ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2651f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2652d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
265367c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
26547585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2655573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2656c2d6cb16SFilipe Manana 	mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2657de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
265819c00ddcSChris Mason 
26590b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
26606324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2661f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
266247ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
26630b86a832SChris Mason 	btrfs_mapping_init(&fs_info->mapping_tree);
266466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
266566d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
266666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delalloc_block_rsv,
266766d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELALLOC);
266866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
266966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
267066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
267166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
267266d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2673cb03c743SChris Mason 	atomic_set(&fs_info->nr_async_submits, 0);
2674771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
26758c8bee1dSChris Mason 	atomic_set(&fs_info->async_submit_draining, 0);
26760986fe9eSChris Mason 	atomic_set(&fs_info->nr_async_bios, 0);
26774cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2678fcebe456SJosef Bacik 	atomic_set(&fs_info->qgroup_op_seq, 0);
26792fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2680fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
26819e7cc91aSWang Xiaoguang 	fs_info->fs_frozen = 0;
2682e20d96d6SChris Mason 	fs_info->sb = sb;
268395ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
26849ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
26854cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
26862bf64758SJosef Bacik 	fs_info->free_chunk_space = 0;
2687f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
26888b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2689f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
269090519d66SArne Jansen 	/* readahead state */
2691d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
269290519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2693c8b97818SChris Mason 
2694b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2695b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
26960afbaf8cSChris Mason 
2697199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2698199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
269916cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
270074e4d827SDavid Sterba 					GFP_KERNEL);
270116cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
270216cdcec7SMiao Xie 		err = -ENOMEM;
270316cdcec7SMiao Xie 		goto fail_iput;
270416cdcec7SMiao Xie 	}
270516cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
27063eaa2885SChris Mason 
2707638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
270821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
270921adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
271021adbd5cSStefan Behrens #endif
2711779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
271221c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2713a2de733cSArne Jansen 
2714a061fc8dSChris Mason 	sb->s_blocksize = 4096;
2715a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(4096);
271632a88aa1SJens Axboe 	sb->s_bdi = &fs_info->bdi;
2717a061fc8dSChris Mason 
27186bccf3abSJeff Mahoney 	btrfs_init_btree_inode(fs_info);
271939279cc3SChris Mason 
2720e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
27216bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2722a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
2723925baeddSChris Mason 
272411833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[0],
2725f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
272611833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[1],
2727f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
272811833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2729afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2730509659cdSChris Mason 
27315a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
273279154b1bSChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2733925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2734a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2735a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27367d9eb12cSChris Mason 	mutex_init(&fs_info->volume_mutex);
27371bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27389e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2739c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
274076dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2741803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2742fa9c0d79SChris Mason 
2743ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2744f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2745416ac51dSArne Jansen 
2746fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2747fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2748fa9c0d79SChris Mason 
2749e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2750f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2751bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27524854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
27533768f368SChris Mason 
275404216820SFilipe Manana 	INIT_LIST_HEAD(&fs_info->pinned_chunks);
275504216820SFilipe Manana 
2756da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2757da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2758da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2759da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2760da17066cSJeff Mahoney 
276153b381b3SDavid Woodhouse 	ret = btrfs_alloc_stripe_hash_table(fs_info);
276253b381b3SDavid Woodhouse 	if (ret) {
276383c8266aSDavid Sterba 		err = ret;
276453b381b3SDavid Woodhouse 		goto fail_alloc;
276553b381b3SDavid Woodhouse 	}
276653b381b3SDavid Woodhouse 
2767da17066cSJeff Mahoney 	__setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
27687eccb903SChris Mason 
27693c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
27701104a885SDavid Sterba 
27711104a885SDavid Sterba 	/*
27721104a885SDavid Sterba 	 * Read super block and check the signature bytes only
27731104a885SDavid Sterba 	 */
2774a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
277592fc03fbSAnand Jain 	if (IS_ERR(bh)) {
277692fc03fbSAnand Jain 		err = PTR_ERR(bh);
277716cdcec7SMiao Xie 		goto fail_alloc;
277820b45077SDave Young 	}
277939279cc3SChris Mason 
27801104a885SDavid Sterba 	/*
27811104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
27821104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
27831104a885SDavid Sterba 	 */
2784ab8d0fc4SJeff Mahoney 	if (btrfs_check_super_csum(fs_info, bh->b_data)) {
278505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
27861104a885SDavid Sterba 		err = -EINVAL;
2787b2acdddfSAnand Jain 		brelse(bh);
27881104a885SDavid Sterba 		goto fail_alloc;
27891104a885SDavid Sterba 	}
27901104a885SDavid Sterba 
27911104a885SDavid Sterba 	/*
27921104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
27931104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
27941104a885SDavid Sterba 	 * the whole block of INFO_SIZE
27951104a885SDavid Sterba 	 */
27966c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
27976c41761fSDavid Sterba 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
27986c41761fSDavid Sterba 	       sizeof(*fs_info->super_for_commit));
2799a061fc8dSChris Mason 	brelse(bh);
28005f39d397SChris Mason 
28016c41761fSDavid Sterba 	memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
28020b86a832SChris Mason 
28033d3a126aSDavid Sterba 	ret = btrfs_check_super_valid(fs_info);
28041104a885SDavid Sterba 	if (ret) {
280505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
28061104a885SDavid Sterba 		err = -EINVAL;
28071104a885SDavid Sterba 		goto fail_alloc;
28081104a885SDavid Sterba 	}
28091104a885SDavid Sterba 
28106c41761fSDavid Sterba 	disk_super = fs_info->super_copy;
28110f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
281216cdcec7SMiao Xie 		goto fail_alloc;
28130f7d52f4SChris Mason 
2814acce952bSliubo 	/* check FS state, whether FS is broken. */
281587533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
281687533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2817acce952bSliubo 
281875e7cb7fSLiu Bo 	/*
2819af31f5e5SChris Mason 	 * run through our array of backup supers and setup
2820af31f5e5SChris Mason 	 * our ring pointer to the oldest one
2821af31f5e5SChris Mason 	 */
2822af31f5e5SChris Mason 	generation = btrfs_super_generation(disk_super);
2823af31f5e5SChris Mason 	find_oldest_super_backup(fs_info, generation);
2824af31f5e5SChris Mason 
2825af31f5e5SChris Mason 	/*
282675e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
282775e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
282875e7cb7fSLiu Bo 	 */
282975e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
283075e7cb7fSLiu Bo 
28312ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
28322b82032cSYan Zheng 	if (ret) {
28332b82032cSYan Zheng 		err = ret;
283416cdcec7SMiao Xie 		goto fail_alloc;
28352b82032cSYan Zheng 	}
2836dfe25020SChris Mason 
2837f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2838f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2839f2b636e8SJosef Bacik 	if (features) {
284005135f59SDavid Sterba 		btrfs_err(fs_info,
284105135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
2842c1c9ff7cSGeert Uytterhoeven 		    features);
2843f2b636e8SJosef Bacik 		err = -EINVAL;
284416cdcec7SMiao Xie 		goto fail_alloc;
2845f2b636e8SJosef Bacik 	}
2846f2b636e8SJosef Bacik 
28475d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
28485d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
28490b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2850a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2851727011e0SChris Mason 
28523173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
285305135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
28543173a18fSJosef Bacik 
2855727011e0SChris Mason 	/*
2856727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2857727011e0SChris Mason 	 * they are bigger than the page size
2858727011e0SChris Mason 	 */
285909cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2860727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
286105135f59SDavid Sterba 			btrfs_info(fs_info,
286205135f59SDavid Sterba 				"flagging fs with big metadata feature");
2863727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2864727011e0SChris Mason 	}
2865727011e0SChris Mason 
2866bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2867bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2868b7f67055SChandan Rajendra 	stripesize = sectorsize;
2869707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2870963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2871bc3f116fSChris Mason 
2872da17066cSJeff Mahoney 	/* Cache block sizes */
2873da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
2874da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
2875da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
2876da17066cSJeff Mahoney 
2877bc3f116fSChris Mason 	/*
2878bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2879bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2880bc3f116fSChris Mason 	 */
2881bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2882707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
288305135f59SDavid Sterba 		btrfs_err(fs_info,
288405135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
288505135f59SDavid Sterba 			nodesize, sectorsize);
2886bc3f116fSChris Mason 		goto fail_alloc;
2887bc3f116fSChris Mason 	}
2888bc3f116fSChris Mason 
2889ceda0864SMiao Xie 	/*
2890ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
2891ceda0864SMiao Xie 	 * update the flag.
2892ceda0864SMiao Xie 	 */
28935d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
28945d4f98a2SYan Zheng 
2895f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2896f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2897f2b636e8SJosef Bacik 	if (!(sb->s_flags & MS_RDONLY) && features) {
289805135f59SDavid Sterba 		btrfs_err(fs_info,
289905135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
2900c1c9ff7cSGeert Uytterhoeven 		       features);
2901f2b636e8SJosef Bacik 		err = -EINVAL;
290216cdcec7SMiao Xie 		goto fail_alloc;
2903f2b636e8SJosef Bacik 	}
290461d92c32SChris Mason 
29055cdc7ad3SQu Wenruo 	max_active = fs_info->thread_pool_size;
290661d92c32SChris Mason 
29072a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
29082a458198SEric Sandeen 	if (ret) {
29092a458198SEric Sandeen 		err = ret;
29100dc3b84aSJosef Bacik 		goto fail_sb_buffer;
29110dc3b84aSJosef Bacik 	}
29124543df7eSChris Mason 
29134575c9ccSChris Mason 	fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
2914c8b97818SChris Mason 	fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
291509cbfeafSKirill A. Shutemov 				    SZ_4M / PAGE_SIZE);
29164575c9ccSChris Mason 
2917a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
2918a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
2919db94535dSChris Mason 
2920925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
29216bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
2922925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
292384eed90fSChris Mason 	if (ret) {
292405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
29255d4f98a2SYan Zheng 		goto fail_sb_buffer;
292684eed90fSChris Mason 	}
29270b86a832SChris Mason 
292884234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
29290b86a832SChris Mason 
2930da17066cSJeff Mahoney 	__setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
29310b86a832SChris Mason 
29322ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
29330b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
2934ce86cd59SDavid Sterba 					   generation);
293564c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
293664c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
293705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
2938e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
2939e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
294095ab1f64SZhao Lei 		chunk_root->node = NULL;
2941af31f5e5SChris Mason 		goto fail_tree_roots;
294283121942SDavid Woodhouse 	}
29435d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
29445d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
29450b86a832SChris Mason 
2946e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2947b308bc2fSGeert Uytterhoeven 	   btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2948e17cade2SChris Mason 
29495b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
29502b82032cSYan Zheng 	if (ret) {
295105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
2952af31f5e5SChris Mason 		goto fail_tree_roots;
29532b82032cSYan Zheng 	}
29540b86a832SChris Mason 
29558dabb742SStefan Behrens 	/*
29568dabb742SStefan Behrens 	 * keep the device that is marked to be the target device for the
29578dabb742SStefan Behrens 	 * dev_replace procedure
29588dabb742SStefan Behrens 	 */
29599eaed21eSEric Sandeen 	btrfs_close_extra_devices(fs_devices, 0);
2960dfe25020SChris Mason 
2961a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
296205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
2963a6b0d5c8SChris Mason 		goto fail_tree_roots;
2964a6b0d5c8SChris Mason 	}
2965a6b0d5c8SChris Mason 
2966af31f5e5SChris Mason retry_root_backup:
296784234f3aSYan Zheng 	generation = btrfs_super_generation(disk_super);
29680b86a832SChris Mason 
29692ff7e61eSJeff Mahoney 	tree_root->node = read_tree_block(fs_info,
2970db94535dSChris Mason 					  btrfs_super_root(disk_super),
2971ce86cd59SDavid Sterba 					  generation);
297264c043deSLiu Bo 	if (IS_ERR(tree_root->node) ||
297364c043deSLiu Bo 	    !extent_buffer_uptodate(tree_root->node)) {
297405135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to read tree root");
2975e5fffbacSchandan 		if (!IS_ERR(tree_root->node))
2976e5fffbacSchandan 			free_extent_buffer(tree_root->node);
297795ab1f64SZhao Lei 		tree_root->node = NULL;
2978af31f5e5SChris Mason 		goto recovery_tree_root;
297983121942SDavid Woodhouse 	}
2980af31f5e5SChris Mason 
29815d4f98a2SYan Zheng 	btrfs_set_root_node(&tree_root->root_item, tree_root->node);
29825d4f98a2SYan Zheng 	tree_root->commit_root = btrfs_root_node(tree_root);
298369e9c6c6SStefan Behrens 	btrfs_set_root_refs(&tree_root->root_item, 1);
2984db94535dSChris Mason 
2985f32e48e9SChandan Rajendra 	mutex_lock(&tree_root->objectid_mutex);
2986f32e48e9SChandan Rajendra 	ret = btrfs_find_highest_objectid(tree_root,
2987f32e48e9SChandan Rajendra 					&tree_root->highest_objectid);
2988f32e48e9SChandan Rajendra 	if (ret) {
2989f32e48e9SChandan Rajendra 		mutex_unlock(&tree_root->objectid_mutex);
2990f32e48e9SChandan Rajendra 		goto recovery_tree_root;
2991f32e48e9SChandan Rajendra 	}
2992f32e48e9SChandan Rajendra 
2993f32e48e9SChandan Rajendra 	ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2994f32e48e9SChandan Rajendra 
2995f32e48e9SChandan Rajendra 	mutex_unlock(&tree_root->objectid_mutex);
2996f32e48e9SChandan Rajendra 
29976bccf3abSJeff Mahoney 	ret = btrfs_read_roots(fs_info);
29984bbcaa64SEric Sandeen 	if (ret)
2999af31f5e5SChris Mason 		goto recovery_tree_root;
3000f7a81ea4SStefan Behrens 
30018929ecfaSYan, Zheng 	fs_info->generation = generation;
30028929ecfaSYan, Zheng 	fs_info->last_trans_committed = generation;
30038929ecfaSYan, Zheng 
300468310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
300568310a5eSIlya Dryomov 	if (ret) {
300605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
300768310a5eSIlya Dryomov 		goto fail_block_groups;
300868310a5eSIlya Dryomov 	}
300968310a5eSIlya Dryomov 
3010733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3011733f4fbbSStefan Behrens 	if (ret) {
301205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3013733f4fbbSStefan Behrens 		goto fail_block_groups;
3014733f4fbbSStefan Behrens 	}
3015733f4fbbSStefan Behrens 
30168dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
30178dabb742SStefan Behrens 	if (ret) {
301805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
30198dabb742SStefan Behrens 		goto fail_block_groups;
30208dabb742SStefan Behrens 	}
30218dabb742SStefan Behrens 
30229eaed21eSEric Sandeen 	btrfs_close_extra_devices(fs_devices, 1);
30238dabb742SStefan Behrens 
3024b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3025b7c35e81SAnand Jain 	if (ret) {
302605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
302705135f59SDavid Sterba 				ret);
3028b7c35e81SAnand Jain 		goto fail_block_groups;
3029b7c35e81SAnand Jain 	}
3030b7c35e81SAnand Jain 
3031b7c35e81SAnand Jain 	ret = btrfs_sysfs_add_device(fs_devices);
3032b7c35e81SAnand Jain 	if (ret) {
303305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs device interface: %d",
303405135f59SDavid Sterba 				ret);
3035b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
3036b7c35e81SAnand Jain 	}
3037b7c35e81SAnand Jain 
303896f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
30395ac1d209SJeff Mahoney 	if (ret) {
304005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3041b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
30425ac1d209SJeff Mahoney 	}
30435ac1d209SJeff Mahoney 
3044c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3045c59021f8Sliubo 	if (ret) {
304605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
30472365dd3cSAnand Jain 		goto fail_sysfs;
3048c59021f8Sliubo 	}
3049c59021f8Sliubo 
30505b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
30511b1d1f66SJosef Bacik 	if (ret) {
305205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
30532365dd3cSAnand Jain 		goto fail_sysfs;
30541b1d1f66SJosef Bacik 	}
30555af3e8ccSStefan Behrens 	fs_info->num_tolerated_disk_barrier_failures =
30565af3e8ccSStefan Behrens 		btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3057292fd7fcSStefan Behrens 	if (fs_info->fs_devices->missing_devices >
3058292fd7fcSStefan Behrens 	     fs_info->num_tolerated_disk_barrier_failures &&
3059292fd7fcSStefan Behrens 	    !(sb->s_flags & MS_RDONLY)) {
306005135f59SDavid Sterba 		btrfs_warn(fs_info,
306105135f59SDavid Sterba "missing devices (%llu) exceeds the limit (%d), writeable mount is not allowed",
306278fa1770SZhao Lei 			fs_info->fs_devices->missing_devices,
306378fa1770SZhao Lei 			fs_info->num_tolerated_disk_barrier_failures);
30642365dd3cSAnand Jain 		goto fail_sysfs;
3065292fd7fcSStefan Behrens 	}
30669078a3e1SChris Mason 
3067a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3068a74a4b97SChris Mason 					       "btrfs-cleaner");
306957506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
30702365dd3cSAnand Jain 		goto fail_sysfs;
3071a74a4b97SChris Mason 
3072a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3073a74a4b97SChris Mason 						   tree_root,
3074a74a4b97SChris Mason 						   "btrfs-transaction");
307557506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
30763f157a2fSChris Mason 		goto fail_cleaner;
3077a74a4b97SChris Mason 
30780b246afaSJeff Mahoney 	if (!btrfs_test_opt(fs_info, SSD) &&
30790b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOSSD) &&
3080c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
308105135f59SDavid Sterba 		btrfs_info(fs_info, "detected SSD devices, enabling SSD mode");
3082c289811cSChris Mason 		btrfs_set_opt(fs_info->mount_opt, SSD);
3083c289811cSChris Mason 	}
3084c289811cSChris Mason 
3085572d9ab7SDavid Sterba 	/*
308601327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3087572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3088572d9ab7SDavid Sterba 	 */
3089572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
30903818aea2SQu Wenruo 
309121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
30920b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
30932ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
30940b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
309521adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
309621adbd5cSStefan Behrens 				    1 : 0,
309721adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
309821adbd5cSStefan Behrens 		if (ret)
309905135f59SDavid Sterba 			btrfs_warn(fs_info,
310005135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
310105135f59SDavid Sterba 				ret);
310221adbd5cSStefan Behrens 	}
310321adbd5cSStefan Behrens #endif
3104bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3105bcef60f2SArne Jansen 	if (ret)
3106bcef60f2SArne Jansen 		goto fail_trans_kthread;
310721adbd5cSStefan Behrens 
310896da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
310996da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
31100b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
311163443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
311279787eaaSJeff Mahoney 		if (ret) {
311363443bf5SEric Sandeen 			err = ret;
311428c16cbbSWang Shilong 			goto fail_qgroup;
3115e556ce2cSYan Zheng 		}
3116e02119d5SChris Mason 	}
31171a40e23bSZheng Yan 
31186bccf3abSJeff Mahoney 	ret = btrfs_find_orphan_roots(fs_info);
311979787eaaSJeff Mahoney 	if (ret)
312028c16cbbSWang Shilong 		goto fail_qgroup;
312176dda93cSYan, Zheng 
31227c2ca468SChris Mason 	if (!(sb->s_flags & MS_RDONLY)) {
3123d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
312444c44af2SIlya Dryomov 		if (ret)
312528c16cbbSWang Shilong 			goto fail_qgroup;
312690c711abSZygo Blaxell 
312790c711abSZygo Blaxell 		mutex_lock(&fs_info->cleaner_mutex);
31285d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
312990c711abSZygo Blaxell 		mutex_unlock(&fs_info->cleaner_mutex);
3130d7ce5843SMiao Xie 		if (ret < 0) {
313105135f59SDavid Sterba 			btrfs_warn(fs_info, "failed to recover relocation: %d",
313205135f59SDavid Sterba 					ret);
3133d7ce5843SMiao Xie 			err = -EINVAL;
3134bcef60f2SArne Jansen 			goto fail_qgroup;
3135d7ce5843SMiao Xie 		}
31367c2ca468SChris Mason 	}
31371a40e23bSZheng Yan 
31383de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
31393de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
3140cb517eabSMiao Xie 	location.offset = 0;
31413de4586cSChris Mason 
31423de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
31433140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
31443140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3145bcef60f2SArne Jansen 		goto fail_qgroup;
31463140c9a3SDan Carpenter 	}
3147c289811cSChris Mason 
31482b6ba629SIlya Dryomov 	if (sb->s_flags & MS_RDONLY)
31492b6ba629SIlya Dryomov 		return 0;
31502b6ba629SIlya Dryomov 
3151f8d468a1SOmar Sandoval 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3152f8d468a1SOmar Sandoval 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31536675df31SOmar Sandoval 		clear_free_space_tree = 1;
31546675df31SOmar Sandoval 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
31556675df31SOmar Sandoval 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
31566675df31SOmar Sandoval 		btrfs_warn(fs_info, "free space tree is invalid");
31576675df31SOmar Sandoval 		clear_free_space_tree = 1;
31586675df31SOmar Sandoval 	}
31596675df31SOmar Sandoval 
31606675df31SOmar Sandoval 	if (clear_free_space_tree) {
3161f8d468a1SOmar Sandoval 		btrfs_info(fs_info, "clearing free space tree");
3162f8d468a1SOmar Sandoval 		ret = btrfs_clear_free_space_tree(fs_info);
3163f8d468a1SOmar Sandoval 		if (ret) {
3164f8d468a1SOmar Sandoval 			btrfs_warn(fs_info,
3165f8d468a1SOmar Sandoval 				   "failed to clear free space tree: %d", ret);
31666bccf3abSJeff Mahoney 			close_ctree(fs_info);
3167f8d468a1SOmar Sandoval 			return ret;
3168f8d468a1SOmar Sandoval 		}
3169f8d468a1SOmar Sandoval 	}
3170f8d468a1SOmar Sandoval 
31710b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3172511711afSChris Mason 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
317305135f59SDavid Sterba 		btrfs_info(fs_info, "creating free space tree");
3174511711afSChris Mason 		ret = btrfs_create_free_space_tree(fs_info);
3175511711afSChris Mason 		if (ret) {
317605135f59SDavid Sterba 			btrfs_warn(fs_info,
317705135f59SDavid Sterba 				"failed to create free space tree: %d", ret);
31786bccf3abSJeff Mahoney 			close_ctree(fs_info);
3179511711afSChris Mason 			return ret;
3180511711afSChris Mason 		}
3181511711afSChris Mason 	}
3182511711afSChris Mason 
3183e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
31842b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31852b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31862b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
31876bccf3abSJeff Mahoney 		close_ctree(fs_info);
31882b6ba629SIlya Dryomov 		return ret;
31892b6ba629SIlya Dryomov 	}
3190e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
319159641015SIlya Dryomov 
31922b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
31932b6ba629SIlya Dryomov 	if (ret) {
319405135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume balance: %d", ret);
31956bccf3abSJeff Mahoney 		close_ctree(fs_info);
31962b6ba629SIlya Dryomov 		return ret;
3197e3acc2a6SJosef Bacik 	}
3198e3acc2a6SJosef Bacik 
31998dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
32008dabb742SStefan Behrens 	if (ret) {
320105135f59SDavid Sterba 		btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
32026bccf3abSJeff Mahoney 		close_ctree(fs_info);
32038dabb742SStefan Behrens 		return ret;
32048dabb742SStefan Behrens 	}
32058dabb742SStefan Behrens 
3206b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
3207b382a324SJan Schmidt 
32084bbcaa64SEric Sandeen 	if (!fs_info->uuid_root) {
320905135f59SDavid Sterba 		btrfs_info(fs_info, "creating UUID tree");
3210f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
3211f7a81ea4SStefan Behrens 		if (ret) {
321205135f59SDavid Sterba 			btrfs_warn(fs_info,
321305135f59SDavid Sterba 				"failed to create the UUID tree: %d", ret);
32146bccf3abSJeff Mahoney 			close_ctree(fs_info);
3215f7a81ea4SStefan Behrens 			return ret;
3216f7a81ea4SStefan Behrens 		}
32170b246afaSJeff Mahoney 	} else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
32184bbcaa64SEric Sandeen 		   fs_info->generation !=
32194bbcaa64SEric Sandeen 				btrfs_super_uuid_tree_generation(disk_super)) {
322005135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
322170f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
322270f80175SStefan Behrens 		if (ret) {
322305135f59SDavid Sterba 			btrfs_warn(fs_info,
322405135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
32256bccf3abSJeff Mahoney 			close_ctree(fs_info);
322670f80175SStefan Behrens 			return ret;
322770f80175SStefan Behrens 		}
322870f80175SStefan Behrens 	} else {
3229afcdd129SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3230f7a81ea4SStefan Behrens 	}
3231afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
323247ab2a6cSJosef Bacik 
32338dcddfa0SQu Wenruo 	/*
32348dcddfa0SQu Wenruo 	 * backuproot only affect mount behavior, and if open_ctree succeeded,
32358dcddfa0SQu Wenruo 	 * no need to keep the flag
32368dcddfa0SQu Wenruo 	 */
32378dcddfa0SQu Wenruo 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
32388dcddfa0SQu Wenruo 
3239ad2b2c80SAl Viro 	return 0;
324039279cc3SChris Mason 
3241bcef60f2SArne Jansen fail_qgroup:
3242bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
32437c2ca468SChris Mason fail_trans_kthread:
32447c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
32452ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3246faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
32473f157a2fSChris Mason fail_cleaner:
3248a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
32497c2ca468SChris Mason 
32507c2ca468SChris Mason 	/*
32517c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
32527c2ca468SChris Mason 	 * kthreads
32537c2ca468SChris Mason 	 */
32547c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
32557c2ca468SChris Mason 
32562365dd3cSAnand Jain fail_sysfs:
32576618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
32582365dd3cSAnand Jain 
3259b7c35e81SAnand Jain fail_fsdev_sysfs:
3260b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3261b7c35e81SAnand Jain 
32621b1d1f66SJosef Bacik fail_block_groups:
326354067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3264af31f5e5SChris Mason 
3265af31f5e5SChris Mason fail_tree_roots:
3266af31f5e5SChris Mason 	free_root_pointers(fs_info, 1);
32672b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3268af31f5e5SChris Mason 
326939279cc3SChris Mason fail_sb_buffer:
32707abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
32715cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
327216cdcec7SMiao Xie fail_alloc:
32734543df7eSChris Mason fail_iput:
3274586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3275586e46e2SIlya Dryomov 
32764543df7eSChris Mason 	iput(fs_info->btree_inode);
3277c404e0dcSMiao Xie fail_bio_counter:
3278c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
3279963d678bSMiao Xie fail_delalloc_bytes:
3280963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3281e2d84521SMiao Xie fail_dirty_metadata_bytes:
3282e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3283ad081f14SJens Axboe fail_bdi:
32847e662854SQinghuang Feng 	bdi_destroy(&fs_info->bdi);
328576dda93cSYan, Zheng fail_srcu:
328676dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
32877e662854SQinghuang Feng fail:
328853b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3289586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3290ad2b2c80SAl Viro 	return err;
3291af31f5e5SChris Mason 
3292af31f5e5SChris Mason recovery_tree_root:
32930b246afaSJeff Mahoney 	if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3294af31f5e5SChris Mason 		goto fail_tree_roots;
3295af31f5e5SChris Mason 
3296af31f5e5SChris Mason 	free_root_pointers(fs_info, 0);
3297af31f5e5SChris Mason 
3298af31f5e5SChris Mason 	/* don't use the log in recovery mode, it won't be valid */
3299af31f5e5SChris Mason 	btrfs_set_super_log_root(disk_super, 0);
3300af31f5e5SChris Mason 
3301af31f5e5SChris Mason 	/* we can't trust the free space cache either */
3302af31f5e5SChris Mason 	btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3303af31f5e5SChris Mason 
3304af31f5e5SChris Mason 	ret = next_root_backup(fs_info, fs_info->super_copy,
3305af31f5e5SChris Mason 			       &num_backups_tried, &backup_index);
3306af31f5e5SChris Mason 	if (ret == -1)
3307af31f5e5SChris Mason 		goto fail_block_groups;
3308af31f5e5SChris Mason 	goto retry_root_backup;
3309eb60ceacSChris Mason }
3310eb60ceacSChris Mason 
3311f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3312f2984462SChris Mason {
3313f2984462SChris Mason 	if (uptodate) {
3314f2984462SChris Mason 		set_buffer_uptodate(bh);
3315f2984462SChris Mason 	} else {
3316442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
3317442a4f63SStefan Behrens 			bh->b_private;
3318442a4f63SStefan Behrens 
3319fb456252SJeff Mahoney 		btrfs_warn_rl_in_rcu(device->fs_info,
3320b14af3b4SDavid Sterba 				"lost page write due to IO error on %s",
3321606686eeSJosef Bacik 					  rcu_str_deref(device->name));
332201327610SNicholas D Steeves 		/* note, we don't set_buffer_write_io_error because we have
33231259ab75SChris Mason 		 * our own ways of dealing with the IO errors
33241259ab75SChris Mason 		 */
3325f2984462SChris Mason 		clear_buffer_uptodate(bh);
3326442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3327f2984462SChris Mason 	}
3328f2984462SChris Mason 	unlock_buffer(bh);
3329f2984462SChris Mason 	put_bh(bh);
3330f2984462SChris Mason }
3331f2984462SChris Mason 
333229c36d72SAnand Jain int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
333329c36d72SAnand Jain 			struct buffer_head **bh_ret)
333429c36d72SAnand Jain {
333529c36d72SAnand Jain 	struct buffer_head *bh;
333629c36d72SAnand Jain 	struct btrfs_super_block *super;
333729c36d72SAnand Jain 	u64 bytenr;
333829c36d72SAnand Jain 
333929c36d72SAnand Jain 	bytenr = btrfs_sb_offset(copy_num);
334029c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
334129c36d72SAnand Jain 		return -EINVAL;
334229c36d72SAnand Jain 
334329c36d72SAnand Jain 	bh = __bread(bdev, bytenr / 4096, BTRFS_SUPER_INFO_SIZE);
334429c36d72SAnand Jain 	/*
334529c36d72SAnand Jain 	 * If we fail to read from the underlying devices, as of now
334629c36d72SAnand Jain 	 * the best option we have is to mark it EIO.
334729c36d72SAnand Jain 	 */
334829c36d72SAnand Jain 	if (!bh)
334929c36d72SAnand Jain 		return -EIO;
335029c36d72SAnand Jain 
335129c36d72SAnand Jain 	super = (struct btrfs_super_block *)bh->b_data;
335229c36d72SAnand Jain 	if (btrfs_super_bytenr(super) != bytenr ||
335329c36d72SAnand Jain 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
335429c36d72SAnand Jain 		brelse(bh);
335529c36d72SAnand Jain 		return -EINVAL;
335629c36d72SAnand Jain 	}
335729c36d72SAnand Jain 
335829c36d72SAnand Jain 	*bh_ret = bh;
335929c36d72SAnand Jain 	return 0;
336029c36d72SAnand Jain }
336129c36d72SAnand Jain 
336229c36d72SAnand Jain 
3363a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3364a512bbf8SYan Zheng {
3365a512bbf8SYan Zheng 	struct buffer_head *bh;
3366a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
3367a512bbf8SYan Zheng 	struct btrfs_super_block *super;
3368a512bbf8SYan Zheng 	int i;
3369a512bbf8SYan Zheng 	u64 transid = 0;
337092fc03fbSAnand Jain 	int ret = -EINVAL;
3371a512bbf8SYan Zheng 
3372a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3373a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3374a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3375a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3376a512bbf8SYan Zheng 	 */
3377a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
337829c36d72SAnand Jain 		ret = btrfs_read_dev_one_super(bdev, i, &bh);
337929c36d72SAnand Jain 		if (ret)
3380a512bbf8SYan Zheng 			continue;
3381a512bbf8SYan Zheng 
3382a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
3383a512bbf8SYan Zheng 
3384a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
3385a512bbf8SYan Zheng 			brelse(latest);
3386a512bbf8SYan Zheng 			latest = bh;
3387a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3388a512bbf8SYan Zheng 		} else {
3389a512bbf8SYan Zheng 			brelse(bh);
3390a512bbf8SYan Zheng 		}
3391a512bbf8SYan Zheng 	}
339292fc03fbSAnand Jain 
339392fc03fbSAnand Jain 	if (!latest)
339492fc03fbSAnand Jain 		return ERR_PTR(ret);
339592fc03fbSAnand Jain 
3396a512bbf8SYan Zheng 	return latest;
3397a512bbf8SYan Zheng }
3398a512bbf8SYan Zheng 
33994eedeb75SHisashi Hifumi /*
34004eedeb75SHisashi Hifumi  * this should be called twice, once with wait == 0 and
34014eedeb75SHisashi Hifumi  * once with wait == 1.  When wait == 0 is done, all the buffer heads
34024eedeb75SHisashi Hifumi  * we write are pinned.
34034eedeb75SHisashi Hifumi  *
34044eedeb75SHisashi Hifumi  * They are released when wait == 1 is done.
34054eedeb75SHisashi Hifumi  * max_mirrors must be the same for both runs, and it indicates how
34064eedeb75SHisashi Hifumi  * many supers on this one device should be written.
34074eedeb75SHisashi Hifumi  *
34084eedeb75SHisashi Hifumi  * max_mirrors == 0 means to write them all.
34094eedeb75SHisashi Hifumi  */
3410a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3411a512bbf8SYan Zheng 			    struct btrfs_super_block *sb,
3412b75f5062SDavid Sterba 			    int wait, int max_mirrors)
3413a512bbf8SYan Zheng {
3414a512bbf8SYan Zheng 	struct buffer_head *bh;
3415a512bbf8SYan Zheng 	int i;
3416a512bbf8SYan Zheng 	int ret;
3417a512bbf8SYan Zheng 	int errors = 0;
3418a512bbf8SYan Zheng 	u32 crc;
3419a512bbf8SYan Zheng 	u64 bytenr;
3420a512bbf8SYan Zheng 
3421a512bbf8SYan Zheng 	if (max_mirrors == 0)
3422a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3423a512bbf8SYan Zheng 
3424a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3425a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3426935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3427935e5cc9SMiao Xie 		    device->commit_total_bytes)
3428a512bbf8SYan Zheng 			break;
3429a512bbf8SYan Zheng 
3430a512bbf8SYan Zheng 		if (wait) {
3431a512bbf8SYan Zheng 			bh = __find_get_block(device->bdev, bytenr / 4096,
3432a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE);
3433634554dcSJosef Bacik 			if (!bh) {
3434634554dcSJosef Bacik 				errors++;
3435634554dcSJosef Bacik 				continue;
3436634554dcSJosef Bacik 			}
3437a512bbf8SYan Zheng 			wait_on_buffer(bh);
34384eedeb75SHisashi Hifumi 			if (!buffer_uptodate(bh))
34394eedeb75SHisashi Hifumi 				errors++;
34404eedeb75SHisashi Hifumi 
34414eedeb75SHisashi Hifumi 			/* drop our reference */
34424eedeb75SHisashi Hifumi 			brelse(bh);
34434eedeb75SHisashi Hifumi 
34444eedeb75SHisashi Hifumi 			/* drop the reference from the wait == 0 run */
3445a512bbf8SYan Zheng 			brelse(bh);
3446a512bbf8SYan Zheng 			continue;
3447a512bbf8SYan Zheng 		} else {
3448a512bbf8SYan Zheng 			btrfs_set_super_bytenr(sb, bytenr);
3449a512bbf8SYan Zheng 
3450a512bbf8SYan Zheng 			crc = ~(u32)0;
3451b0496686SLiu Bo 			crc = btrfs_csum_data((char *)sb +
3452a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE, crc,
3453a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE -
3454a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE);
3455a512bbf8SYan Zheng 			btrfs_csum_final(crc, sb->csum);
3456a512bbf8SYan Zheng 
34574eedeb75SHisashi Hifumi 			/*
34584eedeb75SHisashi Hifumi 			 * one reference for us, and we leave it for the
34594eedeb75SHisashi Hifumi 			 * caller
34604eedeb75SHisashi Hifumi 			 */
3461a512bbf8SYan Zheng 			bh = __getblk(device->bdev, bytenr / 4096,
3462a512bbf8SYan Zheng 				      BTRFS_SUPER_INFO_SIZE);
3463634554dcSJosef Bacik 			if (!bh) {
3464fb456252SJeff Mahoney 				btrfs_err(device->fs_info,
3465f14d104dSDavid Sterba 				    "couldn't get super buffer head for bytenr %llu",
3466f14d104dSDavid Sterba 				    bytenr);
3467634554dcSJosef Bacik 				errors++;
3468634554dcSJosef Bacik 				continue;
3469634554dcSJosef Bacik 			}
3470634554dcSJosef Bacik 
3471a512bbf8SYan Zheng 			memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3472a512bbf8SYan Zheng 
34734eedeb75SHisashi Hifumi 			/* one reference for submit_bh */
3474a512bbf8SYan Zheng 			get_bh(bh);
34754eedeb75SHisashi Hifumi 
34764eedeb75SHisashi Hifumi 			set_buffer_uptodate(bh);
3477a512bbf8SYan Zheng 			lock_buffer(bh);
3478a512bbf8SYan Zheng 			bh->b_end_io = btrfs_end_buffer_write_sync;
3479442a4f63SStefan Behrens 			bh->b_private = device;
3480a512bbf8SYan Zheng 		}
3481a512bbf8SYan Zheng 
3482387125fcSChris Mason 		/*
3483387125fcSChris Mason 		 * we fua the first super.  The others we allow
3484387125fcSChris Mason 		 * to go down lazy.
3485387125fcSChris Mason 		 */
3486e8117c26SWang Shilong 		if (i == 0)
348770fd7614SChristoph Hellwig 			ret = btrfsic_submit_bh(REQ_OP_WRITE, REQ_FUA, bh);
3488e8117c26SWang Shilong 		else
348970fd7614SChristoph Hellwig 			ret = btrfsic_submit_bh(REQ_OP_WRITE, REQ_SYNC, bh);
34904eedeb75SHisashi Hifumi 		if (ret)
3491a512bbf8SYan Zheng 			errors++;
3492a512bbf8SYan Zheng 	}
3493a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3494a512bbf8SYan Zheng }
3495a512bbf8SYan Zheng 
3496387125fcSChris Mason /*
3497387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3498387125fcSChris Mason  * for the barrier when it is done
3499387125fcSChris Mason  */
35004246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3501387125fcSChris Mason {
3502387125fcSChris Mason 	if (bio->bi_private)
3503387125fcSChris Mason 		complete(bio->bi_private);
3504387125fcSChris Mason 	bio_put(bio);
3505387125fcSChris Mason }
3506387125fcSChris Mason 
3507387125fcSChris Mason /*
3508387125fcSChris Mason  * trigger flushes for one the devices.  If you pass wait == 0, the flushes are
3509387125fcSChris Mason  * sent down.  With wait == 1, it waits for the previous flush.
3510387125fcSChris Mason  *
3511387125fcSChris Mason  * any device where the flush fails with eopnotsupp are flagged as not-barrier
3512387125fcSChris Mason  * capable
3513387125fcSChris Mason  */
3514387125fcSChris Mason static int write_dev_flush(struct btrfs_device *device, int wait)
3515387125fcSChris Mason {
3516387125fcSChris Mason 	struct bio *bio;
3517387125fcSChris Mason 	int ret = 0;
3518387125fcSChris Mason 
3519387125fcSChris Mason 	if (device->nobarriers)
3520387125fcSChris Mason 		return 0;
3521387125fcSChris Mason 
3522387125fcSChris Mason 	if (wait) {
3523387125fcSChris Mason 		bio = device->flush_bio;
3524387125fcSChris Mason 		if (!bio)
3525387125fcSChris Mason 			return 0;
3526387125fcSChris Mason 
3527387125fcSChris Mason 		wait_for_completion(&device->flush_wait);
3528387125fcSChris Mason 
35294246a0b6SChristoph Hellwig 		if (bio->bi_error) {
35304246a0b6SChristoph Hellwig 			ret = bio->bi_error;
3531442a4f63SStefan Behrens 			btrfs_dev_stat_inc_and_print(device,
3532442a4f63SStefan Behrens 				BTRFS_DEV_STAT_FLUSH_ERRS);
3533387125fcSChris Mason 		}
3534387125fcSChris Mason 
3535387125fcSChris Mason 		/* drop the reference from the wait == 0 run */
3536387125fcSChris Mason 		bio_put(bio);
3537387125fcSChris Mason 		device->flush_bio = NULL;
3538387125fcSChris Mason 
3539387125fcSChris Mason 		return ret;
3540387125fcSChris Mason 	}
3541387125fcSChris Mason 
3542387125fcSChris Mason 	/*
3543387125fcSChris Mason 	 * one reference for us, and we leave it for the
3544387125fcSChris Mason 	 * caller
3545387125fcSChris Mason 	 */
35469c017abcSJesper Juhl 	device->flush_bio = NULL;
35479be3395bSChris Mason 	bio = btrfs_io_bio_alloc(GFP_NOFS, 0);
3548387125fcSChris Mason 	if (!bio)
3549387125fcSChris Mason 		return -ENOMEM;
3550387125fcSChris Mason 
3551387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
3552387125fcSChris Mason 	bio->bi_bdev = device->bdev;
355370fd7614SChristoph Hellwig 	bio->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
3554387125fcSChris Mason 	init_completion(&device->flush_wait);
3555387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3556387125fcSChris Mason 	device->flush_bio = bio;
3557387125fcSChris Mason 
3558387125fcSChris Mason 	bio_get(bio);
35594e49ea4aSMike Christie 	btrfsic_submit_bio(bio);
3560387125fcSChris Mason 
3561387125fcSChris Mason 	return 0;
3562387125fcSChris Mason }
3563387125fcSChris Mason 
3564387125fcSChris Mason /*
3565387125fcSChris Mason  * send an empty flush down to each device in parallel,
3566387125fcSChris Mason  * then wait for them
3567387125fcSChris Mason  */
3568387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3569387125fcSChris Mason {
3570387125fcSChris Mason 	struct list_head *head;
3571387125fcSChris Mason 	struct btrfs_device *dev;
35725af3e8ccSStefan Behrens 	int errors_send = 0;
35735af3e8ccSStefan Behrens 	int errors_wait = 0;
3574387125fcSChris Mason 	int ret;
3575387125fcSChris Mason 
3576387125fcSChris Mason 	/* send down all the barriers */
3577387125fcSChris Mason 	head = &info->fs_devices->devices;
3578387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
3579f88ba6a2SHidetoshi Seto 		if (dev->missing)
3580f88ba6a2SHidetoshi Seto 			continue;
3581387125fcSChris Mason 		if (!dev->bdev) {
35825af3e8ccSStefan Behrens 			errors_send++;
3583387125fcSChris Mason 			continue;
3584387125fcSChris Mason 		}
3585387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
3586387125fcSChris Mason 			continue;
3587387125fcSChris Mason 
3588387125fcSChris Mason 		ret = write_dev_flush(dev, 0);
3589387125fcSChris Mason 		if (ret)
35905af3e8ccSStefan Behrens 			errors_send++;
3591387125fcSChris Mason 	}
3592387125fcSChris Mason 
3593387125fcSChris Mason 	/* wait for all the barriers */
3594387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
3595f88ba6a2SHidetoshi Seto 		if (dev->missing)
3596f88ba6a2SHidetoshi Seto 			continue;
3597387125fcSChris Mason 		if (!dev->bdev) {
35985af3e8ccSStefan Behrens 			errors_wait++;
3599387125fcSChris Mason 			continue;
3600387125fcSChris Mason 		}
3601387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
3602387125fcSChris Mason 			continue;
3603387125fcSChris Mason 
3604387125fcSChris Mason 		ret = write_dev_flush(dev, 1);
3605387125fcSChris Mason 		if (ret)
36065af3e8ccSStefan Behrens 			errors_wait++;
3607387125fcSChris Mason 	}
36085af3e8ccSStefan Behrens 	if (errors_send > info->num_tolerated_disk_barrier_failures ||
36095af3e8ccSStefan Behrens 	    errors_wait > info->num_tolerated_disk_barrier_failures)
3610387125fcSChris Mason 		return -EIO;
3611387125fcSChris Mason 	return 0;
3612387125fcSChris Mason }
3613387125fcSChris Mason 
3614943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3615943c6e99SZhao Lei {
36168789f4feSZhao Lei 	int raid_type;
36178789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3618943c6e99SZhao Lei 
36198789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
36208789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
36218789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
36228789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
36238789f4feSZhao Lei 				    tolerated_failures);
3624943c6e99SZhao Lei 
36258789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
36268789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
36278789f4feSZhao Lei 			continue;
36288789f4feSZhao Lei 		if (!(flags & btrfs_raid_group[raid_type]))
36298789f4feSZhao Lei 			continue;
36308789f4feSZhao Lei 		min_tolerated = min(min_tolerated,
36318789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
36328789f4feSZhao Lei 				    tolerated_failures);
36338789f4feSZhao Lei 	}
3634943c6e99SZhao Lei 
36358789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3636ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
36378789f4feSZhao Lei 		min_tolerated = 0;
36388789f4feSZhao Lei 	}
36398789f4feSZhao Lei 
36408789f4feSZhao Lei 	return min_tolerated;
3641943c6e99SZhao Lei }
3642943c6e99SZhao Lei 
36435af3e8ccSStefan Behrens int btrfs_calc_num_tolerated_disk_barrier_failures(
36445af3e8ccSStefan Behrens 	struct btrfs_fs_info *fs_info)
36455af3e8ccSStefan Behrens {
36465af3e8ccSStefan Behrens 	struct btrfs_ioctl_space_info space;
36475af3e8ccSStefan Behrens 	struct btrfs_space_info *sinfo;
36485af3e8ccSStefan Behrens 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
36495af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_SYSTEM,
36505af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_METADATA,
36515af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
36525af3e8ccSStefan Behrens 	int i;
36535af3e8ccSStefan Behrens 	int c;
36545af3e8ccSStefan Behrens 	int num_tolerated_disk_barrier_failures =
36555af3e8ccSStefan Behrens 		(int)fs_info->fs_devices->num_devices;
36565af3e8ccSStefan Behrens 
36572c458045SZhao Lei 	for (i = 0; i < ARRAY_SIZE(types); i++) {
36585af3e8ccSStefan Behrens 		struct btrfs_space_info *tmp;
36595af3e8ccSStefan Behrens 
36605af3e8ccSStefan Behrens 		sinfo = NULL;
36615af3e8ccSStefan Behrens 		rcu_read_lock();
36625af3e8ccSStefan Behrens 		list_for_each_entry_rcu(tmp, &fs_info->space_info, list) {
36635af3e8ccSStefan Behrens 			if (tmp->flags == types[i]) {
36645af3e8ccSStefan Behrens 				sinfo = tmp;
36655af3e8ccSStefan Behrens 				break;
36665af3e8ccSStefan Behrens 			}
36675af3e8ccSStefan Behrens 		}
36685af3e8ccSStefan Behrens 		rcu_read_unlock();
36695af3e8ccSStefan Behrens 
36705af3e8ccSStefan Behrens 		if (!sinfo)
36715af3e8ccSStefan Behrens 			continue;
36725af3e8ccSStefan Behrens 
36735af3e8ccSStefan Behrens 		down_read(&sinfo->groups_sem);
36745af3e8ccSStefan Behrens 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
36755af3e8ccSStefan Behrens 			u64 flags;
36765af3e8ccSStefan Behrens 
36772c458045SZhao Lei 			if (list_empty(&sinfo->block_groups[c]))
36782c458045SZhao Lei 				continue;
36792c458045SZhao Lei 
36802c458045SZhao Lei 			btrfs_get_block_group_info(&sinfo->block_groups[c],
36812c458045SZhao Lei 						   &space);
36822c458045SZhao Lei 			if (space.total_bytes == 0 || space.used_bytes == 0)
36835af3e8ccSStefan Behrens 				continue;
36845af3e8ccSStefan Behrens 			flags = space.flags;
3685943c6e99SZhao Lei 
3686943c6e99SZhao Lei 			num_tolerated_disk_barrier_failures = min(
3687943c6e99SZhao Lei 				num_tolerated_disk_barrier_failures,
3688943c6e99SZhao Lei 				btrfs_get_num_tolerated_disk_barrier_failures(
3689943c6e99SZhao Lei 					flags));
36905af3e8ccSStefan Behrens 		}
36915af3e8ccSStefan Behrens 		up_read(&sinfo->groups_sem);
36925af3e8ccSStefan Behrens 	}
36935af3e8ccSStefan Behrens 
36945af3e8ccSStefan Behrens 	return num_tolerated_disk_barrier_failures;
36955af3e8ccSStefan Behrens }
36965af3e8ccSStefan Behrens 
3697eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3698f2984462SChris Mason {
3699e5e9a520SChris Mason 	struct list_head *head;
3700f2984462SChris Mason 	struct btrfs_device *dev;
3701a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3702f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3703f2984462SChris Mason 	int ret;
3704f2984462SChris Mason 	int do_barriers;
3705a236aed1SChris Mason 	int max_errors;
3706a236aed1SChris Mason 	int total_errors = 0;
3707a061fc8dSChris Mason 	u64 flags;
3708f2984462SChris Mason 
37090b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
37100b246afaSJeff Mahoney 	backup_super_roots(fs_info);
3711f2984462SChris Mason 
37120b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3713a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3714e5e9a520SChris Mason 
37150b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
37160b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
37170b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3718387125fcSChris Mason 
37195af3e8ccSStefan Behrens 	if (do_barriers) {
37200b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
37215af3e8ccSStefan Behrens 		if (ret) {
37225af3e8ccSStefan Behrens 			mutex_unlock(
37230b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
37240b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
37255af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
37265af3e8ccSStefan Behrens 			return ret;
37275af3e8ccSStefan Behrens 		}
37285af3e8ccSStefan Behrens 	}
3729387125fcSChris Mason 
37301f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
3731dfe25020SChris Mason 		if (!dev->bdev) {
3732dfe25020SChris Mason 			total_errors++;
3733dfe25020SChris Mason 			continue;
3734dfe25020SChris Mason 		}
37352b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
3736dfe25020SChris Mason 			continue;
3737dfe25020SChris Mason 
37382b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3739a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3740a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
37417df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3742935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3743ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3744ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3745a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3746a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3747a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3748a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
37492b82032cSYan Zheng 		memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
3750a512bbf8SYan Zheng 
3751a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3752a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3753f2984462SChris Mason 
3754b75f5062SDavid Sterba 		ret = write_dev_supers(dev, sb, 0, max_mirrors);
3755a236aed1SChris Mason 		if (ret)
3756a236aed1SChris Mason 			total_errors++;
3757f2984462SChris Mason 	}
3758a236aed1SChris Mason 	if (total_errors > max_errors) {
37590b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3760d397712bSChris Mason 			  total_errors);
37610b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
376279787eaaSJeff Mahoney 
37639d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
37640b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
37650b246afaSJeff Mahoney 				      "%d errors while writing supers",
37660b246afaSJeff Mahoney 				      total_errors);
37679d565ba4SStefan Behrens 		return -EIO;
3768a236aed1SChris Mason 	}
3769f2984462SChris Mason 
3770a512bbf8SYan Zheng 	total_errors = 0;
37711f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
3772dfe25020SChris Mason 		if (!dev->bdev)
3773dfe25020SChris Mason 			continue;
37742b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
3775dfe25020SChris Mason 			continue;
3776dfe25020SChris Mason 
3777b75f5062SDavid Sterba 		ret = write_dev_supers(dev, sb, 1, max_mirrors);
3778a512bbf8SYan Zheng 		if (ret)
37791259ab75SChris Mason 			total_errors++;
3780f2984462SChris Mason 	}
37810b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3782a236aed1SChris Mason 	if (total_errors > max_errors) {
37830b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
37840b246afaSJeff Mahoney 				      "%d errors while writing supers",
37850b246afaSJeff Mahoney 				      total_errors);
378679787eaaSJeff Mahoney 		return -EIO;
3787a236aed1SChris Mason 	}
3788f2984462SChris Mason 	return 0;
3789f2984462SChris Mason }
3790f2984462SChris Mason 
3791cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3792cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3793cb517eabSMiao Xie 				  struct btrfs_root *root)
37942619ba1fSChris Mason {
37954df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
37962619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
37972619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
37984df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
379976dda93cSYan, Zheng 
380076dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
380176dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
380276dda93cSYan, Zheng 
38031c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
38043321719eSLiu Bo 		btrfs_free_log(NULL, root);
38051c1ea4f7SLiu Bo 		if (root->reloc_root) {
38061c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->node);
38071c1ea4f7SLiu Bo 			free_extent_buffer(root->reloc_root->commit_root);
38081c1ea4f7SLiu Bo 			btrfs_put_fs_root(root->reloc_root);
38091c1ea4f7SLiu Bo 			root->reloc_root = NULL;
38101c1ea4f7SLiu Bo 		}
38111c1ea4f7SLiu Bo 	}
38123321719eSLiu Bo 
3813faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3814581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3815faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3816581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
38174df27c4dSYan, Zheng 	free_fs_root(root);
38184df27c4dSYan, Zheng }
38194df27c4dSYan, Zheng 
38204df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root)
38214df27c4dSYan, Zheng {
382257cdc8dbSDavid Sterba 	iput(root->ino_cache_inode);
38234df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
38242ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(root->fs_info, root->orphan_block_rsv);
38251cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
38260ee5dc67SAl Viro 	if (root->anon_dev)
38270ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
38288257b2dcSMiao Xie 	if (root->subv_writers)
38298257b2dcSMiao Xie 		btrfs_free_subvolume_writers(root->subv_writers);
38305f39d397SChris Mason 	free_extent_buffer(root->node);
38315f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3832581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3833581bb050SLi Zefan 	kfree(root->free_ino_pinned);
383458176a96SJosef Bacik 	kfree(root->name);
3835b0feb9d9SMiao Xie 	btrfs_put_fs_root(root);
38362619ba1fSChris Mason }
38372619ba1fSChris Mason 
3838cb517eabSMiao Xie void btrfs_free_fs_root(struct btrfs_root *root)
3839cb517eabSMiao Xie {
3840cb517eabSMiao Xie 	free_fs_root(root);
3841cfaa7295SChris Mason }
3842cfaa7295SChris Mason 
3843c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3844c146afadSYan Zheng {
3845c146afadSYan Zheng 	u64 root_objectid = 0;
3846c146afadSYan Zheng 	struct btrfs_root *gang[8];
384765d33fd7SQu Wenruo 	int i = 0;
384865d33fd7SQu Wenruo 	int err = 0;
384965d33fd7SQu Wenruo 	unsigned int ret = 0;
385065d33fd7SQu Wenruo 	int index;
3851c146afadSYan Zheng 
3852c146afadSYan Zheng 	while (1) {
385365d33fd7SQu Wenruo 		index = srcu_read_lock(&fs_info->subvol_srcu);
3854c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3855c146afadSYan Zheng 					     (void **)gang, root_objectid,
3856c146afadSYan Zheng 					     ARRAY_SIZE(gang));
385765d33fd7SQu Wenruo 		if (!ret) {
385865d33fd7SQu Wenruo 			srcu_read_unlock(&fs_info->subvol_srcu, index);
3859c146afadSYan Zheng 			break;
386065d33fd7SQu Wenruo 		}
38615d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
386266b4ffd1SJosef Bacik 
386365d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
386465d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
386565d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
386665d33fd7SQu Wenruo 				gang[i] = NULL;
386765d33fd7SQu Wenruo 				continue;
386865d33fd7SQu Wenruo 			}
386965d33fd7SQu Wenruo 			/* grab all the search result for later use */
387065d33fd7SQu Wenruo 			gang[i] = btrfs_grab_fs_root(gang[i]);
387165d33fd7SQu Wenruo 		}
387265d33fd7SQu Wenruo 		srcu_read_unlock(&fs_info->subvol_srcu, index);
387365d33fd7SQu Wenruo 
387465d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
387565d33fd7SQu Wenruo 			if (!gang[i])
387665d33fd7SQu Wenruo 				continue;
3877c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
387866b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
387966b4ffd1SJosef Bacik 			if (err)
388065d33fd7SQu Wenruo 				break;
388165d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
3882c146afadSYan Zheng 		}
3883c146afadSYan Zheng 		root_objectid++;
3884c146afadSYan Zheng 	}
388565d33fd7SQu Wenruo 
388665d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
388765d33fd7SQu Wenruo 	for (; i < ret; i++) {
388865d33fd7SQu Wenruo 		if (gang[i])
388965d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
389065d33fd7SQu Wenruo 	}
389165d33fd7SQu Wenruo 	return err;
3892c146afadSYan Zheng }
3893c146afadSYan Zheng 
38946bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3895c146afadSYan Zheng {
38966bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3897c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3898c146afadSYan Zheng 
38990b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
39002ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
39010b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
39020b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
3903c71bf099SYan, Zheng 
3904c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
39050b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
39060b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
3907c71bf099SYan, Zheng 
39087a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
39093612b495STsutomu Itoh 	if (IS_ERR(trans))
39103612b495STsutomu Itoh 		return PTR_ERR(trans);
39113a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
3912c146afadSYan Zheng }
3913c146afadSYan Zheng 
39146bccf3abSJeff Mahoney void close_ctree(struct btrfs_fs_info *fs_info)
3915eb60ceacSChris Mason {
39166bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
3917c146afadSYan Zheng 	int ret;
3918e089f05cSChris Mason 
3919afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3920a2135011SChris Mason 
39217343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
3922d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
39237343dd61SJustin Maggard 
3924803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3925803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3926803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3927803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3928803b2f54SStefan Behrens 
3929837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3930aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3931837d5b6eSIlya Dryomov 
39328dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
39338dabb742SStefan Behrens 
3934aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
39354cb5300bSChris Mason 
39364cb5300bSChris Mason 	/* wait for any defraggers to finish */
39374cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
39384cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
39394cb5300bSChris Mason 
39404cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
394126176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
39424cb5300bSChris Mason 
394321c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
394421c7e756SMiao Xie 
3945c146afadSYan Zheng 	if (!(fs_info->sb->s_flags & MS_RDONLY)) {
3946e44163e1SJeff Mahoney 		/*
3947e44163e1SJeff Mahoney 		 * If the cleaner thread is stopped and there are
3948e44163e1SJeff Mahoney 		 * block groups queued for removal, the deletion will be
3949e44163e1SJeff Mahoney 		 * skipped when we quit the cleaner thread.
3950e44163e1SJeff Mahoney 		 */
39510b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
3952e44163e1SJeff Mahoney 
39536bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
3954d397712bSChris Mason 		if (ret)
395504892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
3956c146afadSYan Zheng 	}
3957ed2ff2cbSChris Mason 
395887533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
39592ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
3960acce952bSliubo 
3961e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
3962e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
39638929ecfaSYan, Zheng 
3964afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
3965f25784b3SYan Zheng 
396604892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
3967bcef60f2SArne Jansen 
3968963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
396904892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
3970963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
3971b0c68f8bSChris Mason 	}
397231153d81SYan Zheng 
39736618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
3974b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
39755ac1d209SJeff Mahoney 
3976faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
3977d10c5f31SChris Mason 
39781a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
39791a4319ccSLiu Bo 
3980de348ee0SWang Shilong 	/*
3981de348ee0SWang Shilong 	 * we must make sure there is not any read request to
3982de348ee0SWang Shilong 	 * submit after we stopping all workers.
3983de348ee0SWang Shilong 	 */
3984de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
398596192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
398696192499SJosef Bacik 
39875cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
39885cdd7db6SFilipe Manana 
3989afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
399013e6c37bSJosef Bacik 	free_root_pointers(fs_info, 1);
39919ad6b7bcSChris Mason 
399213e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
3993d6bfde87SChris Mason 
399421adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
39950b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
39962ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
399721adbd5cSStefan Behrens #endif
399821adbd5cSStefan Behrens 
3999dfe25020SChris Mason 	btrfs_close_devices(fs_info->fs_devices);
40000b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
4001b248a415SChris Mason 
4002e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
4003963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
4004c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
400504160088SChris Mason 	bdi_destroy(&fs_info->bdi);
400676dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
40070b86a832SChris Mason 
400853b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
400953b381b3SDavid Woodhouse 
4010cdfb080eSChris Mason 	__btrfs_free_block_rsv(root->orphan_block_rsv);
40111cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
401204216820SFilipe Manana 
401334441361SDavid Sterba 	mutex_lock(&fs_info->chunk_mutex);
401404216820SFilipe Manana 	while (!list_empty(&fs_info->pinned_chunks)) {
401504216820SFilipe Manana 		struct extent_map *em;
401604216820SFilipe Manana 
401704216820SFilipe Manana 		em = list_first_entry(&fs_info->pinned_chunks,
401804216820SFilipe Manana 				      struct extent_map, list);
401904216820SFilipe Manana 		list_del_init(&em->list);
402004216820SFilipe Manana 		free_extent_map(em);
402104216820SFilipe Manana 	}
402234441361SDavid Sterba 	mutex_unlock(&fs_info->chunk_mutex);
4023eb60ceacSChris Mason }
4024eb60ceacSChris Mason 
4025b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4026b9fab919SChris Mason 			  int atomic)
4027ccd467d6SChris Mason {
40281259ab75SChris Mason 	int ret;
4029727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
40301259ab75SChris Mason 
40310b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
40321259ab75SChris Mason 	if (!ret)
40331259ab75SChris Mason 		return ret;
40341259ab75SChris Mason 
40351259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4036b9fab919SChris Mason 				    parent_transid, atomic);
4037b9fab919SChris Mason 	if (ret == -EAGAIN)
4038b9fab919SChris Mason 		return ret;
40391259ab75SChris Mason 	return !ret;
40405f39d397SChris Mason }
40416702ed49SChris Mason 
40425f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
40435f39d397SChris Mason {
40440b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info;
404506ea65a3SJosef Bacik 	struct btrfs_root *root;
40465f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4047b9473439SChris Mason 	int was_dirty;
4048b4ce94deSChris Mason 
404906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
405006ea65a3SJosef Bacik 	/*
405106ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
405206ea65a3SJosef Bacik 	 * enabled.  Normal people shouldn't be marking dummy buffers as dirty
405306ea65a3SJosef Bacik 	 * outside of the sanity tests.
405406ea65a3SJosef Bacik 	 */
405506ea65a3SJosef Bacik 	if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
405606ea65a3SJosef Bacik 		return;
405706ea65a3SJosef Bacik #endif
405806ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
40590b246afaSJeff Mahoney 	fs_info = root->fs_info;
4060b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
40610b246afaSJeff Mahoney 	if (transid != fs_info->generation)
40625d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
40630b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
40640b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4065e2d84521SMiao Xie 	if (!was_dirty)
40660b246afaSJeff Mahoney 		__percpu_counter_add(&fs_info->dirty_metadata_bytes,
4067e2d84521SMiao Xie 				     buf->len,
40680b246afaSJeff Mahoney 				     fs_info->dirty_metadata_batch);
40691f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
40701f21ef0aSFilipe Manana 	if (btrfs_header_level(buf) == 0 && check_leaf(root, buf)) {
40712ff7e61eSJeff Mahoney 		btrfs_print_leaf(fs_info, buf);
40721f21ef0aSFilipe Manana 		ASSERT(0);
40731f21ef0aSFilipe Manana 	}
40741f21ef0aSFilipe Manana #endif
4075eb60ceacSChris Mason }
4076eb60ceacSChris Mason 
40772ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4078b53d3f5dSLiu Bo 					int flush_delayed)
407935b7e476SChris Mason {
4080188de649SChris Mason 	/*
4081188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4082188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4083188de649SChris Mason 	 */
4084e2d84521SMiao Xie 	int ret;
4085d6bfde87SChris Mason 
40866933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4087d6bfde87SChris Mason 		return;
4088d6bfde87SChris Mason 
4089b53d3f5dSLiu Bo 	if (flush_delayed)
40902ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
409116cdcec7SMiao Xie 
40920b246afaSJeff Mahoney 	ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4093e2d84521SMiao Xie 				     BTRFS_DIRTY_METADATA_THRESH);
4094e2d84521SMiao Xie 	if (ret > 0) {
40950b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
409616cdcec7SMiao Xie 	}
409716cdcec7SMiao Xie }
409816cdcec7SMiao Xie 
40992ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
410016cdcec7SMiao Xie {
41012ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
410235b7e476SChris Mason }
4103b53d3f5dSLiu Bo 
41042ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4105b53d3f5dSLiu Bo {
41062ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4107d6bfde87SChris Mason }
41086b80053dSChris Mason 
4109ca7a79adSChris Mason int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
41106b80053dSChris Mason {
4111727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
41122ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41132ff7e61eSJeff Mahoney 
41142ff7e61eSJeff Mahoney 	return btree_read_extent_buffer_pages(fs_info, buf, parent_transid);
41156b80053dSChris Mason }
41160da5468fSChris Mason 
41173d3a126aSDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info)
4118acce952bSliubo {
4119c926093eSDavid Sterba 	struct btrfs_super_block *sb = fs_info->super_copy;
4120319e4d06SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
4121319e4d06SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
4122c926093eSDavid Sterba 	int ret = 0;
4123c926093eSDavid Sterba 
4124319e4d06SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
4125ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "no valid FS found");
4126319e4d06SQu Wenruo 		ret = -EINVAL;
4127319e4d06SQu Wenruo 	}
4128319e4d06SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP)
4129ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "unrecognized super flag: %llu",
4130319e4d06SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
413121e7626bSDavid Sterba 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
4132ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
413321e7626bSDavid Sterba 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
4134c926093eSDavid Sterba 		ret = -EINVAL;
4135c926093eSDavid Sterba 	}
413621e7626bSDavid Sterba 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
4137ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
413821e7626bSDavid Sterba 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
4139c926093eSDavid Sterba 		ret = -EINVAL;
4140c926093eSDavid Sterba 	}
414121e7626bSDavid Sterba 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
4142ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
414321e7626bSDavid Sterba 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
4144c926093eSDavid Sterba 		ret = -EINVAL;
4145c926093eSDavid Sterba 	}
4146c926093eSDavid Sterba 
41471104a885SDavid Sterba 	/*
4148319e4d06SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
4149319e4d06SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
41501104a885SDavid Sterba 	 */
4151319e4d06SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
4152319e4d06SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4153ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
415475d6ad38SDavid Sterba 		ret = -EINVAL;
415575d6ad38SDavid Sterba 	}
4156319e4d06SQu Wenruo 	/* Only PAGE SIZE is supported yet */
415709cbfeafSKirill A. Shutemov 	if (sectorsize != PAGE_SIZE) {
4158ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info,
4159ab8d0fc4SJeff Mahoney 			"sectorsize %llu not supported yet, only support %lu",
416009cbfeafSKirill A. Shutemov 			sectorsize, PAGE_SIZE);
4161319e4d06SQu Wenruo 		ret = -EINVAL;
4162319e4d06SQu Wenruo 	}
4163319e4d06SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
4164319e4d06SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
4165ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
4166319e4d06SQu Wenruo 		ret = -EINVAL;
4167319e4d06SQu Wenruo 	}
4168319e4d06SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
4169ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
4170ab8d0fc4SJeff Mahoney 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
4171319e4d06SQu Wenruo 		ret = -EINVAL;
4172319e4d06SQu Wenruo 	}
4173319e4d06SQu Wenruo 
4174319e4d06SQu Wenruo 	/* Root alignment check */
4175319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
4176ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
4177319e4d06SQu Wenruo 			   btrfs_super_root(sb));
4178319e4d06SQu Wenruo 		ret = -EINVAL;
4179319e4d06SQu Wenruo 	}
4180319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
4181ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
4182319e4d06SQu Wenruo 			   btrfs_super_chunk_root(sb));
4183319e4d06SQu Wenruo 		ret = -EINVAL;
4184319e4d06SQu Wenruo 	}
4185319e4d06SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
4186ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
4187319e4d06SQu Wenruo 			   btrfs_super_log_root(sb));
418875d6ad38SDavid Sterba 		ret = -EINVAL;
418975d6ad38SDavid Sterba 	}
419075d6ad38SDavid Sterba 
4191c926093eSDavid Sterba 	if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_UUID_SIZE) != 0) {
4192ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info,
4193ab8d0fc4SJeff Mahoney 			   "dev_item UUID does not match fsid: %pU != %pU",
4194c926093eSDavid Sterba 			   fs_info->fsid, sb->dev_item.fsid);
4195c926093eSDavid Sterba 		ret = -EINVAL;
4196c926093eSDavid Sterba 	}
4197c926093eSDavid Sterba 
4198c926093eSDavid Sterba 	/*
4199c926093eSDavid Sterba 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
4200c926093eSDavid Sterba 	 * done later
4201c926093eSDavid Sterba 	 */
420299e3ecfcSLiu Bo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
420399e3ecfcSLiu Bo 		btrfs_err(fs_info, "bytes_used is too small %llu",
420499e3ecfcSLiu Bo 			  btrfs_super_bytes_used(sb));
420599e3ecfcSLiu Bo 		ret = -EINVAL;
420699e3ecfcSLiu Bo 	}
4207b7f67055SChandan Rajendra 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
420899e3ecfcSLiu Bo 		btrfs_err(fs_info, "invalid stripesize %u",
420999e3ecfcSLiu Bo 			  btrfs_super_stripesize(sb));
421099e3ecfcSLiu Bo 		ret = -EINVAL;
421199e3ecfcSLiu Bo 	}
421221e7626bSDavid Sterba 	if (btrfs_super_num_devices(sb) > (1UL << 31))
4213ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
421421e7626bSDavid Sterba 			   btrfs_super_num_devices(sb));
421575d6ad38SDavid Sterba 	if (btrfs_super_num_devices(sb) == 0) {
4216ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "number of devices is 0");
421775d6ad38SDavid Sterba 		ret = -EINVAL;
421875d6ad38SDavid Sterba 	}
4219c926093eSDavid Sterba 
422021e7626bSDavid Sterba 	if (btrfs_super_bytenr(sb) != BTRFS_SUPER_INFO_OFFSET) {
4221ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
422221e7626bSDavid Sterba 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
4223c926093eSDavid Sterba 		ret = -EINVAL;
4224c926093eSDavid Sterba 	}
4225c926093eSDavid Sterba 
4226c926093eSDavid Sterba 	/*
4227ce7fca5fSDavid Sterba 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
4228ce7fca5fSDavid Sterba 	 * and one chunk
4229ce7fca5fSDavid Sterba 	 */
4230ce7fca5fSDavid Sterba 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4231ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "system chunk array too big %u > %u",
4232ce7fca5fSDavid Sterba 			  btrfs_super_sys_array_size(sb),
4233ce7fca5fSDavid Sterba 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
4234ce7fca5fSDavid Sterba 		ret = -EINVAL;
4235ce7fca5fSDavid Sterba 	}
4236ce7fca5fSDavid Sterba 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
4237ce7fca5fSDavid Sterba 			+ sizeof(struct btrfs_chunk)) {
4238ab8d0fc4SJeff Mahoney 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
4239ce7fca5fSDavid Sterba 			  btrfs_super_sys_array_size(sb),
4240ce7fca5fSDavid Sterba 			  sizeof(struct btrfs_disk_key)
4241ce7fca5fSDavid Sterba 			  + sizeof(struct btrfs_chunk));
4242ce7fca5fSDavid Sterba 		ret = -EINVAL;
4243ce7fca5fSDavid Sterba 	}
4244ce7fca5fSDavid Sterba 
4245ce7fca5fSDavid Sterba 	/*
4246c926093eSDavid Sterba 	 * The generation is a global counter, we'll trust it more than the others
4247c926093eSDavid Sterba 	 * but it's still possible that it's the one that's wrong.
4248c926093eSDavid Sterba 	 */
424921e7626bSDavid Sterba 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
4250ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info,
4251ab8d0fc4SJeff Mahoney 			"suspicious: generation < chunk_root_generation: %llu < %llu",
4252ab8d0fc4SJeff Mahoney 			btrfs_super_generation(sb),
4253ab8d0fc4SJeff Mahoney 			btrfs_super_chunk_root_generation(sb));
425421e7626bSDavid Sterba 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
425521e7626bSDavid Sterba 	    && btrfs_super_cache_generation(sb) != (u64)-1)
4256ab8d0fc4SJeff Mahoney 		btrfs_warn(fs_info,
4257ab8d0fc4SJeff Mahoney 			"suspicious: generation < cache_generation: %llu < %llu",
4258ab8d0fc4SJeff Mahoney 			btrfs_super_generation(sb),
4259ab8d0fc4SJeff Mahoney 			btrfs_super_cache_generation(sb));
4260c926093eSDavid Sterba 
4261c926093eSDavid Sterba 	return ret;
4262fcd1f065SDavid Sterba }
4263fcd1f065SDavid Sterba 
42642ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4265acce952bSliubo {
42660b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
42672ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
42680b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4269acce952bSliubo 
42700b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
42710b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4272acce952bSliubo 
4273acce952bSliubo 	/* cleanup FS via transaction */
42742ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
4275acce952bSliubo }
4276acce952bSliubo 
4277143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4278acce952bSliubo {
4279acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4280acce952bSliubo 
4281199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4282779880efSJosef Bacik 	/*
4283779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4284779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4285779880efSJosef Bacik 	 */
4286199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4287779880efSJosef Bacik 			    root_extent_list)
4288779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4289199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4290199c2a9cSMiao Xie }
4291199c2a9cSMiao Xie 
4292199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4293199c2a9cSMiao Xie {
4294199c2a9cSMiao Xie 	struct btrfs_root *root;
4295199c2a9cSMiao Xie 	struct list_head splice;
4296199c2a9cSMiao Xie 
4297199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4298199c2a9cSMiao Xie 
4299199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4300199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4301199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4302199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4303199c2a9cSMiao Xie 					ordered_root);
43041de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
43051de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4306199c2a9cSMiao Xie 
43072a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4308199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4309199c2a9cSMiao Xie 
43102a85d9caSLiu Bo 		cond_resched();
43112a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4312199c2a9cSMiao Xie 	}
4313199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
4314acce952bSliubo }
4315acce952bSliubo 
431635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
43172ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4318acce952bSliubo {
4319acce952bSliubo 	struct rb_node *node;
4320acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4321acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4322acce952bSliubo 	int ret = 0;
4323acce952bSliubo 
4324acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4325acce952bSliubo 
4326acce952bSliubo 	spin_lock(&delayed_refs->lock);
4327d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4328cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
43290b246afaSJeff Mahoney 		btrfs_info(fs_info, "delayed_refs has NO entry");
4330acce952bSliubo 		return ret;
4331acce952bSliubo 	}
4332acce952bSliubo 
4333d7df2c79SJosef Bacik 	while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4334d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
4335c6fc2454SQu Wenruo 		struct btrfs_delayed_ref_node *tmp;
4336e78417d1SJosef Bacik 		bool pin_bytes = false;
4337acce952bSliubo 
4338d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4339d7df2c79SJosef Bacik 				href_node);
4340b939d1abSJosef Bacik 		if (!mutex_trylock(&head->mutex)) {
4341d7df2c79SJosef Bacik 			atomic_inc(&head->node.refs);
434279787eaaSJeff Mahoney 			spin_unlock(&delayed_refs->lock);
4343b939d1abSJosef Bacik 
4344acce952bSliubo 			mutex_lock(&head->mutex);
4345b939d1abSJosef Bacik 			mutex_unlock(&head->mutex);
4346d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(&head->node);
4347e18fca73SJosef Bacik 			spin_lock(&delayed_refs->lock);
4348b939d1abSJosef Bacik 			continue;
4349b939d1abSJosef Bacik 		}
4350d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4351c6fc2454SQu Wenruo 		list_for_each_entry_safe_reverse(ref, tmp, &head->ref_list,
4352c6fc2454SQu Wenruo 						 list) {
4353d7df2c79SJosef Bacik 			ref->in_tree = 0;
4354c6fc2454SQu Wenruo 			list_del(&ref->list);
43551d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
43561d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4357d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4358d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4359d7df2c79SJosef Bacik 		}
436054067ae9SJosef Bacik 		if (head->must_insert_reserved)
4361e78417d1SJosef Bacik 			pin_bytes = true;
436278a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4363acce952bSliubo 		delayed_refs->num_heads--;
4364d7df2c79SJosef Bacik 		if (head->processing == 0)
4365acce952bSliubo 			delayed_refs->num_heads_ready--;
4366d7df2c79SJosef Bacik 		atomic_dec(&delayed_refs->num_entries);
4367d7df2c79SJosef Bacik 		head->node.in_tree = 0;
4368c46effa6SLiu Bo 		rb_erase(&head->href_node, &delayed_refs->href_root);
4369d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4370acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4371e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4372acce952bSliubo 
4373d7df2c79SJosef Bacik 		if (pin_bytes)
43742ff7e61eSJeff Mahoney 			btrfs_pin_extent(fs_info, head->node.bytenr,
4375d7df2c79SJosef Bacik 					 head->node.num_bytes, 1);
4376d7df2c79SJosef Bacik 		btrfs_put_delayed_ref(&head->node);
4377acce952bSliubo 		cond_resched();
4378acce952bSliubo 		spin_lock(&delayed_refs->lock);
4379acce952bSliubo 	}
4380acce952bSliubo 
4381acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4382acce952bSliubo 
4383acce952bSliubo 	return ret;
4384acce952bSliubo }
4385acce952bSliubo 
4386143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4387acce952bSliubo {
4388acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4389acce952bSliubo 	struct list_head splice;
4390acce952bSliubo 
4391acce952bSliubo 	INIT_LIST_HEAD(&splice);
4392acce952bSliubo 
4393eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4394eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4395acce952bSliubo 
4396acce952bSliubo 	while (!list_empty(&splice)) {
4397eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4398acce952bSliubo 					       delalloc_inodes);
4399acce952bSliubo 
4400acce952bSliubo 		list_del_init(&btrfs_inode->delalloc_inodes);
4401df0af1a5SMiao Xie 		clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
4402df0af1a5SMiao Xie 			  &btrfs_inode->runtime_flags);
4403eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4404acce952bSliubo 
4405acce952bSliubo 		btrfs_invalidate_inodes(btrfs_inode->root);
4406b216cbfbSMiao Xie 
4407eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4408acce952bSliubo 	}
4409acce952bSliubo 
4410eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4411eb73c1b7SMiao Xie }
4412eb73c1b7SMiao Xie 
4413eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4414eb73c1b7SMiao Xie {
4415eb73c1b7SMiao Xie 	struct btrfs_root *root;
4416eb73c1b7SMiao Xie 	struct list_head splice;
4417eb73c1b7SMiao Xie 
4418eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4419eb73c1b7SMiao Xie 
4420eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4421eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4422eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4423eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4424eb73c1b7SMiao Xie 					 delalloc_root);
4425eb73c1b7SMiao Xie 		list_del_init(&root->delalloc_root);
4426eb73c1b7SMiao Xie 		root = btrfs_grab_fs_root(root);
4427eb73c1b7SMiao Xie 		BUG_ON(!root);
4428eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4429eb73c1b7SMiao Xie 
4430eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
4431eb73c1b7SMiao Xie 		btrfs_put_fs_root(root);
4432eb73c1b7SMiao Xie 
4433eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4434eb73c1b7SMiao Xie 	}
4435eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4436acce952bSliubo }
4437acce952bSliubo 
44382ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4439acce952bSliubo 					struct extent_io_tree *dirty_pages,
4440acce952bSliubo 					int mark)
4441acce952bSliubo {
4442acce952bSliubo 	int ret;
4443acce952bSliubo 	struct extent_buffer *eb;
4444acce952bSliubo 	u64 start = 0;
4445acce952bSliubo 	u64 end;
4446acce952bSliubo 
4447acce952bSliubo 	while (1) {
4448acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4449e6138876SJosef Bacik 					    mark, NULL);
4450acce952bSliubo 		if (ret)
4451acce952bSliubo 			break;
4452acce952bSliubo 
445391166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4454acce952bSliubo 		while (start <= end) {
44550b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
44560b246afaSJeff Mahoney 			start += fs_info->nodesize;
4457fd8b2b61SJosef Bacik 			if (!eb)
4458acce952bSliubo 				continue;
4459fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4460acce952bSliubo 
4461fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4462fd8b2b61SJosef Bacik 					       &eb->bflags))
4463fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4464fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4465acce952bSliubo 		}
4466acce952bSliubo 	}
4467acce952bSliubo 
4468acce952bSliubo 	return ret;
4469acce952bSliubo }
4470acce952bSliubo 
44712ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4472acce952bSliubo 				       struct extent_io_tree *pinned_extents)
4473acce952bSliubo {
4474acce952bSliubo 	struct extent_io_tree *unpin;
4475acce952bSliubo 	u64 start;
4476acce952bSliubo 	u64 end;
4477acce952bSliubo 	int ret;
4478ed0eaa14SLiu Bo 	bool loop = true;
4479acce952bSliubo 
4480acce952bSliubo 	unpin = pinned_extents;
4481ed0eaa14SLiu Bo again:
4482acce952bSliubo 	while (1) {
4483acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
4484e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
4485acce952bSliubo 		if (ret)
4486acce952bSliubo 			break;
4487acce952bSliubo 
4488af6f8f60SDavid Sterba 		clear_extent_dirty(unpin, start, end);
44892ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4490acce952bSliubo 		cond_resched();
4491acce952bSliubo 	}
4492acce952bSliubo 
4493ed0eaa14SLiu Bo 	if (loop) {
44940b246afaSJeff Mahoney 		if (unpin == &fs_info->freed_extents[0])
44950b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[1];
4496ed0eaa14SLiu Bo 		else
44970b246afaSJeff Mahoney 			unpin = &fs_info->freed_extents[0];
4498ed0eaa14SLiu Bo 		loop = false;
4499ed0eaa14SLiu Bo 		goto again;
4500ed0eaa14SLiu Bo 	}
4501ed0eaa14SLiu Bo 
4502acce952bSliubo 	return 0;
4503acce952bSliubo }
4504acce952bSliubo 
4505c79a1751SLiu Bo static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4506c79a1751SLiu Bo {
4507c79a1751SLiu Bo 	struct inode *inode;
4508c79a1751SLiu Bo 
4509c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4510c79a1751SLiu Bo 	if (inode) {
4511c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4512c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4513c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4514c79a1751SLiu Bo 		iput(inode);
4515c79a1751SLiu Bo 	}
4516c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4517c79a1751SLiu Bo }
4518c79a1751SLiu Bo 
4519c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
45202ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4521c79a1751SLiu Bo {
4522c79a1751SLiu Bo 	struct btrfs_block_group_cache *cache;
4523c79a1751SLiu Bo 
4524c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4525c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4526c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
4527c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4528c79a1751SLiu Bo 					 dirty_list);
4529c79a1751SLiu Bo 		if (!cache) {
45300b246afaSJeff Mahoney 			btrfs_err(fs_info, "orphan block group dirty_bgs list");
4531c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4532c79a1751SLiu Bo 			return;
4533c79a1751SLiu Bo 		}
4534c79a1751SLiu Bo 
4535c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4536c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4537c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4538c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4539c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4540c79a1751SLiu Bo 		}
4541c79a1751SLiu Bo 
4542c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4543c79a1751SLiu Bo 		spin_lock(&cache->lock);
4544c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4545c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4546c79a1751SLiu Bo 
4547c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4548c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4549c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4550c79a1751SLiu Bo 	}
4551c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4552c79a1751SLiu Bo 
4553c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4554c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
4555c79a1751SLiu Bo 					 struct btrfs_block_group_cache,
4556c79a1751SLiu Bo 					 io_list);
4557c79a1751SLiu Bo 		if (!cache) {
45580b246afaSJeff Mahoney 			btrfs_err(fs_info, "orphan block group on io_bgs list");
4559c79a1751SLiu Bo 			return;
4560c79a1751SLiu Bo 		}
4561c79a1751SLiu Bo 
4562c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4563c79a1751SLiu Bo 		spin_lock(&cache->lock);
4564c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4565c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4566c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4567c79a1751SLiu Bo 	}
4568c79a1751SLiu Bo }
4569c79a1751SLiu Bo 
457049b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
45712ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
457249b25e05SJeff Mahoney {
45732ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4574c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4575c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4576c79a1751SLiu Bo 
45772ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
457849b25e05SJeff Mahoney 
45794a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
45800b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
458149b25e05SJeff Mahoney 
45824a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
45830b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
458449b25e05SJeff Mahoney 
4585ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4586ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
458767cde344SMiao Xie 
45882ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
458949b25e05SJeff Mahoney 				     EXTENT_DIRTY);
45902ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info,
45910b246afaSJeff Mahoney 				    fs_info->pinned_extents);
459249b25e05SJeff Mahoney 
45934a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
45944a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
45954a9d8bdeSMiao Xie 
459649b25e05SJeff Mahoney 	/*
459749b25e05SJeff Mahoney 	memset(cur_trans, 0, sizeof(*cur_trans));
459849b25e05SJeff Mahoney 	kmem_cache_free(btrfs_transaction_cachep, cur_trans);
459949b25e05SJeff Mahoney 	*/
460049b25e05SJeff Mahoney }
460149b25e05SJeff Mahoney 
46022ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4603acce952bSliubo {
4604acce952bSliubo 	struct btrfs_transaction *t;
4605acce952bSliubo 
46060b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4607acce952bSliubo 
46080b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
46090b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
46100b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4611724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4612724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
4613724e2315SJosef Bacik 			atomic_inc(&t->use_count);
46140b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
46152ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4616724e2315SJosef Bacik 			btrfs_put_transaction(t);
46170b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4618724e2315SJosef Bacik 			continue;
4619724e2315SJosef Bacik 		}
46200b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4621724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
46220b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4623724e2315SJosef Bacik 			/*
4624724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4625724e2315SJosef Bacik 			 * handle open currently for this transaction.
4626724e2315SJosef Bacik 			 */
4627724e2315SJosef Bacik 			wait_event(t->writer_wait,
4628724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4629724e2315SJosef Bacik 		} else {
46300b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4631724e2315SJosef Bacik 		}
46322ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4633724e2315SJosef Bacik 
46340b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
46350b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
46360b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4637724e2315SJosef Bacik 		list_del_init(&t->list);
46380b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4639a4abeea4SJosef Bacik 
4640724e2315SJosef Bacik 		btrfs_put_transaction(t);
46412ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
46420b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4643724e2315SJosef Bacik 	}
46440b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
46450b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4646ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4647ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
46482ff7e61eSJeff Mahoney 	btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
46490b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
46500b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4651acce952bSliubo 
4652acce952bSliubo 	return 0;
4653acce952bSliubo }
4654acce952bSliubo 
4655e8c9f186SDavid Sterba static const struct extent_io_ops btree_extent_io_ops = {
4656ce9adaa5SChris Mason 	.readpage_end_io_hook = btree_readpage_end_io_hook,
46574bb31e92SArne Jansen 	.readpage_io_failed_hook = btree_io_failed_hook,
46580b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
4659239b14b3SChris Mason 	/* note we're sharing with inode.c for the merge bio hook */
4660239b14b3SChris Mason 	.merge_bio_hook = btrfs_merge_bio_hook,
46610da5468fSChris Mason };
4662