xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 29549aec)
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>
28a74a4b97SChris Mason #include <linux/freezer.h>
295a0e3ad6STejun Heo #include <linux/slab.h>
30784b4e29SChris Mason #include <linux/migrate.h>
317a36ddecSDavid Sterba #include <linux/ratelimit.h>
326463fe58SStefan Behrens #include <linux/uuid.h>
33803b2f54SStefan Behrens #include <linux/semaphore.h>
347e75bf3fSDavid Sterba #include <asm/unaligned.h>
35eb60ceacSChris Mason #include "ctree.h"
36eb60ceacSChris Mason #include "disk-io.h"
370b947affSFilipe David Borba Manana #include "hash.h"
38e089f05cSChris Mason #include "transaction.h"
390f7d52f4SChris Mason #include "btrfs_inode.h"
400b86a832SChris Mason #include "volumes.h"
41db94535dSChris Mason #include "print-tree.h"
42925baeddSChris Mason #include "locking.h"
43e02119d5SChris Mason #include "tree-log.h"
44fa9c0d79SChris Mason #include "free-space-cache.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"
52eb60ceacSChris Mason 
53de0022b9SJosef Bacik #ifdef CONFIG_X86
54de0022b9SJosef Bacik #include <asm/cpufeature.h>
55de0022b9SJosef Bacik #endif
56de0022b9SJosef Bacik 
57d1310b2eSChris Mason static struct extent_io_ops btree_extent_io_ops;
588b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
594df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root);
60fcd1f065SDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
61acce952bSliubo 				    int read_only);
62143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
63acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
64acce952bSliubo 				      struct btrfs_root *root);
65143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
66acce952bSliubo static int btrfs_destroy_marked_extents(struct btrfs_root *root,
67acce952bSliubo 					struct extent_io_tree *dirty_pages,
68acce952bSliubo 					int mark);
69acce952bSliubo static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
70acce952bSliubo 				       struct extent_io_tree *pinned_extents);
7148a3b636SEric Sandeen static int btrfs_cleanup_transaction(struct btrfs_root *root);
7248a3b636SEric Sandeen static void btrfs_error_commit_super(struct btrfs_root *root);
73ce9adaa5SChris Mason 
74d352ac68SChris Mason /*
75d352ac68SChris Mason  * end_io_wq structs are used to do processing in task context when an IO is
76d352ac68SChris Mason  * complete.  This is used during reads to verify checksums, and it is used
77d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
78d352ac68SChris Mason  */
79ce9adaa5SChris Mason struct end_io_wq {
80ce9adaa5SChris Mason 	struct bio *bio;
81ce9adaa5SChris Mason 	bio_end_io_t *end_io;
82ce9adaa5SChris Mason 	void *private;
83ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
84ce9adaa5SChris Mason 	int error;
8522c59948SChris Mason 	int metadata;
86ce9adaa5SChris Mason 	struct list_head list;
878b712842SChris Mason 	struct btrfs_work work;
88ce9adaa5SChris Mason };
890da5468fSChris Mason 
90d352ac68SChris Mason /*
91d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
92d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
93d352ac68SChris Mason  * just before they are sent down the IO stack.
94d352ac68SChris Mason  */
9544b8bd7eSChris Mason struct async_submit_bio {
9644b8bd7eSChris Mason 	struct inode *inode;
9744b8bd7eSChris Mason 	struct bio *bio;
9844b8bd7eSChris Mason 	struct list_head list;
994a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_start;
1004a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_done;
10144b8bd7eSChris Mason 	int rw;
10244b8bd7eSChris Mason 	int mirror_num;
103c8b97818SChris Mason 	unsigned long bio_flags;
104eaf25d93SChris Mason 	/*
105eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
106eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
107eaf25d93SChris Mason 	 */
108eaf25d93SChris Mason 	u64 bio_offset;
1098b712842SChris Mason 	struct btrfs_work work;
11079787eaaSJeff Mahoney 	int error;
11144b8bd7eSChris Mason };
11244b8bd7eSChris Mason 
11385d4e461SChris Mason /*
11485d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
11585d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
11685d4e461SChris Mason  * the level the eb occupies in the tree.
1174008c04aSChris Mason  *
11885d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
11985d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
12085d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
12185d4e461SChris Mason  * by btrfs_root->objectid.  This ensures that all special purpose roots
12285d4e461SChris Mason  * have separate keysets.
1234008c04aSChris Mason  *
12485d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
12585d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
12685d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1274008c04aSChris Mason  *
12885d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
12985d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
13085d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
13185d4e461SChris Mason  *
13285d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
13385d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
13485d4e461SChris Mason  * needs update as well.
1354008c04aSChris Mason  */
1364008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1374008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1384008c04aSChris Mason #  error
1394008c04aSChris Mason # endif
14085d4e461SChris Mason 
14185d4e461SChris Mason static struct btrfs_lockdep_keyset {
14285d4e461SChris Mason 	u64			id;		/* root objectid */
14385d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
14485d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
14585d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
14685d4e461SChris Mason } btrfs_lockdep_keysets[] = {
14785d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
14885d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
14985d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
15085d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
15185d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
15285d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
15360b62978SDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	.name_stem = "quota"	},
15485d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
15585d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
15685d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
15713fd8da9SDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	.name_stem = "uuid"	},
15885d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1594008c04aSChris Mason };
16085d4e461SChris Mason 
16185d4e461SChris Mason void __init btrfs_init_lockdep(void)
16285d4e461SChris Mason {
16385d4e461SChris Mason 	int i, j;
16485d4e461SChris Mason 
16585d4e461SChris Mason 	/* initialize lockdep class names */
16685d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
16785d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
16885d4e461SChris Mason 
16985d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
17085d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
17185d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
17285d4e461SChris Mason 	}
17385d4e461SChris Mason }
17485d4e461SChris Mason 
17585d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
17685d4e461SChris Mason 				    int level)
17785d4e461SChris Mason {
17885d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
17985d4e461SChris Mason 
18085d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
18185d4e461SChris Mason 
18285d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
18385d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
18485d4e461SChris Mason 		if (ks->id == objectid)
18585d4e461SChris Mason 			break;
18685d4e461SChris Mason 
18785d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
18885d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
18985d4e461SChris Mason }
19085d4e461SChris Mason 
1914008c04aSChris Mason #endif
1924008c04aSChris Mason 
193d352ac68SChris Mason /*
194d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
195d352ac68SChris Mason  * that covers the entire device
196d352ac68SChris Mason  */
197b2950863SChristoph Hellwig static struct extent_map *btree_get_extent(struct inode *inode,
198306e16ceSDavid Sterba 		struct page *page, size_t pg_offset, u64 start, u64 len,
1995f39d397SChris Mason 		int create)
2005f39d397SChris Mason {
2015f39d397SChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
2025f39d397SChris Mason 	struct extent_map *em;
2035f39d397SChris Mason 	int ret;
2045f39d397SChris Mason 
205890871beSChris Mason 	read_lock(&em_tree->lock);
206d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
207a061fc8dSChris Mason 	if (em) {
208a061fc8dSChris Mason 		em->bdev =
209a061fc8dSChris Mason 			BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
210890871beSChris Mason 		read_unlock(&em_tree->lock);
2115f39d397SChris Mason 		goto out;
212a061fc8dSChris Mason 	}
213890871beSChris Mason 	read_unlock(&em_tree->lock);
2147b13b7b1SChris Mason 
215172ddd60SDavid Sterba 	em = alloc_extent_map();
2165f39d397SChris Mason 	if (!em) {
2175f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2185f39d397SChris Mason 		goto out;
2195f39d397SChris Mason 	}
2205f39d397SChris Mason 	em->start = 0;
2210afbaf8cSChris Mason 	em->len = (u64)-1;
222c8b97818SChris Mason 	em->block_len = (u64)-1;
2235f39d397SChris Mason 	em->block_start = 0;
224a061fc8dSChris Mason 	em->bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
225d1310b2eSChris Mason 
226890871beSChris Mason 	write_lock(&em_tree->lock);
22709a2a8f9SJosef Bacik 	ret = add_extent_mapping(em_tree, em, 0);
2285f39d397SChris Mason 	if (ret == -EEXIST) {
2295f39d397SChris Mason 		free_extent_map(em);
2307b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
231b4f359abSTsutomu Itoh 		if (!em)
2320433f20dSTsutomu Itoh 			em = ERR_PTR(-EIO);
2335f39d397SChris Mason 	} else if (ret) {
2347b13b7b1SChris Mason 		free_extent_map(em);
2350433f20dSTsutomu Itoh 		em = ERR_PTR(ret);
2365f39d397SChris Mason 	}
237890871beSChris Mason 	write_unlock(&em_tree->lock);
2387b13b7b1SChris Mason 
2395f39d397SChris Mason out:
2405f39d397SChris Mason 	return em;
2415f39d397SChris Mason }
2425f39d397SChris Mason 
243b0496686SLiu Bo u32 btrfs_csum_data(char *data, u32 seed, size_t len)
24419c00ddcSChris Mason {
2450b947affSFilipe David Borba Manana 	return btrfs_crc32c(seed, data, len);
24619c00ddcSChris Mason }
24719c00ddcSChris Mason 
24819c00ddcSChris Mason void btrfs_csum_final(u32 crc, char *result)
24919c00ddcSChris Mason {
2507e75bf3fSDavid Sterba 	put_unaligned_le32(~crc, result);
25119c00ddcSChris Mason }
25219c00ddcSChris Mason 
253d352ac68SChris Mason /*
254d352ac68SChris Mason  * compute the csum for a btree block, and either verify it or write it
255d352ac68SChris Mason  * into the csum field of the block.
256d352ac68SChris Mason  */
25719c00ddcSChris Mason static int csum_tree_block(struct btrfs_root *root, struct extent_buffer *buf,
25819c00ddcSChris Mason 			   int verify)
25919c00ddcSChris Mason {
2606c41761fSDavid Sterba 	u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
261607d432dSJosef Bacik 	char *result = NULL;
26219c00ddcSChris Mason 	unsigned long len;
26319c00ddcSChris Mason 	unsigned long cur_len;
26419c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
26519c00ddcSChris Mason 	char *kaddr;
26619c00ddcSChris Mason 	unsigned long map_start;
26719c00ddcSChris Mason 	unsigned long map_len;
26819c00ddcSChris Mason 	int err;
26919c00ddcSChris Mason 	u32 crc = ~(u32)0;
270607d432dSJosef Bacik 	unsigned long inline_result;
27119c00ddcSChris Mason 
27219c00ddcSChris Mason 	len = buf->len - offset;
27319c00ddcSChris Mason 	while (len > 0) {
27419c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
275a6591715SChris Mason 					&kaddr, &map_start, &map_len);
276d397712bSChris Mason 		if (err)
27719c00ddcSChris Mason 			return 1;
27819c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
279b0496686SLiu Bo 		crc = btrfs_csum_data(kaddr + offset - map_start,
28019c00ddcSChris Mason 				      crc, cur_len);
28119c00ddcSChris Mason 		len -= cur_len;
28219c00ddcSChris Mason 		offset += cur_len;
28319c00ddcSChris Mason 	}
284607d432dSJosef Bacik 	if (csum_size > sizeof(inline_result)) {
285607d432dSJosef Bacik 		result = kzalloc(csum_size * sizeof(char), GFP_NOFS);
286607d432dSJosef Bacik 		if (!result)
287607d432dSJosef Bacik 			return 1;
288607d432dSJosef Bacik 	} else {
289607d432dSJosef Bacik 		result = (char *)&inline_result;
290607d432dSJosef Bacik 	}
291607d432dSJosef Bacik 
29219c00ddcSChris Mason 	btrfs_csum_final(crc, result);
29319c00ddcSChris Mason 
29419c00ddcSChris Mason 	if (verify) {
295607d432dSJosef Bacik 		if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
296e4204dedSChris Mason 			u32 val;
297e4204dedSChris Mason 			u32 found = 0;
298607d432dSJosef Bacik 			memcpy(&found, result, csum_size);
299e4204dedSChris Mason 
300607d432dSJosef Bacik 			read_extent_buffer(buf, &val, 0, csum_size);
301efe120a0SFrank Holton 			printk_ratelimited(KERN_INFO
302efe120a0SFrank Holton 				"BTRFS: %s checksum verify failed on %llu wanted %X found %X "
303193f284dSChris Mason 				"level %d\n",
304c1c9ff7cSGeert Uytterhoeven 				root->fs_info->sb->s_id, buf->start,
305c1c9ff7cSGeert Uytterhoeven 				val, found, btrfs_header_level(buf));
306607d432dSJosef Bacik 			if (result != (char *)&inline_result)
307607d432dSJosef Bacik 				kfree(result);
30819c00ddcSChris Mason 			return 1;
30919c00ddcSChris Mason 		}
31019c00ddcSChris Mason 	} else {
311607d432dSJosef Bacik 		write_extent_buffer(buf, result, 0, csum_size);
31219c00ddcSChris Mason 	}
313607d432dSJosef Bacik 	if (result != (char *)&inline_result)
314607d432dSJosef Bacik 		kfree(result);
31519c00ddcSChris Mason 	return 0;
31619c00ddcSChris Mason }
31719c00ddcSChris Mason 
318d352ac68SChris Mason /*
319d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
320d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
321d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
322d352ac68SChris Mason  * in the wrong place.
323d352ac68SChris Mason  */
3241259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
325b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
326b9fab919SChris Mason 				 int atomic)
3271259ab75SChris Mason {
3282ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3291259ab75SChris Mason 	int ret;
330a26e8c9fSJosef Bacik 	bool need_lock = (current->journal_info ==
331a26e8c9fSJosef Bacik 			  (void *)BTRFS_SEND_TRANS_STUB);
3321259ab75SChris Mason 
3331259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
3341259ab75SChris Mason 		return 0;
3351259ab75SChris Mason 
336b9fab919SChris Mason 	if (atomic)
337b9fab919SChris Mason 		return -EAGAIN;
338b9fab919SChris Mason 
339a26e8c9fSJosef Bacik 	if (need_lock) {
340a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
341a26e8c9fSJosef Bacik 		btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
342a26e8c9fSJosef Bacik 	}
343a26e8c9fSJosef Bacik 
3442ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
345d0082371SJeff Mahoney 			 0, &cached_state);
3460b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3471259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3481259ab75SChris Mason 		ret = 0;
3491259ab75SChris Mason 		goto out;
3501259ab75SChris Mason 	}
35129549aecSWang Shilong 	printk_ratelimited(KERN_INFO "BTRFS (device %s): parent transid verify failed on %llu wanted %llu found %llu\n",
35229549aecSWang Shilong 			eb->fs_info->sb->s_id, eb->start,
35329549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
3541259ab75SChris Mason 	ret = 1;
355a26e8c9fSJosef Bacik 
356a26e8c9fSJosef Bacik 	/*
357a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
358a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
359a26e8c9fSJosef Bacik 	 * block that has been free'd and re-allocated.  So don't clear uptodate
360a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
361a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
362a26e8c9fSJosef Bacik 	 * making everybody very sad.
363a26e8c9fSJosef Bacik 	 */
364a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
3650b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
36633958dc6SChris Mason out:
3672ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
3682ac55d41SJosef Bacik 			     &cached_state, GFP_NOFS);
369472b909fSJosef Bacik 	if (need_lock)
370a26e8c9fSJosef Bacik 		btrfs_tree_read_unlock_blocking(eb);
3711259ab75SChris Mason 	return ret;
3721259ab75SChris Mason }
3731259ab75SChris Mason 
374d352ac68SChris Mason /*
3751104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3761104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3771104a885SDavid Sterba  */
3781104a885SDavid Sterba static int btrfs_check_super_csum(char *raw_disk_sb)
3791104a885SDavid Sterba {
3801104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3811104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
3821104a885SDavid Sterba 	u16 csum_type = btrfs_super_csum_type(disk_sb);
3831104a885SDavid Sterba 	int ret = 0;
3841104a885SDavid Sterba 
3851104a885SDavid Sterba 	if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
3861104a885SDavid Sterba 		u32 crc = ~(u32)0;
3871104a885SDavid Sterba 		const int csum_size = sizeof(crc);
3881104a885SDavid Sterba 		char result[csum_size];
3891104a885SDavid Sterba 
3901104a885SDavid Sterba 		/*
3911104a885SDavid Sterba 		 * The super_block structure does not span the whole
3921104a885SDavid Sterba 		 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
3931104a885SDavid Sterba 		 * is filled with zeros and is included in the checkum.
3941104a885SDavid Sterba 		 */
3951104a885SDavid Sterba 		crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
3961104a885SDavid Sterba 				crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3971104a885SDavid Sterba 		btrfs_csum_final(crc, result);
3981104a885SDavid Sterba 
3991104a885SDavid Sterba 		if (memcmp(raw_disk_sb, result, csum_size))
4001104a885SDavid Sterba 			ret = 1;
401667e7d94SChris Mason 
402667e7d94SChris Mason 		if (ret && btrfs_super_generation(disk_sb) < 10) {
403efe120a0SFrank Holton 			printk(KERN_WARNING
404efe120a0SFrank Holton 				"BTRFS: super block crcs don't match, older mkfs detected\n");
405667e7d94SChris Mason 			ret = 0;
406667e7d94SChris Mason 		}
4071104a885SDavid Sterba 	}
4081104a885SDavid Sterba 
4091104a885SDavid Sterba 	if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
410efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: unsupported checksum algorithm %u\n",
4111104a885SDavid Sterba 				csum_type);
4121104a885SDavid Sterba 		ret = 1;
4131104a885SDavid Sterba 	}
4141104a885SDavid Sterba 
4151104a885SDavid Sterba 	return ret;
4161104a885SDavid Sterba }
4171104a885SDavid Sterba 
4181104a885SDavid Sterba /*
419d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
420d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
421d352ac68SChris Mason  */
422f188591eSChris Mason static int btree_read_extent_buffer_pages(struct btrfs_root *root,
423f188591eSChris Mason 					  struct extent_buffer *eb,
424ca7a79adSChris Mason 					  u64 start, u64 parent_transid)
425f188591eSChris Mason {
426f188591eSChris Mason 	struct extent_io_tree *io_tree;
427ea466794SJosef Bacik 	int failed = 0;
428f188591eSChris Mason 	int ret;
429f188591eSChris Mason 	int num_copies = 0;
430f188591eSChris Mason 	int mirror_num = 0;
431ea466794SJosef Bacik 	int failed_mirror = 0;
432f188591eSChris Mason 
433a826d6dcSJosef Bacik 	clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
434f188591eSChris Mason 	io_tree = &BTRFS_I(root->fs_info->btree_inode)->io_tree;
435f188591eSChris Mason 	while (1) {
436bb82ab88SArne Jansen 		ret = read_extent_buffer_pages(io_tree, eb, start,
437bb82ab88SArne Jansen 					       WAIT_COMPLETE,
438f188591eSChris Mason 					       btree_get_extent, mirror_num);
439256dd1bbSStefan Behrens 		if (!ret) {
440256dd1bbSStefan Behrens 			if (!verify_parent_transid(io_tree, eb,
441b9fab919SChris Mason 						   parent_transid, 0))
442ea466794SJosef Bacik 				break;
443256dd1bbSStefan Behrens 			else
444256dd1bbSStefan Behrens 				ret = -EIO;
445256dd1bbSStefan Behrens 		}
446d397712bSChris Mason 
447a826d6dcSJosef Bacik 		/*
448a826d6dcSJosef Bacik 		 * This buffer's crc is fine, but its contents are corrupted, so
449a826d6dcSJosef Bacik 		 * there is no reason to read the other copies, they won't be
450a826d6dcSJosef Bacik 		 * any less wrong.
451a826d6dcSJosef Bacik 		 */
452a826d6dcSJosef Bacik 		if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
453ea466794SJosef Bacik 			break;
454ea466794SJosef Bacik 
4555d964051SStefan Behrens 		num_copies = btrfs_num_copies(root->fs_info,
456f188591eSChris Mason 					      eb->start, eb->len);
4574235298eSChris Mason 		if (num_copies == 1)
458ea466794SJosef Bacik 			break;
4594235298eSChris Mason 
4605cf1ab56SJosef Bacik 		if (!failed_mirror) {
4615cf1ab56SJosef Bacik 			failed = 1;
4625cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4635cf1ab56SJosef Bacik 		}
4645cf1ab56SJosef Bacik 
465f188591eSChris Mason 		mirror_num++;
466ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
467ea466794SJosef Bacik 			mirror_num++;
468ea466794SJosef Bacik 
4694235298eSChris Mason 		if (mirror_num > num_copies)
470ea466794SJosef Bacik 			break;
471f188591eSChris Mason 	}
472ea466794SJosef Bacik 
473c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
474ea466794SJosef Bacik 		repair_eb_io_failure(root, eb, failed_mirror);
475ea466794SJosef Bacik 
476ea466794SJosef Bacik 	return ret;
477f188591eSChris Mason }
47819c00ddcSChris Mason 
479d352ac68SChris Mason /*
480d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
481d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
482d352ac68SChris Mason  */
483d397712bSChris Mason 
484b2950863SChristoph Hellwig static int csum_dirty_buffer(struct btrfs_root *root, struct page *page)
48519c00ddcSChris Mason {
4864eee4fa4SMiao Xie 	u64 start = page_offset(page);
48719c00ddcSChris Mason 	u64 found_start;
48819c00ddcSChris Mason 	struct extent_buffer *eb;
489f188591eSChris Mason 
4904f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4914f2de97aSJosef Bacik 	if (page != eb->pages[0])
4924f2de97aSJosef Bacik 		return 0;
49319c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
494fae7f21cSDulshani Gunawardhana 	if (WARN_ON(found_start != start || !PageUptodate(page)))
4954f2de97aSJosef Bacik 		return 0;
49619c00ddcSChris Mason 	csum_tree_block(root, eb, 0);
49719c00ddcSChris Mason 	return 0;
49819c00ddcSChris Mason }
49919c00ddcSChris Mason 
5002b82032cSYan Zheng static int check_tree_block_fsid(struct btrfs_root *root,
5012b82032cSYan Zheng 				 struct extent_buffer *eb)
5022b82032cSYan Zheng {
5032b82032cSYan Zheng 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
5042b82032cSYan Zheng 	u8 fsid[BTRFS_UUID_SIZE];
5052b82032cSYan Zheng 	int ret = 1;
5062b82032cSYan Zheng 
5070a4e5586SRoss Kirk 	read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
5082b82032cSYan Zheng 	while (fs_devices) {
5092b82032cSYan Zheng 		if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
5102b82032cSYan Zheng 			ret = 0;
5112b82032cSYan Zheng 			break;
5122b82032cSYan Zheng 		}
5132b82032cSYan Zheng 		fs_devices = fs_devices->seed;
5142b82032cSYan Zheng 	}
5152b82032cSYan Zheng 	return ret;
5162b82032cSYan Zheng }
5172b82032cSYan Zheng 
518a826d6dcSJosef Bacik #define CORRUPT(reason, eb, root, slot)				\
519efe120a0SFrank Holton 	btrfs_crit(root->fs_info, "corrupt leaf, %s: block=%llu,"	\
520efe120a0SFrank Holton 		   "root=%llu, slot=%d", reason,			\
521c1c9ff7cSGeert Uytterhoeven 	       btrfs_header_bytenr(eb),	root->objectid, slot)
522a826d6dcSJosef Bacik 
523a826d6dcSJosef Bacik static noinline int check_leaf(struct btrfs_root *root,
524a826d6dcSJosef Bacik 			       struct extent_buffer *leaf)
525a826d6dcSJosef Bacik {
526a826d6dcSJosef Bacik 	struct btrfs_key key;
527a826d6dcSJosef Bacik 	struct btrfs_key leaf_key;
528a826d6dcSJosef Bacik 	u32 nritems = btrfs_header_nritems(leaf);
529a826d6dcSJosef Bacik 	int slot;
530a826d6dcSJosef Bacik 
531a826d6dcSJosef Bacik 	if (nritems == 0)
532a826d6dcSJosef Bacik 		return 0;
533a826d6dcSJosef Bacik 
534a826d6dcSJosef Bacik 	/* Check the 0 item */
535a826d6dcSJosef Bacik 	if (btrfs_item_offset_nr(leaf, 0) + btrfs_item_size_nr(leaf, 0) !=
536a826d6dcSJosef Bacik 	    BTRFS_LEAF_DATA_SIZE(root)) {
537a826d6dcSJosef Bacik 		CORRUPT("invalid item offset size pair", leaf, root, 0);
538a826d6dcSJosef Bacik 		return -EIO;
539a826d6dcSJosef Bacik 	}
540a826d6dcSJosef Bacik 
541a826d6dcSJosef Bacik 	/*
542a826d6dcSJosef Bacik 	 * Check to make sure each items keys are in the correct order and their
543a826d6dcSJosef Bacik 	 * offsets make sense.  We only have to loop through nritems-1 because
544a826d6dcSJosef Bacik 	 * we check the current slot against the next slot, which verifies the
545a826d6dcSJosef Bacik 	 * next slot's offset+size makes sense and that the current's slot
546a826d6dcSJosef Bacik 	 * offset is correct.
547a826d6dcSJosef Bacik 	 */
548a826d6dcSJosef Bacik 	for (slot = 0; slot < nritems - 1; slot++) {
549a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &leaf_key, slot);
550a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &key, slot + 1);
551a826d6dcSJosef Bacik 
552a826d6dcSJosef Bacik 		/* Make sure the keys are in the right order */
553a826d6dcSJosef Bacik 		if (btrfs_comp_cpu_keys(&leaf_key, &key) >= 0) {
554a826d6dcSJosef Bacik 			CORRUPT("bad key order", leaf, root, slot);
555a826d6dcSJosef Bacik 			return -EIO;
556a826d6dcSJosef Bacik 		}
557a826d6dcSJosef Bacik 
558a826d6dcSJosef Bacik 		/*
559a826d6dcSJosef Bacik 		 * Make sure the offset and ends are right, remember that the
560a826d6dcSJosef Bacik 		 * item data starts at the end of the leaf and grows towards the
561a826d6dcSJosef Bacik 		 * front.
562a826d6dcSJosef Bacik 		 */
563a826d6dcSJosef Bacik 		if (btrfs_item_offset_nr(leaf, slot) !=
564a826d6dcSJosef Bacik 			btrfs_item_end_nr(leaf, slot + 1)) {
565a826d6dcSJosef Bacik 			CORRUPT("slot offset bad", leaf, root, slot);
566a826d6dcSJosef Bacik 			return -EIO;
567a826d6dcSJosef Bacik 		}
568a826d6dcSJosef Bacik 
569a826d6dcSJosef Bacik 		/*
570a826d6dcSJosef Bacik 		 * Check to make sure that we don't point outside of the leaf,
571a826d6dcSJosef Bacik 		 * just incase all the items are consistent to eachother, but
572a826d6dcSJosef Bacik 		 * all point outside of the leaf.
573a826d6dcSJosef Bacik 		 */
574a826d6dcSJosef Bacik 		if (btrfs_item_end_nr(leaf, slot) >
575a826d6dcSJosef Bacik 		    BTRFS_LEAF_DATA_SIZE(root)) {
576a826d6dcSJosef Bacik 			CORRUPT("slot end outside of leaf", leaf, root, slot);
577a826d6dcSJosef Bacik 			return -EIO;
578a826d6dcSJosef Bacik 		}
579a826d6dcSJosef Bacik 	}
580a826d6dcSJosef Bacik 
581a826d6dcSJosef Bacik 	return 0;
582a826d6dcSJosef Bacik }
583a826d6dcSJosef Bacik 
584facc8a22SMiao Xie static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
585facc8a22SMiao Xie 				      u64 phy_offset, struct page *page,
586facc8a22SMiao Xie 				      u64 start, u64 end, int mirror)
587ce9adaa5SChris Mason {
588ce9adaa5SChris Mason 	u64 found_start;
589ce9adaa5SChris Mason 	int found_level;
590ce9adaa5SChris Mason 	struct extent_buffer *eb;
591ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
592f188591eSChris Mason 	int ret = 0;
593727011e0SChris Mason 	int reads_done;
594ce9adaa5SChris Mason 
595ce9adaa5SChris Mason 	if (!page->private)
596ce9adaa5SChris Mason 		goto out;
597d397712bSChris Mason 
5984f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
599d397712bSChris Mason 
6000b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
6010b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
6020b32f4bbSJosef Bacik 	 */
6030b32f4bbSJosef Bacik 	extent_buffer_get(eb);
6040b32f4bbSJosef Bacik 
6050b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
606727011e0SChris Mason 	if (!reads_done)
607727011e0SChris Mason 		goto err;
608f188591eSChris Mason 
6095cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
610ea466794SJosef Bacik 	if (test_bit(EXTENT_BUFFER_IOERR, &eb->bflags)) {
611ea466794SJosef Bacik 		ret = -EIO;
612ea466794SJosef Bacik 		goto err;
613ea466794SJosef Bacik 	}
614ea466794SJosef Bacik 
615ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
616727011e0SChris Mason 	if (found_start != eb->start) {
61729549aecSWang Shilong 		printk_ratelimited(KERN_INFO "BTRFS (device %s): bad tree block start "
618193f284dSChris Mason 			       "%llu %llu\n",
61929549aecSWang Shilong 			       eb->fs_info->sb->s_id, found_start, eb->start);
620f188591eSChris Mason 		ret = -EIO;
621ce9adaa5SChris Mason 		goto err;
622ce9adaa5SChris Mason 	}
6232b82032cSYan Zheng 	if (check_tree_block_fsid(root, eb)) {
62429549aecSWang Shilong 		printk_ratelimited(KERN_INFO "BTRFS (device %s): bad fsid on block %llu\n",
62529549aecSWang Shilong 			       eb->fs_info->sb->s_id, eb->start);
6261259ab75SChris Mason 		ret = -EIO;
6271259ab75SChris Mason 		goto err;
6281259ab75SChris Mason 	}
629ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
6301c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
631efe120a0SFrank Holton 		btrfs_info(root->fs_info, "bad tree block level %d",
6321c24c3ceSJosef Bacik 			   (int)btrfs_header_level(eb));
6331c24c3ceSJosef Bacik 		ret = -EIO;
6341c24c3ceSJosef Bacik 		goto err;
6351c24c3ceSJosef Bacik 	}
636ce9adaa5SChris Mason 
63785d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
63885d4e461SChris Mason 				       eb, found_level);
6394008c04aSChris Mason 
640ce9adaa5SChris Mason 	ret = csum_tree_block(root, eb, 1);
641a826d6dcSJosef Bacik 	if (ret) {
642f188591eSChris Mason 		ret = -EIO;
643a826d6dcSJosef Bacik 		goto err;
644a826d6dcSJosef Bacik 	}
645a826d6dcSJosef Bacik 
646a826d6dcSJosef Bacik 	/*
647a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
648a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
649a826d6dcSJosef Bacik 	 * return -EIO.
650a826d6dcSJosef Bacik 	 */
651a826d6dcSJosef Bacik 	if (found_level == 0 && check_leaf(root, eb)) {
652a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
653a826d6dcSJosef Bacik 		ret = -EIO;
654a826d6dcSJosef Bacik 	}
655ce9adaa5SChris Mason 
6560b32f4bbSJosef Bacik 	if (!ret)
6570b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
658ce9adaa5SChris Mason err:
65979fb65a1SJosef Bacik 	if (reads_done &&
66079fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
6614bb31e92SArne Jansen 		btree_readahead_hook(root, eb, eb->start, ret);
6624bb31e92SArne Jansen 
66353b381b3SDavid Woodhouse 	if (ret) {
66453b381b3SDavid Woodhouse 		/*
66553b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
66653b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
66753b381b3SDavid Woodhouse 		 * to decrement
66853b381b3SDavid Woodhouse 		 */
66953b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6700b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
67153b381b3SDavid Woodhouse 	}
6720b32f4bbSJosef Bacik 	free_extent_buffer(eb);
673ce9adaa5SChris Mason out:
674f188591eSChris Mason 	return ret;
675ce9adaa5SChris Mason }
676ce9adaa5SChris Mason 
677ea466794SJosef Bacik static int btree_io_failed_hook(struct page *page, int failed_mirror)
6784bb31e92SArne Jansen {
6794bb31e92SArne Jansen 	struct extent_buffer *eb;
6804bb31e92SArne Jansen 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
6814bb31e92SArne Jansen 
6824f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
683ea466794SJosef Bacik 	set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
6845cf1ab56SJosef Bacik 	eb->read_mirror = failed_mirror;
68553b381b3SDavid Woodhouse 	atomic_dec(&eb->io_pages);
686ea466794SJosef Bacik 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
6874bb31e92SArne Jansen 		btree_readahead_hook(root, eb, eb->start, -EIO);
6884bb31e92SArne Jansen 	return -EIO;	/* we fixed nothing */
6894bb31e92SArne Jansen }
6904bb31e92SArne Jansen 
691ce9adaa5SChris Mason static void end_workqueue_bio(struct bio *bio, int err)
692ce9adaa5SChris Mason {
693ce9adaa5SChris Mason 	struct end_io_wq *end_io_wq = bio->bi_private;
694ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6959e0af237SLiu Bo 	struct btrfs_workqueue *wq;
6969e0af237SLiu Bo 	btrfs_work_func_t func;
697ce9adaa5SChris Mason 
698ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
699ce9adaa5SChris Mason 	end_io_wq->error = err;
700d20f7043SChris Mason 
7017b6d91daSChristoph Hellwig 	if (bio->bi_rw & REQ_WRITE) {
7029e0af237SLiu Bo 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
7039e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
7049e0af237SLiu Bo 			func = btrfs_endio_meta_write_helper;
7059e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
7069e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
7079e0af237SLiu Bo 			func = btrfs_freespace_write_helper;
7089e0af237SLiu Bo 		} else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7099e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7109e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
711d20f7043SChris Mason 		} else {
7129e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7139e0af237SLiu Bo 			func = btrfs_endio_write_helper;
714d20f7043SChris Mason 		}
7159e0af237SLiu Bo 	} else {
7169e0af237SLiu Bo 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
7179e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
7189e0af237SLiu Bo 			func = btrfs_endio_raid56_helper;
7199e0af237SLiu Bo 		} else if (end_io_wq->metadata) {
7209e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
7219e0af237SLiu Bo 			func = btrfs_endio_meta_helper;
7229e0af237SLiu Bo 		} else {
7239e0af237SLiu Bo 			wq = fs_info->endio_workers;
7249e0af237SLiu Bo 			func = btrfs_endio_helper;
7259e0af237SLiu Bo 		}
7269e0af237SLiu Bo 	}
7279e0af237SLiu Bo 
7289e0af237SLiu Bo 	btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
7299e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
730ce9adaa5SChris Mason }
731ce9adaa5SChris Mason 
7320cb59c99SJosef Bacik /*
7330cb59c99SJosef Bacik  * For the metadata arg you want
7340cb59c99SJosef Bacik  *
7350cb59c99SJosef Bacik  * 0 - if data
7360cb59c99SJosef Bacik  * 1 - if normal metadta
7370cb59c99SJosef Bacik  * 2 - if writing to the free space cache area
73853b381b3SDavid Woodhouse  * 3 - raid parity work
7390cb59c99SJosef Bacik  */
74022c59948SChris Mason int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
74122c59948SChris Mason 			int metadata)
7420b86a832SChris Mason {
743ce9adaa5SChris Mason 	struct end_io_wq *end_io_wq;
744ce9adaa5SChris Mason 	end_io_wq = kmalloc(sizeof(*end_io_wq), GFP_NOFS);
745ce9adaa5SChris Mason 	if (!end_io_wq)
746ce9adaa5SChris Mason 		return -ENOMEM;
747ce9adaa5SChris Mason 
748ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
749ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
75022c59948SChris Mason 	end_io_wq->info = info;
751ce9adaa5SChris Mason 	end_io_wq->error = 0;
752ce9adaa5SChris Mason 	end_io_wq->bio = bio;
75322c59948SChris Mason 	end_io_wq->metadata = metadata;
754ce9adaa5SChris Mason 
755ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
756ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
75722c59948SChris Mason 	return 0;
75822c59948SChris Mason }
75922c59948SChris Mason 
760b64a2851SChris Mason unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
7614854ddd0SChris Mason {
7624854ddd0SChris Mason 	unsigned long limit = min_t(unsigned long,
7635cdc7ad3SQu Wenruo 				    info->thread_pool_size,
7644854ddd0SChris Mason 				    info->fs_devices->open_devices);
7654854ddd0SChris Mason 	return 256 * limit;
7664854ddd0SChris Mason }
7674854ddd0SChris Mason 
7684a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7694a69a410SChris Mason {
7704a69a410SChris Mason 	struct async_submit_bio *async;
77179787eaaSJeff Mahoney 	int ret;
7724a69a410SChris Mason 
7734a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
77479787eaaSJeff Mahoney 	ret = async->submit_bio_start(async->inode, async->rw, async->bio,
775eaf25d93SChris Mason 				      async->mirror_num, async->bio_flags,
776eaf25d93SChris Mason 				      async->bio_offset);
77779787eaaSJeff Mahoney 	if (ret)
77879787eaaSJeff Mahoney 		async->error = ret;
7794a69a410SChris Mason }
7804a69a410SChris Mason 
7814a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7828b712842SChris Mason {
7838b712842SChris Mason 	struct btrfs_fs_info *fs_info;
7848b712842SChris Mason 	struct async_submit_bio *async;
7854854ddd0SChris Mason 	int limit;
7868b712842SChris Mason 
7878b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7888b712842SChris Mason 	fs_info = BTRFS_I(async->inode)->root->fs_info;
7894854ddd0SChris Mason 
790b64a2851SChris Mason 	limit = btrfs_async_submit_limit(fs_info);
7914854ddd0SChris Mason 	limit = limit * 2 / 3;
7924854ddd0SChris Mason 
79366657b31SJosef Bacik 	if (atomic_dec_return(&fs_info->nr_async_submits) < limit &&
794b64a2851SChris Mason 	    waitqueue_active(&fs_info->async_submit_wait))
7954854ddd0SChris Mason 		wake_up(&fs_info->async_submit_wait);
7964854ddd0SChris Mason 
79779787eaaSJeff Mahoney 	/* If an error occured we just want to clean up the bio and move on */
79879787eaaSJeff Mahoney 	if (async->error) {
79979787eaaSJeff Mahoney 		bio_endio(async->bio, async->error);
80079787eaaSJeff Mahoney 		return;
80179787eaaSJeff Mahoney 	}
80279787eaaSJeff Mahoney 
8034a69a410SChris Mason 	async->submit_bio_done(async->inode, async->rw, async->bio,
804eaf25d93SChris Mason 			       async->mirror_num, async->bio_flags,
805eaf25d93SChris Mason 			       async->bio_offset);
8064a69a410SChris Mason }
8074a69a410SChris Mason 
8084a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8094a69a410SChris Mason {
8104a69a410SChris Mason 	struct async_submit_bio *async;
8114a69a410SChris Mason 
8124a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8138b712842SChris Mason 	kfree(async);
8148b712842SChris Mason }
8158b712842SChris Mason 
81644b8bd7eSChris Mason int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
81744b8bd7eSChris Mason 			int rw, struct bio *bio, int mirror_num,
818c8b97818SChris Mason 			unsigned long bio_flags,
819eaf25d93SChris Mason 			u64 bio_offset,
8204a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_start,
8214a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_done)
82244b8bd7eSChris Mason {
82344b8bd7eSChris Mason 	struct async_submit_bio *async;
82444b8bd7eSChris Mason 
82544b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
82644b8bd7eSChris Mason 	if (!async)
82744b8bd7eSChris Mason 		return -ENOMEM;
82844b8bd7eSChris Mason 
82944b8bd7eSChris Mason 	async->inode = inode;
83044b8bd7eSChris Mason 	async->rw = rw;
83144b8bd7eSChris Mason 	async->bio = bio;
83244b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8334a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8344a69a410SChris Mason 	async->submit_bio_done = submit_bio_done;
8354a69a410SChris Mason 
8369e0af237SLiu Bo 	btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
8375cdc7ad3SQu Wenruo 			run_one_async_done, run_one_async_free);
8384a69a410SChris Mason 
839c8b97818SChris Mason 	async->bio_flags = bio_flags;
840eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8418c8bee1dSChris Mason 
84279787eaaSJeff Mahoney 	async->error = 0;
84379787eaaSJeff Mahoney 
844cb03c743SChris Mason 	atomic_inc(&fs_info->nr_async_submits);
845d313d7a3SChris Mason 
8467b6d91daSChristoph Hellwig 	if (rw & REQ_SYNC)
8475cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
848d313d7a3SChris Mason 
8495cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
8509473f16cSChris Mason 
851771ed689SChris Mason 	while (atomic_read(&fs_info->async_submit_draining) &&
852771ed689SChris Mason 	      atomic_read(&fs_info->nr_async_submits)) {
853771ed689SChris Mason 		wait_event(fs_info->async_submit_wait,
854771ed689SChris Mason 			   (atomic_read(&fs_info->nr_async_submits) == 0));
855771ed689SChris Mason 	}
856771ed689SChris Mason 
85744b8bd7eSChris Mason 	return 0;
85844b8bd7eSChris Mason }
85944b8bd7eSChris Mason 
860ce3ed71aSChris Mason static int btree_csum_one_bio(struct bio *bio)
861ce3ed71aSChris Mason {
8622c30c71bSKent Overstreet 	struct bio_vec *bvec;
863ce3ed71aSChris Mason 	struct btrfs_root *root;
8642c30c71bSKent Overstreet 	int i, ret = 0;
865ce3ed71aSChris Mason 
8662c30c71bSKent Overstreet 	bio_for_each_segment_all(bvec, bio, i) {
867ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
86879787eaaSJeff Mahoney 		ret = csum_dirty_buffer(root, bvec->bv_page);
86979787eaaSJeff Mahoney 		if (ret)
87079787eaaSJeff Mahoney 			break;
871ce3ed71aSChris Mason 	}
8722c30c71bSKent Overstreet 
87379787eaaSJeff Mahoney 	return ret;
874ce3ed71aSChris Mason }
875ce3ed71aSChris Mason 
8764a69a410SChris Mason static int __btree_submit_bio_start(struct inode *inode, int rw,
8774a69a410SChris Mason 				    struct bio *bio, int mirror_num,
878eaf25d93SChris Mason 				    unsigned long bio_flags,
879eaf25d93SChris Mason 				    u64 bio_offset)
88022c59948SChris Mason {
8818b712842SChris Mason 	/*
8828b712842SChris Mason 	 * when we're called for a write, we're already in the async
8835443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8848b712842SChris Mason 	 */
88579787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
88622c59948SChris Mason }
88722c59948SChris Mason 
8884a69a410SChris Mason static int __btree_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
889eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
890eaf25d93SChris Mason 				 u64 bio_offset)
8914a69a410SChris Mason {
89261891923SStefan Behrens 	int ret;
89361891923SStefan Behrens 
8948b712842SChris Mason 	/*
8954a69a410SChris Mason 	 * when we're called for a write, we're already in the async
8964a69a410SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8978b712842SChris Mason 	 */
89861891923SStefan Behrens 	ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio, mirror_num, 1);
89961891923SStefan Behrens 	if (ret)
90061891923SStefan Behrens 		bio_endio(bio, ret);
90161891923SStefan Behrens 	return ret;
9020b86a832SChris Mason }
9030b86a832SChris Mason 
904de0022b9SJosef Bacik static int check_async_write(struct inode *inode, unsigned long bio_flags)
905de0022b9SJosef Bacik {
906de0022b9SJosef Bacik 	if (bio_flags & EXTENT_BIO_TREE_LOG)
907de0022b9SJosef Bacik 		return 0;
908de0022b9SJosef Bacik #ifdef CONFIG_X86
909de0022b9SJosef Bacik 	if (cpu_has_xmm4_2)
910de0022b9SJosef Bacik 		return 0;
911de0022b9SJosef Bacik #endif
912de0022b9SJosef Bacik 	return 1;
913de0022b9SJosef Bacik }
914de0022b9SJosef Bacik 
91544b8bd7eSChris Mason static int btree_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
916eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
917eaf25d93SChris Mason 				 u64 bio_offset)
91844b8bd7eSChris Mason {
919de0022b9SJosef Bacik 	int async = check_async_write(inode, bio_flags);
9204a69a410SChris Mason 	int ret;
921cad321adSChris Mason 
9227b6d91daSChristoph Hellwig 	if (!(rw & REQ_WRITE)) {
923cad321adSChris Mason 		/*
924cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
925cad321adSChris Mason 		 * can happen in the async kernel threads
926cad321adSChris Mason 		 */
927f3f266abSChris Mason 		ret = btrfs_bio_wq_end_io(BTRFS_I(inode)->root->fs_info,
928f3f266abSChris Mason 					  bio, 1);
9291d4284bdSChris Mason 		if (ret)
93061891923SStefan Behrens 			goto out_w_error;
93161891923SStefan Behrens 		ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
9326f3577bdSChris Mason 				    mirror_num, 0);
933de0022b9SJosef Bacik 	} else if (!async) {
934de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
935de0022b9SJosef Bacik 		if (ret)
93661891923SStefan Behrens 			goto out_w_error;
93761891923SStefan Behrens 		ret = btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
938de0022b9SJosef Bacik 				    mirror_num, 0);
93961891923SStefan Behrens 	} else {
940cad321adSChris Mason 		/*
94161891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
94261891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
943cad321adSChris Mason 		 */
94461891923SStefan Behrens 		ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
945c8b97818SChris Mason 					  inode, rw, bio, mirror_num, 0,
946eaf25d93SChris Mason 					  bio_offset,
9474a69a410SChris Mason 					  __btree_submit_bio_start,
9484a69a410SChris Mason 					  __btree_submit_bio_done);
94944b8bd7eSChris Mason 	}
95044b8bd7eSChris Mason 
95161891923SStefan Behrens 	if (ret) {
95261891923SStefan Behrens out_w_error:
95361891923SStefan Behrens 		bio_endio(bio, ret);
95461891923SStefan Behrens 	}
95561891923SStefan Behrens 	return ret;
95661891923SStefan Behrens }
95761891923SStefan Behrens 
9583dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
959784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
960a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
961a6bc32b8SMel Gorman 			enum migrate_mode mode)
962784b4e29SChris Mason {
963784b4e29SChris Mason 	/*
964784b4e29SChris Mason 	 * we can't safely write a btree page from here,
965784b4e29SChris Mason 	 * we haven't done the locking hook
966784b4e29SChris Mason 	 */
967784b4e29SChris Mason 	if (PageDirty(page))
968784b4e29SChris Mason 		return -EAGAIN;
969784b4e29SChris Mason 	/*
970784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
971784b4e29SChris Mason 	 * We must have no buffers or drop them.
972784b4e29SChris Mason 	 */
973784b4e29SChris Mason 	if (page_has_private(page) &&
974784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
975784b4e29SChris Mason 		return -EAGAIN;
976a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
977784b4e29SChris Mason }
9783dd1462eSJan Beulich #endif
979784b4e29SChris Mason 
9800da5468fSChris Mason 
9810da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9820da5468fSChris Mason 			    struct writeback_control *wbc)
9830da5468fSChris Mason {
984e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
985e2d84521SMiao Xie 	int ret;
986e2d84521SMiao Xie 
987d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
988448d640bSChris Mason 
989448d640bSChris Mason 		if (wbc->for_kupdate)
990448d640bSChris Mason 			return 0;
991448d640bSChris Mason 
992e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
993b9473439SChris Mason 		/* this is a bit racy, but that's ok */
994e2d84521SMiao Xie 		ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
995e2d84521SMiao Xie 					     BTRFS_DIRTY_METADATA_THRESH);
996e2d84521SMiao Xie 		if (ret < 0)
997793955bcSChris Mason 			return 0;
998793955bcSChris Mason 	}
9990b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
10000da5468fSChris Mason }
10010da5468fSChris Mason 
1002b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
10035f39d397SChris Mason {
1004d1310b2eSChris Mason 	struct extent_io_tree *tree;
1005d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10068ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
10075f39d397SChris Mason }
10085f39d397SChris Mason 
100970dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
10105f39d397SChris Mason {
101198509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
101298509cfcSChris Mason 		return 0;
10130c4e538bSDavid Sterba 
1014f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1015d98237b3SChris Mason }
1016d98237b3SChris Mason 
1017d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1018d47992f8SLukas Czerner 				 unsigned int length)
1019d98237b3SChris Mason {
1020d1310b2eSChris Mason 	struct extent_io_tree *tree;
1021d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10225f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
10235f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
10249ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1025efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1026efe120a0SFrank Holton 			   "page private not zero on page %llu",
1027efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
10289ad6b7bcSChris Mason 		ClearPagePrivate(page);
10299ad6b7bcSChris Mason 		set_page_private(page, 0);
10309ad6b7bcSChris Mason 		page_cache_release(page);
10319ad6b7bcSChris Mason 	}
1032d98237b3SChris Mason }
1033d98237b3SChris Mason 
10340b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10350b32f4bbSJosef Bacik {
1036bb146eb2SJosef Bacik #ifdef DEBUG
10370b32f4bbSJosef Bacik 	struct extent_buffer *eb;
10380b32f4bbSJosef Bacik 
10390b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
10400b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
10410b32f4bbSJosef Bacik 	BUG_ON(!eb);
10420b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10430b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
10440b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
1045bb146eb2SJosef Bacik #endif
10460b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10470b32f4bbSJosef Bacik }
10480b32f4bbSJosef Bacik 
10497f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
1050d98237b3SChris Mason 	.readpage	= btree_readpage,
10510da5468fSChris Mason 	.writepages	= btree_writepages,
10525f39d397SChris Mason 	.releasepage	= btree_releasepage,
10535f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10545a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1055784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10565a92bc88SChris Mason #endif
10570b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1058d98237b3SChris Mason };
1059123abc88SChris Mason 
1060ca7a79adSChris Mason int readahead_tree_block(struct btrfs_root *root, u64 bytenr, u32 blocksize,
1061ca7a79adSChris Mason 			 u64 parent_transid)
1062090d1875SChris Mason {
10635f39d397SChris Mason 	struct extent_buffer *buf = NULL;
10645f39d397SChris Mason 	struct inode *btree_inode = root->fs_info->btree_inode;
1065de428b63SChris Mason 	int ret = 0;
1066090d1875SChris Mason 
1067db94535dSChris Mason 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
10685f39d397SChris Mason 	if (!buf)
1069090d1875SChris Mason 		return 0;
1070d1310b2eSChris Mason 	read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
1071bb82ab88SArne Jansen 				 buf, 0, WAIT_NONE, btree_get_extent, 0);
10725f39d397SChris Mason 	free_extent_buffer(buf);
1073de428b63SChris Mason 	return ret;
1074090d1875SChris Mason }
1075090d1875SChris Mason 
1076ab0fff03SArne Jansen int reada_tree_block_flagged(struct btrfs_root *root, u64 bytenr, u32 blocksize,
1077ab0fff03SArne Jansen 			 int mirror_num, struct extent_buffer **eb)
1078ab0fff03SArne Jansen {
1079ab0fff03SArne Jansen 	struct extent_buffer *buf = NULL;
1080ab0fff03SArne Jansen 	struct inode *btree_inode = root->fs_info->btree_inode;
1081ab0fff03SArne Jansen 	struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1082ab0fff03SArne Jansen 	int ret;
1083ab0fff03SArne Jansen 
1084ab0fff03SArne Jansen 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
1085ab0fff03SArne Jansen 	if (!buf)
1086ab0fff03SArne Jansen 		return 0;
1087ab0fff03SArne Jansen 
1088ab0fff03SArne Jansen 	set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1089ab0fff03SArne Jansen 
1090ab0fff03SArne Jansen 	ret = read_extent_buffer_pages(io_tree, buf, 0, WAIT_PAGE_LOCK,
1091ab0fff03SArne Jansen 				       btree_get_extent, mirror_num);
1092ab0fff03SArne Jansen 	if (ret) {
1093ab0fff03SArne Jansen 		free_extent_buffer(buf);
1094ab0fff03SArne Jansen 		return ret;
1095ab0fff03SArne Jansen 	}
1096ab0fff03SArne Jansen 
1097ab0fff03SArne Jansen 	if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1098ab0fff03SArne Jansen 		free_extent_buffer(buf);
1099ab0fff03SArne Jansen 		return -EIO;
11000b32f4bbSJosef Bacik 	} else if (extent_buffer_uptodate(buf)) {
1101ab0fff03SArne Jansen 		*eb = buf;
1102ab0fff03SArne Jansen 	} else {
1103ab0fff03SArne Jansen 		free_extent_buffer(buf);
1104ab0fff03SArne Jansen 	}
1105ab0fff03SArne Jansen 	return 0;
1106ab0fff03SArne Jansen }
1107ab0fff03SArne Jansen 
11080999df54SChris Mason struct extent_buffer *btrfs_find_tree_block(struct btrfs_root *root,
11090999df54SChris Mason 					    u64 bytenr, u32 blocksize)
11100999df54SChris Mason {
1111f28491e0SJosef Bacik 	return find_extent_buffer(root->fs_info, bytenr);
11120999df54SChris Mason }
11130999df54SChris Mason 
11140999df54SChris Mason struct extent_buffer *btrfs_find_create_tree_block(struct btrfs_root *root,
11150999df54SChris Mason 						 u64 bytenr, u32 blocksize)
11160999df54SChris Mason {
1117faa2dbf0SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1118faa2dbf0SJosef Bacik 	if (unlikely(test_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state)))
1119faa2dbf0SJosef Bacik 		return alloc_test_extent_buffer(root->fs_info, bytenr,
1120faa2dbf0SJosef Bacik 						blocksize);
1121faa2dbf0SJosef Bacik #endif
1122f28491e0SJosef Bacik 	return alloc_extent_buffer(root->fs_info, bytenr, blocksize);
11230999df54SChris Mason }
11240999df54SChris Mason 
11250999df54SChris Mason 
1126e02119d5SChris Mason int btrfs_write_tree_block(struct extent_buffer *buf)
1127e02119d5SChris Mason {
1128727011e0SChris Mason 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
11298aa38c31SChristoph Hellwig 					buf->start + buf->len - 1);
1130e02119d5SChris Mason }
1131e02119d5SChris Mason 
1132e02119d5SChris Mason int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1133e02119d5SChris Mason {
1134727011e0SChris Mason 	return filemap_fdatawait_range(buf->pages[0]->mapping,
11358aa38c31SChristoph Hellwig 				       buf->start, buf->start + buf->len - 1);
1136e02119d5SChris Mason }
1137e02119d5SChris Mason 
1138db94535dSChris Mason struct extent_buffer *read_tree_block(struct btrfs_root *root, u64 bytenr,
1139ca7a79adSChris Mason 				      u32 blocksize, u64 parent_transid)
1140e20d96d6SChris Mason {
11415f39d397SChris Mason 	struct extent_buffer *buf = NULL;
114219c00ddcSChris Mason 	int ret;
114319c00ddcSChris Mason 
1144db94535dSChris Mason 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
11455f39d397SChris Mason 	if (!buf)
1146d98237b3SChris Mason 		return NULL;
1147e4204dedSChris Mason 
1148ca7a79adSChris Mason 	ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
11490f0fe8f7SFilipe David Borba Manana 	if (ret) {
11500f0fe8f7SFilipe David Borba Manana 		free_extent_buffer(buf);
11510f0fe8f7SFilipe David Borba Manana 		return NULL;
11520f0fe8f7SFilipe David Borba Manana 	}
11535f39d397SChris Mason 	return buf;
1154ce9adaa5SChris Mason 
1155eb60ceacSChris Mason }
1156eb60ceacSChris Mason 
1157d5c13f92SJeff Mahoney void clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
11585f39d397SChris Mason 		      struct extent_buffer *buf)
1159ed2ff2cbSChris Mason {
1160e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info = root->fs_info;
1161e2d84521SMiao Xie 
116255c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1163e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1164b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1165b4ce94deSChris Mason 
1166b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1167e2d84521SMiao Xie 			__percpu_counter_add(&fs_info->dirty_metadata_bytes,
1168e2d84521SMiao Xie 					     -buf->len,
1169e2d84521SMiao Xie 					     fs_info->dirty_metadata_batch);
1170b9473439SChris Mason 			/* ugh, clear_extent_buffer_dirty needs to lock the page */
1171b9473439SChris Mason 			btrfs_set_lock_blocking(buf);
11720b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1173925baeddSChris Mason 		}
11745f39d397SChris Mason 	}
1175ed7b63ebSJosef Bacik }
11765f39d397SChris Mason 
11778257b2dcSMiao Xie static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
11788257b2dcSMiao Xie {
11798257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
11808257b2dcSMiao Xie 	int ret;
11818257b2dcSMiao Xie 
11828257b2dcSMiao Xie 	writers = kmalloc(sizeof(*writers), GFP_NOFS);
11838257b2dcSMiao Xie 	if (!writers)
11848257b2dcSMiao Xie 		return ERR_PTR(-ENOMEM);
11858257b2dcSMiao Xie 
11868257b2dcSMiao Xie 	ret = percpu_counter_init(&writers->counter, 0);
11878257b2dcSMiao Xie 	if (ret < 0) {
11888257b2dcSMiao Xie 		kfree(writers);
11898257b2dcSMiao Xie 		return ERR_PTR(ret);
11908257b2dcSMiao Xie 	}
11918257b2dcSMiao Xie 
11928257b2dcSMiao Xie 	init_waitqueue_head(&writers->wait);
11938257b2dcSMiao Xie 	return writers;
11948257b2dcSMiao Xie }
11958257b2dcSMiao Xie 
11968257b2dcSMiao Xie static void
11978257b2dcSMiao Xie btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
11988257b2dcSMiao Xie {
11998257b2dcSMiao Xie 	percpu_counter_destroy(&writers->counter);
12008257b2dcSMiao Xie 	kfree(writers);
12018257b2dcSMiao Xie }
12028257b2dcSMiao Xie 
1203707e8a07SDavid Sterba static void __setup_root(u32 nodesize, u32 sectorsize, u32 stripesize,
1204707e8a07SDavid Sterba 			 struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1205e20d96d6SChris Mason 			 u64 objectid)
1206d97e63b6SChris Mason {
1207cfaa7295SChris Mason 	root->node = NULL;
1208a28ec197SChris Mason 	root->commit_root = NULL;
1209db94535dSChris Mason 	root->sectorsize = sectorsize;
1210db94535dSChris Mason 	root->nodesize = nodesize;
121187ee04ebSChris Mason 	root->stripesize = stripesize;
121227cdeb70SMiao Xie 	root->state = 0;
1213d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
12140b86a832SChris Mason 
12150f7d52f4SChris Mason 	root->objectid = objectid;
12160f7d52f4SChris Mason 	root->last_trans = 0;
121713a8a7c8SYan, Zheng 	root->highest_objectid = 0;
1218eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1219199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
122058176a96SJosef Bacik 	root->name = NULL;
12216bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
122216cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1223f0486c68SYan, Zheng 	root->block_rsv = NULL;
1224d68fc57bSYan, Zheng 	root->orphan_block_rsv = NULL;
12250b86a832SChris Mason 
12260b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
12275d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1228eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1229eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1230199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1231199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
12322ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
12332ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
1234d68fc57bSYan, Zheng 	spin_lock_init(&root->orphan_lock);
12355d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1236eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1237199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1238f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
12392ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
12402ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
1241a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1242e02119d5SChris Mason 	mutex_init(&root->log_mutex);
124331f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1244573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
12457237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
12467237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
12477237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
12488b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
12498b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
12507237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
12517237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
12527237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
12532ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
12548a35d95fSJosef Bacik 	atomic_set(&root->orphan_inodes, 0);
1255b0feb9d9SMiao Xie 	atomic_set(&root->refs, 1);
12568257b2dcSMiao Xie 	atomic_set(&root->will_be_snapshoted, 0);
12577237f183SYan Zheng 	root->log_transid = 0;
1258d1433debSMiao Xie 	root->log_transid_committed = -1;
1259257c62e1SChris Mason 	root->last_log_commit = 0;
126006ea65a3SJosef Bacik 	if (fs_info)
1261d0c803c4SChris Mason 		extent_io_tree_init(&root->dirty_log_pages,
1262f993c883SDavid Sterba 				     fs_info->btree_inode->i_mapping);
1263017e5369SChris Mason 
12643768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
12653768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
12666702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
126758176a96SJosef Bacik 	memset(&root->root_kobj, 0, sizeof(root->root_kobj));
126806ea65a3SJosef Bacik 	if (fs_info)
12693f157a2fSChris Mason 		root->defrag_trans_start = fs_info->generation;
127006ea65a3SJosef Bacik 	else
127106ea65a3SJosef Bacik 		root->defrag_trans_start = 0;
127258176a96SJosef Bacik 	init_completion(&root->kobj_unregister);
12734d775673SChris Mason 	root->root_key.objectid = objectid;
12740ee5dc67SAl Viro 	root->anon_dev = 0;
12758ea05e3aSAlexander Block 
12765f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
12773768f368SChris Mason }
12783768f368SChris Mason 
1279f84a8bd6SAl Viro static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info)
12806f07e42eSAl Viro {
12816f07e42eSAl Viro 	struct btrfs_root *root = kzalloc(sizeof(*root), GFP_NOFS);
12826f07e42eSAl Viro 	if (root)
12836f07e42eSAl Viro 		root->fs_info = fs_info;
12846f07e42eSAl Viro 	return root;
12856f07e42eSAl Viro }
12866f07e42eSAl Viro 
128706ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
128806ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
128906ea65a3SJosef Bacik struct btrfs_root *btrfs_alloc_dummy_root(void)
129006ea65a3SJosef Bacik {
129106ea65a3SJosef Bacik 	struct btrfs_root *root;
129206ea65a3SJosef Bacik 
129306ea65a3SJosef Bacik 	root = btrfs_alloc_root(NULL);
129406ea65a3SJosef Bacik 	if (!root)
129506ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1296707e8a07SDavid Sterba 	__setup_root(4096, 4096, 4096, root, NULL, 1);
129727cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state);
1298faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
129906ea65a3SJosef Bacik 
130006ea65a3SJosef Bacik 	return root;
130106ea65a3SJosef Bacik }
130206ea65a3SJosef Bacik #endif
130306ea65a3SJosef Bacik 
130420897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
130520897f5cSArne Jansen 				     struct btrfs_fs_info *fs_info,
130620897f5cSArne Jansen 				     u64 objectid)
130720897f5cSArne Jansen {
130820897f5cSArne Jansen 	struct extent_buffer *leaf;
130920897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
131020897f5cSArne Jansen 	struct btrfs_root *root;
131120897f5cSArne Jansen 	struct btrfs_key key;
131220897f5cSArne Jansen 	int ret = 0;
13136463fe58SStefan Behrens 	uuid_le uuid;
131420897f5cSArne Jansen 
131520897f5cSArne Jansen 	root = btrfs_alloc_root(fs_info);
131620897f5cSArne Jansen 	if (!root)
131720897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
131820897f5cSArne Jansen 
1319707e8a07SDavid Sterba 	__setup_root(tree_root->nodesize, tree_root->sectorsize,
1320707e8a07SDavid Sterba 		tree_root->stripesize, root, fs_info, objectid);
132120897f5cSArne Jansen 	root->root_key.objectid = objectid;
132220897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
132320897f5cSArne Jansen 	root->root_key.offset = 0;
132420897f5cSArne Jansen 
1325707e8a07SDavid Sterba 	leaf = btrfs_alloc_free_block(trans, root, root->nodesize,
132620897f5cSArne Jansen 				      0, objectid, NULL, 0, 0, 0);
132720897f5cSArne Jansen 	if (IS_ERR(leaf)) {
132820897f5cSArne Jansen 		ret = PTR_ERR(leaf);
13291dd05682STsutomu Itoh 		leaf = NULL;
133020897f5cSArne Jansen 		goto fail;
133120897f5cSArne Jansen 	}
133220897f5cSArne Jansen 
133320897f5cSArne Jansen 	memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
133420897f5cSArne Jansen 	btrfs_set_header_bytenr(leaf, leaf->start);
133520897f5cSArne Jansen 	btrfs_set_header_generation(leaf, trans->transid);
133620897f5cSArne Jansen 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
133720897f5cSArne Jansen 	btrfs_set_header_owner(leaf, objectid);
133820897f5cSArne Jansen 	root->node = leaf;
133920897f5cSArne Jansen 
13400a4e5586SRoss Kirk 	write_extent_buffer(leaf, fs_info->fsid, btrfs_header_fsid(),
134120897f5cSArne Jansen 			    BTRFS_FSID_SIZE);
134220897f5cSArne Jansen 	write_extent_buffer(leaf, fs_info->chunk_tree_uuid,
1343b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(leaf),
134420897f5cSArne Jansen 			    BTRFS_UUID_SIZE);
134520897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
134620897f5cSArne Jansen 
134720897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
134827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
134920897f5cSArne Jansen 
135020897f5cSArne Jansen 	root->root_item.flags = 0;
135120897f5cSArne Jansen 	root->root_item.byte_limit = 0;
135220897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
135320897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
135420897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
135520897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
135620897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
135720897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
135820897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
13596463fe58SStefan Behrens 	uuid_le_gen(&uuid);
13606463fe58SStefan Behrens 	memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
136120897f5cSArne Jansen 	root->root_item.drop_level = 0;
136220897f5cSArne Jansen 
136320897f5cSArne Jansen 	key.objectid = objectid;
136420897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
136520897f5cSArne Jansen 	key.offset = 0;
136620897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
136720897f5cSArne Jansen 	if (ret)
136820897f5cSArne Jansen 		goto fail;
136920897f5cSArne Jansen 
137020897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
137120897f5cSArne Jansen 
137220897f5cSArne Jansen 	return root;
13731dd05682STsutomu Itoh 
13741dd05682STsutomu Itoh fail:
13751dd05682STsutomu Itoh 	if (leaf) {
13761dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
137759885b39STsutomu Itoh 		free_extent_buffer(root->commit_root);
13781dd05682STsutomu Itoh 		free_extent_buffer(leaf);
13791dd05682STsutomu Itoh 	}
13801dd05682STsutomu Itoh 	kfree(root);
13811dd05682STsutomu Itoh 
13821dd05682STsutomu Itoh 	return ERR_PTR(ret);
138320897f5cSArne Jansen }
138420897f5cSArne Jansen 
13857237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1386e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13870f7d52f4SChris Mason {
13880f7d52f4SChris Mason 	struct btrfs_root *root;
13890f7d52f4SChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
13907237f183SYan Zheng 	struct extent_buffer *leaf;
1391e02119d5SChris Mason 
13926f07e42eSAl Viro 	root = btrfs_alloc_root(fs_info);
1393e02119d5SChris Mason 	if (!root)
13947237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1395e02119d5SChris Mason 
1396707e8a07SDavid Sterba 	__setup_root(tree_root->nodesize, tree_root->sectorsize,
1397707e8a07SDavid Sterba 		     tree_root->stripesize, root, fs_info,
1398707e8a07SDavid Sterba 		     BTRFS_TREE_LOG_OBJECTID);
1399e02119d5SChris Mason 
1400e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1401e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1402e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
140327cdeb70SMiao Xie 
14047237f183SYan Zheng 	/*
140527cdeb70SMiao Xie 	 * DON'T set REF_COWS for log trees
140627cdeb70SMiao Xie 	 *
14077237f183SYan Zheng 	 * log trees do not get reference counted because they go away
14087237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
14097237f183SYan Zheng 	 * to file data extents, and those reference counts still get
14107237f183SYan Zheng 	 * updated (along with back refs to the log tree).
14117237f183SYan Zheng 	 */
1412e02119d5SChris Mason 
1413707e8a07SDavid Sterba 	leaf = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
141466d7e7f0SArne Jansen 				      BTRFS_TREE_LOG_OBJECTID, NULL,
14155581a51aSJan Schmidt 				      0, 0, 0);
14167237f183SYan Zheng 	if (IS_ERR(leaf)) {
14177237f183SYan Zheng 		kfree(root);
14187237f183SYan Zheng 		return ERR_CAST(leaf);
14197237f183SYan Zheng 	}
1420e02119d5SChris Mason 
14215d4f98a2SYan Zheng 	memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
14225d4f98a2SYan Zheng 	btrfs_set_header_bytenr(leaf, leaf->start);
14235d4f98a2SYan Zheng 	btrfs_set_header_generation(leaf, trans->transid);
14245d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
14255d4f98a2SYan Zheng 	btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
14267237f183SYan Zheng 	root->node = leaf;
1427e02119d5SChris Mason 
1428e02119d5SChris Mason 	write_extent_buffer(root->node, root->fs_info->fsid,
14290a4e5586SRoss Kirk 			    btrfs_header_fsid(), BTRFS_FSID_SIZE);
1430e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1431e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
14327237f183SYan Zheng 	return root;
14337237f183SYan Zheng }
14347237f183SYan Zheng 
14357237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
14367237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
14377237f183SYan Zheng {
14387237f183SYan Zheng 	struct btrfs_root *log_root;
14397237f183SYan Zheng 
14407237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
14417237f183SYan Zheng 	if (IS_ERR(log_root))
14427237f183SYan Zheng 		return PTR_ERR(log_root);
14437237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
14447237f183SYan Zheng 	fs_info->log_root_tree = log_root;
14457237f183SYan Zheng 	return 0;
14467237f183SYan Zheng }
14477237f183SYan Zheng 
14487237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
14497237f183SYan Zheng 		       struct btrfs_root *root)
14507237f183SYan Zheng {
14517237f183SYan Zheng 	struct btrfs_root *log_root;
14527237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
14537237f183SYan Zheng 
14547237f183SYan Zheng 	log_root = alloc_log_tree(trans, root->fs_info);
14557237f183SYan Zheng 	if (IS_ERR(log_root))
14567237f183SYan Zheng 		return PTR_ERR(log_root);
14577237f183SYan Zheng 
14587237f183SYan Zheng 	log_root->last_trans = trans->transid;
14597237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14607237f183SYan Zheng 
14617237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14623cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14633cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14643cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1465707e8a07SDavid Sterba 	btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
14663cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14677237f183SYan Zheng 
14685d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14697237f183SYan Zheng 
14707237f183SYan Zheng 	WARN_ON(root->log_root);
14717237f183SYan Zheng 	root->log_root = log_root;
14727237f183SYan Zheng 	root->log_transid = 0;
1473d1433debSMiao Xie 	root->log_transid_committed = -1;
1474257c62e1SChris Mason 	root->last_log_commit = 0;
1475e02119d5SChris Mason 	return 0;
1476e02119d5SChris Mason }
1477e02119d5SChris Mason 
147835a3621bSStefan Behrens static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1479cb517eabSMiao Xie 					       struct btrfs_key *key)
1480e02119d5SChris Mason {
1481e02119d5SChris Mason 	struct btrfs_root *root;
1482e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
14830f7d52f4SChris Mason 	struct btrfs_path *path;
148484234f3aSYan Zheng 	u64 generation;
1485db94535dSChris Mason 	u32 blocksize;
1486cb517eabSMiao Xie 	int ret;
1487cb517eabSMiao Xie 
1488cb517eabSMiao Xie 	path = btrfs_alloc_path();
1489cb517eabSMiao Xie 	if (!path)
1490cb517eabSMiao Xie 		return ERR_PTR(-ENOMEM);
14910f7d52f4SChris Mason 
14926f07e42eSAl Viro 	root = btrfs_alloc_root(fs_info);
1493cb517eabSMiao Xie 	if (!root) {
1494cb517eabSMiao Xie 		ret = -ENOMEM;
1495cb517eabSMiao Xie 		goto alloc_fail;
14960f7d52f4SChris Mason 	}
14970f7d52f4SChris Mason 
1498707e8a07SDavid Sterba 	__setup_root(tree_root->nodesize, tree_root->sectorsize,
1499707e8a07SDavid Sterba 		tree_root->stripesize, root, fs_info, key->objectid);
15000f7d52f4SChris Mason 
1501cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1502cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
15030f7d52f4SChris Mason 	if (ret) {
150413a8a7c8SYan, Zheng 		if (ret > 0)
150513a8a7c8SYan, Zheng 			ret = -ENOENT;
1506cb517eabSMiao Xie 		goto find_fail;
15070f7d52f4SChris Mason 	}
150813a8a7c8SYan, Zheng 
150984234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1510707e8a07SDavid Sterba 	blocksize = root->nodesize;
1511db94535dSChris Mason 	root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
151284234f3aSYan Zheng 				     blocksize, generation);
1513cb517eabSMiao Xie 	if (!root->node) {
1514cb517eabSMiao Xie 		ret = -ENOMEM;
1515cb517eabSMiao Xie 		goto find_fail;
1516cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1517cb517eabSMiao Xie 		ret = -EIO;
1518cb517eabSMiao Xie 		goto read_fail;
1519416bc658SJosef Bacik 	}
15205d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
152113a8a7c8SYan, Zheng out:
1522cb517eabSMiao Xie 	btrfs_free_path(path);
1523cb517eabSMiao Xie 	return root;
1524cb517eabSMiao Xie 
1525cb517eabSMiao Xie read_fail:
1526cb517eabSMiao Xie 	free_extent_buffer(root->node);
1527cb517eabSMiao Xie find_fail:
1528cb517eabSMiao Xie 	kfree(root);
1529cb517eabSMiao Xie alloc_fail:
1530cb517eabSMiao Xie 	root = ERR_PTR(ret);
1531cb517eabSMiao Xie 	goto out;
1532cb517eabSMiao Xie }
1533cb517eabSMiao Xie 
1534cb517eabSMiao Xie struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1535cb517eabSMiao Xie 				      struct btrfs_key *location)
1536cb517eabSMiao Xie {
1537cb517eabSMiao Xie 	struct btrfs_root *root;
1538cb517eabSMiao Xie 
1539cb517eabSMiao Xie 	root = btrfs_read_tree_root(tree_root, location);
1540cb517eabSMiao Xie 	if (IS_ERR(root))
1541cb517eabSMiao Xie 		return root;
1542cb517eabSMiao Xie 
1543cb517eabSMiao Xie 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
154427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_REF_COWS, &root->state);
154508fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
154608fe4db1SLi Zefan 	}
154713a8a7c8SYan, Zheng 
15485eda7b5eSChris Mason 	return root;
15495eda7b5eSChris Mason }
15505eda7b5eSChris Mason 
1551cb517eabSMiao Xie int btrfs_init_fs_root(struct btrfs_root *root)
1552cb517eabSMiao Xie {
1553cb517eabSMiao Xie 	int ret;
15548257b2dcSMiao Xie 	struct btrfs_subvolume_writers *writers;
1555cb517eabSMiao Xie 
1556cb517eabSMiao Xie 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1557cb517eabSMiao Xie 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1558cb517eabSMiao Xie 					GFP_NOFS);
1559cb517eabSMiao Xie 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
1560cb517eabSMiao Xie 		ret = -ENOMEM;
1561cb517eabSMiao Xie 		goto fail;
1562cb517eabSMiao Xie 	}
1563cb517eabSMiao Xie 
15648257b2dcSMiao Xie 	writers = btrfs_alloc_subvolume_writers();
15658257b2dcSMiao Xie 	if (IS_ERR(writers)) {
15668257b2dcSMiao Xie 		ret = PTR_ERR(writers);
15678257b2dcSMiao Xie 		goto fail;
15688257b2dcSMiao Xie 	}
15698257b2dcSMiao Xie 	root->subv_writers = writers;
15708257b2dcSMiao Xie 
1571cb517eabSMiao Xie 	btrfs_init_free_ino_ctl(root);
157257cdc8dbSDavid Sterba 	spin_lock_init(&root->ino_cache_lock);
157357cdc8dbSDavid Sterba 	init_waitqueue_head(&root->ino_cache_wait);
1574cb517eabSMiao Xie 
1575cb517eabSMiao Xie 	ret = get_anon_bdev(&root->anon_dev);
1576cb517eabSMiao Xie 	if (ret)
15778257b2dcSMiao Xie 		goto free_writers;
1578cb517eabSMiao Xie 	return 0;
15798257b2dcSMiao Xie 
15808257b2dcSMiao Xie free_writers:
15818257b2dcSMiao Xie 	btrfs_free_subvolume_writers(root->subv_writers);
1582cb517eabSMiao Xie fail:
1583cb517eabSMiao Xie 	kfree(root->free_ino_ctl);
1584cb517eabSMiao Xie 	kfree(root->free_ino_pinned);
1585cb517eabSMiao Xie 	return ret;
1586cb517eabSMiao Xie }
1587cb517eabSMiao Xie 
1588171170c1SSergei Trofimovich static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1589cb517eabSMiao Xie 					       u64 root_id)
1590cb517eabSMiao Xie {
1591cb517eabSMiao Xie 	struct btrfs_root *root;
1592cb517eabSMiao Xie 
1593cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1594cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1595cb517eabSMiao Xie 				 (unsigned long)root_id);
1596cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1597cb517eabSMiao Xie 	return root;
1598cb517eabSMiao Xie }
1599cb517eabSMiao Xie 
1600cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1601cb517eabSMiao Xie 			 struct btrfs_root *root)
1602cb517eabSMiao Xie {
1603cb517eabSMiao Xie 	int ret;
1604cb517eabSMiao Xie 
1605cb517eabSMiao Xie 	ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
1606cb517eabSMiao Xie 	if (ret)
1607cb517eabSMiao Xie 		return ret;
1608cb517eabSMiao Xie 
1609cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1610cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1611cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1612cb517eabSMiao Xie 				root);
1613cb517eabSMiao Xie 	if (ret == 0)
161427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1615cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1616cb517eabSMiao Xie 	radix_tree_preload_end();
1617cb517eabSMiao Xie 
1618cb517eabSMiao Xie 	return ret;
1619cb517eabSMiao Xie }
1620cb517eabSMiao Xie 
1621c00869f1SMiao Xie struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1622c00869f1SMiao Xie 				     struct btrfs_key *location,
1623c00869f1SMiao Xie 				     bool check_ref)
16245eda7b5eSChris Mason {
16255eda7b5eSChris Mason 	struct btrfs_root *root;
16265eda7b5eSChris Mason 	int ret;
16275eda7b5eSChris Mason 
1628edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1629edbd8d4eSChris Mason 		return fs_info->tree_root;
1630edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1631edbd8d4eSChris Mason 		return fs_info->extent_root;
16328f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
16338f18cf13SChris Mason 		return fs_info->chunk_root;
16348f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
16358f18cf13SChris Mason 		return fs_info->dev_root;
16360403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
16370403e47eSYan Zheng 		return fs_info->csum_root;
1638bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1639bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1640bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
1641f7a81ea4SStefan Behrens 	if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1642f7a81ea4SStefan Behrens 		return fs_info->uuid_root ? fs_info->uuid_root :
1643f7a81ea4SStefan Behrens 					    ERR_PTR(-ENOENT);
16444df27c4dSYan, Zheng again:
1645cb517eabSMiao Xie 	root = btrfs_lookup_fs_root(fs_info, location->objectid);
164648475471SStefan Behrens 	if (root) {
1647c00869f1SMiao Xie 		if (check_ref && btrfs_root_refs(&root->root_item) == 0)
164848475471SStefan Behrens 			return ERR_PTR(-ENOENT);
16495eda7b5eSChris Mason 		return root;
165048475471SStefan Behrens 	}
16515eda7b5eSChris Mason 
1652cb517eabSMiao Xie 	root = btrfs_read_fs_root(fs_info->tree_root, location);
16535eda7b5eSChris Mason 	if (IS_ERR(root))
16545eda7b5eSChris Mason 		return root;
16553394e160SChris Mason 
1656c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1657d68fc57bSYan, Zheng 		ret = -ENOENT;
1658d68fc57bSYan, Zheng 		goto fail;
1659d68fc57bSYan, Zheng 	}
1660d68fc57bSYan, Zheng 
1661cb517eabSMiao Xie 	ret = btrfs_init_fs_root(root);
1662cb517eabSMiao Xie 	if (ret)
1663cb517eabSMiao Xie 		goto fail;
1664cb517eabSMiao Xie 
16653f870c28SKelley Nielsen 	ret = btrfs_find_item(fs_info->tree_root, NULL, BTRFS_ORPHAN_OBJECTID,
16663f870c28SKelley Nielsen 			location->objectid, BTRFS_ORPHAN_ITEM_KEY, NULL);
1667d68fc57bSYan, Zheng 	if (ret < 0)
1668d68fc57bSYan, Zheng 		goto fail;
1669d68fc57bSYan, Zheng 	if (ret == 0)
167027cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1671d68fc57bSYan, Zheng 
1672cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16730f7d52f4SChris Mason 	if (ret) {
16744df27c4dSYan, Zheng 		if (ret == -EEXIST) {
16754df27c4dSYan, Zheng 			free_fs_root(root);
16764df27c4dSYan, Zheng 			goto again;
16770f7d52f4SChris Mason 		}
16784df27c4dSYan, Zheng 		goto fail;
16794df27c4dSYan, Zheng 	}
1680edbd8d4eSChris Mason 	return root;
16814df27c4dSYan, Zheng fail:
16824df27c4dSYan, Zheng 	free_fs_root(root);
16834df27c4dSYan, Zheng 	return ERR_PTR(ret);
1684edbd8d4eSChris Mason }
1685edbd8d4eSChris Mason 
168604160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
168704160088SChris Mason {
168804160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
168904160088SChris Mason 	int ret = 0;
169004160088SChris Mason 	struct btrfs_device *device;
169104160088SChris Mason 	struct backing_dev_info *bdi;
1692b7967db7SChris Mason 
16931f78160cSXiao Guangrong 	rcu_read_lock();
16941f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1695dfe25020SChris Mason 		if (!device->bdev)
1696dfe25020SChris Mason 			continue;
169704160088SChris Mason 		bdi = blk_get_backing_dev_info(device->bdev);
169804160088SChris Mason 		if (bdi && bdi_congested(bdi, bdi_bits)) {
169904160088SChris Mason 			ret = 1;
170004160088SChris Mason 			break;
170104160088SChris Mason 		}
170204160088SChris Mason 	}
17031f78160cSXiao Guangrong 	rcu_read_unlock();
170404160088SChris Mason 	return ret;
170504160088SChris Mason }
170604160088SChris Mason 
170738b66988SChris Mason /*
1708ad081f14SJens Axboe  * If this fails, caller must call bdi_destroy() to get rid of the
1709ad081f14SJens Axboe  * bdi again.
1710ad081f14SJens Axboe  */
171104160088SChris Mason static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
171204160088SChris Mason {
1713ad081f14SJens Axboe 	int err;
1714ad081f14SJens Axboe 
1715ad081f14SJens Axboe 	bdi->capabilities = BDI_CAP_MAP_COPY;
1716e6d086d8SJens Axboe 	err = bdi_setup_and_register(bdi, "btrfs", BDI_CAP_MAP_COPY);
1717ad081f14SJens Axboe 	if (err)
1718ad081f14SJens Axboe 		return err;
1719ad081f14SJens Axboe 
17204575c9ccSChris Mason 	bdi->ra_pages	= default_backing_dev_info.ra_pages;
172104160088SChris Mason 	bdi->congested_fn	= btrfs_congested_fn;
172204160088SChris Mason 	bdi->congested_data	= info;
172304160088SChris Mason 	return 0;
172404160088SChris Mason }
172504160088SChris Mason 
17268b712842SChris Mason /*
17278b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
17288b712842SChris Mason  * functions.  This is where read checksum verification actually happens
17298b712842SChris Mason  */
17308b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1731ce9adaa5SChris Mason {
1732ce9adaa5SChris Mason 	struct bio *bio;
17338b712842SChris Mason 	struct end_io_wq *end_io_wq;
1734ce9adaa5SChris Mason 	int error;
1735ce9adaa5SChris Mason 
17368b712842SChris Mason 	end_io_wq = container_of(work, struct end_io_wq, work);
1737ce9adaa5SChris Mason 	bio = end_io_wq->bio;
17388b712842SChris Mason 
1739ce9adaa5SChris Mason 	error = end_io_wq->error;
1740ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1741ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
1742ce9adaa5SChris Mason 	kfree(end_io_wq);
1743bc1e79acSKent Overstreet 	bio_endio_nodec(bio, error);
1744ce9adaa5SChris Mason }
174544b8bd7eSChris Mason 
1746a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1747a74a4b97SChris Mason {
1748a74a4b97SChris Mason 	struct btrfs_root *root = arg;
1749d0278245SMiao Xie 	int again;
1750a74a4b97SChris Mason 
1751a74a4b97SChris Mason 	do {
1752d0278245SMiao Xie 		again = 0;
17539d1a2a3aSDavid Sterba 
1754d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
1755babbf170SMiao Xie 		if (btrfs_need_cleaner_sleep(root))
1756d0278245SMiao Xie 			goto sleep;
1757d0278245SMiao Xie 
1758d0278245SMiao Xie 		if (!mutex_trylock(&root->fs_info->cleaner_mutex))
1759d0278245SMiao Xie 			goto sleep;
1760d0278245SMiao Xie 
1761dc7f370cSMiao Xie 		/*
1762dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1763dc7f370cSMiao Xie 		 * during the above check and trylock.
1764dc7f370cSMiao Xie 		 */
1765babbf170SMiao Xie 		if (btrfs_need_cleaner_sleep(root)) {
1766dc7f370cSMiao Xie 			mutex_unlock(&root->fs_info->cleaner_mutex);
1767dc7f370cSMiao Xie 			goto sleep;
1768dc7f370cSMiao Xie 		}
1769dc7f370cSMiao Xie 
177024bbcf04SYan, Zheng 		btrfs_run_delayed_iputs(root);
17719d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
1772a74a4b97SChris Mason 		mutex_unlock(&root->fs_info->cleaner_mutex);
1773a74a4b97SChris Mason 
1774d0278245SMiao Xie 		/*
177505323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
177605323cd1SMiao Xie 		 * needn't do anything special here.
1777d0278245SMiao Xie 		 */
1778d0278245SMiao Xie 		btrfs_run_defrag_inodes(root->fs_info);
1779d0278245SMiao Xie sleep:
17809d1a2a3aSDavid Sterba 		if (!try_to_freeze() && !again) {
1781a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
17828929ecfaSYan, Zheng 			if (!kthread_should_stop())
1783a74a4b97SChris Mason 				schedule();
1784a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1785a74a4b97SChris Mason 		}
1786a74a4b97SChris Mason 	} while (!kthread_should_stop());
1787a74a4b97SChris Mason 	return 0;
1788a74a4b97SChris Mason }
1789a74a4b97SChris Mason 
1790a74a4b97SChris Mason static int transaction_kthread(void *arg)
1791a74a4b97SChris Mason {
1792a74a4b97SChris Mason 	struct btrfs_root *root = arg;
1793a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1794a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17958929ecfaSYan, Zheng 	u64 transid;
1796a74a4b97SChris Mason 	unsigned long now;
1797a74a4b97SChris Mason 	unsigned long delay;
1798914b2007SJan Kara 	bool cannot_commit;
1799a74a4b97SChris Mason 
1800a74a4b97SChris Mason 	do {
1801914b2007SJan Kara 		cannot_commit = false;
18028b87dc17SDavid Sterba 		delay = HZ * root->fs_info->commit_interval;
1803a74a4b97SChris Mason 		mutex_lock(&root->fs_info->transaction_kthread_mutex);
1804a74a4b97SChris Mason 
1805a4abeea4SJosef Bacik 		spin_lock(&root->fs_info->trans_lock);
1806a74a4b97SChris Mason 		cur = root->fs_info->running_transaction;
1807a74a4b97SChris Mason 		if (!cur) {
1808a4abeea4SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
1809a74a4b97SChris Mason 			goto sleep;
1810a74a4b97SChris Mason 		}
181131153d81SYan Zheng 
1812a74a4b97SChris Mason 		now = get_seconds();
18134a9d8bdeSMiao Xie 		if (cur->state < TRANS_STATE_BLOCKED &&
18148b87dc17SDavid Sterba 		    (now < cur->start_time ||
18158b87dc17SDavid Sterba 		     now - cur->start_time < root->fs_info->commit_interval)) {
1816a4abeea4SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
1817a74a4b97SChris Mason 			delay = HZ * 5;
1818a74a4b97SChris Mason 			goto sleep;
1819a74a4b97SChris Mason 		}
18208929ecfaSYan, Zheng 		transid = cur->transid;
1821a4abeea4SJosef Bacik 		spin_unlock(&root->fs_info->trans_lock);
182256bec294SChris Mason 
182379787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1824354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1825914b2007SJan Kara 		if (IS_ERR(trans)) {
1826354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1827914b2007SJan Kara 				cannot_commit = true;
182879787eaaSJeff Mahoney 			goto sleep;
1829914b2007SJan Kara 		}
18308929ecfaSYan, Zheng 		if (transid == trans->transid) {
183179787eaaSJeff Mahoney 			btrfs_commit_transaction(trans, root);
18328929ecfaSYan, Zheng 		} else {
18338929ecfaSYan, Zheng 			btrfs_end_transaction(trans, root);
18348929ecfaSYan, Zheng 		}
1835a74a4b97SChris Mason sleep:
1836a74a4b97SChris Mason 		wake_up_process(root->fs_info->cleaner_kthread);
1837a74a4b97SChris Mason 		mutex_unlock(&root->fs_info->transaction_kthread_mutex);
1838a74a4b97SChris Mason 
18394e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
18404e121c06SJosef Bacik 				      &root->fs_info->fs_state)))
18414e121c06SJosef Bacik 			btrfs_cleanup_transaction(root);
1842a0acae0eSTejun Heo 		if (!try_to_freeze()) {
1843a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
18448929ecfaSYan, Zheng 			if (!kthread_should_stop() &&
1845914b2007SJan Kara 			    (!btrfs_transaction_blocked(root->fs_info) ||
1846914b2007SJan Kara 			     cannot_commit))
1847a74a4b97SChris Mason 				schedule_timeout(delay);
1848a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1849a74a4b97SChris Mason 		}
1850a74a4b97SChris Mason 	} while (!kthread_should_stop());
1851a74a4b97SChris Mason 	return 0;
1852a74a4b97SChris Mason }
1853a74a4b97SChris Mason 
1854af31f5e5SChris Mason /*
1855af31f5e5SChris Mason  * this will find the highest generation in the array of
1856af31f5e5SChris Mason  * root backups.  The index of the highest array is returned,
1857af31f5e5SChris Mason  * or -1 if we can't find anything.
1858af31f5e5SChris Mason  *
1859af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1860af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1861af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1862af31f5e5SChris Mason  */
1863af31f5e5SChris Mason static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1864af31f5e5SChris Mason {
1865af31f5e5SChris Mason 	u64 cur;
1866af31f5e5SChris Mason 	int newest_index = -1;
1867af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1868af31f5e5SChris Mason 	int i;
1869af31f5e5SChris Mason 
1870af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1871af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1872af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1873af31f5e5SChris Mason 		if (cur == newest_gen)
1874af31f5e5SChris Mason 			newest_index = i;
1875af31f5e5SChris Mason 	}
1876af31f5e5SChris Mason 
1877af31f5e5SChris Mason 	/* check to see if we actually wrapped around */
1878af31f5e5SChris Mason 	if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1879af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots;
1880af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1881af31f5e5SChris Mason 		if (cur == newest_gen)
1882af31f5e5SChris Mason 			newest_index = 0;
1883af31f5e5SChris Mason 	}
1884af31f5e5SChris Mason 	return newest_index;
1885af31f5e5SChris Mason }
1886af31f5e5SChris Mason 
1887af31f5e5SChris Mason 
1888af31f5e5SChris Mason /*
1889af31f5e5SChris Mason  * find the oldest backup so we know where to store new entries
1890af31f5e5SChris Mason  * in the backup array.  This will set the backup_root_index
1891af31f5e5SChris Mason  * field in the fs_info struct
1892af31f5e5SChris Mason  */
1893af31f5e5SChris Mason static void find_oldest_super_backup(struct btrfs_fs_info *info,
1894af31f5e5SChris Mason 				     u64 newest_gen)
1895af31f5e5SChris Mason {
1896af31f5e5SChris Mason 	int newest_index = -1;
1897af31f5e5SChris Mason 
1898af31f5e5SChris Mason 	newest_index = find_newest_super_backup(info, newest_gen);
1899af31f5e5SChris Mason 	/* if there was garbage in there, just move along */
1900af31f5e5SChris Mason 	if (newest_index == -1) {
1901af31f5e5SChris Mason 		info->backup_root_index = 0;
1902af31f5e5SChris Mason 	} else {
1903af31f5e5SChris Mason 		info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1904af31f5e5SChris Mason 	}
1905af31f5e5SChris Mason }
1906af31f5e5SChris Mason 
1907af31f5e5SChris Mason /*
1908af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1909af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1910af31f5e5SChris Mason  * done
1911af31f5e5SChris Mason  */
1912af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1913af31f5e5SChris Mason {
1914af31f5e5SChris Mason 	int next_backup;
1915af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1916af31f5e5SChris Mason 	int last_backup;
1917af31f5e5SChris Mason 
1918af31f5e5SChris Mason 	next_backup = info->backup_root_index;
1919af31f5e5SChris Mason 	last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1920af31f5e5SChris Mason 		BTRFS_NUM_BACKUP_ROOTS;
1921af31f5e5SChris Mason 
1922af31f5e5SChris Mason 	/*
1923af31f5e5SChris Mason 	 * just overwrite the last backup if we're at the same generation
1924af31f5e5SChris Mason 	 * this happens only at umount
1925af31f5e5SChris Mason 	 */
1926af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + last_backup;
1927af31f5e5SChris Mason 	if (btrfs_backup_tree_root_gen(root_backup) ==
1928af31f5e5SChris Mason 	    btrfs_header_generation(info->tree_root->node))
1929af31f5e5SChris Mason 		next_backup = last_backup;
1930af31f5e5SChris Mason 
1931af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1932af31f5e5SChris Mason 
1933af31f5e5SChris Mason 	/*
1934af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1935af31f5e5SChris Mason 	 * regardless of which ones we use today
1936af31f5e5SChris Mason 	 */
1937af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1938af31f5e5SChris Mason 
1939af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1940af31f5e5SChris Mason 
1941af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1942af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1943af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1944af31f5e5SChris Mason 
1945af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1946af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1947af31f5e5SChris Mason 
1948af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1949af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1950af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1951af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1952af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1953af31f5e5SChris Mason 
1954af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1955af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1956af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1957af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1958af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1959af31f5e5SChris Mason 
19607c7e82a7SChris Mason 	/*
19617c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
19627c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
19637c7e82a7SChris Mason 	 */
19647c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
19657c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
19667c7e82a7SChris Mason 					 info->fs_root->node->start);
1967af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1968af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1969af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1970af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19717c7e82a7SChris Mason 	}
1972af31f5e5SChris Mason 
1973af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1974af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1975af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1976af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1977af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1978af31f5e5SChris Mason 
1979af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1980af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1981af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1982af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1983af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1984af31f5e5SChris Mason 
1985af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1986af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1987af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1988af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1989af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1990af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1991af31f5e5SChris Mason 
1992af31f5e5SChris Mason 	/*
1993af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1994af31f5e5SChris Mason 	 * for the next commit
1995af31f5e5SChris Mason 	 */
1996af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1997af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1998af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1999af31f5e5SChris Mason }
2000af31f5e5SChris Mason 
2001af31f5e5SChris Mason /*
2002af31f5e5SChris Mason  * this copies info out of the root backup array and back into
2003af31f5e5SChris Mason  * the in-memory super block.  It is meant to help iterate through
2004af31f5e5SChris Mason  * the array, so you send it the number of backups you've already
2005af31f5e5SChris Mason  * tried and the last backup index you used.
2006af31f5e5SChris Mason  *
2007af31f5e5SChris Mason  * this returns -1 when it has tried all the backups
2008af31f5e5SChris Mason  */
2009af31f5e5SChris Mason static noinline int next_root_backup(struct btrfs_fs_info *info,
2010af31f5e5SChris Mason 				     struct btrfs_super_block *super,
2011af31f5e5SChris Mason 				     int *num_backups_tried, int *backup_index)
2012af31f5e5SChris Mason {
2013af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2014af31f5e5SChris Mason 	int newest = *backup_index;
2015af31f5e5SChris Mason 
2016af31f5e5SChris Mason 	if (*num_backups_tried == 0) {
2017af31f5e5SChris Mason 		u64 gen = btrfs_super_generation(super);
2018af31f5e5SChris Mason 
2019af31f5e5SChris Mason 		newest = find_newest_super_backup(info, gen);
2020af31f5e5SChris Mason 		if (newest == -1)
2021af31f5e5SChris Mason 			return -1;
2022af31f5e5SChris Mason 
2023af31f5e5SChris Mason 		*backup_index = newest;
2024af31f5e5SChris Mason 		*num_backups_tried = 1;
2025af31f5e5SChris Mason 	} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2026af31f5e5SChris Mason 		/* we've tried all the backups, all done */
2027af31f5e5SChris Mason 		return -1;
2028af31f5e5SChris Mason 	} else {
2029af31f5e5SChris Mason 		/* jump to the next oldest backup */
2030af31f5e5SChris Mason 		newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2031af31f5e5SChris Mason 			BTRFS_NUM_BACKUP_ROOTS;
2032af31f5e5SChris Mason 		*backup_index = newest;
2033af31f5e5SChris Mason 		*num_backups_tried += 1;
2034af31f5e5SChris Mason 	}
2035af31f5e5SChris Mason 	root_backup = super->super_roots + newest;
2036af31f5e5SChris Mason 
2037af31f5e5SChris Mason 	btrfs_set_super_generation(super,
2038af31f5e5SChris Mason 				   btrfs_backup_tree_root_gen(root_backup));
2039af31f5e5SChris Mason 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2040af31f5e5SChris Mason 	btrfs_set_super_root_level(super,
2041af31f5e5SChris Mason 				   btrfs_backup_tree_root_level(root_backup));
2042af31f5e5SChris Mason 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2043af31f5e5SChris Mason 
2044af31f5e5SChris Mason 	/*
2045af31f5e5SChris Mason 	 * fixme: the total bytes and num_devices need to match or we should
2046af31f5e5SChris Mason 	 * need a fsck
2047af31f5e5SChris Mason 	 */
2048af31f5e5SChris Mason 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2049af31f5e5SChris Mason 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2050af31f5e5SChris Mason 	return 0;
2051af31f5e5SChris Mason }
2052af31f5e5SChris Mason 
20537abadb64SLiu Bo /* helper to cleanup workers */
20547abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20557abadb64SLiu Bo {
2056dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2057afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
20585cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2059fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2060fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2061fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2062d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2063fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2064fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2065fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2066a8c93d4eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->submit_workers);
20675b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2068e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2069736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2070a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2071fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2072a79b7d4bSChris Mason 	btrfs_destroy_workqueue(fs_info->extent_workers);
20737abadb64SLiu Bo }
20747abadb64SLiu Bo 
20752e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20762e9f5954SRashika {
20772e9f5954SRashika 	if (root) {
20782e9f5954SRashika 		free_extent_buffer(root->node);
20792e9f5954SRashika 		free_extent_buffer(root->commit_root);
20802e9f5954SRashika 		root->node = NULL;
20812e9f5954SRashika 		root->commit_root = NULL;
20822e9f5954SRashika 	}
20832e9f5954SRashika }
20842e9f5954SRashika 
2085af31f5e5SChris Mason /* helper to cleanup tree roots */
2086af31f5e5SChris Mason static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2087af31f5e5SChris Mason {
20882e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2089655b09feSJosef Bacik 
20902e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
20912e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
20922e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
20932e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20942e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20952e9f5954SRashika 	if (chunk_root)
20962e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2097af31f5e5SChris Mason }
2098af31f5e5SChris Mason 
2099faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2100171f6537SJosef Bacik {
2101171f6537SJosef Bacik 	int ret;
2102171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2103171f6537SJosef Bacik 	int i;
2104171f6537SJosef Bacik 
2105171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2106171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2107171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2108171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2109171f6537SJosef Bacik 
211027cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2111cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2112171f6537SJosef Bacik 		} else {
2113171f6537SJosef Bacik 			free_extent_buffer(gang[0]->node);
2114171f6537SJosef Bacik 			free_extent_buffer(gang[0]->commit_root);
2115b0feb9d9SMiao Xie 			btrfs_put_fs_root(gang[0]);
2116171f6537SJosef Bacik 		}
2117171f6537SJosef Bacik 	}
2118171f6537SJosef Bacik 
2119171f6537SJosef Bacik 	while (1) {
2120171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2121171f6537SJosef Bacik 					     (void **)gang, 0,
2122171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2123171f6537SJosef Bacik 		if (!ret)
2124171f6537SJosef Bacik 			break;
2125171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2126cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2127171f6537SJosef Bacik 	}
21281a4319ccSLiu Bo 
21291a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
21301a4319ccSLiu Bo 		btrfs_free_log_root_tree(NULL, fs_info);
21311a4319ccSLiu Bo 		btrfs_destroy_pinned_extent(fs_info->tree_root,
21321a4319ccSLiu Bo 					    fs_info->pinned_extents);
21331a4319ccSLiu Bo 	}
2134171f6537SJosef Bacik }
2135af31f5e5SChris Mason 
2136ad2b2c80SAl Viro int open_ctree(struct super_block *sb,
2137dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
2138dfe25020SChris Mason 	       char *options)
2139eb60ceacSChris Mason {
2140db94535dSChris Mason 	u32 sectorsize;
2141db94535dSChris Mason 	u32 nodesize;
2142db94535dSChris Mason 	u32 blocksize;
214387ee04ebSChris Mason 	u32 stripesize;
214484234f3aSYan Zheng 	u64 generation;
2145f2b636e8SJosef Bacik 	u64 features;
21463de4586cSChris Mason 	struct btrfs_key location;
2147a061fc8dSChris Mason 	struct buffer_head *bh;
21484d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
2149815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2150f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
21514d34b278SIlya Dryomov 	struct btrfs_root *extent_root;
21524d34b278SIlya Dryomov 	struct btrfs_root *csum_root;
21534d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
21544d34b278SIlya Dryomov 	struct btrfs_root *dev_root;
2155bcef60f2SArne Jansen 	struct btrfs_root *quota_root;
2156f7a81ea4SStefan Behrens 	struct btrfs_root *uuid_root;
2157e02119d5SChris Mason 	struct btrfs_root *log_tree_root;
2158eb60ceacSChris Mason 	int ret;
2159e58ca020SYan 	int err = -EINVAL;
2160af31f5e5SChris Mason 	int num_backups_tried = 0;
2161af31f5e5SChris Mason 	int backup_index = 0;
21625cdc7ad3SQu Wenruo 	int max_active;
21635cdc7ad3SQu Wenruo 	int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
216470f80175SStefan Behrens 	bool create_uuid_tree;
216570f80175SStefan Behrens 	bool check_uuid_tree;
21664543df7eSChris Mason 
2167f84a8bd6SAl Viro 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info);
21686f07e42eSAl Viro 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info);
2169cb517eabSMiao Xie 	if (!tree_root || !chunk_root) {
217039279cc3SChris Mason 		err = -ENOMEM;
217139279cc3SChris Mason 		goto fail;
217239279cc3SChris Mason 	}
217376dda93cSYan, Zheng 
217476dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
217576dda93cSYan, Zheng 	if (ret) {
217676dda93cSYan, Zheng 		err = ret;
217776dda93cSYan, Zheng 		goto fail;
217876dda93cSYan, Zheng 	}
217976dda93cSYan, Zheng 
218076dda93cSYan, Zheng 	ret = setup_bdi(fs_info, &fs_info->bdi);
218176dda93cSYan, Zheng 	if (ret) {
218276dda93cSYan, Zheng 		err = ret;
218376dda93cSYan, Zheng 		goto fail_srcu;
218476dda93cSYan, Zheng 	}
218576dda93cSYan, Zheng 
2186e2d84521SMiao Xie 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0);
2187e2d84521SMiao Xie 	if (ret) {
2188e2d84521SMiao Xie 		err = ret;
2189e2d84521SMiao Xie 		goto fail_bdi;
2190e2d84521SMiao Xie 	}
2191e2d84521SMiao Xie 	fs_info->dirty_metadata_batch = PAGE_CACHE_SIZE *
2192e2d84521SMiao Xie 					(1 + ilog2(nr_cpu_ids));
2193e2d84521SMiao Xie 
2194963d678bSMiao Xie 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0);
2195963d678bSMiao Xie 	if (ret) {
2196963d678bSMiao Xie 		err = ret;
2197963d678bSMiao Xie 		goto fail_dirty_metadata_bytes;
2198963d678bSMiao Xie 	}
2199963d678bSMiao Xie 
2200c404e0dcSMiao Xie 	ret = percpu_counter_init(&fs_info->bio_counter, 0);
2201c404e0dcSMiao Xie 	if (ret) {
2202c404e0dcSMiao Xie 		err = ret;
2203c404e0dcSMiao Xie 		goto fail_delalloc_bytes;
2204c404e0dcSMiao Xie 	}
2205c404e0dcSMiao Xie 
220676dda93cSYan, Zheng 	fs_info->btree_inode = new_inode(sb);
220776dda93cSYan, Zheng 	if (!fs_info->btree_inode) {
220876dda93cSYan, Zheng 		err = -ENOMEM;
2209c404e0dcSMiao Xie 		goto fail_bio_counter;
221076dda93cSYan, Zheng 	}
221176dda93cSYan, Zheng 
2212a6591715SChris Mason 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
22131561dedaSMiao Xie 
221476dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2215f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
22168fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2217facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
221824bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2219eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
222011833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2221eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2222a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
222376dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
222424bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
22254cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
22262bf64758SJosef Bacik 	spin_lock_init(&fs_info->free_chunk_lock);
2227f29021b2SJan Schmidt 	spin_lock_init(&fs_info->tree_mod_seq_lock);
2228ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2229fcebe456SJosef Bacik 	spin_lock_init(&fs_info->qgroup_op_lock);
2230f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
2231f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
22327585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2233573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2234de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
223519c00ddcSChris Mason 
223658176a96SJosef Bacik 	init_completion(&fs_info->kobj_unregister);
22370b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
22386324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2239f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
22400b86a832SChris Mason 	btrfs_mapping_init(&fs_info->mapping_tree);
224166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
224266d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
224366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delalloc_block_rsv,
224466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELALLOC);
224566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
224666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
224766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
224866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
224966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2250cb03c743SChris Mason 	atomic_set(&fs_info->nr_async_submits, 0);
2251771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
22528c8bee1dSChris Mason 	atomic_set(&fs_info->async_submit_draining, 0);
22530986fe9eSChris Mason 	atomic_set(&fs_info->nr_async_bios, 0);
22544cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2255fcebe456SJosef Bacik 	atomic_set(&fs_info->qgroup_op_seq, 0);
2256fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2257e20d96d6SChris Mason 	fs_info->sb = sb;
22586f568d35SChris Mason 	fs_info->max_inline = 8192 * 1024;
22599ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
22604cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
22612bf64758SJosef Bacik 	fs_info->free_chunk_space = 0;
2262f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
22638b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
22640a2b2a84SJosef Bacik 	fs_info->avg_delayed_ref_runtime = div64_u64(NSEC_PER_SEC, 64);
226590519d66SArne Jansen 	/* readahead state */
226690519d66SArne Jansen 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_WAIT);
226790519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2268c8b97818SChris Mason 
2269b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2270b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
22710afbaf8cSChris Mason 
2272199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2273199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
227416cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
227516cdcec7SMiao Xie 					GFP_NOFS);
227616cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
227716cdcec7SMiao Xie 		err = -ENOMEM;
227816cdcec7SMiao Xie 		goto fail_iput;
227916cdcec7SMiao Xie 	}
228016cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
22813eaa2885SChris Mason 
2282a2de733cSArne Jansen 	mutex_init(&fs_info->scrub_lock);
2283a2de733cSArne Jansen 	atomic_set(&fs_info->scrubs_running, 0);
2284a2de733cSArne Jansen 	atomic_set(&fs_info->scrub_pause_req, 0);
2285a2de733cSArne Jansen 	atomic_set(&fs_info->scrubs_paused, 0);
2286a2de733cSArne Jansen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2287c404e0dcSMiao Xie 	init_waitqueue_head(&fs_info->replace_wait);
2288a2de733cSArne Jansen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2289a2de733cSArne Jansen 	fs_info->scrub_workers_refcnt = 0;
229021adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
229121adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
229221adbd5cSStefan Behrens #endif
2293a2de733cSArne Jansen 
2294c9e9f97bSIlya Dryomov 	spin_lock_init(&fs_info->balance_lock);
2295c9e9f97bSIlya Dryomov 	mutex_init(&fs_info->balance_mutex);
2296837d5b6eSIlya Dryomov 	atomic_set(&fs_info->balance_running, 0);
2297837d5b6eSIlya Dryomov 	atomic_set(&fs_info->balance_pause_req, 0);
2298a7e99c69SIlya Dryomov 	atomic_set(&fs_info->balance_cancel_req, 0);
2299c9e9f97bSIlya Dryomov 	fs_info->balance_ctl = NULL;
2300837d5b6eSIlya Dryomov 	init_waitqueue_head(&fs_info->balance_wait_q);
230121c7e756SMiao Xie 	btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2302a061fc8dSChris Mason 
23030afbaf8cSChris Mason 	sb->s_blocksize = 4096;
23040afbaf8cSChris Mason 	sb->s_blocksize_bits = blksize_bits(4096);
230532a88aa1SJens Axboe 	sb->s_bdi = &fs_info->bdi;
23060afbaf8cSChris Mason 
230776dda93cSYan, Zheng 	fs_info->btree_inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2308bfe86848SMiklos Szeredi 	set_nlink(fs_info->btree_inode, 1);
23090afbaf8cSChris Mason 	/*
23100afbaf8cSChris Mason 	 * we set the i_size on the btree inode to the max possible int.
23110afbaf8cSChris Mason 	 * the real end of the address space is determined by all of
23120afbaf8cSChris Mason 	 * the devices in the system
23130afbaf8cSChris Mason 	 */
23140afbaf8cSChris Mason 	fs_info->btree_inode->i_size = OFFSET_MAX;
2315d98237b3SChris Mason 	fs_info->btree_inode->i_mapping->a_ops = &btree_aops;
231604160088SChris Mason 	fs_info->btree_inode->i_mapping->backing_dev_info = &fs_info->bdi;
231704160088SChris Mason 
23185d4f98a2SYan Zheng 	RB_CLEAR_NODE(&BTRFS_I(fs_info->btree_inode)->rb_node);
2319d1310b2eSChris Mason 	extent_io_tree_init(&BTRFS_I(fs_info->btree_inode)->io_tree,
2320f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
23210b32f4bbSJosef Bacik 	BTRFS_I(fs_info->btree_inode)->io_tree.track_uptodate = 0;
2322a8067e02SDavid Sterba 	extent_map_tree_init(&BTRFS_I(fs_info->btree_inode)->extent_tree);
23230da5468fSChris Mason 
2324d1310b2eSChris Mason 	BTRFS_I(fs_info->btree_inode)->io_tree.ops = &btree_extent_io_ops;
2325d1310b2eSChris Mason 
23260f7d52f4SChris Mason 	BTRFS_I(fs_info->btree_inode)->root = tree_root;
23270f7d52f4SChris Mason 	memset(&BTRFS_I(fs_info->btree_inode)->location, 0,
23280f7d52f4SChris Mason 	       sizeof(struct btrfs_key));
232972ac3c0dSJosef Bacik 	set_bit(BTRFS_INODE_DUMMY,
233072ac3c0dSJosef Bacik 		&BTRFS_I(fs_info->btree_inode)->runtime_flags);
2331778ba82bSFilipe David Borba Manana 	btrfs_insert_inode_hash(fs_info->btree_inode);
233239279cc3SChris Mason 
2333e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
23346bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2335a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
2336925baeddSChris Mason 
233711833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[0],
2338f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
233911833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[1],
2340f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
234111833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2342e6dcd2dcSChris Mason 	fs_info->do_barriers = 1;
2343f9295749SChris Mason 
2344d98237b3SChris Mason 
23455a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
23469ffba8cdSJosef Bacik 	mutex_init(&fs_info->ordered_extent_flush_mutex);
234730ae8467SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2348925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2349925baeddSChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2350a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
2351a74a4b97SChris Mason 	mutex_init(&fs_info->volume_mutex);
23529e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2353c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
235476dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2355803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2356e922e087SStefan Behrens 	fs_info->dev_replace.lock_owner = 0;
2357e922e087SStefan Behrens 	atomic_set(&fs_info->dev_replace.nesting_level, 0);
2358e922e087SStefan Behrens 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2359e922e087SStefan Behrens 	mutex_init(&fs_info->dev_replace.lock_management_lock);
2360e922e087SStefan Behrens 	mutex_init(&fs_info->dev_replace.lock);
2361fa9c0d79SChris Mason 
2362416ac51dSArne Jansen 	spin_lock_init(&fs_info->qgroup_lock);
2363f2f6ed3dSWang Shilong 	mutex_init(&fs_info->qgroup_ioctl_lock);
2364416ac51dSArne Jansen 	fs_info->qgroup_tree = RB_ROOT;
2365fcebe456SJosef Bacik 	fs_info->qgroup_op_tree = RB_ROOT;
2366416ac51dSArne Jansen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2367416ac51dSArne Jansen 	fs_info->qgroup_seq = 1;
2368416ac51dSArne Jansen 	fs_info->quota_enabled = 0;
2369416ac51dSArne Jansen 	fs_info->pending_quota_state = 0;
23701e8f9158SWang Shilong 	fs_info->qgroup_ulist = NULL;
23712f232036SJan Schmidt 	mutex_init(&fs_info->qgroup_rescan_lock);
2372416ac51dSArne Jansen 
2373fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2374fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2375fa9c0d79SChris Mason 
23767d9eb12cSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
23773768f368SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2378bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
23794854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
23809a8dd150SChris Mason 
238153b381b3SDavid Woodhouse 	ret = btrfs_alloc_stripe_hash_table(fs_info);
238253b381b3SDavid Woodhouse 	if (ret) {
238383c8266aSDavid Sterba 		err = ret;
238453b381b3SDavid Woodhouse 		goto fail_alloc;
238553b381b3SDavid Woodhouse 	}
238653b381b3SDavid Woodhouse 
2387707e8a07SDavid Sterba 	__setup_root(4096, 4096, 4096, tree_root,
23882c90e5d6SChris Mason 		     fs_info, BTRFS_ROOT_TREE_OBJECTID);
23897eccb903SChris Mason 
23903c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
23911104a885SDavid Sterba 
23921104a885SDavid Sterba 	/*
23931104a885SDavid Sterba 	 * Read super block and check the signature bytes only
23941104a885SDavid Sterba 	 */
2395a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
239620b45077SDave Young 	if (!bh) {
239720b45077SDave Young 		err = -EINVAL;
239816cdcec7SMiao Xie 		goto fail_alloc;
239920b45077SDave Young 	}
240039279cc3SChris Mason 
24011104a885SDavid Sterba 	/*
24021104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
24031104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
24041104a885SDavid Sterba 	 */
24051104a885SDavid Sterba 	if (btrfs_check_super_csum(bh->b_data)) {
2406efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: superblock checksum mismatch\n");
24071104a885SDavid Sterba 		err = -EINVAL;
24081104a885SDavid Sterba 		goto fail_alloc;
24091104a885SDavid Sterba 	}
24101104a885SDavid Sterba 
24111104a885SDavid Sterba 	/*
24121104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
24131104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
24141104a885SDavid Sterba 	 * the whole block of INFO_SIZE
24151104a885SDavid Sterba 	 */
24166c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
24176c41761fSDavid Sterba 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
24186c41761fSDavid Sterba 	       sizeof(*fs_info->super_for_commit));
2419a061fc8dSChris Mason 	brelse(bh);
24205f39d397SChris Mason 
24216c41761fSDavid Sterba 	memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
24220b86a832SChris Mason 
24231104a885SDavid Sterba 	ret = btrfs_check_super_valid(fs_info, sb->s_flags & MS_RDONLY);
24241104a885SDavid Sterba 	if (ret) {
2425efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: superblock contains fatal errors\n");
24261104a885SDavid Sterba 		err = -EINVAL;
24271104a885SDavid Sterba 		goto fail_alloc;
24281104a885SDavid Sterba 	}
24291104a885SDavid Sterba 
24306c41761fSDavid Sterba 	disk_super = fs_info->super_copy;
24310f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
243216cdcec7SMiao Xie 		goto fail_alloc;
24330f7d52f4SChris Mason 
2434acce952bSliubo 	/* check FS state, whether FS is broken. */
243587533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
243687533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2437acce952bSliubo 
243875e7cb7fSLiu Bo 	/*
2439af31f5e5SChris Mason 	 * run through our array of backup supers and setup
2440af31f5e5SChris Mason 	 * our ring pointer to the oldest one
2441af31f5e5SChris Mason 	 */
2442af31f5e5SChris Mason 	generation = btrfs_super_generation(disk_super);
2443af31f5e5SChris Mason 	find_oldest_super_backup(fs_info, generation);
2444af31f5e5SChris Mason 
2445af31f5e5SChris Mason 	/*
244675e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
244775e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
244875e7cb7fSLiu Bo 	 */
244975e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
245075e7cb7fSLiu Bo 
24512b82032cSYan Zheng 	ret = btrfs_parse_options(tree_root, options);
24522b82032cSYan Zheng 	if (ret) {
24532b82032cSYan Zheng 		err = ret;
245416cdcec7SMiao Xie 		goto fail_alloc;
24552b82032cSYan Zheng 	}
2456dfe25020SChris Mason 
2457f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2458f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2459f2b636e8SJosef Bacik 	if (features) {
2460f2b636e8SJosef Bacik 		printk(KERN_ERR "BTRFS: couldn't mount because of "
2461f2b636e8SJosef Bacik 		       "unsupported optional features (%Lx).\n",
2462c1c9ff7cSGeert Uytterhoeven 		       features);
2463f2b636e8SJosef Bacik 		err = -EINVAL;
246416cdcec7SMiao Xie 		goto fail_alloc;
2465f2b636e8SJosef Bacik 	}
2466f2b636e8SJosef Bacik 
2467707e8a07SDavid Sterba 	/*
2468707e8a07SDavid Sterba 	 * Leafsize and nodesize were always equal, this is only a sanity check.
2469707e8a07SDavid Sterba 	 */
2470707e8a07SDavid Sterba 	if (le32_to_cpu(disk_super->__unused_leafsize) !=
2471727011e0SChris Mason 	    btrfs_super_nodesize(disk_super)) {
2472727011e0SChris Mason 		printk(KERN_ERR "BTRFS: couldn't mount because metadata "
2473727011e0SChris Mason 		       "blocksizes don't match.  node %d leaf %d\n",
2474727011e0SChris Mason 		       btrfs_super_nodesize(disk_super),
2475707e8a07SDavid Sterba 		       le32_to_cpu(disk_super->__unused_leafsize));
2476727011e0SChris Mason 		err = -EINVAL;
2477727011e0SChris Mason 		goto fail_alloc;
2478727011e0SChris Mason 	}
2479707e8a07SDavid Sterba 	if (btrfs_super_nodesize(disk_super) > BTRFS_MAX_METADATA_BLOCKSIZE) {
2480727011e0SChris Mason 		printk(KERN_ERR "BTRFS: couldn't mount because metadata "
2481727011e0SChris Mason 		       "blocksize (%d) was too large\n",
2482707e8a07SDavid Sterba 		       btrfs_super_nodesize(disk_super));
2483727011e0SChris Mason 		err = -EINVAL;
2484727011e0SChris Mason 		goto fail_alloc;
2485727011e0SChris Mason 	}
2486727011e0SChris Mason 
24875d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
24885d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
248969e380d1SLi Zefan 	if (tree_root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
2490a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2491727011e0SChris Mason 
24923173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2493efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: has skinny extents\n");
24943173a18fSJosef Bacik 
2495727011e0SChris Mason 	/*
2496727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2497727011e0SChris Mason 	 * they are bigger than the page size
2498727011e0SChris Mason 	 */
2499707e8a07SDavid Sterba 	if (btrfs_super_nodesize(disk_super) > PAGE_CACHE_SIZE) {
2500727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2501efe120a0SFrank Holton 			printk(KERN_INFO "BTRFS: flagging fs with big metadata feature\n");
2502727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2503727011e0SChris Mason 	}
2504727011e0SChris Mason 
2505bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2506bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2507bc3f116fSChris Mason 	stripesize = btrfs_super_stripesize(disk_super);
2508707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2509963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2510bc3f116fSChris Mason 
2511bc3f116fSChris Mason 	/*
2512bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2513bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2514bc3f116fSChris Mason 	 */
2515bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2516707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
2517efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: unequal leaf/node/sector sizes "
2518bc3f116fSChris Mason 				"are not allowed for mixed block groups on %s\n",
2519bc3f116fSChris Mason 				sb->s_id);
2520bc3f116fSChris Mason 		goto fail_alloc;
2521bc3f116fSChris Mason 	}
2522bc3f116fSChris Mason 
2523ceda0864SMiao Xie 	/*
2524ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
2525ceda0864SMiao Xie 	 * update the flag.
2526ceda0864SMiao Xie 	 */
25275d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
25285d4f98a2SYan Zheng 
2529f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2530f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2531f2b636e8SJosef Bacik 	if (!(sb->s_flags & MS_RDONLY) && features) {
2532f2b636e8SJosef Bacik 		printk(KERN_ERR "BTRFS: couldn't mount RDWR because of "
2533f2b636e8SJosef Bacik 		       "unsupported option features (%Lx).\n",
2534c1c9ff7cSGeert Uytterhoeven 		       features);
2535f2b636e8SJosef Bacik 		err = -EINVAL;
253616cdcec7SMiao Xie 		goto fail_alloc;
2537f2b636e8SJosef Bacik 	}
253861d92c32SChris Mason 
25395cdc7ad3SQu Wenruo 	max_active = fs_info->thread_pool_size;
254061d92c32SChris Mason 
25415cdc7ad3SQu Wenruo 	fs_info->workers =
25425cdc7ad3SQu Wenruo 		btrfs_alloc_workqueue("worker", flags | WQ_HIGHPRI,
25435cdc7ad3SQu Wenruo 				      max_active, 16);
2544c8b97818SChris Mason 
2545afe3d242SQu Wenruo 	fs_info->delalloc_workers =
2546afe3d242SQu Wenruo 		btrfs_alloc_workqueue("delalloc", flags, max_active, 2);
2547771ed689SChris Mason 
2548a44903abSQu Wenruo 	fs_info->flush_workers =
2549a44903abSQu Wenruo 		btrfs_alloc_workqueue("flush_delalloc", flags, max_active, 0);
25508ccf6f19SMiao Xie 
2551e66f0bb1SQu Wenruo 	fs_info->caching_workers =
2552e66f0bb1SQu Wenruo 		btrfs_alloc_workqueue("cache", flags, max_active, 0);
255361b49440SChris Mason 
2554a8c93d4eSQu Wenruo 	/*
2555a8c93d4eSQu Wenruo 	 * a higher idle thresh on the submit workers makes it much more
255661b49440SChris Mason 	 * likely that bios will be send down in a sane order to the
255761b49440SChris Mason 	 * devices
255861b49440SChris Mason 	 */
2559a8c93d4eSQu Wenruo 	fs_info->submit_workers =
2560a8c93d4eSQu Wenruo 		btrfs_alloc_workqueue("submit", flags,
2561a8c93d4eSQu Wenruo 				      min_t(u64, fs_devices->num_devices,
2562a8c93d4eSQu Wenruo 					    max_active), 64);
256353863232SChris Mason 
2564dc6e3209SQu Wenruo 	fs_info->fixup_workers =
2565dc6e3209SQu Wenruo 		btrfs_alloc_workqueue("fixup", flags, 1, 0);
256661b49440SChris Mason 
256761b49440SChris Mason 	/*
256861b49440SChris Mason 	 * endios are largely parallel and should have a very
256961b49440SChris Mason 	 * low idle thresh
257061b49440SChris Mason 	 */
2571fccb5d86SQu Wenruo 	fs_info->endio_workers =
2572fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("endio", flags, max_active, 4);
2573fccb5d86SQu Wenruo 	fs_info->endio_meta_workers =
2574fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("endio-meta", flags, max_active, 4);
2575fccb5d86SQu Wenruo 	fs_info->endio_meta_write_workers =
2576fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("endio-meta-write", flags, max_active, 2);
2577fccb5d86SQu Wenruo 	fs_info->endio_raid56_workers =
2578fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("endio-raid56", flags, max_active, 4);
2579d05a33acSQu Wenruo 	fs_info->rmw_workers =
2580d05a33acSQu Wenruo 		btrfs_alloc_workqueue("rmw", flags, max_active, 2);
2581fccb5d86SQu Wenruo 	fs_info->endio_write_workers =
2582fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("endio-write", flags, max_active, 2);
2583fccb5d86SQu Wenruo 	fs_info->endio_freespace_worker =
2584fccb5d86SQu Wenruo 		btrfs_alloc_workqueue("freespace-write", flags, max_active, 0);
25855b3bc44eSQu Wenruo 	fs_info->delayed_workers =
25865b3bc44eSQu Wenruo 		btrfs_alloc_workqueue("delayed-meta", flags, max_active, 0);
2587736cfa15SQu Wenruo 	fs_info->readahead_workers =
2588736cfa15SQu Wenruo 		btrfs_alloc_workqueue("readahead", flags, max_active, 2);
2589fc97fab0SQu Wenruo 	fs_info->qgroup_rescan_workers =
2590fc97fab0SQu Wenruo 		btrfs_alloc_workqueue("qgroup-rescan", flags, 1, 0);
2591a79b7d4bSChris Mason 	fs_info->extent_workers =
2592a79b7d4bSChris Mason 		btrfs_alloc_workqueue("extent-refs", flags,
2593a79b7d4bSChris Mason 				      min_t(u64, fs_devices->num_devices,
2594a79b7d4bSChris Mason 					    max_active), 8);
2595b51912c9SChris Mason 
2596a8c93d4eSQu Wenruo 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2597fccb5d86SQu Wenruo 	      fs_info->submit_workers && fs_info->flush_workers &&
2598fccb5d86SQu Wenruo 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2599fccb5d86SQu Wenruo 	      fs_info->endio_meta_write_workers &&
2600fccb5d86SQu Wenruo 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2601e66f0bb1SQu Wenruo 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2602dc6e3209SQu Wenruo 	      fs_info->caching_workers && fs_info->readahead_workers &&
2603fc97fab0SQu Wenruo 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2604a79b7d4bSChris Mason 	      fs_info->fixup_workers && fs_info->extent_workers &&
2605fc97fab0SQu Wenruo 	      fs_info->qgroup_rescan_workers)) {
2606fed425c7SIlya Dryomov 		err = -ENOMEM;
26070dc3b84aSJosef Bacik 		goto fail_sb_buffer;
26080dc3b84aSJosef Bacik 	}
26094543df7eSChris Mason 
26104575c9ccSChris Mason 	fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
2611c8b97818SChris Mason 	fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
2612c8b97818SChris Mason 				    4 * 1024 * 1024 / PAGE_CACHE_SIZE);
26134575c9ccSChris Mason 
2614db94535dSChris Mason 	tree_root->nodesize = nodesize;
2615db94535dSChris Mason 	tree_root->sectorsize = sectorsize;
261687ee04ebSChris Mason 	tree_root->stripesize = stripesize;
2617a061fc8dSChris Mason 
2618a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
2619a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
2620db94535dSChris Mason 
26213cae210fSQu Wenruo 	if (btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
2622efe120a0SFrank Holton 		printk(KERN_INFO "BTRFS: valid FS not found on %s\n", sb->s_id);
262339279cc3SChris Mason 		goto fail_sb_buffer;
262439279cc3SChris Mason 	}
262519c00ddcSChris Mason 
26268d082fb7SLiu Bo 	if (sectorsize != PAGE_SIZE) {
2627efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: Incompatible sector size(%lu) "
26288d082fb7SLiu Bo 		       "found on %s\n", (unsigned long)sectorsize, sb->s_id);
2629941b2ddfSKeith Mannthey 		goto fail_sb_buffer;
2630941b2ddfSKeith Mannthey 	}
2631941b2ddfSKeith Mannthey 
2632925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
2633e4404d6eSYan Zheng 	ret = btrfs_read_sys_array(tree_root);
2634925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
263584eed90fSChris Mason 	if (ret) {
2636efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to read the system "
2637d397712bSChris Mason 		       "array on %s\n", sb->s_id);
26385d4f98a2SYan Zheng 		goto fail_sb_buffer;
263984eed90fSChris Mason 	}
26400b86a832SChris Mason 
2641707e8a07SDavid Sterba 	blocksize = tree_root->nodesize;
264284234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
26430b86a832SChris Mason 
2644707e8a07SDavid Sterba 	__setup_root(nodesize, sectorsize, stripesize, chunk_root,
2645707e8a07SDavid Sterba 		     fs_info, BTRFS_CHUNK_TREE_OBJECTID);
26460b86a832SChris Mason 
26470b86a832SChris Mason 	chunk_root->node = read_tree_block(chunk_root,
26480b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
264984234f3aSYan Zheng 					   blocksize, generation);
2650416bc658SJosef Bacik 	if (!chunk_root->node ||
2651416bc658SJosef Bacik 	    !test_bit(EXTENT_BUFFER_UPTODATE, &chunk_root->node->bflags)) {
2652efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to read chunk root on %s\n",
265383121942SDavid Woodhouse 		       sb->s_id);
2654af31f5e5SChris Mason 		goto fail_tree_roots;
265583121942SDavid Woodhouse 	}
26565d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
26575d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
26580b86a832SChris Mason 
2659e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2660b308bc2fSGeert Uytterhoeven 	   btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2661e17cade2SChris Mason 
26620b86a832SChris Mason 	ret = btrfs_read_chunk_tree(chunk_root);
26632b82032cSYan Zheng 	if (ret) {
2664efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to read chunk tree on %s\n",
2665d397712bSChris Mason 		       sb->s_id);
2666af31f5e5SChris Mason 		goto fail_tree_roots;
26672b82032cSYan Zheng 	}
26680b86a832SChris Mason 
26698dabb742SStefan Behrens 	/*
26708dabb742SStefan Behrens 	 * keep the device that is marked to be the target device for the
26718dabb742SStefan Behrens 	 * dev_replace procedure
26728dabb742SStefan Behrens 	 */
26738dabb742SStefan Behrens 	btrfs_close_extra_devices(fs_info, fs_devices, 0);
2674dfe25020SChris Mason 
2675a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
2676efe120a0SFrank Holton 		printk(KERN_CRIT "BTRFS: failed to read devices on %s\n",
2677a6b0d5c8SChris Mason 		       sb->s_id);
2678a6b0d5c8SChris Mason 		goto fail_tree_roots;
2679a6b0d5c8SChris Mason 	}
2680a6b0d5c8SChris Mason 
2681af31f5e5SChris Mason retry_root_backup:
2682707e8a07SDavid Sterba 	blocksize = tree_root->nodesize;
268384234f3aSYan Zheng 	generation = btrfs_super_generation(disk_super);
26840b86a832SChris Mason 
2685e20d96d6SChris Mason 	tree_root->node = read_tree_block(tree_root,
2686db94535dSChris Mason 					  btrfs_super_root(disk_super),
268784234f3aSYan Zheng 					  blocksize, generation);
2688af31f5e5SChris Mason 	if (!tree_root->node ||
2689af31f5e5SChris Mason 	    !test_bit(EXTENT_BUFFER_UPTODATE, &tree_root->node->bflags)) {
2690efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to read tree root on %s\n",
269183121942SDavid Woodhouse 		       sb->s_id);
2692af31f5e5SChris Mason 
2693af31f5e5SChris Mason 		goto recovery_tree_root;
269483121942SDavid Woodhouse 	}
2695af31f5e5SChris Mason 
26965d4f98a2SYan Zheng 	btrfs_set_root_node(&tree_root->root_item, tree_root->node);
26975d4f98a2SYan Zheng 	tree_root->commit_root = btrfs_root_node(tree_root);
269869e9c6c6SStefan Behrens 	btrfs_set_root_refs(&tree_root->root_item, 1);
2699db94535dSChris Mason 
2700cb517eabSMiao Xie 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2701cb517eabSMiao Xie 	location.type = BTRFS_ROOT_ITEM_KEY;
2702cb517eabSMiao Xie 	location.offset = 0;
2703cb517eabSMiao Xie 
2704cb517eabSMiao Xie 	extent_root = btrfs_read_tree_root(tree_root, &location);
2705cb517eabSMiao Xie 	if (IS_ERR(extent_root)) {
2706cb517eabSMiao Xie 		ret = PTR_ERR(extent_root);
2707af31f5e5SChris Mason 		goto recovery_tree_root;
2708cb517eabSMiao Xie 	}
270927cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &extent_root->state);
2710cb517eabSMiao Xie 	fs_info->extent_root = extent_root;
27110b86a832SChris Mason 
2712cb517eabSMiao Xie 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2713cb517eabSMiao Xie 	dev_root = btrfs_read_tree_root(tree_root, &location);
2714cb517eabSMiao Xie 	if (IS_ERR(dev_root)) {
2715cb517eabSMiao Xie 		ret = PTR_ERR(dev_root);
2716af31f5e5SChris Mason 		goto recovery_tree_root;
2717cb517eabSMiao Xie 	}
271827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &dev_root->state);
2719cb517eabSMiao Xie 	fs_info->dev_root = dev_root;
2720cb517eabSMiao Xie 	btrfs_init_devices_late(fs_info);
27213768f368SChris Mason 
2722cb517eabSMiao Xie 	location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2723cb517eabSMiao Xie 	csum_root = btrfs_read_tree_root(tree_root, &location);
2724cb517eabSMiao Xie 	if (IS_ERR(csum_root)) {
2725cb517eabSMiao Xie 		ret = PTR_ERR(csum_root);
2726af31f5e5SChris Mason 		goto recovery_tree_root;
2727cb517eabSMiao Xie 	}
272827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &csum_root->state);
2729cb517eabSMiao Xie 	fs_info->csum_root = csum_root;
2730d20f7043SChris Mason 
2731cb517eabSMiao Xie 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2732cb517eabSMiao Xie 	quota_root = btrfs_read_tree_root(tree_root, &location);
2733cb517eabSMiao Xie 	if (!IS_ERR(quota_root)) {
273427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &quota_root->state);
2735bcef60f2SArne Jansen 		fs_info->quota_enabled = 1;
2736bcef60f2SArne Jansen 		fs_info->pending_quota_state = 1;
2737cb517eabSMiao Xie 		fs_info->quota_root = quota_root;
2738bcef60f2SArne Jansen 	}
2739bcef60f2SArne Jansen 
2740f7a81ea4SStefan Behrens 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2741f7a81ea4SStefan Behrens 	uuid_root = btrfs_read_tree_root(tree_root, &location);
2742f7a81ea4SStefan Behrens 	if (IS_ERR(uuid_root)) {
2743f7a81ea4SStefan Behrens 		ret = PTR_ERR(uuid_root);
2744f7a81ea4SStefan Behrens 		if (ret != -ENOENT)
2745f7a81ea4SStefan Behrens 			goto recovery_tree_root;
2746f7a81ea4SStefan Behrens 		create_uuid_tree = true;
274770f80175SStefan Behrens 		check_uuid_tree = false;
2748f7a81ea4SStefan Behrens 	} else {
274927cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &uuid_root->state);
2750f7a81ea4SStefan Behrens 		fs_info->uuid_root = uuid_root;
275170f80175SStefan Behrens 		create_uuid_tree = false;
275270f80175SStefan Behrens 		check_uuid_tree =
275370f80175SStefan Behrens 		    generation != btrfs_super_uuid_tree_generation(disk_super);
2754f7a81ea4SStefan Behrens 	}
2755f7a81ea4SStefan Behrens 
27568929ecfaSYan, Zheng 	fs_info->generation = generation;
27578929ecfaSYan, Zheng 	fs_info->last_trans_committed = generation;
27588929ecfaSYan, Zheng 
275968310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
276068310a5eSIlya Dryomov 	if (ret) {
2761efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to recover balance\n");
276268310a5eSIlya Dryomov 		goto fail_block_groups;
276368310a5eSIlya Dryomov 	}
276468310a5eSIlya Dryomov 
2765733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
2766733f4fbbSStefan Behrens 	if (ret) {
2767efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: failed to init dev_stats: %d\n",
2768733f4fbbSStefan Behrens 		       ret);
2769733f4fbbSStefan Behrens 		goto fail_block_groups;
2770733f4fbbSStefan Behrens 	}
2771733f4fbbSStefan Behrens 
27728dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
27738dabb742SStefan Behrens 	if (ret) {
2774efe120a0SFrank Holton 		pr_err("BTRFS: failed to init dev_replace: %d\n", ret);
27758dabb742SStefan Behrens 		goto fail_block_groups;
27768dabb742SStefan Behrens 	}
27778dabb742SStefan Behrens 
27788dabb742SStefan Behrens 	btrfs_close_extra_devices(fs_info, fs_devices, 1);
27798dabb742SStefan Behrens 
27805ac1d209SJeff Mahoney 	ret = btrfs_sysfs_add_one(fs_info);
27815ac1d209SJeff Mahoney 	if (ret) {
2782efe120a0SFrank Holton 		pr_err("BTRFS: failed to init sysfs interface: %d\n", ret);
27835ac1d209SJeff Mahoney 		goto fail_block_groups;
27845ac1d209SJeff Mahoney 	}
27855ac1d209SJeff Mahoney 
2786c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
2787c59021f8Sliubo 	if (ret) {
2788efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: Failed to initial space info: %d\n", ret);
27892365dd3cSAnand Jain 		goto fail_sysfs;
2790c59021f8Sliubo 	}
2791c59021f8Sliubo 
27921b1d1f66SJosef Bacik 	ret = btrfs_read_block_groups(extent_root);
27931b1d1f66SJosef Bacik 	if (ret) {
2794efe120a0SFrank Holton 		printk(KERN_ERR "BTRFS: Failed to read block groups: %d\n", ret);
27952365dd3cSAnand Jain 		goto fail_sysfs;
27961b1d1f66SJosef Bacik 	}
27975af3e8ccSStefan Behrens 	fs_info->num_tolerated_disk_barrier_failures =
27985af3e8ccSStefan Behrens 		btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
2799292fd7fcSStefan Behrens 	if (fs_info->fs_devices->missing_devices >
2800292fd7fcSStefan Behrens 	     fs_info->num_tolerated_disk_barrier_failures &&
2801292fd7fcSStefan Behrens 	    !(sb->s_flags & MS_RDONLY)) {
2802efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: "
2803efe120a0SFrank Holton 			"too many missing devices, writeable mount is not allowed\n");
28042365dd3cSAnand Jain 		goto fail_sysfs;
2805292fd7fcSStefan Behrens 	}
28069078a3e1SChris Mason 
2807a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2808a74a4b97SChris Mason 					       "btrfs-cleaner");
280957506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
28102365dd3cSAnand Jain 		goto fail_sysfs;
2811a74a4b97SChris Mason 
2812a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
2813a74a4b97SChris Mason 						   tree_root,
2814a74a4b97SChris Mason 						   "btrfs-transaction");
281557506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
28163f157a2fSChris Mason 		goto fail_cleaner;
2817a74a4b97SChris Mason 
2818c289811cSChris Mason 	if (!btrfs_test_opt(tree_root, SSD) &&
2819c289811cSChris Mason 	    !btrfs_test_opt(tree_root, NOSSD) &&
2820c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
2821efe120a0SFrank Holton 		printk(KERN_INFO "BTRFS: detected SSD devices, enabling SSD "
2822c289811cSChris Mason 		       "mode\n");
2823c289811cSChris Mason 		btrfs_set_opt(fs_info->mount_opt, SSD);
2824c289811cSChris Mason 	}
2825c289811cSChris Mason 
28263818aea2SQu Wenruo 	/* Set the real inode map cache flag */
28273818aea2SQu Wenruo 	if (btrfs_test_opt(tree_root, CHANGE_INODE_CACHE))
28283818aea2SQu Wenruo 		btrfs_set_opt(tree_root->fs_info->mount_opt, INODE_MAP_CACHE);
28293818aea2SQu Wenruo 
283021adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
283121adbd5cSStefan Behrens 	if (btrfs_test_opt(tree_root, CHECK_INTEGRITY)) {
283221adbd5cSStefan Behrens 		ret = btrfsic_mount(tree_root, fs_devices,
283321adbd5cSStefan Behrens 				    btrfs_test_opt(tree_root,
283421adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
283521adbd5cSStefan Behrens 				    1 : 0,
283621adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
283721adbd5cSStefan Behrens 		if (ret)
2838efe120a0SFrank Holton 			printk(KERN_WARNING "BTRFS: failed to initialize"
283921adbd5cSStefan Behrens 			       " integrity check module %s\n", sb->s_id);
284021adbd5cSStefan Behrens 	}
284121adbd5cSStefan Behrens #endif
2842bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
2843bcef60f2SArne Jansen 	if (ret)
2844bcef60f2SArne Jansen 		goto fail_trans_kthread;
284521adbd5cSStefan Behrens 
2846acce952bSliubo 	/* do not make disk changes in broken FS */
284768ce9682SStefan Behrens 	if (btrfs_super_log_root(disk_super) != 0) {
2848e02119d5SChris Mason 		u64 bytenr = btrfs_super_log_root(disk_super);
2849d18a2c44SChris Mason 
28507c2ca468SChris Mason 		if (fs_devices->rw_devices == 0) {
2851efe120a0SFrank Holton 			printk(KERN_WARNING "BTRFS: log replay required "
2852d397712bSChris Mason 			       "on RO media\n");
28537c2ca468SChris Mason 			err = -EIO;
2854bcef60f2SArne Jansen 			goto fail_qgroup;
28557c2ca468SChris Mason 		}
2856707e8a07SDavid Sterba 		blocksize = tree_root->nodesize;
2857e02119d5SChris Mason 
28586f07e42eSAl Viro 		log_tree_root = btrfs_alloc_root(fs_info);
2859676e4c86SDan Carpenter 		if (!log_tree_root) {
2860676e4c86SDan Carpenter 			err = -ENOMEM;
2861bcef60f2SArne Jansen 			goto fail_qgroup;
2862676e4c86SDan Carpenter 		}
2863e02119d5SChris Mason 
2864707e8a07SDavid Sterba 		__setup_root(nodesize, sectorsize, stripesize,
2865e02119d5SChris Mason 			     log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2866e02119d5SChris Mason 
2867e02119d5SChris Mason 		log_tree_root->node = read_tree_block(tree_root, bytenr,
286884234f3aSYan Zheng 						      blocksize,
286984234f3aSYan Zheng 						      generation + 1);
2870416bc658SJosef Bacik 		if (!log_tree_root->node ||
2871416bc658SJosef Bacik 		    !extent_buffer_uptodate(log_tree_root->node)) {
2872efe120a0SFrank Holton 			printk(KERN_ERR "BTRFS: failed to read log tree\n");
2873416bc658SJosef Bacik 			free_extent_buffer(log_tree_root->node);
2874416bc658SJosef Bacik 			kfree(log_tree_root);
287528c16cbbSWang Shilong 			goto fail_qgroup;
2876416bc658SJosef Bacik 		}
287779787eaaSJeff Mahoney 		/* returns with log_tree_root freed on success */
2878e02119d5SChris Mason 		ret = btrfs_recover_log_trees(log_tree_root);
287979787eaaSJeff Mahoney 		if (ret) {
288079787eaaSJeff Mahoney 			btrfs_error(tree_root->fs_info, ret,
288179787eaaSJeff Mahoney 				    "Failed to recover log tree");
288279787eaaSJeff Mahoney 			free_extent_buffer(log_tree_root->node);
288379787eaaSJeff Mahoney 			kfree(log_tree_root);
288428c16cbbSWang Shilong 			goto fail_qgroup;
288579787eaaSJeff Mahoney 		}
2886e556ce2cSYan Zheng 
2887e556ce2cSYan Zheng 		if (sb->s_flags & MS_RDONLY) {
2888e556ce2cSYan Zheng 			ret = btrfs_commit_super(tree_root);
288979787eaaSJeff Mahoney 			if (ret)
289028c16cbbSWang Shilong 				goto fail_qgroup;
2891e556ce2cSYan Zheng 		}
2892e02119d5SChris Mason 	}
28931a40e23bSZheng Yan 
289476dda93cSYan, Zheng 	ret = btrfs_find_orphan_roots(tree_root);
289579787eaaSJeff Mahoney 	if (ret)
289628c16cbbSWang Shilong 		goto fail_qgroup;
289776dda93cSYan, Zheng 
28987c2ca468SChris Mason 	if (!(sb->s_flags & MS_RDONLY)) {
2899d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
290044c44af2SIlya Dryomov 		if (ret)
290128c16cbbSWang Shilong 			goto fail_qgroup;
2902d68fc57bSYan, Zheng 
29035f316481SWang Shilong 		mutex_lock(&fs_info->cleaner_mutex);
29045d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
29055f316481SWang Shilong 		mutex_unlock(&fs_info->cleaner_mutex);
2906d7ce5843SMiao Xie 		if (ret < 0) {
2907d7ce5843SMiao Xie 			printk(KERN_WARNING
2908efe120a0SFrank Holton 			       "BTRFS: failed to recover relocation\n");
2909d7ce5843SMiao Xie 			err = -EINVAL;
2910bcef60f2SArne Jansen 			goto fail_qgroup;
2911d7ce5843SMiao Xie 		}
29127c2ca468SChris Mason 	}
29131a40e23bSZheng Yan 
29143de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
29153de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
2916cb517eabSMiao Xie 	location.offset = 0;
29173de4586cSChris Mason 
29183de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
29193140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
29203140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
2921bcef60f2SArne Jansen 		goto fail_qgroup;
29223140c9a3SDan Carpenter 	}
2923c289811cSChris Mason 
29242b6ba629SIlya Dryomov 	if (sb->s_flags & MS_RDONLY)
29252b6ba629SIlya Dryomov 		return 0;
29262b6ba629SIlya Dryomov 
2927e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
29282b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
29292b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
29302b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
29312b6ba629SIlya Dryomov 		close_ctree(tree_root);
29322b6ba629SIlya Dryomov 		return ret;
29332b6ba629SIlya Dryomov 	}
2934e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
293559641015SIlya Dryomov 
29362b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
29372b6ba629SIlya Dryomov 	if (ret) {
2938efe120a0SFrank Holton 		printk(KERN_WARNING "BTRFS: failed to resume balance\n");
293966b4ffd1SJosef Bacik 		close_ctree(tree_root);
29402b6ba629SIlya Dryomov 		return ret;
2941e3acc2a6SJosef Bacik 	}
2942e3acc2a6SJosef Bacik 
29438dabb742SStefan Behrens 	ret = btrfs_resume_dev_replace_async(fs_info);
29448dabb742SStefan Behrens 	if (ret) {
2945efe120a0SFrank Holton 		pr_warn("BTRFS: failed to resume dev_replace\n");
29468dabb742SStefan Behrens 		close_ctree(tree_root);
29478dabb742SStefan Behrens 		return ret;
29488dabb742SStefan Behrens 	}
29498dabb742SStefan Behrens 
2950b382a324SJan Schmidt 	btrfs_qgroup_rescan_resume(fs_info);
2951b382a324SJan Schmidt 
2952f7a81ea4SStefan Behrens 	if (create_uuid_tree) {
2953efe120a0SFrank Holton 		pr_info("BTRFS: creating UUID tree\n");
2954f7a81ea4SStefan Behrens 		ret = btrfs_create_uuid_tree(fs_info);
2955f7a81ea4SStefan Behrens 		if (ret) {
2956efe120a0SFrank Holton 			pr_warn("BTRFS: failed to create the UUID tree %d\n",
2957f7a81ea4SStefan Behrens 				ret);
2958f7a81ea4SStefan Behrens 			close_ctree(tree_root);
2959f7a81ea4SStefan Behrens 			return ret;
2960f7a81ea4SStefan Behrens 		}
2961f420ee1eSStefan Behrens 	} else if (check_uuid_tree ||
2962f420ee1eSStefan Behrens 		   btrfs_test_opt(tree_root, RESCAN_UUID_TREE)) {
2963efe120a0SFrank Holton 		pr_info("BTRFS: checking UUID tree\n");
296470f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
296570f80175SStefan Behrens 		if (ret) {
2966efe120a0SFrank Holton 			pr_warn("BTRFS: failed to check the UUID tree %d\n",
296770f80175SStefan Behrens 				ret);
296870f80175SStefan Behrens 			close_ctree(tree_root);
296970f80175SStefan Behrens 			return ret;
297070f80175SStefan Behrens 		}
297170f80175SStefan Behrens 	} else {
297270f80175SStefan Behrens 		fs_info->update_uuid_tree_gen = 1;
2973f7a81ea4SStefan Behrens 	}
2974f7a81ea4SStefan Behrens 
2975ad2b2c80SAl Viro 	return 0;
297639279cc3SChris Mason 
2977bcef60f2SArne Jansen fail_qgroup:
2978bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
29797c2ca468SChris Mason fail_trans_kthread:
29807c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
298154067ae9SJosef Bacik 	btrfs_cleanup_transaction(fs_info->tree_root);
2982faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
29833f157a2fSChris Mason fail_cleaner:
2984a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
29857c2ca468SChris Mason 
29867c2ca468SChris Mason 	/*
29877c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
29887c2ca468SChris Mason 	 * kthreads
29897c2ca468SChris Mason 	 */
29907c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
29917c2ca468SChris Mason 
29922365dd3cSAnand Jain fail_sysfs:
29932365dd3cSAnand Jain 	btrfs_sysfs_remove_one(fs_info);
29942365dd3cSAnand Jain 
29951b1d1f66SJosef Bacik fail_block_groups:
299654067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
29971b1d1f66SJosef Bacik 	btrfs_free_block_groups(fs_info);
2998af31f5e5SChris Mason 
2999af31f5e5SChris Mason fail_tree_roots:
3000af31f5e5SChris Mason 	free_root_pointers(fs_info, 1);
30012b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3002af31f5e5SChris Mason 
300339279cc3SChris Mason fail_sb_buffer:
30047abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
300516cdcec7SMiao Xie fail_alloc:
30064543df7eSChris Mason fail_iput:
3007586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3008586e46e2SIlya Dryomov 
30094543df7eSChris Mason 	iput(fs_info->btree_inode);
3010c404e0dcSMiao Xie fail_bio_counter:
3011c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
3012963d678bSMiao Xie fail_delalloc_bytes:
3013963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3014e2d84521SMiao Xie fail_dirty_metadata_bytes:
3015e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3016ad081f14SJens Axboe fail_bdi:
30177e662854SQinghuang Feng 	bdi_destroy(&fs_info->bdi);
301876dda93cSYan, Zheng fail_srcu:
301976dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
30207e662854SQinghuang Feng fail:
302153b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
3022586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3023ad2b2c80SAl Viro 	return err;
3024af31f5e5SChris Mason 
3025af31f5e5SChris Mason recovery_tree_root:
3026af31f5e5SChris Mason 	if (!btrfs_test_opt(tree_root, RECOVERY))
3027af31f5e5SChris Mason 		goto fail_tree_roots;
3028af31f5e5SChris Mason 
3029af31f5e5SChris Mason 	free_root_pointers(fs_info, 0);
3030af31f5e5SChris Mason 
3031af31f5e5SChris Mason 	/* don't use the log in recovery mode, it won't be valid */
3032af31f5e5SChris Mason 	btrfs_set_super_log_root(disk_super, 0);
3033af31f5e5SChris Mason 
3034af31f5e5SChris Mason 	/* we can't trust the free space cache either */
3035af31f5e5SChris Mason 	btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3036af31f5e5SChris Mason 
3037af31f5e5SChris Mason 	ret = next_root_backup(fs_info, fs_info->super_copy,
3038af31f5e5SChris Mason 			       &num_backups_tried, &backup_index);
3039af31f5e5SChris Mason 	if (ret == -1)
3040af31f5e5SChris Mason 		goto fail_block_groups;
3041af31f5e5SChris Mason 	goto retry_root_backup;
3042eb60ceacSChris Mason }
3043eb60ceacSChris Mason 
3044f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3045f2984462SChris Mason {
3046f2984462SChris Mason 	if (uptodate) {
3047f2984462SChris Mason 		set_buffer_uptodate(bh);
3048f2984462SChris Mason 	} else {
3049442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
3050442a4f63SStefan Behrens 			bh->b_private;
3051442a4f63SStefan Behrens 
3052efe120a0SFrank Holton 		printk_ratelimited_in_rcu(KERN_WARNING "BTRFS: lost page write due to "
3053606686eeSJosef Bacik 					  "I/O error on %s\n",
3054606686eeSJosef Bacik 					  rcu_str_deref(device->name));
30551259ab75SChris Mason 		/* note, we dont' set_buffer_write_io_error because we have
30561259ab75SChris Mason 		 * our own ways of dealing with the IO errors
30571259ab75SChris Mason 		 */
3058f2984462SChris Mason 		clear_buffer_uptodate(bh);
3059442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3060f2984462SChris Mason 	}
3061f2984462SChris Mason 	unlock_buffer(bh);
3062f2984462SChris Mason 	put_bh(bh);
3063f2984462SChris Mason }
3064f2984462SChris Mason 
3065a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3066a512bbf8SYan Zheng {
3067a512bbf8SYan Zheng 	struct buffer_head *bh;
3068a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
3069a512bbf8SYan Zheng 	struct btrfs_super_block *super;
3070a512bbf8SYan Zheng 	int i;
3071a512bbf8SYan Zheng 	u64 transid = 0;
3072a512bbf8SYan Zheng 	u64 bytenr;
3073a512bbf8SYan Zheng 
3074a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3075a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3076a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3077a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3078a512bbf8SYan Zheng 	 */
3079a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3080a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
30818068a47eSAnand Jain 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
30828068a47eSAnand Jain 					i_size_read(bdev->bd_inode))
3083a512bbf8SYan Zheng 			break;
30848068a47eSAnand Jain 		bh = __bread(bdev, bytenr / 4096,
30858068a47eSAnand Jain 					BTRFS_SUPER_INFO_SIZE);
3086a512bbf8SYan Zheng 		if (!bh)
3087a512bbf8SYan Zheng 			continue;
3088a512bbf8SYan Zheng 
3089a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
3090a512bbf8SYan Zheng 		if (btrfs_super_bytenr(super) != bytenr ||
30913cae210fSQu Wenruo 		    btrfs_super_magic(super) != BTRFS_MAGIC) {
3092a512bbf8SYan Zheng 			brelse(bh);
3093a512bbf8SYan Zheng 			continue;
3094a512bbf8SYan Zheng 		}
3095a512bbf8SYan Zheng 
3096a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
3097a512bbf8SYan Zheng 			brelse(latest);
3098a512bbf8SYan Zheng 			latest = bh;
3099a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3100a512bbf8SYan Zheng 		} else {
3101a512bbf8SYan Zheng 			brelse(bh);
3102a512bbf8SYan Zheng 		}
3103a512bbf8SYan Zheng 	}
3104a512bbf8SYan Zheng 	return latest;
3105a512bbf8SYan Zheng }
3106a512bbf8SYan Zheng 
31074eedeb75SHisashi Hifumi /*
31084eedeb75SHisashi Hifumi  * this should be called twice, once with wait == 0 and
31094eedeb75SHisashi Hifumi  * once with wait == 1.  When wait == 0 is done, all the buffer heads
31104eedeb75SHisashi Hifumi  * we write are pinned.
31114eedeb75SHisashi Hifumi  *
31124eedeb75SHisashi Hifumi  * They are released when wait == 1 is done.
31134eedeb75SHisashi Hifumi  * max_mirrors must be the same for both runs, and it indicates how
31144eedeb75SHisashi Hifumi  * many supers on this one device should be written.
31154eedeb75SHisashi Hifumi  *
31164eedeb75SHisashi Hifumi  * max_mirrors == 0 means to write them all.
31174eedeb75SHisashi Hifumi  */
3118a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3119a512bbf8SYan Zheng 			    struct btrfs_super_block *sb,
3120a512bbf8SYan Zheng 			    int do_barriers, int wait, int max_mirrors)
3121a512bbf8SYan Zheng {
3122a512bbf8SYan Zheng 	struct buffer_head *bh;
3123a512bbf8SYan Zheng 	int i;
3124a512bbf8SYan Zheng 	int ret;
3125a512bbf8SYan Zheng 	int errors = 0;
3126a512bbf8SYan Zheng 	u32 crc;
3127a512bbf8SYan Zheng 	u64 bytenr;
3128a512bbf8SYan Zheng 
3129a512bbf8SYan Zheng 	if (max_mirrors == 0)
3130a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3131a512bbf8SYan Zheng 
3132a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3133a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
3134a512bbf8SYan Zheng 		if (bytenr + BTRFS_SUPER_INFO_SIZE >= device->total_bytes)
3135a512bbf8SYan Zheng 			break;
3136a512bbf8SYan Zheng 
3137a512bbf8SYan Zheng 		if (wait) {
3138a512bbf8SYan Zheng 			bh = __find_get_block(device->bdev, bytenr / 4096,
3139a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE);
3140634554dcSJosef Bacik 			if (!bh) {
3141634554dcSJosef Bacik 				errors++;
3142634554dcSJosef Bacik 				continue;
3143634554dcSJosef Bacik 			}
3144a512bbf8SYan Zheng 			wait_on_buffer(bh);
31454eedeb75SHisashi Hifumi 			if (!buffer_uptodate(bh))
31464eedeb75SHisashi Hifumi 				errors++;
31474eedeb75SHisashi Hifumi 
31484eedeb75SHisashi Hifumi 			/* drop our reference */
31494eedeb75SHisashi Hifumi 			brelse(bh);
31504eedeb75SHisashi Hifumi 
31514eedeb75SHisashi Hifumi 			/* drop the reference from the wait == 0 run */
3152a512bbf8SYan Zheng 			brelse(bh);
3153a512bbf8SYan Zheng 			continue;
3154a512bbf8SYan Zheng 		} else {
3155a512bbf8SYan Zheng 			btrfs_set_super_bytenr(sb, bytenr);
3156a512bbf8SYan Zheng 
3157a512bbf8SYan Zheng 			crc = ~(u32)0;
3158b0496686SLiu Bo 			crc = btrfs_csum_data((char *)sb +
3159a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE, crc,
3160a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE -
3161a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE);
3162a512bbf8SYan Zheng 			btrfs_csum_final(crc, sb->csum);
3163a512bbf8SYan Zheng 
31644eedeb75SHisashi Hifumi 			/*
31654eedeb75SHisashi Hifumi 			 * one reference for us, and we leave it for the
31664eedeb75SHisashi Hifumi 			 * caller
31674eedeb75SHisashi Hifumi 			 */
3168a512bbf8SYan Zheng 			bh = __getblk(device->bdev, bytenr / 4096,
3169a512bbf8SYan Zheng 				      BTRFS_SUPER_INFO_SIZE);
3170634554dcSJosef Bacik 			if (!bh) {
3171efe120a0SFrank Holton 				printk(KERN_ERR "BTRFS: couldn't get super "
3172634554dcSJosef Bacik 				       "buffer head for bytenr %Lu\n", bytenr);
3173634554dcSJosef Bacik 				errors++;
3174634554dcSJosef Bacik 				continue;
3175634554dcSJosef Bacik 			}
3176634554dcSJosef Bacik 
3177a512bbf8SYan Zheng 			memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3178a512bbf8SYan Zheng 
31794eedeb75SHisashi Hifumi 			/* one reference for submit_bh */
3180a512bbf8SYan Zheng 			get_bh(bh);
31814eedeb75SHisashi Hifumi 
31824eedeb75SHisashi Hifumi 			set_buffer_uptodate(bh);
3183a512bbf8SYan Zheng 			lock_buffer(bh);
3184a512bbf8SYan Zheng 			bh->b_end_io = btrfs_end_buffer_write_sync;
3185442a4f63SStefan Behrens 			bh->b_private = device;
3186a512bbf8SYan Zheng 		}
3187a512bbf8SYan Zheng 
3188387125fcSChris Mason 		/*
3189387125fcSChris Mason 		 * we fua the first super.  The others we allow
3190387125fcSChris Mason 		 * to go down lazy.
3191387125fcSChris Mason 		 */
3192e8117c26SWang Shilong 		if (i == 0)
319321adbd5cSStefan Behrens 			ret = btrfsic_submit_bh(WRITE_FUA, bh);
3194e8117c26SWang Shilong 		else
3195e8117c26SWang Shilong 			ret = btrfsic_submit_bh(WRITE_SYNC, bh);
31964eedeb75SHisashi Hifumi 		if (ret)
3197a512bbf8SYan Zheng 			errors++;
3198a512bbf8SYan Zheng 	}
3199a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3200a512bbf8SYan Zheng }
3201a512bbf8SYan Zheng 
3202387125fcSChris Mason /*
3203387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3204387125fcSChris Mason  * for the barrier when it is done
3205387125fcSChris Mason  */
3206387125fcSChris Mason static void btrfs_end_empty_barrier(struct bio *bio, int err)
3207387125fcSChris Mason {
3208387125fcSChris Mason 	if (err) {
3209387125fcSChris Mason 		if (err == -EOPNOTSUPP)
3210387125fcSChris Mason 			set_bit(BIO_EOPNOTSUPP, &bio->bi_flags);
3211387125fcSChris Mason 		clear_bit(BIO_UPTODATE, &bio->bi_flags);
3212387125fcSChris Mason 	}
3213387125fcSChris Mason 	if (bio->bi_private)
3214387125fcSChris Mason 		complete(bio->bi_private);
3215387125fcSChris Mason 	bio_put(bio);
3216387125fcSChris Mason }
3217387125fcSChris Mason 
3218387125fcSChris Mason /*
3219387125fcSChris Mason  * trigger flushes for one the devices.  If you pass wait == 0, the flushes are
3220387125fcSChris Mason  * sent down.  With wait == 1, it waits for the previous flush.
3221387125fcSChris Mason  *
3222387125fcSChris Mason  * any device where the flush fails with eopnotsupp are flagged as not-barrier
3223387125fcSChris Mason  * capable
3224387125fcSChris Mason  */
3225387125fcSChris Mason static int write_dev_flush(struct btrfs_device *device, int wait)
3226387125fcSChris Mason {
3227387125fcSChris Mason 	struct bio *bio;
3228387125fcSChris Mason 	int ret = 0;
3229387125fcSChris Mason 
3230387125fcSChris Mason 	if (device->nobarriers)
3231387125fcSChris Mason 		return 0;
3232387125fcSChris Mason 
3233387125fcSChris Mason 	if (wait) {
3234387125fcSChris Mason 		bio = device->flush_bio;
3235387125fcSChris Mason 		if (!bio)
3236387125fcSChris Mason 			return 0;
3237387125fcSChris Mason 
3238387125fcSChris Mason 		wait_for_completion(&device->flush_wait);
3239387125fcSChris Mason 
3240387125fcSChris Mason 		if (bio_flagged(bio, BIO_EOPNOTSUPP)) {
3241efe120a0SFrank Holton 			printk_in_rcu("BTRFS: disabling barriers on dev %s\n",
3242606686eeSJosef Bacik 				      rcu_str_deref(device->name));
3243387125fcSChris Mason 			device->nobarriers = 1;
32445af3e8ccSStefan Behrens 		} else if (!bio_flagged(bio, BIO_UPTODATE)) {
3245387125fcSChris Mason 			ret = -EIO;
3246442a4f63SStefan Behrens 			btrfs_dev_stat_inc_and_print(device,
3247442a4f63SStefan Behrens 				BTRFS_DEV_STAT_FLUSH_ERRS);
3248387125fcSChris Mason 		}
3249387125fcSChris Mason 
3250387125fcSChris Mason 		/* drop the reference from the wait == 0 run */
3251387125fcSChris Mason 		bio_put(bio);
3252387125fcSChris Mason 		device->flush_bio = NULL;
3253387125fcSChris Mason 
3254387125fcSChris Mason 		return ret;
3255387125fcSChris Mason 	}
3256387125fcSChris Mason 
3257387125fcSChris Mason 	/*
3258387125fcSChris Mason 	 * one reference for us, and we leave it for the
3259387125fcSChris Mason 	 * caller
3260387125fcSChris Mason 	 */
32619c017abcSJesper Juhl 	device->flush_bio = NULL;
32629be3395bSChris Mason 	bio = btrfs_io_bio_alloc(GFP_NOFS, 0);
3263387125fcSChris Mason 	if (!bio)
3264387125fcSChris Mason 		return -ENOMEM;
3265387125fcSChris Mason 
3266387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
3267387125fcSChris Mason 	bio->bi_bdev = device->bdev;
3268387125fcSChris Mason 	init_completion(&device->flush_wait);
3269387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3270387125fcSChris Mason 	device->flush_bio = bio;
3271387125fcSChris Mason 
3272387125fcSChris Mason 	bio_get(bio);
327321adbd5cSStefan Behrens 	btrfsic_submit_bio(WRITE_FLUSH, bio);
3274387125fcSChris Mason 
3275387125fcSChris Mason 	return 0;
3276387125fcSChris Mason }
3277387125fcSChris Mason 
3278387125fcSChris Mason /*
3279387125fcSChris Mason  * send an empty flush down to each device in parallel,
3280387125fcSChris Mason  * then wait for them
3281387125fcSChris Mason  */
3282387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3283387125fcSChris Mason {
3284387125fcSChris Mason 	struct list_head *head;
3285387125fcSChris Mason 	struct btrfs_device *dev;
32865af3e8ccSStefan Behrens 	int errors_send = 0;
32875af3e8ccSStefan Behrens 	int errors_wait = 0;
3288387125fcSChris Mason 	int ret;
3289387125fcSChris Mason 
3290387125fcSChris Mason 	/* send down all the barriers */
3291387125fcSChris Mason 	head = &info->fs_devices->devices;
3292387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
3293f88ba6a2SHidetoshi Seto 		if (dev->missing)
3294f88ba6a2SHidetoshi Seto 			continue;
3295387125fcSChris Mason 		if (!dev->bdev) {
32965af3e8ccSStefan Behrens 			errors_send++;
3297387125fcSChris Mason 			continue;
3298387125fcSChris Mason 		}
3299387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
3300387125fcSChris Mason 			continue;
3301387125fcSChris Mason 
3302387125fcSChris Mason 		ret = write_dev_flush(dev, 0);
3303387125fcSChris Mason 		if (ret)
33045af3e8ccSStefan Behrens 			errors_send++;
3305387125fcSChris Mason 	}
3306387125fcSChris Mason 
3307387125fcSChris Mason 	/* wait for all the barriers */
3308387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
3309f88ba6a2SHidetoshi Seto 		if (dev->missing)
3310f88ba6a2SHidetoshi Seto 			continue;
3311387125fcSChris Mason 		if (!dev->bdev) {
33125af3e8ccSStefan Behrens 			errors_wait++;
3313387125fcSChris Mason 			continue;
3314387125fcSChris Mason 		}
3315387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
3316387125fcSChris Mason 			continue;
3317387125fcSChris Mason 
3318387125fcSChris Mason 		ret = write_dev_flush(dev, 1);
3319387125fcSChris Mason 		if (ret)
33205af3e8ccSStefan Behrens 			errors_wait++;
3321387125fcSChris Mason 	}
33225af3e8ccSStefan Behrens 	if (errors_send > info->num_tolerated_disk_barrier_failures ||
33235af3e8ccSStefan Behrens 	    errors_wait > info->num_tolerated_disk_barrier_failures)
3324387125fcSChris Mason 		return -EIO;
3325387125fcSChris Mason 	return 0;
3326387125fcSChris Mason }
3327387125fcSChris Mason 
33285af3e8ccSStefan Behrens int btrfs_calc_num_tolerated_disk_barrier_failures(
33295af3e8ccSStefan Behrens 	struct btrfs_fs_info *fs_info)
33305af3e8ccSStefan Behrens {
33315af3e8ccSStefan Behrens 	struct btrfs_ioctl_space_info space;
33325af3e8ccSStefan Behrens 	struct btrfs_space_info *sinfo;
33335af3e8ccSStefan Behrens 	u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
33345af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_SYSTEM,
33355af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_METADATA,
33365af3e8ccSStefan Behrens 		       BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
33375af3e8ccSStefan Behrens 	int num_types = 4;
33385af3e8ccSStefan Behrens 	int i;
33395af3e8ccSStefan Behrens 	int c;
33405af3e8ccSStefan Behrens 	int num_tolerated_disk_barrier_failures =
33415af3e8ccSStefan Behrens 		(int)fs_info->fs_devices->num_devices;
33425af3e8ccSStefan Behrens 
33435af3e8ccSStefan Behrens 	for (i = 0; i < num_types; i++) {
33445af3e8ccSStefan Behrens 		struct btrfs_space_info *tmp;
33455af3e8ccSStefan Behrens 
33465af3e8ccSStefan Behrens 		sinfo = NULL;
33475af3e8ccSStefan Behrens 		rcu_read_lock();
33485af3e8ccSStefan Behrens 		list_for_each_entry_rcu(tmp, &fs_info->space_info, list) {
33495af3e8ccSStefan Behrens 			if (tmp->flags == types[i]) {
33505af3e8ccSStefan Behrens 				sinfo = tmp;
33515af3e8ccSStefan Behrens 				break;
33525af3e8ccSStefan Behrens 			}
33535af3e8ccSStefan Behrens 		}
33545af3e8ccSStefan Behrens 		rcu_read_unlock();
33555af3e8ccSStefan Behrens 
33565af3e8ccSStefan Behrens 		if (!sinfo)
33575af3e8ccSStefan Behrens 			continue;
33585af3e8ccSStefan Behrens 
33595af3e8ccSStefan Behrens 		down_read(&sinfo->groups_sem);
33605af3e8ccSStefan Behrens 		for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
33615af3e8ccSStefan Behrens 			if (!list_empty(&sinfo->block_groups[c])) {
33625af3e8ccSStefan Behrens 				u64 flags;
33635af3e8ccSStefan Behrens 
33645af3e8ccSStefan Behrens 				btrfs_get_block_group_info(
33655af3e8ccSStefan Behrens 					&sinfo->block_groups[c], &space);
33665af3e8ccSStefan Behrens 				if (space.total_bytes == 0 ||
33675af3e8ccSStefan Behrens 				    space.used_bytes == 0)
33685af3e8ccSStefan Behrens 					continue;
33695af3e8ccSStefan Behrens 				flags = space.flags;
33705af3e8ccSStefan Behrens 				/*
33715af3e8ccSStefan Behrens 				 * return
33725af3e8ccSStefan Behrens 				 * 0: if dup, single or RAID0 is configured for
33735af3e8ccSStefan Behrens 				 *    any of metadata, system or data, else
33745af3e8ccSStefan Behrens 				 * 1: if RAID5 is configured, or if RAID1 or
33755af3e8ccSStefan Behrens 				 *    RAID10 is configured and only two mirrors
33765af3e8ccSStefan Behrens 				 *    are used, else
33775af3e8ccSStefan Behrens 				 * 2: if RAID6 is configured, else
33785af3e8ccSStefan Behrens 				 * num_mirrors - 1: if RAID1 or RAID10 is
33795af3e8ccSStefan Behrens 				 *                  configured and more than
33805af3e8ccSStefan Behrens 				 *                  2 mirrors are used.
33815af3e8ccSStefan Behrens 				 */
33825af3e8ccSStefan Behrens 				if (num_tolerated_disk_barrier_failures > 0 &&
33835af3e8ccSStefan Behrens 				    ((flags & (BTRFS_BLOCK_GROUP_DUP |
33845af3e8ccSStefan Behrens 					       BTRFS_BLOCK_GROUP_RAID0)) ||
33855af3e8ccSStefan Behrens 				     ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK)
33865af3e8ccSStefan Behrens 				      == 0)))
33875af3e8ccSStefan Behrens 					num_tolerated_disk_barrier_failures = 0;
338853b381b3SDavid Woodhouse 				else if (num_tolerated_disk_barrier_failures > 1) {
338953b381b3SDavid Woodhouse 					if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
339053b381b3SDavid Woodhouse 					    BTRFS_BLOCK_GROUP_RAID5 |
339153b381b3SDavid Woodhouse 					    BTRFS_BLOCK_GROUP_RAID10)) {
33925af3e8ccSStefan Behrens 						num_tolerated_disk_barrier_failures = 1;
339353b381b3SDavid Woodhouse 					} else if (flags &
339415b0a89dSHenrik Nordvik 						   BTRFS_BLOCK_GROUP_RAID6) {
339553b381b3SDavid Woodhouse 						num_tolerated_disk_barrier_failures = 2;
339653b381b3SDavid Woodhouse 					}
339753b381b3SDavid Woodhouse 				}
33985af3e8ccSStefan Behrens 			}
33995af3e8ccSStefan Behrens 		}
34005af3e8ccSStefan Behrens 		up_read(&sinfo->groups_sem);
34015af3e8ccSStefan Behrens 	}
34025af3e8ccSStefan Behrens 
34035af3e8ccSStefan Behrens 	return num_tolerated_disk_barrier_failures;
34045af3e8ccSStefan Behrens }
34055af3e8ccSStefan Behrens 
340648a3b636SEric Sandeen static int write_all_supers(struct btrfs_root *root, int max_mirrors)
3407f2984462SChris Mason {
3408e5e9a520SChris Mason 	struct list_head *head;
3409f2984462SChris Mason 	struct btrfs_device *dev;
3410a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3411f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3412f2984462SChris Mason 	int ret;
3413f2984462SChris Mason 	int do_barriers;
3414a236aed1SChris Mason 	int max_errors;
3415a236aed1SChris Mason 	int total_errors = 0;
3416a061fc8dSChris Mason 	u64 flags;
3417f2984462SChris Mason 
3418f2984462SChris Mason 	do_barriers = !btrfs_test_opt(root, NOBARRIER);
3419af31f5e5SChris Mason 	backup_super_roots(root->fs_info);
3420f2984462SChris Mason 
34216c41761fSDavid Sterba 	sb = root->fs_info->super_for_commit;
3422a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3423e5e9a520SChris Mason 
3424174ba509SChris Mason 	mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
3425e5e9a520SChris Mason 	head = &root->fs_info->fs_devices->devices;
3426d7306801SFilipe David Borba Manana 	max_errors = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
3427387125fcSChris Mason 
34285af3e8ccSStefan Behrens 	if (do_barriers) {
34295af3e8ccSStefan Behrens 		ret = barrier_all_devices(root->fs_info);
34305af3e8ccSStefan Behrens 		if (ret) {
34315af3e8ccSStefan Behrens 			mutex_unlock(
34325af3e8ccSStefan Behrens 				&root->fs_info->fs_devices->device_list_mutex);
34335af3e8ccSStefan Behrens 			btrfs_error(root->fs_info, ret,
34345af3e8ccSStefan Behrens 				    "errors while submitting device barriers.");
34355af3e8ccSStefan Behrens 			return ret;
34365af3e8ccSStefan Behrens 		}
34375af3e8ccSStefan Behrens 	}
3438387125fcSChris Mason 
34391f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
3440dfe25020SChris Mason 		if (!dev->bdev) {
3441dfe25020SChris Mason 			total_errors++;
3442dfe25020SChris Mason 			continue;
3443dfe25020SChris Mason 		}
34442b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
3445dfe25020SChris Mason 			continue;
3446dfe25020SChris Mason 
34472b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3448a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3449a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
34507df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
34517df69d3eSMiao Xie 						   dev->disk_total_bytes);
3452a061fc8dSChris Mason 		btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
3453a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3454a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3455a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3456a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
34572b82032cSYan Zheng 		memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
3458a512bbf8SYan Zheng 
3459a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3460a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3461f2984462SChris Mason 
3462a512bbf8SYan Zheng 		ret = write_dev_supers(dev, sb, do_barriers, 0, max_mirrors);
3463a236aed1SChris Mason 		if (ret)
3464a236aed1SChris Mason 			total_errors++;
3465f2984462SChris Mason 	}
3466a236aed1SChris Mason 	if (total_errors > max_errors) {
3467efe120a0SFrank Holton 		btrfs_err(root->fs_info, "%d errors while writing supers",
3468d397712bSChris Mason 		       total_errors);
3469a724b436SStefan Behrens 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
347079787eaaSJeff Mahoney 
34719d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
34729d565ba4SStefan Behrens 		btrfs_error(root->fs_info, -EIO,
34739d565ba4SStefan Behrens 			    "%d errors while writing supers", total_errors);
34749d565ba4SStefan Behrens 		return -EIO;
3475a236aed1SChris Mason 	}
3476f2984462SChris Mason 
3477a512bbf8SYan Zheng 	total_errors = 0;
34781f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
3479dfe25020SChris Mason 		if (!dev->bdev)
3480dfe25020SChris Mason 			continue;
34812b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
3482dfe25020SChris Mason 			continue;
3483dfe25020SChris Mason 
3484a512bbf8SYan Zheng 		ret = write_dev_supers(dev, sb, do_barriers, 1, max_mirrors);
3485a512bbf8SYan Zheng 		if (ret)
34861259ab75SChris Mason 			total_errors++;
3487f2984462SChris Mason 	}
3488174ba509SChris Mason 	mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
3489a236aed1SChris Mason 	if (total_errors > max_errors) {
349079787eaaSJeff Mahoney 		btrfs_error(root->fs_info, -EIO,
349179787eaaSJeff Mahoney 			    "%d errors while writing supers", total_errors);
349279787eaaSJeff Mahoney 		return -EIO;
3493a236aed1SChris Mason 	}
3494f2984462SChris Mason 	return 0;
3495f2984462SChris Mason }
3496f2984462SChris Mason 
3497a512bbf8SYan Zheng int write_ctree_super(struct btrfs_trans_handle *trans,
3498a512bbf8SYan Zheng 		      struct btrfs_root *root, int max_mirrors)
3499cfaa7295SChris Mason {
3500f570e757SRashika 	return write_all_supers(root, max_mirrors);
3501cfaa7295SChris Mason }
3502cfaa7295SChris Mason 
3503cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3504cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3505cb517eabSMiao Xie 				  struct btrfs_root *root)
35062619ba1fSChris Mason {
35074df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
35082619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
35092619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
35104df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
351176dda93cSYan, Zheng 
351276dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
351376dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
351476dda93cSYan, Zheng 
35151a4319ccSLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
35163321719eSLiu Bo 		btrfs_free_log(NULL, root);
35173321719eSLiu Bo 
3518faa2dbf0SJosef Bacik 	if (root->free_ino_pinned)
3519581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_pinned);
3520faa2dbf0SJosef Bacik 	if (root->free_ino_ctl)
3521581bb050SLi Zefan 		__btrfs_remove_free_space_cache(root->free_ino_ctl);
35224df27c4dSYan, Zheng 	free_fs_root(root);
35234df27c4dSYan, Zheng }
35244df27c4dSYan, Zheng 
35254df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root)
35264df27c4dSYan, Zheng {
352757cdc8dbSDavid Sterba 	iput(root->ino_cache_inode);
35284df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
35291cb048f5SFilipe David Borba Manana 	btrfs_free_block_rsv(root, root->orphan_block_rsv);
35301cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
35310ee5dc67SAl Viro 	if (root->anon_dev)
35320ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
35338257b2dcSMiao Xie 	if (root->subv_writers)
35348257b2dcSMiao Xie 		btrfs_free_subvolume_writers(root->subv_writers);
35355f39d397SChris Mason 	free_extent_buffer(root->node);
35365f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3537581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3538581bb050SLi Zefan 	kfree(root->free_ino_pinned);
353958176a96SJosef Bacik 	kfree(root->name);
3540b0feb9d9SMiao Xie 	btrfs_put_fs_root(root);
35412619ba1fSChris Mason }
35422619ba1fSChris Mason 
3543cb517eabSMiao Xie void btrfs_free_fs_root(struct btrfs_root *root)
3544cb517eabSMiao Xie {
3545cb517eabSMiao Xie 	free_fs_root(root);
3546eb60ceacSChris Mason }
3547eb60ceacSChris Mason 
3548c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3549c146afadSYan Zheng {
3550c146afadSYan Zheng 	u64 root_objectid = 0;
3551c146afadSYan Zheng 	struct btrfs_root *gang[8];
355265d33fd7SQu Wenruo 	int i = 0;
355365d33fd7SQu Wenruo 	int err = 0;
355465d33fd7SQu Wenruo 	unsigned int ret = 0;
355565d33fd7SQu Wenruo 	int index;
3556c146afadSYan Zheng 
3557c146afadSYan Zheng 	while (1) {
355865d33fd7SQu Wenruo 		index = srcu_read_lock(&fs_info->subvol_srcu);
3559c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3560c146afadSYan Zheng 					     (void **)gang, root_objectid,
3561c146afadSYan Zheng 					     ARRAY_SIZE(gang));
356265d33fd7SQu Wenruo 		if (!ret) {
356365d33fd7SQu Wenruo 			srcu_read_unlock(&fs_info->subvol_srcu, index);
3564c146afadSYan Zheng 			break;
356565d33fd7SQu Wenruo 		}
35665d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
356766b4ffd1SJosef Bacik 
356865d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
356965d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
357065d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
357165d33fd7SQu Wenruo 				gang[i] = NULL;
357265d33fd7SQu Wenruo 				continue;
357365d33fd7SQu Wenruo 			}
357465d33fd7SQu Wenruo 			/* grab all the search result for later use */
357565d33fd7SQu Wenruo 			gang[i] = btrfs_grab_fs_root(gang[i]);
357665d33fd7SQu Wenruo 		}
357765d33fd7SQu Wenruo 		srcu_read_unlock(&fs_info->subvol_srcu, index);
357865d33fd7SQu Wenruo 
357965d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
358065d33fd7SQu Wenruo 			if (!gang[i])
358165d33fd7SQu Wenruo 				continue;
3582c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
358366b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
358466b4ffd1SJosef Bacik 			if (err)
358565d33fd7SQu Wenruo 				break;
358665d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
3587c146afadSYan Zheng 		}
3588c146afadSYan Zheng 		root_objectid++;
3589c146afadSYan Zheng 	}
359065d33fd7SQu Wenruo 
359165d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
359265d33fd7SQu Wenruo 	for (; i < ret; i++) {
359365d33fd7SQu Wenruo 		if (gang[i])
359465d33fd7SQu Wenruo 			btrfs_put_fs_root(gang[i]);
359565d33fd7SQu Wenruo 	}
359665d33fd7SQu Wenruo 	return err;
3597c146afadSYan Zheng }
3598c146afadSYan Zheng 
3599c146afadSYan Zheng int btrfs_commit_super(struct btrfs_root *root)
3600c146afadSYan Zheng {
3601c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3602c146afadSYan Zheng 
3603c146afadSYan Zheng 	mutex_lock(&root->fs_info->cleaner_mutex);
360424bbcf04SYan, Zheng 	btrfs_run_delayed_iputs(root);
3605c146afadSYan Zheng 	mutex_unlock(&root->fs_info->cleaner_mutex);
36069d1a2a3aSDavid Sterba 	wake_up_process(root->fs_info->cleaner_kthread);
3607c71bf099SYan, Zheng 
3608c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
3609c71bf099SYan, Zheng 	down_write(&root->fs_info->cleanup_work_sem);
3610c71bf099SYan, Zheng 	up_write(&root->fs_info->cleanup_work_sem);
3611c71bf099SYan, Zheng 
36127a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
36133612b495STsutomu Itoh 	if (IS_ERR(trans))
36143612b495STsutomu Itoh 		return PTR_ERR(trans);
3615d52c1bccSLiu Bo 	return btrfs_commit_transaction(trans, root);
3616c146afadSYan Zheng }
3617c146afadSYan Zheng 
36183abdbd78SDavid Sterba void close_ctree(struct btrfs_root *root)
3619eb60ceacSChris Mason {
36200f7d52f4SChris Mason 	struct btrfs_fs_info *fs_info = root->fs_info;
3621c146afadSYan Zheng 	int ret;
3622e089f05cSChris Mason 
3623facda1e7SChris Mason 	fs_info->closing = 1;
3624a2135011SChris Mason 	smp_mb();
3625a2135011SChris Mason 
3626803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
3627803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
3628803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
3629803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
3630803b2f54SStefan Behrens 
3631837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3632aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
3633837d5b6eSIlya Dryomov 
36348dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
36358dabb742SStefan Behrens 
3636aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
36374cb5300bSChris Mason 
36384cb5300bSChris Mason 	/* wait for any defraggers to finish */
36394cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
36404cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
36414cb5300bSChris Mason 
36424cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
364326176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
36444cb5300bSChris Mason 
364521c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
364621c7e756SMiao Xie 
3647c146afadSYan Zheng 	if (!(fs_info->sb->s_flags & MS_RDONLY)) {
3648c146afadSYan Zheng 		ret = btrfs_commit_super(root);
3649d397712bSChris Mason 		if (ret)
3650efe120a0SFrank Holton 			btrfs_err(root->fs_info, "commit super ret %d", ret);
3651c146afadSYan Zheng 	}
3652ed2ff2cbSChris Mason 
365387533c47SMiao Xie 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
365468ce9682SStefan Behrens 		btrfs_error_commit_super(root);
3655acce952bSliubo 
3656e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
3657e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
36588929ecfaSYan, Zheng 
3659f25784b3SYan Zheng 	fs_info->closing = 2;
3660f25784b3SYan Zheng 	smp_mb();
3661f25784b3SYan Zheng 
3662bcef60f2SArne Jansen 	btrfs_free_qgroup_config(root->fs_info);
3663bcef60f2SArne Jansen 
3664963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
3665efe120a0SFrank Holton 		btrfs_info(root->fs_info, "at unmount delalloc count %lld",
3666963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
3667b0c68f8bSChris Mason 	}
366831153d81SYan Zheng 
36695ac1d209SJeff Mahoney 	btrfs_sysfs_remove_one(fs_info);
36705ac1d209SJeff Mahoney 
3671faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
3672d10c5f31SChris Mason 
36731a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
36741a4319ccSLiu Bo 
36752b1360daSJosef Bacik 	btrfs_free_block_groups(fs_info);
36762b1360daSJosef Bacik 
3677de348ee0SWang Shilong 	/*
3678de348ee0SWang Shilong 	 * we must make sure there is not any read request to
3679de348ee0SWang Shilong 	 * submit after we stopping all workers.
3680de348ee0SWang Shilong 	 */
3681de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
368296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
368396192499SJosef Bacik 
368413e6c37bSJosef Bacik 	free_root_pointers(fs_info, 1);
36859ad6b7bcSChris Mason 
368613e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
3687d6bfde87SChris Mason 
368821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
368921adbd5cSStefan Behrens 	if (btrfs_test_opt(root, CHECK_INTEGRITY))
369021adbd5cSStefan Behrens 		btrfsic_unmount(root, fs_info->fs_devices);
369121adbd5cSStefan Behrens #endif
369221adbd5cSStefan Behrens 
3693dfe25020SChris Mason 	btrfs_close_devices(fs_info->fs_devices);
36940b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3695b248a415SChris Mason 
3696e2d84521SMiao Xie 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3697963d678bSMiao Xie 	percpu_counter_destroy(&fs_info->delalloc_bytes);
3698c404e0dcSMiao Xie 	percpu_counter_destroy(&fs_info->bio_counter);
369904160088SChris Mason 	bdi_destroy(&fs_info->bdi);
370076dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
37010b86a832SChris Mason 
370253b381b3SDavid Woodhouse 	btrfs_free_stripe_hash_table(fs_info);
370353b381b3SDavid Woodhouse 
37041cb048f5SFilipe David Borba Manana 	btrfs_free_block_rsv(root, root->orphan_block_rsv);
37051cb048f5SFilipe David Borba Manana 	root->orphan_block_rsv = NULL;
3706eb60ceacSChris Mason }
3707eb60ceacSChris Mason 
3708b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
3709b9fab919SChris Mason 			  int atomic)
3710ccd467d6SChris Mason {
37111259ab75SChris Mason 	int ret;
3712727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
37131259ab75SChris Mason 
37140b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
37151259ab75SChris Mason 	if (!ret)
37161259ab75SChris Mason 		return ret;
37171259ab75SChris Mason 
37181259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
3719b9fab919SChris Mason 				    parent_transid, atomic);
3720b9fab919SChris Mason 	if (ret == -EAGAIN)
3721b9fab919SChris Mason 		return ret;
37221259ab75SChris Mason 	return !ret;
37235f39d397SChris Mason }
37246702ed49SChris Mason 
37255f39d397SChris Mason int btrfs_set_buffer_uptodate(struct extent_buffer *buf)
37265f39d397SChris Mason {
37270b32f4bbSJosef Bacik 	return set_extent_buffer_uptodate(buf);
37285f39d397SChris Mason }
37295f39d397SChris Mason 
37305f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
37315f39d397SChris Mason {
373206ea65a3SJosef Bacik 	struct btrfs_root *root;
37335f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
3734b9473439SChris Mason 	int was_dirty;
3735b4ce94deSChris Mason 
373606ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
373706ea65a3SJosef Bacik 	/*
373806ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
373906ea65a3SJosef Bacik 	 * enabled.  Normal people shouldn't be marking dummy buffers as dirty
374006ea65a3SJosef Bacik 	 * outside of the sanity tests.
374106ea65a3SJosef Bacik 	 */
374206ea65a3SJosef Bacik 	if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
374306ea65a3SJosef Bacik 		return;
374406ea65a3SJosef Bacik #endif
374506ea65a3SJosef Bacik 	root = BTRFS_I(buf->pages[0]->mapping->host)->root;
3746b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
374731b1a2bdSJulia Lawall 	if (transid != root->fs_info->generation)
374831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, "
3749d397712bSChris Mason 		       "found %llu running %llu\n",
3750c1c9ff7cSGeert Uytterhoeven 			buf->start, transid, root->fs_info->generation);
37510b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
3752e2d84521SMiao Xie 	if (!was_dirty)
3753e2d84521SMiao Xie 		__percpu_counter_add(&root->fs_info->dirty_metadata_bytes,
3754e2d84521SMiao Xie 				     buf->len,
3755e2d84521SMiao Xie 				     root->fs_info->dirty_metadata_batch);
37561f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
37571f21ef0aSFilipe Manana 	if (btrfs_header_level(buf) == 0 && check_leaf(root, buf)) {
37581f21ef0aSFilipe Manana 		btrfs_print_leaf(root, buf);
37591f21ef0aSFilipe Manana 		ASSERT(0);
37601f21ef0aSFilipe Manana 	}
37611f21ef0aSFilipe Manana #endif
3762eb60ceacSChris Mason }
3763eb60ceacSChris Mason 
3764b53d3f5dSLiu Bo static void __btrfs_btree_balance_dirty(struct btrfs_root *root,
3765b53d3f5dSLiu Bo 					int flush_delayed)
376635b7e476SChris Mason {
3767188de649SChris Mason 	/*
3768188de649SChris Mason 	 * looks as though older kernels can get into trouble with
3769188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
3770188de649SChris Mason 	 */
3771e2d84521SMiao Xie 	int ret;
3772d6bfde87SChris Mason 
37736933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
3774d6bfde87SChris Mason 		return;
3775d6bfde87SChris Mason 
3776b53d3f5dSLiu Bo 	if (flush_delayed)
377716cdcec7SMiao Xie 		btrfs_balance_delayed_items(root);
377816cdcec7SMiao Xie 
3779e2d84521SMiao Xie 	ret = percpu_counter_compare(&root->fs_info->dirty_metadata_bytes,
3780e2d84521SMiao Xie 				     BTRFS_DIRTY_METADATA_THRESH);
3781e2d84521SMiao Xie 	if (ret > 0) {
3782d0e1d66bSNamjae Jeon 		balance_dirty_pages_ratelimited(
3783d0e1d66bSNamjae Jeon 				   root->fs_info->btree_inode->i_mapping);
378416cdcec7SMiao Xie 	}
378516cdcec7SMiao Xie 	return;
378616cdcec7SMiao Xie }
378716cdcec7SMiao Xie 
3788b53d3f5dSLiu Bo void btrfs_btree_balance_dirty(struct btrfs_root *root)
378916cdcec7SMiao Xie {
3790b53d3f5dSLiu Bo 	__btrfs_btree_balance_dirty(root, 1);
379135b7e476SChris Mason }
3792b53d3f5dSLiu Bo 
3793b53d3f5dSLiu Bo void btrfs_btree_balance_dirty_nodelay(struct btrfs_root *root)
3794b53d3f5dSLiu Bo {
3795b53d3f5dSLiu Bo 	__btrfs_btree_balance_dirty(root, 0);
3796d6bfde87SChris Mason }
37976b80053dSChris Mason 
3798ca7a79adSChris Mason int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
37996b80053dSChris Mason {
3800727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
38010b32f4bbSJosef Bacik 	return btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
38026b80053dSChris Mason }
38030da5468fSChris Mason 
3804fcd1f065SDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
3805acce952bSliubo 			      int read_only)
3806acce952bSliubo {
38071104a885SDavid Sterba 	/*
38081104a885SDavid Sterba 	 * Placeholder for checks
38091104a885SDavid Sterba 	 */
3810fcd1f065SDavid Sterba 	return 0;
3811fcd1f065SDavid Sterba }
3812fcd1f065SDavid Sterba 
381348a3b636SEric Sandeen static void btrfs_error_commit_super(struct btrfs_root *root)
3814acce952bSliubo {
3815acce952bSliubo 	mutex_lock(&root->fs_info->cleaner_mutex);
3816acce952bSliubo 	btrfs_run_delayed_iputs(root);
3817acce952bSliubo 	mutex_unlock(&root->fs_info->cleaner_mutex);
3818acce952bSliubo 
3819acce952bSliubo 	down_write(&root->fs_info->cleanup_work_sem);
3820acce952bSliubo 	up_write(&root->fs_info->cleanup_work_sem);
3821acce952bSliubo 
3822acce952bSliubo 	/* cleanup FS via transaction */
3823acce952bSliubo 	btrfs_cleanup_transaction(root);
3824acce952bSliubo }
3825acce952bSliubo 
3826143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
3827acce952bSliubo {
3828acce952bSliubo 	struct btrfs_ordered_extent *ordered;
3829acce952bSliubo 
3830199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
3831779880efSJosef Bacik 	/*
3832779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
3833779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
3834779880efSJosef Bacik 	 */
3835199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
3836779880efSJosef Bacik 			    root_extent_list)
3837779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
3838199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
3839199c2a9cSMiao Xie }
3840199c2a9cSMiao Xie 
3841199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
3842199c2a9cSMiao Xie {
3843199c2a9cSMiao Xie 	struct btrfs_root *root;
3844199c2a9cSMiao Xie 	struct list_head splice;
3845199c2a9cSMiao Xie 
3846199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
3847199c2a9cSMiao Xie 
3848199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
3849199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
3850199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
3851199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
3852199c2a9cSMiao Xie 					ordered_root);
38531de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
38541de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
3855199c2a9cSMiao Xie 
38562a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
3857199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
3858199c2a9cSMiao Xie 
38592a85d9caSLiu Bo 		cond_resched();
38602a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
3861199c2a9cSMiao Xie 	}
3862199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
3863acce952bSliubo }
3864acce952bSliubo 
386535a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
3866acce952bSliubo 				      struct btrfs_root *root)
3867acce952bSliubo {
3868acce952bSliubo 	struct rb_node *node;
3869acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
3870acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
3871acce952bSliubo 	int ret = 0;
3872acce952bSliubo 
3873acce952bSliubo 	delayed_refs = &trans->delayed_refs;
3874acce952bSliubo 
3875acce952bSliubo 	spin_lock(&delayed_refs->lock);
3876d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
3877cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
3878efe120a0SFrank Holton 		btrfs_info(root->fs_info, "delayed_refs has NO entry");
3879acce952bSliubo 		return ret;
3880acce952bSliubo 	}
3881acce952bSliubo 
3882d7df2c79SJosef Bacik 	while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
3883d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
3884e78417d1SJosef Bacik 		bool pin_bytes = false;
3885acce952bSliubo 
3886d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
3887d7df2c79SJosef Bacik 				href_node);
3888b939d1abSJosef Bacik 		if (!mutex_trylock(&head->mutex)) {
3889d7df2c79SJosef Bacik 			atomic_inc(&head->node.refs);
389079787eaaSJeff Mahoney 			spin_unlock(&delayed_refs->lock);
3891b939d1abSJosef Bacik 
3892acce952bSliubo 			mutex_lock(&head->mutex);
3893b939d1abSJosef Bacik 			mutex_unlock(&head->mutex);
3894d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(&head->node);
3895e18fca73SJosef Bacik 			spin_lock(&delayed_refs->lock);
3896b939d1abSJosef Bacik 			continue;
3897b939d1abSJosef Bacik 		}
3898d7df2c79SJosef Bacik 		spin_lock(&head->lock);
3899d7df2c79SJosef Bacik 		while ((node = rb_first(&head->ref_root)) != NULL) {
3900d7df2c79SJosef Bacik 			ref = rb_entry(node, struct btrfs_delayed_ref_node,
3901d7df2c79SJosef Bacik 				       rb_node);
3902d7df2c79SJosef Bacik 			ref->in_tree = 0;
3903d7df2c79SJosef Bacik 			rb_erase(&ref->rb_node, &head->ref_root);
3904d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
3905d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
3906d7df2c79SJosef Bacik 		}
390754067ae9SJosef Bacik 		if (head->must_insert_reserved)
3908e78417d1SJosef Bacik 			pin_bytes = true;
390978a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
3910acce952bSliubo 		delayed_refs->num_heads--;
3911d7df2c79SJosef Bacik 		if (head->processing == 0)
3912acce952bSliubo 			delayed_refs->num_heads_ready--;
3913d7df2c79SJosef Bacik 		atomic_dec(&delayed_refs->num_entries);
3914d7df2c79SJosef Bacik 		head->node.in_tree = 0;
3915c46effa6SLiu Bo 		rb_erase(&head->href_node, &delayed_refs->href_root);
3916d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
3917acce952bSliubo 		spin_unlock(&delayed_refs->lock);
3918e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
3919acce952bSliubo 
3920d7df2c79SJosef Bacik 		if (pin_bytes)
3921d7df2c79SJosef Bacik 			btrfs_pin_extent(root, head->node.bytenr,
3922d7df2c79SJosef Bacik 					 head->node.num_bytes, 1);
3923d7df2c79SJosef Bacik 		btrfs_put_delayed_ref(&head->node);
3924acce952bSliubo 		cond_resched();
3925acce952bSliubo 		spin_lock(&delayed_refs->lock);
3926acce952bSliubo 	}
3927acce952bSliubo 
3928acce952bSliubo 	spin_unlock(&delayed_refs->lock);
3929acce952bSliubo 
3930acce952bSliubo 	return ret;
3931acce952bSliubo }
3932acce952bSliubo 
3933143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
3934acce952bSliubo {
3935acce952bSliubo 	struct btrfs_inode *btrfs_inode;
3936acce952bSliubo 	struct list_head splice;
3937acce952bSliubo 
3938acce952bSliubo 	INIT_LIST_HEAD(&splice);
3939acce952bSliubo 
3940eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
3941eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
3942acce952bSliubo 
3943acce952bSliubo 	while (!list_empty(&splice)) {
3944eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
3945acce952bSliubo 					       delalloc_inodes);
3946acce952bSliubo 
3947acce952bSliubo 		list_del_init(&btrfs_inode->delalloc_inodes);
3948df0af1a5SMiao Xie 		clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
3949df0af1a5SMiao Xie 			  &btrfs_inode->runtime_flags);
3950eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
3951acce952bSliubo 
3952acce952bSliubo 		btrfs_invalidate_inodes(btrfs_inode->root);
3953b216cbfbSMiao Xie 
3954eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
3955acce952bSliubo 	}
3956acce952bSliubo 
3957eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
3958eb73c1b7SMiao Xie }
3959eb73c1b7SMiao Xie 
3960eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
3961eb73c1b7SMiao Xie {
3962eb73c1b7SMiao Xie 	struct btrfs_root *root;
3963eb73c1b7SMiao Xie 	struct list_head splice;
3964eb73c1b7SMiao Xie 
3965eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
3966eb73c1b7SMiao Xie 
3967eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
3968eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
3969eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
3970eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
3971eb73c1b7SMiao Xie 					 delalloc_root);
3972eb73c1b7SMiao Xie 		list_del_init(&root->delalloc_root);
3973eb73c1b7SMiao Xie 		root = btrfs_grab_fs_root(root);
3974eb73c1b7SMiao Xie 		BUG_ON(!root);
3975eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
3976eb73c1b7SMiao Xie 
3977eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
3978eb73c1b7SMiao Xie 		btrfs_put_fs_root(root);
3979eb73c1b7SMiao Xie 
3980eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
3981eb73c1b7SMiao Xie 	}
3982eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
3983acce952bSliubo }
3984acce952bSliubo 
3985acce952bSliubo static int btrfs_destroy_marked_extents(struct btrfs_root *root,
3986acce952bSliubo 					struct extent_io_tree *dirty_pages,
3987acce952bSliubo 					int mark)
3988acce952bSliubo {
3989acce952bSliubo 	int ret;
3990acce952bSliubo 	struct extent_buffer *eb;
3991acce952bSliubo 	u64 start = 0;
3992acce952bSliubo 	u64 end;
3993acce952bSliubo 
3994acce952bSliubo 	while (1) {
3995acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
3996e6138876SJosef Bacik 					    mark, NULL);
3997acce952bSliubo 		if (ret)
3998acce952bSliubo 			break;
3999acce952bSliubo 
4000acce952bSliubo 		clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
4001acce952bSliubo 		while (start <= end) {
4002fd8b2b61SJosef Bacik 			eb = btrfs_find_tree_block(root, start,
4003707e8a07SDavid Sterba 						   root->nodesize);
4004707e8a07SDavid Sterba 			start += root->nodesize;
4005fd8b2b61SJosef Bacik 			if (!eb)
4006acce952bSliubo 				continue;
4007fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4008acce952bSliubo 
4009fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4010fd8b2b61SJosef Bacik 					       &eb->bflags))
4011fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4012fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4013acce952bSliubo 		}
4014acce952bSliubo 	}
4015acce952bSliubo 
4016acce952bSliubo 	return ret;
4017acce952bSliubo }
4018acce952bSliubo 
4019acce952bSliubo static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
4020acce952bSliubo 				       struct extent_io_tree *pinned_extents)
4021acce952bSliubo {
4022acce952bSliubo 	struct extent_io_tree *unpin;
4023acce952bSliubo 	u64 start;
4024acce952bSliubo 	u64 end;
4025acce952bSliubo 	int ret;
4026ed0eaa14SLiu Bo 	bool loop = true;
4027acce952bSliubo 
4028acce952bSliubo 	unpin = pinned_extents;
4029ed0eaa14SLiu Bo again:
4030acce952bSliubo 	while (1) {
4031acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
4032e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
4033acce952bSliubo 		if (ret)
4034acce952bSliubo 			break;
4035acce952bSliubo 
4036acce952bSliubo 		/* opt_discard */
40375378e607SLi Dongyang 		if (btrfs_test_opt(root, DISCARD))
40385378e607SLi Dongyang 			ret = btrfs_error_discard_extent(root, start,
40395378e607SLi Dongyang 							 end + 1 - start,
40405378e607SLi Dongyang 							 NULL);
4041acce952bSliubo 
4042acce952bSliubo 		clear_extent_dirty(unpin, start, end, GFP_NOFS);
4043acce952bSliubo 		btrfs_error_unpin_extent_range(root, start, end);
4044acce952bSliubo 		cond_resched();
4045acce952bSliubo 	}
4046acce952bSliubo 
4047ed0eaa14SLiu Bo 	if (loop) {
4048ed0eaa14SLiu Bo 		if (unpin == &root->fs_info->freed_extents[0])
4049ed0eaa14SLiu Bo 			unpin = &root->fs_info->freed_extents[1];
4050ed0eaa14SLiu Bo 		else
4051ed0eaa14SLiu Bo 			unpin = &root->fs_info->freed_extents[0];
4052ed0eaa14SLiu Bo 		loop = false;
4053ed0eaa14SLiu Bo 		goto again;
4054ed0eaa14SLiu Bo 	}
4055ed0eaa14SLiu Bo 
4056acce952bSliubo 	return 0;
4057acce952bSliubo }
4058acce952bSliubo 
405949b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
406049b25e05SJeff Mahoney 				   struct btrfs_root *root)
406149b25e05SJeff Mahoney {
406249b25e05SJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, root);
406349b25e05SJeff Mahoney 
40644a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
406549b25e05SJeff Mahoney 	wake_up(&root->fs_info->transaction_blocked_wait);
406649b25e05SJeff Mahoney 
40674a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
406849b25e05SJeff Mahoney 	wake_up(&root->fs_info->transaction_wait);
406949b25e05SJeff Mahoney 
407067cde344SMiao Xie 	btrfs_destroy_delayed_inodes(root);
407167cde344SMiao Xie 	btrfs_assert_delayed_root_empty(root);
407267cde344SMiao Xie 
407349b25e05SJeff Mahoney 	btrfs_destroy_marked_extents(root, &cur_trans->dirty_pages,
407449b25e05SJeff Mahoney 				     EXTENT_DIRTY);
40756e841e32SLiu Bo 	btrfs_destroy_pinned_extent(root,
40766e841e32SLiu Bo 				    root->fs_info->pinned_extents);
407749b25e05SJeff Mahoney 
40784a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
40794a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
40804a9d8bdeSMiao Xie 
408149b25e05SJeff Mahoney 	/*
408249b25e05SJeff Mahoney 	memset(cur_trans, 0, sizeof(*cur_trans));
408349b25e05SJeff Mahoney 	kmem_cache_free(btrfs_transaction_cachep, cur_trans);
408449b25e05SJeff Mahoney 	*/
408549b25e05SJeff Mahoney }
408649b25e05SJeff Mahoney 
408748a3b636SEric Sandeen static int btrfs_cleanup_transaction(struct btrfs_root *root)
4088acce952bSliubo {
4089acce952bSliubo 	struct btrfs_transaction *t;
4090acce952bSliubo 
4091acce952bSliubo 	mutex_lock(&root->fs_info->transaction_kthread_mutex);
4092acce952bSliubo 
4093a4abeea4SJosef Bacik 	spin_lock(&root->fs_info->trans_lock);
4094724e2315SJosef Bacik 	while (!list_empty(&root->fs_info->trans_list)) {
4095724e2315SJosef Bacik 		t = list_first_entry(&root->fs_info->trans_list,
4096724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4097724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
4098724e2315SJosef Bacik 			atomic_inc(&t->use_count);
4099724e2315SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
4100724e2315SJosef Bacik 			btrfs_wait_for_commit(root, t->transid);
4101724e2315SJosef Bacik 			btrfs_put_transaction(t);
4102724e2315SJosef Bacik 			spin_lock(&root->fs_info->trans_lock);
4103724e2315SJosef Bacik 			continue;
4104724e2315SJosef Bacik 		}
4105724e2315SJosef Bacik 		if (t == root->fs_info->running_transaction) {
4106724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
4107724e2315SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
4108724e2315SJosef Bacik 			/*
4109724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4110724e2315SJosef Bacik 			 * handle open currently for this transaction.
4111724e2315SJosef Bacik 			 */
4112724e2315SJosef Bacik 			wait_event(t->writer_wait,
4113724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4114724e2315SJosef Bacik 		} else {
4115724e2315SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
4116724e2315SJosef Bacik 		}
4117724e2315SJosef Bacik 		btrfs_cleanup_one_transaction(t, root);
4118724e2315SJosef Bacik 
4119724e2315SJosef Bacik 		spin_lock(&root->fs_info->trans_lock);
4120724e2315SJosef Bacik 		if (t == root->fs_info->running_transaction)
4121ac673879SMiao Xie 			root->fs_info->running_transaction = NULL;
4122724e2315SJosef Bacik 		list_del_init(&t->list);
4123a4abeea4SJosef Bacik 		spin_unlock(&root->fs_info->trans_lock);
4124a4abeea4SJosef Bacik 
4125724e2315SJosef Bacik 		btrfs_put_transaction(t);
4126724e2315SJosef Bacik 		trace_btrfs_transaction_commit(root);
4127724e2315SJosef Bacik 		spin_lock(&root->fs_info->trans_lock);
4128724e2315SJosef Bacik 	}
4129724e2315SJosef Bacik 	spin_unlock(&root->fs_info->trans_lock);
4130199c2a9cSMiao Xie 	btrfs_destroy_all_ordered_extents(root->fs_info);
413167cde344SMiao Xie 	btrfs_destroy_delayed_inodes(root);
413267cde344SMiao Xie 	btrfs_assert_delayed_root_empty(root);
4133724e2315SJosef Bacik 	btrfs_destroy_pinned_extent(root, root->fs_info->pinned_extents);
4134eb73c1b7SMiao Xie 	btrfs_destroy_all_delalloc_inodes(root->fs_info);
4135acce952bSliubo 	mutex_unlock(&root->fs_info->transaction_kthread_mutex);
4136acce952bSliubo 
4137acce952bSliubo 	return 0;
4138acce952bSliubo }
4139acce952bSliubo 
4140d1310b2eSChris Mason static struct extent_io_ops btree_extent_io_ops = {
4141ce9adaa5SChris Mason 	.readpage_end_io_hook = btree_readpage_end_io_hook,
41424bb31e92SArne Jansen 	.readpage_io_failed_hook = btree_io_failed_hook,
41430b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
4144239b14b3SChris Mason 	/* note we're sharing with inode.c for the merge bio hook */
4145239b14b3SChris Mason 	.merge_bio_hook = btrfs_merge_bio_hook,
41460da5468fSChris Mason };
4147