xref: /openbmc/linux/fs/btrfs/disk-io.c (revision bcef60f2)
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>
29163e783eSDavid Woodhouse #include <linux/crc32c.h>
305a0e3ad6STejun Heo #include <linux/slab.h>
31784b4e29SChris Mason #include <linux/migrate.h>
327a36ddecSDavid Sterba #include <linux/ratelimit.h>
337e75bf3fSDavid Sterba #include <asm/unaligned.h>
344b4e25f2SChris Mason #include "compat.h"
35eb60ceacSChris Mason #include "ctree.h"
36eb60ceacSChris Mason #include "disk-io.h"
37e089f05cSChris Mason #include "transaction.h"
380f7d52f4SChris Mason #include "btrfs_inode.h"
390b86a832SChris Mason #include "volumes.h"
40db94535dSChris Mason #include "print-tree.h"
418b712842SChris Mason #include "async-thread.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"
48eb60ceacSChris Mason 
49d1310b2eSChris Mason static struct extent_io_ops btree_extent_io_ops;
508b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
514df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root);
52fcd1f065SDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
53acce952bSliubo 				    int read_only);
54143bede5SJeff Mahoney static void btrfs_destroy_ordered_operations(struct btrfs_root *root);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
57acce952bSliubo 				      struct btrfs_root *root);
58143bede5SJeff Mahoney static void btrfs_destroy_pending_snapshots(struct btrfs_transaction *t);
59143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
60acce952bSliubo static int btrfs_destroy_marked_extents(struct btrfs_root *root,
61acce952bSliubo 					struct extent_io_tree *dirty_pages,
62acce952bSliubo 					int mark);
63acce952bSliubo static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
64acce952bSliubo 				       struct extent_io_tree *pinned_extents);
65ce9adaa5SChris Mason 
66d352ac68SChris Mason /*
67d352ac68SChris Mason  * end_io_wq structs are used to do processing in task context when an IO is
68d352ac68SChris Mason  * complete.  This is used during reads to verify checksums, and it is used
69d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
70d352ac68SChris Mason  */
71ce9adaa5SChris Mason struct end_io_wq {
72ce9adaa5SChris Mason 	struct bio *bio;
73ce9adaa5SChris Mason 	bio_end_io_t *end_io;
74ce9adaa5SChris Mason 	void *private;
75ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
76ce9adaa5SChris Mason 	int error;
7722c59948SChris Mason 	int metadata;
78ce9adaa5SChris Mason 	struct list_head list;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
82d352ac68SChris Mason /*
83d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
84d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
85d352ac68SChris Mason  * just before they are sent down the IO stack.
86d352ac68SChris Mason  */
8744b8bd7eSChris Mason struct async_submit_bio {
8844b8bd7eSChris Mason 	struct inode *inode;
8944b8bd7eSChris Mason 	struct bio *bio;
9044b8bd7eSChris Mason 	struct list_head list;
914a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_start;
924a69a410SChris Mason 	extent_submit_bio_hook_t *submit_bio_done;
9344b8bd7eSChris Mason 	int rw;
9444b8bd7eSChris Mason 	int mirror_num;
95c8b97818SChris Mason 	unsigned long bio_flags;
96eaf25d93SChris Mason 	/*
97eaf25d93SChris Mason 	 * bio_offset is optional, can be used if the pages in the bio
98eaf25d93SChris Mason 	 * can't tell us where in the file the bio should go
99eaf25d93SChris Mason 	 */
100eaf25d93SChris Mason 	u64 bio_offset;
1018b712842SChris Mason 	struct btrfs_work work;
10279787eaaSJeff Mahoney 	int error;
10344b8bd7eSChris Mason };
10444b8bd7eSChris Mason 
10585d4e461SChris Mason /*
10685d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
10785d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
10885d4e461SChris Mason  * the level the eb occupies in the tree.
1094008c04aSChris Mason  *
11085d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
11185d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
11285d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
11385d4e461SChris Mason  * by btrfs_root->objectid.  This ensures that all special purpose roots
11485d4e461SChris Mason  * have separate keysets.
1154008c04aSChris Mason  *
11685d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
11785d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
11885d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1194008c04aSChris Mason  *
12085d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
12185d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
12285d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
12385d4e461SChris Mason  *
12485d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
12585d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
12685d4e461SChris Mason  * needs update as well.
1274008c04aSChris Mason  */
1284008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1294008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1304008c04aSChris Mason #  error
1314008c04aSChris Mason # endif
13285d4e461SChris Mason 
13385d4e461SChris Mason static struct btrfs_lockdep_keyset {
13485d4e461SChris Mason 	u64			id;		/* root objectid */
13585d4e461SChris Mason 	const char		*name_stem;	/* lock name stem */
13685d4e461SChris Mason 	char			names[BTRFS_MAX_LEVEL + 1][20];
13785d4e461SChris Mason 	struct lock_class_key	keys[BTRFS_MAX_LEVEL + 1];
13885d4e461SChris Mason } btrfs_lockdep_keysets[] = {
13985d4e461SChris Mason 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	.name_stem = "root"	},
14085d4e461SChris Mason 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	.name_stem = "extent"	},
14185d4e461SChris Mason 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	.name_stem = "chunk"	},
14285d4e461SChris Mason 	{ .id = BTRFS_DEV_TREE_OBJECTID,	.name_stem = "dev"	},
14385d4e461SChris Mason 	{ .id = BTRFS_FS_TREE_OBJECTID,		.name_stem = "fs"	},
14485d4e461SChris Mason 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	.name_stem = "csum"	},
14585d4e461SChris Mason 	{ .id = BTRFS_ORPHAN_OBJECTID,		.name_stem = "orphan"	},
14685d4e461SChris Mason 	{ .id = BTRFS_TREE_LOG_OBJECTID,	.name_stem = "log"	},
14785d4e461SChris Mason 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	.name_stem = "treloc"	},
14885d4e461SChris Mason 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	.name_stem = "dreloc"	},
14985d4e461SChris Mason 	{ .id = 0,				.name_stem = "tree"	},
1504008c04aSChris Mason };
15185d4e461SChris Mason 
15285d4e461SChris Mason void __init btrfs_init_lockdep(void)
15385d4e461SChris Mason {
15485d4e461SChris Mason 	int i, j;
15585d4e461SChris Mason 
15685d4e461SChris Mason 	/* initialize lockdep class names */
15785d4e461SChris Mason 	for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
15885d4e461SChris Mason 		struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
15985d4e461SChris Mason 
16085d4e461SChris Mason 		for (j = 0; j < ARRAY_SIZE(ks->names); j++)
16185d4e461SChris Mason 			snprintf(ks->names[j], sizeof(ks->names[j]),
16285d4e461SChris Mason 				 "btrfs-%s-%02d", ks->name_stem, j);
16385d4e461SChris Mason 	}
16485d4e461SChris Mason }
16585d4e461SChris Mason 
16685d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
16785d4e461SChris Mason 				    int level)
16885d4e461SChris Mason {
16985d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
17085d4e461SChris Mason 
17185d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
17285d4e461SChris Mason 
17385d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
17485d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
17585d4e461SChris Mason 		if (ks->id == objectid)
17685d4e461SChris Mason 			break;
17785d4e461SChris Mason 
17885d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
17985d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
18085d4e461SChris Mason }
18185d4e461SChris Mason 
1824008c04aSChris Mason #endif
1834008c04aSChris Mason 
184d352ac68SChris Mason /*
185d352ac68SChris Mason  * extents on the btree inode are pretty simple, there's one extent
186d352ac68SChris Mason  * that covers the entire device
187d352ac68SChris Mason  */
188b2950863SChristoph Hellwig static struct extent_map *btree_get_extent(struct inode *inode,
189306e16ceSDavid Sterba 		struct page *page, size_t pg_offset, u64 start, u64 len,
1905f39d397SChris Mason 		int create)
1915f39d397SChris Mason {
1925f39d397SChris Mason 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1935f39d397SChris Mason 	struct extent_map *em;
1945f39d397SChris Mason 	int ret;
1955f39d397SChris Mason 
196890871beSChris Mason 	read_lock(&em_tree->lock);
197d1310b2eSChris Mason 	em = lookup_extent_mapping(em_tree, start, len);
198a061fc8dSChris Mason 	if (em) {
199a061fc8dSChris Mason 		em->bdev =
200a061fc8dSChris Mason 			BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
201890871beSChris Mason 		read_unlock(&em_tree->lock);
2025f39d397SChris Mason 		goto out;
203a061fc8dSChris Mason 	}
204890871beSChris Mason 	read_unlock(&em_tree->lock);
2057b13b7b1SChris Mason 
206172ddd60SDavid Sterba 	em = alloc_extent_map();
2075f39d397SChris Mason 	if (!em) {
2085f39d397SChris Mason 		em = ERR_PTR(-ENOMEM);
2095f39d397SChris Mason 		goto out;
2105f39d397SChris Mason 	}
2115f39d397SChris Mason 	em->start = 0;
2120afbaf8cSChris Mason 	em->len = (u64)-1;
213c8b97818SChris Mason 	em->block_len = (u64)-1;
2145f39d397SChris Mason 	em->block_start = 0;
215a061fc8dSChris Mason 	em->bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
216d1310b2eSChris Mason 
217890871beSChris Mason 	write_lock(&em_tree->lock);
2185f39d397SChris Mason 	ret = add_extent_mapping(em_tree, em);
2195f39d397SChris Mason 	if (ret == -EEXIST) {
2200afbaf8cSChris Mason 		u64 failed_start = em->start;
2210afbaf8cSChris Mason 		u64 failed_len = em->len;
2220afbaf8cSChris Mason 
2235f39d397SChris Mason 		free_extent_map(em);
2247b13b7b1SChris Mason 		em = lookup_extent_mapping(em_tree, start, len);
2250afbaf8cSChris Mason 		if (em) {
2267b13b7b1SChris Mason 			ret = 0;
2270afbaf8cSChris Mason 		} else {
2280afbaf8cSChris Mason 			em = lookup_extent_mapping(em_tree, failed_start,
2290afbaf8cSChris Mason 						   failed_len);
2307b13b7b1SChris Mason 			ret = -EIO;
2310afbaf8cSChris Mason 		}
2325f39d397SChris Mason 	} else if (ret) {
2337b13b7b1SChris Mason 		free_extent_map(em);
2347b13b7b1SChris Mason 		em = NULL;
2355f39d397SChris Mason 	}
236890871beSChris Mason 	write_unlock(&em_tree->lock);
2377b13b7b1SChris Mason 
2387b13b7b1SChris Mason 	if (ret)
2397b13b7b1SChris Mason 		em = ERR_PTR(ret);
2405f39d397SChris Mason out:
2415f39d397SChris Mason 	return em;
2425f39d397SChris Mason }
2435f39d397SChris Mason 
24419c00ddcSChris Mason u32 btrfs_csum_data(struct btrfs_root *root, char *data, u32 seed, size_t len)
24519c00ddcSChris Mason {
246163e783eSDavid Woodhouse 	return crc32c(seed, data, len);
24719c00ddcSChris Mason }
24819c00ddcSChris Mason 
24919c00ddcSChris Mason void btrfs_csum_final(u32 crc, char *result)
25019c00ddcSChris Mason {
2517e75bf3fSDavid Sterba 	put_unaligned_le32(~crc, result);
25219c00ddcSChris Mason }
25319c00ddcSChris Mason 
254d352ac68SChris Mason /*
255d352ac68SChris Mason  * compute the csum for a btree block, and either verify it or write it
256d352ac68SChris Mason  * into the csum field of the block.
257d352ac68SChris Mason  */
25819c00ddcSChris Mason static int csum_tree_block(struct btrfs_root *root, struct extent_buffer *buf,
25919c00ddcSChris Mason 			   int verify)
26019c00ddcSChris Mason {
2616c41761fSDavid Sterba 	u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
262607d432dSJosef Bacik 	char *result = NULL;
26319c00ddcSChris Mason 	unsigned long len;
26419c00ddcSChris Mason 	unsigned long cur_len;
26519c00ddcSChris Mason 	unsigned long offset = BTRFS_CSUM_SIZE;
26619c00ddcSChris Mason 	char *kaddr;
26719c00ddcSChris Mason 	unsigned long map_start;
26819c00ddcSChris Mason 	unsigned long map_len;
26919c00ddcSChris Mason 	int err;
27019c00ddcSChris Mason 	u32 crc = ~(u32)0;
271607d432dSJosef Bacik 	unsigned long inline_result;
27219c00ddcSChris Mason 
27319c00ddcSChris Mason 	len = buf->len - offset;
27419c00ddcSChris Mason 	while (len > 0) {
27519c00ddcSChris Mason 		err = map_private_extent_buffer(buf, offset, 32,
276a6591715SChris Mason 					&kaddr, &map_start, &map_len);
277d397712bSChris Mason 		if (err)
27819c00ddcSChris Mason 			return 1;
27919c00ddcSChris Mason 		cur_len = min(len, map_len - (offset - map_start));
28019c00ddcSChris Mason 		crc = btrfs_csum_data(root, kaddr + offset - map_start,
28119c00ddcSChris Mason 				      crc, cur_len);
28219c00ddcSChris Mason 		len -= cur_len;
28319c00ddcSChris Mason 		offset += cur_len;
28419c00ddcSChris Mason 	}
285607d432dSJosef Bacik 	if (csum_size > sizeof(inline_result)) {
286607d432dSJosef Bacik 		result = kzalloc(csum_size * sizeof(char), GFP_NOFS);
287607d432dSJosef Bacik 		if (!result)
288607d432dSJosef Bacik 			return 1;
289607d432dSJosef Bacik 	} else {
290607d432dSJosef Bacik 		result = (char *)&inline_result;
291607d432dSJosef Bacik 	}
292607d432dSJosef Bacik 
29319c00ddcSChris Mason 	btrfs_csum_final(crc, result);
29419c00ddcSChris Mason 
29519c00ddcSChris Mason 	if (verify) {
296607d432dSJosef Bacik 		if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
297e4204dedSChris Mason 			u32 val;
298e4204dedSChris Mason 			u32 found = 0;
299607d432dSJosef Bacik 			memcpy(&found, result, csum_size);
300e4204dedSChris Mason 
301607d432dSJosef Bacik 			read_extent_buffer(buf, &val, 0, csum_size);
3027a36ddecSDavid Sterba 			printk_ratelimited(KERN_INFO "btrfs: %s checksum verify "
303193f284dSChris Mason 				       "failed on %llu wanted %X found %X "
304193f284dSChris Mason 				       "level %d\n",
30519c00ddcSChris Mason 				       root->fs_info->sb->s_id,
306193f284dSChris Mason 				       (unsigned long long)buf->start, val, found,
307193f284dSChris Mason 				       btrfs_header_level(buf));
308607d432dSJosef Bacik 			if (result != (char *)&inline_result)
309607d432dSJosef Bacik 				kfree(result);
31019c00ddcSChris Mason 			return 1;
31119c00ddcSChris Mason 		}
31219c00ddcSChris Mason 	} else {
313607d432dSJosef Bacik 		write_extent_buffer(buf, result, 0, csum_size);
31419c00ddcSChris Mason 	}
315607d432dSJosef Bacik 	if (result != (char *)&inline_result)
316607d432dSJosef Bacik 		kfree(result);
31719c00ddcSChris Mason 	return 0;
31819c00ddcSChris Mason }
31919c00ddcSChris Mason 
320d352ac68SChris Mason /*
321d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
322d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
323d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
324d352ac68SChris Mason  * in the wrong place.
325d352ac68SChris Mason  */
3261259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
327b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
328b9fab919SChris Mason 				 int atomic)
3291259ab75SChris Mason {
3302ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
3311259ab75SChris Mason 	int ret;
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 
3392ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
340d0082371SJeff Mahoney 			 0, &cached_state);
3410b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
3421259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
3431259ab75SChris Mason 		ret = 0;
3441259ab75SChris Mason 		goto out;
3451259ab75SChris Mason 	}
3467a36ddecSDavid Sterba 	printk_ratelimited("parent transid verify failed on %llu wanted %llu "
347193f284dSChris Mason 		       "found %llu\n",
3481259ab75SChris Mason 		       (unsigned long long)eb->start,
3491259ab75SChris Mason 		       (unsigned long long)parent_transid,
3501259ab75SChris Mason 		       (unsigned long long)btrfs_header_generation(eb));
3511259ab75SChris Mason 	ret = 1;
3520b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
35333958dc6SChris Mason out:
3542ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
3552ac55d41SJosef Bacik 			     &cached_state, GFP_NOFS);
3561259ab75SChris Mason 	return ret;
3571259ab75SChris Mason }
3581259ab75SChris Mason 
359d352ac68SChris Mason /*
360d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
361d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
362d352ac68SChris Mason  */
363f188591eSChris Mason static int btree_read_extent_buffer_pages(struct btrfs_root *root,
364f188591eSChris Mason 					  struct extent_buffer *eb,
365ca7a79adSChris Mason 					  u64 start, u64 parent_transid)
366f188591eSChris Mason {
367f188591eSChris Mason 	struct extent_io_tree *io_tree;
368ea466794SJosef Bacik 	int failed = 0;
369f188591eSChris Mason 	int ret;
370f188591eSChris Mason 	int num_copies = 0;
371f188591eSChris Mason 	int mirror_num = 0;
372ea466794SJosef Bacik 	int failed_mirror = 0;
373f188591eSChris Mason 
374a826d6dcSJosef Bacik 	clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
375f188591eSChris Mason 	io_tree = &BTRFS_I(root->fs_info->btree_inode)->io_tree;
376f188591eSChris Mason 	while (1) {
377bb82ab88SArne Jansen 		ret = read_extent_buffer_pages(io_tree, eb, start,
378bb82ab88SArne Jansen 					       WAIT_COMPLETE,
379f188591eSChris Mason 					       btree_get_extent, mirror_num);
380b9fab919SChris Mason 		if (!ret && !verify_parent_transid(io_tree, eb,
381b9fab919SChris Mason 						   parent_transid, 0))
382ea466794SJosef Bacik 			break;
383d397712bSChris Mason 
384a826d6dcSJosef Bacik 		/*
385a826d6dcSJosef Bacik 		 * This buffer's crc is fine, but its contents are corrupted, so
386a826d6dcSJosef Bacik 		 * there is no reason to read the other copies, they won't be
387a826d6dcSJosef Bacik 		 * any less wrong.
388a826d6dcSJosef Bacik 		 */
389a826d6dcSJosef Bacik 		if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
390ea466794SJosef Bacik 			break;
391ea466794SJosef Bacik 
392f188591eSChris Mason 		num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
393f188591eSChris Mason 					      eb->start, eb->len);
3944235298eSChris Mason 		if (num_copies == 1)
395ea466794SJosef Bacik 			break;
3964235298eSChris Mason 
3975cf1ab56SJosef Bacik 		if (!failed_mirror) {
3985cf1ab56SJosef Bacik 			failed = 1;
3995cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4005cf1ab56SJosef Bacik 		}
4015cf1ab56SJosef Bacik 
402f188591eSChris Mason 		mirror_num++;
403ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
404ea466794SJosef Bacik 			mirror_num++;
405ea466794SJosef Bacik 
4064235298eSChris Mason 		if (mirror_num > num_copies)
407ea466794SJosef Bacik 			break;
408f188591eSChris Mason 	}
409ea466794SJosef Bacik 
410ea466794SJosef Bacik 	if (failed && !ret)
411ea466794SJosef Bacik 		repair_eb_io_failure(root, eb, failed_mirror);
412ea466794SJosef Bacik 
413ea466794SJosef Bacik 	return ret;
414f188591eSChris Mason }
41519c00ddcSChris Mason 
416d352ac68SChris Mason /*
417d397712bSChris Mason  * checksum a dirty tree block before IO.  This has extra checks to make sure
418d397712bSChris Mason  * we only fill in the checksum field in the first page of a multi-page block
419d352ac68SChris Mason  */
420d397712bSChris Mason 
421b2950863SChristoph Hellwig static int csum_dirty_buffer(struct btrfs_root *root, struct page *page)
42219c00ddcSChris Mason {
423d1310b2eSChris Mason 	struct extent_io_tree *tree;
42435ebb934SChris Mason 	u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
42519c00ddcSChris Mason 	u64 found_start;
42619c00ddcSChris Mason 	struct extent_buffer *eb;
427f188591eSChris Mason 
428d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
42919c00ddcSChris Mason 
4304f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4314f2de97aSJosef Bacik 	if (page != eb->pages[0])
4324f2de97aSJosef Bacik 		return 0;
43319c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
43419c00ddcSChris Mason 	if (found_start != start) {
43555c69072SChris Mason 		WARN_ON(1);
4364f2de97aSJosef Bacik 		return 0;
43755c69072SChris Mason 	}
438727011e0SChris Mason 	if (eb->pages[0] != page) {
43955c69072SChris Mason 		WARN_ON(1);
4404f2de97aSJosef Bacik 		return 0;
44155c69072SChris Mason 	}
44255c69072SChris Mason 	if (!PageUptodate(page)) {
44355c69072SChris Mason 		WARN_ON(1);
4444f2de97aSJosef Bacik 		return 0;
44519c00ddcSChris Mason 	}
44619c00ddcSChris Mason 	csum_tree_block(root, eb, 0);
44719c00ddcSChris Mason 	return 0;
44819c00ddcSChris Mason }
44919c00ddcSChris Mason 
4502b82032cSYan Zheng static int check_tree_block_fsid(struct btrfs_root *root,
4512b82032cSYan Zheng 				 struct extent_buffer *eb)
4522b82032cSYan Zheng {
4532b82032cSYan Zheng 	struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
4542b82032cSYan Zheng 	u8 fsid[BTRFS_UUID_SIZE];
4552b82032cSYan Zheng 	int ret = 1;
4562b82032cSYan Zheng 
4572b82032cSYan Zheng 	read_extent_buffer(eb, fsid, (unsigned long)btrfs_header_fsid(eb),
4582b82032cSYan Zheng 			   BTRFS_FSID_SIZE);
4592b82032cSYan Zheng 	while (fs_devices) {
4602b82032cSYan Zheng 		if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
4612b82032cSYan Zheng 			ret = 0;
4622b82032cSYan Zheng 			break;
4632b82032cSYan Zheng 		}
4642b82032cSYan Zheng 		fs_devices = fs_devices->seed;
4652b82032cSYan Zheng 	}
4662b82032cSYan Zheng 	return ret;
4672b82032cSYan Zheng }
4682b82032cSYan Zheng 
469a826d6dcSJosef Bacik #define CORRUPT(reason, eb, root, slot)				\
470a826d6dcSJosef Bacik 	printk(KERN_CRIT "btrfs: corrupt leaf, %s: block=%llu,"	\
471a826d6dcSJosef Bacik 	       "root=%llu, slot=%d\n", reason,			\
472a826d6dcSJosef Bacik 	       (unsigned long long)btrfs_header_bytenr(eb),	\
473a826d6dcSJosef Bacik 	       (unsigned long long)root->objectid, slot)
474a826d6dcSJosef Bacik 
475a826d6dcSJosef Bacik static noinline int check_leaf(struct btrfs_root *root,
476a826d6dcSJosef Bacik 			       struct extent_buffer *leaf)
477a826d6dcSJosef Bacik {
478a826d6dcSJosef Bacik 	struct btrfs_key key;
479a826d6dcSJosef Bacik 	struct btrfs_key leaf_key;
480a826d6dcSJosef Bacik 	u32 nritems = btrfs_header_nritems(leaf);
481a826d6dcSJosef Bacik 	int slot;
482a826d6dcSJosef Bacik 
483a826d6dcSJosef Bacik 	if (nritems == 0)
484a826d6dcSJosef Bacik 		return 0;
485a826d6dcSJosef Bacik 
486a826d6dcSJosef Bacik 	/* Check the 0 item */
487a826d6dcSJosef Bacik 	if (btrfs_item_offset_nr(leaf, 0) + btrfs_item_size_nr(leaf, 0) !=
488a826d6dcSJosef Bacik 	    BTRFS_LEAF_DATA_SIZE(root)) {
489a826d6dcSJosef Bacik 		CORRUPT("invalid item offset size pair", leaf, root, 0);
490a826d6dcSJosef Bacik 		return -EIO;
491a826d6dcSJosef Bacik 	}
492a826d6dcSJosef Bacik 
493a826d6dcSJosef Bacik 	/*
494a826d6dcSJosef Bacik 	 * Check to make sure each items keys are in the correct order and their
495a826d6dcSJosef Bacik 	 * offsets make sense.  We only have to loop through nritems-1 because
496a826d6dcSJosef Bacik 	 * we check the current slot against the next slot, which verifies the
497a826d6dcSJosef Bacik 	 * next slot's offset+size makes sense and that the current's slot
498a826d6dcSJosef Bacik 	 * offset is correct.
499a826d6dcSJosef Bacik 	 */
500a826d6dcSJosef Bacik 	for (slot = 0; slot < nritems - 1; slot++) {
501a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &leaf_key, slot);
502a826d6dcSJosef Bacik 		btrfs_item_key_to_cpu(leaf, &key, slot + 1);
503a826d6dcSJosef Bacik 
504a826d6dcSJosef Bacik 		/* Make sure the keys are in the right order */
505a826d6dcSJosef Bacik 		if (btrfs_comp_cpu_keys(&leaf_key, &key) >= 0) {
506a826d6dcSJosef Bacik 			CORRUPT("bad key order", leaf, root, slot);
507a826d6dcSJosef Bacik 			return -EIO;
508a826d6dcSJosef Bacik 		}
509a826d6dcSJosef Bacik 
510a826d6dcSJosef Bacik 		/*
511a826d6dcSJosef Bacik 		 * Make sure the offset and ends are right, remember that the
512a826d6dcSJosef Bacik 		 * item data starts at the end of the leaf and grows towards the
513a826d6dcSJosef Bacik 		 * front.
514a826d6dcSJosef Bacik 		 */
515a826d6dcSJosef Bacik 		if (btrfs_item_offset_nr(leaf, slot) !=
516a826d6dcSJosef Bacik 			btrfs_item_end_nr(leaf, slot + 1)) {
517a826d6dcSJosef Bacik 			CORRUPT("slot offset bad", leaf, root, slot);
518a826d6dcSJosef Bacik 			return -EIO;
519a826d6dcSJosef Bacik 		}
520a826d6dcSJosef Bacik 
521a826d6dcSJosef Bacik 		/*
522a826d6dcSJosef Bacik 		 * Check to make sure that we don't point outside of the leaf,
523a826d6dcSJosef Bacik 		 * just incase all the items are consistent to eachother, but
524a826d6dcSJosef Bacik 		 * all point outside of the leaf.
525a826d6dcSJosef Bacik 		 */
526a826d6dcSJosef Bacik 		if (btrfs_item_end_nr(leaf, slot) >
527a826d6dcSJosef Bacik 		    BTRFS_LEAF_DATA_SIZE(root)) {
528a826d6dcSJosef Bacik 			CORRUPT("slot end outside of leaf", leaf, root, slot);
529a826d6dcSJosef Bacik 			return -EIO;
530a826d6dcSJosef Bacik 		}
531a826d6dcSJosef Bacik 	}
532a826d6dcSJosef Bacik 
533a826d6dcSJosef Bacik 	return 0;
534a826d6dcSJosef Bacik }
535a826d6dcSJosef Bacik 
536727011e0SChris Mason struct extent_buffer *find_eb_for_page(struct extent_io_tree *tree,
537727011e0SChris Mason 				       struct page *page, int max_walk)
538727011e0SChris Mason {
539727011e0SChris Mason 	struct extent_buffer *eb;
540727011e0SChris Mason 	u64 start = page_offset(page);
541727011e0SChris Mason 	u64 target = start;
542727011e0SChris Mason 	u64 min_start;
543727011e0SChris Mason 
544727011e0SChris Mason 	if (start < max_walk)
545727011e0SChris Mason 		min_start = 0;
546727011e0SChris Mason 	else
547727011e0SChris Mason 		min_start = start - max_walk;
548727011e0SChris Mason 
549727011e0SChris Mason 	while (start >= min_start) {
550727011e0SChris Mason 		eb = find_extent_buffer(tree, start, 0);
551727011e0SChris Mason 		if (eb) {
552727011e0SChris Mason 			/*
553727011e0SChris Mason 			 * we found an extent buffer and it contains our page
554727011e0SChris Mason 			 * horray!
555727011e0SChris Mason 			 */
556727011e0SChris Mason 			if (eb->start <= target &&
557727011e0SChris Mason 			    eb->start + eb->len > target)
558727011e0SChris Mason 				return eb;
559727011e0SChris Mason 
560727011e0SChris Mason 			/* we found an extent buffer that wasn't for us */
561727011e0SChris Mason 			free_extent_buffer(eb);
562727011e0SChris Mason 			return NULL;
563727011e0SChris Mason 		}
564727011e0SChris Mason 		if (start == 0)
565727011e0SChris Mason 			break;
566727011e0SChris Mason 		start -= PAGE_CACHE_SIZE;
567727011e0SChris Mason 	}
568727011e0SChris Mason 	return NULL;
569727011e0SChris Mason }
570727011e0SChris Mason 
571b2950863SChristoph Hellwig static int btree_readpage_end_io_hook(struct page *page, u64 start, u64 end,
5725cf1ab56SJosef Bacik 			       struct extent_state *state, int mirror)
573ce9adaa5SChris Mason {
574ce9adaa5SChris Mason 	struct extent_io_tree *tree;
575ce9adaa5SChris Mason 	u64 found_start;
576ce9adaa5SChris Mason 	int found_level;
577ce9adaa5SChris Mason 	struct extent_buffer *eb;
578ce9adaa5SChris Mason 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
579f188591eSChris Mason 	int ret = 0;
580727011e0SChris Mason 	int reads_done;
581ce9adaa5SChris Mason 
582ce9adaa5SChris Mason 	if (!page->private)
583ce9adaa5SChris Mason 		goto out;
584d397712bSChris Mason 
585727011e0SChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
5864f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
587d397712bSChris Mason 
5880b32f4bbSJosef Bacik 	/* the pending IO might have been the only thing that kept this buffer
5890b32f4bbSJosef Bacik 	 * in memory.  Make sure we have a ref for all this other checks
5900b32f4bbSJosef Bacik 	 */
5910b32f4bbSJosef Bacik 	extent_buffer_get(eb);
5920b32f4bbSJosef Bacik 
5930b32f4bbSJosef Bacik 	reads_done = atomic_dec_and_test(&eb->io_pages);
594727011e0SChris Mason 	if (!reads_done)
595727011e0SChris Mason 		goto err;
596f188591eSChris Mason 
5975cf1ab56SJosef Bacik 	eb->read_mirror = mirror;
598ea466794SJosef Bacik 	if (test_bit(EXTENT_BUFFER_IOERR, &eb->bflags)) {
599ea466794SJosef Bacik 		ret = -EIO;
600ea466794SJosef Bacik 		goto err;
601ea466794SJosef Bacik 	}
602ea466794SJosef Bacik 
603ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
604727011e0SChris Mason 	if (found_start != eb->start) {
6057a36ddecSDavid Sterba 		printk_ratelimited(KERN_INFO "btrfs bad tree block start "
606193f284dSChris Mason 			       "%llu %llu\n",
607a1b32a59SChris Mason 			       (unsigned long long)found_start,
608a1b32a59SChris Mason 			       (unsigned long long)eb->start);
609f188591eSChris Mason 		ret = -EIO;
610ce9adaa5SChris Mason 		goto err;
611ce9adaa5SChris Mason 	}
6122b82032cSYan Zheng 	if (check_tree_block_fsid(root, eb)) {
6137a36ddecSDavid Sterba 		printk_ratelimited(KERN_INFO "btrfs bad fsid on block %llu\n",
614d397712bSChris Mason 			       (unsigned long long)eb->start);
6151259ab75SChris Mason 		ret = -EIO;
6161259ab75SChris Mason 		goto err;
6171259ab75SChris Mason 	}
618ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
619ce9adaa5SChris Mason 
62085d4e461SChris Mason 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
62185d4e461SChris Mason 				       eb, found_level);
6224008c04aSChris Mason 
623ce9adaa5SChris Mason 	ret = csum_tree_block(root, eb, 1);
624a826d6dcSJosef Bacik 	if (ret) {
625f188591eSChris Mason 		ret = -EIO;
626a826d6dcSJosef Bacik 		goto err;
627a826d6dcSJosef Bacik 	}
628a826d6dcSJosef Bacik 
629a826d6dcSJosef Bacik 	/*
630a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
631a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
632a826d6dcSJosef Bacik 	 * return -EIO.
633a826d6dcSJosef Bacik 	 */
634a826d6dcSJosef Bacik 	if (found_level == 0 && check_leaf(root, eb)) {
635a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
636a826d6dcSJosef Bacik 		ret = -EIO;
637a826d6dcSJosef Bacik 	}
638ce9adaa5SChris Mason 
6390b32f4bbSJosef Bacik 	if (!ret)
6400b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
641ce9adaa5SChris Mason err:
6424bb31e92SArne Jansen 	if (test_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags)) {
6434bb31e92SArne Jansen 		clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags);
6444bb31e92SArne Jansen 		btree_readahead_hook(root, eb, eb->start, ret);
6454bb31e92SArne Jansen 	}
6464bb31e92SArne Jansen 
6470b32f4bbSJosef Bacik 	if (ret)
6480b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
6490b32f4bbSJosef Bacik 	free_extent_buffer(eb);
650ce9adaa5SChris Mason out:
651f188591eSChris Mason 	return ret;
652ce9adaa5SChris Mason }
653ce9adaa5SChris Mason 
654ea466794SJosef Bacik static int btree_io_failed_hook(struct page *page, int failed_mirror)
6554bb31e92SArne Jansen {
6564bb31e92SArne Jansen 	struct extent_buffer *eb;
6574bb31e92SArne Jansen 	struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
6584bb31e92SArne Jansen 
6594f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
660ea466794SJosef Bacik 	set_bit(EXTENT_BUFFER_IOERR, &eb->bflags);
6615cf1ab56SJosef Bacik 	eb->read_mirror = failed_mirror;
662ea466794SJosef Bacik 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
6634bb31e92SArne Jansen 		btree_readahead_hook(root, eb, eb->start, -EIO);
6644bb31e92SArne Jansen 	return -EIO;	/* we fixed nothing */
6654bb31e92SArne Jansen }
6664bb31e92SArne Jansen 
667ce9adaa5SChris Mason static void end_workqueue_bio(struct bio *bio, int err)
668ce9adaa5SChris Mason {
669ce9adaa5SChris Mason 	struct end_io_wq *end_io_wq = bio->bi_private;
670ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
671ce9adaa5SChris Mason 
672ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
673ce9adaa5SChris Mason 	end_io_wq->error = err;
6748b712842SChris Mason 	end_io_wq->work.func = end_workqueue_fn;
6758b712842SChris Mason 	end_io_wq->work.flags = 0;
676d20f7043SChris Mason 
6777b6d91daSChristoph Hellwig 	if (bio->bi_rw & REQ_WRITE) {
6780cb59c99SJosef Bacik 		if (end_io_wq->metadata == 1)
679cad321adSChris Mason 			btrfs_queue_worker(&fs_info->endio_meta_write_workers,
680cad321adSChris Mason 					   &end_io_wq->work);
6810cb59c99SJosef Bacik 		else if (end_io_wq->metadata == 2)
6820cb59c99SJosef Bacik 			btrfs_queue_worker(&fs_info->endio_freespace_worker,
6830cb59c99SJosef Bacik 					   &end_io_wq->work);
684cad321adSChris Mason 		else
685e6dcd2dcSChris Mason 			btrfs_queue_worker(&fs_info->endio_write_workers,
686e6dcd2dcSChris Mason 					   &end_io_wq->work);
687d20f7043SChris Mason 	} else {
688d20f7043SChris Mason 		if (end_io_wq->metadata)
689d20f7043SChris Mason 			btrfs_queue_worker(&fs_info->endio_meta_workers,
690d20f7043SChris Mason 					   &end_io_wq->work);
691e6dcd2dcSChris Mason 		else
692d20f7043SChris Mason 			btrfs_queue_worker(&fs_info->endio_workers,
693d20f7043SChris Mason 					   &end_io_wq->work);
694d20f7043SChris Mason 	}
695ce9adaa5SChris Mason }
696ce9adaa5SChris Mason 
6970cb59c99SJosef Bacik /*
6980cb59c99SJosef Bacik  * For the metadata arg you want
6990cb59c99SJosef Bacik  *
7000cb59c99SJosef Bacik  * 0 - if data
7010cb59c99SJosef Bacik  * 1 - if normal metadta
7020cb59c99SJosef Bacik  * 2 - if writing to the free space cache area
7030cb59c99SJosef Bacik  */
70422c59948SChris Mason int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
70522c59948SChris Mason 			int metadata)
7060b86a832SChris Mason {
707ce9adaa5SChris Mason 	struct end_io_wq *end_io_wq;
708ce9adaa5SChris Mason 	end_io_wq = kmalloc(sizeof(*end_io_wq), GFP_NOFS);
709ce9adaa5SChris Mason 	if (!end_io_wq)
710ce9adaa5SChris Mason 		return -ENOMEM;
711ce9adaa5SChris Mason 
712ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
713ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
71422c59948SChris Mason 	end_io_wq->info = info;
715ce9adaa5SChris Mason 	end_io_wq->error = 0;
716ce9adaa5SChris Mason 	end_io_wq->bio = bio;
71722c59948SChris Mason 	end_io_wq->metadata = metadata;
718ce9adaa5SChris Mason 
719ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
720ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
72122c59948SChris Mason 	return 0;
72222c59948SChris Mason }
72322c59948SChris Mason 
724b64a2851SChris Mason unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
7254854ddd0SChris Mason {
7264854ddd0SChris Mason 	unsigned long limit = min_t(unsigned long,
7274854ddd0SChris Mason 				    info->workers.max_workers,
7284854ddd0SChris Mason 				    info->fs_devices->open_devices);
7294854ddd0SChris Mason 	return 256 * limit;
7304854ddd0SChris Mason }
7314854ddd0SChris Mason 
7324a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7334a69a410SChris Mason {
7344a69a410SChris Mason 	struct async_submit_bio *async;
73579787eaaSJeff Mahoney 	int ret;
7364a69a410SChris Mason 
7374a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
73879787eaaSJeff Mahoney 	ret = async->submit_bio_start(async->inode, async->rw, async->bio,
739eaf25d93SChris Mason 				      async->mirror_num, async->bio_flags,
740eaf25d93SChris Mason 				      async->bio_offset);
74179787eaaSJeff Mahoney 	if (ret)
74279787eaaSJeff Mahoney 		async->error = ret;
7434a69a410SChris Mason }
7444a69a410SChris Mason 
7454a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7468b712842SChris Mason {
7478b712842SChris Mason 	struct btrfs_fs_info *fs_info;
7488b712842SChris Mason 	struct async_submit_bio *async;
7494854ddd0SChris Mason 	int limit;
7508b712842SChris Mason 
7518b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7528b712842SChris Mason 	fs_info = BTRFS_I(async->inode)->root->fs_info;
7534854ddd0SChris Mason 
754b64a2851SChris Mason 	limit = btrfs_async_submit_limit(fs_info);
7554854ddd0SChris Mason 	limit = limit * 2 / 3;
7564854ddd0SChris Mason 
7578b712842SChris Mason 	atomic_dec(&fs_info->nr_async_submits);
7580986fe9eSChris Mason 
759b64a2851SChris Mason 	if (atomic_read(&fs_info->nr_async_submits) < limit &&
760b64a2851SChris Mason 	    waitqueue_active(&fs_info->async_submit_wait))
7614854ddd0SChris Mason 		wake_up(&fs_info->async_submit_wait);
7624854ddd0SChris Mason 
76379787eaaSJeff Mahoney 	/* If an error occured we just want to clean up the bio and move on */
76479787eaaSJeff Mahoney 	if (async->error) {
76579787eaaSJeff Mahoney 		bio_endio(async->bio, async->error);
76679787eaaSJeff Mahoney 		return;
76779787eaaSJeff Mahoney 	}
76879787eaaSJeff Mahoney 
7694a69a410SChris Mason 	async->submit_bio_done(async->inode, async->rw, async->bio,
770eaf25d93SChris Mason 			       async->mirror_num, async->bio_flags,
771eaf25d93SChris Mason 			       async->bio_offset);
7724a69a410SChris Mason }
7734a69a410SChris Mason 
7744a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7754a69a410SChris Mason {
7764a69a410SChris Mason 	struct async_submit_bio *async;
7774a69a410SChris Mason 
7784a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7798b712842SChris Mason 	kfree(async);
7808b712842SChris Mason }
7818b712842SChris Mason 
78244b8bd7eSChris Mason int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
78344b8bd7eSChris Mason 			int rw, struct bio *bio, int mirror_num,
784c8b97818SChris Mason 			unsigned long bio_flags,
785eaf25d93SChris Mason 			u64 bio_offset,
7864a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_start,
7874a69a410SChris Mason 			extent_submit_bio_hook_t *submit_bio_done)
78844b8bd7eSChris Mason {
78944b8bd7eSChris Mason 	struct async_submit_bio *async;
79044b8bd7eSChris Mason 
79144b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
79244b8bd7eSChris Mason 	if (!async)
79344b8bd7eSChris Mason 		return -ENOMEM;
79444b8bd7eSChris Mason 
79544b8bd7eSChris Mason 	async->inode = inode;
79644b8bd7eSChris Mason 	async->rw = rw;
79744b8bd7eSChris Mason 	async->bio = bio;
79844b8bd7eSChris Mason 	async->mirror_num = mirror_num;
7994a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8004a69a410SChris Mason 	async->submit_bio_done = submit_bio_done;
8014a69a410SChris Mason 
8024a69a410SChris Mason 	async->work.func = run_one_async_start;
8034a69a410SChris Mason 	async->work.ordered_func = run_one_async_done;
8044a69a410SChris Mason 	async->work.ordered_free = run_one_async_free;
8054a69a410SChris Mason 
8068b712842SChris Mason 	async->work.flags = 0;
807c8b97818SChris Mason 	async->bio_flags = bio_flags;
808eaf25d93SChris Mason 	async->bio_offset = bio_offset;
8098c8bee1dSChris Mason 
81079787eaaSJeff Mahoney 	async->error = 0;
81179787eaaSJeff Mahoney 
812cb03c743SChris Mason 	atomic_inc(&fs_info->nr_async_submits);
813d313d7a3SChris Mason 
8147b6d91daSChristoph Hellwig 	if (rw & REQ_SYNC)
815d313d7a3SChris Mason 		btrfs_set_work_high_prio(&async->work);
816d313d7a3SChris Mason 
8178b712842SChris Mason 	btrfs_queue_worker(&fs_info->workers, &async->work);
8189473f16cSChris Mason 
819771ed689SChris Mason 	while (atomic_read(&fs_info->async_submit_draining) &&
820771ed689SChris Mason 	      atomic_read(&fs_info->nr_async_submits)) {
821771ed689SChris Mason 		wait_event(fs_info->async_submit_wait,
822771ed689SChris Mason 			   (atomic_read(&fs_info->nr_async_submits) == 0));
823771ed689SChris Mason 	}
824771ed689SChris Mason 
82544b8bd7eSChris Mason 	return 0;
82644b8bd7eSChris Mason }
82744b8bd7eSChris Mason 
828ce3ed71aSChris Mason static int btree_csum_one_bio(struct bio *bio)
829ce3ed71aSChris Mason {
830ce3ed71aSChris Mason 	struct bio_vec *bvec = bio->bi_io_vec;
831ce3ed71aSChris Mason 	int bio_index = 0;
832ce3ed71aSChris Mason 	struct btrfs_root *root;
83379787eaaSJeff Mahoney 	int ret = 0;
834ce3ed71aSChris Mason 
835ce3ed71aSChris Mason 	WARN_ON(bio->bi_vcnt <= 0);
836ce3ed71aSChris Mason 	while (bio_index < bio->bi_vcnt) {
837ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
83879787eaaSJeff Mahoney 		ret = csum_dirty_buffer(root, bvec->bv_page);
83979787eaaSJeff Mahoney 		if (ret)
84079787eaaSJeff Mahoney 			break;
841ce3ed71aSChris Mason 		bio_index++;
842ce3ed71aSChris Mason 		bvec++;
843ce3ed71aSChris Mason 	}
84479787eaaSJeff Mahoney 	return ret;
845ce3ed71aSChris Mason }
846ce3ed71aSChris Mason 
8474a69a410SChris Mason static int __btree_submit_bio_start(struct inode *inode, int rw,
8484a69a410SChris Mason 				    struct bio *bio, int mirror_num,
849eaf25d93SChris Mason 				    unsigned long bio_flags,
850eaf25d93SChris Mason 				    u64 bio_offset)
85122c59948SChris Mason {
8528b712842SChris Mason 	/*
8538b712842SChris Mason 	 * when we're called for a write, we're already in the async
8545443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8558b712842SChris Mason 	 */
85679787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
85722c59948SChris Mason }
85822c59948SChris Mason 
8594a69a410SChris Mason static int __btree_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
860eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
861eaf25d93SChris Mason 				 u64 bio_offset)
8624a69a410SChris Mason {
8638b712842SChris Mason 	/*
8644a69a410SChris Mason 	 * when we're called for a write, we're already in the async
8654a69a410SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8668b712842SChris Mason 	 */
8678b712842SChris Mason 	return btrfs_map_bio(BTRFS_I(inode)->root, rw, bio, mirror_num, 1);
8680b86a832SChris Mason }
8690b86a832SChris Mason 
87044b8bd7eSChris Mason static int btree_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
871eaf25d93SChris Mason 				 int mirror_num, unsigned long bio_flags,
872eaf25d93SChris Mason 				 u64 bio_offset)
87344b8bd7eSChris Mason {
8744a69a410SChris Mason 	int ret;
875cad321adSChris Mason 
8767b6d91daSChristoph Hellwig 	if (!(rw & REQ_WRITE)) {
877f3f266abSChris Mason 
878cad321adSChris Mason 		/*
879cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
880cad321adSChris Mason 		 * can happen in the async kernel threads
881cad321adSChris Mason 		 */
882f3f266abSChris Mason 		ret = btrfs_bio_wq_end_io(BTRFS_I(inode)->root->fs_info,
883f3f266abSChris Mason 					  bio, 1);
8841d4284bdSChris Mason 		if (ret)
8851d4284bdSChris Mason 			return ret;
8864a69a410SChris Mason 		return btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
8876f3577bdSChris Mason 				     mirror_num, 0);
88844b8bd7eSChris Mason 	}
889d313d7a3SChris Mason 
890cad321adSChris Mason 	/*
891cad321adSChris Mason 	 * kthread helpers are used to submit writes so that checksumming
892cad321adSChris Mason 	 * can happen in parallel across all CPUs
893cad321adSChris Mason 	 */
89444b8bd7eSChris Mason 	return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
895c8b97818SChris Mason 				   inode, rw, bio, mirror_num, 0,
896eaf25d93SChris Mason 				   bio_offset,
8974a69a410SChris Mason 				   __btree_submit_bio_start,
8984a69a410SChris Mason 				   __btree_submit_bio_done);
89944b8bd7eSChris Mason }
90044b8bd7eSChris Mason 
9013dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
902784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
903a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
904a6bc32b8SMel Gorman 			enum migrate_mode mode)
905784b4e29SChris Mason {
906784b4e29SChris Mason 	/*
907784b4e29SChris Mason 	 * we can't safely write a btree page from here,
908784b4e29SChris Mason 	 * we haven't done the locking hook
909784b4e29SChris Mason 	 */
910784b4e29SChris Mason 	if (PageDirty(page))
911784b4e29SChris Mason 		return -EAGAIN;
912784b4e29SChris Mason 	/*
913784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
914784b4e29SChris Mason 	 * We must have no buffers or drop them.
915784b4e29SChris Mason 	 */
916784b4e29SChris Mason 	if (page_has_private(page) &&
917784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
918784b4e29SChris Mason 		return -EAGAIN;
919a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
920784b4e29SChris Mason }
9213dd1462eSJan Beulich #endif
922784b4e29SChris Mason 
9230da5468fSChris Mason 
9240da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9250da5468fSChris Mason 			    struct writeback_control *wbc)
9260da5468fSChris Mason {
927d1310b2eSChris Mason 	struct extent_io_tree *tree;
928d1310b2eSChris Mason 	tree = &BTRFS_I(mapping->host)->io_tree;
929d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
930b9473439SChris Mason 		struct btrfs_root *root = BTRFS_I(mapping->host)->root;
931793955bcSChris Mason 		u64 num_dirty;
93224ab9cd8SChris Mason 		unsigned long thresh = 32 * 1024 * 1024;
933448d640bSChris Mason 
934448d640bSChris Mason 		if (wbc->for_kupdate)
935448d640bSChris Mason 			return 0;
936448d640bSChris Mason 
937b9473439SChris Mason 		/* this is a bit racy, but that's ok */
938b9473439SChris Mason 		num_dirty = root->fs_info->dirty_metadata_bytes;
939d397712bSChris Mason 		if (num_dirty < thresh)
940793955bcSChris Mason 			return 0;
941793955bcSChris Mason 	}
9420b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9430da5468fSChris Mason }
9440da5468fSChris Mason 
945b2950863SChristoph Hellwig static int btree_readpage(struct file *file, struct page *page)
9465f39d397SChris Mason {
947d1310b2eSChris Mason 	struct extent_io_tree *tree;
948d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9498ddc7d9cSJan Schmidt 	return extent_read_full_page(tree, page, btree_get_extent, 0);
9505f39d397SChris Mason }
9515f39d397SChris Mason 
95270dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9535f39d397SChris Mason {
95498509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
95598509cfcSChris Mason 		return 0;
9560c4e538bSDavid Sterba 	/*
9570c4e538bSDavid Sterba 	 * We need to mask out eg. __GFP_HIGHMEM and __GFP_DMA32 as we're doing
9580c4e538bSDavid Sterba 	 * slab allocation from alloc_extent_state down the callchain where
9590c4e538bSDavid Sterba 	 * it'd hit a BUG_ON as those flags are not allowed.
9600c4e538bSDavid Sterba 	 */
9610c4e538bSDavid Sterba 	gfp_flags &= ~GFP_SLAB_BUG_MASK;
9620c4e538bSDavid Sterba 
9633083ee2eSJosef Bacik 	return try_release_extent_buffer(page, gfp_flags);
964d98237b3SChris Mason }
965d98237b3SChris Mason 
9665f39d397SChris Mason static void btree_invalidatepage(struct page *page, unsigned long offset)
967d98237b3SChris Mason {
968d1310b2eSChris Mason 	struct extent_io_tree *tree;
969d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9705f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9715f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9729ad6b7bcSChris Mason 	if (PagePrivate(page)) {
973d397712bSChris Mason 		printk(KERN_WARNING "btrfs warning page private not zero "
974d397712bSChris Mason 		       "on page %llu\n", (unsigned long long)page_offset(page));
9759ad6b7bcSChris Mason 		ClearPagePrivate(page);
9769ad6b7bcSChris Mason 		set_page_private(page, 0);
9779ad6b7bcSChris Mason 		page_cache_release(page);
9789ad6b7bcSChris Mason 	}
979d98237b3SChris Mason }
980d98237b3SChris Mason 
9810b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9820b32f4bbSJosef Bacik {
9830b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9840b32f4bbSJosef Bacik 
9850b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9860b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9870b32f4bbSJosef Bacik 	BUG_ON(!eb);
9880b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9890b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
9900b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
9910b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
9920b32f4bbSJosef Bacik }
9930b32f4bbSJosef Bacik 
9947f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
995d98237b3SChris Mason 	.readpage	= btree_readpage,
9960da5468fSChris Mason 	.writepages	= btree_writepages,
9975f39d397SChris Mason 	.releasepage	= btree_releasepage,
9985f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
9995a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1000784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10015a92bc88SChris Mason #endif
10020b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1003d98237b3SChris Mason };
1004123abc88SChris Mason 
1005ca7a79adSChris Mason int readahead_tree_block(struct btrfs_root *root, u64 bytenr, u32 blocksize,
1006ca7a79adSChris Mason 			 u64 parent_transid)
1007090d1875SChris Mason {
10085f39d397SChris Mason 	struct extent_buffer *buf = NULL;
10095f39d397SChris Mason 	struct inode *btree_inode = root->fs_info->btree_inode;
1010de428b63SChris Mason 	int ret = 0;
1011090d1875SChris Mason 
1012db94535dSChris Mason 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
10135f39d397SChris Mason 	if (!buf)
1014090d1875SChris Mason 		return 0;
1015d1310b2eSChris Mason 	read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
1016bb82ab88SArne Jansen 				 buf, 0, WAIT_NONE, btree_get_extent, 0);
10175f39d397SChris Mason 	free_extent_buffer(buf);
1018de428b63SChris Mason 	return ret;
1019090d1875SChris Mason }
1020090d1875SChris Mason 
1021ab0fff03SArne Jansen int reada_tree_block_flagged(struct btrfs_root *root, u64 bytenr, u32 blocksize,
1022ab0fff03SArne Jansen 			 int mirror_num, struct extent_buffer **eb)
1023ab0fff03SArne Jansen {
1024ab0fff03SArne Jansen 	struct extent_buffer *buf = NULL;
1025ab0fff03SArne Jansen 	struct inode *btree_inode = root->fs_info->btree_inode;
1026ab0fff03SArne Jansen 	struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1027ab0fff03SArne Jansen 	int ret;
1028ab0fff03SArne Jansen 
1029ab0fff03SArne Jansen 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
1030ab0fff03SArne Jansen 	if (!buf)
1031ab0fff03SArne Jansen 		return 0;
1032ab0fff03SArne Jansen 
1033ab0fff03SArne Jansen 	set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1034ab0fff03SArne Jansen 
1035ab0fff03SArne Jansen 	ret = read_extent_buffer_pages(io_tree, buf, 0, WAIT_PAGE_LOCK,
1036ab0fff03SArne Jansen 				       btree_get_extent, mirror_num);
1037ab0fff03SArne Jansen 	if (ret) {
1038ab0fff03SArne Jansen 		free_extent_buffer(buf);
1039ab0fff03SArne Jansen 		return ret;
1040ab0fff03SArne Jansen 	}
1041ab0fff03SArne Jansen 
1042ab0fff03SArne Jansen 	if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1043ab0fff03SArne Jansen 		free_extent_buffer(buf);
1044ab0fff03SArne Jansen 		return -EIO;
10450b32f4bbSJosef Bacik 	} else if (extent_buffer_uptodate(buf)) {
1046ab0fff03SArne Jansen 		*eb = buf;
1047ab0fff03SArne Jansen 	} else {
1048ab0fff03SArne Jansen 		free_extent_buffer(buf);
1049ab0fff03SArne Jansen 	}
1050ab0fff03SArne Jansen 	return 0;
1051ab0fff03SArne Jansen }
1052ab0fff03SArne Jansen 
10530999df54SChris Mason struct extent_buffer *btrfs_find_tree_block(struct btrfs_root *root,
10540999df54SChris Mason 					    u64 bytenr, u32 blocksize)
10550999df54SChris Mason {
10560999df54SChris Mason 	struct inode *btree_inode = root->fs_info->btree_inode;
10570999df54SChris Mason 	struct extent_buffer *eb;
10580999df54SChris Mason 	eb = find_extent_buffer(&BTRFS_I(btree_inode)->io_tree,
1059f09d1f60SDavid Sterba 				bytenr, blocksize);
10600999df54SChris Mason 	return eb;
10610999df54SChris Mason }
10620999df54SChris Mason 
10630999df54SChris Mason struct extent_buffer *btrfs_find_create_tree_block(struct btrfs_root *root,
10640999df54SChris Mason 						 u64 bytenr, u32 blocksize)
10650999df54SChris Mason {
10660999df54SChris Mason 	struct inode *btree_inode = root->fs_info->btree_inode;
10670999df54SChris Mason 	struct extent_buffer *eb;
10680999df54SChris Mason 
10690999df54SChris Mason 	eb = alloc_extent_buffer(&BTRFS_I(btree_inode)->io_tree,
1070727011e0SChris Mason 				 bytenr, blocksize);
10710999df54SChris Mason 	return eb;
10720999df54SChris Mason }
10730999df54SChris Mason 
10740999df54SChris Mason 
1075e02119d5SChris Mason int btrfs_write_tree_block(struct extent_buffer *buf)
1076e02119d5SChris Mason {
1077727011e0SChris Mason 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
10788aa38c31SChristoph Hellwig 					buf->start + buf->len - 1);
1079e02119d5SChris Mason }
1080e02119d5SChris Mason 
1081e02119d5SChris Mason int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1082e02119d5SChris Mason {
1083727011e0SChris Mason 	return filemap_fdatawait_range(buf->pages[0]->mapping,
10848aa38c31SChristoph Hellwig 				       buf->start, buf->start + buf->len - 1);
1085e02119d5SChris Mason }
1086e02119d5SChris Mason 
1087db94535dSChris Mason struct extent_buffer *read_tree_block(struct btrfs_root *root, u64 bytenr,
1088ca7a79adSChris Mason 				      u32 blocksize, u64 parent_transid)
1089e20d96d6SChris Mason {
10905f39d397SChris Mason 	struct extent_buffer *buf = NULL;
109119c00ddcSChris Mason 	int ret;
109219c00ddcSChris Mason 
1093db94535dSChris Mason 	buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
10945f39d397SChris Mason 	if (!buf)
1095d98237b3SChris Mason 		return NULL;
1096e4204dedSChris Mason 
1097ca7a79adSChris Mason 	ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
10985f39d397SChris Mason 	return buf;
1099ce9adaa5SChris Mason 
1100eb60ceacSChris Mason }
1101eb60ceacSChris Mason 
1102d5c13f92SJeff Mahoney void clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
11035f39d397SChris Mason 		      struct extent_buffer *buf)
1104ed2ff2cbSChris Mason {
110555c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1106925baeddSChris Mason 	    root->fs_info->running_transaction->transid) {
1107b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1108b4ce94deSChris Mason 
1109b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1110b9473439SChris Mason 			spin_lock(&root->fs_info->delalloc_lock);
1111b9473439SChris Mason 			if (root->fs_info->dirty_metadata_bytes >= buf->len)
1112b9473439SChris Mason 				root->fs_info->dirty_metadata_bytes -= buf->len;
1113d5c13f92SJeff Mahoney 			else {
1114d5c13f92SJeff Mahoney 				spin_unlock(&root->fs_info->delalloc_lock);
1115d5c13f92SJeff Mahoney 				btrfs_panic(root->fs_info, -EOVERFLOW,
1116d5c13f92SJeff Mahoney 					  "Can't clear %lu bytes from "
1117d5c13f92SJeff Mahoney 					  " dirty_mdatadata_bytes (%lu)",
1118d5c13f92SJeff Mahoney 					  buf->len,
1119d5c13f92SJeff Mahoney 					  root->fs_info->dirty_metadata_bytes);
1120d5c13f92SJeff Mahoney 			}
1121b9473439SChris Mason 			spin_unlock(&root->fs_info->delalloc_lock);
1122b9473439SChris Mason 		}
1123b4ce94deSChris Mason 
1124b9473439SChris Mason 		/* ugh, clear_extent_buffer_dirty needs to lock the page */
1125b9473439SChris Mason 		btrfs_set_lock_blocking(buf);
11260b32f4bbSJosef Bacik 		clear_extent_buffer_dirty(buf);
1127925baeddSChris Mason 	}
11285f39d397SChris Mason }
11295f39d397SChris Mason 
1130143bede5SJeff Mahoney static void __setup_root(u32 nodesize, u32 leafsize, u32 sectorsize,
113187ee04ebSChris Mason 			 u32 stripesize, struct btrfs_root *root,
11329f5fae2fSChris Mason 			 struct btrfs_fs_info *fs_info,
1133e20d96d6SChris Mason 			 u64 objectid)
1134d97e63b6SChris Mason {
1135cfaa7295SChris Mason 	root->node = NULL;
1136a28ec197SChris Mason 	root->commit_root = NULL;
1137db94535dSChris Mason 	root->sectorsize = sectorsize;
1138db94535dSChris Mason 	root->nodesize = nodesize;
1139db94535dSChris Mason 	root->leafsize = leafsize;
114087ee04ebSChris Mason 	root->stripesize = stripesize;
1141123abc88SChris Mason 	root->ref_cows = 0;
11420b86a832SChris Mason 	root->track_dirty = 0;
1143c71bf099SYan, Zheng 	root->in_radix = 0;
1144d68fc57bSYan, Zheng 	root->orphan_item_inserted = 0;
1145d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11460b86a832SChris Mason 
11470f7d52f4SChris Mason 	root->objectid = objectid;
11480f7d52f4SChris Mason 	root->last_trans = 0;
114913a8a7c8SYan, Zheng 	root->highest_objectid = 0;
115058176a96SJosef Bacik 	root->name = NULL;
11516bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115216cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1153f0486c68SYan, Zheng 	root->block_rsv = NULL;
1154d68fc57bSYan, Zheng 	root->orphan_block_rsv = NULL;
11550b86a832SChris Mason 
11560b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11575d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1158d68fc57bSYan, Zheng 	spin_lock_init(&root->orphan_lock);
11595d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1160f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
1161a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1162e02119d5SChris Mason 	mutex_init(&root->log_mutex);
11637237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11647237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11657237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11667237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11677237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11687237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11698a35d95fSJosef Bacik 	atomic_set(&root->orphan_inodes, 0);
11707237f183SYan Zheng 	root->log_batch = 0;
11717237f183SYan Zheng 	root->log_transid = 0;
1172257c62e1SChris Mason 	root->last_log_commit = 0;
1173d0c803c4SChris Mason 	extent_io_tree_init(&root->dirty_log_pages,
1174f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
1175017e5369SChris Mason 
11763768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11773768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11786702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
117958176a96SJosef Bacik 	memset(&root->root_kobj, 0, sizeof(root->root_kobj));
11803f157a2fSChris Mason 	root->defrag_trans_start = fs_info->generation;
118158176a96SJosef Bacik 	init_completion(&root->kobj_unregister);
11826702ed49SChris Mason 	root->defrag_running = 0;
11834d775673SChris Mason 	root->root_key.objectid = objectid;
11840ee5dc67SAl Viro 	root->anon_dev = 0;
11853768f368SChris Mason }
11863768f368SChris Mason 
1187200a5c17SJeff Mahoney static int __must_check find_and_setup_root(struct btrfs_root *tree_root,
11889f5fae2fSChris Mason 					    struct btrfs_fs_info *fs_info,
11899f5fae2fSChris Mason 					    u64 objectid,
1190e20d96d6SChris Mason 					    struct btrfs_root *root)
11913768f368SChris Mason {
11923768f368SChris Mason 	int ret;
1193db94535dSChris Mason 	u32 blocksize;
119484234f3aSYan Zheng 	u64 generation;
11953768f368SChris Mason 
1196db94535dSChris Mason 	__setup_root(tree_root->nodesize, tree_root->leafsize,
119787ee04ebSChris Mason 		     tree_root->sectorsize, tree_root->stripesize,
119887ee04ebSChris Mason 		     root, fs_info, objectid);
11993768f368SChris Mason 	ret = btrfs_find_last_root(tree_root, objectid,
12003768f368SChris Mason 				   &root->root_item, &root->root_key);
12014df27c4dSYan, Zheng 	if (ret > 0)
12024df27c4dSYan, Zheng 		return -ENOENT;
1203200a5c17SJeff Mahoney 	else if (ret < 0)
1204200a5c17SJeff Mahoney 		return ret;
12053768f368SChris Mason 
120684234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1207db94535dSChris Mason 	blocksize = btrfs_level_size(root, btrfs_root_level(&root->root_item));
1208af31f5e5SChris Mason 	root->commit_root = NULL;
1209db94535dSChris Mason 	root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
121084234f3aSYan Zheng 				     blocksize, generation);
1211b9fab919SChris Mason 	if (!root->node || !btrfs_buffer_uptodate(root->node, generation, 0)) {
121268433b73SChris Mason 		free_extent_buffer(root->node);
1213af31f5e5SChris Mason 		root->node = NULL;
121468433b73SChris Mason 		return -EIO;
121568433b73SChris Mason 	}
12164df27c4dSYan, Zheng 	root->commit_root = btrfs_root_node(root);
1217d97e63b6SChris Mason 	return 0;
1218d97e63b6SChris Mason }
1219d97e63b6SChris Mason 
1220f84a8bd6SAl Viro static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info)
12216f07e42eSAl Viro {
12226f07e42eSAl Viro 	struct btrfs_root *root = kzalloc(sizeof(*root), GFP_NOFS);
12236f07e42eSAl Viro 	if (root)
12246f07e42eSAl Viro 		root->fs_info = fs_info;
12256f07e42eSAl Viro 	return root;
12266f07e42eSAl Viro }
12276f07e42eSAl Viro 
122820897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
122920897f5cSArne Jansen 				     struct btrfs_fs_info *fs_info,
123020897f5cSArne Jansen 				     u64 objectid)
123120897f5cSArne Jansen {
123220897f5cSArne Jansen 	struct extent_buffer *leaf;
123320897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
123420897f5cSArne Jansen 	struct btrfs_root *root;
123520897f5cSArne Jansen 	struct btrfs_key key;
123620897f5cSArne Jansen 	int ret = 0;
123720897f5cSArne Jansen 	u64 bytenr;
123820897f5cSArne Jansen 
123920897f5cSArne Jansen 	root = btrfs_alloc_root(fs_info);
124020897f5cSArne Jansen 	if (!root)
124120897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
124220897f5cSArne Jansen 
124320897f5cSArne Jansen 	__setup_root(tree_root->nodesize, tree_root->leafsize,
124420897f5cSArne Jansen 		     tree_root->sectorsize, tree_root->stripesize,
124520897f5cSArne Jansen 		     root, fs_info, objectid);
124620897f5cSArne Jansen 	root->root_key.objectid = objectid;
124720897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
124820897f5cSArne Jansen 	root->root_key.offset = 0;
124920897f5cSArne Jansen 
125020897f5cSArne Jansen 	leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
125120897f5cSArne Jansen 				      0, objectid, NULL, 0, 0, 0);
125220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
125320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
125420897f5cSArne Jansen 		goto fail;
125520897f5cSArne Jansen 	}
125620897f5cSArne Jansen 
125720897f5cSArne Jansen 	bytenr = leaf->start;
125820897f5cSArne Jansen 	memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
125920897f5cSArne Jansen 	btrfs_set_header_bytenr(leaf, leaf->start);
126020897f5cSArne Jansen 	btrfs_set_header_generation(leaf, trans->transid);
126120897f5cSArne Jansen 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
126220897f5cSArne Jansen 	btrfs_set_header_owner(leaf, objectid);
126320897f5cSArne Jansen 	root->node = leaf;
126420897f5cSArne Jansen 
126520897f5cSArne Jansen 	write_extent_buffer(leaf, fs_info->fsid,
126620897f5cSArne Jansen 			    (unsigned long)btrfs_header_fsid(leaf),
126720897f5cSArne Jansen 			    BTRFS_FSID_SIZE);
126820897f5cSArne Jansen 	write_extent_buffer(leaf, fs_info->chunk_tree_uuid,
126920897f5cSArne Jansen 			    (unsigned long)btrfs_header_chunk_tree_uuid(leaf),
127020897f5cSArne Jansen 			    BTRFS_UUID_SIZE);
127120897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
127220897f5cSArne Jansen 
127320897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
127420897f5cSArne Jansen 	root->track_dirty = 1;
127520897f5cSArne Jansen 
127620897f5cSArne Jansen 
127720897f5cSArne Jansen 	root->root_item.flags = 0;
127820897f5cSArne Jansen 	root->root_item.byte_limit = 0;
127920897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
128020897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
128120897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
128220897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
128320897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
128420897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
128520897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
128620897f5cSArne Jansen 	root->root_item.drop_level = 0;
128720897f5cSArne Jansen 
128820897f5cSArne Jansen 	key.objectid = objectid;
128920897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
129020897f5cSArne Jansen 	key.offset = 0;
129120897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
129220897f5cSArne Jansen 	if (ret)
129320897f5cSArne Jansen 		goto fail;
129420897f5cSArne Jansen 
129520897f5cSArne Jansen 	btrfs_tree_unlock(leaf);
129620897f5cSArne Jansen 
129720897f5cSArne Jansen fail:
129820897f5cSArne Jansen 	if (ret)
129920897f5cSArne Jansen 		return ERR_PTR(ret);
130020897f5cSArne Jansen 
130120897f5cSArne Jansen 	return root;
130220897f5cSArne Jansen }
130320897f5cSArne Jansen 
13047237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1305e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13060f7d52f4SChris Mason {
13070f7d52f4SChris Mason 	struct btrfs_root *root;
13080f7d52f4SChris Mason 	struct btrfs_root *tree_root = fs_info->tree_root;
13097237f183SYan Zheng 	struct extent_buffer *leaf;
1310e02119d5SChris Mason 
13116f07e42eSAl Viro 	root = btrfs_alloc_root(fs_info);
1312e02119d5SChris Mason 	if (!root)
13137237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1314e02119d5SChris Mason 
1315e02119d5SChris Mason 	__setup_root(tree_root->nodesize, tree_root->leafsize,
1316e02119d5SChris Mason 		     tree_root->sectorsize, tree_root->stripesize,
1317e02119d5SChris Mason 		     root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1318e02119d5SChris Mason 
1319e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1320e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1321e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
13227237f183SYan Zheng 	/*
13237237f183SYan Zheng 	 * log trees do not get reference counted because they go away
13247237f183SYan Zheng 	 * before a real commit is actually done.  They do store pointers
13257237f183SYan Zheng 	 * to file data extents, and those reference counts still get
13267237f183SYan Zheng 	 * updated (along with back refs to the log tree).
13277237f183SYan Zheng 	 */
1328e02119d5SChris Mason 	root->ref_cows = 0;
1329e02119d5SChris Mason 
13305d4f98a2SYan Zheng 	leaf = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
133166d7e7f0SArne Jansen 				      BTRFS_TREE_LOG_OBJECTID, NULL,
13325581a51aSJan Schmidt 				      0, 0, 0);
13337237f183SYan Zheng 	if (IS_ERR(leaf)) {
13347237f183SYan Zheng 		kfree(root);
13357237f183SYan Zheng 		return ERR_CAST(leaf);
13367237f183SYan Zheng 	}
1337e02119d5SChris Mason 
13385d4f98a2SYan Zheng 	memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
13395d4f98a2SYan Zheng 	btrfs_set_header_bytenr(leaf, leaf->start);
13405d4f98a2SYan Zheng 	btrfs_set_header_generation(leaf, trans->transid);
13415d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
13425d4f98a2SYan Zheng 	btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
13437237f183SYan Zheng 	root->node = leaf;
1344e02119d5SChris Mason 
1345e02119d5SChris Mason 	write_extent_buffer(root->node, root->fs_info->fsid,
1346e02119d5SChris Mason 			    (unsigned long)btrfs_header_fsid(root->node),
1347e02119d5SChris Mason 			    BTRFS_FSID_SIZE);
1348e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1349e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13507237f183SYan Zheng 	return root;
13517237f183SYan Zheng }
13527237f183SYan Zheng 
13537237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13547237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13557237f183SYan Zheng {
13567237f183SYan Zheng 	struct btrfs_root *log_root;
13577237f183SYan Zheng 
13587237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13597237f183SYan Zheng 	if (IS_ERR(log_root))
13607237f183SYan Zheng 		return PTR_ERR(log_root);
13617237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13627237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13637237f183SYan Zheng 	return 0;
13647237f183SYan Zheng }
13657237f183SYan Zheng 
13667237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13677237f183SYan Zheng 		       struct btrfs_root *root)
13687237f183SYan Zheng {
13697237f183SYan Zheng 	struct btrfs_root *log_root;
13707237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13717237f183SYan Zheng 
13727237f183SYan Zheng 	log_root = alloc_log_tree(trans, root->fs_info);
13737237f183SYan Zheng 	if (IS_ERR(log_root))
13747237f183SYan Zheng 		return PTR_ERR(log_root);
13757237f183SYan Zheng 
13767237f183SYan Zheng 	log_root->last_trans = trans->transid;
13777237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13787237f183SYan Zheng 
13797237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13807237f183SYan Zheng 	inode_item->generation = cpu_to_le64(1);
13817237f183SYan Zheng 	inode_item->size = cpu_to_le64(3);
13827237f183SYan Zheng 	inode_item->nlink = cpu_to_le32(1);
13837237f183SYan Zheng 	inode_item->nbytes = cpu_to_le64(root->leafsize);
13847237f183SYan Zheng 	inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
13857237f183SYan Zheng 
13865d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13877237f183SYan Zheng 
13887237f183SYan Zheng 	WARN_ON(root->log_root);
13897237f183SYan Zheng 	root->log_root = log_root;
13907237f183SYan Zheng 	root->log_transid = 0;
1391257c62e1SChris Mason 	root->last_log_commit = 0;
1392e02119d5SChris Mason 	return 0;
1393e02119d5SChris Mason }
1394e02119d5SChris Mason 
1395e02119d5SChris Mason struct btrfs_root *btrfs_read_fs_root_no_radix(struct btrfs_root *tree_root,
1396e02119d5SChris Mason 					       struct btrfs_key *location)
1397e02119d5SChris Mason {
1398e02119d5SChris Mason 	struct btrfs_root *root;
1399e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
14000f7d52f4SChris Mason 	struct btrfs_path *path;
14015f39d397SChris Mason 	struct extent_buffer *l;
140284234f3aSYan Zheng 	u64 generation;
1403db94535dSChris Mason 	u32 blocksize;
14040f7d52f4SChris Mason 	int ret = 0;
14050f7d52f4SChris Mason 
14066f07e42eSAl Viro 	root = btrfs_alloc_root(fs_info);
14070cf6c620SChris Mason 	if (!root)
14080f7d52f4SChris Mason 		return ERR_PTR(-ENOMEM);
14090f7d52f4SChris Mason 	if (location->offset == (u64)-1) {
1410db94535dSChris Mason 		ret = find_and_setup_root(tree_root, fs_info,
14110f7d52f4SChris Mason 					  location->objectid, root);
14120f7d52f4SChris Mason 		if (ret) {
14130f7d52f4SChris Mason 			kfree(root);
14140f7d52f4SChris Mason 			return ERR_PTR(ret);
14150f7d52f4SChris Mason 		}
141613a8a7c8SYan, Zheng 		goto out;
14170f7d52f4SChris Mason 	}
14180f7d52f4SChris Mason 
1419db94535dSChris Mason 	__setup_root(tree_root->nodesize, tree_root->leafsize,
142087ee04ebSChris Mason 		     tree_root->sectorsize, tree_root->stripesize,
142187ee04ebSChris Mason 		     root, fs_info, location->objectid);
14220f7d52f4SChris Mason 
14230f7d52f4SChris Mason 	path = btrfs_alloc_path();
1424db5b493aSTsutomu Itoh 	if (!path) {
1425db5b493aSTsutomu Itoh 		kfree(root);
1426db5b493aSTsutomu Itoh 		return ERR_PTR(-ENOMEM);
1427db5b493aSTsutomu Itoh 	}
14280f7d52f4SChris Mason 	ret = btrfs_search_slot(NULL, tree_root, location, path, 0, 0);
142913a8a7c8SYan, Zheng 	if (ret == 0) {
14305f39d397SChris Mason 		l = path->nodes[0];
14315f39d397SChris Mason 		read_extent_buffer(l, &root->root_item,
14325f39d397SChris Mason 				btrfs_item_ptr_offset(l, path->slots[0]),
14330f7d52f4SChris Mason 				sizeof(root->root_item));
143444b36eb2SYan Zheng 		memcpy(&root->root_key, location, sizeof(*location));
143513a8a7c8SYan, Zheng 	}
14360f7d52f4SChris Mason 	btrfs_free_path(path);
14370f7d52f4SChris Mason 	if (ret) {
14385e540f77STsutomu Itoh 		kfree(root);
143913a8a7c8SYan, Zheng 		if (ret > 0)
144013a8a7c8SYan, Zheng 			ret = -ENOENT;
14410f7d52f4SChris Mason 		return ERR_PTR(ret);
14420f7d52f4SChris Mason 	}
144313a8a7c8SYan, Zheng 
144484234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1445db94535dSChris Mason 	blocksize = btrfs_level_size(root, btrfs_root_level(&root->root_item));
1446db94535dSChris Mason 	root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
144784234f3aSYan Zheng 				     blocksize, generation);
14485d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
144979787eaaSJeff Mahoney 	BUG_ON(!root->node); /* -ENOMEM */
145013a8a7c8SYan, Zheng out:
145108fe4db1SLi Zefan 	if (location->objectid != BTRFS_TREE_LOG_OBJECTID) {
14520f7d52f4SChris Mason 		root->ref_cows = 1;
145308fe4db1SLi Zefan 		btrfs_check_and_init_root_item(&root->root_item);
145408fe4db1SLi Zefan 	}
145513a8a7c8SYan, Zheng 
14565eda7b5eSChris Mason 	return root;
14575eda7b5eSChris Mason }
14585eda7b5eSChris Mason 
1459edbd8d4eSChris Mason struct btrfs_root *btrfs_read_fs_root_no_name(struct btrfs_fs_info *fs_info,
1460edbd8d4eSChris Mason 					      struct btrfs_key *location)
14615eda7b5eSChris Mason {
14625eda7b5eSChris Mason 	struct btrfs_root *root;
14635eda7b5eSChris Mason 	int ret;
14645eda7b5eSChris Mason 
1465edbd8d4eSChris Mason 	if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1466edbd8d4eSChris Mason 		return fs_info->tree_root;
1467edbd8d4eSChris Mason 	if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1468edbd8d4eSChris Mason 		return fs_info->extent_root;
14698f18cf13SChris Mason 	if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
14708f18cf13SChris Mason 		return fs_info->chunk_root;
14718f18cf13SChris Mason 	if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
14728f18cf13SChris Mason 		return fs_info->dev_root;
14730403e47eSYan Zheng 	if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
14740403e47eSYan Zheng 		return fs_info->csum_root;
1475bcef60f2SArne Jansen 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1476bcef60f2SArne Jansen 		return fs_info->quota_root ? fs_info->quota_root :
1477bcef60f2SArne Jansen 					     ERR_PTR(-ENOENT);
14784df27c4dSYan, Zheng again:
14794df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
14805eda7b5eSChris Mason 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
14815eda7b5eSChris Mason 				 (unsigned long)location->objectid);
14824df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
14835eda7b5eSChris Mason 	if (root)
14845eda7b5eSChris Mason 		return root;
14855eda7b5eSChris Mason 
1486e02119d5SChris Mason 	root = btrfs_read_fs_root_no_radix(fs_info->tree_root, location);
14875eda7b5eSChris Mason 	if (IS_ERR(root))
14885eda7b5eSChris Mason 		return root;
14893394e160SChris Mason 
1490581bb050SLi Zefan 	root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1491581bb050SLi Zefan 	root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1492581bb050SLi Zefan 					GFP_NOFS);
149335a30d7cSDavid Sterba 	if (!root->free_ino_pinned || !root->free_ino_ctl) {
149435a30d7cSDavid Sterba 		ret = -ENOMEM;
1495581bb050SLi Zefan 		goto fail;
149635a30d7cSDavid Sterba 	}
1497581bb050SLi Zefan 
1498581bb050SLi Zefan 	btrfs_init_free_ino_ctl(root);
1499581bb050SLi Zefan 	mutex_init(&root->fs_commit_mutex);
1500581bb050SLi Zefan 	spin_lock_init(&root->cache_lock);
1501581bb050SLi Zefan 	init_waitqueue_head(&root->cache_wait);
1502581bb050SLi Zefan 
15030ee5dc67SAl Viro 	ret = get_anon_bdev(&root->anon_dev);
1504ac08aedfSChris Mason 	if (ret)
1505ac08aedfSChris Mason 		goto fail;
15063394e160SChris Mason 
1507d68fc57bSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0) {
1508d68fc57bSYan, Zheng 		ret = -ENOENT;
1509d68fc57bSYan, Zheng 		goto fail;
1510d68fc57bSYan, Zheng 	}
1511d68fc57bSYan, Zheng 
1512d68fc57bSYan, Zheng 	ret = btrfs_find_orphan_item(fs_info->tree_root, location->objectid);
1513d68fc57bSYan, Zheng 	if (ret < 0)
1514d68fc57bSYan, Zheng 		goto fail;
1515d68fc57bSYan, Zheng 	if (ret == 0)
1516d68fc57bSYan, Zheng 		root->orphan_item_inserted = 1;
1517d68fc57bSYan, Zheng 
15184df27c4dSYan, Zheng 	ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
15194df27c4dSYan, Zheng 	if (ret)
15204df27c4dSYan, Zheng 		goto fail;
15214df27c4dSYan, Zheng 
15224df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
15232619ba1fSChris Mason 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
15242619ba1fSChris Mason 				(unsigned long)root->root_key.objectid,
15250f7d52f4SChris Mason 				root);
1526d68fc57bSYan, Zheng 	if (ret == 0)
15274df27c4dSYan, Zheng 		root->in_radix = 1;
1528d68fc57bSYan, Zheng 
15294df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
15304df27c4dSYan, Zheng 	radix_tree_preload_end();
15310f7d52f4SChris Mason 	if (ret) {
15324df27c4dSYan, Zheng 		if (ret == -EEXIST) {
15334df27c4dSYan, Zheng 			free_fs_root(root);
15344df27c4dSYan, Zheng 			goto again;
15350f7d52f4SChris Mason 		}
15364df27c4dSYan, Zheng 		goto fail;
15374df27c4dSYan, Zheng 	}
15384df27c4dSYan, Zheng 
1539edbd8d4eSChris Mason 	ret = btrfs_find_dead_roots(fs_info->tree_root,
15405d4f98a2SYan Zheng 				    root->root_key.objectid);
15414df27c4dSYan, Zheng 	WARN_ON(ret);
1542edbd8d4eSChris Mason 	return root;
15434df27c4dSYan, Zheng fail:
15444df27c4dSYan, Zheng 	free_fs_root(root);
15454df27c4dSYan, Zheng 	return ERR_PTR(ret);
1546edbd8d4eSChris Mason }
1547edbd8d4eSChris Mason 
154804160088SChris Mason static int btrfs_congested_fn(void *congested_data, int bdi_bits)
154904160088SChris Mason {
155004160088SChris Mason 	struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
155104160088SChris Mason 	int ret = 0;
155204160088SChris Mason 	struct btrfs_device *device;
155304160088SChris Mason 	struct backing_dev_info *bdi;
1554b7967db7SChris Mason 
15551f78160cSXiao Guangrong 	rcu_read_lock();
15561f78160cSXiao Guangrong 	list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1557dfe25020SChris Mason 		if (!device->bdev)
1558dfe25020SChris Mason 			continue;
155904160088SChris Mason 		bdi = blk_get_backing_dev_info(device->bdev);
156004160088SChris Mason 		if (bdi && bdi_congested(bdi, bdi_bits)) {
156104160088SChris Mason 			ret = 1;
156204160088SChris Mason 			break;
156304160088SChris Mason 		}
156404160088SChris Mason 	}
15651f78160cSXiao Guangrong 	rcu_read_unlock();
156604160088SChris Mason 	return ret;
156704160088SChris Mason }
156804160088SChris Mason 
156938b66988SChris Mason /*
1570ad081f14SJens Axboe  * If this fails, caller must call bdi_destroy() to get rid of the
1571ad081f14SJens Axboe  * bdi again.
1572ad081f14SJens Axboe  */
157304160088SChris Mason static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
157404160088SChris Mason {
1575ad081f14SJens Axboe 	int err;
1576ad081f14SJens Axboe 
1577ad081f14SJens Axboe 	bdi->capabilities = BDI_CAP_MAP_COPY;
1578e6d086d8SJens Axboe 	err = bdi_setup_and_register(bdi, "btrfs", BDI_CAP_MAP_COPY);
1579ad081f14SJens Axboe 	if (err)
1580ad081f14SJens Axboe 		return err;
1581ad081f14SJens Axboe 
15824575c9ccSChris Mason 	bdi->ra_pages	= default_backing_dev_info.ra_pages;
158304160088SChris Mason 	bdi->congested_fn	= btrfs_congested_fn;
158404160088SChris Mason 	bdi->congested_data	= info;
158504160088SChris Mason 	return 0;
158604160088SChris Mason }
158704160088SChris Mason 
15888b712842SChris Mason /*
15898b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
15908b712842SChris Mason  * functions.  This is where read checksum verification actually happens
15918b712842SChris Mason  */
15928b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1593ce9adaa5SChris Mason {
1594ce9adaa5SChris Mason 	struct bio *bio;
15958b712842SChris Mason 	struct end_io_wq *end_io_wq;
15968b712842SChris Mason 	struct btrfs_fs_info *fs_info;
1597ce9adaa5SChris Mason 	int error;
1598ce9adaa5SChris Mason 
15998b712842SChris Mason 	end_io_wq = container_of(work, struct end_io_wq, work);
1600ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16018b712842SChris Mason 	fs_info = end_io_wq->info;
16028b712842SChris Mason 
1603ce9adaa5SChris Mason 	error = end_io_wq->error;
1604ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1605ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
1606ce9adaa5SChris Mason 	kfree(end_io_wq);
1607ce9adaa5SChris Mason 	bio_endio(bio, error);
1608ce9adaa5SChris Mason }
160944b8bd7eSChris Mason 
1610a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1611a74a4b97SChris Mason {
1612a74a4b97SChris Mason 	struct btrfs_root *root = arg;
1613a74a4b97SChris Mason 
1614a74a4b97SChris Mason 	do {
1615a74a4b97SChris Mason 		vfs_check_frozen(root->fs_info->sb, SB_FREEZE_WRITE);
161676dda93cSYan, Zheng 
161776dda93cSYan, Zheng 		if (!(root->fs_info->sb->s_flags & MS_RDONLY) &&
161876dda93cSYan, Zheng 		    mutex_trylock(&root->fs_info->cleaner_mutex)) {
161924bbcf04SYan, Zheng 			btrfs_run_delayed_iputs(root);
1620a74a4b97SChris Mason 			btrfs_clean_old_snapshots(root);
1621a74a4b97SChris Mason 			mutex_unlock(&root->fs_info->cleaner_mutex);
16224cb5300bSChris Mason 			btrfs_run_defrag_inodes(root->fs_info);
162376dda93cSYan, Zheng 		}
1624a74a4b97SChris Mason 
1625a0acae0eSTejun Heo 		if (!try_to_freeze()) {
1626a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
16278929ecfaSYan, Zheng 			if (!kthread_should_stop())
1628a74a4b97SChris Mason 				schedule();
1629a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1630a74a4b97SChris Mason 		}
1631a74a4b97SChris Mason 	} while (!kthread_should_stop());
1632a74a4b97SChris Mason 	return 0;
1633a74a4b97SChris Mason }
1634a74a4b97SChris Mason 
1635a74a4b97SChris Mason static int transaction_kthread(void *arg)
1636a74a4b97SChris Mason {
1637a74a4b97SChris Mason 	struct btrfs_root *root = arg;
1638a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1639a74a4b97SChris Mason 	struct btrfs_transaction *cur;
16408929ecfaSYan, Zheng 	u64 transid;
1641a74a4b97SChris Mason 	unsigned long now;
1642a74a4b97SChris Mason 	unsigned long delay;
1643914b2007SJan Kara 	bool cannot_commit;
1644a74a4b97SChris Mason 
1645a74a4b97SChris Mason 	do {
1646914b2007SJan Kara 		cannot_commit = false;
1647a74a4b97SChris Mason 		delay = HZ * 30;
1648a74a4b97SChris Mason 		vfs_check_frozen(root->fs_info->sb, SB_FREEZE_WRITE);
1649a74a4b97SChris Mason 		mutex_lock(&root->fs_info->transaction_kthread_mutex);
1650a74a4b97SChris Mason 
1651a4abeea4SJosef Bacik 		spin_lock(&root->fs_info->trans_lock);
1652a74a4b97SChris Mason 		cur = root->fs_info->running_transaction;
1653a74a4b97SChris Mason 		if (!cur) {
1654a4abeea4SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
1655a74a4b97SChris Mason 			goto sleep;
1656a74a4b97SChris Mason 		}
165731153d81SYan Zheng 
1658a74a4b97SChris Mason 		now = get_seconds();
16598929ecfaSYan, Zheng 		if (!cur->blocked &&
16608929ecfaSYan, Zheng 		    (now < cur->start_time || now - cur->start_time < 30)) {
1661a4abeea4SJosef Bacik 			spin_unlock(&root->fs_info->trans_lock);
1662a74a4b97SChris Mason 			delay = HZ * 5;
1663a74a4b97SChris Mason 			goto sleep;
1664a74a4b97SChris Mason 		}
16658929ecfaSYan, Zheng 		transid = cur->transid;
1666a4abeea4SJosef Bacik 		spin_unlock(&root->fs_info->trans_lock);
166756bec294SChris Mason 
166879787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
16697a7eaa40SJosef Bacik 		trans = btrfs_join_transaction(root);
1670914b2007SJan Kara 		if (IS_ERR(trans)) {
1671914b2007SJan Kara 			cannot_commit = true;
167279787eaaSJeff Mahoney 			goto sleep;
1673914b2007SJan Kara 		}
16748929ecfaSYan, Zheng 		if (transid == trans->transid) {
167579787eaaSJeff Mahoney 			btrfs_commit_transaction(trans, root);
16768929ecfaSYan, Zheng 		} else {
16778929ecfaSYan, Zheng 			btrfs_end_transaction(trans, root);
16788929ecfaSYan, Zheng 		}
1679a74a4b97SChris Mason sleep:
1680a74a4b97SChris Mason 		wake_up_process(root->fs_info->cleaner_kthread);
1681a74a4b97SChris Mason 		mutex_unlock(&root->fs_info->transaction_kthread_mutex);
1682a74a4b97SChris Mason 
1683a0acae0eSTejun Heo 		if (!try_to_freeze()) {
1684a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
16858929ecfaSYan, Zheng 			if (!kthread_should_stop() &&
1686914b2007SJan Kara 			    (!btrfs_transaction_blocked(root->fs_info) ||
1687914b2007SJan Kara 			     cannot_commit))
1688a74a4b97SChris Mason 				schedule_timeout(delay);
1689a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1690a74a4b97SChris Mason 		}
1691a74a4b97SChris Mason 	} while (!kthread_should_stop());
1692a74a4b97SChris Mason 	return 0;
1693a74a4b97SChris Mason }
1694a74a4b97SChris Mason 
1695af31f5e5SChris Mason /*
1696af31f5e5SChris Mason  * this will find the highest generation in the array of
1697af31f5e5SChris Mason  * root backups.  The index of the highest array is returned,
1698af31f5e5SChris Mason  * or -1 if we can't find anything.
1699af31f5e5SChris Mason  *
1700af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1701af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1702af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1703af31f5e5SChris Mason  */
1704af31f5e5SChris Mason static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1705af31f5e5SChris Mason {
1706af31f5e5SChris Mason 	u64 cur;
1707af31f5e5SChris Mason 	int newest_index = -1;
1708af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1709af31f5e5SChris Mason 	int i;
1710af31f5e5SChris Mason 
1711af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1712af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1713af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1714af31f5e5SChris Mason 		if (cur == newest_gen)
1715af31f5e5SChris Mason 			newest_index = i;
1716af31f5e5SChris Mason 	}
1717af31f5e5SChris Mason 
1718af31f5e5SChris Mason 	/* check to see if we actually wrapped around */
1719af31f5e5SChris Mason 	if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1720af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots;
1721af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1722af31f5e5SChris Mason 		if (cur == newest_gen)
1723af31f5e5SChris Mason 			newest_index = 0;
1724af31f5e5SChris Mason 	}
1725af31f5e5SChris Mason 	return newest_index;
1726af31f5e5SChris Mason }
1727af31f5e5SChris Mason 
1728af31f5e5SChris Mason 
1729af31f5e5SChris Mason /*
1730af31f5e5SChris Mason  * find the oldest backup so we know where to store new entries
1731af31f5e5SChris Mason  * in the backup array.  This will set the backup_root_index
1732af31f5e5SChris Mason  * field in the fs_info struct
1733af31f5e5SChris Mason  */
1734af31f5e5SChris Mason static void find_oldest_super_backup(struct btrfs_fs_info *info,
1735af31f5e5SChris Mason 				     u64 newest_gen)
1736af31f5e5SChris Mason {
1737af31f5e5SChris Mason 	int newest_index = -1;
1738af31f5e5SChris Mason 
1739af31f5e5SChris Mason 	newest_index = find_newest_super_backup(info, newest_gen);
1740af31f5e5SChris Mason 	/* if there was garbage in there, just move along */
1741af31f5e5SChris Mason 	if (newest_index == -1) {
1742af31f5e5SChris Mason 		info->backup_root_index = 0;
1743af31f5e5SChris Mason 	} else {
1744af31f5e5SChris Mason 		info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1745af31f5e5SChris Mason 	}
1746af31f5e5SChris Mason }
1747af31f5e5SChris Mason 
1748af31f5e5SChris Mason /*
1749af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1750af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1751af31f5e5SChris Mason  * done
1752af31f5e5SChris Mason  */
1753af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1754af31f5e5SChris Mason {
1755af31f5e5SChris Mason 	int next_backup;
1756af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1757af31f5e5SChris Mason 	int last_backup;
1758af31f5e5SChris Mason 
1759af31f5e5SChris Mason 	next_backup = info->backup_root_index;
1760af31f5e5SChris Mason 	last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1761af31f5e5SChris Mason 		BTRFS_NUM_BACKUP_ROOTS;
1762af31f5e5SChris Mason 
1763af31f5e5SChris Mason 	/*
1764af31f5e5SChris Mason 	 * just overwrite the last backup if we're at the same generation
1765af31f5e5SChris Mason 	 * this happens only at umount
1766af31f5e5SChris Mason 	 */
1767af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + last_backup;
1768af31f5e5SChris Mason 	if (btrfs_backup_tree_root_gen(root_backup) ==
1769af31f5e5SChris Mason 	    btrfs_header_generation(info->tree_root->node))
1770af31f5e5SChris Mason 		next_backup = last_backup;
1771af31f5e5SChris Mason 
1772af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1773af31f5e5SChris Mason 
1774af31f5e5SChris Mason 	/*
1775af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1776af31f5e5SChris Mason 	 * regardless of which ones we use today
1777af31f5e5SChris Mason 	 */
1778af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1779af31f5e5SChris Mason 
1780af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1781af31f5e5SChris Mason 
1782af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1783af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1784af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1785af31f5e5SChris Mason 
1786af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1787af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1788af31f5e5SChris Mason 
1789af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1790af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1791af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1792af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1793af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1794af31f5e5SChris Mason 
1795af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1796af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1797af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1798af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1799af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1800af31f5e5SChris Mason 
18017c7e82a7SChris Mason 	/*
18027c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18037c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18047c7e82a7SChris Mason 	 */
18057c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18067c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18077c7e82a7SChris Mason 					 info->fs_root->node->start);
1808af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1809af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1810af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1811af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
18127c7e82a7SChris Mason 	}
1813af31f5e5SChris Mason 
1814af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1815af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1816af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1817af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1818af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1819af31f5e5SChris Mason 
1820af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1821af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1822af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1823af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1824af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1825af31f5e5SChris Mason 
1826af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1827af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1828af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1829af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1830af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1831af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1832af31f5e5SChris Mason 
1833af31f5e5SChris Mason 	/*
1834af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1835af31f5e5SChris Mason 	 * for the next commit
1836af31f5e5SChris Mason 	 */
1837af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1838af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1839af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1840af31f5e5SChris Mason }
1841af31f5e5SChris Mason 
1842af31f5e5SChris Mason /*
1843af31f5e5SChris Mason  * this copies info out of the root backup array and back into
1844af31f5e5SChris Mason  * the in-memory super block.  It is meant to help iterate through
1845af31f5e5SChris Mason  * the array, so you send it the number of backups you've already
1846af31f5e5SChris Mason  * tried and the last backup index you used.
1847af31f5e5SChris Mason  *
1848af31f5e5SChris Mason  * this returns -1 when it has tried all the backups
1849af31f5e5SChris Mason  */
1850af31f5e5SChris Mason static noinline int next_root_backup(struct btrfs_fs_info *info,
1851af31f5e5SChris Mason 				     struct btrfs_super_block *super,
1852af31f5e5SChris Mason 				     int *num_backups_tried, int *backup_index)
1853af31f5e5SChris Mason {
1854af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1855af31f5e5SChris Mason 	int newest = *backup_index;
1856af31f5e5SChris Mason 
1857af31f5e5SChris Mason 	if (*num_backups_tried == 0) {
1858af31f5e5SChris Mason 		u64 gen = btrfs_super_generation(super);
1859af31f5e5SChris Mason 
1860af31f5e5SChris Mason 		newest = find_newest_super_backup(info, gen);
1861af31f5e5SChris Mason 		if (newest == -1)
1862af31f5e5SChris Mason 			return -1;
1863af31f5e5SChris Mason 
1864af31f5e5SChris Mason 		*backup_index = newest;
1865af31f5e5SChris Mason 		*num_backups_tried = 1;
1866af31f5e5SChris Mason 	} else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1867af31f5e5SChris Mason 		/* we've tried all the backups, all done */
1868af31f5e5SChris Mason 		return -1;
1869af31f5e5SChris Mason 	} else {
1870af31f5e5SChris Mason 		/* jump to the next oldest backup */
1871af31f5e5SChris Mason 		newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1872af31f5e5SChris Mason 			BTRFS_NUM_BACKUP_ROOTS;
1873af31f5e5SChris Mason 		*backup_index = newest;
1874af31f5e5SChris Mason 		*num_backups_tried += 1;
1875af31f5e5SChris Mason 	}
1876af31f5e5SChris Mason 	root_backup = super->super_roots + newest;
1877af31f5e5SChris Mason 
1878af31f5e5SChris Mason 	btrfs_set_super_generation(super,
1879af31f5e5SChris Mason 				   btrfs_backup_tree_root_gen(root_backup));
1880af31f5e5SChris Mason 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1881af31f5e5SChris Mason 	btrfs_set_super_root_level(super,
1882af31f5e5SChris Mason 				   btrfs_backup_tree_root_level(root_backup));
1883af31f5e5SChris Mason 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1884af31f5e5SChris Mason 
1885af31f5e5SChris Mason 	/*
1886af31f5e5SChris Mason 	 * fixme: the total bytes and num_devices need to match or we should
1887af31f5e5SChris Mason 	 * need a fsck
1888af31f5e5SChris Mason 	 */
1889af31f5e5SChris Mason 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1890af31f5e5SChris Mason 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1891af31f5e5SChris Mason 	return 0;
1892af31f5e5SChris Mason }
1893af31f5e5SChris Mason 
1894af31f5e5SChris Mason /* helper to cleanup tree roots */
1895af31f5e5SChris Mason static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
1896af31f5e5SChris Mason {
1897af31f5e5SChris Mason 	free_extent_buffer(info->tree_root->node);
1898af31f5e5SChris Mason 	free_extent_buffer(info->tree_root->commit_root);
1899af31f5e5SChris Mason 	free_extent_buffer(info->dev_root->node);
1900af31f5e5SChris Mason 	free_extent_buffer(info->dev_root->commit_root);
1901af31f5e5SChris Mason 	free_extent_buffer(info->extent_root->node);
1902af31f5e5SChris Mason 	free_extent_buffer(info->extent_root->commit_root);
1903af31f5e5SChris Mason 	free_extent_buffer(info->csum_root->node);
1904af31f5e5SChris Mason 	free_extent_buffer(info->csum_root->commit_root);
1905bcef60f2SArne Jansen 	if (info->quota_root) {
1906bcef60f2SArne Jansen 		free_extent_buffer(info->quota_root->node);
1907bcef60f2SArne Jansen 		free_extent_buffer(info->quota_root->commit_root);
1908bcef60f2SArne Jansen 	}
1909af31f5e5SChris Mason 
1910af31f5e5SChris Mason 	info->tree_root->node = NULL;
1911af31f5e5SChris Mason 	info->tree_root->commit_root = NULL;
1912af31f5e5SChris Mason 	info->dev_root->node = NULL;
1913af31f5e5SChris Mason 	info->dev_root->commit_root = NULL;
1914af31f5e5SChris Mason 	info->extent_root->node = NULL;
1915af31f5e5SChris Mason 	info->extent_root->commit_root = NULL;
1916af31f5e5SChris Mason 	info->csum_root->node = NULL;
1917af31f5e5SChris Mason 	info->csum_root->commit_root = NULL;
1918bcef60f2SArne Jansen 	if (info->quota_root) {
1919bcef60f2SArne Jansen 		info->quota_root->node = NULL;
1920bcef60f2SArne Jansen 		info->quota_root->commit_root = NULL;
1921bcef60f2SArne Jansen 	}
1922af31f5e5SChris Mason 
1923af31f5e5SChris Mason 	if (chunk_root) {
1924af31f5e5SChris Mason 		free_extent_buffer(info->chunk_root->node);
1925af31f5e5SChris Mason 		free_extent_buffer(info->chunk_root->commit_root);
1926af31f5e5SChris Mason 		info->chunk_root->node = NULL;
1927af31f5e5SChris Mason 		info->chunk_root->commit_root = NULL;
1928af31f5e5SChris Mason 	}
1929af31f5e5SChris Mason }
1930af31f5e5SChris Mason 
1931af31f5e5SChris Mason 
1932ad2b2c80SAl Viro int open_ctree(struct super_block *sb,
1933dfe25020SChris Mason 	       struct btrfs_fs_devices *fs_devices,
1934dfe25020SChris Mason 	       char *options)
1935eb60ceacSChris Mason {
1936db94535dSChris Mason 	u32 sectorsize;
1937db94535dSChris Mason 	u32 nodesize;
1938db94535dSChris Mason 	u32 leafsize;
1939db94535dSChris Mason 	u32 blocksize;
194087ee04ebSChris Mason 	u32 stripesize;
194184234f3aSYan Zheng 	u64 generation;
1942f2b636e8SJosef Bacik 	u64 features;
19433de4586cSChris Mason 	struct btrfs_key location;
1944a061fc8dSChris Mason 	struct buffer_head *bh;
19454d34b278SIlya Dryomov 	struct btrfs_super_block *disk_super;
1946815745cfSAl Viro 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1947f84a8bd6SAl Viro 	struct btrfs_root *tree_root;
19484d34b278SIlya Dryomov 	struct btrfs_root *extent_root;
19494d34b278SIlya Dryomov 	struct btrfs_root *csum_root;
19504d34b278SIlya Dryomov 	struct btrfs_root *chunk_root;
19514d34b278SIlya Dryomov 	struct btrfs_root *dev_root;
1952bcef60f2SArne Jansen 	struct btrfs_root *quota_root;
1953e02119d5SChris Mason 	struct btrfs_root *log_tree_root;
1954eb60ceacSChris Mason 	int ret;
1955e58ca020SYan 	int err = -EINVAL;
1956af31f5e5SChris Mason 	int num_backups_tried = 0;
1957af31f5e5SChris Mason 	int backup_index = 0;
19584543df7eSChris Mason 
1959f84a8bd6SAl Viro 	tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info);
19606f07e42eSAl Viro 	extent_root = fs_info->extent_root = btrfs_alloc_root(fs_info);
19616f07e42eSAl Viro 	csum_root = fs_info->csum_root = btrfs_alloc_root(fs_info);
19626f07e42eSAl Viro 	chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info);
19636f07e42eSAl Viro 	dev_root = fs_info->dev_root = btrfs_alloc_root(fs_info);
1964bcef60f2SArne Jansen 	quota_root = fs_info->quota_root = btrfs_alloc_root(fs_info);
19658790d502SChris Mason 
1966f84a8bd6SAl Viro 	if (!tree_root || !extent_root || !csum_root ||
1967bcef60f2SArne Jansen 	    !chunk_root || !dev_root || !quota_root) {
196839279cc3SChris Mason 		err = -ENOMEM;
196939279cc3SChris Mason 		goto fail;
197039279cc3SChris Mason 	}
197176dda93cSYan, Zheng 
197276dda93cSYan, Zheng 	ret = init_srcu_struct(&fs_info->subvol_srcu);
197376dda93cSYan, Zheng 	if (ret) {
197476dda93cSYan, Zheng 		err = ret;
197576dda93cSYan, Zheng 		goto fail;
197676dda93cSYan, Zheng 	}
197776dda93cSYan, Zheng 
197876dda93cSYan, Zheng 	ret = setup_bdi(fs_info, &fs_info->bdi);
197976dda93cSYan, Zheng 	if (ret) {
198076dda93cSYan, Zheng 		err = ret;
198176dda93cSYan, Zheng 		goto fail_srcu;
198276dda93cSYan, Zheng 	}
198376dda93cSYan, Zheng 
198476dda93cSYan, Zheng 	fs_info->btree_inode = new_inode(sb);
198576dda93cSYan, Zheng 	if (!fs_info->btree_inode) {
198676dda93cSYan, Zheng 		err = -ENOMEM;
198776dda93cSYan, Zheng 		goto fail_bdi;
198876dda93cSYan, Zheng 	}
198976dda93cSYan, Zheng 
1990a6591715SChris Mason 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
19911561dedaSMiao Xie 
199276dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
19938fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
1994facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
199524bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
199619c00ddcSChris Mason 	INIT_LIST_HEAD(&fs_info->hashers);
1997ea8c2819SChris Mason 	INIT_LIST_HEAD(&fs_info->delalloc_inodes);
19985a3f23d5SChris Mason 	INIT_LIST_HEAD(&fs_info->ordered_operations);
199911833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
20001832a6d5SChris Mason 	spin_lock_init(&fs_info->delalloc_lock);
2001a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
200231153d81SYan Zheng 	spin_lock_init(&fs_info->ref_cache_lock);
200376dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
200424bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
20054cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
20062bf64758SJosef Bacik 	spin_lock_init(&fs_info->free_chunk_lock);
2007f29021b2SJan Schmidt 	spin_lock_init(&fs_info->tree_mod_seq_lock);
2008f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
20097585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
201019c00ddcSChris Mason 
201158176a96SJosef Bacik 	init_completion(&fs_info->kobj_unregister);
20120b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
20136324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2014f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
20150b86a832SChris Mason 	btrfs_mapping_init(&fs_info->mapping_tree);
2016f0486c68SYan, Zheng 	btrfs_init_block_rsv(&fs_info->global_block_rsv);
2017f0486c68SYan, Zheng 	btrfs_init_block_rsv(&fs_info->delalloc_block_rsv);
2018f0486c68SYan, Zheng 	btrfs_init_block_rsv(&fs_info->trans_block_rsv);
2019f0486c68SYan, Zheng 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv);
2020f0486c68SYan, Zheng 	btrfs_init_block_rsv(&fs_info->empty_block_rsv);
20216d668ddaSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv);
2022cb03c743SChris Mason 	atomic_set(&fs_info->nr_async_submits, 0);
2023771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
20248c8bee1dSChris Mason 	atomic_set(&fs_info->async_submit_draining, 0);
20250986fe9eSChris Mason 	atomic_set(&fs_info->nr_async_bios, 0);
20264cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2027f29021b2SJan Schmidt 	atomic_set(&fs_info->tree_mod_seq, 0);
2028e20d96d6SChris Mason 	fs_info->sb = sb;
20296f568d35SChris Mason 	fs_info->max_inline = 8192 * 1024;
20309ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
20314cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2032a4abeea4SJosef Bacik 	fs_info->trans_no_join = 0;
20332bf64758SJosef Bacik 	fs_info->free_chunk_space = 0;
2034f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
2035c8b97818SChris Mason 
2036097b8a7cSJan Schmidt 	init_waitqueue_head(&fs_info->tree_mod_seq_wait);
2037097b8a7cSJan Schmidt 
203890519d66SArne Jansen 	/* readahead state */
203990519d66SArne Jansen 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_WAIT);
204090519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
20412c90e5d6SChris Mason 
2042b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2043b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
20440afbaf8cSChris Mason 
20453eaa2885SChris Mason 	INIT_LIST_HEAD(&fs_info->ordered_extents);
20463eaa2885SChris Mason 	spin_lock_init(&fs_info->ordered_extent_lock);
204716cdcec7SMiao Xie 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
204816cdcec7SMiao Xie 					GFP_NOFS);
204916cdcec7SMiao Xie 	if (!fs_info->delayed_root) {
205016cdcec7SMiao Xie 		err = -ENOMEM;
205116cdcec7SMiao Xie 		goto fail_iput;
205216cdcec7SMiao Xie 	}
205316cdcec7SMiao Xie 	btrfs_init_delayed_root(fs_info->delayed_root);
20543eaa2885SChris Mason 
2055a2de733cSArne Jansen 	mutex_init(&fs_info->scrub_lock);
2056a2de733cSArne Jansen 	atomic_set(&fs_info->scrubs_running, 0);
2057a2de733cSArne Jansen 	atomic_set(&fs_info->scrub_pause_req, 0);
2058a2de733cSArne Jansen 	atomic_set(&fs_info->scrubs_paused, 0);
2059a2de733cSArne Jansen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2060a2de733cSArne Jansen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2061a2de733cSArne Jansen 	init_rwsem(&fs_info->scrub_super_lock);
2062a2de733cSArne Jansen 	fs_info->scrub_workers_refcnt = 0;
206321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
206421adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
206521adbd5cSStefan Behrens #endif
2066a2de733cSArne Jansen 
2067c9e9f97bSIlya Dryomov 	spin_lock_init(&fs_info->balance_lock);
2068c9e9f97bSIlya Dryomov 	mutex_init(&fs_info->balance_mutex);
2069837d5b6eSIlya Dryomov 	atomic_set(&fs_info->balance_running, 0);
2070837d5b6eSIlya Dryomov 	atomic_set(&fs_info->balance_pause_req, 0);
2071a7e99c69SIlya Dryomov 	atomic_set(&fs_info->balance_cancel_req, 0);
2072c9e9f97bSIlya Dryomov 	fs_info->balance_ctl = NULL;
2073837d5b6eSIlya Dryomov 	init_waitqueue_head(&fs_info->balance_wait_q);
2074a061fc8dSChris Mason 
20750afbaf8cSChris Mason 	sb->s_blocksize = 4096;
20760afbaf8cSChris Mason 	sb->s_blocksize_bits = blksize_bits(4096);
207732a88aa1SJens Axboe 	sb->s_bdi = &fs_info->bdi;
20780afbaf8cSChris Mason 
207976dda93cSYan, Zheng 	fs_info->btree_inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2080bfe86848SMiklos Szeredi 	set_nlink(fs_info->btree_inode, 1);
20810afbaf8cSChris Mason 	/*
20820afbaf8cSChris Mason 	 * we set the i_size on the btree inode to the max possible int.
20830afbaf8cSChris Mason 	 * the real end of the address space is determined by all of
20840afbaf8cSChris Mason 	 * the devices in the system
20850afbaf8cSChris Mason 	 */
20860afbaf8cSChris Mason 	fs_info->btree_inode->i_size = OFFSET_MAX;
2087d98237b3SChris Mason 	fs_info->btree_inode->i_mapping->a_ops = &btree_aops;
208804160088SChris Mason 	fs_info->btree_inode->i_mapping->backing_dev_info = &fs_info->bdi;
208904160088SChris Mason 
20905d4f98a2SYan Zheng 	RB_CLEAR_NODE(&BTRFS_I(fs_info->btree_inode)->rb_node);
2091d1310b2eSChris Mason 	extent_io_tree_init(&BTRFS_I(fs_info->btree_inode)->io_tree,
2092f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
20930b32f4bbSJosef Bacik 	BTRFS_I(fs_info->btree_inode)->io_tree.track_uptodate = 0;
2094a8067e02SDavid Sterba 	extent_map_tree_init(&BTRFS_I(fs_info->btree_inode)->extent_tree);
20950da5468fSChris Mason 
2096d1310b2eSChris Mason 	BTRFS_I(fs_info->btree_inode)->io_tree.ops = &btree_extent_io_ops;
2097d1310b2eSChris Mason 
20980f7d52f4SChris Mason 	BTRFS_I(fs_info->btree_inode)->root = tree_root;
20990f7d52f4SChris Mason 	memset(&BTRFS_I(fs_info->btree_inode)->location, 0,
21000f7d52f4SChris Mason 	       sizeof(struct btrfs_key));
210172ac3c0dSJosef Bacik 	set_bit(BTRFS_INODE_DUMMY,
210272ac3c0dSJosef Bacik 		&BTRFS_I(fs_info->btree_inode)->runtime_flags);
210322b0ebdaSChris Mason 	insert_inode_hash(fs_info->btree_inode);
210439279cc3SChris Mason 
2105e02119d5SChris Mason 	spin_lock_init(&fs_info->block_group_cache_lock);
21066bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2107925baeddSChris Mason 
210811833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[0],
2109f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
211011833d66SYan Zheng 	extent_io_tree_init(&fs_info->freed_extents[1],
2111f993c883SDavid Sterba 			     fs_info->btree_inode->i_mapping);
211211833d66SYan Zheng 	fs_info->pinned_extents = &fs_info->freed_extents[0];
2113e6dcd2dcSChris Mason 	fs_info->do_barriers = 1;
2114f9295749SChris Mason 
2115d98237b3SChris Mason 
21165a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
211730ae8467SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2118925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2119925baeddSChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2120a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
2121a74a4b97SChris Mason 	mutex_init(&fs_info->volume_mutex);
2122276e680dSYan Zheng 	init_rwsem(&fs_info->extent_commit_sem);
2123c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
212476dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2125fa9c0d79SChris Mason 
2126416ac51dSArne Jansen 	spin_lock_init(&fs_info->qgroup_lock);
2127416ac51dSArne Jansen 	fs_info->qgroup_tree = RB_ROOT;
2128416ac51dSArne Jansen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2129416ac51dSArne Jansen 	fs_info->qgroup_seq = 1;
2130416ac51dSArne Jansen 	fs_info->quota_enabled = 0;
2131416ac51dSArne Jansen 	fs_info->pending_quota_state = 0;
2132416ac51dSArne Jansen 
2133fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2134fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2135fa9c0d79SChris Mason 
21367d9eb12cSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
21373768f368SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2138bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
21394854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
21409a8dd150SChris Mason 
21410b86a832SChris Mason 	__setup_root(4096, 4096, 4096, 4096, tree_root,
21422c90e5d6SChris Mason 		     fs_info, BTRFS_ROOT_TREE_OBJECTID);
21437eccb903SChris Mason 
21443c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
2145a512bbf8SYan Zheng 	bh = btrfs_read_dev_super(fs_devices->latest_bdev);
214620b45077SDave Young 	if (!bh) {
214720b45077SDave Young 		err = -EINVAL;
214816cdcec7SMiao Xie 		goto fail_alloc;
214920b45077SDave Young 	}
215039279cc3SChris Mason 
21516c41761fSDavid Sterba 	memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
21526c41761fSDavid Sterba 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
21536c41761fSDavid Sterba 	       sizeof(*fs_info->super_for_commit));
2154a061fc8dSChris Mason 	brelse(bh);
21555f39d397SChris Mason 
21566c41761fSDavid Sterba 	memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
21570b86a832SChris Mason 
21586c41761fSDavid Sterba 	disk_super = fs_info->super_copy;
21590f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
216016cdcec7SMiao Xie 		goto fail_alloc;
21610f7d52f4SChris Mason 
2162acce952bSliubo 	/* check FS state, whether FS is broken. */
2163acce952bSliubo 	fs_info->fs_state |= btrfs_super_flags(disk_super);
2164acce952bSliubo 
2165fcd1f065SDavid Sterba 	ret = btrfs_check_super_valid(fs_info, sb->s_flags & MS_RDONLY);
2166fcd1f065SDavid Sterba 	if (ret) {
2167fcd1f065SDavid Sterba 		printk(KERN_ERR "btrfs: superblock contains fatal errors\n");
2168fcd1f065SDavid Sterba 		err = ret;
2169fcd1f065SDavid Sterba 		goto fail_alloc;
2170fcd1f065SDavid Sterba 	}
2171acce952bSliubo 
217275e7cb7fSLiu Bo 	/*
2173af31f5e5SChris Mason 	 * run through our array of backup supers and setup
2174af31f5e5SChris Mason 	 * our ring pointer to the oldest one
2175af31f5e5SChris Mason 	 */
2176af31f5e5SChris Mason 	generation = btrfs_super_generation(disk_super);
2177af31f5e5SChris Mason 	find_oldest_super_backup(fs_info, generation);
2178af31f5e5SChris Mason 
2179af31f5e5SChris Mason 	/*
218075e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
218175e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
218275e7cb7fSLiu Bo 	 */
218375e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
218475e7cb7fSLiu Bo 
21852b82032cSYan Zheng 	ret = btrfs_parse_options(tree_root, options);
21862b82032cSYan Zheng 	if (ret) {
21872b82032cSYan Zheng 		err = ret;
218816cdcec7SMiao Xie 		goto fail_alloc;
21892b82032cSYan Zheng 	}
2190dfe25020SChris Mason 
2191f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
2192f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
2193f2b636e8SJosef Bacik 	if (features) {
2194f2b636e8SJosef Bacik 		printk(KERN_ERR "BTRFS: couldn't mount because of "
2195f2b636e8SJosef Bacik 		       "unsupported optional features (%Lx).\n",
219621380931SJoel Becker 		       (unsigned long long)features);
2197f2b636e8SJosef Bacik 		err = -EINVAL;
219816cdcec7SMiao Xie 		goto fail_alloc;
2199f2b636e8SJosef Bacik 	}
2200f2b636e8SJosef Bacik 
2201727011e0SChris Mason 	if (btrfs_super_leafsize(disk_super) !=
2202727011e0SChris Mason 	    btrfs_super_nodesize(disk_super)) {
2203727011e0SChris Mason 		printk(KERN_ERR "BTRFS: couldn't mount because metadata "
2204727011e0SChris Mason 		       "blocksizes don't match.  node %d leaf %d\n",
2205727011e0SChris Mason 		       btrfs_super_nodesize(disk_super),
2206727011e0SChris Mason 		       btrfs_super_leafsize(disk_super));
2207727011e0SChris Mason 		err = -EINVAL;
2208727011e0SChris Mason 		goto fail_alloc;
2209727011e0SChris Mason 	}
2210727011e0SChris Mason 	if (btrfs_super_leafsize(disk_super) > BTRFS_MAX_METADATA_BLOCKSIZE) {
2211727011e0SChris Mason 		printk(KERN_ERR "BTRFS: couldn't mount because metadata "
2212727011e0SChris Mason 		       "blocksize (%d) was too large\n",
2213727011e0SChris Mason 		       btrfs_super_leafsize(disk_super));
2214727011e0SChris Mason 		err = -EINVAL;
2215727011e0SChris Mason 		goto fail_alloc;
2216727011e0SChris Mason 	}
2217727011e0SChris Mason 
22185d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
22195d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
222069e380d1SLi Zefan 	if (tree_root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
2221a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2222727011e0SChris Mason 
2223727011e0SChris Mason 	/*
2224727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
2225727011e0SChris Mason 	 * they are bigger than the page size
2226727011e0SChris Mason 	 */
2227727011e0SChris Mason 	if (btrfs_super_leafsize(disk_super) > PAGE_CACHE_SIZE) {
2228727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2229727011e0SChris Mason 			printk(KERN_INFO "btrfs flagging fs with big metadata feature\n");
2230727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2231727011e0SChris Mason 	}
2232727011e0SChris Mason 
2233bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
2234bc3f116fSChris Mason 	leafsize = btrfs_super_leafsize(disk_super);
2235bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
2236bc3f116fSChris Mason 	stripesize = btrfs_super_stripesize(disk_super);
2237bc3f116fSChris Mason 
2238bc3f116fSChris Mason 	/*
2239bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
2240bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
2241bc3f116fSChris Mason 	 */
2242bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2243bc3f116fSChris Mason 	    (sectorsize != leafsize)) {
2244bc3f116fSChris Mason 		printk(KERN_WARNING "btrfs: unequal leaf/node/sector sizes "
2245bc3f116fSChris Mason 				"are not allowed for mixed block groups on %s\n",
2246bc3f116fSChris Mason 				sb->s_id);
2247bc3f116fSChris Mason 		goto fail_alloc;
2248bc3f116fSChris Mason 	}
2249bc3f116fSChris Mason 
22505d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
22515d4f98a2SYan Zheng 
2252f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
2253f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
2254f2b636e8SJosef Bacik 	if (!(sb->s_flags & MS_RDONLY) && features) {
2255f2b636e8SJosef Bacik 		printk(KERN_ERR "BTRFS: couldn't mount RDWR because of "
2256f2b636e8SJosef Bacik 		       "unsupported option features (%Lx).\n",
225721380931SJoel Becker 		       (unsigned long long)features);
2258f2b636e8SJosef Bacik 		err = -EINVAL;
225916cdcec7SMiao Xie 		goto fail_alloc;
2260f2b636e8SJosef Bacik 	}
226161d92c32SChris Mason 
226261d92c32SChris Mason 	btrfs_init_workers(&fs_info->generic_worker,
226361d92c32SChris Mason 			   "genwork", 1, NULL);
226461d92c32SChris Mason 
22655443be45SChris Mason 	btrfs_init_workers(&fs_info->workers, "worker",
226661d92c32SChris Mason 			   fs_info->thread_pool_size,
226761d92c32SChris Mason 			   &fs_info->generic_worker);
2268c8b97818SChris Mason 
2269771ed689SChris Mason 	btrfs_init_workers(&fs_info->delalloc_workers, "delalloc",
227061d92c32SChris Mason 			   fs_info->thread_pool_size,
227161d92c32SChris Mason 			   &fs_info->generic_worker);
2272771ed689SChris Mason 
22735443be45SChris Mason 	btrfs_init_workers(&fs_info->submit_workers, "submit",
2274b720d209SChris Mason 			   min_t(u64, fs_devices->num_devices,
227561d92c32SChris Mason 			   fs_info->thread_pool_size),
227661d92c32SChris Mason 			   &fs_info->generic_worker);
227761b49440SChris Mason 
2278bab39bf9SJosef Bacik 	btrfs_init_workers(&fs_info->caching_workers, "cache",
2279bab39bf9SJosef Bacik 			   2, &fs_info->generic_worker);
2280bab39bf9SJosef Bacik 
228161b49440SChris Mason 	/* a higher idle thresh on the submit workers makes it much more
228261b49440SChris Mason 	 * likely that bios will be send down in a sane order to the
228361b49440SChris Mason 	 * devices
228461b49440SChris Mason 	 */
228561b49440SChris Mason 	fs_info->submit_workers.idle_thresh = 64;
228653863232SChris Mason 
2287771ed689SChris Mason 	fs_info->workers.idle_thresh = 16;
22884a69a410SChris Mason 	fs_info->workers.ordered = 1;
228961b49440SChris Mason 
2290771ed689SChris Mason 	fs_info->delalloc_workers.idle_thresh = 2;
2291771ed689SChris Mason 	fs_info->delalloc_workers.ordered = 1;
2292771ed689SChris Mason 
229361d92c32SChris Mason 	btrfs_init_workers(&fs_info->fixup_workers, "fixup", 1,
229461d92c32SChris Mason 			   &fs_info->generic_worker);
22955443be45SChris Mason 	btrfs_init_workers(&fs_info->endio_workers, "endio",
229661d92c32SChris Mason 			   fs_info->thread_pool_size,
229761d92c32SChris Mason 			   &fs_info->generic_worker);
2298d20f7043SChris Mason 	btrfs_init_workers(&fs_info->endio_meta_workers, "endio-meta",
229961d92c32SChris Mason 			   fs_info->thread_pool_size,
230061d92c32SChris Mason 			   &fs_info->generic_worker);
2301cad321adSChris Mason 	btrfs_init_workers(&fs_info->endio_meta_write_workers,
230261d92c32SChris Mason 			   "endio-meta-write", fs_info->thread_pool_size,
230361d92c32SChris Mason 			   &fs_info->generic_worker);
23045443be45SChris Mason 	btrfs_init_workers(&fs_info->endio_write_workers, "endio-write",
230561d92c32SChris Mason 			   fs_info->thread_pool_size,
230661d92c32SChris Mason 			   &fs_info->generic_worker);
23070cb59c99SJosef Bacik 	btrfs_init_workers(&fs_info->endio_freespace_worker, "freespace-write",
23080cb59c99SJosef Bacik 			   1, &fs_info->generic_worker);
230916cdcec7SMiao Xie 	btrfs_init_workers(&fs_info->delayed_workers, "delayed-meta",
231016cdcec7SMiao Xie 			   fs_info->thread_pool_size,
231116cdcec7SMiao Xie 			   &fs_info->generic_worker);
231290519d66SArne Jansen 	btrfs_init_workers(&fs_info->readahead_workers, "readahead",
231390519d66SArne Jansen 			   fs_info->thread_pool_size,
231490519d66SArne Jansen 			   &fs_info->generic_worker);
231561b49440SChris Mason 
231661b49440SChris Mason 	/*
231761b49440SChris Mason 	 * endios are largely parallel and should have a very
231861b49440SChris Mason 	 * low idle thresh
231961b49440SChris Mason 	 */
232061b49440SChris Mason 	fs_info->endio_workers.idle_thresh = 4;
2321b51912c9SChris Mason 	fs_info->endio_meta_workers.idle_thresh = 4;
2322b51912c9SChris Mason 
23239042846bSChris Mason 	fs_info->endio_write_workers.idle_thresh = 2;
23249042846bSChris Mason 	fs_info->endio_meta_write_workers.idle_thresh = 2;
232590519d66SArne Jansen 	fs_info->readahead_workers.idle_thresh = 2;
23269042846bSChris Mason 
23270dc3b84aSJosef Bacik 	/*
23280dc3b84aSJosef Bacik 	 * btrfs_start_workers can really only fail because of ENOMEM so just
23290dc3b84aSJosef Bacik 	 * return -ENOMEM if any of these fail.
23300dc3b84aSJosef Bacik 	 */
23310dc3b84aSJosef Bacik 	ret = btrfs_start_workers(&fs_info->workers);
23320dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->generic_worker);
23330dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->submit_workers);
23340dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->delalloc_workers);
23350dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->fixup_workers);
23360dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->endio_workers);
23370dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->endio_meta_workers);
23380dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->endio_meta_write_workers);
23390dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->endio_write_workers);
23400dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->endio_freespace_worker);
23410dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->delayed_workers);
23420dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->caching_workers);
23430dc3b84aSJosef Bacik 	ret |= btrfs_start_workers(&fs_info->readahead_workers);
23440dc3b84aSJosef Bacik 	if (ret) {
23450dc3b84aSJosef Bacik 		ret = -ENOMEM;
23460dc3b84aSJosef Bacik 		goto fail_sb_buffer;
23470dc3b84aSJosef Bacik 	}
23484543df7eSChris Mason 
23494575c9ccSChris Mason 	fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
2350c8b97818SChris Mason 	fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
2351c8b97818SChris Mason 				    4 * 1024 * 1024 / PAGE_CACHE_SIZE);
23524575c9ccSChris Mason 
2353db94535dSChris Mason 	tree_root->nodesize = nodesize;
2354db94535dSChris Mason 	tree_root->leafsize = leafsize;
2355db94535dSChris Mason 	tree_root->sectorsize = sectorsize;
235687ee04ebSChris Mason 	tree_root->stripesize = stripesize;
2357a061fc8dSChris Mason 
2358a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
2359a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
2360db94535dSChris Mason 
236139279cc3SChris Mason 	if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
236239279cc3SChris Mason 		    sizeof(disk_super->magic))) {
2363d397712bSChris Mason 		printk(KERN_INFO "btrfs: valid FS not found on %s\n", sb->s_id);
236439279cc3SChris Mason 		goto fail_sb_buffer;
236539279cc3SChris Mason 	}
236619c00ddcSChris Mason 
23678d082fb7SLiu Bo 	if (sectorsize != PAGE_SIZE) {
23688d082fb7SLiu Bo 		printk(KERN_WARNING "btrfs: Incompatible sector size(%lu) "
23698d082fb7SLiu Bo 		       "found on %s\n", (unsigned long)sectorsize, sb->s_id);
2370941b2ddfSKeith Mannthey 		goto fail_sb_buffer;
2371941b2ddfSKeith Mannthey 	}
2372941b2ddfSKeith Mannthey 
2373925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
2374e4404d6eSYan Zheng 	ret = btrfs_read_sys_array(tree_root);
2375925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
237684eed90fSChris Mason 	if (ret) {
2377d397712bSChris Mason 		printk(KERN_WARNING "btrfs: failed to read the system "
2378d397712bSChris Mason 		       "array on %s\n", sb->s_id);
23795d4f98a2SYan Zheng 		goto fail_sb_buffer;
238084eed90fSChris Mason 	}
23810b86a832SChris Mason 
23820b86a832SChris Mason 	blocksize = btrfs_level_size(tree_root,
23830b86a832SChris Mason 				     btrfs_super_chunk_root_level(disk_super));
238484234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
23850b86a832SChris Mason 
23860b86a832SChris Mason 	__setup_root(nodesize, leafsize, sectorsize, stripesize,
23870b86a832SChris Mason 		     chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
23880b86a832SChris Mason 
23890b86a832SChris Mason 	chunk_root->node = read_tree_block(chunk_root,
23900b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
239184234f3aSYan Zheng 					   blocksize, generation);
239279787eaaSJeff Mahoney 	BUG_ON(!chunk_root->node); /* -ENOMEM */
239383121942SDavid Woodhouse 	if (!test_bit(EXTENT_BUFFER_UPTODATE, &chunk_root->node->bflags)) {
239483121942SDavid Woodhouse 		printk(KERN_WARNING "btrfs: failed to read chunk root on %s\n",
239583121942SDavid Woodhouse 		       sb->s_id);
2396af31f5e5SChris Mason 		goto fail_tree_roots;
239783121942SDavid Woodhouse 	}
23985d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
23995d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
24000b86a832SChris Mason 
2401e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2402e17cade2SChris Mason 	   (unsigned long)btrfs_header_chunk_tree_uuid(chunk_root->node),
2403e17cade2SChris Mason 	   BTRFS_UUID_SIZE);
2404e17cade2SChris Mason 
24050b86a832SChris Mason 	ret = btrfs_read_chunk_tree(chunk_root);
24062b82032cSYan Zheng 	if (ret) {
2407d397712bSChris Mason 		printk(KERN_WARNING "btrfs: failed to read chunk tree on %s\n",
2408d397712bSChris Mason 		       sb->s_id);
2409af31f5e5SChris Mason 		goto fail_tree_roots;
24102b82032cSYan Zheng 	}
24110b86a832SChris Mason 
2412dfe25020SChris Mason 	btrfs_close_extra_devices(fs_devices);
2413dfe25020SChris Mason 
2414a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
2415a6b0d5c8SChris Mason 		printk(KERN_CRIT "btrfs: failed to read devices on %s\n",
2416a6b0d5c8SChris Mason 		       sb->s_id);
2417a6b0d5c8SChris Mason 		goto fail_tree_roots;
2418a6b0d5c8SChris Mason 	}
2419a6b0d5c8SChris Mason 
2420af31f5e5SChris Mason retry_root_backup:
2421db94535dSChris Mason 	blocksize = btrfs_level_size(tree_root,
2422db94535dSChris Mason 				     btrfs_super_root_level(disk_super));
242384234f3aSYan Zheng 	generation = btrfs_super_generation(disk_super);
24240b86a832SChris Mason 
2425e20d96d6SChris Mason 	tree_root->node = read_tree_block(tree_root,
2426db94535dSChris Mason 					  btrfs_super_root(disk_super),
242784234f3aSYan Zheng 					  blocksize, generation);
2428af31f5e5SChris Mason 	if (!tree_root->node ||
2429af31f5e5SChris Mason 	    !test_bit(EXTENT_BUFFER_UPTODATE, &tree_root->node->bflags)) {
243083121942SDavid Woodhouse 		printk(KERN_WARNING "btrfs: failed to read tree root on %s\n",
243183121942SDavid Woodhouse 		       sb->s_id);
2432af31f5e5SChris Mason 
2433af31f5e5SChris Mason 		goto recovery_tree_root;
243483121942SDavid Woodhouse 	}
2435af31f5e5SChris Mason 
24365d4f98a2SYan Zheng 	btrfs_set_root_node(&tree_root->root_item, tree_root->node);
24375d4f98a2SYan Zheng 	tree_root->commit_root = btrfs_root_node(tree_root);
2438db94535dSChris Mason 
2439db94535dSChris Mason 	ret = find_and_setup_root(tree_root, fs_info,
2440e20d96d6SChris Mason 				  BTRFS_EXTENT_TREE_OBJECTID, extent_root);
24410b86a832SChris Mason 	if (ret)
2442af31f5e5SChris Mason 		goto recovery_tree_root;
24430b86a832SChris Mason 	extent_root->track_dirty = 1;
24440b86a832SChris Mason 
24450b86a832SChris Mason 	ret = find_and_setup_root(tree_root, fs_info,
24460b86a832SChris Mason 				  BTRFS_DEV_TREE_OBJECTID, dev_root);
24470b86a832SChris Mason 	if (ret)
2448af31f5e5SChris Mason 		goto recovery_tree_root;
24495d4f98a2SYan Zheng 	dev_root->track_dirty = 1;
24503768f368SChris Mason 
2451d20f7043SChris Mason 	ret = find_and_setup_root(tree_root, fs_info,
2452d20f7043SChris Mason 				  BTRFS_CSUM_TREE_OBJECTID, csum_root);
2453d20f7043SChris Mason 	if (ret)
2454af31f5e5SChris Mason 		goto recovery_tree_root;
2455d20f7043SChris Mason 	csum_root->track_dirty = 1;
2456d20f7043SChris Mason 
2457bcef60f2SArne Jansen 	ret = find_and_setup_root(tree_root, fs_info,
2458bcef60f2SArne Jansen 				  BTRFS_QUOTA_TREE_OBJECTID, quota_root);
2459bcef60f2SArne Jansen 	if (ret) {
2460bcef60f2SArne Jansen 		kfree(quota_root);
2461bcef60f2SArne Jansen 		quota_root = fs_info->quota_root = NULL;
2462bcef60f2SArne Jansen 	} else {
2463bcef60f2SArne Jansen 		quota_root->track_dirty = 1;
2464bcef60f2SArne Jansen 		fs_info->quota_enabled = 1;
2465bcef60f2SArne Jansen 		fs_info->pending_quota_state = 1;
2466bcef60f2SArne Jansen 	}
2467bcef60f2SArne Jansen 
24688929ecfaSYan, Zheng 	fs_info->generation = generation;
24698929ecfaSYan, Zheng 	fs_info->last_trans_committed = generation;
24708929ecfaSYan, Zheng 
247168310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
247268310a5eSIlya Dryomov 	if (ret) {
247368310a5eSIlya Dryomov 		printk(KERN_WARNING "btrfs: failed to recover balance\n");
247468310a5eSIlya Dryomov 		goto fail_block_groups;
247568310a5eSIlya Dryomov 	}
247668310a5eSIlya Dryomov 
2477733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
2478733f4fbbSStefan Behrens 	if (ret) {
2479733f4fbbSStefan Behrens 		printk(KERN_ERR "btrfs: failed to init dev_stats: %d\n",
2480733f4fbbSStefan Behrens 		       ret);
2481733f4fbbSStefan Behrens 		goto fail_block_groups;
2482733f4fbbSStefan Behrens 	}
2483733f4fbbSStefan Behrens 
2484c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
2485c59021f8Sliubo 	if (ret) {
2486c59021f8Sliubo 		printk(KERN_ERR "Failed to initial space info: %d\n", ret);
2487c59021f8Sliubo 		goto fail_block_groups;
2488c59021f8Sliubo 	}
2489c59021f8Sliubo 
24901b1d1f66SJosef Bacik 	ret = btrfs_read_block_groups(extent_root);
24911b1d1f66SJosef Bacik 	if (ret) {
24921b1d1f66SJosef Bacik 		printk(KERN_ERR "Failed to read block groups: %d\n", ret);
24931b1d1f66SJosef Bacik 		goto fail_block_groups;
24941b1d1f66SJosef Bacik 	}
24959078a3e1SChris Mason 
2496a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2497a74a4b97SChris Mason 					       "btrfs-cleaner");
249857506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
24991b1d1f66SJosef Bacik 		goto fail_block_groups;
2500a74a4b97SChris Mason 
2501a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
2502a74a4b97SChris Mason 						   tree_root,
2503a74a4b97SChris Mason 						   "btrfs-transaction");
250457506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
25053f157a2fSChris Mason 		goto fail_cleaner;
2506a74a4b97SChris Mason 
2507c289811cSChris Mason 	if (!btrfs_test_opt(tree_root, SSD) &&
2508c289811cSChris Mason 	    !btrfs_test_opt(tree_root, NOSSD) &&
2509c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
2510c289811cSChris Mason 		printk(KERN_INFO "Btrfs detected SSD devices, enabling SSD "
2511c289811cSChris Mason 		       "mode\n");
2512c289811cSChris Mason 		btrfs_set_opt(fs_info->mount_opt, SSD);
2513c289811cSChris Mason 	}
2514c289811cSChris Mason 
251521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
251621adbd5cSStefan Behrens 	if (btrfs_test_opt(tree_root, CHECK_INTEGRITY)) {
251721adbd5cSStefan Behrens 		ret = btrfsic_mount(tree_root, fs_devices,
251821adbd5cSStefan Behrens 				    btrfs_test_opt(tree_root,
251921adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
252021adbd5cSStefan Behrens 				    1 : 0,
252121adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
252221adbd5cSStefan Behrens 		if (ret)
252321adbd5cSStefan Behrens 			printk(KERN_WARNING "btrfs: failed to initialize"
252421adbd5cSStefan Behrens 			       " integrity check module %s\n", sb->s_id);
252521adbd5cSStefan Behrens 	}
252621adbd5cSStefan Behrens #endif
2527bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
2528bcef60f2SArne Jansen 	if (ret)
2529bcef60f2SArne Jansen 		goto fail_trans_kthread;
253021adbd5cSStefan Behrens 
2531acce952bSliubo 	/* do not make disk changes in broken FS */
2532acce952bSliubo 	if (btrfs_super_log_root(disk_super) != 0 &&
2533acce952bSliubo 	    !(fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)) {
2534e02119d5SChris Mason 		u64 bytenr = btrfs_super_log_root(disk_super);
2535d18a2c44SChris Mason 
25367c2ca468SChris Mason 		if (fs_devices->rw_devices == 0) {
2537d397712bSChris Mason 			printk(KERN_WARNING "Btrfs log replay required "
2538d397712bSChris Mason 			       "on RO media\n");
25397c2ca468SChris Mason 			err = -EIO;
2540bcef60f2SArne Jansen 			goto fail_qgroup;
25417c2ca468SChris Mason 		}
2542e02119d5SChris Mason 		blocksize =
2543e02119d5SChris Mason 		     btrfs_level_size(tree_root,
2544e02119d5SChris Mason 				      btrfs_super_log_root_level(disk_super));
2545e02119d5SChris Mason 
25466f07e42eSAl Viro 		log_tree_root = btrfs_alloc_root(fs_info);
2547676e4c86SDan Carpenter 		if (!log_tree_root) {
2548676e4c86SDan Carpenter 			err = -ENOMEM;
2549bcef60f2SArne Jansen 			goto fail_qgroup;
2550676e4c86SDan Carpenter 		}
2551e02119d5SChris Mason 
2552e02119d5SChris Mason 		__setup_root(nodesize, leafsize, sectorsize, stripesize,
2553e02119d5SChris Mason 			     log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2554e02119d5SChris Mason 
2555e02119d5SChris Mason 		log_tree_root->node = read_tree_block(tree_root, bytenr,
255684234f3aSYan Zheng 						      blocksize,
255784234f3aSYan Zheng 						      generation + 1);
255879787eaaSJeff Mahoney 		/* returns with log_tree_root freed on success */
2559e02119d5SChris Mason 		ret = btrfs_recover_log_trees(log_tree_root);
256079787eaaSJeff Mahoney 		if (ret) {
256179787eaaSJeff Mahoney 			btrfs_error(tree_root->fs_info, ret,
256279787eaaSJeff Mahoney 				    "Failed to recover log tree");
256379787eaaSJeff Mahoney 			free_extent_buffer(log_tree_root->node);
256479787eaaSJeff Mahoney 			kfree(log_tree_root);
256579787eaaSJeff Mahoney 			goto fail_trans_kthread;
256679787eaaSJeff Mahoney 		}
2567e556ce2cSYan Zheng 
2568e556ce2cSYan Zheng 		if (sb->s_flags & MS_RDONLY) {
2569e556ce2cSYan Zheng 			ret = btrfs_commit_super(tree_root);
257079787eaaSJeff Mahoney 			if (ret)
257179787eaaSJeff Mahoney 				goto fail_trans_kthread;
2572e556ce2cSYan Zheng 		}
2573e02119d5SChris Mason 	}
25741a40e23bSZheng Yan 
257576dda93cSYan, Zheng 	ret = btrfs_find_orphan_roots(tree_root);
257679787eaaSJeff Mahoney 	if (ret)
257779787eaaSJeff Mahoney 		goto fail_trans_kthread;
257876dda93cSYan, Zheng 
25797c2ca468SChris Mason 	if (!(sb->s_flags & MS_RDONLY)) {
2580d68fc57bSYan, Zheng 		ret = btrfs_cleanup_fs_roots(fs_info);
258179787eaaSJeff Mahoney 		if (ret) {
258279787eaaSJeff Mahoney 			}
2583d68fc57bSYan, Zheng 
25845d4f98a2SYan Zheng 		ret = btrfs_recover_relocation(tree_root);
2585d7ce5843SMiao Xie 		if (ret < 0) {
2586d7ce5843SMiao Xie 			printk(KERN_WARNING
2587d7ce5843SMiao Xie 			       "btrfs: failed to recover relocation\n");
2588d7ce5843SMiao Xie 			err = -EINVAL;
2589bcef60f2SArne Jansen 			goto fail_qgroup;
2590d7ce5843SMiao Xie 		}
25917c2ca468SChris Mason 	}
25921a40e23bSZheng Yan 
25933de4586cSChris Mason 	location.objectid = BTRFS_FS_TREE_OBJECTID;
25943de4586cSChris Mason 	location.type = BTRFS_ROOT_ITEM_KEY;
25953de4586cSChris Mason 	location.offset = (u64)-1;
25963de4586cSChris Mason 
25973de4586cSChris Mason 	fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
25983de4586cSChris Mason 	if (!fs_info->fs_root)
2599bcef60f2SArne Jansen 		goto fail_qgroup;
26003140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
26013140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
2602bcef60f2SArne Jansen 		goto fail_qgroup;
26033140c9a3SDan Carpenter 	}
2604c289811cSChris Mason 
26052b6ba629SIlya Dryomov 	if (sb->s_flags & MS_RDONLY)
26062b6ba629SIlya Dryomov 		return 0;
26072b6ba629SIlya Dryomov 
2608e3acc2a6SJosef Bacik 	down_read(&fs_info->cleanup_work_sem);
26092b6ba629SIlya Dryomov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
26102b6ba629SIlya Dryomov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
26112b6ba629SIlya Dryomov 		up_read(&fs_info->cleanup_work_sem);
26122b6ba629SIlya Dryomov 		close_ctree(tree_root);
26132b6ba629SIlya Dryomov 		return ret;
26142b6ba629SIlya Dryomov 	}
2615e3acc2a6SJosef Bacik 	up_read(&fs_info->cleanup_work_sem);
261659641015SIlya Dryomov 
26172b6ba629SIlya Dryomov 	ret = btrfs_resume_balance_async(fs_info);
26182b6ba629SIlya Dryomov 	if (ret) {
26192b6ba629SIlya Dryomov 		printk(KERN_WARNING "btrfs: failed to resume balance\n");
262066b4ffd1SJosef Bacik 		close_ctree(tree_root);
26212b6ba629SIlya Dryomov 		return ret;
2622e3acc2a6SJosef Bacik 	}
2623e3acc2a6SJosef Bacik 
2624ad2b2c80SAl Viro 	return 0;
262539279cc3SChris Mason 
2626bcef60f2SArne Jansen fail_qgroup:
2627bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
26287c2ca468SChris Mason fail_trans_kthread:
26297c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
26303f157a2fSChris Mason fail_cleaner:
2631a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
26327c2ca468SChris Mason 
26337c2ca468SChris Mason 	/*
26347c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
26357c2ca468SChris Mason 	 * kthreads
26367c2ca468SChris Mason 	 */
26377c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
26387c2ca468SChris Mason 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
26397c2ca468SChris Mason 
26401b1d1f66SJosef Bacik fail_block_groups:
26411b1d1f66SJosef Bacik 	btrfs_free_block_groups(fs_info);
2642af31f5e5SChris Mason 
2643af31f5e5SChris Mason fail_tree_roots:
2644af31f5e5SChris Mason 	free_root_pointers(fs_info, 1);
2645af31f5e5SChris Mason 
264639279cc3SChris Mason fail_sb_buffer:
264761d92c32SChris Mason 	btrfs_stop_workers(&fs_info->generic_worker);
2648306c8b68SChris Mason 	btrfs_stop_workers(&fs_info->readahead_workers);
2649247e743cSChris Mason 	btrfs_stop_workers(&fs_info->fixup_workers);
2650771ed689SChris Mason 	btrfs_stop_workers(&fs_info->delalloc_workers);
26518b712842SChris Mason 	btrfs_stop_workers(&fs_info->workers);
26528b712842SChris Mason 	btrfs_stop_workers(&fs_info->endio_workers);
2653d20f7043SChris Mason 	btrfs_stop_workers(&fs_info->endio_meta_workers);
2654cad321adSChris Mason 	btrfs_stop_workers(&fs_info->endio_meta_write_workers);
2655e6dcd2dcSChris Mason 	btrfs_stop_workers(&fs_info->endio_write_workers);
26560cb59c99SJosef Bacik 	btrfs_stop_workers(&fs_info->endio_freespace_worker);
26571cc127b5SChris Mason 	btrfs_stop_workers(&fs_info->submit_workers);
265816cdcec7SMiao Xie 	btrfs_stop_workers(&fs_info->delayed_workers);
2659bab39bf9SJosef Bacik 	btrfs_stop_workers(&fs_info->caching_workers);
266016cdcec7SMiao Xie fail_alloc:
26614543df7eSChris Mason fail_iput:
2662586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
2663586e46e2SIlya Dryomov 
26647c2ca468SChris Mason 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
26654543df7eSChris Mason 	iput(fs_info->btree_inode);
2666ad081f14SJens Axboe fail_bdi:
26677e662854SQinghuang Feng 	bdi_destroy(&fs_info->bdi);
266876dda93cSYan, Zheng fail_srcu:
266976dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
26707e662854SQinghuang Feng fail:
2671586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
2672ad2b2c80SAl Viro 	return err;
2673af31f5e5SChris Mason 
2674af31f5e5SChris Mason recovery_tree_root:
2675af31f5e5SChris Mason 	if (!btrfs_test_opt(tree_root, RECOVERY))
2676af31f5e5SChris Mason 		goto fail_tree_roots;
2677af31f5e5SChris Mason 
2678af31f5e5SChris Mason 	free_root_pointers(fs_info, 0);
2679af31f5e5SChris Mason 
2680af31f5e5SChris Mason 	/* don't use the log in recovery mode, it won't be valid */
2681af31f5e5SChris Mason 	btrfs_set_super_log_root(disk_super, 0);
2682af31f5e5SChris Mason 
2683af31f5e5SChris Mason 	/* we can't trust the free space cache either */
2684af31f5e5SChris Mason 	btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2685af31f5e5SChris Mason 
2686af31f5e5SChris Mason 	ret = next_root_backup(fs_info, fs_info->super_copy,
2687af31f5e5SChris Mason 			       &num_backups_tried, &backup_index);
2688af31f5e5SChris Mason 	if (ret == -1)
2689af31f5e5SChris Mason 		goto fail_block_groups;
2690af31f5e5SChris Mason 	goto retry_root_backup;
2691eb60ceacSChris Mason }
2692eb60ceacSChris Mason 
2693f2984462SChris Mason static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
2694f2984462SChris Mason {
2695f2984462SChris Mason 	if (uptodate) {
2696f2984462SChris Mason 		set_buffer_uptodate(bh);
2697f2984462SChris Mason 	} else {
2698442a4f63SStefan Behrens 		struct btrfs_device *device = (struct btrfs_device *)
2699442a4f63SStefan Behrens 			bh->b_private;
2700442a4f63SStefan Behrens 
2701606686eeSJosef Bacik 		printk_ratelimited_in_rcu(KERN_WARNING "lost page write due to "
2702606686eeSJosef Bacik 					  "I/O error on %s\n",
2703606686eeSJosef Bacik 					  rcu_str_deref(device->name));
27041259ab75SChris Mason 		/* note, we dont' set_buffer_write_io_error because we have
27051259ab75SChris Mason 		 * our own ways of dealing with the IO errors
27061259ab75SChris Mason 		 */
2707f2984462SChris Mason 		clear_buffer_uptodate(bh);
2708442a4f63SStefan Behrens 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
2709f2984462SChris Mason 	}
2710f2984462SChris Mason 	unlock_buffer(bh);
2711f2984462SChris Mason 	put_bh(bh);
2712f2984462SChris Mason }
2713f2984462SChris Mason 
2714a512bbf8SYan Zheng struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
2715a512bbf8SYan Zheng {
2716a512bbf8SYan Zheng 	struct buffer_head *bh;
2717a512bbf8SYan Zheng 	struct buffer_head *latest = NULL;
2718a512bbf8SYan Zheng 	struct btrfs_super_block *super;
2719a512bbf8SYan Zheng 	int i;
2720a512bbf8SYan Zheng 	u64 transid = 0;
2721a512bbf8SYan Zheng 	u64 bytenr;
2722a512bbf8SYan Zheng 
2723a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
2724a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
2725a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
2726a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
2727a512bbf8SYan Zheng 	 */
2728a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
2729a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
2730a512bbf8SYan Zheng 		if (bytenr + 4096 >= i_size_read(bdev->bd_inode))
2731a512bbf8SYan Zheng 			break;
2732a512bbf8SYan Zheng 		bh = __bread(bdev, bytenr / 4096, 4096);
2733a512bbf8SYan Zheng 		if (!bh)
2734a512bbf8SYan Zheng 			continue;
2735a512bbf8SYan Zheng 
2736a512bbf8SYan Zheng 		super = (struct btrfs_super_block *)bh->b_data;
2737a512bbf8SYan Zheng 		if (btrfs_super_bytenr(super) != bytenr ||
2738a512bbf8SYan Zheng 		    strncmp((char *)(&super->magic), BTRFS_MAGIC,
2739a512bbf8SYan Zheng 			    sizeof(super->magic))) {
2740a512bbf8SYan Zheng 			brelse(bh);
2741a512bbf8SYan Zheng 			continue;
2742a512bbf8SYan Zheng 		}
2743a512bbf8SYan Zheng 
2744a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
2745a512bbf8SYan Zheng 			brelse(latest);
2746a512bbf8SYan Zheng 			latest = bh;
2747a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
2748a512bbf8SYan Zheng 		} else {
2749a512bbf8SYan Zheng 			brelse(bh);
2750a512bbf8SYan Zheng 		}
2751a512bbf8SYan Zheng 	}
2752a512bbf8SYan Zheng 	return latest;
2753a512bbf8SYan Zheng }
2754a512bbf8SYan Zheng 
27554eedeb75SHisashi Hifumi /*
27564eedeb75SHisashi Hifumi  * this should be called twice, once with wait == 0 and
27574eedeb75SHisashi Hifumi  * once with wait == 1.  When wait == 0 is done, all the buffer heads
27584eedeb75SHisashi Hifumi  * we write are pinned.
27594eedeb75SHisashi Hifumi  *
27604eedeb75SHisashi Hifumi  * They are released when wait == 1 is done.
27614eedeb75SHisashi Hifumi  * max_mirrors must be the same for both runs, and it indicates how
27624eedeb75SHisashi Hifumi  * many supers on this one device should be written.
27634eedeb75SHisashi Hifumi  *
27644eedeb75SHisashi Hifumi  * max_mirrors == 0 means to write them all.
27654eedeb75SHisashi Hifumi  */
2766a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
2767a512bbf8SYan Zheng 			    struct btrfs_super_block *sb,
2768a512bbf8SYan Zheng 			    int do_barriers, int wait, int max_mirrors)
2769a512bbf8SYan Zheng {
2770a512bbf8SYan Zheng 	struct buffer_head *bh;
2771a512bbf8SYan Zheng 	int i;
2772a512bbf8SYan Zheng 	int ret;
2773a512bbf8SYan Zheng 	int errors = 0;
2774a512bbf8SYan Zheng 	u32 crc;
2775a512bbf8SYan Zheng 	u64 bytenr;
2776a512bbf8SYan Zheng 
2777a512bbf8SYan Zheng 	if (max_mirrors == 0)
2778a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
2779a512bbf8SYan Zheng 
2780a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
2781a512bbf8SYan Zheng 		bytenr = btrfs_sb_offset(i);
2782a512bbf8SYan Zheng 		if (bytenr + BTRFS_SUPER_INFO_SIZE >= device->total_bytes)
2783a512bbf8SYan Zheng 			break;
2784a512bbf8SYan Zheng 
2785a512bbf8SYan Zheng 		if (wait) {
2786a512bbf8SYan Zheng 			bh = __find_get_block(device->bdev, bytenr / 4096,
2787a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE);
2788a512bbf8SYan Zheng 			BUG_ON(!bh);
2789a512bbf8SYan Zheng 			wait_on_buffer(bh);
27904eedeb75SHisashi Hifumi 			if (!buffer_uptodate(bh))
27914eedeb75SHisashi Hifumi 				errors++;
27924eedeb75SHisashi Hifumi 
27934eedeb75SHisashi Hifumi 			/* drop our reference */
27944eedeb75SHisashi Hifumi 			brelse(bh);
27954eedeb75SHisashi Hifumi 
27964eedeb75SHisashi Hifumi 			/* drop the reference from the wait == 0 run */
2797a512bbf8SYan Zheng 			brelse(bh);
2798a512bbf8SYan Zheng 			continue;
2799a512bbf8SYan Zheng 		} else {
2800a512bbf8SYan Zheng 			btrfs_set_super_bytenr(sb, bytenr);
2801a512bbf8SYan Zheng 
2802a512bbf8SYan Zheng 			crc = ~(u32)0;
2803a512bbf8SYan Zheng 			crc = btrfs_csum_data(NULL, (char *)sb +
2804a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE, crc,
2805a512bbf8SYan Zheng 					      BTRFS_SUPER_INFO_SIZE -
2806a512bbf8SYan Zheng 					      BTRFS_CSUM_SIZE);
2807a512bbf8SYan Zheng 			btrfs_csum_final(crc, sb->csum);
2808a512bbf8SYan Zheng 
28094eedeb75SHisashi Hifumi 			/*
28104eedeb75SHisashi Hifumi 			 * one reference for us, and we leave it for the
28114eedeb75SHisashi Hifumi 			 * caller
28124eedeb75SHisashi Hifumi 			 */
2813a512bbf8SYan Zheng 			bh = __getblk(device->bdev, bytenr / 4096,
2814a512bbf8SYan Zheng 				      BTRFS_SUPER_INFO_SIZE);
2815a512bbf8SYan Zheng 			memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
2816a512bbf8SYan Zheng 
28174eedeb75SHisashi Hifumi 			/* one reference for submit_bh */
2818a512bbf8SYan Zheng 			get_bh(bh);
28194eedeb75SHisashi Hifumi 
28204eedeb75SHisashi Hifumi 			set_buffer_uptodate(bh);
2821a512bbf8SYan Zheng 			lock_buffer(bh);
2822a512bbf8SYan Zheng 			bh->b_end_io = btrfs_end_buffer_write_sync;
2823442a4f63SStefan Behrens 			bh->b_private = device;
2824a512bbf8SYan Zheng 		}
2825a512bbf8SYan Zheng 
2826387125fcSChris Mason 		/*
2827387125fcSChris Mason 		 * we fua the first super.  The others we allow
2828387125fcSChris Mason 		 * to go down lazy.
2829387125fcSChris Mason 		 */
283021adbd5cSStefan Behrens 		ret = btrfsic_submit_bh(WRITE_FUA, bh);
28314eedeb75SHisashi Hifumi 		if (ret)
2832a512bbf8SYan Zheng 			errors++;
2833a512bbf8SYan Zheng 	}
2834a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
2835a512bbf8SYan Zheng }
2836a512bbf8SYan Zheng 
2837387125fcSChris Mason /*
2838387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
2839387125fcSChris Mason  * for the barrier when it is done
2840387125fcSChris Mason  */
2841387125fcSChris Mason static void btrfs_end_empty_barrier(struct bio *bio, int err)
2842387125fcSChris Mason {
2843387125fcSChris Mason 	if (err) {
2844387125fcSChris Mason 		if (err == -EOPNOTSUPP)
2845387125fcSChris Mason 			set_bit(BIO_EOPNOTSUPP, &bio->bi_flags);
2846387125fcSChris Mason 		clear_bit(BIO_UPTODATE, &bio->bi_flags);
2847387125fcSChris Mason 	}
2848387125fcSChris Mason 	if (bio->bi_private)
2849387125fcSChris Mason 		complete(bio->bi_private);
2850387125fcSChris Mason 	bio_put(bio);
2851387125fcSChris Mason }
2852387125fcSChris Mason 
2853387125fcSChris Mason /*
2854387125fcSChris Mason  * trigger flushes for one the devices.  If you pass wait == 0, the flushes are
2855387125fcSChris Mason  * sent down.  With wait == 1, it waits for the previous flush.
2856387125fcSChris Mason  *
2857387125fcSChris Mason  * any device where the flush fails with eopnotsupp are flagged as not-barrier
2858387125fcSChris Mason  * capable
2859387125fcSChris Mason  */
2860387125fcSChris Mason static int write_dev_flush(struct btrfs_device *device, int wait)
2861387125fcSChris Mason {
2862387125fcSChris Mason 	struct bio *bio;
2863387125fcSChris Mason 	int ret = 0;
2864387125fcSChris Mason 
2865387125fcSChris Mason 	if (device->nobarriers)
2866387125fcSChris Mason 		return 0;
2867387125fcSChris Mason 
2868387125fcSChris Mason 	if (wait) {
2869387125fcSChris Mason 		bio = device->flush_bio;
2870387125fcSChris Mason 		if (!bio)
2871387125fcSChris Mason 			return 0;
2872387125fcSChris Mason 
2873387125fcSChris Mason 		wait_for_completion(&device->flush_wait);
2874387125fcSChris Mason 
2875387125fcSChris Mason 		if (bio_flagged(bio, BIO_EOPNOTSUPP)) {
2876606686eeSJosef Bacik 			printk_in_rcu("btrfs: disabling barriers on dev %s\n",
2877606686eeSJosef Bacik 				      rcu_str_deref(device->name));
2878387125fcSChris Mason 			device->nobarriers = 1;
2879387125fcSChris Mason 		}
2880387125fcSChris Mason 		if (!bio_flagged(bio, BIO_UPTODATE)) {
2881387125fcSChris Mason 			ret = -EIO;
2882442a4f63SStefan Behrens 			if (!bio_flagged(bio, BIO_EOPNOTSUPP))
2883442a4f63SStefan Behrens 				btrfs_dev_stat_inc_and_print(device,
2884442a4f63SStefan Behrens 					BTRFS_DEV_STAT_FLUSH_ERRS);
2885387125fcSChris Mason 		}
2886387125fcSChris Mason 
2887387125fcSChris Mason 		/* drop the reference from the wait == 0 run */
2888387125fcSChris Mason 		bio_put(bio);
2889387125fcSChris Mason 		device->flush_bio = NULL;
2890387125fcSChris Mason 
2891387125fcSChris Mason 		return ret;
2892387125fcSChris Mason 	}
2893387125fcSChris Mason 
2894387125fcSChris Mason 	/*
2895387125fcSChris Mason 	 * one reference for us, and we leave it for the
2896387125fcSChris Mason 	 * caller
2897387125fcSChris Mason 	 */
2898387125fcSChris Mason 	device->flush_bio = NULL;;
2899387125fcSChris Mason 	bio = bio_alloc(GFP_NOFS, 0);
2900387125fcSChris Mason 	if (!bio)
2901387125fcSChris Mason 		return -ENOMEM;
2902387125fcSChris Mason 
2903387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
2904387125fcSChris Mason 	bio->bi_bdev = device->bdev;
2905387125fcSChris Mason 	init_completion(&device->flush_wait);
2906387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
2907387125fcSChris Mason 	device->flush_bio = bio;
2908387125fcSChris Mason 
2909387125fcSChris Mason 	bio_get(bio);
291021adbd5cSStefan Behrens 	btrfsic_submit_bio(WRITE_FLUSH, bio);
2911387125fcSChris Mason 
2912387125fcSChris Mason 	return 0;
2913387125fcSChris Mason }
2914387125fcSChris Mason 
2915387125fcSChris Mason /*
2916387125fcSChris Mason  * send an empty flush down to each device in parallel,
2917387125fcSChris Mason  * then wait for them
2918387125fcSChris Mason  */
2919387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
2920387125fcSChris Mason {
2921387125fcSChris Mason 	struct list_head *head;
2922387125fcSChris Mason 	struct btrfs_device *dev;
2923387125fcSChris Mason 	int errors = 0;
2924387125fcSChris Mason 	int ret;
2925387125fcSChris Mason 
2926387125fcSChris Mason 	/* send down all the barriers */
2927387125fcSChris Mason 	head = &info->fs_devices->devices;
2928387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
2929387125fcSChris Mason 		if (!dev->bdev) {
2930387125fcSChris Mason 			errors++;
2931387125fcSChris Mason 			continue;
2932387125fcSChris Mason 		}
2933387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
2934387125fcSChris Mason 			continue;
2935387125fcSChris Mason 
2936387125fcSChris Mason 		ret = write_dev_flush(dev, 0);
2937387125fcSChris Mason 		if (ret)
2938387125fcSChris Mason 			errors++;
2939387125fcSChris Mason 	}
2940387125fcSChris Mason 
2941387125fcSChris Mason 	/* wait for all the barriers */
2942387125fcSChris Mason 	list_for_each_entry_rcu(dev, head, dev_list) {
2943387125fcSChris Mason 		if (!dev->bdev) {
2944387125fcSChris Mason 			errors++;
2945387125fcSChris Mason 			continue;
2946387125fcSChris Mason 		}
2947387125fcSChris Mason 		if (!dev->in_fs_metadata || !dev->writeable)
2948387125fcSChris Mason 			continue;
2949387125fcSChris Mason 
2950387125fcSChris Mason 		ret = write_dev_flush(dev, 1);
2951387125fcSChris Mason 		if (ret)
2952387125fcSChris Mason 			errors++;
2953387125fcSChris Mason 	}
2954387125fcSChris Mason 	if (errors)
2955387125fcSChris Mason 		return -EIO;
2956387125fcSChris Mason 	return 0;
2957387125fcSChris Mason }
2958387125fcSChris Mason 
2959a512bbf8SYan Zheng int write_all_supers(struct btrfs_root *root, int max_mirrors)
2960f2984462SChris Mason {
2961e5e9a520SChris Mason 	struct list_head *head;
2962f2984462SChris Mason 	struct btrfs_device *dev;
2963a061fc8dSChris Mason 	struct btrfs_super_block *sb;
2964f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
2965f2984462SChris Mason 	int ret;
2966f2984462SChris Mason 	int do_barriers;
2967a236aed1SChris Mason 	int max_errors;
2968a236aed1SChris Mason 	int total_errors = 0;
2969a061fc8dSChris Mason 	u64 flags;
2970f2984462SChris Mason 
29716c41761fSDavid Sterba 	max_errors = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
2972f2984462SChris Mason 	do_barriers = !btrfs_test_opt(root, NOBARRIER);
2973af31f5e5SChris Mason 	backup_super_roots(root->fs_info);
2974f2984462SChris Mason 
29756c41761fSDavid Sterba 	sb = root->fs_info->super_for_commit;
2976a061fc8dSChris Mason 	dev_item = &sb->dev_item;
2977e5e9a520SChris Mason 
2978174ba509SChris Mason 	mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2979e5e9a520SChris Mason 	head = &root->fs_info->fs_devices->devices;
2980387125fcSChris Mason 
2981387125fcSChris Mason 	if (do_barriers)
2982387125fcSChris Mason 		barrier_all_devices(root->fs_info);
2983387125fcSChris Mason 
29841f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
2985dfe25020SChris Mason 		if (!dev->bdev) {
2986dfe25020SChris Mason 			total_errors++;
2987dfe25020SChris Mason 			continue;
2988dfe25020SChris Mason 		}
29892b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
2990dfe25020SChris Mason 			continue;
2991dfe25020SChris Mason 
29922b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
2993a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
2994a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
2995a061fc8dSChris Mason 		btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
2996a061fc8dSChris Mason 		btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
2997a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
2998a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
2999a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3000a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
30012b82032cSYan Zheng 		memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
3002a512bbf8SYan Zheng 
3003a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3004a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3005f2984462SChris Mason 
3006a512bbf8SYan Zheng 		ret = write_dev_supers(dev, sb, do_barriers, 0, max_mirrors);
3007a236aed1SChris Mason 		if (ret)
3008a236aed1SChris Mason 			total_errors++;
3009f2984462SChris Mason 	}
3010a236aed1SChris Mason 	if (total_errors > max_errors) {
3011d397712bSChris Mason 		printk(KERN_ERR "btrfs: %d errors while writing supers\n",
3012d397712bSChris Mason 		       total_errors);
301379787eaaSJeff Mahoney 
301479787eaaSJeff Mahoney 		/* This shouldn't happen. FUA is masked off if unsupported */
3015a236aed1SChris Mason 		BUG();
3016a236aed1SChris Mason 	}
3017f2984462SChris Mason 
3018a512bbf8SYan Zheng 	total_errors = 0;
30191f78160cSXiao Guangrong 	list_for_each_entry_rcu(dev, head, dev_list) {
3020dfe25020SChris Mason 		if (!dev->bdev)
3021dfe25020SChris Mason 			continue;
30222b82032cSYan Zheng 		if (!dev->in_fs_metadata || !dev->writeable)
3023dfe25020SChris Mason 			continue;
3024dfe25020SChris Mason 
3025a512bbf8SYan Zheng 		ret = write_dev_supers(dev, sb, do_barriers, 1, max_mirrors);
3026a512bbf8SYan Zheng 		if (ret)
30271259ab75SChris Mason 			total_errors++;
3028f2984462SChris Mason 	}
3029174ba509SChris Mason 	mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
3030a236aed1SChris Mason 	if (total_errors > max_errors) {
303179787eaaSJeff Mahoney 		btrfs_error(root->fs_info, -EIO,
303279787eaaSJeff Mahoney 			    "%d errors while writing supers", total_errors);
303379787eaaSJeff Mahoney 		return -EIO;
3034a236aed1SChris Mason 	}
3035f2984462SChris Mason 	return 0;
3036f2984462SChris Mason }
3037f2984462SChris Mason 
3038a512bbf8SYan Zheng int write_ctree_super(struct btrfs_trans_handle *trans,
3039a512bbf8SYan Zheng 		      struct btrfs_root *root, int max_mirrors)
3040cfaa7295SChris Mason {
3041e66f709bSChris Mason 	int ret;
30422c90e5d6SChris Mason 
3043a512bbf8SYan Zheng 	ret = write_all_supers(root, max_mirrors);
30445f39d397SChris Mason 	return ret;
3045cfaa7295SChris Mason }
3046cfaa7295SChris Mason 
3047143bede5SJeff Mahoney void btrfs_free_fs_root(struct btrfs_fs_info *fs_info, struct btrfs_root *root)
30482619ba1fSChris Mason {
30494df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
30502619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
30512619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
30524df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
305376dda93cSYan, Zheng 
305476dda93cSYan, Zheng 	if (btrfs_root_refs(&root->root_item) == 0)
305576dda93cSYan, Zheng 		synchronize_srcu(&fs_info->subvol_srcu);
305676dda93cSYan, Zheng 
3057581bb050SLi Zefan 	__btrfs_remove_free_space_cache(root->free_ino_pinned);
3058581bb050SLi Zefan 	__btrfs_remove_free_space_cache(root->free_ino_ctl);
30594df27c4dSYan, Zheng 	free_fs_root(root);
30604df27c4dSYan, Zheng }
30614df27c4dSYan, Zheng 
30624df27c4dSYan, Zheng static void free_fs_root(struct btrfs_root *root)
30634df27c4dSYan, Zheng {
306482d5902dSLi Zefan 	iput(root->cache_inode);
30654df27c4dSYan, Zheng 	WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
30660ee5dc67SAl Viro 	if (root->anon_dev)
30670ee5dc67SAl Viro 		free_anon_bdev(root->anon_dev);
30685f39d397SChris Mason 	free_extent_buffer(root->node);
30695f39d397SChris Mason 	free_extent_buffer(root->commit_root);
3070581bb050SLi Zefan 	kfree(root->free_ino_ctl);
3071581bb050SLi Zefan 	kfree(root->free_ino_pinned);
307258176a96SJosef Bacik 	kfree(root->name);
30732619ba1fSChris Mason 	kfree(root);
30742619ba1fSChris Mason }
30752619ba1fSChris Mason 
3076143bede5SJeff Mahoney static void del_fs_roots(struct btrfs_fs_info *fs_info)
30770f7d52f4SChris Mason {
30780f7d52f4SChris Mason 	int ret;
30790f7d52f4SChris Mason 	struct btrfs_root *gang[8];
30800f7d52f4SChris Mason 	int i;
30810f7d52f4SChris Mason 
308276dda93cSYan, Zheng 	while (!list_empty(&fs_info->dead_roots)) {
308376dda93cSYan, Zheng 		gang[0] = list_entry(fs_info->dead_roots.next,
308476dda93cSYan, Zheng 				     struct btrfs_root, root_list);
308576dda93cSYan, Zheng 		list_del(&gang[0]->root_list);
308676dda93cSYan, Zheng 
308776dda93cSYan, Zheng 		if (gang[0]->in_radix) {
308876dda93cSYan, Zheng 			btrfs_free_fs_root(fs_info, gang[0]);
308976dda93cSYan, Zheng 		} else {
309076dda93cSYan, Zheng 			free_extent_buffer(gang[0]->node);
309176dda93cSYan, Zheng 			free_extent_buffer(gang[0]->commit_root);
309276dda93cSYan, Zheng 			kfree(gang[0]);
309376dda93cSYan, Zheng 		}
309476dda93cSYan, Zheng 	}
309576dda93cSYan, Zheng 
30960f7d52f4SChris Mason 	while (1) {
30970f7d52f4SChris Mason 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
30980f7d52f4SChris Mason 					     (void **)gang, 0,
30990f7d52f4SChris Mason 					     ARRAY_SIZE(gang));
31000f7d52f4SChris Mason 		if (!ret)
31010f7d52f4SChris Mason 			break;
31022619ba1fSChris Mason 		for (i = 0; i < ret; i++)
31035eda7b5eSChris Mason 			btrfs_free_fs_root(fs_info, gang[i]);
31040f7d52f4SChris Mason 	}
31050f7d52f4SChris Mason }
3106b4100d64SChris Mason 
3107c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3108c146afadSYan Zheng {
3109c146afadSYan Zheng 	u64 root_objectid = 0;
3110c146afadSYan Zheng 	struct btrfs_root *gang[8];
3111c146afadSYan Zheng 	int i;
3112c146afadSYan Zheng 	int ret;
3113c146afadSYan Zheng 
3114c146afadSYan Zheng 	while (1) {
3115c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3116c146afadSYan Zheng 					     (void **)gang, root_objectid,
3117c146afadSYan Zheng 					     ARRAY_SIZE(gang));
3118c146afadSYan Zheng 		if (!ret)
3119c146afadSYan Zheng 			break;
31205d4f98a2SYan Zheng 
31215d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
3122c146afadSYan Zheng 		for (i = 0; i < ret; i++) {
312366b4ffd1SJosef Bacik 			int err;
312466b4ffd1SJosef Bacik 
3125c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
312666b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
312766b4ffd1SJosef Bacik 			if (err)
312866b4ffd1SJosef Bacik 				return err;
3129c146afadSYan Zheng 		}
3130c146afadSYan Zheng 		root_objectid++;
3131c146afadSYan Zheng 	}
3132c146afadSYan Zheng 	return 0;
3133c146afadSYan Zheng }
3134c146afadSYan Zheng 
3135c146afadSYan Zheng int btrfs_commit_super(struct btrfs_root *root)
3136c146afadSYan Zheng {
3137c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
3138c146afadSYan Zheng 	int ret;
3139c146afadSYan Zheng 
3140c146afadSYan Zheng 	mutex_lock(&root->fs_info->cleaner_mutex);
314124bbcf04SYan, Zheng 	btrfs_run_delayed_iputs(root);
3142c146afadSYan Zheng 	btrfs_clean_old_snapshots(root);
3143c146afadSYan Zheng 	mutex_unlock(&root->fs_info->cleaner_mutex);
3144c71bf099SYan, Zheng 
3145c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
3146c71bf099SYan, Zheng 	down_write(&root->fs_info->cleanup_work_sem);
3147c71bf099SYan, Zheng 	up_write(&root->fs_info->cleanup_work_sem);
3148c71bf099SYan, Zheng 
31497a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
31503612b495STsutomu Itoh 	if (IS_ERR(trans))
31513612b495STsutomu Itoh 		return PTR_ERR(trans);
3152c146afadSYan Zheng 	ret = btrfs_commit_transaction(trans, root);
315379787eaaSJeff Mahoney 	if (ret)
315479787eaaSJeff Mahoney 		return ret;
3155c146afadSYan Zheng 	/* run commit again to drop the original snapshot */
31567a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
31573612b495STsutomu Itoh 	if (IS_ERR(trans))
31583612b495STsutomu Itoh 		return PTR_ERR(trans);
315979787eaaSJeff Mahoney 	ret = btrfs_commit_transaction(trans, root);
316079787eaaSJeff Mahoney 	if (ret)
316179787eaaSJeff Mahoney 		return ret;
3162c146afadSYan Zheng 	ret = btrfs_write_and_wait_transaction(NULL, root);
316379787eaaSJeff Mahoney 	if (ret) {
316479787eaaSJeff Mahoney 		btrfs_error(root->fs_info, ret,
316579787eaaSJeff Mahoney 			    "Failed to sync btree inode to disk.");
316679787eaaSJeff Mahoney 		return ret;
316779787eaaSJeff Mahoney 	}
3168c146afadSYan Zheng 
3169a512bbf8SYan Zheng 	ret = write_ctree_super(NULL, root, 0);
3170c146afadSYan Zheng 	return ret;
3171c146afadSYan Zheng }
3172c146afadSYan Zheng 
3173e20d96d6SChris Mason int close_ctree(struct btrfs_root *root)
3174eb60ceacSChris Mason {
31750f7d52f4SChris Mason 	struct btrfs_fs_info *fs_info = root->fs_info;
3176c146afadSYan Zheng 	int ret;
3177e089f05cSChris Mason 
3178facda1e7SChris Mason 	fs_info->closing = 1;
3179a2135011SChris Mason 	smp_mb();
3180a2135011SChris Mason 
3181837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
3182837d5b6eSIlya Dryomov 	btrfs_pause_balance(root->fs_info);
3183837d5b6eSIlya Dryomov 
3184a2de733cSArne Jansen 	btrfs_scrub_cancel(root);
31854cb5300bSChris Mason 
31864cb5300bSChris Mason 	/* wait for any defraggers to finish */
31874cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
31884cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
31894cb5300bSChris Mason 
31904cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
3191e3029d9fSAl Viro 	btrfs_run_defrag_inodes(fs_info);
31924cb5300bSChris Mason 
3193acce952bSliubo 	/*
3194acce952bSliubo 	 * Here come 2 situations when btrfs is broken to flip readonly:
3195acce952bSliubo 	 *
3196acce952bSliubo 	 * 1. when btrfs flips readonly somewhere else before
3197acce952bSliubo 	 * btrfs_commit_super, sb->s_flags has MS_RDONLY flag,
3198acce952bSliubo 	 * and btrfs will skip to write sb directly to keep
3199acce952bSliubo 	 * ERROR state on disk.
3200acce952bSliubo 	 *
3201acce952bSliubo 	 * 2. when btrfs flips readonly just in btrfs_commit_super,
3202ae0e47f0SJustin P. Mattock 	 * and in such case, btrfs cannot write sb via btrfs_commit_super,
3203acce952bSliubo 	 * and since fs_state has been set BTRFS_SUPER_FLAG_ERROR flag,
3204acce952bSliubo 	 * btrfs will cleanup all FS resources first and write sb then.
3205acce952bSliubo 	 */
3206c146afadSYan Zheng 	if (!(fs_info->sb->s_flags & MS_RDONLY)) {
3207c146afadSYan Zheng 		ret = btrfs_commit_super(root);
3208d397712bSChris Mason 		if (ret)
3209d397712bSChris Mason 			printk(KERN_ERR "btrfs: commit super ret %d\n", ret);
3210c146afadSYan Zheng 	}
3211ed2ff2cbSChris Mason 
3212acce952bSliubo 	if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) {
3213acce952bSliubo 		ret = btrfs_error_commit_super(root);
3214acce952bSliubo 		if (ret)
3215acce952bSliubo 			printk(KERN_ERR "btrfs: commit super ret %d\n", ret);
3216acce952bSliubo 	}
3217acce952bSliubo 
3218300e4f8aSJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3219300e4f8aSJosef Bacik 
3220e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
3221e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
32228929ecfaSYan, Zheng 
3223f25784b3SYan Zheng 	fs_info->closing = 2;
3224f25784b3SYan Zheng 	smp_mb();
3225f25784b3SYan Zheng 
3226bcef60f2SArne Jansen 	btrfs_free_qgroup_config(root->fs_info);
3227bcef60f2SArne Jansen 
3228b0c68f8bSChris Mason 	if (fs_info->delalloc_bytes) {
3229d397712bSChris Mason 		printk(KERN_INFO "btrfs: at unmount delalloc count %llu\n",
323021380931SJoel Becker 		       (unsigned long long)fs_info->delalloc_bytes);
3231b0c68f8bSChris Mason 	}
323231153d81SYan Zheng 	if (fs_info->total_ref_cache_size) {
3233d397712bSChris Mason 		printk(KERN_INFO "btrfs: at umount reference cache size %llu\n",
3234d397712bSChris Mason 		       (unsigned long long)fs_info->total_ref_cache_size);
323531153d81SYan Zheng 	}
323631153d81SYan Zheng 
32375f39d397SChris Mason 	free_extent_buffer(fs_info->extent_root->node);
32385d4f98a2SYan Zheng 	free_extent_buffer(fs_info->extent_root->commit_root);
32395f39d397SChris Mason 	free_extent_buffer(fs_info->tree_root->node);
32405d4f98a2SYan Zheng 	free_extent_buffer(fs_info->tree_root->commit_root);
3241e3029d9fSAl Viro 	free_extent_buffer(fs_info->chunk_root->node);
3242e3029d9fSAl Viro 	free_extent_buffer(fs_info->chunk_root->commit_root);
3243e3029d9fSAl Viro 	free_extent_buffer(fs_info->dev_root->node);
3244e3029d9fSAl Viro 	free_extent_buffer(fs_info->dev_root->commit_root);
3245e3029d9fSAl Viro 	free_extent_buffer(fs_info->csum_root->node);
3246e3029d9fSAl Viro 	free_extent_buffer(fs_info->csum_root->commit_root);
3247bcef60f2SArne Jansen 	if (fs_info->quota_root) {
3248bcef60f2SArne Jansen 		free_extent_buffer(fs_info->quota_root->node);
3249bcef60f2SArne Jansen 		free_extent_buffer(fs_info->quota_root->commit_root);
3250bcef60f2SArne Jansen 	}
3251d20f7043SChris Mason 
3252e3029d9fSAl Viro 	btrfs_free_block_groups(fs_info);
3253c146afadSYan Zheng 
32540f7d52f4SChris Mason 	del_fs_roots(fs_info);
3255d10c5f31SChris Mason 
3256c146afadSYan Zheng 	iput(fs_info->btree_inode);
32579ad6b7bcSChris Mason 
325861d92c32SChris Mason 	btrfs_stop_workers(&fs_info->generic_worker);
3259247e743cSChris Mason 	btrfs_stop_workers(&fs_info->fixup_workers);
3260771ed689SChris Mason 	btrfs_stop_workers(&fs_info->delalloc_workers);
32618b712842SChris Mason 	btrfs_stop_workers(&fs_info->workers);
32628b712842SChris Mason 	btrfs_stop_workers(&fs_info->endio_workers);
3263d20f7043SChris Mason 	btrfs_stop_workers(&fs_info->endio_meta_workers);
3264cad321adSChris Mason 	btrfs_stop_workers(&fs_info->endio_meta_write_workers);
3265e6dcd2dcSChris Mason 	btrfs_stop_workers(&fs_info->endio_write_workers);
32660cb59c99SJosef Bacik 	btrfs_stop_workers(&fs_info->endio_freespace_worker);
32671cc127b5SChris Mason 	btrfs_stop_workers(&fs_info->submit_workers);
326816cdcec7SMiao Xie 	btrfs_stop_workers(&fs_info->delayed_workers);
3269bab39bf9SJosef Bacik 	btrfs_stop_workers(&fs_info->caching_workers);
327090519d66SArne Jansen 	btrfs_stop_workers(&fs_info->readahead_workers);
3271d6bfde87SChris Mason 
327221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
327321adbd5cSStefan Behrens 	if (btrfs_test_opt(root, CHECK_INTEGRITY))
327421adbd5cSStefan Behrens 		btrfsic_unmount(root, fs_info->fs_devices);
327521adbd5cSStefan Behrens #endif
327621adbd5cSStefan Behrens 
3277dfe25020SChris Mason 	btrfs_close_devices(fs_info->fs_devices);
32780b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3279b248a415SChris Mason 
328004160088SChris Mason 	bdi_destroy(&fs_info->bdi);
328176dda93cSYan, Zheng 	cleanup_srcu_struct(&fs_info->subvol_srcu);
32820b86a832SChris Mason 
3283eb60ceacSChris Mason 	return 0;
3284eb60ceacSChris Mason }
3285eb60ceacSChris Mason 
3286b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
3287b9fab919SChris Mason 			  int atomic)
3288ccd467d6SChris Mason {
32891259ab75SChris Mason 	int ret;
3290727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
32911259ab75SChris Mason 
32920b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
32931259ab75SChris Mason 	if (!ret)
32941259ab75SChris Mason 		return ret;
32951259ab75SChris Mason 
32961259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
3297b9fab919SChris Mason 				    parent_transid, atomic);
3298b9fab919SChris Mason 	if (ret == -EAGAIN)
3299b9fab919SChris Mason 		return ret;
33001259ab75SChris Mason 	return !ret;
33015f39d397SChris Mason }
33026702ed49SChris Mason 
33035f39d397SChris Mason int btrfs_set_buffer_uptodate(struct extent_buffer *buf)
33045f39d397SChris Mason {
33050b32f4bbSJosef Bacik 	return set_extent_buffer_uptodate(buf);
33065f39d397SChris Mason }
33075f39d397SChris Mason 
33085f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
33095f39d397SChris Mason {
3310727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
33115f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
3312b9473439SChris Mason 	int was_dirty;
3313b4ce94deSChris Mason 
3314b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
3315ccd467d6SChris Mason 	if (transid != root->fs_info->generation) {
3316d397712bSChris Mason 		printk(KERN_CRIT "btrfs transid mismatch buffer %llu, "
3317d397712bSChris Mason 		       "found %llu running %llu\n",
3318db94535dSChris Mason 			(unsigned long long)buf->start,
3319d397712bSChris Mason 			(unsigned long long)transid,
3320d397712bSChris Mason 			(unsigned long long)root->fs_info->generation);
3321ccd467d6SChris Mason 		WARN_ON(1);
3322ccd467d6SChris Mason 	}
33230b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
3324b9473439SChris Mason 	if (!was_dirty) {
3325b9473439SChris Mason 		spin_lock(&root->fs_info->delalloc_lock);
3326b9473439SChris Mason 		root->fs_info->dirty_metadata_bytes += buf->len;
3327b9473439SChris Mason 		spin_unlock(&root->fs_info->delalloc_lock);
3328b9473439SChris Mason 	}
3329eb60ceacSChris Mason }
3330eb60ceacSChris Mason 
3331d3c2fdcfSChris Mason void btrfs_btree_balance_dirty(struct btrfs_root *root, unsigned long nr)
333235b7e476SChris Mason {
3333188de649SChris Mason 	/*
3334188de649SChris Mason 	 * looks as though older kernels can get into trouble with
3335188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
3336188de649SChris Mason 	 */
3337d6bfde87SChris Mason 	u64 num_dirty;
3338771ed689SChris Mason 	unsigned long thresh = 32 * 1024 * 1024;
3339d6bfde87SChris Mason 
33406933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
3341d6bfde87SChris Mason 		return;
3342d6bfde87SChris Mason 
334316cdcec7SMiao Xie 	btrfs_balance_delayed_items(root);
334416cdcec7SMiao Xie 
334516cdcec7SMiao Xie 	num_dirty = root->fs_info->dirty_metadata_bytes;
334616cdcec7SMiao Xie 
334716cdcec7SMiao Xie 	if (num_dirty > thresh) {
334816cdcec7SMiao Xie 		balance_dirty_pages_ratelimited_nr(
334916cdcec7SMiao Xie 				   root->fs_info->btree_inode->i_mapping, 1);
335016cdcec7SMiao Xie 	}
335116cdcec7SMiao Xie 	return;
335216cdcec7SMiao Xie }
335316cdcec7SMiao Xie 
335416cdcec7SMiao Xie void __btrfs_btree_balance_dirty(struct btrfs_root *root, unsigned long nr)
335516cdcec7SMiao Xie {
335616cdcec7SMiao Xie 	/*
335716cdcec7SMiao Xie 	 * looks as though older kernels can get into trouble with
335816cdcec7SMiao Xie 	 * this code, they end up stuck in balance_dirty_pages forever
335916cdcec7SMiao Xie 	 */
336016cdcec7SMiao Xie 	u64 num_dirty;
336116cdcec7SMiao Xie 	unsigned long thresh = 32 * 1024 * 1024;
336216cdcec7SMiao Xie 
336316cdcec7SMiao Xie 	if (current->flags & PF_MEMALLOC)
336416cdcec7SMiao Xie 		return;
336516cdcec7SMiao Xie 
3366585ad2c3SChris Mason 	num_dirty = root->fs_info->dirty_metadata_bytes;
3367585ad2c3SChris Mason 
3368d6bfde87SChris Mason 	if (num_dirty > thresh) {
3369d3c2fdcfSChris Mason 		balance_dirty_pages_ratelimited_nr(
3370304fced6SChris Mason 				   root->fs_info->btree_inode->i_mapping, 1);
337135b7e476SChris Mason 	}
3372188de649SChris Mason 	return;
3373d6bfde87SChris Mason }
33746b80053dSChris Mason 
3375ca7a79adSChris Mason int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
33766b80053dSChris Mason {
3377727011e0SChris Mason 	struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
33780b32f4bbSJosef Bacik 	return btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
33796b80053dSChris Mason }
33800da5468fSChris Mason 
338120897f5cSArne Jansen int btree_lock_page_hook(struct page *page, void *data,
338201d658f2SChris Mason 				void (*flush_fn)(void *))
33834bef0848SChris Mason {
33844bef0848SChris Mason 	struct inode *inode = page->mapping->host;
3385b9473439SChris Mason 	struct btrfs_root *root = BTRFS_I(inode)->root;
33864bef0848SChris Mason 	struct extent_buffer *eb;
33874bef0848SChris Mason 
33884f2de97aSJosef Bacik 	/*
33894f2de97aSJosef Bacik 	 * We culled this eb but the page is still hanging out on the mapping,
33904f2de97aSJosef Bacik 	 * carry on.
33914f2de97aSJosef Bacik 	 */
33924f2de97aSJosef Bacik 	if (!PagePrivate(page))
33934bef0848SChris Mason 		goto out;
33944bef0848SChris Mason 
33954f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
33964f2de97aSJosef Bacik 	if (!eb) {
33974f2de97aSJosef Bacik 		WARN_ON(1);
33984f2de97aSJosef Bacik 		goto out;
33994f2de97aSJosef Bacik 	}
34004f2de97aSJosef Bacik 	if (page != eb->pages[0])
34014bef0848SChris Mason 		goto out;
34024bef0848SChris Mason 
340301d658f2SChris Mason 	if (!btrfs_try_tree_write_lock(eb)) {
340401d658f2SChris Mason 		flush_fn(data);
34054bef0848SChris Mason 		btrfs_tree_lock(eb);
340601d658f2SChris Mason 	}
34074bef0848SChris Mason 	btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
3408b9473439SChris Mason 
3409b9473439SChris Mason 	if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
3410b9473439SChris Mason 		spin_lock(&root->fs_info->delalloc_lock);
3411b9473439SChris Mason 		if (root->fs_info->dirty_metadata_bytes >= eb->len)
3412b9473439SChris Mason 			root->fs_info->dirty_metadata_bytes -= eb->len;
3413b9473439SChris Mason 		else
3414b9473439SChris Mason 			WARN_ON(1);
3415b9473439SChris Mason 		spin_unlock(&root->fs_info->delalloc_lock);
3416b9473439SChris Mason 	}
3417b9473439SChris Mason 
34184bef0848SChris Mason 	btrfs_tree_unlock(eb);
34194bef0848SChris Mason out:
342001d658f2SChris Mason 	if (!trylock_page(page)) {
342101d658f2SChris Mason 		flush_fn(data);
34224bef0848SChris Mason 		lock_page(page);
342301d658f2SChris Mason 	}
34244bef0848SChris Mason 	return 0;
34254bef0848SChris Mason }
34264bef0848SChris Mason 
3427fcd1f065SDavid Sterba static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
3428acce952bSliubo 			      int read_only)
3429acce952bSliubo {
3430fcd1f065SDavid Sterba 	if (btrfs_super_csum_type(fs_info->super_copy) >= ARRAY_SIZE(btrfs_csum_sizes)) {
3431fcd1f065SDavid Sterba 		printk(KERN_ERR "btrfs: unsupported checksum algorithm\n");
3432fcd1f065SDavid Sterba 		return -EINVAL;
3433fcd1f065SDavid Sterba 	}
3434acce952bSliubo 
3435fcd1f065SDavid Sterba 	if (read_only)
3436fcd1f065SDavid Sterba 		return 0;
3437fcd1f065SDavid Sterba 
3438fcd1f065SDavid Sterba 	if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) {
3439acce952bSliubo 		printk(KERN_WARNING "warning: mount fs with errors, "
3440acce952bSliubo 		       "running btrfsck is recommended\n");
3441acce952bSliubo 	}
3442acce952bSliubo 
3443fcd1f065SDavid Sterba 	return 0;
3444fcd1f065SDavid Sterba }
3445fcd1f065SDavid Sterba 
3446acce952bSliubo int btrfs_error_commit_super(struct btrfs_root *root)
3447acce952bSliubo {
3448acce952bSliubo 	int ret;
3449acce952bSliubo 
3450acce952bSliubo 	mutex_lock(&root->fs_info->cleaner_mutex);
3451acce952bSliubo 	btrfs_run_delayed_iputs(root);
3452acce952bSliubo 	mutex_unlock(&root->fs_info->cleaner_mutex);
3453acce952bSliubo 
3454acce952bSliubo 	down_write(&root->fs_info->cleanup_work_sem);
3455acce952bSliubo 	up_write(&root->fs_info->cleanup_work_sem);
3456acce952bSliubo 
3457acce952bSliubo 	/* cleanup FS via transaction */
3458acce952bSliubo 	btrfs_cleanup_transaction(root);
3459acce952bSliubo 
3460acce952bSliubo 	ret = write_ctree_super(NULL, root, 0);
3461acce952bSliubo 
3462acce952bSliubo 	return ret;
3463acce952bSliubo }
3464acce952bSliubo 
3465143bede5SJeff Mahoney static void btrfs_destroy_ordered_operations(struct btrfs_root *root)
3466acce952bSliubo {
3467acce952bSliubo 	struct btrfs_inode *btrfs_inode;
3468acce952bSliubo 	struct list_head splice;
3469acce952bSliubo 
3470acce952bSliubo 	INIT_LIST_HEAD(&splice);
3471acce952bSliubo 
3472acce952bSliubo 	mutex_lock(&root->fs_info->ordered_operations_mutex);
3473acce952bSliubo 	spin_lock(&root->fs_info->ordered_extent_lock);
3474acce952bSliubo 
3475acce952bSliubo 	list_splice_init(&root->fs_info->ordered_operations, &splice);
3476acce952bSliubo 	while (!list_empty(&splice)) {
3477acce952bSliubo 		btrfs_inode = list_entry(splice.next, struct btrfs_inode,
3478acce952bSliubo 					 ordered_operations);
3479acce952bSliubo 
3480acce952bSliubo 		list_del_init(&btrfs_inode->ordered_operations);
3481acce952bSliubo 
3482acce952bSliubo 		btrfs_invalidate_inodes(btrfs_inode->root);
3483acce952bSliubo 	}
3484acce952bSliubo 
3485acce952bSliubo 	spin_unlock(&root->fs_info->ordered_extent_lock);
3486acce952bSliubo 	mutex_unlock(&root->fs_info->ordered_operations_mutex);
3487acce952bSliubo }
3488acce952bSliubo 
3489143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
3490acce952bSliubo {
3491acce952bSliubo 	struct list_head splice;
3492acce952bSliubo 	struct btrfs_ordered_extent *ordered;
3493acce952bSliubo 	struct inode *inode;
3494acce952bSliubo 
3495acce952bSliubo 	INIT_LIST_HEAD(&splice);
3496acce952bSliubo 
3497acce952bSliubo 	spin_lock(&root->fs_info->ordered_extent_lock);
3498acce952bSliubo 
3499acce952bSliubo 	list_splice_init(&root->fs_info->ordered_extents, &splice);
3500acce952bSliubo 	while (!list_empty(&splice)) {
3501acce952bSliubo 		ordered = list_entry(splice.next, struct btrfs_ordered_extent,
3502acce952bSliubo 				     root_extent_list);
3503acce952bSliubo 
3504acce952bSliubo 		list_del_init(&ordered->root_extent_list);
3505acce952bSliubo 		atomic_inc(&ordered->refs);
3506acce952bSliubo 
3507acce952bSliubo 		/* the inode may be getting freed (in sys_unlink path). */
3508acce952bSliubo 		inode = igrab(ordered->inode);
3509acce952bSliubo 
3510acce952bSliubo 		spin_unlock(&root->fs_info->ordered_extent_lock);
3511acce952bSliubo 		if (inode)
3512acce952bSliubo 			iput(inode);
3513acce952bSliubo 
3514acce952bSliubo 		atomic_set(&ordered->refs, 1);
3515acce952bSliubo 		btrfs_put_ordered_extent(ordered);
3516acce952bSliubo 
3517acce952bSliubo 		spin_lock(&root->fs_info->ordered_extent_lock);
3518acce952bSliubo 	}
3519acce952bSliubo 
3520acce952bSliubo 	spin_unlock(&root->fs_info->ordered_extent_lock);
3521acce952bSliubo }
3522acce952bSliubo 
352379787eaaSJeff Mahoney int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
3524acce952bSliubo 			       struct btrfs_root *root)
3525acce952bSliubo {
3526acce952bSliubo 	struct rb_node *node;
3527acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
3528acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
3529acce952bSliubo 	int ret = 0;
3530acce952bSliubo 
3531acce952bSliubo 	delayed_refs = &trans->delayed_refs;
3532acce952bSliubo 
3533acce952bSliubo 	spin_lock(&delayed_refs->lock);
3534acce952bSliubo 	if (delayed_refs->num_entries == 0) {
3535cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
3536acce952bSliubo 		printk(KERN_INFO "delayed_refs has NO entry\n");
3537acce952bSliubo 		return ret;
3538acce952bSliubo 	}
3539acce952bSliubo 
3540b939d1abSJosef Bacik 	while ((node = rb_first(&delayed_refs->root)) != NULL) {
3541acce952bSliubo 		ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
3542acce952bSliubo 
3543acce952bSliubo 		atomic_set(&ref->refs, 1);
3544acce952bSliubo 		if (btrfs_delayed_ref_is_head(ref)) {
3545acce952bSliubo 			struct btrfs_delayed_ref_head *head;
3546acce952bSliubo 
3547acce952bSliubo 			head = btrfs_delayed_node_to_head(ref);
3548b939d1abSJosef Bacik 			if (!mutex_trylock(&head->mutex)) {
3549b939d1abSJosef Bacik 				atomic_inc(&ref->refs);
355079787eaaSJeff Mahoney 				spin_unlock(&delayed_refs->lock);
3551b939d1abSJosef Bacik 
3552b939d1abSJosef Bacik 				/* Need to wait for the delayed ref to run */
3553acce952bSliubo 				mutex_lock(&head->mutex);
3554b939d1abSJosef Bacik 				mutex_unlock(&head->mutex);
3555b939d1abSJosef Bacik 				btrfs_put_delayed_ref(ref);
3556b939d1abSJosef Bacik 
3557e18fca73SJosef Bacik 				spin_lock(&delayed_refs->lock);
3558b939d1abSJosef Bacik 				continue;
3559b939d1abSJosef Bacik 			}
3560b939d1abSJosef Bacik 
3561acce952bSliubo 			kfree(head->extent_op);
3562acce952bSliubo 			delayed_refs->num_heads--;
3563acce952bSliubo 			if (list_empty(&head->cluster))
3564acce952bSliubo 				delayed_refs->num_heads_ready--;
3565acce952bSliubo 			list_del_init(&head->cluster);
3566acce952bSliubo 		}
3567b939d1abSJosef Bacik 		ref->in_tree = 0;
3568b939d1abSJosef Bacik 		rb_erase(&ref->rb_node, &delayed_refs->root);
3569b939d1abSJosef Bacik 		delayed_refs->num_entries--;
3570b939d1abSJosef Bacik 
3571acce952bSliubo 		spin_unlock(&delayed_refs->lock);
3572acce952bSliubo 		btrfs_put_delayed_ref(ref);
3573acce952bSliubo 
3574acce952bSliubo 		cond_resched();
3575acce952bSliubo 		spin_lock(&delayed_refs->lock);
3576acce952bSliubo 	}
3577acce952bSliubo 
3578acce952bSliubo 	spin_unlock(&delayed_refs->lock);
3579acce952bSliubo 
3580acce952bSliubo 	return ret;
3581acce952bSliubo }
3582acce952bSliubo 
3583143bede5SJeff Mahoney static void btrfs_destroy_pending_snapshots(struct btrfs_transaction *t)
3584acce952bSliubo {
3585acce952bSliubo 	struct btrfs_pending_snapshot *snapshot;
3586acce952bSliubo 	struct list_head splice;
3587acce952bSliubo 
3588acce952bSliubo 	INIT_LIST_HEAD(&splice);
3589acce952bSliubo 
3590acce952bSliubo 	list_splice_init(&t->pending_snapshots, &splice);
3591acce952bSliubo 
3592acce952bSliubo 	while (!list_empty(&splice)) {
3593acce952bSliubo 		snapshot = list_entry(splice.next,
3594acce952bSliubo 				      struct btrfs_pending_snapshot,
3595acce952bSliubo 				      list);
3596acce952bSliubo 
3597acce952bSliubo 		list_del_init(&snapshot->list);
3598acce952bSliubo 
3599acce952bSliubo 		kfree(snapshot);
3600acce952bSliubo 	}
3601acce952bSliubo }
3602acce952bSliubo 
3603143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
3604acce952bSliubo {
3605acce952bSliubo 	struct btrfs_inode *btrfs_inode;
3606acce952bSliubo 	struct list_head splice;
3607acce952bSliubo 
3608acce952bSliubo 	INIT_LIST_HEAD(&splice);
3609acce952bSliubo 
3610acce952bSliubo 	spin_lock(&root->fs_info->delalloc_lock);
36115be76758SDavid Sterba 	list_splice_init(&root->fs_info->delalloc_inodes, &splice);
3612acce952bSliubo 
3613acce952bSliubo 	while (!list_empty(&splice)) {
3614acce952bSliubo 		btrfs_inode = list_entry(splice.next, struct btrfs_inode,
3615acce952bSliubo 				    delalloc_inodes);
3616acce952bSliubo 
3617acce952bSliubo 		list_del_init(&btrfs_inode->delalloc_inodes);
3618acce952bSliubo 
3619acce952bSliubo 		btrfs_invalidate_inodes(btrfs_inode->root);
3620acce952bSliubo 	}
3621acce952bSliubo 
3622acce952bSliubo 	spin_unlock(&root->fs_info->delalloc_lock);
3623acce952bSliubo }
3624acce952bSliubo 
3625acce952bSliubo static int btrfs_destroy_marked_extents(struct btrfs_root *root,
3626acce952bSliubo 					struct extent_io_tree *dirty_pages,
3627acce952bSliubo 					int mark)
3628acce952bSliubo {
3629acce952bSliubo 	int ret;
3630acce952bSliubo 	struct page *page;
3631acce952bSliubo 	struct inode *btree_inode = root->fs_info->btree_inode;
3632acce952bSliubo 	struct extent_buffer *eb;
3633acce952bSliubo 	u64 start = 0;
3634acce952bSliubo 	u64 end;
3635acce952bSliubo 	u64 offset;
3636acce952bSliubo 	unsigned long index;
3637acce952bSliubo 
3638acce952bSliubo 	while (1) {
3639acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
3640acce952bSliubo 					    mark);
3641acce952bSliubo 		if (ret)
3642acce952bSliubo 			break;
3643acce952bSliubo 
3644acce952bSliubo 		clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
3645acce952bSliubo 		while (start <= end) {
3646acce952bSliubo 			index = start >> PAGE_CACHE_SHIFT;
3647acce952bSliubo 			start = (u64)(index + 1) << PAGE_CACHE_SHIFT;
3648acce952bSliubo 			page = find_get_page(btree_inode->i_mapping, index);
3649acce952bSliubo 			if (!page)
3650acce952bSliubo 				continue;
3651acce952bSliubo 			offset = page_offset(page);
3652acce952bSliubo 
3653acce952bSliubo 			spin_lock(&dirty_pages->buffer_lock);
3654acce952bSliubo 			eb = radix_tree_lookup(
3655acce952bSliubo 			     &(&BTRFS_I(page->mapping->host)->io_tree)->buffer,
3656acce952bSliubo 					       offset >> PAGE_CACHE_SHIFT);
3657acce952bSliubo 			spin_unlock(&dirty_pages->buffer_lock);
3658ee670f0aSJosef Bacik 			if (eb)
3659acce952bSliubo 				ret = test_and_clear_bit(EXTENT_BUFFER_DIRTY,
3660acce952bSliubo 							 &eb->bflags);
3661acce952bSliubo 			if (PageWriteback(page))
3662acce952bSliubo 				end_page_writeback(page);
3663acce952bSliubo 
3664acce952bSliubo 			lock_page(page);
3665acce952bSliubo 			if (PageDirty(page)) {
3666acce952bSliubo 				clear_page_dirty_for_io(page);
3667acce952bSliubo 				spin_lock_irq(&page->mapping->tree_lock);
3668acce952bSliubo 				radix_tree_tag_clear(&page->mapping->page_tree,
3669acce952bSliubo 							page_index(page),
3670acce952bSliubo 							PAGECACHE_TAG_DIRTY);
3671acce952bSliubo 				spin_unlock_irq(&page->mapping->tree_lock);
3672acce952bSliubo 			}
3673acce952bSliubo 
3674acce952bSliubo 			unlock_page(page);
3675ee670f0aSJosef Bacik 			page_cache_release(page);
3676acce952bSliubo 		}
3677acce952bSliubo 	}
3678acce952bSliubo 
3679acce952bSliubo 	return ret;
3680acce952bSliubo }
3681acce952bSliubo 
3682acce952bSliubo static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
3683acce952bSliubo 				       struct extent_io_tree *pinned_extents)
3684acce952bSliubo {
3685acce952bSliubo 	struct extent_io_tree *unpin;
3686acce952bSliubo 	u64 start;
3687acce952bSliubo 	u64 end;
3688acce952bSliubo 	int ret;
3689ed0eaa14SLiu Bo 	bool loop = true;
3690acce952bSliubo 
3691acce952bSliubo 	unpin = pinned_extents;
3692ed0eaa14SLiu Bo again:
3693acce952bSliubo 	while (1) {
3694acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
3695acce952bSliubo 					    EXTENT_DIRTY);
3696acce952bSliubo 		if (ret)
3697acce952bSliubo 			break;
3698acce952bSliubo 
3699acce952bSliubo 		/* opt_discard */
37005378e607SLi Dongyang 		if (btrfs_test_opt(root, DISCARD))
37015378e607SLi Dongyang 			ret = btrfs_error_discard_extent(root, start,
37025378e607SLi Dongyang 							 end + 1 - start,
37035378e607SLi Dongyang 							 NULL);
3704acce952bSliubo 
3705acce952bSliubo 		clear_extent_dirty(unpin, start, end, GFP_NOFS);
3706acce952bSliubo 		btrfs_error_unpin_extent_range(root, start, end);
3707acce952bSliubo 		cond_resched();
3708acce952bSliubo 	}
3709acce952bSliubo 
3710ed0eaa14SLiu Bo 	if (loop) {
3711ed0eaa14SLiu Bo 		if (unpin == &root->fs_info->freed_extents[0])
3712ed0eaa14SLiu Bo 			unpin = &root->fs_info->freed_extents[1];
3713ed0eaa14SLiu Bo 		else
3714ed0eaa14SLiu Bo 			unpin = &root->fs_info->freed_extents[0];
3715ed0eaa14SLiu Bo 		loop = false;
3716ed0eaa14SLiu Bo 		goto again;
3717ed0eaa14SLiu Bo 	}
3718ed0eaa14SLiu Bo 
3719acce952bSliubo 	return 0;
3720acce952bSliubo }
3721acce952bSliubo 
372249b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
372349b25e05SJeff Mahoney 				   struct btrfs_root *root)
372449b25e05SJeff Mahoney {
372549b25e05SJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, root);
372649b25e05SJeff Mahoney 	btrfs_block_rsv_release(root, &root->fs_info->trans_block_rsv,
372749b25e05SJeff Mahoney 				cur_trans->dirty_pages.dirty_bytes);
372849b25e05SJeff Mahoney 
372949b25e05SJeff Mahoney 	/* FIXME: cleanup wait for commit */
373049b25e05SJeff Mahoney 	cur_trans->in_commit = 1;
373149b25e05SJeff Mahoney 	cur_trans->blocked = 1;
373249b25e05SJeff Mahoney 	wake_up(&root->fs_info->transaction_blocked_wait);
373349b25e05SJeff Mahoney 
373449b25e05SJeff Mahoney 	cur_trans->blocked = 0;
373549b25e05SJeff Mahoney 	wake_up(&root->fs_info->transaction_wait);
373649b25e05SJeff Mahoney 
373749b25e05SJeff Mahoney 	cur_trans->commit_done = 1;
373849b25e05SJeff Mahoney 	wake_up(&cur_trans->commit_wait);
373949b25e05SJeff Mahoney 
374067cde344SMiao Xie 	btrfs_destroy_delayed_inodes(root);
374167cde344SMiao Xie 	btrfs_assert_delayed_root_empty(root);
374267cde344SMiao Xie 
374349b25e05SJeff Mahoney 	btrfs_destroy_pending_snapshots(cur_trans);
374449b25e05SJeff Mahoney 
374549b25e05SJeff Mahoney 	btrfs_destroy_marked_extents(root, &cur_trans->dirty_pages,
374649b25e05SJeff Mahoney 				     EXTENT_DIRTY);
37476e841e32SLiu Bo 	btrfs_destroy_pinned_extent(root,
37486e841e32SLiu Bo 				    root->fs_info->pinned_extents);
374949b25e05SJeff Mahoney 
375049b25e05SJeff Mahoney 	/*
375149b25e05SJeff Mahoney 	memset(cur_trans, 0, sizeof(*cur_trans));
375249b25e05SJeff Mahoney 	kmem_cache_free(btrfs_transaction_cachep, cur_trans);
375349b25e05SJeff Mahoney 	*/
375449b25e05SJeff Mahoney }
375549b25e05SJeff Mahoney 
375649b25e05SJeff Mahoney int btrfs_cleanup_transaction(struct btrfs_root *root)
3757acce952bSliubo {
3758acce952bSliubo 	struct btrfs_transaction *t;
3759acce952bSliubo 	LIST_HEAD(list);
3760acce952bSliubo 
3761acce952bSliubo 	mutex_lock(&root->fs_info->transaction_kthread_mutex);
3762acce952bSliubo 
3763a4abeea4SJosef Bacik 	spin_lock(&root->fs_info->trans_lock);
3764acce952bSliubo 	list_splice_init(&root->fs_info->trans_list, &list);
3765a4abeea4SJosef Bacik 	root->fs_info->trans_no_join = 1;
3766a4abeea4SJosef Bacik 	spin_unlock(&root->fs_info->trans_lock);
3767a4abeea4SJosef Bacik 
3768acce952bSliubo 	while (!list_empty(&list)) {
3769acce952bSliubo 		t = list_entry(list.next, struct btrfs_transaction, list);
3770acce952bSliubo 		if (!t)
3771acce952bSliubo 			break;
3772acce952bSliubo 
3773acce952bSliubo 		btrfs_destroy_ordered_operations(root);
3774acce952bSliubo 
3775acce952bSliubo 		btrfs_destroy_ordered_extents(root);
3776acce952bSliubo 
3777acce952bSliubo 		btrfs_destroy_delayed_refs(t, root);
3778acce952bSliubo 
3779acce952bSliubo 		btrfs_block_rsv_release(root,
3780acce952bSliubo 					&root->fs_info->trans_block_rsv,
3781acce952bSliubo 					t->dirty_pages.dirty_bytes);
3782acce952bSliubo 
3783acce952bSliubo 		/* FIXME: cleanup wait for commit */
3784acce952bSliubo 		t->in_commit = 1;
3785acce952bSliubo 		t->blocked = 1;
3786acce952bSliubo 		if (waitqueue_active(&root->fs_info->transaction_blocked_wait))
3787acce952bSliubo 			wake_up(&root->fs_info->transaction_blocked_wait);
3788acce952bSliubo 
3789acce952bSliubo 		t->blocked = 0;
3790acce952bSliubo 		if (waitqueue_active(&root->fs_info->transaction_wait))
3791acce952bSliubo 			wake_up(&root->fs_info->transaction_wait);
3792acce952bSliubo 
3793acce952bSliubo 		t->commit_done = 1;
3794acce952bSliubo 		if (waitqueue_active(&t->commit_wait))
3795acce952bSliubo 			wake_up(&t->commit_wait);
3796acce952bSliubo 
379767cde344SMiao Xie 		btrfs_destroy_delayed_inodes(root);
379867cde344SMiao Xie 		btrfs_assert_delayed_root_empty(root);
379967cde344SMiao Xie 
3800acce952bSliubo 		btrfs_destroy_pending_snapshots(t);
3801acce952bSliubo 
3802acce952bSliubo 		btrfs_destroy_delalloc_inodes(root);
3803acce952bSliubo 
3804a4abeea4SJosef Bacik 		spin_lock(&root->fs_info->trans_lock);
3805acce952bSliubo 		root->fs_info->running_transaction = NULL;
3806a4abeea4SJosef Bacik 		spin_unlock(&root->fs_info->trans_lock);
3807acce952bSliubo 
3808acce952bSliubo 		btrfs_destroy_marked_extents(root, &t->dirty_pages,
3809acce952bSliubo 					     EXTENT_DIRTY);
3810acce952bSliubo 
3811acce952bSliubo 		btrfs_destroy_pinned_extent(root,
3812acce952bSliubo 					    root->fs_info->pinned_extents);
3813acce952bSliubo 
381413c5a93eSJosef Bacik 		atomic_set(&t->use_count, 0);
3815acce952bSliubo 		list_del_init(&t->list);
3816acce952bSliubo 		memset(t, 0, sizeof(*t));
3817acce952bSliubo 		kmem_cache_free(btrfs_transaction_cachep, t);
3818acce952bSliubo 	}
3819acce952bSliubo 
3820a4abeea4SJosef Bacik 	spin_lock(&root->fs_info->trans_lock);
3821a4abeea4SJosef Bacik 	root->fs_info->trans_no_join = 0;
3822a4abeea4SJosef Bacik 	spin_unlock(&root->fs_info->trans_lock);
3823acce952bSliubo 	mutex_unlock(&root->fs_info->transaction_kthread_mutex);
3824acce952bSliubo 
3825acce952bSliubo 	return 0;
3826acce952bSliubo }
3827acce952bSliubo 
3828d1310b2eSChris Mason static struct extent_io_ops btree_extent_io_ops = {
38294bef0848SChris Mason 	.write_cache_pages_lock_hook = btree_lock_page_hook,
3830ce9adaa5SChris Mason 	.readpage_end_io_hook = btree_readpage_end_io_hook,
38314bb31e92SArne Jansen 	.readpage_io_failed_hook = btree_io_failed_hook,
38320b86a832SChris Mason 	.submit_bio_hook = btree_submit_bio_hook,
3833239b14b3SChris Mason 	/* note we're sharing with inode.c for the merge bio hook */
3834239b14b3SChris Mason 	.merge_bio_hook = btrfs_merge_bio_hook,
38350da5468fSChris Mason };
3836