xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 4eb150d6)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6e20d96d6SChris Mason #include <linux/fs.h>
7d98237b3SChris Mason #include <linux/blkdev.h>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10ce9adaa5SChris Mason #include <linux/workqueue.h>
11a74a4b97SChris Mason #include <linux/kthread.h>
125a0e3ad6STejun Heo #include <linux/slab.h>
13784b4e29SChris Mason #include <linux/migrate.h>
147a36ddecSDavid Sterba #include <linux/ratelimit.h>
156463fe58SStefan Behrens #include <linux/uuid.h>
16803b2f54SStefan Behrens #include <linux/semaphore.h>
17540adea3SMasami Hiramatsu #include <linux/error-injection.h>
189678c543SNikolay Borisov #include <linux/crc32c.h>
19b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
216d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
24e089f05cSChris Mason #include "transaction.h"
250f7d52f4SChris Mason #include "btrfs_inode.h"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41aac0023cSJosef Bacik #include "block-group.h"
42b0643e59SDennis Zhou #include "discard.h"
43f603bb94SNikolay Borisov #include "space-info.h"
44b70f5097SNaohiro Aota #include "zoned.h"
45139e8cd3SQu Wenruo #include "subpage.h"
46eb60ceacSChris Mason 
47319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
48319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
53319e4d06SQu Wenruo 
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
102141386e1SJosef Bacik {
103141386e1SJosef Bacik 	if (fs_info->csum_shash)
104141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
105141386e1SJosef Bacik }
106141386e1SJosef Bacik 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
109d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
110d352ac68SChris Mason  * just before they are sent down the IO stack.
111d352ac68SChris Mason  */
11244b8bd7eSChris Mason struct async_submit_bio {
1138896a08dSQu Wenruo 	struct inode *inode;
11444b8bd7eSChris Mason 	struct bio *bio;
115a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11644b8bd7eSChris Mason 	int mirror_num;
1171941b64bSQu Wenruo 
1181941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
1191941b64bSQu Wenruo 	u64 dio_file_offset;
1208b712842SChris Mason 	struct btrfs_work work;
1214e4cbee9SChristoph Hellwig 	blk_status_t status;
12244b8bd7eSChris Mason };
12344b8bd7eSChris Mason 
12485d4e461SChris Mason /*
12585d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12685d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12785d4e461SChris Mason  * the level the eb occupies in the tree.
1284008c04aSChris Mason  *
12985d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13085d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13185d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1324fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1334fd786e6SMisono Tomohiro  * roots have separate keysets.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13685d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13785d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1384008c04aSChris Mason  *
13985d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14085d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14185d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14285d4e461SChris Mason  *
14385d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14485d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14585d4e461SChris Mason  * needs update as well.
1464008c04aSChris Mason  */
1474008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1484008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1494008c04aSChris Mason #  error
1504008c04aSChris Mason # endif
15185d4e461SChris Mason 
152ab1405aaSDavid Sterba #define DEFINE_LEVEL(stem, level)					\
153ab1405aaSDavid Sterba 	.names[level] = "btrfs-" stem "-0" #level,
154ab1405aaSDavid Sterba 
155ab1405aaSDavid Sterba #define DEFINE_NAME(stem)						\
156ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 0)						\
157ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 1)						\
158ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 2)						\
159ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 3)						\
160ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 4)						\
161ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 5)						\
162ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 6)						\
163ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 7)
164ab1405aaSDavid Sterba 
16585d4e461SChris Mason static struct btrfs_lockdep_keyset {
16685d4e461SChris Mason 	u64			id;		/* root objectid */
167ab1405aaSDavid Sterba 	/* Longest entry: btrfs-free-space-00 */
168387824afSDavid Sterba 	char			names[BTRFS_MAX_LEVEL][20];
169387824afSDavid Sterba 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
17085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
171ab1405aaSDavid Sterba 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
172ab1405aaSDavid Sterba 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
173ab1405aaSDavid Sterba 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
174ab1405aaSDavid Sterba 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
175ab1405aaSDavid Sterba 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
176ab1405aaSDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
177ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
178ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
179ab1405aaSDavid Sterba 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
180ab1405aaSDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
181ab1405aaSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
182ab1405aaSDavid Sterba 	{ .id = 0,				DEFINE_NAME("tree")	},
1834008c04aSChris Mason };
18485d4e461SChris Mason 
185ab1405aaSDavid Sterba #undef DEFINE_LEVEL
186ab1405aaSDavid Sterba #undef DEFINE_NAME
18785d4e461SChris Mason 
18885d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18985d4e461SChris Mason 				    int level)
19085d4e461SChris Mason {
19185d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19285d4e461SChris Mason 
19385d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19485d4e461SChris Mason 
19585d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19685d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19785d4e461SChris Mason 		if (ks->id == objectid)
19885d4e461SChris Mason 			break;
19985d4e461SChris Mason 
20085d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20185d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20285d4e461SChris Mason }
20385d4e461SChris Mason 
2044008c04aSChris Mason #endif
2054008c04aSChris Mason 
206d352ac68SChris Mason /*
2072996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
208d352ac68SChris Mason  */
209c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
21019c00ddcSChris Mason {
211d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
2127280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
213a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
214d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
21519c00ddcSChris Mason 	char *kaddr;
216e9be5a30SDavid Sterba 	int i;
217d5178578SJohannes Thumshirn 
218d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
219d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
220a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
221e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
222a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
22319c00ddcSChris Mason 
224e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
225e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
226e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
22719c00ddcSChris Mason 	}
22871a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
229d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
23019c00ddcSChris Mason }
23119c00ddcSChris Mason 
232d352ac68SChris Mason /*
233d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
234d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
235d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
236d352ac68SChris Mason  * in the wrong place.
237d352ac68SChris Mason  */
2381259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
239b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
240b9fab919SChris Mason 				 int atomic)
2411259ab75SChris Mason {
2422ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2431259ab75SChris Mason 	int ret;
2441259ab75SChris Mason 
2451259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
2461259ab75SChris Mason 		return 0;
2471259ab75SChris Mason 
248b9fab919SChris Mason 	if (atomic)
249b9fab919SChris Mason 		return -EAGAIN;
250b9fab919SChris Mason 
2512ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
252ff13db41SDavid Sterba 			 &cached_state);
2530b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
2541259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
2551259ab75SChris Mason 		ret = 0;
2561259ab75SChris Mason 		goto out;
2571259ab75SChris Mason 	}
25894647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
25994647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
26094647322SDavid Sterba 			eb->start,
26129549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
2621259ab75SChris Mason 	ret = 1;
2630b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
26433958dc6SChris Mason out:
2652ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
266e43bbe5eSDavid Sterba 			     &cached_state);
2671259ab75SChris Mason 	return ret;
2681259ab75SChris Mason }
2691259ab75SChris Mason 
270e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
271e7e16f48SJohannes Thumshirn {
272e7e16f48SJohannes Thumshirn 	switch (csum_type) {
273e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
2743951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
2753831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
276352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
277e7e16f48SJohannes Thumshirn 		return true;
278e7e16f48SJohannes Thumshirn 	default:
279e7e16f48SJohannes Thumshirn 		return false;
280e7e16f48SJohannes Thumshirn 	}
281e7e16f48SJohannes Thumshirn }
282e7e16f48SJohannes Thumshirn 
283d352ac68SChris Mason /*
2841104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
2851104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
2861104a885SDavid Sterba  */
287ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
288ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
2891104a885SDavid Sterba {
2901104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
2911104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
29251bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
293d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
294d5178578SJohannes Thumshirn 
295d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
2961104a885SDavid Sterba 
2971104a885SDavid Sterba 	/*
2981104a885SDavid Sterba 	 * The super_block structure does not span the whole
29951bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
30051bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3011104a885SDavid Sterba 	 */
302fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
303fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3041104a885SDavid Sterba 
30555fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
306e7e16f48SJohannes Thumshirn 		return 1;
3071104a885SDavid Sterba 
308e7e16f48SJohannes Thumshirn 	return 0;
3091104a885SDavid Sterba }
3101104a885SDavid Sterba 
311e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
312ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
313581c1760SQu Wenruo {
314e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
315581c1760SQu Wenruo 	int found_level;
316581c1760SQu Wenruo 	struct btrfs_key found_key;
317581c1760SQu Wenruo 	int ret;
318581c1760SQu Wenruo 
319581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
320581c1760SQu Wenruo 	if (found_level != level) {
32163489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
32263489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
323581c1760SQu Wenruo 		btrfs_err(fs_info,
324581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
325581c1760SQu Wenruo 			  eb->start, level, found_level);
326581c1760SQu Wenruo 		return -EIO;
327581c1760SQu Wenruo 	}
328581c1760SQu Wenruo 
329581c1760SQu Wenruo 	if (!first_key)
330581c1760SQu Wenruo 		return 0;
331581c1760SQu Wenruo 
3325d41be6fSQu Wenruo 	/*
3335d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3345d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
3355d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
3365d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
3375d41be6fSQu Wenruo 	 */
3385d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
3395d41be6fSQu Wenruo 		return 0;
34062fdaa52SQu Wenruo 
34162fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
34262fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
34362fdaa52SQu Wenruo 		btrfs_err(fs_info,
34462fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
34562fdaa52SQu Wenruo 			  eb->start);
34662fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
34762fdaa52SQu Wenruo 		return -EUCLEAN;
34862fdaa52SQu Wenruo 	}
34962fdaa52SQu Wenruo 
350581c1760SQu Wenruo 	if (found_level)
351581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
352581c1760SQu Wenruo 	else
353581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
354581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
355581c1760SQu Wenruo 
356581c1760SQu Wenruo 	if (ret) {
35763489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
35863489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
359581c1760SQu Wenruo 		btrfs_err(fs_info,
360ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
361ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
362ff76a864SLiu Bo 			  first_key->type, first_key->offset,
363ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
364ff76a864SLiu Bo 			  found_key.offset);
365581c1760SQu Wenruo 	}
366581c1760SQu Wenruo 	return ret;
367581c1760SQu Wenruo }
368581c1760SQu Wenruo 
3691104a885SDavid Sterba /*
370d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
371d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
372581c1760SQu Wenruo  *
373581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
374581c1760SQu Wenruo  * @level:		expected level, mandatory check
375581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
376d352ac68SChris Mason  */
3775ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
378581c1760SQu Wenruo 					  u64 parent_transid, int level,
379581c1760SQu Wenruo 					  struct btrfs_key *first_key)
380f188591eSChris Mason {
3815ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
382f188591eSChris Mason 	struct extent_io_tree *io_tree;
383ea466794SJosef Bacik 	int failed = 0;
384f188591eSChris Mason 	int ret;
385f188591eSChris Mason 	int num_copies = 0;
386f188591eSChris Mason 	int mirror_num = 0;
387ea466794SJosef Bacik 	int failed_mirror = 0;
388f188591eSChris Mason 
3890b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
390f188591eSChris Mason 	while (1) {
391f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
392c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
393256dd1bbSStefan Behrens 		if (!ret) {
394581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
395b9fab919SChris Mason 						   parent_transid, 0))
396256dd1bbSStefan Behrens 				ret = -EIO;
397e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
398ff76a864SLiu Bo 						first_key, parent_transid))
399581c1760SQu Wenruo 				ret = -EUCLEAN;
400581c1760SQu Wenruo 			else
401581c1760SQu Wenruo 				break;
402256dd1bbSStefan Behrens 		}
403d397712bSChris Mason 
4040b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
405f188591eSChris Mason 					      eb->start, eb->len);
4064235298eSChris Mason 		if (num_copies == 1)
407ea466794SJosef Bacik 			break;
4084235298eSChris Mason 
4095cf1ab56SJosef Bacik 		if (!failed_mirror) {
4105cf1ab56SJosef Bacik 			failed = 1;
4115cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4125cf1ab56SJosef Bacik 		}
4135cf1ab56SJosef Bacik 
414f188591eSChris Mason 		mirror_num++;
415ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
416ea466794SJosef Bacik 			mirror_num++;
417ea466794SJosef Bacik 
4184235298eSChris Mason 		if (mirror_num > num_copies)
419ea466794SJosef Bacik 			break;
420f188591eSChris Mason 	}
421ea466794SJosef Bacik 
422c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
42320a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
424ea466794SJosef Bacik 
425ea466794SJosef Bacik 	return ret;
426f188591eSChris Mason }
42719c00ddcSChris Mason 
428eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
429eca0f6f6SQu Wenruo {
430eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
431eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
432eca0f6f6SQu Wenruo 	int ret;
433eca0f6f6SQu Wenruo 
434eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
435eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
436eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
437eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
438eca0f6f6SQu Wenruo 
439eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
440eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
441eca0f6f6SQu Wenruo 	else
442eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
443eca0f6f6SQu Wenruo 
444eca0f6f6SQu Wenruo 	if (ret < 0) {
445eca0f6f6SQu Wenruo 		btrfs_print_tree(eb, 0);
446eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
447eca0f6f6SQu Wenruo 			"block=%llu write time tree block corruption detected",
448eca0f6f6SQu Wenruo 			eb->start);
449eca0f6f6SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
450eca0f6f6SQu Wenruo 		return ret;
451eca0f6f6SQu Wenruo 	}
452eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
453eca0f6f6SQu Wenruo 
454eca0f6f6SQu Wenruo 	return 0;
455eca0f6f6SQu Wenruo }
456eca0f6f6SQu Wenruo 
457eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
458eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
459eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
460eca0f6f6SQu Wenruo {
461eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
462eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
463eca0f6f6SQu Wenruo 	u64 cur;
464eca0f6f6SQu Wenruo 	int ret = 0;
465eca0f6f6SQu Wenruo 
466eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
467eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
468eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
469eca0f6f6SQu Wenruo 		bool uptodate;
470eca0f6f6SQu Wenruo 
471eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
472eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
473eca0f6f6SQu Wenruo 						       fs_info->nodesize);
474eca0f6f6SQu Wenruo 
475eca0f6f6SQu Wenruo 		/* A dirty eb shouldn't disappear from buffer_radix */
476eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
477eca0f6f6SQu Wenruo 			return -EUCLEAN;
478eca0f6f6SQu Wenruo 
479eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
480eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
481eca0f6f6SQu Wenruo 			return -EUCLEAN;
482eca0f6f6SQu Wenruo 		}
483eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
484eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
485eca0f6f6SQu Wenruo 			return -EUCLEAN;
486eca0f6f6SQu Wenruo 		}
487eca0f6f6SQu Wenruo 
488eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
489eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
490eca0f6f6SQu Wenruo 		if (ret < 0)
491eca0f6f6SQu Wenruo 			return ret;
492eca0f6f6SQu Wenruo 	}
493eca0f6f6SQu Wenruo 	return ret;
494eca0f6f6SQu Wenruo }
495eca0f6f6SQu Wenruo 
496d352ac68SChris Mason /*
497ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
498ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
499ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
500d352ac68SChris Mason  */
501ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
50219c00ddcSChris Mason {
503ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
5044eee4fa4SMiao Xie 	u64 start = page_offset(page);
50519c00ddcSChris Mason 	u64 found_start;
50619c00ddcSChris Mason 	struct extent_buffer *eb;
507eca0f6f6SQu Wenruo 
508eca0f6f6SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE)
509eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
510f188591eSChris Mason 
5114f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5124f2de97aSJosef Bacik 	if (page != eb->pages[0])
5134f2de97aSJosef Bacik 		return 0;
5140f805531SAlex Lyakas 
51519c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
516d3575156SNaohiro Aota 
517d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
518d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
519d3575156SNaohiro Aota 		return 0;
520d3575156SNaohiro Aota 	}
521d3575156SNaohiro Aota 
5220f805531SAlex Lyakas 	/*
5230f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5240f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5250f805531SAlex Lyakas 	 */
5260f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5270f805531SAlex Lyakas 		return -EUCLEAN;
5280f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5290f805531SAlex Lyakas 		return -EUCLEAN;
5300f805531SAlex Lyakas 
531eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
53219c00ddcSChris Mason }
53319c00ddcSChris Mason 
534b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5352b82032cSYan Zheng {
536b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
537944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
53844880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
539944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5402b82032cSYan Zheng 
5419a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5429a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5437239ff4bSNikolay Borisov 	/*
544944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
545944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
546944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5477239ff4bSNikolay Borisov 	 */
548944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5497239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5507239ff4bSNikolay Borisov 	else
5517239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5527239ff4bSNikolay Borisov 
553944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
554944d3f9fSNikolay Borisov 		return 0;
555944d3f9fSNikolay Borisov 
556944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
557944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
558944d3f9fSNikolay Borisov 			return 0;
559944d3f9fSNikolay Borisov 
560944d3f9fSNikolay Borisov 	return 1;
5612b82032cSYan Zheng }
5622b82032cSYan Zheng 
56377bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
56477bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
565ce9adaa5SChris Mason {
56677bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
567ce9adaa5SChris Mason 	u64 found_start;
56877bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
56977bf40a2SQu Wenruo 	u8 found_level;
5702996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
571dfd29eedSDavid Sterba 	const u8 *header_csum;
57277bf40a2SQu Wenruo 	int ret = 0;
573ea466794SJosef Bacik 
574ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
575727011e0SChris Mason 	if (found_start != eb->start) {
576893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
577893bf4b1SSu Yue 			     eb->start, found_start);
578f188591eSChris Mason 		ret = -EIO;
57977bf40a2SQu Wenruo 		goto out;
580ce9adaa5SChris Mason 	}
581b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
58202873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
58394647322SDavid Sterba 			     eb->start);
5841259ab75SChris Mason 		ret = -EIO;
58577bf40a2SQu Wenruo 		goto out;
5861259ab75SChris Mason 	}
587ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5881c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
589893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
590893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5911c24c3ceSJosef Bacik 		ret = -EIO;
59277bf40a2SQu Wenruo 		goto out;
5931c24c3ceSJosef Bacik 	}
594ce9adaa5SChris Mason 
595c67b3892SDavid Sterba 	csum_tree_block(eb, result);
596dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
597dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
598a826d6dcSJosef Bacik 
599dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
6002996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
601ff14aa79SDavid Sterba 	"checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
602ff14aa79SDavid Sterba 			      eb->start,
603dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
60435be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
60535be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
6062996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
60777bf40a2SQu Wenruo 		goto out;
6082996e1f8SJohannes Thumshirn 	}
6092996e1f8SJohannes Thumshirn 
610a826d6dcSJosef Bacik 	/*
611a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
612a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
613a826d6dcSJosef Bacik 	 * return -EIO.
614a826d6dcSJosef Bacik 	 */
6151c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
616a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
617a826d6dcSJosef Bacik 		ret = -EIO;
618a826d6dcSJosef Bacik 	}
619ce9adaa5SChris Mason 
620813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
621053ab70fSLiu Bo 		ret = -EIO;
622053ab70fSLiu Bo 
6230b32f4bbSJosef Bacik 	if (!ret)
6240b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
62575391f0dSQu Wenruo 	else
62675391f0dSQu Wenruo 		btrfs_err(fs_info,
62775391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
62875391f0dSQu Wenruo 			  eb->start);
62977bf40a2SQu Wenruo out:
63077bf40a2SQu Wenruo 	return ret;
63177bf40a2SQu Wenruo }
63277bf40a2SQu Wenruo 
633371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
634371cdc07SQu Wenruo 				   int mirror)
635371cdc07SQu Wenruo {
636371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
637371cdc07SQu Wenruo 	struct extent_buffer *eb;
638371cdc07SQu Wenruo 	bool reads_done;
639371cdc07SQu Wenruo 	int ret = 0;
640371cdc07SQu Wenruo 
641371cdc07SQu Wenruo 	/*
642371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
643371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
644371cdc07SQu Wenruo 	 */
645371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
646371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
647371cdc07SQu Wenruo 
648371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
649371cdc07SQu Wenruo 	/*
650371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
651371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
652371cdc07SQu Wenruo 	 */
653371cdc07SQu Wenruo 	ASSERT(eb);
654371cdc07SQu Wenruo 
655371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
656371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
657371cdc07SQu Wenruo 	ASSERT(reads_done);
658371cdc07SQu Wenruo 
659371cdc07SQu Wenruo 	eb->read_mirror = mirror;
660371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
661371cdc07SQu Wenruo 		ret = -EIO;
662371cdc07SQu Wenruo 		goto err;
663371cdc07SQu Wenruo 	}
664371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
665371cdc07SQu Wenruo 	if (ret < 0)
666371cdc07SQu Wenruo 		goto err;
667371cdc07SQu Wenruo 
668371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
669371cdc07SQu Wenruo 
670371cdc07SQu Wenruo 	free_extent_buffer(eb);
671371cdc07SQu Wenruo 	return ret;
672371cdc07SQu Wenruo err:
673371cdc07SQu Wenruo 	/*
674371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
675371cdc07SQu Wenruo 	 * make sure it has something to decrement.
676371cdc07SQu Wenruo 	 */
677371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
678371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
679371cdc07SQu Wenruo 	free_extent_buffer(eb);
680371cdc07SQu Wenruo 	return ret;
681371cdc07SQu Wenruo }
682371cdc07SQu Wenruo 
683c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
68477bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
68577bf40a2SQu Wenruo 				   int mirror)
68677bf40a2SQu Wenruo {
68777bf40a2SQu Wenruo 	struct extent_buffer *eb;
68877bf40a2SQu Wenruo 	int ret = 0;
68977bf40a2SQu Wenruo 	int reads_done;
69077bf40a2SQu Wenruo 
69177bf40a2SQu Wenruo 	ASSERT(page->private);
692371cdc07SQu Wenruo 
693371cdc07SQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
694371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
695371cdc07SQu Wenruo 
69677bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
69777bf40a2SQu Wenruo 
69877bf40a2SQu Wenruo 	/*
69977bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
70077bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
70177bf40a2SQu Wenruo 	 */
70277bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
70377bf40a2SQu Wenruo 
70477bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
70577bf40a2SQu Wenruo 	if (!reads_done)
70677bf40a2SQu Wenruo 		goto err;
70777bf40a2SQu Wenruo 
70877bf40a2SQu Wenruo 	eb->read_mirror = mirror;
70977bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
71077bf40a2SQu Wenruo 		ret = -EIO;
71177bf40a2SQu Wenruo 		goto err;
71277bf40a2SQu Wenruo 	}
71377bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
714ce9adaa5SChris Mason err:
71553b381b3SDavid Woodhouse 	if (ret) {
71653b381b3SDavid Woodhouse 		/*
71753b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
71853b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
71953b381b3SDavid Woodhouse 		 * to decrement
72053b381b3SDavid Woodhouse 		 */
72153b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7220b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
72353b381b3SDavid Woodhouse 	}
7240b32f4bbSJosef Bacik 	free_extent_buffer(eb);
72577bf40a2SQu Wenruo 
726f188591eSChris Mason 	return ret;
727ce9adaa5SChris Mason }
728ce9adaa5SChris Mason 
7294246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
730ce9adaa5SChris Mason {
73197eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
732ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7339e0af237SLiu Bo 	struct btrfs_workqueue *wq;
734ce9adaa5SChris Mason 
735ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7364e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
737d20f7043SChris Mason 
738cfe94440SNaohiro Aota 	if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
739a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7409e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
741a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7429e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
743a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7449e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
745a0cac0ecSOmar Sandoval 		else
7469e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7479e0af237SLiu Bo 	} else {
7485c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7499e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
750a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7519e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
752a0cac0ecSOmar Sandoval 		else
7539e0af237SLiu Bo 			wq = fs_info->endio_workers;
7549e0af237SLiu Bo 	}
7559e0af237SLiu Bo 
756a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7579e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
758ce9adaa5SChris Mason }
759ce9adaa5SChris Mason 
7604e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
761bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7620b86a832SChris Mason {
76397eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7648b110e39SMiao Xie 
76597eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
766ce9adaa5SChris Mason 	if (!end_io_wq)
7674e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
768ce9adaa5SChris Mason 
769ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
770ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
77122c59948SChris Mason 	end_io_wq->info = info;
7724e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
773ce9adaa5SChris Mason 	end_io_wq->bio = bio;
77422c59948SChris Mason 	end_io_wq->metadata = metadata;
775ce9adaa5SChris Mason 
776ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
777ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
77822c59948SChris Mason 	return 0;
77922c59948SChris Mason }
78022c59948SChris Mason 
7814a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7824a69a410SChris Mason {
7834a69a410SChris Mason 	struct async_submit_bio *async;
7844e4cbee9SChristoph Hellwig 	blk_status_t ret;
7854a69a410SChris Mason 
7864a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7871941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
7881941b64bSQu Wenruo 				      async->dio_file_offset);
78979787eaaSJeff Mahoney 	if (ret)
7904e4cbee9SChristoph Hellwig 		async->status = ret;
7914a69a410SChris Mason }
7924a69a410SChris Mason 
79306ea01b1SDavid Sterba /*
79406ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
79506ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
79606ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
79706ea01b1SDavid Sterba  *
79806ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
79906ea01b1SDavid Sterba  * inserted into the tree.
80006ea01b1SDavid Sterba  */
8014a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
8028b712842SChris Mason {
8038b712842SChris Mason 	struct async_submit_bio *async;
80406ea01b1SDavid Sterba 	struct inode *inode;
80506ea01b1SDavid Sterba 	blk_status_t ret;
8068b712842SChris Mason 
8078b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8088896a08dSQu Wenruo 	inode = async->inode;
8094854ddd0SChris Mason 
810bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
8114e4cbee9SChristoph Hellwig 	if (async->status) {
8124e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
8134246a0b6SChristoph Hellwig 		bio_endio(async->bio);
81479787eaaSJeff Mahoney 		return;
81579787eaaSJeff Mahoney 	}
81679787eaaSJeff Mahoney 
817ec39f769SChris Mason 	/*
818ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
819ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
820ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
821ec39f769SChris Mason 	 */
822ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
82308635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
82406ea01b1SDavid Sterba 	if (ret) {
82506ea01b1SDavid Sterba 		async->bio->bi_status = ret;
82606ea01b1SDavid Sterba 		bio_endio(async->bio);
82706ea01b1SDavid Sterba 	}
8284a69a410SChris Mason }
8294a69a410SChris Mason 
8304a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8314a69a410SChris Mason {
8324a69a410SChris Mason 	struct async_submit_bio *async;
8334a69a410SChris Mason 
8344a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8358b712842SChris Mason 	kfree(async);
8368b712842SChris Mason }
8378b712842SChris Mason 
8388896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
839c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
8401941b64bSQu Wenruo 				 u64 dio_file_offset,
841e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
84244b8bd7eSChris Mason {
8438896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
84444b8bd7eSChris Mason 	struct async_submit_bio *async;
84544b8bd7eSChris Mason 
84644b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
84744b8bd7eSChris Mason 	if (!async)
8484e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
84944b8bd7eSChris Mason 
8508896a08dSQu Wenruo 	async->inode = inode;
85144b8bd7eSChris Mason 	async->bio = bio;
85244b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8534a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8544a69a410SChris Mason 
855a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
856a0cac0ecSOmar Sandoval 			run_one_async_free);
8574a69a410SChris Mason 
8581941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
8598c8bee1dSChris Mason 
8604e4cbee9SChristoph Hellwig 	async->status = 0;
86179787eaaSJeff Mahoney 
86267f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8635cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
864d313d7a3SChris Mason 
8655cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
86644b8bd7eSChris Mason 	return 0;
86744b8bd7eSChris Mason }
86844b8bd7eSChris Mason 
8694e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
870ce3ed71aSChris Mason {
8712c30c71bSKent Overstreet 	struct bio_vec *bvec;
872ce3ed71aSChris Mason 	struct btrfs_root *root;
8732b070cfeSChristoph Hellwig 	int ret = 0;
8746dc4f100SMing Lei 	struct bvec_iter_all iter_all;
875ce3ed71aSChris Mason 
876c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8772b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
878ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
879ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
88079787eaaSJeff Mahoney 		if (ret)
88179787eaaSJeff Mahoney 			break;
882ce3ed71aSChris Mason 	}
8832c30c71bSKent Overstreet 
8844e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
885ce3ed71aSChris Mason }
886ce3ed71aSChris Mason 
8878896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
8881941b64bSQu Wenruo 					   u64 dio_file_offset)
88922c59948SChris Mason {
8908b712842SChris Mason 	/*
8918b712842SChris Mason 	 * when we're called for a write, we're already in the async
8925443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8938b712842SChris Mason 	 */
89479787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
89522c59948SChris Mason }
89622c59948SChris Mason 
897f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
8989b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
899de0022b9SJosef Bacik {
9004eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
901f4dcfb30SJohannes Thumshirn 		return false;
9026300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
903f4dcfb30SJohannes Thumshirn 		return false;
9049b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
905f4dcfb30SJohannes Thumshirn 		return false;
906f4dcfb30SJohannes Thumshirn 	return true;
907de0022b9SJosef Bacik }
908de0022b9SJosef Bacik 
9091b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
9101b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
91144b8bd7eSChris Mason {
9120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9134e4cbee9SChristoph Hellwig 	blk_status_t ret;
914cad321adSChris Mason 
915cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
916cad321adSChris Mason 		/*
917cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
918cad321adSChris Mason 		 * can happen in the async kernel threads
919cad321adSChris Mason 		 */
9200b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
9210b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
9221d4284bdSChris Mason 		if (ret)
92361891923SStefan Behrens 			goto out_w_error;
92408635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
925f4dcfb30SJohannes Thumshirn 	} else if (!should_async_write(fs_info, BTRFS_I(inode))) {
926de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
927de0022b9SJosef Bacik 		if (ret)
92861891923SStefan Behrens 			goto out_w_error;
92908635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
93061891923SStefan Behrens 	} else {
931cad321adSChris Mason 		/*
93261891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
93361891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
934cad321adSChris Mason 		 */
9358896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
9368896a08dSQu Wenruo 					  0, btree_submit_bio_start);
93744b8bd7eSChris Mason 	}
93844b8bd7eSChris Mason 
9394246a0b6SChristoph Hellwig 	if (ret)
9404246a0b6SChristoph Hellwig 		goto out_w_error;
9414246a0b6SChristoph Hellwig 	return 0;
9424246a0b6SChristoph Hellwig 
94361891923SStefan Behrens out_w_error:
9444e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9454246a0b6SChristoph Hellwig 	bio_endio(bio);
94661891923SStefan Behrens 	return ret;
94761891923SStefan Behrens }
94861891923SStefan Behrens 
9493dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
950784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
951a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
952a6bc32b8SMel Gorman 			enum migrate_mode mode)
953784b4e29SChris Mason {
954784b4e29SChris Mason 	/*
955784b4e29SChris Mason 	 * we can't safely write a btree page from here,
956784b4e29SChris Mason 	 * we haven't done the locking hook
957784b4e29SChris Mason 	 */
958784b4e29SChris Mason 	if (PageDirty(page))
959784b4e29SChris Mason 		return -EAGAIN;
960784b4e29SChris Mason 	/*
961784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
962784b4e29SChris Mason 	 * We must have no buffers or drop them.
963784b4e29SChris Mason 	 */
964784b4e29SChris Mason 	if (page_has_private(page) &&
965784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
966784b4e29SChris Mason 		return -EAGAIN;
967a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
968784b4e29SChris Mason }
9693dd1462eSJan Beulich #endif
970784b4e29SChris Mason 
9710da5468fSChris Mason 
9720da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9730da5468fSChris Mason 			    struct writeback_control *wbc)
9740da5468fSChris Mason {
975e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
976e2d84521SMiao Xie 	int ret;
977e2d84521SMiao Xie 
978d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
979448d640bSChris Mason 
980448d640bSChris Mason 		if (wbc->for_kupdate)
981448d640bSChris Mason 			return 0;
982448d640bSChris Mason 
983e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
984b9473439SChris Mason 		/* this is a bit racy, but that's ok */
985d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
986d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
987d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
988e2d84521SMiao Xie 		if (ret < 0)
989793955bcSChris Mason 			return 0;
990793955bcSChris Mason 	}
9910b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9920da5468fSChris Mason }
9930da5468fSChris Mason 
99470dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9955f39d397SChris Mason {
99698509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
99798509cfcSChris Mason 		return 0;
9980c4e538bSDavid Sterba 
999f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1000d98237b3SChris Mason }
1001d98237b3SChris Mason 
1002d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1003d47992f8SLukas Czerner 				 unsigned int length)
1004d98237b3SChris Mason {
1005d1310b2eSChris Mason 	struct extent_io_tree *tree;
1006d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10075f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
10085f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
10099ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1010efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1011efe120a0SFrank Holton 			   "page private not zero on page %llu",
1012efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
1013d1b89bc0SGuoqing Jiang 		detach_page_private(page);
10149ad6b7bcSChris Mason 	}
1015d98237b3SChris Mason }
1016d98237b3SChris Mason 
10170b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10180b32f4bbSJosef Bacik {
1019bb146eb2SJosef Bacik #ifdef DEBUG
1020139e8cd3SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
1021139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
10220b32f4bbSJosef Bacik 	struct extent_buffer *eb;
1023139e8cd3SQu Wenruo 	int cur_bit = 0;
1024139e8cd3SQu Wenruo 	u64 page_start = page_offset(page);
10250b32f4bbSJosef Bacik 
1026139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
10270b32f4bbSJosef Bacik 		BUG_ON(!PagePrivate(page));
10280b32f4bbSJosef Bacik 		eb = (struct extent_buffer *)page->private;
10290b32f4bbSJosef Bacik 		BUG_ON(!eb);
10300b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10310b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
103249d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1033139e8cd3SQu Wenruo 		return __set_page_dirty_nobuffers(page);
1034139e8cd3SQu Wenruo 	}
1035139e8cd3SQu Wenruo 	ASSERT(PagePrivate(page) && page->private);
1036139e8cd3SQu Wenruo 	subpage = (struct btrfs_subpage *)page->private;
1037139e8cd3SQu Wenruo 
1038139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
1039139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
1040139e8cd3SQu Wenruo 		unsigned long flags;
1041139e8cd3SQu Wenruo 		u64 cur;
1042139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
1043139e8cd3SQu Wenruo 
1044139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
1045139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
1046139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
1047139e8cd3SQu Wenruo 			cur_bit++;
1048139e8cd3SQu Wenruo 			continue;
1049139e8cd3SQu Wenruo 		}
1050139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
1051139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
1052139e8cd3SQu Wenruo 
1053139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
1054139e8cd3SQu Wenruo 		ASSERT(eb);
1055139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1056139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
105749d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1058139e8cd3SQu Wenruo 		free_extent_buffer(eb);
1059139e8cd3SQu Wenruo 
1060139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
1061139e8cd3SQu Wenruo 	}
1062bb146eb2SJosef Bacik #endif
10630b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10640b32f4bbSJosef Bacik }
10650b32f4bbSJosef Bacik 
10667f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
10670da5468fSChris Mason 	.writepages	= btree_writepages,
10685f39d397SChris Mason 	.releasepage	= btree_releasepage,
10695f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10705a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1071784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10725a92bc88SChris Mason #endif
10730b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1074d98237b3SChris Mason };
1075123abc88SChris Mason 
10762ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10772ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10783fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
10793fbaf258SJosef Bacik 						int level)
10800999df54SChris Mason {
10810b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10820b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10833fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
10840999df54SChris Mason }
10850999df54SChris Mason 
1086581c1760SQu Wenruo /*
1087581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1088581c1760SQu Wenruo  * verification.
1089581c1760SQu Wenruo  *
10901b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
1091581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1092581c1760SQu Wenruo  * @level:		expected level, mandatory check
1093581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1094581c1760SQu Wenruo  */
10952ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
10961b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
10971b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
1098e20d96d6SChris Mason {
10995f39d397SChris Mason 	struct extent_buffer *buf = NULL;
110019c00ddcSChris Mason 	int ret;
110119c00ddcSChris Mason 
11023fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
1103c871b0f2SLiu Bo 	if (IS_ERR(buf))
1104c871b0f2SLiu Bo 		return buf;
1105e4204dedSChris Mason 
11065ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1107581c1760SQu Wenruo 					     level, first_key);
11080f0fe8f7SFilipe David Borba Manana 	if (ret) {
1109537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
111064c043deSLiu Bo 		return ERR_PTR(ret);
11110f0fe8f7SFilipe David Borba Manana 	}
11125f39d397SChris Mason 	return buf;
1113ce9adaa5SChris Mason 
1114eb60ceacSChris Mason }
1115eb60ceacSChris Mason 
11166a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1117ed2ff2cbSChris Mason {
11186a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
111955c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1120e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
112149d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
1122b4ce94deSChris Mason 
1123b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1124104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1125e2d84521SMiao Xie 						 -buf->len,
1126e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
11270b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1128925baeddSChris Mason 		}
11295f39d397SChris Mason 	}
1130ed7b63ebSJosef Bacik }
11315f39d397SChris Mason 
1132da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1133e20d96d6SChris Mason 			 u64 objectid)
1134d97e63b6SChris Mason {
11357c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
11362e608bd1SJosef Bacik 
11372e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
11382e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
11392e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
114096dfcb46SJosef Bacik 	root->fs_info = fs_info;
11412e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
1142cfaa7295SChris Mason 	root->node = NULL;
1143a28ec197SChris Mason 	root->commit_root = NULL;
114427cdeb70SMiao Xie 	root->state = 0;
1145abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
11460b86a832SChris Mason 
11470f7d52f4SChris Mason 	root->last_trans = 0;
11486b8fad57SNikolay Borisov 	root->free_objectid = 0;
1149eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1150199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11516bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115216cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
11532e608bd1SJosef Bacik 
11542e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
11550b86a832SChris Mason 
11560b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11575d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1158eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1159eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1160199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1161199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1162d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11632ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11642ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11655d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1166eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1167199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1168f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11692ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11702ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11718287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1172a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1173e02119d5SChris Mason 	mutex_init(&root->log_mutex);
117431f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1175573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1176c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11777237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11787237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11797237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11808b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11818b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11827237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11837237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11847237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11852ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11860700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11878ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1188eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11897237f183SYan Zheng 	root->log_transid = 0;
1190d1433debSMiao Xie 	root->log_transid_committed = -1;
1191257c62e1SChris Mason 	root->last_log_commit = 0;
11922e608bd1SJosef Bacik 	root->anon_dev = 0;
1193e289f03eSFilipe Manana 	if (!dummy) {
119443eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
119543eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1196e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1197e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1198e289f03eSFilipe Manana 	}
1199017e5369SChris Mason 
12005f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1201370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1202bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1203bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1204bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1205bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1206bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1207bd647ce3SJosef Bacik #endif
12083768f368SChris Mason }
12093768f368SChris Mason 
121074e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
121196dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
12126f07e42eSAl Viro {
121374e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12146f07e42eSAl Viro 	if (root)
121596dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
12166f07e42eSAl Viro 	return root;
12176f07e42eSAl Viro }
12186f07e42eSAl Viro 
121906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
122006ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1221da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
122206ea65a3SJosef Bacik {
122306ea65a3SJosef Bacik 	struct btrfs_root *root;
122406ea65a3SJosef Bacik 
12257c0260eeSJeff Mahoney 	if (!fs_info)
12267c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12277c0260eeSJeff Mahoney 
122896dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
122906ea65a3SJosef Bacik 	if (!root)
123006ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1231da17066cSJeff Mahoney 
1232b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1233faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
123406ea65a3SJosef Bacik 
123506ea65a3SJosef Bacik 	return root;
123606ea65a3SJosef Bacik }
123706ea65a3SJosef Bacik #endif
123806ea65a3SJosef Bacik 
1239abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
1240abed4aaaSJosef Bacik {
1241abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
1242abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
1243abed4aaaSJosef Bacik 
1244abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
1245abed4aaaSJosef Bacik }
1246abed4aaaSJosef Bacik 
1247abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
1248abed4aaaSJosef Bacik {
1249abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
1250abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
1251abed4aaaSJosef Bacik 
1252abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
1253abed4aaaSJosef Bacik }
1254abed4aaaSJosef Bacik 
1255abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
1256abed4aaaSJosef Bacik {
1257abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1258abed4aaaSJosef Bacik 	struct rb_node *tmp;
1259abed4aaaSJosef Bacik 
1260abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1261abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1262abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1263abed4aaaSJosef Bacik 	ASSERT(!tmp);
1264abed4aaaSJosef Bacik 
1265abed4aaaSJosef Bacik 	return tmp ? -EEXIST : 0;
1266abed4aaaSJosef Bacik }
1267abed4aaaSJosef Bacik 
1268abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
1269abed4aaaSJosef Bacik {
1270abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1271abed4aaaSJosef Bacik 
1272abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1273abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
1274abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1275abed4aaaSJosef Bacik }
1276abed4aaaSJosef Bacik 
1277abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1278abed4aaaSJosef Bacik 				     struct btrfs_key *key)
1279abed4aaaSJosef Bacik {
1280abed4aaaSJosef Bacik 	struct rb_node *node;
1281abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
1282abed4aaaSJosef Bacik 
1283abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
1284abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1285abed4aaaSJosef Bacik 	if (node)
1286abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
1287abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
1288abed4aaaSJosef Bacik 
1289abed4aaaSJosef Bacik 	return root;
1290abed4aaaSJosef Bacik }
1291abed4aaaSJosef Bacik 
1292f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1293f7238e50SJosef Bacik {
1294f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
1295f7238e50SJosef Bacik 	u64 ret;
1296f7238e50SJosef Bacik 
1297f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1298f7238e50SJosef Bacik 		return 0;
1299f7238e50SJosef Bacik 
1300f7238e50SJosef Bacik 	if (bytenr)
1301f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
1302f7238e50SJosef Bacik 	else
1303f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1304f7238e50SJosef Bacik 	ASSERT(block_group);
1305f7238e50SJosef Bacik 	if (!block_group)
1306f7238e50SJosef Bacik 		return 0;
1307f7238e50SJosef Bacik 	ret = block_group->global_root_id;
1308f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
1309f7238e50SJosef Bacik 
1310f7238e50SJosef Bacik 	return ret;
1311f7238e50SJosef Bacik }
1312f7238e50SJosef Bacik 
1313abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1314abed4aaaSJosef Bacik {
1315abed4aaaSJosef Bacik 	struct btrfs_key key = {
1316abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1317abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1318f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1319abed4aaaSJosef Bacik 	};
1320abed4aaaSJosef Bacik 
1321abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1322abed4aaaSJosef Bacik }
1323abed4aaaSJosef Bacik 
1324abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1325abed4aaaSJosef Bacik {
1326abed4aaaSJosef Bacik 	struct btrfs_key key = {
1327abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1328abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1329f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1330abed4aaaSJosef Bacik 	};
1331abed4aaaSJosef Bacik 
1332abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1333abed4aaaSJosef Bacik }
1334abed4aaaSJosef Bacik 
133520897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
133620897f5cSArne Jansen 				     u64 objectid)
133720897f5cSArne Jansen {
13389b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
133920897f5cSArne Jansen 	struct extent_buffer *leaf;
134020897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
134120897f5cSArne Jansen 	struct btrfs_root *root;
134220897f5cSArne Jansen 	struct btrfs_key key;
1343b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
134420897f5cSArne Jansen 	int ret = 0;
134520897f5cSArne Jansen 
1346b89f6d1fSFilipe Manana 	/*
1347b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1348b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1349b89f6d1fSFilipe Manana 	 */
1350b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
135196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1352b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
135320897f5cSArne Jansen 	if (!root)
135420897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
135520897f5cSArne Jansen 
135620897f5cSArne Jansen 	root->root_key.objectid = objectid;
135720897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
135820897f5cSArne Jansen 	root->root_key.offset = 0;
135920897f5cSArne Jansen 
13609631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
13619631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
136220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
136320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
13641dd05682STsutomu Itoh 		leaf = NULL;
13658a6a87cdSBoris Burkov 		goto fail_unlock;
136620897f5cSArne Jansen 	}
136720897f5cSArne Jansen 
136820897f5cSArne Jansen 	root->node = leaf;
136920897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
137020897f5cSArne Jansen 
137120897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
137227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
137320897f5cSArne Jansen 
1374f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1375f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
137620897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
137720897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
137820897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
137920897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
138020897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
138120897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
138220897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
138333d85fdaSQu Wenruo 	if (is_fstree(objectid))
1384807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1385807fc790SAndy Shevchenko 	else
1386807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1387c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
138820897f5cSArne Jansen 
13898a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
13908a6a87cdSBoris Burkov 
139120897f5cSArne Jansen 	key.objectid = objectid;
139220897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
139320897f5cSArne Jansen 	key.offset = 0;
139420897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
139520897f5cSArne Jansen 	if (ret)
139620897f5cSArne Jansen 		goto fail;
139720897f5cSArne Jansen 
139820897f5cSArne Jansen 	return root;
13991dd05682STsutomu Itoh 
14008a6a87cdSBoris Burkov fail_unlock:
14018c38938cSJosef Bacik 	if (leaf)
14021dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
14038a6a87cdSBoris Burkov fail:
140400246528SJosef Bacik 	btrfs_put_root(root);
14051dd05682STsutomu Itoh 
14061dd05682STsutomu Itoh 	return ERR_PTR(ret);
140720897f5cSArne Jansen }
140820897f5cSArne Jansen 
14097237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1410e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
14110f7d52f4SChris Mason {
14120f7d52f4SChris Mason 	struct btrfs_root *root;
1413e02119d5SChris Mason 
141496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1415e02119d5SChris Mason 	if (!root)
14167237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1417e02119d5SChris Mason 
1418e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1419e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1420e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
142127cdeb70SMiao Xie 
14226ab6ebb7SNaohiro Aota 	return root;
14236ab6ebb7SNaohiro Aota }
14246ab6ebb7SNaohiro Aota 
14256ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
14266ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
14276ab6ebb7SNaohiro Aota {
14286ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
14296ab6ebb7SNaohiro Aota 
14307237f183SYan Zheng 	/*
143192a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
143227cdeb70SMiao Xie 	 *
143392a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
143492a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
143592a7cc42SQu Wenruo 	 *
143692a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
143792a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
14387237f183SYan Zheng 	 */
1439e02119d5SChris Mason 
14404d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
14419631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
14426ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
14436ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1444e02119d5SChris Mason 
14457237f183SYan Zheng 	root->node = leaf;
1446e02119d5SChris Mason 
1447e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1448e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
14496ab6ebb7SNaohiro Aota 
14506ab6ebb7SNaohiro Aota 	return 0;
14517237f183SYan Zheng }
14527237f183SYan Zheng 
14537237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
14547237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
14557237f183SYan Zheng {
14567237f183SYan Zheng 	struct btrfs_root *log_root;
14577237f183SYan Zheng 
14587237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
14597237f183SYan Zheng 	if (IS_ERR(log_root))
14607237f183SYan Zheng 		return PTR_ERR(log_root);
14616ab6ebb7SNaohiro Aota 
14623ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
14633ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
14643ddebf27SNaohiro Aota 
14656ab6ebb7SNaohiro Aota 		if (ret) {
14666ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
14676ab6ebb7SNaohiro Aota 			return ret;
14686ab6ebb7SNaohiro Aota 		}
14693ddebf27SNaohiro Aota 	}
14706ab6ebb7SNaohiro Aota 
14717237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
14727237f183SYan Zheng 	fs_info->log_root_tree = log_root;
14737237f183SYan Zheng 	return 0;
14747237f183SYan Zheng }
14757237f183SYan Zheng 
14767237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
14777237f183SYan Zheng 		       struct btrfs_root *root)
14787237f183SYan Zheng {
14790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14807237f183SYan Zheng 	struct btrfs_root *log_root;
14817237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
14826ab6ebb7SNaohiro Aota 	int ret;
14837237f183SYan Zheng 
14840b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
14857237f183SYan Zheng 	if (IS_ERR(log_root))
14867237f183SYan Zheng 		return PTR_ERR(log_root);
14877237f183SYan Zheng 
14886ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
14896ab6ebb7SNaohiro Aota 	if (ret) {
14906ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
14916ab6ebb7SNaohiro Aota 		return ret;
14926ab6ebb7SNaohiro Aota 	}
14936ab6ebb7SNaohiro Aota 
14947237f183SYan Zheng 	log_root->last_trans = trans->transid;
14957237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14967237f183SYan Zheng 
14977237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14983cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14993cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
15003cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1501da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
15020b246afaSJeff Mahoney 				     fs_info->nodesize);
15033cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
15047237f183SYan Zheng 
15055d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
15067237f183SYan Zheng 
15077237f183SYan Zheng 	WARN_ON(root->log_root);
15087237f183SYan Zheng 	root->log_root = log_root;
15097237f183SYan Zheng 	root->log_transid = 0;
1510d1433debSMiao Xie 	root->log_transid_committed = -1;
1511257c62e1SChris Mason 	root->last_log_commit = 0;
1512e02119d5SChris Mason 	return 0;
1513e02119d5SChris Mason }
1514e02119d5SChris Mason 
151549d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
151649d11beaSJosef Bacik 					      struct btrfs_path *path,
1517cb517eabSMiao Xie 					      struct btrfs_key *key)
1518e02119d5SChris Mason {
1519e02119d5SChris Mason 	struct btrfs_root *root;
1520e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
152184234f3aSYan Zheng 	u64 generation;
1522cb517eabSMiao Xie 	int ret;
1523581c1760SQu Wenruo 	int level;
1524cb517eabSMiao Xie 
152596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
152649d11beaSJosef Bacik 	if (!root)
152749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
15280f7d52f4SChris Mason 
1529cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1530cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
15310f7d52f4SChris Mason 	if (ret) {
153213a8a7c8SYan, Zheng 		if (ret > 0)
153313a8a7c8SYan, Zheng 			ret = -ENOENT;
153449d11beaSJosef Bacik 		goto fail;
15350f7d52f4SChris Mason 	}
153613a8a7c8SYan, Zheng 
153784234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1538581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
15392ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
15402ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
15411b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
154264c043deSLiu Bo 	if (IS_ERR(root->node)) {
154364c043deSLiu Bo 		ret = PTR_ERR(root->node);
15448c38938cSJosef Bacik 		root->node = NULL;
154549d11beaSJosef Bacik 		goto fail;
1546*4eb150d6SQu Wenruo 	}
1547*4eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1548cb517eabSMiao Xie 		ret = -EIO;
154949d11beaSJosef Bacik 		goto fail;
1550416bc658SJosef Bacik 	}
15515d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1552cb517eabSMiao Xie 	return root;
155349d11beaSJosef Bacik fail:
155400246528SJosef Bacik 	btrfs_put_root(root);
155549d11beaSJosef Bacik 	return ERR_PTR(ret);
155649d11beaSJosef Bacik }
155749d11beaSJosef Bacik 
155849d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
155949d11beaSJosef Bacik 					struct btrfs_key *key)
156049d11beaSJosef Bacik {
156149d11beaSJosef Bacik 	struct btrfs_root *root;
156249d11beaSJosef Bacik 	struct btrfs_path *path;
156349d11beaSJosef Bacik 
156449d11beaSJosef Bacik 	path = btrfs_alloc_path();
156549d11beaSJosef Bacik 	if (!path)
156649d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
156749d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
156849d11beaSJosef Bacik 	btrfs_free_path(path);
156949d11beaSJosef Bacik 
157049d11beaSJosef Bacik 	return root;
1571cb517eabSMiao Xie }
1572cb517eabSMiao Xie 
15732dfb1e43SQu Wenruo /*
15742dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
15752dfb1e43SQu Wenruo  *
15762dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
15772dfb1e43SQu Wenruo  */
15782dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1579cb517eabSMiao Xie {
1580cb517eabSMiao Xie 	int ret;
1581dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1582cb517eabSMiao Xie 
1583dcc3eb96SNikolay Borisov 	/*
1584dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1585dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1586dcc3eb96SNikolay Borisov 	 */
1587dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1588dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1589dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1590dcc3eb96SNikolay Borisov 	if (ret)
15918257b2dcSMiao Xie 		goto fail;
15928257b2dcSMiao Xie 
1593aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
159437f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
159592a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1596f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1597f39e4571SJosef Bacik 	}
1598f39e4571SJosef Bacik 
1599851fd730SQu Wenruo 	/*
1600851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1601851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1602851fd730SQu Wenruo 	 */
1603851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1604851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
16052dfb1e43SQu Wenruo 		if (!anon_dev) {
1606cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1607cb517eabSMiao Xie 			if (ret)
1608876d2cf1SLiu Bo 				goto fail;
16092dfb1e43SQu Wenruo 		} else {
16102dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
16112dfb1e43SQu Wenruo 		}
1612851fd730SQu Wenruo 	}
1613f32e48e9SChandan Rajendra 
1614f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1615453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1616f32e48e9SChandan Rajendra 	if (ret) {
1617f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1618876d2cf1SLiu Bo 		goto fail;
1619f32e48e9SChandan Rajendra 	}
1620f32e48e9SChandan Rajendra 
16216b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1622f32e48e9SChandan Rajendra 
1623f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1624f32e48e9SChandan Rajendra 
1625cb517eabSMiao Xie 	return 0;
1626cb517eabSMiao Xie fail:
162784db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1628cb517eabSMiao Xie 	return ret;
1629cb517eabSMiao Xie }
1630cb517eabSMiao Xie 
1631a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1632cb517eabSMiao Xie 					       u64 root_id)
1633cb517eabSMiao Xie {
1634cb517eabSMiao Xie 	struct btrfs_root *root;
1635cb517eabSMiao Xie 
1636cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1637cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1638cb517eabSMiao Xie 				 (unsigned long)root_id);
1639bc44d7c4SJosef Bacik 	if (root)
164000246528SJosef Bacik 		root = btrfs_grab_root(root);
1641cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1642cb517eabSMiao Xie 	return root;
1643cb517eabSMiao Xie }
1644cb517eabSMiao Xie 
164549d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
164649d11beaSJosef Bacik 						u64 objectid)
164749d11beaSJosef Bacik {
1648abed4aaaSJosef Bacik 	struct btrfs_key key = {
1649abed4aaaSJosef Bacik 		.objectid = objectid,
1650abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1651abed4aaaSJosef Bacik 		.offset = 0,
1652abed4aaaSJosef Bacik 	};
1653abed4aaaSJosef Bacik 
165449d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
165549d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
165649d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1657abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
165849d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
165949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
166049d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
166149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
166249d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1663abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
166449d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
166549d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
166649d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
166749d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
166849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
166949d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
1670abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1671abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1672abed4aaaSJosef Bacik 
1673abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1674abed4aaaSJosef Bacik 	}
167549d11beaSJosef Bacik 	return NULL;
167649d11beaSJosef Bacik }
167749d11beaSJosef Bacik 
1678cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1679cb517eabSMiao Xie 			 struct btrfs_root *root)
1680cb517eabSMiao Xie {
1681cb517eabSMiao Xie 	int ret;
1682cb517eabSMiao Xie 
1683e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1684cb517eabSMiao Xie 	if (ret)
1685cb517eabSMiao Xie 		return ret;
1686cb517eabSMiao Xie 
1687cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1688cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1689cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1690cb517eabSMiao Xie 				root);
1691af01d2e5SJosef Bacik 	if (ret == 0) {
169200246528SJosef Bacik 		btrfs_grab_root(root);
169327cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1694af01d2e5SJosef Bacik 	}
1695cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1696cb517eabSMiao Xie 	radix_tree_preload_end();
1697cb517eabSMiao Xie 
1698cb517eabSMiao Xie 	return ret;
1699cb517eabSMiao Xie }
1700cb517eabSMiao Xie 
1701bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1702bd647ce3SJosef Bacik {
1703bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1704bd647ce3SJosef Bacik 	struct btrfs_root *root;
1705bd647ce3SJosef Bacik 
1706bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1707457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1708457f1864SJosef Bacik 
1709bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1710bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1711457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
171271008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1713bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1714bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
171500246528SJosef Bacik 			btrfs_put_root(root);
171600246528SJosef Bacik 		btrfs_put_root(root);
1717bd647ce3SJosef Bacik 	}
1718bd647ce3SJosef Bacik #endif
1719bd647ce3SJosef Bacik }
1720bd647ce3SJosef Bacik 
1721abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1722abed4aaaSJosef Bacik {
1723abed4aaaSJosef Bacik 	struct btrfs_root *root;
1724abed4aaaSJosef Bacik 	struct rb_node *node;
1725abed4aaaSJosef Bacik 
1726abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1727abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1728abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1729abed4aaaSJosef Bacik 		btrfs_put_root(root);
1730abed4aaaSJosef Bacik 	}
1731abed4aaaSJosef Bacik }
1732abed4aaaSJosef Bacik 
17330d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
17340d4b0463SJosef Bacik {
1735141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1736141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
17375deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1738141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1739141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1740141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1741141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
17420d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
17430d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1744abed4aaaSJosef Bacik 	free_global_roots(fs_info);
174500246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
174600246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
174700246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
174800246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
174900246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
175000246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1751aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
17529c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1753bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
17543fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
17550d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
17560d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
17578481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
17580d4b0463SJosef Bacik 	kvfree(fs_info);
17590d4b0463SJosef Bacik }
17600d4b0463SJosef Bacik 
17610d4b0463SJosef Bacik 
17622dfb1e43SQu Wenruo /*
17632dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
17642dfb1e43SQu Wenruo  *
17652dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
17662dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
17672dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
17682dfb1e43SQu Wenruo  *
17692dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
17702dfb1e43SQu Wenruo  *
17712dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
17722dfb1e43SQu Wenruo  *	 same root objectid.
17732dfb1e43SQu Wenruo  *
17742dfb1e43SQu Wenruo  * @objectid:	root id
17752dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
17762dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
17772dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
17782dfb1e43SQu Wenruo  *		for orphan roots
17792dfb1e43SQu Wenruo  */
17802dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
17812dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
17822dfb1e43SQu Wenruo 					     bool check_ref)
17835eda7b5eSChris Mason {
17845eda7b5eSChris Mason 	struct btrfs_root *root;
1785381cf658SDavid Sterba 	struct btrfs_path *path;
17861d4c08e0SDavid Sterba 	struct btrfs_key key;
17875eda7b5eSChris Mason 	int ret;
17885eda7b5eSChris Mason 
178949d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
179049d11beaSJosef Bacik 	if (root)
179149d11beaSJosef Bacik 		return root;
17924df27c4dSYan, Zheng again:
179356e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
179448475471SStefan Behrens 	if (root) {
17952dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
17962dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1797bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
179800246528SJosef Bacik 			btrfs_put_root(root);
179948475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1800bc44d7c4SJosef Bacik 		}
18015eda7b5eSChris Mason 		return root;
180248475471SStefan Behrens 	}
18035eda7b5eSChris Mason 
180456e9357aSDavid Sterba 	key.objectid = objectid;
180556e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
180656e9357aSDavid Sterba 	key.offset = (u64)-1;
180756e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
18085eda7b5eSChris Mason 	if (IS_ERR(root))
18095eda7b5eSChris Mason 		return root;
18103394e160SChris Mason 
1811c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1812d68fc57bSYan, Zheng 		ret = -ENOENT;
1813d68fc57bSYan, Zheng 		goto fail;
1814d68fc57bSYan, Zheng 	}
1815d68fc57bSYan, Zheng 
18162dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1817cb517eabSMiao Xie 	if (ret)
1818cb517eabSMiao Xie 		goto fail;
1819cb517eabSMiao Xie 
1820381cf658SDavid Sterba 	path = btrfs_alloc_path();
1821381cf658SDavid Sterba 	if (!path) {
1822381cf658SDavid Sterba 		ret = -ENOMEM;
1823381cf658SDavid Sterba 		goto fail;
1824381cf658SDavid Sterba 	}
18251d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
18261d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
182756e9357aSDavid Sterba 	key.offset = objectid;
18281d4c08e0SDavid Sterba 
18291d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1830381cf658SDavid Sterba 	btrfs_free_path(path);
1831d68fc57bSYan, Zheng 	if (ret < 0)
1832d68fc57bSYan, Zheng 		goto fail;
1833d68fc57bSYan, Zheng 	if (ret == 0)
183427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1835d68fc57bSYan, Zheng 
1836cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
18370f7d52f4SChris Mason 	if (ret) {
183800246528SJosef Bacik 		btrfs_put_root(root);
18394785e24fSJosef Bacik 		if (ret == -EEXIST)
18404df27c4dSYan, Zheng 			goto again;
18414df27c4dSYan, Zheng 		goto fail;
18424df27c4dSYan, Zheng 	}
1843edbd8d4eSChris Mason 	return root;
18444df27c4dSYan, Zheng fail:
184533fab972SFilipe Manana 	/*
184633fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
184733fab972SFilipe Manana 	 * responsability to free it in case we fail. So we have to set our
184833fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
184933fab972SFilipe Manana 	 * and once again by our caller.
185033fab972SFilipe Manana 	 */
185133fab972SFilipe Manana 	if (anon_dev)
185233fab972SFilipe Manana 		root->anon_dev = 0;
18538c38938cSJosef Bacik 	btrfs_put_root(root);
18544df27c4dSYan, Zheng 	return ERR_PTR(ret);
1855edbd8d4eSChris Mason }
1856edbd8d4eSChris Mason 
18572dfb1e43SQu Wenruo /*
18582dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
18592dfb1e43SQu Wenruo  *
18602dfb1e43SQu Wenruo  * @objectid:	tree objectid
18612dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
18622dfb1e43SQu Wenruo  *		one reference
18632dfb1e43SQu Wenruo  */
18642dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
18652dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
18662dfb1e43SQu Wenruo {
18672dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
18682dfb1e43SQu Wenruo }
18692dfb1e43SQu Wenruo 
18702dfb1e43SQu Wenruo /*
18712dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
18722dfb1e43SQu Wenruo  * the anonymous block device id
18732dfb1e43SQu Wenruo  *
18742dfb1e43SQu Wenruo  * @objectid:	tree objectid
18752dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
18762dfb1e43SQu Wenruo  *		parameter value
18772dfb1e43SQu Wenruo  */
18782dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
18792dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
18802dfb1e43SQu Wenruo {
18812dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
18822dfb1e43SQu Wenruo }
18832dfb1e43SQu Wenruo 
18848b712842SChris Mason /*
188549d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
188649d11beaSJosef Bacik  * @fs_info:	the fs_info
188749d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
188849d11beaSJosef Bacik  *
188949d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
189049d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
189149d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
189249d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
189349d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
189449d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
189549d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
189649d11beaSJosef Bacik  * backref code is finished using the root.
189749d11beaSJosef Bacik  */
189849d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
189949d11beaSJosef Bacik 						 struct btrfs_path *path,
190049d11beaSJosef Bacik 						 u64 objectid)
190149d11beaSJosef Bacik {
190249d11beaSJosef Bacik 	struct btrfs_root *root;
190349d11beaSJosef Bacik 	struct btrfs_key key;
190449d11beaSJosef Bacik 
190549d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
190649d11beaSJosef Bacik 
190749d11beaSJosef Bacik 	/*
190849d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
190949d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
191049d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
191149d11beaSJosef Bacik 	 * != NULL just return it.
191249d11beaSJosef Bacik 	 */
191349d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
191449d11beaSJosef Bacik 	if (root)
191549d11beaSJosef Bacik 		return root;
191649d11beaSJosef Bacik 
191749d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
191849d11beaSJosef Bacik 	if (root)
191949d11beaSJosef Bacik 		return root;
192049d11beaSJosef Bacik 
192149d11beaSJosef Bacik 	key.objectid = objectid;
192249d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
192349d11beaSJosef Bacik 	key.offset = (u64)-1;
192449d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
192549d11beaSJosef Bacik 	btrfs_release_path(path);
192649d11beaSJosef Bacik 
192749d11beaSJosef Bacik 	return root;
192849d11beaSJosef Bacik }
192949d11beaSJosef Bacik 
193049d11beaSJosef Bacik /*
19318b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
19328b712842SChris Mason  * functions.  This is where read checksum verification actually happens
19338b712842SChris Mason  */
19348b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1935ce9adaa5SChris Mason {
1936ce9adaa5SChris Mason 	struct bio *bio;
193797eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1938ce9adaa5SChris Mason 
193997eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1940ce9adaa5SChris Mason 	bio = end_io_wq->bio;
19418b712842SChris Mason 
19424e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1943ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1944ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
19454246a0b6SChristoph Hellwig 	bio_endio(bio);
19469be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1947ce9adaa5SChris Mason }
194844b8bd7eSChris Mason 
1949a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1950a74a4b97SChris Mason {
195133c44184SJosef Bacik 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)arg;
1952d0278245SMiao Xie 	int again;
1953a74a4b97SChris Mason 
1954d6fd0ae2SOmar Sandoval 	while (1) {
1955d0278245SMiao Xie 		again = 0;
19569d1a2a3aSDavid Sterba 
1957fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1958fd340d0fSJosef Bacik 
1959d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
19602ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1961d0278245SMiao Xie 			goto sleep;
1962d0278245SMiao Xie 
196390c711abSZygo Blaxell 		/*
196490c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
196590c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
196690c711abSZygo Blaxell 		 */
19670b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
196890c711abSZygo Blaxell 			goto sleep;
196990c711abSZygo Blaxell 
19700b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1971d0278245SMiao Xie 			goto sleep;
1972d0278245SMiao Xie 
1973dc7f370cSMiao Xie 		/*
1974dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1975dc7f370cSMiao Xie 		 * during the above check and trylock.
1976dc7f370cSMiao Xie 		 */
19772ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
19780b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1979dc7f370cSMiao Xie 			goto sleep;
1980dc7f370cSMiao Xie 		}
1981dc7f370cSMiao Xie 
19822ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1983c2d6cb16SFilipe Manana 
198433c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
19850b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1986a74a4b97SChris Mason 
1987d0278245SMiao Xie 		/*
198805323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
198905323cd1SMiao Xie 		 * needn't do anything special here.
1990d0278245SMiao Xie 		 */
19910b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
199267c5e7d4SFilipe Manana 
199367c5e7d4SFilipe Manana 		/*
1994f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
199567c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
199667c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1997f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
199867c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
199967c5e7d4SFilipe Manana 		 * unused block groups.
200067c5e7d4SFilipe Manana 		 */
20010b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
200218bb8bbfSJohannes Thumshirn 
200318bb8bbfSJohannes Thumshirn 		/*
200418bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
200518bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
200618bb8bbfSJohannes Thumshirn 		 * space.
200718bb8bbfSJohannes Thumshirn 		 */
200818bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
2009d0278245SMiao Xie sleep:
2010a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
2011d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
2012d6fd0ae2SOmar Sandoval 			kthread_parkme();
2013d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
2014d6fd0ae2SOmar Sandoval 			return 0;
2015838fe188SJiri Kosina 		if (!again) {
2016a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
2017a74a4b97SChris Mason 			schedule();
2018a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
2019a74a4b97SChris Mason 		}
2020da288d28SFilipe Manana 	}
2021a74a4b97SChris Mason }
2022a74a4b97SChris Mason 
2023a74a4b97SChris Mason static int transaction_kthread(void *arg)
2024a74a4b97SChris Mason {
2025a74a4b97SChris Mason 	struct btrfs_root *root = arg;
20260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2027a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
2028a74a4b97SChris Mason 	struct btrfs_transaction *cur;
20298929ecfaSYan, Zheng 	u64 transid;
2030643900beSNikolay Borisov 	time64_t delta;
2031a74a4b97SChris Mason 	unsigned long delay;
2032914b2007SJan Kara 	bool cannot_commit;
2033a74a4b97SChris Mason 
2034a74a4b97SChris Mason 	do {
2035914b2007SJan Kara 		cannot_commit = false;
2036ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
20370b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
2038a74a4b97SChris Mason 
20390b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
20400b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
2041a74a4b97SChris Mason 		if (!cur) {
20420b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2043a74a4b97SChris Mason 			goto sleep;
2044a74a4b97SChris Mason 		}
204531153d81SYan Zheng 
2046643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
2047fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
2048fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
2049643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
20500b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
2051fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
2052fb8a7e94SNikolay Borisov 			delay = min(delay,
2053fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
2054a74a4b97SChris Mason 			goto sleep;
2055a74a4b97SChris Mason 		}
20568929ecfaSYan, Zheng 		transid = cur->transid;
20570b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
205856bec294SChris Mason 
205979787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
2060354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
2061914b2007SJan Kara 		if (IS_ERR(trans)) {
2062354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
2063914b2007SJan Kara 				cannot_commit = true;
206479787eaaSJeff Mahoney 			goto sleep;
2065914b2007SJan Kara 		}
20668929ecfaSYan, Zheng 		if (transid == trans->transid) {
20673a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
20688929ecfaSYan, Zheng 		} else {
20693a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
20708929ecfaSYan, Zheng 		}
2071a74a4b97SChris Mason sleep:
20720b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
20730b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
2074a74a4b97SChris Mason 
207584961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
20762ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
20778929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
20780b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
2079914b2007SJan Kara 				 cannot_commit))
2080bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
2081a74a4b97SChris Mason 	} while (!kthread_should_stop());
2082a74a4b97SChris Mason 	return 0;
2083a74a4b97SChris Mason }
2084a74a4b97SChris Mason 
2085af31f5e5SChris Mason /*
208601f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
208701f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
208801f0f9daSNikolay Borisov  * anything.
2089af31f5e5SChris Mason  *
2090af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
2091af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
2092af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
2093af31f5e5SChris Mason  */
209401f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
2095af31f5e5SChris Mason {
209601f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
2097af31f5e5SChris Mason 	u64 cur;
2098af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2099af31f5e5SChris Mason 	int i;
2100af31f5e5SChris Mason 
2101af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2102af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
2103af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
2104af31f5e5SChris Mason 		if (cur == newest_gen)
210501f0f9daSNikolay Borisov 			return i;
2106af31f5e5SChris Mason 	}
2107af31f5e5SChris Mason 
210801f0f9daSNikolay Borisov 	return -EINVAL;
2109af31f5e5SChris Mason }
2110af31f5e5SChris Mason 
2111af31f5e5SChris Mason /*
2112af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
2113af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
2114af31f5e5SChris Mason  * done
2115af31f5e5SChris Mason  */
2116af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
2117af31f5e5SChris Mason {
21186ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
2119af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2120af31f5e5SChris Mason 
2121af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2122af31f5e5SChris Mason 
2123af31f5e5SChris Mason 	/*
2124af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2125af31f5e5SChris Mason 	 * regardless of which ones we use today
2126af31f5e5SChris Mason 	 */
2127af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2128af31f5e5SChris Mason 
2129af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2130af31f5e5SChris Mason 
2131af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2132af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2133af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2134af31f5e5SChris Mason 
2135af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2136af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2137af31f5e5SChris Mason 
2138af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2139af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2140af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2141af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2142af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2143af31f5e5SChris Mason 
21449c54e80dSJosef Bacik 	if (btrfs_fs_incompat(info, EXTENT_TREE_V2)) {
21459c54e80dSJosef Bacik 		btrfs_set_backup_block_group_root(root_backup,
21469c54e80dSJosef Bacik 					info->block_group_root->node->start);
21479c54e80dSJosef Bacik 		btrfs_set_backup_block_group_root_gen(root_backup,
21489c54e80dSJosef Bacik 			btrfs_header_generation(info->block_group_root->node));
21499c54e80dSJosef Bacik 		btrfs_set_backup_block_group_root_level(root_backup,
21509c54e80dSJosef Bacik 			btrfs_header_level(info->block_group_root->node));
21519c54e80dSJosef Bacik 	} else {
21529c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
2153f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
21549c54e80dSJosef Bacik 
21559c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
21569c54e80dSJosef Bacik 					     extent_root->node->start);
2157af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
215829cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
2159af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
216029cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
2161f7238e50SJosef Bacik 
2162f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
2163f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
2164f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
2165f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
2166f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
21679c54e80dSJosef Bacik 	}
2168af31f5e5SChris Mason 
21697c7e82a7SChris Mason 	/*
21707c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
21717c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
21727c7e82a7SChris Mason 	 */
21737c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
21747c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
21757c7e82a7SChris Mason 					 info->fs_root->node->start);
2176af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2177af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2178af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2179af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
21807c7e82a7SChris Mason 	}
2181af31f5e5SChris Mason 
2182af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2183af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2184af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2185af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2186af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2187af31f5e5SChris Mason 
2188af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2189af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2190af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2191af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2192af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2193af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2194af31f5e5SChris Mason 
2195af31f5e5SChris Mason 	/*
2196af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2197af31f5e5SChris Mason 	 * for the next commit
2198af31f5e5SChris Mason 	 */
2199af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2200af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2201af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2202af31f5e5SChris Mason }
2203af31f5e5SChris Mason 
2204af31f5e5SChris Mason /*
2205bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2206bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2207bd2336b2SNikolay Borisov  *
2208bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2209bd2336b2SNikolay Borisov  * priority - priority of backup root required
2210bd2336b2SNikolay Borisov  *
2211bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2212bd2336b2SNikolay Borisov  */
2213bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2214bd2336b2SNikolay Borisov {
2215bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2216bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2217bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2218bd2336b2SNikolay Borisov 
2219bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2220bd2336b2SNikolay Borisov 		if (priority == 0)
2221bd2336b2SNikolay Borisov 			return backup_index;
2222bd2336b2SNikolay Borisov 
2223bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2224bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2225bd2336b2SNikolay Borisov 	} else {
2226bd2336b2SNikolay Borisov 		return -EINVAL;
2227bd2336b2SNikolay Borisov 	}
2228bd2336b2SNikolay Borisov 
2229bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2230bd2336b2SNikolay Borisov 
2231bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2232bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2233bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2234bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2235bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2236bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2237bd2336b2SNikolay Borisov 
2238bd2336b2SNikolay Borisov 	/*
2239bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2240bd2336b2SNikolay Borisov 	 * need a fsck
2241bd2336b2SNikolay Borisov 	 */
2242bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2243bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2244bd2336b2SNikolay Borisov 
2245bd2336b2SNikolay Borisov 	return backup_index;
2246bd2336b2SNikolay Borisov }
2247bd2336b2SNikolay Borisov 
22487abadb64SLiu Bo /* helper to cleanup workers */
22497abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
22507abadb64SLiu Bo {
2251dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2252afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
22535cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2254fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2255fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2256d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2257fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2258fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
22595b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2260e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2261a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2262fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2263b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2264b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2265a9b9477dSFilipe Manana 	/*
2266a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2267a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2268a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2269a9b9477dSFilipe Manana 	 */
2270a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2271a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
22727abadb64SLiu Bo }
22737abadb64SLiu Bo 
22742e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
22752e9f5954SRashika {
22762e9f5954SRashika 	if (root) {
22772e9f5954SRashika 		free_extent_buffer(root->node);
22782e9f5954SRashika 		free_extent_buffer(root->commit_root);
22792e9f5954SRashika 		root->node = NULL;
22802e9f5954SRashika 		root->commit_root = NULL;
22812e9f5954SRashika 	}
22822e9f5954SRashika }
22832e9f5954SRashika 
2284abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2285abed4aaaSJosef Bacik {
2286abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
2287abed4aaaSJosef Bacik 
2288abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
2289abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
2290abed4aaaSJosef Bacik 					     rb_node)
2291abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
2292abed4aaaSJosef Bacik }
2293abed4aaaSJosef Bacik 
2294af31f5e5SChris Mason /* helper to cleanup tree roots */
22954273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2296af31f5e5SChris Mason {
22972e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2298655b09feSJosef Bacik 
2299abed4aaaSJosef Bacik 	free_global_root_pointers(info);
23002e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
23012e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
23022e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
23038c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2304aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
23059c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
23064273eaffSAnand Jain 	if (free_chunk_root)
23072e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2308af31f5e5SChris Mason }
2309af31f5e5SChris Mason 
23108c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
23118c38938cSJosef Bacik {
23128c38938cSJosef Bacik 	if (!root)
23138c38938cSJosef Bacik 		return;
23148c38938cSJosef Bacik 
23158c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
23168c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
23171dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
23188c38938cSJosef Bacik 		if (root->anon_dev)
23198c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
23208c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2321923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
23228c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
23238c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
23248c38938cSJosef Bacik 		list_del_init(&root->leak_list);
23258c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
23268c38938cSJosef Bacik #endif
23278c38938cSJosef Bacik 		kfree(root);
23288c38938cSJosef Bacik 	}
23298c38938cSJosef Bacik }
23308c38938cSJosef Bacik 
2331faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2332171f6537SJosef Bacik {
2333171f6537SJosef Bacik 	int ret;
2334171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2335171f6537SJosef Bacik 	int i;
2336171f6537SJosef Bacik 
2337171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2338171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2339171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2340171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2341171f6537SJosef Bacik 
23428c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2343cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
234400246528SJosef Bacik 		btrfs_put_root(gang[0]);
2345171f6537SJosef Bacik 	}
2346171f6537SJosef Bacik 
2347171f6537SJosef Bacik 	while (1) {
2348171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2349171f6537SJosef Bacik 					     (void **)gang, 0,
2350171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2351171f6537SJosef Bacik 		if (!ret)
2352171f6537SJosef Bacik 			break;
2353171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2354cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2355171f6537SJosef Bacik 	}
2356171f6537SJosef Bacik }
2357af31f5e5SChris Mason 
2358638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2359638aa7edSEric Sandeen {
2360638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2361638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2362638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2363638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2364638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2365638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2366ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2367638aa7edSEric Sandeen }
2368638aa7edSEric Sandeen 
2369779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2370779a65a4SEric Sandeen {
2371779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2372779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2373779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2374779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2375779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2376779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2377907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2378779a65a4SEric Sandeen }
2379779a65a4SEric Sandeen 
23806bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2381f37938e0SEric Sandeen {
23822ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
23832ff7e61eSJeff Mahoney 
23842ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
23852ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2386f37938e0SEric Sandeen 	/*
2387f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2388f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2389f37938e0SEric Sandeen 	 * the devices in the system
2390f37938e0SEric Sandeen 	 */
23912ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
23922ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2393f37938e0SEric Sandeen 
23942ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
239543eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
23962c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
23977b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
23982ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2399f37938e0SEric Sandeen 
24005c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
24012ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
24022ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
24032ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2404f37938e0SEric Sandeen }
2405f37938e0SEric Sandeen 
2406ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2407ad618368SEric Sandeen {
2408ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2409129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
24107f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2411ad618368SEric Sandeen }
2412ad618368SEric Sandeen 
2413f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2414f9e92e40SEric Sandeen {
2415f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2416f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2417f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2418f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2419f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2420f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2421d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2422f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2423f9e92e40SEric Sandeen }
2424f9e92e40SEric Sandeen 
2425d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
24262a458198SEric Sandeen {
2427f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
24286f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
24292a458198SEric Sandeen 
24302a458198SEric Sandeen 	fs_info->workers =
2431cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2432cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
24332a458198SEric Sandeen 
24342a458198SEric Sandeen 	fs_info->delalloc_workers =
2435cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2436cb001095SJeff Mahoney 				      flags, max_active, 2);
24372a458198SEric Sandeen 
24382a458198SEric Sandeen 	fs_info->flush_workers =
2439cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2440cb001095SJeff Mahoney 				      flags, max_active, 0);
24412a458198SEric Sandeen 
24422a458198SEric Sandeen 	fs_info->caching_workers =
2443cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
24442a458198SEric Sandeen 
24452a458198SEric Sandeen 	fs_info->fixup_workers =
2446cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
24472a458198SEric Sandeen 
24482a458198SEric Sandeen 	/*
24492a458198SEric Sandeen 	 * endios are largely parallel and should have a very
24502a458198SEric Sandeen 	 * low idle thresh
24512a458198SEric Sandeen 	 */
24522a458198SEric Sandeen 	fs_info->endio_workers =
2453cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
24542a458198SEric Sandeen 	fs_info->endio_meta_workers =
2455cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2456cb001095SJeff Mahoney 				      max_active, 4);
24572a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2458cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2459cb001095SJeff Mahoney 				      max_active, 2);
24602a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2461cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2462cb001095SJeff Mahoney 				      max_active, 4);
24632a458198SEric Sandeen 	fs_info->rmw_workers =
2464cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
24652a458198SEric Sandeen 	fs_info->endio_write_workers =
2466cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2467cb001095SJeff Mahoney 				      max_active, 2);
24682a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2469cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2470cb001095SJeff Mahoney 				      max_active, 0);
24712a458198SEric Sandeen 	fs_info->delayed_workers =
2472cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2473cb001095SJeff Mahoney 				      max_active, 0);
24742a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2475cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2476b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2477b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
24782a458198SEric Sandeen 
24792a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2480ba8a9d07SChris Mason 	      fs_info->flush_workers &&
24812a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
24822a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
24832a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
24842a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2485f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2486f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2487b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
24882a458198SEric Sandeen 		return -ENOMEM;
24892a458198SEric Sandeen 	}
24902a458198SEric Sandeen 
24912a458198SEric Sandeen 	return 0;
24922a458198SEric Sandeen }
24932a458198SEric Sandeen 
24946d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
24956d97c6e3SJohannes Thumshirn {
24966d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2497b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
24986d97c6e3SJohannes Thumshirn 
2499b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
25006d97c6e3SJohannes Thumshirn 
25016d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
25026d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2503b4e967beSDavid Sterba 			  csum_driver);
25046d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
25056d97c6e3SJohannes Thumshirn 	}
25066d97c6e3SJohannes Thumshirn 
25076d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
25086d97c6e3SJohannes Thumshirn 
25096d97c6e3SJohannes Thumshirn 	return 0;
25106d97c6e3SJohannes Thumshirn }
25116d97c6e3SJohannes Thumshirn 
251263443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
251363443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
251463443bf5SEric Sandeen {
251563443bf5SEric Sandeen 	int ret;
251663443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
251763443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
251863443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2519581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
252063443bf5SEric Sandeen 
252163443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2522f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
252363443bf5SEric Sandeen 		return -EIO;
252463443bf5SEric Sandeen 	}
252563443bf5SEric Sandeen 
252696dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
252796dfcb46SJosef Bacik 					 GFP_KERNEL);
252863443bf5SEric Sandeen 	if (!log_tree_root)
252963443bf5SEric Sandeen 		return -ENOMEM;
253063443bf5SEric Sandeen 
25312ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
25321b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
25331b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
25341b7ec85eSJosef Bacik 					      NULL);
253564c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2536f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
25370eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
25388c38938cSJosef Bacik 		log_tree_root->node = NULL;
253900246528SJosef Bacik 		btrfs_put_root(log_tree_root);
25400eeff236SLiu Bo 		return ret;
2541*4eb150d6SQu Wenruo 	}
2542*4eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2543f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
254400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
254563443bf5SEric Sandeen 		return -EIO;
254663443bf5SEric Sandeen 	}
2547*4eb150d6SQu Wenruo 
254863443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
254963443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
255063443bf5SEric Sandeen 	if (ret) {
25510b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
255263443bf5SEric Sandeen 				      "Failed to recover log tree");
255300246528SJosef Bacik 		btrfs_put_root(log_tree_root);
255463443bf5SEric Sandeen 		return ret;
255563443bf5SEric Sandeen 	}
255663443bf5SEric Sandeen 
2557bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
25586bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
255963443bf5SEric Sandeen 		if (ret)
256063443bf5SEric Sandeen 			return ret;
256163443bf5SEric Sandeen 	}
256263443bf5SEric Sandeen 
256363443bf5SEric Sandeen 	return 0;
256463443bf5SEric Sandeen }
256563443bf5SEric Sandeen 
2566abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2567abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2568abed4aaaSJosef Bacik 				      const char *name)
2569abed4aaaSJosef Bacik {
2570abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2571abed4aaaSJosef Bacik 	struct btrfs_root *root;
2572f7238e50SJosef Bacik 	u64 max_global_id = 0;
2573abed4aaaSJosef Bacik 	int ret;
2574abed4aaaSJosef Bacik 	struct btrfs_key key = {
2575abed4aaaSJosef Bacik 		.objectid = objectid,
2576abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2577abed4aaaSJosef Bacik 		.offset = 0,
2578abed4aaaSJosef Bacik 	};
2579abed4aaaSJosef Bacik 	bool found = false;
2580abed4aaaSJosef Bacik 
2581abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2582abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2583abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2584abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2585abed4aaaSJosef Bacik 		return 0;
2586abed4aaaSJosef Bacik 	}
2587abed4aaaSJosef Bacik 
2588abed4aaaSJosef Bacik 	while (1) {
2589abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2590abed4aaaSJosef Bacik 		if (ret < 0)
2591abed4aaaSJosef Bacik 			break;
2592abed4aaaSJosef Bacik 
2593abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2594abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2595abed4aaaSJosef Bacik 			if (ret) {
2596abed4aaaSJosef Bacik 				if (ret > 0)
2597abed4aaaSJosef Bacik 					ret = 0;
2598abed4aaaSJosef Bacik 				break;
2599abed4aaaSJosef Bacik 			}
2600abed4aaaSJosef Bacik 		}
2601abed4aaaSJosef Bacik 		ret = 0;
2602abed4aaaSJosef Bacik 
2603abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2604abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2605abed4aaaSJosef Bacik 			break;
2606abed4aaaSJosef Bacik 		btrfs_release_path(path);
2607abed4aaaSJosef Bacik 
2608f7238e50SJosef Bacik 		/*
2609f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2610f7238e50SJosef Bacik 		 * everybody.
2611f7238e50SJosef Bacik 		 */
2612f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2613f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2614f7238e50SJosef Bacik 
2615abed4aaaSJosef Bacik 		found = true;
2616abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2617abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2618abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2619abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2620abed4aaaSJosef Bacik 			break;
2621abed4aaaSJosef Bacik 		}
2622abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2623abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2624abed4aaaSJosef Bacik 		if (ret) {
2625abed4aaaSJosef Bacik 			btrfs_put_root(root);
2626abed4aaaSJosef Bacik 			break;
2627abed4aaaSJosef Bacik 		}
2628abed4aaaSJosef Bacik 		key.offset++;
2629abed4aaaSJosef Bacik 	}
2630abed4aaaSJosef Bacik 	btrfs_release_path(path);
2631abed4aaaSJosef Bacik 
2632f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2633f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2634f7238e50SJosef Bacik 
2635abed4aaaSJosef Bacik 	if (!found || ret) {
2636abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2637abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2638abed4aaaSJosef Bacik 
2639abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2640abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2641abed4aaaSJosef Bacik 		else
2642abed4aaaSJosef Bacik 			ret = 0;
2643abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2644abed4aaaSJosef Bacik 	}
2645abed4aaaSJosef Bacik 	return ret;
2646abed4aaaSJosef Bacik }
2647abed4aaaSJosef Bacik 
2648abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2649abed4aaaSJosef Bacik {
2650abed4aaaSJosef Bacik 	struct btrfs_path *path;
2651abed4aaaSJosef Bacik 	int ret = 0;
2652abed4aaaSJosef Bacik 
2653abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2654abed4aaaSJosef Bacik 	if (!path)
2655abed4aaaSJosef Bacik 		return -ENOMEM;
2656abed4aaaSJosef Bacik 
2657abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2658abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2659abed4aaaSJosef Bacik 	if (ret)
2660abed4aaaSJosef Bacik 		goto out;
2661abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2662abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2663abed4aaaSJosef Bacik 	if (ret)
2664abed4aaaSJosef Bacik 		goto out;
2665abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2666abed4aaaSJosef Bacik 		goto out;
2667abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2668abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2669abed4aaaSJosef Bacik 					 "free space");
2670abed4aaaSJosef Bacik out:
2671abed4aaaSJosef Bacik 	btrfs_free_path(path);
2672abed4aaaSJosef Bacik 	return ret;
2673abed4aaaSJosef Bacik }
2674abed4aaaSJosef Bacik 
26756bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
26764bbcaa64SEric Sandeen {
26776bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2678a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
26794bbcaa64SEric Sandeen 	struct btrfs_key location;
26804bbcaa64SEric Sandeen 	int ret;
26814bbcaa64SEric Sandeen 
26826bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
26836bccf3abSJeff Mahoney 
2684abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2685abed4aaaSJosef Bacik 	if (ret)
2686abed4aaaSJosef Bacik 		return ret;
2687abed4aaaSJosef Bacik 
2688abed4aaaSJosef Bacik 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
26894bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
26904bbcaa64SEric Sandeen 	location.offset = 0;
26914bbcaa64SEric Sandeen 
2692a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2693f50f4353SLiu Bo 	if (IS_ERR(root)) {
269442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2695f50f4353SLiu Bo 			ret = PTR_ERR(root);
2696f50f4353SLiu Bo 			goto out;
2697f50f4353SLiu Bo 		}
269842437a63SJosef Bacik 	} else {
2699a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2700a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
270142437a63SJosef Bacik 	}
2702820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2703820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
27044bbcaa64SEric Sandeen 
2705aeb935a4SQu Wenruo 	/*
2706aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2707aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2708aeb935a4SQu Wenruo 	 */
270956e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
271056e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2711aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
271242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2713aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2714aeb935a4SQu Wenruo 			goto out;
2715aeb935a4SQu Wenruo 		}
271642437a63SJosef Bacik 	} else {
2717aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2718aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
271942437a63SJosef Bacik 	}
2720aeb935a4SQu Wenruo 
27214bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2722a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2723a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2724a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2725afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2726a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
27274bbcaa64SEric Sandeen 	}
27284bbcaa64SEric Sandeen 
27294bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2730a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2731a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
273242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2733a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
27344bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2735f50f4353SLiu Bo 				goto out;
273642437a63SJosef Bacik 		}
27374bbcaa64SEric Sandeen 	} else {
2738a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2739a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
27404bbcaa64SEric Sandeen 	}
27414bbcaa64SEric Sandeen 
27424bbcaa64SEric Sandeen 	return 0;
2743f50f4353SLiu Bo out:
2744f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2745f50f4353SLiu Bo 		   location.objectid, ret);
2746f50f4353SLiu Bo 	return ret;
27474bbcaa64SEric Sandeen }
27484bbcaa64SEric Sandeen 
2749069ec957SQu Wenruo /*
2750069ec957SQu Wenruo  * Real super block validation
2751069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2752069ec957SQu Wenruo  *
2753069ec957SQu Wenruo  * @sb:		super block to check
2754069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2755069ec957SQu Wenruo  * 		0	the primary (1st) sb
2756069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2757069ec957SQu Wenruo  * 	       -1	skip bytenr check
2758069ec957SQu Wenruo  */
2759069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2760069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
276121a852b0SQu Wenruo {
276221a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
276321a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
276421a852b0SQu Wenruo 	int ret = 0;
276521a852b0SQu Wenruo 
276621a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
276721a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
276821a852b0SQu Wenruo 		ret = -EINVAL;
276921a852b0SQu Wenruo 	}
277021a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
277121a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
277221a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
277321a852b0SQu Wenruo 		ret = -EINVAL;
277421a852b0SQu Wenruo 	}
277521a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
277621a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
277721a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
277821a852b0SQu Wenruo 		ret = -EINVAL;
277921a852b0SQu Wenruo 	}
278021a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
278121a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
278221a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
278321a852b0SQu Wenruo 		ret = -EINVAL;
278421a852b0SQu Wenruo 	}
278521a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
278621a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
278721a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
278821a852b0SQu Wenruo 		ret = -EINVAL;
278921a852b0SQu Wenruo 	}
279021a852b0SQu Wenruo 
279121a852b0SQu Wenruo 	/*
279221a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
279321a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
279421a852b0SQu Wenruo 	 */
279521a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
279621a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
279721a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
279821a852b0SQu Wenruo 		ret = -EINVAL;
279921a852b0SQu Wenruo 	}
28000bb3eb3eSQu Wenruo 
28010bb3eb3eSQu Wenruo 	/*
28020bb3eb3eSQu Wenruo 	 * For 4K page size, we only support 4K sector size.
280350780d9bSAnand Jain 	 * For 64K page size, we support 64K and 4K sector sizes.
28040bb3eb3eSQu Wenruo 	 */
28050bb3eb3eSQu Wenruo 	if ((PAGE_SIZE == SZ_4K && sectorsize != PAGE_SIZE) ||
28060bb3eb3eSQu Wenruo 	    (PAGE_SIZE == SZ_64K && (sectorsize != SZ_4K &&
28070bb3eb3eSQu Wenruo 				     sectorsize != SZ_64K))) {
280821a852b0SQu Wenruo 		btrfs_err(fs_info,
28090bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
281021a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
281121a852b0SQu Wenruo 		ret = -EINVAL;
281221a852b0SQu Wenruo 	}
28130bb3eb3eSQu Wenruo 
281421a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
281521a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
281621a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
281721a852b0SQu Wenruo 		ret = -EINVAL;
281821a852b0SQu Wenruo 	}
281921a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
282021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
282121a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
282221a852b0SQu Wenruo 		ret = -EINVAL;
282321a852b0SQu Wenruo 	}
282421a852b0SQu Wenruo 
282521a852b0SQu Wenruo 	/* Root alignment check */
282621a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
282721a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
282821a852b0SQu Wenruo 			   btrfs_super_root(sb));
282921a852b0SQu Wenruo 		ret = -EINVAL;
283021a852b0SQu Wenruo 	}
283121a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
283221a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
283321a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
283421a852b0SQu Wenruo 		ret = -EINVAL;
283521a852b0SQu Wenruo 	}
283621a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
283721a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
283821a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
283921a852b0SQu Wenruo 		ret = -EINVAL;
284021a852b0SQu Wenruo 	}
284121a852b0SQu Wenruo 
2842aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2843aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2844aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2845aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2846aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2847aefd7f70SNikolay Borisov 		ret = -EINVAL;
2848aefd7f70SNikolay Borisov 	}
2849aefd7f70SNikolay Borisov 
2850aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2851aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2852aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2853aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2854aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2855aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2856aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2857aefd7f70SNikolay Borisov 		ret = -EINVAL;
2858aefd7f70SNikolay Borisov 	}
2859aefd7f70SNikolay Borisov 
2860de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
28617239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
286221a852b0SQu Wenruo 		btrfs_err(fs_info,
28637239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2864de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
286521a852b0SQu Wenruo 		ret = -EINVAL;
286621a852b0SQu Wenruo 	}
286721a852b0SQu Wenruo 
286821a852b0SQu Wenruo 	/*
286921a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
287021a852b0SQu Wenruo 	 * done later
287121a852b0SQu Wenruo 	 */
287221a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
287321a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
287421a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
287521a852b0SQu Wenruo 		ret = -EINVAL;
287621a852b0SQu Wenruo 	}
287721a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
287821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
287921a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
288021a852b0SQu Wenruo 		ret = -EINVAL;
288121a852b0SQu Wenruo 	}
288221a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
288321a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
288421a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
288521a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
288621a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
288721a852b0SQu Wenruo 		ret = -EINVAL;
288821a852b0SQu Wenruo 	}
288921a852b0SQu Wenruo 
2890069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2891069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
289221a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
289321a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
289421a852b0SQu Wenruo 		ret = -EINVAL;
289521a852b0SQu Wenruo 	}
289621a852b0SQu Wenruo 
289721a852b0SQu Wenruo 	/*
289821a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
289921a852b0SQu Wenruo 	 * and one chunk
290021a852b0SQu Wenruo 	 */
290121a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
290221a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
290321a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
290421a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
290521a852b0SQu Wenruo 		ret = -EINVAL;
290621a852b0SQu Wenruo 	}
290721a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
290821a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
290921a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
291021a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
291121a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
291221a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
291321a852b0SQu Wenruo 		ret = -EINVAL;
291421a852b0SQu Wenruo 	}
291521a852b0SQu Wenruo 
291621a852b0SQu Wenruo 	/*
291721a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
291821a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
291921a852b0SQu Wenruo 	 */
292021a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
292121a852b0SQu Wenruo 		btrfs_warn(fs_info,
292221a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
292321a852b0SQu Wenruo 			btrfs_super_generation(sb),
292421a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
292521a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
292621a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
292721a852b0SQu Wenruo 		btrfs_warn(fs_info,
292821a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
292921a852b0SQu Wenruo 			btrfs_super_generation(sb),
293021a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
293121a852b0SQu Wenruo 
293221a852b0SQu Wenruo 	return ret;
293321a852b0SQu Wenruo }
293421a852b0SQu Wenruo 
2935069ec957SQu Wenruo /*
2936069ec957SQu Wenruo  * Validation of super block at mount time.
2937069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2938069ec957SQu Wenruo  * flags will be skipped.
2939069ec957SQu Wenruo  */
2940069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2941069ec957SQu Wenruo {
2942069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2943069ec957SQu Wenruo }
2944069ec957SQu Wenruo 
294575cb857dSQu Wenruo /*
294675cb857dSQu Wenruo  * Validation of super block at write time.
294775cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
294875cb857dSQu Wenruo  * overwritten soon.
294975cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
295075cb857dSQu Wenruo  */
295175cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
295275cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
295375cb857dSQu Wenruo {
295475cb857dSQu Wenruo 	int ret;
295575cb857dSQu Wenruo 
295675cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
295775cb857dSQu Wenruo 	if (ret < 0)
295875cb857dSQu Wenruo 		goto out;
2959e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
296075cb857dSQu Wenruo 		ret = -EUCLEAN;
296175cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
296275cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
296375cb857dSQu Wenruo 		goto out;
296475cb857dSQu Wenruo 	}
296575cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
296675cb857dSQu Wenruo 		ret = -EUCLEAN;
296775cb857dSQu Wenruo 		btrfs_err(fs_info,
296875cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
296975cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
297075cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
297175cb857dSQu Wenruo 		goto out;
297275cb857dSQu Wenruo 	}
297375cb857dSQu Wenruo out:
297475cb857dSQu Wenruo 	if (ret < 0)
297575cb857dSQu Wenruo 		btrfs_err(fs_info,
297675cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
297775cb857dSQu Wenruo 	return ret;
297875cb857dSQu Wenruo }
297975cb857dSQu Wenruo 
2980bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2981bd676446SJosef Bacik {
2982bd676446SJosef Bacik 	int ret = 0;
2983bd676446SJosef Bacik 
2984bd676446SJosef Bacik 	root->node = read_tree_block(root->fs_info, bytenr,
2985bd676446SJosef Bacik 				     root->root_key.objectid, gen, level, NULL);
2986bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2987bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2988bd676446SJosef Bacik 		root->node = NULL;
2989*4eb150d6SQu Wenruo 		return ret;
2990*4eb150d6SQu Wenruo 	}
2991*4eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2992bd676446SJosef Bacik 		free_extent_buffer(root->node);
2993bd676446SJosef Bacik 		root->node = NULL;
2994*4eb150d6SQu Wenruo 		return -EIO;
2995bd676446SJosef Bacik 	}
2996bd676446SJosef Bacik 
2997bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2998bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2999bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
3000bd676446SJosef Bacik 	return ret;
3001bd676446SJosef Bacik }
3002bd676446SJosef Bacik 
3003bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
3004bd676446SJosef Bacik {
3005bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
3006bd676446SJosef Bacik 	u64 gen, bytenr;
3007bd676446SJosef Bacik 	int level, ret;
3008bd676446SJosef Bacik 
3009bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
3010bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
3011bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
3012bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
30139c54e80dSJosef Bacik 	if (ret) {
3014bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
3015bd676446SJosef Bacik 		return ret;
3016bd676446SJosef Bacik 	}
3017bd676446SJosef Bacik 
30189c54e80dSJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
30199c54e80dSJosef Bacik 		return 0;
30209c54e80dSJosef Bacik 
30219c54e80dSJosef Bacik 	bytenr = btrfs_super_block_group_root(sb);
30229c54e80dSJosef Bacik 	gen = btrfs_super_block_group_root_generation(sb);
30239c54e80dSJosef Bacik 	level = btrfs_super_block_group_root_level(sb);
30249c54e80dSJosef Bacik 	ret = load_super_root(fs_info->block_group_root, bytenr, gen, level);
30259c54e80dSJosef Bacik 	if (ret)
30269c54e80dSJosef Bacik 		btrfs_warn(fs_info, "couldn't read block group root");
30279c54e80dSJosef Bacik 	return ret;
30289c54e80dSJosef Bacik }
30299c54e80dSJosef Bacik 
30306ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
3031b8522a1eSNikolay Borisov {
30326ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
3033b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
3034b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
3035b8522a1eSNikolay Borisov 	bool handle_error = false;
3036b8522a1eSNikolay Borisov 	int ret = 0;
3037b8522a1eSNikolay Borisov 	int i;
3038b8522a1eSNikolay Borisov 
30399c54e80dSJosef Bacik 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
30409c54e80dSJosef Bacik 		struct btrfs_root *root;
30419c54e80dSJosef Bacik 
30429c54e80dSJosef Bacik 		root = btrfs_alloc_root(fs_info, BTRFS_BLOCK_GROUP_TREE_OBJECTID,
30439c54e80dSJosef Bacik 					GFP_KERNEL);
30449c54e80dSJosef Bacik 		if (!root)
30459c54e80dSJosef Bacik 			return -ENOMEM;
30469c54e80dSJosef Bacik 		fs_info->block_group_root = root;
30479c54e80dSJosef Bacik 	}
30489c54e80dSJosef Bacik 
3049b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
3050b8522a1eSNikolay Borisov 		if (handle_error) {
3051b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
3052b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
3053b8522a1eSNikolay Borisov 			tree_root->node = NULL;
3054b8522a1eSNikolay Borisov 
3055b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3056b8522a1eSNikolay Borisov 				break;
3057b8522a1eSNikolay Borisov 
3058b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
3059b8522a1eSNikolay Borisov 
3060b8522a1eSNikolay Borisov 			/*
3061b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
3062b8522a1eSNikolay Borisov 			 * valid
3063b8522a1eSNikolay Borisov 			 */
3064b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
3065b8522a1eSNikolay Borisov 
3066b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
3067b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3068b8522a1eSNikolay Borisov 
3069b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
30706ef108ddSNikolay Borisov 			backup_index = ret;
3071b8522a1eSNikolay Borisov 			if (ret < 0)
3072b8522a1eSNikolay Borisov 				return ret;
3073b8522a1eSNikolay Borisov 		}
3074b8522a1eSNikolay Borisov 
3075bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
3076bd676446SJosef Bacik 		if (ret) {
3077217f5004SNikolay Borisov 			handle_error = true;
3078b8522a1eSNikolay Borisov 			continue;
3079b8522a1eSNikolay Borisov 		}
3080b8522a1eSNikolay Borisov 
3081336a0d8dSNikolay Borisov 		/*
3082336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
3083336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
3084336a0d8dSNikolay Borisov 		 */
3085453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
3086b8522a1eSNikolay Borisov 		if (ret < 0) {
3087b8522a1eSNikolay Borisov 			handle_error = true;
3088b8522a1eSNikolay Borisov 			continue;
3089b8522a1eSNikolay Borisov 		}
3090b8522a1eSNikolay Borisov 
30916b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
3092b8522a1eSNikolay Borisov 
3093b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
3094b8522a1eSNikolay Borisov 		if (ret < 0) {
3095b8522a1eSNikolay Borisov 			handle_error = true;
3096b8522a1eSNikolay Borisov 			continue;
3097b8522a1eSNikolay Borisov 		}
3098b8522a1eSNikolay Borisov 
3099b8522a1eSNikolay Borisov 		/* All successful */
3100bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
3101bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
3102d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
31036ef108ddSNikolay Borisov 
31046ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
31056ef108ddSNikolay Borisov 		if (backup_index < 0) {
31066ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
31076ef108ddSNikolay Borisov 		} else {
31086ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
31096ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
31106ef108ddSNikolay Borisov 		}
3111b8522a1eSNikolay Borisov 		break;
3112b8522a1eSNikolay Borisov 	}
3113b8522a1eSNikolay Borisov 
3114b8522a1eSNikolay Borisov 	return ret;
3115b8522a1eSNikolay Borisov }
3116b8522a1eSNikolay Borisov 
31178260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
3118eb60ceacSChris Mason {
311976dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
3120f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
31218fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
3122facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
312324bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
3124eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
312511833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
3126eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
3127a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
312876dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
312924bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
31304cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
3131ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
3132f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
313347ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
313440ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
3135afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
3136c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
3137f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
3138abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
3139d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
3140f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
31417585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
3142573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
31430bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
3144de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
314519c00ddcSChris Mason 
31460b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
31476324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
3148f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
314947ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
315018bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
3151afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
3152bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
3153bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
31543fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
31553fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
3156bd647ce3SJosef Bacik #endif
3157c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
315866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
315966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
316066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
316166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
316266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
316366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
316466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
3165ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
3166ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
3167ba2c4d4eSJosef Bacik 
3168771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
31694cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
3170034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
3171fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
3172abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
317395ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
31749ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
31754cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
3176a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
3177f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
31788b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
3179f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
3180fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
3181c8b97818SChris Mason 
3182b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
3183b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
31840afbaf8cSChris Mason 
3185199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
3186199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
318769fe2d75SJosef Bacik 
3188638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
318921adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
319021adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
319121adbd5cSStefan Behrens #endif
3192779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
319357056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
3194a2de733cSArne Jansen 
31950f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
31966bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
3197a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
31980f9dd46cSJosef Bacik 
3199fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
3200fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
320139279cc3SChris Mason 
32025a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
3203e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
3204925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
3205a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
3206a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
32071bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
32089e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
3209c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
321076dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
3211803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
3212fa9c0d79SChris Mason 
3213ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
3214f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
3215b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
3216416ac51dSArne Jansen 
3217fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3218fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3219fa9c0d79SChris Mason 
3220e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
3221f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
3222bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
32234854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
3224034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
32253768f368SChris Mason 
3226da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
3227da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
3228da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
3229ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
3230da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
3231da17066cSJeff Mahoney 
3232eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
3233eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
3234eede2bf3SOmar Sandoval 
323518bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
323618bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
32378260edbaSJosef Bacik }
32388260edbaSJosef Bacik 
32398260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
32408260edbaSJosef Bacik {
32418260edbaSJosef Bacik 	int ret;
32428260edbaSJosef Bacik 
32438260edbaSJosef Bacik 	fs_info->sb = sb;
32448260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
32458260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
32469e967495SFilipe Manana 
32475deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3248ae18c37aSJosef Bacik 	if (ret)
3249ae18c37aSJosef Bacik 		return ret;
3250ae18c37aSJosef Bacik 
3251ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3252ae18c37aSJosef Bacik 	if (ret)
3253c75e8394SJosef Bacik 		return ret;
3254ae18c37aSJosef Bacik 
3255ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3256ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3257ae18c37aSJosef Bacik 
3258ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3259ae18c37aSJosef Bacik 	if (ret)
3260c75e8394SJosef Bacik 		return ret;
3261ae18c37aSJosef Bacik 
3262ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3263ae18c37aSJosef Bacik 			GFP_KERNEL);
3264ae18c37aSJosef Bacik 	if (ret)
3265c75e8394SJosef Bacik 		return ret;
3266ae18c37aSJosef Bacik 
3267ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3268ae18c37aSJosef Bacik 					GFP_KERNEL);
3269c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3270c75e8394SJosef Bacik 		return -ENOMEM;
3271ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3272ae18c37aSJosef Bacik 
3273a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3274a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3275a0a1db70SFilipe Manana 
3276c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3277ae18c37aSJosef Bacik }
3278ae18c37aSJosef Bacik 
327997f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
328097f4dd09SNikolay Borisov {
328197f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
328297f4dd09SNikolay Borisov 	int ret;
328397f4dd09SNikolay Borisov 
328497f4dd09SNikolay Borisov 	/*
328597f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
328697f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
328797f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
328897f4dd09SNikolay Borisov 	 */
328997f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
329097f4dd09SNikolay Borisov 	if (ret < 0) {
3291c94bec2cSJosef Bacik 		if (ret != -EINTR)
3292c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3293c94bec2cSJosef Bacik 				   ret);
329497f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
329597f4dd09SNikolay Borisov 		return ret;
329697f4dd09SNikolay Borisov 	}
329797f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
329897f4dd09SNikolay Borisov }
329997f4dd09SNikolay Borisov 
330097f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
330197f4dd09SNikolay Borisov {
330297f4dd09SNikolay Borisov 	struct task_struct *task;
330397f4dd09SNikolay Borisov 
330497f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
330597f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
330697f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
330797f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
330897f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
330997f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
331097f4dd09SNikolay Borisov 		return PTR_ERR(task);
331197f4dd09SNikolay Borisov 	}
331297f4dd09SNikolay Borisov 
331397f4dd09SNikolay Borisov 	return 0;
331497f4dd09SNikolay Borisov }
331597f4dd09SNikolay Borisov 
331644c0ca21SBoris Burkov /*
33178cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
33188cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
33198cd29088SBoris Burkov  * code paths.
33208cd29088SBoris Burkov  */
33218cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
33228cd29088SBoris Burkov {
33238cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
33248b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
33258cd29088SBoris Burkov }
33268cd29088SBoris Burkov 
33278cd29088SBoris Burkov /*
332844c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
332944c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
333044c0ca21SBoris Burkov  */
333144c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
333244c0ca21SBoris Burkov {
333344c0ca21SBoris Burkov 	int ret;
333494846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
33358b228324SBoris Burkov 	bool clear_free_space_tree = false;
33368b228324SBoris Burkov 
33378b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
33388b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
33398b228324SBoris Burkov 		clear_free_space_tree = true;
33408b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
33418b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
33428b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
33438b228324SBoris Burkov 		clear_free_space_tree = true;
33448b228324SBoris Burkov 	}
33458b228324SBoris Burkov 
33468b228324SBoris Burkov 	if (clear_free_space_tree) {
33478b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
33488b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
33498b228324SBoris Burkov 		if (ret) {
33508b228324SBoris Burkov 			btrfs_warn(fs_info,
33518b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
33528b228324SBoris Burkov 			goto out;
33538b228324SBoris Burkov 		}
33548b228324SBoris Burkov 	}
335544c0ca21SBoris Burkov 
33568d488a8cSFilipe Manana 	/*
33578d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
33588d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
33598d488a8cSFilipe Manana 	 * them into the fs_info->fs_roots_radix tree. This must be done before
33608d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
33618d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
33628d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
33638d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
33648d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
33658d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
33668d488a8cSFilipe Manana 	 */
33678d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
33688d488a8cSFilipe Manana 	if (ret)
33698d488a8cSFilipe Manana 		goto out;
33708d488a8cSFilipe Manana 
337144c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
337244c0ca21SBoris Burkov 	if (ret)
337344c0ca21SBoris Burkov 		goto out;
337444c0ca21SBoris Burkov 
33758f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
33768f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
33778f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
33788f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
33798f1c21d7SBoris Burkov 		goto out;
33808f1c21d7SBoris Burkov 	}
33818f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
33828f1c21d7SBoris Burkov 
338344c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
33847eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
338544c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
338644c0ca21SBoris Burkov 	if (ret < 0) {
338744c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
338844c0ca21SBoris Burkov 		goto out;
338944c0ca21SBoris Burkov 	}
339044c0ca21SBoris Burkov 
33915011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
33925011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
33935011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
33945011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
33955011139aSBoris Burkov 		if (ret) {
33965011139aSBoris Burkov 			btrfs_warn(fs_info,
33975011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
33985011139aSBoris Burkov 			goto out;
33995011139aSBoris Burkov 		}
34005011139aSBoris Burkov 	}
34015011139aSBoris Burkov 
340294846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
340394846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
340494846229SBoris Burkov 		if (ret)
340594846229SBoris Burkov 			goto out;
340694846229SBoris Burkov 	}
340794846229SBoris Burkov 
340844c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
340944c0ca21SBoris Burkov 	if (ret)
341044c0ca21SBoris Burkov 		goto out;
341144c0ca21SBoris Burkov 
341244c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
341344c0ca21SBoris Burkov 	if (ret) {
341444c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
341544c0ca21SBoris Burkov 		goto out;
341644c0ca21SBoris Burkov 	}
341744c0ca21SBoris Burkov 
341844c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
341944c0ca21SBoris Burkov 
342044c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
342144c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
342244c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
342344c0ca21SBoris Burkov 		if (ret) {
342444c0ca21SBoris Burkov 			btrfs_warn(fs_info,
342544c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
342644c0ca21SBoris Burkov 			goto out;
342744c0ca21SBoris Burkov 		}
342844c0ca21SBoris Burkov 	}
342944c0ca21SBoris Burkov 
343044c0ca21SBoris Burkov out:
343144c0ca21SBoris Burkov 	return ret;
343244c0ca21SBoris Burkov }
343344c0ca21SBoris Burkov 
3434ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3435ae18c37aSJosef Bacik 		      char *options)
3436ae18c37aSJosef Bacik {
3437ae18c37aSJosef Bacik 	u32 sectorsize;
3438ae18c37aSJosef Bacik 	u32 nodesize;
3439ae18c37aSJosef Bacik 	u32 stripesize;
3440ae18c37aSJosef Bacik 	u64 generation;
3441ae18c37aSJosef Bacik 	u64 features;
3442ae18c37aSJosef Bacik 	u16 csum_type;
3443ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3444ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3445ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3446ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3447ae18c37aSJosef Bacik 	int ret;
3448ae18c37aSJosef Bacik 	int err = -EINVAL;
3449ae18c37aSJosef Bacik 	int level;
3450ae18c37aSJosef Bacik 
34518260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
345253b381b3SDavid Woodhouse 	if (ret) {
345383c8266aSDavid Sterba 		err = ret;
3454ae18c37aSJosef Bacik 		goto fail;
345553b381b3SDavid Woodhouse 	}
345653b381b3SDavid Woodhouse 
3457ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3458ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3459ae18c37aSJosef Bacik 				     GFP_KERNEL);
3460ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3461ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3462ae18c37aSJosef Bacik 				      GFP_KERNEL);
3463ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3464ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3465ae18c37aSJosef Bacik 		err = -ENOMEM;
3466c75e8394SJosef Bacik 		goto fail;
3467ae18c37aSJosef Bacik 	}
3468ae18c37aSJosef Bacik 
3469ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3470ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3471ae18c37aSJosef Bacik 		err = -ENOMEM;
3472c75e8394SJosef Bacik 		goto fail;
3473ae18c37aSJosef Bacik 	}
3474ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3475ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3476ae18c37aSJosef Bacik 
3477d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
34781104a885SDavid Sterba 
34791104a885SDavid Sterba 	/*
34801104a885SDavid Sterba 	 * Read super block and check the signature bytes only
34811104a885SDavid Sterba 	 */
3482d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
34838f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
34848f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
348516cdcec7SMiao Xie 		goto fail_alloc;
348620b45077SDave Young 	}
348739279cc3SChris Mason 
34881104a885SDavid Sterba 	/*
3489260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
34908dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
34918dc3f22cSJohannes Thumshirn 	 */
34928f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
349351bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
34948dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
349551bce6c9SJohannes Thumshirn 			  csum_type);
34968dc3f22cSJohannes Thumshirn 		err = -EINVAL;
34978f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
34988dc3f22cSJohannes Thumshirn 		goto fail_alloc;
34998dc3f22cSJohannes Thumshirn 	}
35008dc3f22cSJohannes Thumshirn 
350183c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
350283c68bbcSSu Yue 
35036d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
35046d97c6e3SJohannes Thumshirn 	if (ret) {
35056d97c6e3SJohannes Thumshirn 		err = ret;
35068f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
35076d97c6e3SJohannes Thumshirn 		goto fail_alloc;
35086d97c6e3SJohannes Thumshirn 	}
35096d97c6e3SJohannes Thumshirn 
35108dc3f22cSJohannes Thumshirn 	/*
35111104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
35121104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
35131104a885SDavid Sterba 	 */
35148f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
351505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
35161104a885SDavid Sterba 		err = -EINVAL;
35178f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3518141386e1SJosef Bacik 		goto fail_alloc;
35191104a885SDavid Sterba 	}
35201104a885SDavid Sterba 
35211104a885SDavid Sterba 	/*
35221104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
35231104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
35241104a885SDavid Sterba 	 * the whole block of INFO_SIZE
35251104a885SDavid Sterba 	 */
35268f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
35278f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
35285f39d397SChris Mason 
3529fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3530fbc6feaeSNikolay Borisov 
35310b86a832SChris Mason 
3532fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3533fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3534fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3535fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3536fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3537fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3538fbc6feaeSNikolay Borisov 	}
3539fbc6feaeSNikolay Borisov 
3540fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3541fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3542de37aa51SNikolay Borisov 
3543069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
35441104a885SDavid Sterba 	if (ret) {
354505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
35461104a885SDavid Sterba 		err = -EINVAL;
3547141386e1SJosef Bacik 		goto fail_alloc;
35481104a885SDavid Sterba 	}
35491104a885SDavid Sterba 
35500f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3551141386e1SJosef Bacik 		goto fail_alloc;
35520f7d52f4SChris Mason 
3553acce952bSliubo 	/* check FS state, whether FS is broken. */
355487533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
355587533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3556acce952bSliubo 
355775e7cb7fSLiu Bo 	/*
355875e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
355975e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
356075e7cb7fSLiu Bo 	 */
356175e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
356275e7cb7fSLiu Bo 
35636f93e834SAnand Jain 	/*
35646f93e834SAnand Jain 	 * Flag our filesystem as having big metadata blocks if they are bigger
35656f93e834SAnand Jain 	 * than the page size.
35666f93e834SAnand Jain 	 */
35676f93e834SAnand Jain 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
35686f93e834SAnand Jain 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
35696f93e834SAnand Jain 			btrfs_info(fs_info,
35706f93e834SAnand Jain 				"flagging fs with big metadata feature");
35716f93e834SAnand Jain 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
35726f93e834SAnand Jain 	}
35736f93e834SAnand Jain 
35746f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
35756f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
35766f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
35776f93e834SAnand Jain 	stripesize = sectorsize;
35786f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
35796f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
35806f93e834SAnand Jain 
35816f93e834SAnand Jain 	fs_info->nodesize = nodesize;
35826f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
35836f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
35846f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
35856f93e834SAnand Jain 	fs_info->stripesize = stripesize;
35866f93e834SAnand Jain 
35872ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
35882b82032cSYan Zheng 	if (ret) {
35892b82032cSYan Zheng 		err = ret;
3590141386e1SJosef Bacik 		goto fail_alloc;
35912b82032cSYan Zheng 	}
3592dfe25020SChris Mason 
3593f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3594f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3595f2b636e8SJosef Bacik 	if (features) {
359605135f59SDavid Sterba 		btrfs_err(fs_info,
359705135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3598c1c9ff7cSGeert Uytterhoeven 		    features);
3599f2b636e8SJosef Bacik 		err = -EINVAL;
3600141386e1SJosef Bacik 		goto fail_alloc;
3601f2b636e8SJosef Bacik 	}
3602f2b636e8SJosef Bacik 
36035d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
36045d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
36050b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3606a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
36075c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
36085c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3609727011e0SChris Mason 
36103173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
361105135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
36123173a18fSJosef Bacik 
3613727011e0SChris Mason 	/*
3614bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3615bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3616bc3f116fSChris Mason 	 */
3617bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3618707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
361905135f59SDavid Sterba 		btrfs_err(fs_info,
362005135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
362105135f59SDavid Sterba 			nodesize, sectorsize);
3622141386e1SJosef Bacik 		goto fail_alloc;
3623bc3f116fSChris Mason 	}
3624bc3f116fSChris Mason 
3625ceda0864SMiao Xie 	/*
3626ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3627ceda0864SMiao Xie 	 * update the flag.
3628ceda0864SMiao Xie 	 */
36295d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
36305d4f98a2SYan Zheng 
3631f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3632f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3633bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
363405135f59SDavid Sterba 		btrfs_err(fs_info,
363505135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3636c1c9ff7cSGeert Uytterhoeven 		       features);
3637f2b636e8SJosef Bacik 		err = -EINVAL;
3638141386e1SJosef Bacik 		goto fail_alloc;
3639f2b636e8SJosef Bacik 	}
364061d92c32SChris Mason 
36418481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
36428481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
36438481dd80SQu Wenruo 
364495ea0486SQu Wenruo 		btrfs_warn(fs_info,
364595ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
36460bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
3647c8050b3bSQu Wenruo 		if (btrfs_super_incompat_flags(fs_info->super_copy) &
3648c8050b3bSQu Wenruo 			BTRFS_FEATURE_INCOMPAT_RAID56) {
3649c8050b3bSQu Wenruo 			btrfs_err(fs_info,
3650c8050b3bSQu Wenruo 		"RAID56 is not yet supported for sector size %u with page size %lu",
3651c8050b3bSQu Wenruo 				sectorsize, PAGE_SIZE);
3652c8050b3bSQu Wenruo 			err = -EINVAL;
3653c8050b3bSQu Wenruo 			goto fail_alloc;
3654c8050b3bSQu Wenruo 		}
36558481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
36568481dd80SQu Wenruo 		if (!subpage_info)
36578481dd80SQu Wenruo 			goto fail_alloc;
36588481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
36598481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3660c8050b3bSQu Wenruo 	}
36610bb3eb3eSQu Wenruo 
3662d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
36632a458198SEric Sandeen 	if (ret) {
36642a458198SEric Sandeen 		err = ret;
36650dc3b84aSJosef Bacik 		goto fail_sb_buffer;
36660dc3b84aSJosef Bacik 	}
36674543df7eSChris Mason 
36689e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
36699e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
36704575c9ccSChris Mason 
3671a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3672a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3673de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3674db94535dSChris Mason 
3675925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
36766bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3677925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
367884eed90fSChris Mason 	if (ret) {
367905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
36805d4f98a2SYan Zheng 		goto fail_sb_buffer;
368184eed90fSChris Mason 	}
36820b86a832SChris Mason 
368384234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3684581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3685bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3686bd676446SJosef Bacik 			      generation, level);
3687bd676446SJosef Bacik 	if (ret) {
368805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3689af31f5e5SChris Mason 		goto fail_tree_roots;
369083121942SDavid Woodhouse 	}
36910b86a832SChris Mason 
3692e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3693c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3694c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3695e17cade2SChris Mason 
36965b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
36972b82032cSYan Zheng 	if (ret) {
369805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3699af31f5e5SChris Mason 		goto fail_tree_roots;
37002b82032cSYan Zheng 	}
37010b86a832SChris Mason 
37028dabb742SStefan Behrens 	/*
3703bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3704bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3705bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
37061a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3707bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
37088dabb742SStefan Behrens 	 */
3709bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3710d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
371105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3712a6b0d5c8SChris Mason 		goto fail_tree_roots;
3713a6b0d5c8SChris Mason 	}
3714a6b0d5c8SChris Mason 
3715b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
37164bbcaa64SEric Sandeen 	if (ret)
3717b8522a1eSNikolay Borisov 		goto fail_tree_roots;
37188929ecfaSYan, Zheng 
371975ec1db8SJosef Bacik 	/*
372073651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
372173651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
372273651042SNaohiro Aota 	 * zoned incompat feature flag set.
372373651042SNaohiro Aota 	 */
372473651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
372573651042SNaohiro Aota 	if (ret) {
372673651042SNaohiro Aota 		btrfs_err(fs_info,
372773651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
372873651042SNaohiro Aota 			  ret);
372973651042SNaohiro Aota 		goto fail_block_groups;
373073651042SNaohiro Aota 	}
373173651042SNaohiro Aota 
373273651042SNaohiro Aota 	/*
373375ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
373475ec1db8SJosef Bacik 	 * check the generation here so we can set the
373575ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
373675ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
373775ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
373875ec1db8SJosef Bacik 	 * even though it was perfectly fine.
373975ec1db8SJosef Bacik 	 */
374075ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
374175ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
374275ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
374375ec1db8SJosef Bacik 
3744cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3745cf90d884SQu Wenruo 	if (ret) {
3746cf90d884SQu Wenruo 		btrfs_err(fs_info,
3747cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3748cf90d884SQu Wenruo 			  ret);
3749cf90d884SQu Wenruo 		goto fail_block_groups;
3750cf90d884SQu Wenruo 	}
375168310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
375268310a5eSIlya Dryomov 	if (ret) {
375305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
375468310a5eSIlya Dryomov 		goto fail_block_groups;
375568310a5eSIlya Dryomov 	}
375668310a5eSIlya Dryomov 
3757733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3758733f4fbbSStefan Behrens 	if (ret) {
375905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3760733f4fbbSStefan Behrens 		goto fail_block_groups;
3761733f4fbbSStefan Behrens 	}
3762733f4fbbSStefan Behrens 
37638dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
37648dabb742SStefan Behrens 	if (ret) {
376505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
37668dabb742SStefan Behrens 		goto fail_block_groups;
37678dabb742SStefan Behrens 	}
37688dabb742SStefan Behrens 
3769b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3770b70f5097SNaohiro Aota 	if (ret) {
3771b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3772b70f5097SNaohiro Aota 			  ret);
3773b70f5097SNaohiro Aota 		goto fail_block_groups;
3774b70f5097SNaohiro Aota 	}
3775b70f5097SNaohiro Aota 
3776c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3777b7c35e81SAnand Jain 	if (ret) {
377805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
377905135f59SDavid Sterba 				ret);
3780b7c35e81SAnand Jain 		goto fail_block_groups;
3781b7c35e81SAnand Jain 	}
3782b7c35e81SAnand Jain 
378396f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
37845ac1d209SJeff Mahoney 	if (ret) {
378505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3786b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
37875ac1d209SJeff Mahoney 	}
37885ac1d209SJeff Mahoney 
3789c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3790c59021f8Sliubo 	if (ret) {
379105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
37922365dd3cSAnand Jain 		goto fail_sysfs;
3793c59021f8Sliubo 	}
3794c59021f8Sliubo 
37955b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
37961b1d1f66SJosef Bacik 	if (ret) {
379705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
37982365dd3cSAnand Jain 		goto fail_sysfs;
37991b1d1f66SJosef Bacik 	}
38004330e183SQu Wenruo 
380116beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
380216beac87SNaohiro Aota 
38035c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
38045c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
380505135f59SDavid Sterba 		btrfs_warn(fs_info,
380652042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
38072365dd3cSAnand Jain 		goto fail_sysfs;
3808292fd7fcSStefan Behrens 	}
38099078a3e1SChris Mason 
381033c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3811a74a4b97SChris Mason 					       "btrfs-cleaner");
381257506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
38132365dd3cSAnand Jain 		goto fail_sysfs;
3814a74a4b97SChris Mason 
3815a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3816a74a4b97SChris Mason 						   tree_root,
3817a74a4b97SChris Mason 						   "btrfs-transaction");
381857506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
38193f157a2fSChris Mason 		goto fail_cleaner;
3820a74a4b97SChris Mason 
3821583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3822c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3823583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3824c289811cSChris Mason 	}
3825c289811cSChris Mason 
3826572d9ab7SDavid Sterba 	/*
382701327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3828572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3829572d9ab7SDavid Sterba 	 */
3830572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
38313818aea2SQu Wenruo 
383221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
38330b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
38342ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
38350b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3836cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
383721adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
383821adbd5cSStefan Behrens 		if (ret)
383905135f59SDavid Sterba 			btrfs_warn(fs_info,
384005135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
384105135f59SDavid Sterba 				ret);
384221adbd5cSStefan Behrens 	}
384321adbd5cSStefan Behrens #endif
3844bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3845bcef60f2SArne Jansen 	if (ret)
3846bcef60f2SArne Jansen 		goto fail_trans_kthread;
384721adbd5cSStefan Behrens 
3848fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3849fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3850fd708b81SJosef Bacik 
385196da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
385296da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
38530b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3854e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
385563443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
385679787eaaSJeff Mahoney 		if (ret) {
385763443bf5SEric Sandeen 			err = ret;
385828c16cbbSWang Shilong 			goto fail_qgroup;
3859e556ce2cSYan Zheng 		}
3860e02119d5SChris Mason 	}
38611a40e23bSZheng Yan 
386256e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
38633140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
38643140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3865f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3866315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3867bcef60f2SArne Jansen 		goto fail_qgroup;
38683140c9a3SDan Carpenter 	}
3869c289811cSChris Mason 
3870bc98a42cSDavid Howells 	if (sb_rdonly(sb))
38718cd29088SBoris Burkov 		goto clear_oneshot;
38722b6ba629SIlya Dryomov 
387344c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
38742b6ba629SIlya Dryomov 	if (ret) {
38756bccf3abSJeff Mahoney 		close_ctree(fs_info);
38762b6ba629SIlya Dryomov 		return ret;
3877e3acc2a6SJosef Bacik 	}
3878b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3879b382a324SJan Schmidt 
388044c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
388144c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
388244c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
388305135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
388470f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
388570f80175SStefan Behrens 		if (ret) {
388605135f59SDavid Sterba 			btrfs_warn(fs_info,
388705135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
38886bccf3abSJeff Mahoney 			close_ctree(fs_info);
388970f80175SStefan Behrens 			return ret;
389070f80175SStefan Behrens 		}
3891f7a81ea4SStefan Behrens 	}
389294846229SBoris Burkov 
3893afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
389447ab2a6cSJosef Bacik 
3895b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3896b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3897b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3898b4be6aefSJosef Bacik 
38998cd29088SBoris Burkov clear_oneshot:
39008cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3901ad2b2c80SAl Viro 	return 0;
390239279cc3SChris Mason 
3903bcef60f2SArne Jansen fail_qgroup:
3904bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
39057c2ca468SChris Mason fail_trans_kthread:
39067c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
39072ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3908faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
39093f157a2fSChris Mason fail_cleaner:
3910a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
39117c2ca468SChris Mason 
39127c2ca468SChris Mason 	/*
39137c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
39147c2ca468SChris Mason 	 * kthreads
39157c2ca468SChris Mason 	 */
39167c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
39177c2ca468SChris Mason 
39182365dd3cSAnand Jain fail_sysfs:
39196618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
39202365dd3cSAnand Jain 
3921b7c35e81SAnand Jain fail_fsdev_sysfs:
3922b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3923b7c35e81SAnand Jain 
39241b1d1f66SJosef Bacik fail_block_groups:
392554067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3926af31f5e5SChris Mason 
3927af31f5e5SChris Mason fail_tree_roots:
39289e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
39299e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
39304273eaffSAnand Jain 	free_root_pointers(fs_info, true);
39312b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3932af31f5e5SChris Mason 
393339279cc3SChris Mason fail_sb_buffer:
39347abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
39355cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
393616cdcec7SMiao Xie fail_alloc:
3937586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3938586e46e2SIlya Dryomov 
39394543df7eSChris Mason 	iput(fs_info->btree_inode);
39407e662854SQinghuang Feng fail:
3941586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3942ad2b2c80SAl Viro 	return err;
3943eb60ceacSChris Mason }
3944663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3945eb60ceacSChris Mason 
3946314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3947f2984462SChris Mason {
3948314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3949314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3950314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3951314b6dd0SJohannes Thumshirn 	struct page *page;
3952442a4f63SStefan Behrens 
3953314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3954314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3955314b6dd0SJohannes Thumshirn 
3956314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3957fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3958314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3959314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3960314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3961314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3962314b6dd0SJohannes Thumshirn 			SetPageError(page);
3963314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3964314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3965314b6dd0SJohannes Thumshirn 		} else {
3966314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3967f2984462SChris Mason 		}
3968314b6dd0SJohannes Thumshirn 
3969314b6dd0SJohannes Thumshirn 		put_page(page);
3970314b6dd0SJohannes Thumshirn 		unlock_page(page);
3971314b6dd0SJohannes Thumshirn 	}
3972314b6dd0SJohannes Thumshirn 
3973314b6dd0SJohannes Thumshirn 	bio_put(bio);
3974f2984462SChris Mason }
3975f2984462SChris Mason 
39768f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
39778f32380dSJohannes Thumshirn 						   int copy_num)
397829c36d72SAnand Jain {
397929c36d72SAnand Jain 	struct btrfs_super_block *super;
39808f32380dSJohannes Thumshirn 	struct page *page;
398112659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
39828f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
398312659251SNaohiro Aota 	int ret;
398429c36d72SAnand Jain 
398512659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
398612659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
398712659251SNaohiro Aota 	if (ret == -ENOENT)
398812659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
398912659251SNaohiro Aota 	else if (ret)
399012659251SNaohiro Aota 		return ERR_PTR(ret);
399112659251SNaohiro Aota 
3992cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
39938f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
399429c36d72SAnand Jain 
39958f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
39968f32380dSJohannes Thumshirn 	if (IS_ERR(page))
39978f32380dSJohannes Thumshirn 		return ERR_CAST(page);
399829c36d72SAnand Jain 
39998f32380dSJohannes Thumshirn 	super = page_address(page);
400096c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
400196c2e067SAnand Jain 		btrfs_release_disk_super(super);
400296c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
400396c2e067SAnand Jain 	}
400496c2e067SAnand Jain 
400512659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
40068f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
40078f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
400829c36d72SAnand Jain 	}
400929c36d72SAnand Jain 
40108f32380dSJohannes Thumshirn 	return super;
401129c36d72SAnand Jain }
401229c36d72SAnand Jain 
401329c36d72SAnand Jain 
40148f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
4015a512bbf8SYan Zheng {
40168f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
4017a512bbf8SYan Zheng 	int i;
4018a512bbf8SYan Zheng 	u64 transid = 0;
4019a512bbf8SYan Zheng 
4020a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
4021a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
4022a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
4023a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
4024a512bbf8SYan Zheng 	 */
4025a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
40268f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
40278f32380dSJohannes Thumshirn 		if (IS_ERR(super))
4028a512bbf8SYan Zheng 			continue;
4029a512bbf8SYan Zheng 
4030a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
40318f32380dSJohannes Thumshirn 			if (latest)
40328f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
40338f32380dSJohannes Thumshirn 
40348f32380dSJohannes Thumshirn 			latest = super;
4035a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
4036a512bbf8SYan Zheng 		}
4037a512bbf8SYan Zheng 	}
403892fc03fbSAnand Jain 
40398f32380dSJohannes Thumshirn 	return super;
4040a512bbf8SYan Zheng }
4041a512bbf8SYan Zheng 
40424eedeb75SHisashi Hifumi /*
4043abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
4044314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
40454eedeb75SHisashi Hifumi  *
4046abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
4047abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
4048abbb3b8eSDavid Sterba  * same for write and wait phases.
40494eedeb75SHisashi Hifumi  *
4050314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
40514eedeb75SHisashi Hifumi  */
4052a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
4053abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
4054a512bbf8SYan Zheng {
4055d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
4056314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
4057d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
4058a512bbf8SYan Zheng 	int i;
4059a512bbf8SYan Zheng 	int errors = 0;
406012659251SNaohiro Aota 	int ret;
406112659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
4062a512bbf8SYan Zheng 
4063a512bbf8SYan Zheng 	if (max_mirrors == 0)
4064a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4065a512bbf8SYan Zheng 
4066d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
4067d5178578SJohannes Thumshirn 
4068a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
4069314b6dd0SJohannes Thumshirn 		struct page *page;
4070314b6dd0SJohannes Thumshirn 		struct bio *bio;
4071314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
4072314b6dd0SJohannes Thumshirn 
407312659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
407412659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
407512659251SNaohiro Aota 		if (ret == -ENOENT) {
407612659251SNaohiro Aota 			continue;
407712659251SNaohiro Aota 		} else if (ret < 0) {
407812659251SNaohiro Aota 			btrfs_err(device->fs_info,
407912659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
408012659251SNaohiro Aota 				i);
408112659251SNaohiro Aota 			errors++;
408212659251SNaohiro Aota 			continue;
408312659251SNaohiro Aota 		}
4084935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4085935e5cc9SMiao Xie 		    device->commit_total_bytes)
4086a512bbf8SYan Zheng 			break;
4087a512bbf8SYan Zheng 
408812659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
4089a512bbf8SYan Zheng 
4090fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
4091fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
4092fd08001fSEric Biggers 				    sb->csum);
4093a512bbf8SYan Zheng 
4094314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
4095314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
4096314b6dd0SJohannes Thumshirn 		if (!page) {
4097fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
4098314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
4099f14d104dSDavid Sterba 			    bytenr);
4100634554dcSJosef Bacik 			errors++;
4101634554dcSJosef Bacik 			continue;
4102634554dcSJosef Bacik 		}
4103634554dcSJosef Bacik 
4104314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
4105314b6dd0SJohannes Thumshirn 		get_page(page);
4106a512bbf8SYan Zheng 
4107314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
4108314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
4109a512bbf8SYan Zheng 
4110387125fcSChris Mason 		/*
4111314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
4112314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
4113314b6dd0SJohannes Thumshirn 		 * checking.
4114387125fcSChris Mason 		 */
4115314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
4116314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
4117314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
4118314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
4119314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
4120314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
4121314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
4122314b6dd0SJohannes Thumshirn 
4123314b6dd0SJohannes Thumshirn 		/*
4124314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
4125314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
4126314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
4127314b6dd0SJohannes Thumshirn 		 */
4128314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
41291b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
4130314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
4131314b6dd0SJohannes Thumshirn 
4132314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
41338376d9e1SNaohiro Aota 
41348376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
41358376d9e1SNaohiro Aota 			errors++;
4136a512bbf8SYan Zheng 	}
4137a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
4138a512bbf8SYan Zheng }
4139a512bbf8SYan Zheng 
4140387125fcSChris Mason /*
4141abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
4142abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
4143abbb3b8eSDavid Sterba  *
4144314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
4145abbb3b8eSDavid Sterba  * date.
4146abbb3b8eSDavid Sterba  */
4147abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4148abbb3b8eSDavid Sterba {
4149abbb3b8eSDavid Sterba 	int i;
4150abbb3b8eSDavid Sterba 	int errors = 0;
4151b6a535faSHoward McLauchlan 	bool primary_failed = false;
415212659251SNaohiro Aota 	int ret;
4153abbb3b8eSDavid Sterba 	u64 bytenr;
4154abbb3b8eSDavid Sterba 
4155abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
4156abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4157abbb3b8eSDavid Sterba 
4158abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
4159314b6dd0SJohannes Thumshirn 		struct page *page;
4160314b6dd0SJohannes Thumshirn 
416112659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
416212659251SNaohiro Aota 		if (ret == -ENOENT) {
416312659251SNaohiro Aota 			break;
416412659251SNaohiro Aota 		} else if (ret < 0) {
416512659251SNaohiro Aota 			errors++;
416612659251SNaohiro Aota 			if (i == 0)
416712659251SNaohiro Aota 				primary_failed = true;
416812659251SNaohiro Aota 			continue;
416912659251SNaohiro Aota 		}
4170abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4171abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
4172abbb3b8eSDavid Sterba 			break;
4173abbb3b8eSDavid Sterba 
4174314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
4175314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
4176314b6dd0SJohannes Thumshirn 		if (!page) {
4177abbb3b8eSDavid Sterba 			errors++;
4178b6a535faSHoward McLauchlan 			if (i == 0)
4179b6a535faSHoward McLauchlan 				primary_failed = true;
4180abbb3b8eSDavid Sterba 			continue;
4181abbb3b8eSDavid Sterba 		}
4182314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4183314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4184314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4185abbb3b8eSDavid Sterba 			errors++;
4186b6a535faSHoward McLauchlan 			if (i == 0)
4187b6a535faSHoward McLauchlan 				primary_failed = true;
4188b6a535faSHoward McLauchlan 		}
4189abbb3b8eSDavid Sterba 
4190314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4191314b6dd0SJohannes Thumshirn 		put_page(page);
4192abbb3b8eSDavid Sterba 
4193314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4194314b6dd0SJohannes Thumshirn 		put_page(page);
4195abbb3b8eSDavid Sterba 	}
4196abbb3b8eSDavid Sterba 
4197b6a535faSHoward McLauchlan 	/* log error, force error return */
4198b6a535faSHoward McLauchlan 	if (primary_failed) {
4199b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4200b6a535faSHoward McLauchlan 			  device->devid);
4201b6a535faSHoward McLauchlan 		return -1;
4202b6a535faSHoward McLauchlan 	}
4203b6a535faSHoward McLauchlan 
4204abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4205abbb3b8eSDavid Sterba }
4206abbb3b8eSDavid Sterba 
4207abbb3b8eSDavid Sterba /*
4208387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4209387125fcSChris Mason  * for the barrier when it is done
4210387125fcSChris Mason  */
42114246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4212387125fcSChris Mason {
4213387125fcSChris Mason 	complete(bio->bi_private);
4214387125fcSChris Mason }
4215387125fcSChris Mason 
4216387125fcSChris Mason /*
42174fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
42184fc6441aSAnand Jain  * done in the waiting counterpart.
4219387125fcSChris Mason  */
42204fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4221387125fcSChris Mason {
4222e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
4223387125fcSChris Mason 
4224a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4225a91cf0ffSWang Yugui 	/*
4226a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4227a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4228a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4229a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4230a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4231a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4232a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4233a91cf0ffSWang Yugui 	 * non-debug builds.
4234a91cf0ffSWang Yugui 	 */
4235a91cf0ffSWang Yugui 	struct request_queue *q = bdev_get_queue(device->bdev);
4236c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
42374fc6441aSAnand Jain 		return;
4238a91cf0ffSWang Yugui #endif
4239387125fcSChris Mason 
4240e0ae9994SDavid Sterba 	bio_reset(bio);
4241387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
424274d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
42438d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
4244387125fcSChris Mason 	init_completion(&device->flush_wait);
4245387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4246387125fcSChris Mason 
424743a01111SLu Fengqi 	btrfsic_submit_bio(bio);
42481c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
42494fc6441aSAnand Jain }
4250387125fcSChris Mason 
42514fc6441aSAnand Jain /*
42524fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
42534fc6441aSAnand Jain  */
42548c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
42554fc6441aSAnand Jain {
42564fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
42574fc6441aSAnand Jain 
42581c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
425958efbc9fSOmar Sandoval 		return BLK_STS_OK;
42604fc6441aSAnand Jain 
42611c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
42622980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
42634fc6441aSAnand Jain 
42648c27cb35SLinus Torvalds 	return bio->bi_status;
4265387125fcSChris Mason }
4266387125fcSChris Mason 
4267d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4268401b41e5SAnand Jain {
42696528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4270401b41e5SAnand Jain 		return -EIO;
4271387125fcSChris Mason 	return 0;
4272387125fcSChris Mason }
4273387125fcSChris Mason 
4274387125fcSChris Mason /*
4275387125fcSChris Mason  * send an empty flush down to each device in parallel,
4276387125fcSChris Mason  * then wait for them
4277387125fcSChris Mason  */
4278387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4279387125fcSChris Mason {
4280387125fcSChris Mason 	struct list_head *head;
4281387125fcSChris Mason 	struct btrfs_device *dev;
42825af3e8ccSStefan Behrens 	int errors_wait = 0;
42834e4cbee9SChristoph Hellwig 	blk_status_t ret;
4284387125fcSChris Mason 
42851538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4286387125fcSChris Mason 	/* send down all the barriers */
4287387125fcSChris Mason 	head = &info->fs_devices->devices;
42881538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4289e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4290f88ba6a2SHidetoshi Seto 			continue;
4291cea7c8bfSAnand Jain 		if (!dev->bdev)
4292387125fcSChris Mason 			continue;
4293e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4294ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4295387125fcSChris Mason 			continue;
4296387125fcSChris Mason 
42974fc6441aSAnand Jain 		write_dev_flush(dev);
429858efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4299387125fcSChris Mason 	}
4300387125fcSChris Mason 
4301387125fcSChris Mason 	/* wait for all the barriers */
43021538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4303e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4304f88ba6a2SHidetoshi Seto 			continue;
4305387125fcSChris Mason 		if (!dev->bdev) {
43065af3e8ccSStefan Behrens 			errors_wait++;
4307387125fcSChris Mason 			continue;
4308387125fcSChris Mason 		}
4309e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4310ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4311387125fcSChris Mason 			continue;
4312387125fcSChris Mason 
43134fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4314401b41e5SAnand Jain 		if (ret) {
4315401b41e5SAnand Jain 			dev->last_flush_error = ret;
431666b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
431766b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
43185af3e8ccSStefan Behrens 			errors_wait++;
4319387125fcSChris Mason 		}
4320401b41e5SAnand Jain 	}
4321401b41e5SAnand Jain 
4322cea7c8bfSAnand Jain 	if (errors_wait) {
4323401b41e5SAnand Jain 		/*
4324401b41e5SAnand Jain 		 * At some point we need the status of all disks
4325401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4326401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4327401b41e5SAnand Jain 		 */
4328d10b82feSQu Wenruo 		return check_barrier_error(info);
4329401b41e5SAnand Jain 	}
4330387125fcSChris Mason 	return 0;
4331387125fcSChris Mason }
4332387125fcSChris Mason 
4333943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4334943c6e99SZhao Lei {
43358789f4feSZhao Lei 	int raid_type;
43368789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4337943c6e99SZhao Lei 
43388789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
43398789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
43408c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
43418789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
43428789f4feSZhao Lei 				    tolerated_failures);
4343943c6e99SZhao Lei 
43448789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
43458789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
43468789f4feSZhao Lei 			continue;
434741a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
43488789f4feSZhao Lei 			continue;
43498c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
43508789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
43518789f4feSZhao Lei 				    tolerated_failures);
43528789f4feSZhao Lei 	}
4353943c6e99SZhao Lei 
43548789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4355ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
43568789f4feSZhao Lei 		min_tolerated = 0;
43578789f4feSZhao Lei 	}
43588789f4feSZhao Lei 
43598789f4feSZhao Lei 	return min_tolerated;
4360943c6e99SZhao Lei }
4361943c6e99SZhao Lei 
4362eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4363f2984462SChris Mason {
4364e5e9a520SChris Mason 	struct list_head *head;
4365f2984462SChris Mason 	struct btrfs_device *dev;
4366a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4367f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4368f2984462SChris Mason 	int ret;
4369f2984462SChris Mason 	int do_barriers;
4370a236aed1SChris Mason 	int max_errors;
4371a236aed1SChris Mason 	int total_errors = 0;
4372a061fc8dSChris Mason 	u64 flags;
4373f2984462SChris Mason 
43740b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4375fed3b381SLiu Bo 
4376fed3b381SLiu Bo 	/*
4377fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4378fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4379fed3b381SLiu Bo 	 * been consistent on disk.
4380fed3b381SLiu Bo 	 */
4381fed3b381SLiu Bo 	if (max_mirrors == 0)
43820b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4383f2984462SChris Mason 
43840b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4385a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4386e5e9a520SChris Mason 
43870b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
43880b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
43890b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4390387125fcSChris Mason 
43915af3e8ccSStefan Behrens 	if (do_barriers) {
43920b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
43935af3e8ccSStefan Behrens 		if (ret) {
43945af3e8ccSStefan Behrens 			mutex_unlock(
43950b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
43960b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
43975af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
43985af3e8ccSStefan Behrens 			return ret;
43995af3e8ccSStefan Behrens 		}
44005af3e8ccSStefan Behrens 	}
4401387125fcSChris Mason 
44021538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4403dfe25020SChris Mason 		if (!dev->bdev) {
4404dfe25020SChris Mason 			total_errors++;
4405dfe25020SChris Mason 			continue;
4406dfe25020SChris Mason 		}
4407e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4408ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4409dfe25020SChris Mason 			continue;
4410dfe25020SChris Mason 
44112b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4412a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4413a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
44147df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4415935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4416ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4417ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4418a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4419a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4420a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4421a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
44227239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
44237239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4424a512bbf8SYan Zheng 
4425a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4426a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4427f2984462SChris Mason 
442875cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
442975cb857dSQu Wenruo 		if (ret < 0) {
443075cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
443175cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
443275cb857dSQu Wenruo 				"unexpected superblock corruption detected");
443375cb857dSQu Wenruo 			return -EUCLEAN;
443475cb857dSQu Wenruo 		}
443575cb857dSQu Wenruo 
4436abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4437a236aed1SChris Mason 		if (ret)
4438a236aed1SChris Mason 			total_errors++;
4439f2984462SChris Mason 	}
4440a236aed1SChris Mason 	if (total_errors > max_errors) {
44410b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4442d397712bSChris Mason 			  total_errors);
44430b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
444479787eaaSJeff Mahoney 
44459d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
44460b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
44470b246afaSJeff Mahoney 				      "%d errors while writing supers",
44480b246afaSJeff Mahoney 				      total_errors);
44499d565ba4SStefan Behrens 		return -EIO;
4450a236aed1SChris Mason 	}
4451f2984462SChris Mason 
4452a512bbf8SYan Zheng 	total_errors = 0;
44531538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4454dfe25020SChris Mason 		if (!dev->bdev)
4455dfe25020SChris Mason 			continue;
4456e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4457ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4458dfe25020SChris Mason 			continue;
4459dfe25020SChris Mason 
4460abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4461a512bbf8SYan Zheng 		if (ret)
44621259ab75SChris Mason 			total_errors++;
4463f2984462SChris Mason 	}
44640b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4465a236aed1SChris Mason 	if (total_errors > max_errors) {
44660b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
44670b246afaSJeff Mahoney 				      "%d errors while writing supers",
44680b246afaSJeff Mahoney 				      total_errors);
446979787eaaSJeff Mahoney 		return -EIO;
4470a236aed1SChris Mason 	}
4471f2984462SChris Mason 	return 0;
4472f2984462SChris Mason }
4473f2984462SChris Mason 
4474cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4475cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4476cb517eabSMiao Xie 				  struct btrfs_root *root)
44772619ba1fSChris Mason {
44784785e24fSJosef Bacik 	bool drop_ref = false;
44794785e24fSJosef Bacik 
44804df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
44812619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
44822619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
4483af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
44844785e24fSJosef Bacik 		drop_ref = true;
44854df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
448676dda93cSYan, Zheng 
448784961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4488ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
44891c1ea4f7SLiu Bo 		if (root->reloc_root) {
449000246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
44911c1ea4f7SLiu Bo 			root->reloc_root = NULL;
44921c1ea4f7SLiu Bo 		}
44931c1ea4f7SLiu Bo 	}
44943321719eSLiu Bo 
44954785e24fSJosef Bacik 	if (drop_ref)
449600246528SJosef Bacik 		btrfs_put_root(root);
44972619ba1fSChris Mason }
44982619ba1fSChris Mason 
4499c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4500c146afadSYan Zheng {
4501c146afadSYan Zheng 	u64 root_objectid = 0;
4502c146afadSYan Zheng 	struct btrfs_root *gang[8];
450365d33fd7SQu Wenruo 	int i = 0;
450465d33fd7SQu Wenruo 	int err = 0;
450565d33fd7SQu Wenruo 	unsigned int ret = 0;
4506c146afadSYan Zheng 
4507c146afadSYan Zheng 	while (1) {
4508efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4509c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4510c146afadSYan Zheng 					     (void **)gang, root_objectid,
4511c146afadSYan Zheng 					     ARRAY_SIZE(gang));
451265d33fd7SQu Wenruo 		if (!ret) {
4513efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4514c146afadSYan Zheng 			break;
451565d33fd7SQu Wenruo 		}
45165d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
451766b4ffd1SJosef Bacik 
451865d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
451965d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
452065d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
452165d33fd7SQu Wenruo 				gang[i] = NULL;
452265d33fd7SQu Wenruo 				continue;
452365d33fd7SQu Wenruo 			}
452465d33fd7SQu Wenruo 			/* grab all the search result for later use */
452500246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
452665d33fd7SQu Wenruo 		}
4527efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
452865d33fd7SQu Wenruo 
452965d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
453065d33fd7SQu Wenruo 			if (!gang[i])
453165d33fd7SQu Wenruo 				continue;
4532c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
453366b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
453466b4ffd1SJosef Bacik 			if (err)
453565d33fd7SQu Wenruo 				break;
453600246528SJosef Bacik 			btrfs_put_root(gang[i]);
4537c146afadSYan Zheng 		}
4538c146afadSYan Zheng 		root_objectid++;
4539c146afadSYan Zheng 	}
454065d33fd7SQu Wenruo 
454165d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
454265d33fd7SQu Wenruo 	for (; i < ret; i++) {
454365d33fd7SQu Wenruo 		if (gang[i])
454400246528SJosef Bacik 			btrfs_put_root(gang[i]);
454565d33fd7SQu Wenruo 	}
454665d33fd7SQu Wenruo 	return err;
4547c146afadSYan Zheng }
4548c146afadSYan Zheng 
45496bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4550c146afadSYan Zheng {
45516bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4552c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4553c146afadSYan Zheng 
45540b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45552ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45560b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
45570b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4558c71bf099SYan, Zheng 
4559c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
45600b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45610b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4562c71bf099SYan, Zheng 
45637a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
45643612b495STsutomu Itoh 	if (IS_ERR(trans))
45653612b495STsutomu Itoh 		return PTR_ERR(trans);
45663a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4567c146afadSYan Zheng }
4568c146afadSYan Zheng 
456936c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
457036c86a9eSQu Wenruo {
457136c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
457236c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
457336c86a9eSQu Wenruo 	bool found = false;
457436c86a9eSQu Wenruo 
457536c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
457636c86a9eSQu Wenruo 		return;
457736c86a9eSQu Wenruo 
457836c86a9eSQu Wenruo 	/*
457936c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
458036c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
458136c86a9eSQu Wenruo 	 */
458236c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
458336c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
458436c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
458536c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
458636c86a9eSQu Wenruo 		u64 cur = 0;
458736c86a9eSQu Wenruo 		u64 found_start;
458836c86a9eSQu Wenruo 		u64 found_end;
458936c86a9eSQu Wenruo 
459036c86a9eSQu Wenruo 		found = true;
459136c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
459236c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
459336c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
459436c86a9eSQu Wenruo 			cur = found_end + 1;
459536c86a9eSQu Wenruo 		}
459636c86a9eSQu Wenruo 		btrfs_warn(fs_info,
459736c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
459836c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
459936c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
460036c86a9eSQu Wenruo 
460136c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
460236c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
460336c86a9eSQu Wenruo 		list_del_init(&trans->list);
460436c86a9eSQu Wenruo 
460536c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
460636c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
460736c86a9eSQu Wenruo 	}
460836c86a9eSQu Wenruo 	ASSERT(!found);
460936c86a9eSQu Wenruo }
461036c86a9eSQu Wenruo 
4611b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4612eb60ceacSChris Mason {
4613c146afadSYan Zheng 	int ret;
4614e089f05cSChris Mason 
4615afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4616d6fd0ae2SOmar Sandoval 	/*
4617d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4618d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4619d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4620d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4621d6fd0ae2SOmar Sandoval 	 */
4622d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4623a2135011SChris Mason 
4624b4be6aefSJosef Bacik 	/*
4625b4be6aefSJosef Bacik 	 * If we had UNFINISHED_DROPS we could still be processing them, so
4626b4be6aefSJosef Bacik 	 * clear that bit and wake up relocation so it can stop.
4627b4be6aefSJosef Bacik 	 */
4628b4be6aefSJosef Bacik 	btrfs_wake_unfinished_drop(fs_info);
4629b4be6aefSJosef Bacik 
46307343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4631d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
46327343dd61SJustin Maggard 
4633803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4634803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4635803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4636803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4637803b2f54SStefan Behrens 
4638837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4639aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4640837d5b6eSIlya Dryomov 
46418dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
46428dabb742SStefan Behrens 
4643aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
46444cb5300bSChris Mason 
46454cb5300bSChris Mason 	/* wait for any defraggers to finish */
46464cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
46474cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
46484cb5300bSChris Mason 
46494cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
465026176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
46514cb5300bSChris Mason 
465221c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
465357056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4654576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
465521c7e756SMiao Xie 
465618bb8bbfSJohannes Thumshirn 	cancel_work_sync(&fs_info->reclaim_bgs_work);
465718bb8bbfSJohannes Thumshirn 
4658b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4659b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4660b0643e59SDennis Zhou 
4661bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4662e44163e1SJeff Mahoney 		/*
4663d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4664d6fd0ae2SOmar Sandoval 		 * unused block groups.
4665e44163e1SJeff Mahoney 		 */
46660b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4667e44163e1SJeff Mahoney 
4668f0cc2cd7SFilipe Manana 		/*
4669f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4670f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4671f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4672f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4673f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4674f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4675f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4676f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4677f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4678f0cc2cd7SFilipe Manana 		 */
4679f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4680f0cc2cd7SFilipe Manana 
46816bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4682d397712bSChris Mason 		if (ret)
468304892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4684c146afadSYan Zheng 	}
4685ed2ff2cbSChris Mason 
468684961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
46872ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4688acce952bSliubo 
4689e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4690e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
46918929ecfaSYan, Zheng 
4692e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4693afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4694f25784b3SYan Zheng 
46955958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
46965958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
46975958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
46985958253cSQu Wenruo 	}
46995958253cSQu Wenruo 
470004892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4701fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4702bcef60f2SArne Jansen 
4703963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
470404892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4705963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4706b0c68f8bSChris Mason 	}
470731153d81SYan Zheng 
47085deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
47094297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
47105deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
47114297ff84SJosef Bacik 
47126618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4713b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
47145ac1d209SJeff Mahoney 
47151a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
47161a4319ccSLiu Bo 
4717de348ee0SWang Shilong 	/*
4718de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4719de348ee0SWang Shilong 	 * submit after we stopping all workers.
4720de348ee0SWang Shilong 	 */
4721de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
472296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
472396192499SJosef Bacik 
47240a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
472536c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
47260a31daa4SFilipe Manana 
4727afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
47284273eaffSAnand Jain 	free_root_pointers(fs_info, true);
47298c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
47309ad6b7bcSChris Mason 
47314e19443dSJosef Bacik 	/*
47324e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
47334e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
47344e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
47354e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
47364e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
47374e19443dSJosef Bacik 	 */
47384e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
47394e19443dSJosef Bacik 
474013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4741d6bfde87SChris Mason 
474221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
47430b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
47442ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
474521adbd5cSStefan Behrens #endif
474621adbd5cSStefan Behrens 
47470b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
474868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4749eb60ceacSChris Mason }
4750eb60ceacSChris Mason 
4751b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4752b9fab919SChris Mason 			  int atomic)
4753ccd467d6SChris Mason {
47541259ab75SChris Mason 	int ret;
4755727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
47561259ab75SChris Mason 
47570b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
47581259ab75SChris Mason 	if (!ret)
47591259ab75SChris Mason 		return ret;
47601259ab75SChris Mason 
47611259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4762b9fab919SChris Mason 				    parent_transid, atomic);
4763b9fab919SChris Mason 	if (ret == -EAGAIN)
4764b9fab919SChris Mason 		return ret;
47651259ab75SChris Mason 	return !ret;
47665f39d397SChris Mason }
47676702ed49SChris Mason 
47685f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
47695f39d397SChris Mason {
47702f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
47715f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4772b9473439SChris Mason 	int was_dirty;
4773b4ce94deSChris Mason 
477406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
477506ea65a3SJosef Bacik 	/*
477606ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
477752042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
477806ea65a3SJosef Bacik 	 * outside of the sanity tests.
477906ea65a3SJosef Bacik 	 */
4780b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
478106ea65a3SJosef Bacik 		return;
478206ea65a3SJosef Bacik #endif
478349d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
47840b246afaSJeff Mahoney 	if (transid != fs_info->generation)
47855d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
47860b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
47870b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4788e2d84521SMiao Xie 	if (!was_dirty)
4789104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4790e2d84521SMiao Xie 					 buf->len,
47910b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
47921f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
479369fc6cbbSQu Wenruo 	/*
479469fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
479569fc6cbbSQu Wenruo 	 * but item data not updated.
479669fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
479769fc6cbbSQu Wenruo 	 */
479869fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4799cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4800a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
48011f21ef0aSFilipe Manana 		ASSERT(0);
48021f21ef0aSFilipe Manana 	}
48031f21ef0aSFilipe Manana #endif
4804eb60ceacSChris Mason }
4805eb60ceacSChris Mason 
48062ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4807b53d3f5dSLiu Bo 					int flush_delayed)
480835b7e476SChris Mason {
4809188de649SChris Mason 	/*
4810188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4811188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4812188de649SChris Mason 	 */
4813e2d84521SMiao Xie 	int ret;
4814d6bfde87SChris Mason 
48156933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4816d6bfde87SChris Mason 		return;
4817d6bfde87SChris Mason 
4818b53d3f5dSLiu Bo 	if (flush_delayed)
48192ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
482016cdcec7SMiao Xie 
4821d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4822d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4823d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4824e2d84521SMiao Xie 	if (ret > 0) {
48250b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
482616cdcec7SMiao Xie 	}
482716cdcec7SMiao Xie }
482816cdcec7SMiao Xie 
48292ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
483016cdcec7SMiao Xie {
48312ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
483235b7e476SChris Mason }
4833b53d3f5dSLiu Bo 
48342ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4835b53d3f5dSLiu Bo {
48362ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4837d6bfde87SChris Mason }
48386b80053dSChris Mason 
4839581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4840581c1760SQu Wenruo 		      struct btrfs_key *first_key)
48416b80053dSChris Mason {
48425ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4843581c1760SQu Wenruo 					      level, first_key);
48446b80053dSChris Mason }
48450da5468fSChris Mason 
48462ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4847acce952bSliubo {
4848fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4849fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4850fe816d0fSNikolay Borisov 
48510b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
48522ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
48530b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4854acce952bSliubo 
48550b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
48560b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4857acce952bSliubo }
4858acce952bSliubo 
4859ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4860ef67963dSJosef Bacik {
4861ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4862ef67963dSJosef Bacik 	u64 root_objectid = 0;
4863ef67963dSJosef Bacik 	int ret;
4864ef67963dSJosef Bacik 
4865ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4866ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4867ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4868ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4869ef67963dSJosef Bacik 		int i;
4870ef67963dSJosef Bacik 
4871ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4872ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4873ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4874ef67963dSJosef Bacik 
4875ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4876ef67963dSJosef Bacik 			if (!gang[i])
4877ef67963dSJosef Bacik 				continue;
4878ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4879ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4880ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4881ef67963dSJosef Bacik 		}
4882ef67963dSJosef Bacik 		root_objectid++;
4883ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4884ef67963dSJosef Bacik 	}
4885ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4886ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4887ef67963dSJosef Bacik }
4888ef67963dSJosef Bacik 
4889143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4890acce952bSliubo {
4891acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4892acce952bSliubo 
4893199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4894779880efSJosef Bacik 	/*
4895779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4896779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4897779880efSJosef Bacik 	 */
4898199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4899779880efSJosef Bacik 			    root_extent_list)
4900779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4901199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4902199c2a9cSMiao Xie }
4903199c2a9cSMiao Xie 
4904199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4905199c2a9cSMiao Xie {
4906199c2a9cSMiao Xie 	struct btrfs_root *root;
4907199c2a9cSMiao Xie 	struct list_head splice;
4908199c2a9cSMiao Xie 
4909199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4910199c2a9cSMiao Xie 
4911199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4912199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4913199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4914199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4915199c2a9cSMiao Xie 					ordered_root);
49161de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
49171de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4918199c2a9cSMiao Xie 
49192a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4920199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4921199c2a9cSMiao Xie 
49222a85d9caSLiu Bo 		cond_resched();
49232a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4924199c2a9cSMiao Xie 	}
4925199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
492674d5d229SJosef Bacik 
492774d5d229SJosef Bacik 	/*
492874d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
492974d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
493074d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
493174d5d229SJosef Bacik 	 * actually get run and error out properly.
493274d5d229SJosef Bacik 	 */
493374d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4934acce952bSliubo }
4935acce952bSliubo 
493635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
49372ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4938acce952bSliubo {
4939acce952bSliubo 	struct rb_node *node;
4940acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4941acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4942acce952bSliubo 	int ret = 0;
4943acce952bSliubo 
4944acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4945acce952bSliubo 
4946acce952bSliubo 	spin_lock(&delayed_refs->lock);
4947d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4948cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4949b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4950acce952bSliubo 		return ret;
4951acce952bSliubo 	}
4952acce952bSliubo 
49535c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4954d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
49550e0adbcfSJosef Bacik 		struct rb_node *n;
4956e78417d1SJosef Bacik 		bool pin_bytes = false;
4957acce952bSliubo 
4958d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4959d7df2c79SJosef Bacik 				href_node);
49603069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4961b939d1abSJosef Bacik 			continue;
49623069bd26SJosef Bacik 
4963d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4964e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
49650e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
49660e0adbcfSJosef Bacik 				       ref_node);
4967d7df2c79SJosef Bacik 			ref->in_tree = 0;
4968e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
49690e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
49701d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
49711d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4972d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4973d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4974d7df2c79SJosef Bacik 		}
497554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4976e78417d1SJosef Bacik 			pin_bytes = true;
497778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4978fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4979d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4980acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4981e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4982acce952bSliubo 
4983f603bb94SNikolay Borisov 		if (pin_bytes) {
4984f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4985f603bb94SNikolay Borisov 
4986f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4987f603bb94SNikolay Borisov 			BUG_ON(!cache);
4988f603bb94SNikolay Borisov 
4989f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4990f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4991f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4992f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4993f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4994f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4995f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4996f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4997f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4998f603bb94SNikolay Borisov 
4999f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
5000f603bb94SNikolay Borisov 
5001f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
5002f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
5003f603bb94SNikolay Borisov 		}
500431890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
5005d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
5006acce952bSliubo 		cond_resched();
5007acce952bSliubo 		spin_lock(&delayed_refs->lock);
5008acce952bSliubo 	}
500981f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
5010acce952bSliubo 
5011acce952bSliubo 	spin_unlock(&delayed_refs->lock);
5012acce952bSliubo 
5013acce952bSliubo 	return ret;
5014acce952bSliubo }
5015acce952bSliubo 
5016143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
5017acce952bSliubo {
5018acce952bSliubo 	struct btrfs_inode *btrfs_inode;
5019acce952bSliubo 	struct list_head splice;
5020acce952bSliubo 
5021acce952bSliubo 	INIT_LIST_HEAD(&splice);
5022acce952bSliubo 
5023eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
5024eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
5025acce952bSliubo 
5026acce952bSliubo 	while (!list_empty(&splice)) {
5027fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
5028eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
5029acce952bSliubo 					       delalloc_inodes);
5030fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
5031eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
5032acce952bSliubo 
5033fe816d0fSNikolay Borisov 		/*
5034fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
5035fe816d0fSNikolay Borisov 		 * meanwhile.
5036fe816d0fSNikolay Borisov 		 */
5037fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
5038fe816d0fSNikolay Borisov 		if (inode) {
5039fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
5040fe816d0fSNikolay Borisov 			iput(inode);
5041fe816d0fSNikolay Borisov 		}
5042eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
5043acce952bSliubo 	}
5044eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
5045eb73c1b7SMiao Xie }
5046eb73c1b7SMiao Xie 
5047eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
5048eb73c1b7SMiao Xie {
5049eb73c1b7SMiao Xie 	struct btrfs_root *root;
5050eb73c1b7SMiao Xie 	struct list_head splice;
5051eb73c1b7SMiao Xie 
5052eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
5053eb73c1b7SMiao Xie 
5054eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
5055eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
5056eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
5057eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
5058eb73c1b7SMiao Xie 					 delalloc_root);
505900246528SJosef Bacik 		root = btrfs_grab_root(root);
5060eb73c1b7SMiao Xie 		BUG_ON(!root);
5061eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
5062eb73c1b7SMiao Xie 
5063eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
506400246528SJosef Bacik 		btrfs_put_root(root);
5065eb73c1b7SMiao Xie 
5066eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
5067eb73c1b7SMiao Xie 	}
5068eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
5069acce952bSliubo }
5070acce952bSliubo 
50712ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
5072acce952bSliubo 					struct extent_io_tree *dirty_pages,
5073acce952bSliubo 					int mark)
5074acce952bSliubo {
5075acce952bSliubo 	int ret;
5076acce952bSliubo 	struct extent_buffer *eb;
5077acce952bSliubo 	u64 start = 0;
5078acce952bSliubo 	u64 end;
5079acce952bSliubo 
5080acce952bSliubo 	while (1) {
5081acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
5082e6138876SJosef Bacik 					    mark, NULL);
5083acce952bSliubo 		if (ret)
5084acce952bSliubo 			break;
5085acce952bSliubo 
508691166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
5087acce952bSliubo 		while (start <= end) {
50880b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
50890b246afaSJeff Mahoney 			start += fs_info->nodesize;
5090fd8b2b61SJosef Bacik 			if (!eb)
5091acce952bSliubo 				continue;
5092fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
5093acce952bSliubo 
5094fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
5095fd8b2b61SJosef Bacik 					       &eb->bflags))
5096fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
5097fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
5098acce952bSliubo 		}
5099acce952bSliubo 	}
5100acce952bSliubo 
5101acce952bSliubo 	return ret;
5102acce952bSliubo }
5103acce952bSliubo 
51042ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
5105fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
5106acce952bSliubo {
5107acce952bSliubo 	u64 start;
5108acce952bSliubo 	u64 end;
5109acce952bSliubo 	int ret;
5110acce952bSliubo 
5111acce952bSliubo 	while (1) {
51120e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
51130e6ec385SFilipe Manana 
5114fcd5e742SLu Fengqi 		/*
5115fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
5116fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
5117fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5118fcd5e742SLu Fengqi 		 * the same extent range.
5119fcd5e742SLu Fengqi 		 */
5120fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
5121acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
51220e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
5123fcd5e742SLu Fengqi 		if (ret) {
5124fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5125acce952bSliubo 			break;
5126fcd5e742SLu Fengqi 		}
5127acce952bSliubo 
51280e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
51290e6ec385SFilipe Manana 		free_extent_state(cached_state);
51302ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
5131fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5132acce952bSliubo 		cond_resched();
5133acce952bSliubo 	}
5134acce952bSliubo 
5135acce952bSliubo 	return 0;
5136acce952bSliubo }
5137acce952bSliubo 
513832da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
5139c79a1751SLiu Bo {
5140c79a1751SLiu Bo 	struct inode *inode;
5141c79a1751SLiu Bo 
5142c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
5143c79a1751SLiu Bo 	if (inode) {
5144c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
5145c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
5146c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
5147c79a1751SLiu Bo 		iput(inode);
5148c79a1751SLiu Bo 	}
5149bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
5150c79a1751SLiu Bo 	btrfs_put_block_group(cache);
5151c79a1751SLiu Bo }
5152c79a1751SLiu Bo 
5153c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
51542ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5155c79a1751SLiu Bo {
515632da5386SDavid Sterba 	struct btrfs_block_group *cache;
5157c79a1751SLiu Bo 
5158c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5159c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5160c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
516132da5386SDavid Sterba 					 struct btrfs_block_group,
5162c79a1751SLiu Bo 					 dirty_list);
5163c79a1751SLiu Bo 
5164c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5165c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5166c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5167c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5168c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5169c79a1751SLiu Bo 		}
5170c79a1751SLiu Bo 
5171c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5172c79a1751SLiu Bo 		spin_lock(&cache->lock);
5173c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5174c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5175c79a1751SLiu Bo 
5176c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5177c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5178ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5179c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5180c79a1751SLiu Bo 	}
5181c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5182c79a1751SLiu Bo 
518345ae2c18SNikolay Borisov 	/*
518445ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
518545ae2c18SNikolay Borisov 	 * to use it without any locking
518645ae2c18SNikolay Borisov 	 */
5187c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5188c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
518932da5386SDavid Sterba 					 struct btrfs_block_group,
5190c79a1751SLiu Bo 					 io_list);
5191c79a1751SLiu Bo 
5192c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5193c79a1751SLiu Bo 		spin_lock(&cache->lock);
5194c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5195c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5196c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5197c79a1751SLiu Bo 	}
5198c79a1751SLiu Bo }
5199c79a1751SLiu Bo 
520049b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
52012ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
520249b25e05SJeff Mahoney {
5203bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5204bbbf7243SNikolay Borisov 
52052ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5206c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5207c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5208c79a1751SLiu Bo 
5209bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5210bbbf7243SNikolay Borisov 				 post_commit_list) {
5211bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5212bbbf7243SNikolay Borisov 	}
5213bbbf7243SNikolay Borisov 
52142ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
521549b25e05SJeff Mahoney 
52164a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
52170b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
521849b25e05SJeff Mahoney 
52194a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
52200b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
522149b25e05SJeff Mahoney 
5222ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
522367cde344SMiao Xie 
52242ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
522549b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5226fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
522749b25e05SJeff Mahoney 
5228d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
5229d3575156SNaohiro Aota 
52304a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
52314a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
523249b25e05SJeff Mahoney }
523349b25e05SJeff Mahoney 
52342ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5235acce952bSliubo {
5236acce952bSliubo 	struct btrfs_transaction *t;
5237acce952bSliubo 
52380b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5239acce952bSliubo 
52400b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
52410b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
52420b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5243724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5244724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
52459b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
52460b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
52472ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5248724e2315SJosef Bacik 			btrfs_put_transaction(t);
52490b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5250724e2315SJosef Bacik 			continue;
5251724e2315SJosef Bacik 		}
52520b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5253724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
52540b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5255724e2315SJosef Bacik 			/*
5256724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5257724e2315SJosef Bacik 			 * handle open currently for this transaction.
5258724e2315SJosef Bacik 			 */
5259724e2315SJosef Bacik 			wait_event(t->writer_wait,
5260724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5261724e2315SJosef Bacik 		} else {
52620b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5263724e2315SJosef Bacik 		}
52642ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5265724e2315SJosef Bacik 
52660b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
52670b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
52680b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5269724e2315SJosef Bacik 		list_del_init(&t->list);
52700b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5271a4abeea4SJosef Bacik 
5272724e2315SJosef Bacik 		btrfs_put_transaction(t);
52732e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
52740b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5275724e2315SJosef Bacik 	}
52760b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
52770b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5278ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5279ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
52800b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5281ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
52820b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5283acce952bSliubo 
5284acce952bSliubo 	return 0;
5285acce952bSliubo }
5286ec7d6dfdSNikolay Borisov 
5287453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5288ec7d6dfdSNikolay Borisov {
5289ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5290ec7d6dfdSNikolay Borisov 	int ret;
5291ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5292ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5293ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5294ec7d6dfdSNikolay Borisov 	int slot;
5295ec7d6dfdSNikolay Borisov 
5296ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5297ec7d6dfdSNikolay Borisov 	if (!path)
5298ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5299ec7d6dfdSNikolay Borisov 
5300ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5301ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5302ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5303ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5304ec7d6dfdSNikolay Borisov 	if (ret < 0)
5305ec7d6dfdSNikolay Borisov 		goto error;
5306ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5307ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5308ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5309ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5310ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
531123125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
531223125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5313ec7d6dfdSNikolay Borisov 	} else {
531423125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5315ec7d6dfdSNikolay Borisov 	}
5316ec7d6dfdSNikolay Borisov 	ret = 0;
5317ec7d6dfdSNikolay Borisov error:
5318ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5319ec7d6dfdSNikolay Borisov 	return ret;
5320ec7d6dfdSNikolay Borisov }
5321ec7d6dfdSNikolay Borisov 
5322543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5323ec7d6dfdSNikolay Borisov {
5324ec7d6dfdSNikolay Borisov 	int ret;
5325ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5326ec7d6dfdSNikolay Borisov 
53276b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5328ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5329ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5330ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5331ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5332ec7d6dfdSNikolay Borisov 		goto out;
5333ec7d6dfdSNikolay Borisov 	}
5334ec7d6dfdSNikolay Borisov 
533523125104SNikolay Borisov 	*objectid = root->free_objectid++;
5336ec7d6dfdSNikolay Borisov 	ret = 0;
5337ec7d6dfdSNikolay Borisov out:
5338ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5339ec7d6dfdSNikolay Borisov 	return ret;
5340ec7d6dfdSNikolay Borisov }
5341