xref: /openbmc/linux/fs/btrfs/disk-io.c (revision efcfcbc6)
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>
8fc7cbcd4SDavid Sterba #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"
26103c1972SChristoph Hellwig #include "bio.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"
46c7f13d42SJosef Bacik #include "fs.h"
4707e81dc9SJosef Bacik #include "accessors.h"
48a0231804SJosef Bacik #include "extent-tree.h"
4945c40c8fSJosef Bacik #include "root-tree.h"
5059b818e0SJosef Bacik #include "defrag.h"
51c7a03b52SJosef Bacik #include "uuid-tree.h"
5267707479SJosef Bacik #include "relocation.h"
532fc6822cSJosef Bacik #include "scrub.h"
54c03b2207SJosef Bacik #include "super.h"
55eb60ceacSChris Mason 
56319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
57319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
58319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
59319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
60e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
61e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
62319e4d06SQu Wenruo 
632ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
642ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
65ce9adaa5SChris Mason 
66141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
67141386e1SJosef Bacik {
68141386e1SJosef Bacik 	if (fs_info->csum_shash)
69141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
70141386e1SJosef Bacik }
71141386e1SJosef Bacik 
72d352ac68SChris Mason /*
732996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
74d352ac68SChris Mason  */
75c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
7619c00ddcSChris Mason {
77d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
787280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
79a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
80d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
8119c00ddcSChris Mason 	char *kaddr;
82e9be5a30SDavid Sterba 	int i;
83d5178578SJohannes Thumshirn 
84d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
85d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
86a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
87e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
88a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
8919c00ddcSChris Mason 
905ad9b471Spengfuyuan 	for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
91e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
92e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
9319c00ddcSChris Mason 	}
9471a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
95d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
9619c00ddcSChris Mason }
9719c00ddcSChris Mason 
98d352ac68SChris Mason /*
99d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
100d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
101d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
102d352ac68SChris Mason  * in the wrong place.
103d352ac68SChris Mason  */
104d87e6575SChristoph Hellwig int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid, int atomic)
1051259ab75SChris Mason {
106d87e6575SChristoph Hellwig 	if (!extent_buffer_uptodate(eb))
107d87e6575SChristoph Hellwig 		return 0;
1081259ab75SChris Mason 
1091259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
110d87e6575SChristoph Hellwig 		return 1;
1111259ab75SChris Mason 
112b9fab919SChris Mason 	if (atomic)
113b9fab919SChris Mason 		return -EAGAIN;
114b9fab919SChris Mason 
115d87e6575SChristoph Hellwig 	if (!extent_buffer_uptodate(eb) ||
116d87e6575SChristoph Hellwig 	    btrfs_header_generation(eb) != parent_transid) {
11794647322SDavid Sterba 		btrfs_err_rl(eb->fs_info,
1188f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1198f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
12029549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1210b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
1229e2aff90SChristoph Hellwig 		return 0;
123d87e6575SChristoph Hellwig 	}
1249e2aff90SChristoph Hellwig 	return 1;
1251259ab75SChris Mason }
1261259ab75SChris Mason 
127e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
128e7e16f48SJohannes Thumshirn {
129e7e16f48SJohannes Thumshirn 	switch (csum_type) {
130e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1313951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1323831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
133352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
134e7e16f48SJohannes Thumshirn 		return true;
135e7e16f48SJohannes Thumshirn 	default:
136e7e16f48SJohannes Thumshirn 		return false;
137e7e16f48SJohannes Thumshirn 	}
138e7e16f48SJohannes Thumshirn }
139e7e16f48SJohannes Thumshirn 
140d352ac68SChris Mason /*
1411104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1421104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1431104a885SDavid Sterba  */
1443d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1453d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1461104a885SDavid Sterba {
14751bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
148d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
149d5178578SJohannes Thumshirn 
150d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1511104a885SDavid Sterba 
1521104a885SDavid Sterba 	/*
1531104a885SDavid Sterba 	 * The super_block structure does not span the whole
15451bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
15551bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1561104a885SDavid Sterba 	 */
1573d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
158fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1591104a885SDavid Sterba 
16055fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
161e7e16f48SJohannes Thumshirn 		return 1;
1621104a885SDavid Sterba 
163e7e16f48SJohannes Thumshirn 	return 0;
1641104a885SDavid Sterba }
1651104a885SDavid Sterba 
166bacf60e5SChristoph Hellwig static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
167bacf60e5SChristoph Hellwig 				      int mirror_num)
168bacf60e5SChristoph Hellwig {
169bacf60e5SChristoph Hellwig 	struct btrfs_fs_info *fs_info = eb->fs_info;
170bacf60e5SChristoph Hellwig 	int i, num_pages = num_extent_pages(eb);
171bacf60e5SChristoph Hellwig 	int ret = 0;
172bacf60e5SChristoph Hellwig 
173bacf60e5SChristoph Hellwig 	if (sb_rdonly(fs_info->sb))
174bacf60e5SChristoph Hellwig 		return -EROFS;
175bacf60e5SChristoph Hellwig 
176bacf60e5SChristoph Hellwig 	for (i = 0; i < num_pages; i++) {
177bacf60e5SChristoph Hellwig 		struct page *p = eb->pages[i];
178917ac778SQu Wenruo 		u64 start = max_t(u64, eb->start, page_offset(p));
179917ac778SQu Wenruo 		u64 end = min_t(u64, eb->start + eb->len, page_offset(p) + PAGE_SIZE);
180917ac778SQu Wenruo 		u32 len = end - start;
181bacf60e5SChristoph Hellwig 
182917ac778SQu Wenruo 		ret = btrfs_repair_io_failure(fs_info, 0, start, len,
183917ac778SQu Wenruo 				start, p, offset_in_page(start), mirror_num);
184bacf60e5SChristoph Hellwig 		if (ret)
185bacf60e5SChristoph Hellwig 			break;
186bacf60e5SChristoph Hellwig 	}
187bacf60e5SChristoph Hellwig 
188bacf60e5SChristoph Hellwig 	return ret;
189bacf60e5SChristoph Hellwig }
190bacf60e5SChristoph Hellwig 
1911104a885SDavid Sterba /*
192d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
193d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
194581c1760SQu Wenruo  *
195789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see the comments of the
196789d6a3aSQu Wenruo  *			structure for details.
197d352ac68SChris Mason  */
1986a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
199789d6a3aSQu Wenruo 			     struct btrfs_tree_parent_check *check)
200f188591eSChris Mason {
2015ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
202ea466794SJosef Bacik 	int failed = 0;
203f188591eSChris Mason 	int ret;
204f188591eSChris Mason 	int num_copies = 0;
205f188591eSChris Mason 	int mirror_num = 0;
206ea466794SJosef Bacik 	int failed_mirror = 0;
207f188591eSChris Mason 
208789d6a3aSQu Wenruo 	ASSERT(check);
209789d6a3aSQu Wenruo 
210f188591eSChris Mason 	while (1) {
211f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
212947a6299SQu Wenruo 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
213947a6299SQu Wenruo 		if (!ret)
214581c1760SQu Wenruo 			break;
215d397712bSChris Mason 
2160b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
217f188591eSChris Mason 					      eb->start, eb->len);
2184235298eSChris Mason 		if (num_copies == 1)
219ea466794SJosef Bacik 			break;
2204235298eSChris Mason 
2215cf1ab56SJosef Bacik 		if (!failed_mirror) {
2225cf1ab56SJosef Bacik 			failed = 1;
2235cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
2245cf1ab56SJosef Bacik 		}
2255cf1ab56SJosef Bacik 
226f188591eSChris Mason 		mirror_num++;
227ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
228ea466794SJosef Bacik 			mirror_num++;
229ea466794SJosef Bacik 
2304235298eSChris Mason 		if (mirror_num > num_copies)
231ea466794SJosef Bacik 			break;
232f188591eSChris Mason 	}
233ea466794SJosef Bacik 
234c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
23520a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
236ea466794SJosef Bacik 
237ea466794SJosef Bacik 	return ret;
238f188591eSChris Mason }
23919c00ddcSChris Mason 
24031d89399SChristoph Hellwig /*
24131d89399SChristoph Hellwig  * Checksum a dirty tree block before IO.
24231d89399SChristoph Hellwig  */
24331d89399SChristoph Hellwig blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)
244eca0f6f6SQu Wenruo {
24531d89399SChristoph Hellwig 	struct extent_buffer *eb = bbio->private;
246eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
24731d89399SChristoph Hellwig 	u64 found_start = btrfs_header_bytenr(eb);
248eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
249eca0f6f6SQu Wenruo 	int ret;
250eca0f6f6SQu Wenruo 
25131d89399SChristoph Hellwig 	/* Btree blocks are always contiguous on disk. */
25231d89399SChristoph Hellwig 	if (WARN_ON_ONCE(bbio->file_offset != eb->start))
25331d89399SChristoph Hellwig 		return BLK_STS_IOERR;
25431d89399SChristoph Hellwig 	if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
25531d89399SChristoph Hellwig 		return BLK_STS_IOERR;
25631d89399SChristoph Hellwig 
25731d89399SChristoph Hellwig 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
25831d89399SChristoph Hellwig 		WARN_ON_ONCE(found_start != 0);
25931d89399SChristoph Hellwig 		return BLK_STS_OK;
26031d89399SChristoph Hellwig 	}
26131d89399SChristoph Hellwig 
26231d89399SChristoph Hellwig 	if (WARN_ON_ONCE(found_start != eb->start))
26331d89399SChristoph Hellwig 		return BLK_STS_IOERR;
26431d89399SChristoph Hellwig 	if (WARN_ON(!btrfs_page_test_uptodate(fs_info, eb->pages[0], eb->start,
26531d89399SChristoph Hellwig 					      eb->len)))
26631d89399SChristoph Hellwig 		return BLK_STS_IOERR;
26731d89399SChristoph Hellwig 
268eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
269eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
270eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
271eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
272eca0f6f6SQu Wenruo 
273eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
274eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
275eca0f6f6SQu Wenruo 	else
27685d8a826SJosef Bacik 		ret = btrfs_check_leaf(eb);
277eca0f6f6SQu Wenruo 
2783777369fSQu Wenruo 	if (ret < 0)
2793777369fSQu Wenruo 		goto error;
2803777369fSQu Wenruo 
2813777369fSQu Wenruo 	/*
2823777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
2833777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
2843777369fSQu Wenruo 	 */
2853777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
2863777369fSQu Wenruo 		ret = -EUCLEAN;
287eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
2883777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
2893777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
2903777369fSQu Wenruo 			  fs_info->last_trans_committed);
2913777369fSQu Wenruo 		goto error;
292eca0f6f6SQu Wenruo 	}
293eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
29431d89399SChristoph Hellwig 	return BLK_STS_OK;
2953777369fSQu Wenruo 
2963777369fSQu Wenruo error:
2973777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
2983777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
2993777369fSQu Wenruo 		  eb->start);
30016199ad9SFilipe Manana 	/*
30116199ad9SFilipe Manana 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
30216199ad9SFilipe Manana 	 * a transaction in case there's a bad log tree extent buffer, we just
30316199ad9SFilipe Manana 	 * fallback to a transaction commit. Still we want to know when there is
30416199ad9SFilipe Manana 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
30516199ad9SFilipe Manana 	 */
30616199ad9SFilipe Manana 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
30716199ad9SFilipe Manana 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
308deb6216fSChristoph Hellwig 	return errno_to_blk_status(ret);
309deb6216fSChristoph Hellwig }
310deb6216fSChristoph Hellwig 
311413fb1bcSAnand Jain static bool check_tree_block_fsid(struct extent_buffer *eb)
3122b82032cSYan Zheng {
313b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
314944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
31544880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
316944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
3172b82032cSYan Zheng 
3189a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
3199a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
3207239ff4bSNikolay Borisov 	/*
321944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
322944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
323944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
3247239ff4bSNikolay Borisov 	 */
325944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
3267239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
3277239ff4bSNikolay Borisov 	else
3287239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
3297239ff4bSNikolay Borisov 
330944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
331413fb1bcSAnand Jain 		return false;
332944d3f9fSNikolay Borisov 
333944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
334944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
335413fb1bcSAnand Jain 			return false;
336944d3f9fSNikolay Borisov 
337413fb1bcSAnand Jain 	return true;
3382b82032cSYan Zheng }
3392b82032cSYan Zheng 
34077bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
341046b562bSChristoph Hellwig int btrfs_validate_extent_buffer(struct extent_buffer *eb,
342947a6299SQu Wenruo 				 struct btrfs_tree_parent_check *check)
343ce9adaa5SChris Mason {
34477bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
345ce9adaa5SChris Mason 	u64 found_start;
34677bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
34777bf40a2SQu Wenruo 	u8 found_level;
3482996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
349dfd29eedSDavid Sterba 	const u8 *header_csum;
35077bf40a2SQu Wenruo 	int ret = 0;
351ea466794SJosef Bacik 
352947a6299SQu Wenruo 	ASSERT(check);
353947a6299SQu Wenruo 
354ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
355727011e0SChris Mason 	if (found_start != eb->start) {
3568f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
3578f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
3588f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
359f188591eSChris Mason 		ret = -EIO;
36077bf40a2SQu Wenruo 		goto out;
361ce9adaa5SChris Mason 	}
362b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
3638f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
3648f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
3651259ab75SChris Mason 		ret = -EIO;
36677bf40a2SQu Wenruo 		goto out;
3671259ab75SChris Mason 	}
368ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
3691c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
3708f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
3718f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
3728f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
3731c24c3ceSJosef Bacik 		ret = -EIO;
37477bf40a2SQu Wenruo 		goto out;
3751c24c3ceSJosef Bacik 	}
376ce9adaa5SChris Mason 
377c67b3892SDavid Sterba 	csum_tree_block(eb, result);
378dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
379dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
380a826d6dcSJosef Bacik 
381dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
3822996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
3838f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
3848f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
385dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
38635be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
38735be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
3882996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
38977bf40a2SQu Wenruo 		goto out;
3902996e1f8SJohannes Thumshirn 	}
3912996e1f8SJohannes Thumshirn 
392947a6299SQu Wenruo 	if (found_level != check->level) {
39377177ed1SQu Wenruo 		btrfs_err(fs_info,
39477177ed1SQu Wenruo 		"level verify failed on logical %llu mirror %u wanted %u found %u",
39577177ed1SQu Wenruo 			  eb->start, eb->read_mirror, check->level, found_level);
396947a6299SQu Wenruo 		ret = -EIO;
397947a6299SQu Wenruo 		goto out;
398947a6299SQu Wenruo 	}
399947a6299SQu Wenruo 	if (unlikely(check->transid &&
400947a6299SQu Wenruo 		     btrfs_header_generation(eb) != check->transid)) {
401947a6299SQu Wenruo 		btrfs_err_rl(eb->fs_info,
402947a6299SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
403947a6299SQu Wenruo 				eb->start, eb->read_mirror, check->transid,
404947a6299SQu Wenruo 				btrfs_header_generation(eb));
405947a6299SQu Wenruo 		ret = -EIO;
406947a6299SQu Wenruo 		goto out;
407947a6299SQu Wenruo 	}
408947a6299SQu Wenruo 	if (check->has_first_key) {
409947a6299SQu Wenruo 		struct btrfs_key *expect_key = &check->first_key;
410947a6299SQu Wenruo 		struct btrfs_key found_key;
411947a6299SQu Wenruo 
412947a6299SQu Wenruo 		if (found_level)
413947a6299SQu Wenruo 			btrfs_node_key_to_cpu(eb, &found_key, 0);
414947a6299SQu Wenruo 		else
415947a6299SQu Wenruo 			btrfs_item_key_to_cpu(eb, &found_key, 0);
416947a6299SQu Wenruo 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
417947a6299SQu Wenruo 			btrfs_err(fs_info,
418947a6299SQu Wenruo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
419947a6299SQu Wenruo 				  eb->start, check->transid,
420947a6299SQu Wenruo 				  expect_key->objectid,
421947a6299SQu Wenruo 				  expect_key->type, expect_key->offset,
422947a6299SQu Wenruo 				  found_key.objectid, found_key.type,
423947a6299SQu Wenruo 				  found_key.offset);
424947a6299SQu Wenruo 			ret = -EUCLEAN;
425947a6299SQu Wenruo 			goto out;
426947a6299SQu Wenruo 		}
427947a6299SQu Wenruo 	}
428947a6299SQu Wenruo 	if (check->owner_root) {
429947a6299SQu Wenruo 		ret = btrfs_check_eb_owner(eb, check->owner_root);
430947a6299SQu Wenruo 		if (ret < 0)
431947a6299SQu Wenruo 			goto out;
432947a6299SQu Wenruo 	}
433947a6299SQu Wenruo 
434a826d6dcSJosef Bacik 	/*
435a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
436a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
437a826d6dcSJosef Bacik 	 * return -EIO.
438a826d6dcSJosef Bacik 	 */
43985d8a826SJosef Bacik 	if (found_level == 0 && btrfs_check_leaf(eb)) {
440a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
441a826d6dcSJosef Bacik 		ret = -EIO;
442a826d6dcSJosef Bacik 	}
443ce9adaa5SChris Mason 
444813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
445053ab70fSLiu Bo 		ret = -EIO;
446053ab70fSLiu Bo 
447aebcc159SChristoph Hellwig 	if (ret)
44875391f0dSQu Wenruo 		btrfs_err(fs_info,
4498f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
4508f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
45177bf40a2SQu Wenruo out:
45277bf40a2SQu Wenruo 	return ret;
45377bf40a2SQu Wenruo }
45477bf40a2SQu Wenruo 
4553dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
4568958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
4578958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
458784b4e29SChris Mason {
459784b4e29SChris Mason 	/*
460784b4e29SChris Mason 	 * we can't safely write a btree page from here,
461784b4e29SChris Mason 	 * we haven't done the locking hook
462784b4e29SChris Mason 	 */
4638958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
464784b4e29SChris Mason 		return -EAGAIN;
465784b4e29SChris Mason 	/*
466784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
467784b4e29SChris Mason 	 * We must have no buffers or drop them.
468784b4e29SChris Mason 	 */
4698958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
4708958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
471784b4e29SChris Mason 		return -EAGAIN;
47254184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
473784b4e29SChris Mason }
4748958b551SMatthew Wilcox (Oracle) #else
4758958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
4763dd1462eSJan Beulich #endif
477784b4e29SChris Mason 
4780da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
4790da5468fSChris Mason 			    struct writeback_control *wbc)
4800da5468fSChris Mason {
481e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
482e2d84521SMiao Xie 	int ret;
483e2d84521SMiao Xie 
484d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
485448d640bSChris Mason 
486448d640bSChris Mason 		if (wbc->for_kupdate)
487448d640bSChris Mason 			return 0;
488448d640bSChris Mason 
489e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
490b9473439SChris Mason 		/* this is a bit racy, but that's ok */
491d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
492d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
493d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
494e2d84521SMiao Xie 		if (ret < 0)
495793955bcSChris Mason 			return 0;
496793955bcSChris Mason 	}
4970b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
4980da5468fSChris Mason }
4990da5468fSChris Mason 
500f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
5015f39d397SChris Mason {
502f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
503f913cff3SMatthew Wilcox (Oracle) 		return false;
5040c4e538bSDavid Sterba 
505f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
506d98237b3SChris Mason }
507d98237b3SChris Mason 
508895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
509895586ebSMatthew Wilcox (Oracle) 				 size_t length)
510d98237b3SChris Mason {
511d1310b2eSChris Mason 	struct extent_io_tree *tree;
512895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
513895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
514f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
515895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
516895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
517895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
518895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
519895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
5209ad6b7bcSChris Mason 	}
521d98237b3SChris Mason }
522d98237b3SChris Mason 
523bb146eb2SJosef Bacik #ifdef DEBUG
5240079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
5250079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
5260079c3b1SMatthew Wilcox (Oracle) {
5270079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
528139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
5290b32f4bbSJosef Bacik 	struct extent_buffer *eb;
530139e8cd3SQu Wenruo 	int cur_bit = 0;
5310079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
5320b32f4bbSJosef Bacik 
533139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
5340079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
5350b32f4bbSJosef Bacik 		BUG_ON(!eb);
5360b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5370b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
53849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
5390079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
540139e8cd3SQu Wenruo 	}
5410079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
542139e8cd3SQu Wenruo 
543139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
544139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
545139e8cd3SQu Wenruo 		unsigned long flags;
546139e8cd3SQu Wenruo 		u64 cur;
547139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
548139e8cd3SQu Wenruo 
549139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
550139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
551139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
552139e8cd3SQu Wenruo 			cur_bit++;
553139e8cd3SQu Wenruo 			continue;
554139e8cd3SQu Wenruo 		}
555139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
556139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
557139e8cd3SQu Wenruo 
558139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
559139e8cd3SQu Wenruo 		ASSERT(eb);
560139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
561139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
56249d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
563139e8cd3SQu Wenruo 		free_extent_buffer(eb);
564139e8cd3SQu Wenruo 
565139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
566139e8cd3SQu Wenruo 	}
5670079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
5680b32f4bbSJosef Bacik }
5690079c3b1SMatthew Wilcox (Oracle) #else
5700079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
5710079c3b1SMatthew Wilcox (Oracle) #endif
5720b32f4bbSJosef Bacik 
5737f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
5740da5468fSChris Mason 	.writepages	= btree_writepages,
575f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
576895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
5778958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
5780079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
579d98237b3SChris Mason };
580123abc88SChris Mason 
5812ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
5822ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
5833fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
5843fbaf258SJosef Bacik 						int level)
5850999df54SChris Mason {
5860b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
5870b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
5883fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
5890999df54SChris Mason }
5900999df54SChris Mason 
591581c1760SQu Wenruo /*
592581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
593581c1760SQu Wenruo  * verification.
594581c1760SQu Wenruo  *
595789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see comments of the
596789d6a3aSQu Wenruo  *			structure for details.
597581c1760SQu Wenruo  */
5982ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
599789d6a3aSQu Wenruo 				      struct btrfs_tree_parent_check *check)
600e20d96d6SChris Mason {
6015f39d397SChris Mason 	struct extent_buffer *buf = NULL;
60219c00ddcSChris Mason 	int ret;
60319c00ddcSChris Mason 
604789d6a3aSQu Wenruo 	ASSERT(check);
605789d6a3aSQu Wenruo 
606789d6a3aSQu Wenruo 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
607789d6a3aSQu Wenruo 					   check->level);
608c871b0f2SLiu Bo 	if (IS_ERR(buf))
609c871b0f2SLiu Bo 		return buf;
610e4204dedSChris Mason 
611789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(buf, check);
6120f0fe8f7SFilipe David Borba Manana 	if (ret) {
613537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
61464c043deSLiu Bo 		return ERR_PTR(ret);
6150f0fe8f7SFilipe David Borba Manana 	}
616789d6a3aSQu Wenruo 	if (btrfs_check_eb_owner(buf, check->owner_root)) {
61788c602abSQu Wenruo 		free_extent_buffer_stale(buf);
61888c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
61988c602abSQu Wenruo 	}
6205f39d397SChris Mason 	return buf;
621ce9adaa5SChris Mason 
622eb60ceacSChris Mason }
623eb60ceacSChris Mason 
624da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
625e20d96d6SChris Mason 			 u64 objectid)
626d97e63b6SChris Mason {
6277c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
6282e608bd1SJosef Bacik 
6292e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
6302e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
6312e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
63296dfcb46SJosef Bacik 	root->fs_info = fs_info;
6332e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
634cfaa7295SChris Mason 	root->node = NULL;
635a28ec197SChris Mason 	root->commit_root = NULL;
63627cdeb70SMiao Xie 	root->state = 0;
637abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
6380b86a832SChris Mason 
6390f7d52f4SChris Mason 	root->last_trans = 0;
6406b8fad57SNikolay Borisov 	root->free_objectid = 0;
641eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
642199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
6436bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
644088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
6452e608bd1SJosef Bacik 
6462e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
6470b86a832SChris Mason 
6480b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
6495d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
650eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
651eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
652199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
653199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
654d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
6552ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
6562ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
6575d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
658eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
659199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
660f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
6612ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
6622ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
6638287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
664a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
665e02119d5SChris Mason 	mutex_init(&root->log_mutex);
66631f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
667573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
668c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
6697237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
6707237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
6717237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
6728b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
6738b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
6747237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
6757237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
6767237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
6772ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
6780700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
6798ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
680eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
6817237f183SYan Zheng 	root->log_transid = 0;
682d1433debSMiao Xie 	root->log_transid_committed = -1;
683257c62e1SChris Mason 	root->last_log_commit = 0;
6842e608bd1SJosef Bacik 	root->anon_dev = 0;
685e289f03eSFilipe Manana 	if (!dummy) {
68643eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
68735da5a7eSDavid Sterba 				    IO_TREE_ROOT_DIRTY_LOG_PAGES);
688e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
68935da5a7eSDavid Sterba 				    IO_TREE_LOG_CSUM_RANGE);
690e289f03eSFilipe Manana 	}
691017e5369SChris Mason 
6925f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
693370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
694bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
695bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
696fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
697bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
698fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
699bd647ce3SJosef Bacik #endif
7003768f368SChris Mason }
7013768f368SChris Mason 
70274e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
70396dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
7046f07e42eSAl Viro {
70574e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
7066f07e42eSAl Viro 	if (root)
70796dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
7086f07e42eSAl Viro 	return root;
7096f07e42eSAl Viro }
7106f07e42eSAl Viro 
71106ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
71206ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
713da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
71406ea65a3SJosef Bacik {
71506ea65a3SJosef Bacik 	struct btrfs_root *root;
71606ea65a3SJosef Bacik 
7177c0260eeSJeff Mahoney 	if (!fs_info)
7187c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
7197c0260eeSJeff Mahoney 
72096dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
72106ea65a3SJosef Bacik 	if (!root)
72206ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
723da17066cSJeff Mahoney 
724b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
725faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
72606ea65a3SJosef Bacik 
72706ea65a3SJosef Bacik 	return root;
72806ea65a3SJosef Bacik }
72906ea65a3SJosef Bacik #endif
73006ea65a3SJosef Bacik 
731abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
732abed4aaaSJosef Bacik {
733abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
734abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
735abed4aaaSJosef Bacik 
736abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
737abed4aaaSJosef Bacik }
738abed4aaaSJosef Bacik 
739abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
740abed4aaaSJosef Bacik {
741abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
742abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
743abed4aaaSJosef Bacik 
744abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
745abed4aaaSJosef Bacik }
746abed4aaaSJosef Bacik 
747abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
748abed4aaaSJosef Bacik {
749abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
750abed4aaaSJosef Bacik 	struct rb_node *tmp;
751745806fbSQu Wenruo 	int ret = 0;
752abed4aaaSJosef Bacik 
753abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
754abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
755abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
756abed4aaaSJosef Bacik 
757745806fbSQu Wenruo 	if (tmp) {
758745806fbSQu Wenruo 		ret = -EEXIST;
759745806fbSQu Wenruo 		btrfs_warn(fs_info, "global root %llu %llu already exists",
760745806fbSQu Wenruo 				root->root_key.objectid, root->root_key.offset);
761745806fbSQu Wenruo 	}
762745806fbSQu Wenruo 	return ret;
763abed4aaaSJosef Bacik }
764abed4aaaSJosef Bacik 
765abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
766abed4aaaSJosef Bacik {
767abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
768abed4aaaSJosef Bacik 
769abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
770abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
771abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
772abed4aaaSJosef Bacik }
773abed4aaaSJosef Bacik 
774abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
775abed4aaaSJosef Bacik 				     struct btrfs_key *key)
776abed4aaaSJosef Bacik {
777abed4aaaSJosef Bacik 	struct rb_node *node;
778abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
779abed4aaaSJosef Bacik 
780abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
781abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
782abed4aaaSJosef Bacik 	if (node)
783abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
784abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
785abed4aaaSJosef Bacik 
786abed4aaaSJosef Bacik 	return root;
787abed4aaaSJosef Bacik }
788abed4aaaSJosef Bacik 
789f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
790f7238e50SJosef Bacik {
791f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
792f7238e50SJosef Bacik 	u64 ret;
793f7238e50SJosef Bacik 
794f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
795f7238e50SJosef Bacik 		return 0;
796f7238e50SJosef Bacik 
797f7238e50SJosef Bacik 	if (bytenr)
798f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
799f7238e50SJosef Bacik 	else
800f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
801f7238e50SJosef Bacik 	ASSERT(block_group);
802f7238e50SJosef Bacik 	if (!block_group)
803f7238e50SJosef Bacik 		return 0;
804f7238e50SJosef Bacik 	ret = block_group->global_root_id;
805f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
806f7238e50SJosef Bacik 
807f7238e50SJosef Bacik 	return ret;
808f7238e50SJosef Bacik }
809f7238e50SJosef Bacik 
810abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
811abed4aaaSJosef Bacik {
812abed4aaaSJosef Bacik 	struct btrfs_key key = {
813abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
814abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
815f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
816abed4aaaSJosef Bacik 	};
817abed4aaaSJosef Bacik 
818abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
819abed4aaaSJosef Bacik }
820abed4aaaSJosef Bacik 
821abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
822abed4aaaSJosef Bacik {
823abed4aaaSJosef Bacik 	struct btrfs_key key = {
824abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
825abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
826f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
827abed4aaaSJosef Bacik 	};
828abed4aaaSJosef Bacik 
829abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
830abed4aaaSJosef Bacik }
831abed4aaaSJosef Bacik 
83251129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
83351129b33SJosef Bacik {
83451129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
83551129b33SJosef Bacik 		return fs_info->block_group_root;
83651129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
83751129b33SJosef Bacik }
83851129b33SJosef Bacik 
83920897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
84020897f5cSArne Jansen 				     u64 objectid)
84120897f5cSArne Jansen {
8429b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
84320897f5cSArne Jansen 	struct extent_buffer *leaf;
84420897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
84520897f5cSArne Jansen 	struct btrfs_root *root;
84620897f5cSArne Jansen 	struct btrfs_key key;
847b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
84820897f5cSArne Jansen 	int ret = 0;
84920897f5cSArne Jansen 
850b89f6d1fSFilipe Manana 	/*
851b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
852b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
853b89f6d1fSFilipe Manana 	 */
854b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
85596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
856b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
85720897f5cSArne Jansen 	if (!root)
85820897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
85920897f5cSArne Jansen 
86020897f5cSArne Jansen 	root->root_key.objectid = objectid;
86120897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
86220897f5cSArne Jansen 	root->root_key.offset = 0;
86320897f5cSArne Jansen 
8649631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
8659631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
86620897f5cSArne Jansen 	if (IS_ERR(leaf)) {
86720897f5cSArne Jansen 		ret = PTR_ERR(leaf);
8681dd05682STsutomu Itoh 		leaf = NULL;
869c1b07854SPeng Hao 		goto fail;
87020897f5cSArne Jansen 	}
87120897f5cSArne Jansen 
87220897f5cSArne Jansen 	root->node = leaf;
87320897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
87420897f5cSArne Jansen 
87520897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
87627cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
87720897f5cSArne Jansen 
878f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
879f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
88020897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
88120897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
88220897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
88320897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
88420897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
88520897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
88620897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
88733d85fdaSQu Wenruo 	if (is_fstree(objectid))
888807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
889807fc790SAndy Shevchenko 	else
890807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
891c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
89220897f5cSArne Jansen 
8938a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
8948a6a87cdSBoris Burkov 
89520897f5cSArne Jansen 	key.objectid = objectid;
89620897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
89720897f5cSArne Jansen 	key.offset = 0;
89820897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
89920897f5cSArne Jansen 	if (ret)
90020897f5cSArne Jansen 		goto fail;
90120897f5cSArne Jansen 
90220897f5cSArne Jansen 	return root;
9031dd05682STsutomu Itoh 
9048a6a87cdSBoris Burkov fail:
90500246528SJosef Bacik 	btrfs_put_root(root);
9061dd05682STsutomu Itoh 
9071dd05682STsutomu Itoh 	return ERR_PTR(ret);
90820897f5cSArne Jansen }
90920897f5cSArne Jansen 
9107237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
911e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
9120f7d52f4SChris Mason {
9130f7d52f4SChris Mason 	struct btrfs_root *root;
914e02119d5SChris Mason 
91596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
916e02119d5SChris Mason 	if (!root)
9177237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
918e02119d5SChris Mason 
919e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
920e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
921e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
92227cdeb70SMiao Xie 
9236ab6ebb7SNaohiro Aota 	return root;
9246ab6ebb7SNaohiro Aota }
9256ab6ebb7SNaohiro Aota 
9266ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
9276ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
9286ab6ebb7SNaohiro Aota {
9296ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
9306ab6ebb7SNaohiro Aota 
9317237f183SYan Zheng 	/*
93292a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
93327cdeb70SMiao Xie 	 *
93492a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
93592a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
93692a7cc42SQu Wenruo 	 *
93792a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
93892a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
9397237f183SYan Zheng 	 */
940e02119d5SChris Mason 
9414d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
9429631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
9436ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
9446ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
945e02119d5SChris Mason 
9467237f183SYan Zheng 	root->node = leaf;
947e02119d5SChris Mason 
948e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
949e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
9506ab6ebb7SNaohiro Aota 
9516ab6ebb7SNaohiro Aota 	return 0;
9527237f183SYan Zheng }
9537237f183SYan Zheng 
9547237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
9557237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
9567237f183SYan Zheng {
9577237f183SYan Zheng 	struct btrfs_root *log_root;
9587237f183SYan Zheng 
9597237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
9607237f183SYan Zheng 	if (IS_ERR(log_root))
9617237f183SYan Zheng 		return PTR_ERR(log_root);
9626ab6ebb7SNaohiro Aota 
9633ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
9643ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
9653ddebf27SNaohiro Aota 
9666ab6ebb7SNaohiro Aota 		if (ret) {
9676ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
9686ab6ebb7SNaohiro Aota 			return ret;
9696ab6ebb7SNaohiro Aota 		}
9703ddebf27SNaohiro Aota 	}
9716ab6ebb7SNaohiro Aota 
9727237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
9737237f183SYan Zheng 	fs_info->log_root_tree = log_root;
9747237f183SYan Zheng 	return 0;
9757237f183SYan Zheng }
9767237f183SYan Zheng 
9777237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
9787237f183SYan Zheng 		       struct btrfs_root *root)
9797237f183SYan Zheng {
9800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9817237f183SYan Zheng 	struct btrfs_root *log_root;
9827237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
9836ab6ebb7SNaohiro Aota 	int ret;
9847237f183SYan Zheng 
9850b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
9867237f183SYan Zheng 	if (IS_ERR(log_root))
9877237f183SYan Zheng 		return PTR_ERR(log_root);
9887237f183SYan Zheng 
9896ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
9906ab6ebb7SNaohiro Aota 	if (ret) {
9916ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
9926ab6ebb7SNaohiro Aota 		return ret;
9936ab6ebb7SNaohiro Aota 	}
9946ab6ebb7SNaohiro Aota 
9957237f183SYan Zheng 	log_root->last_trans = trans->transid;
9967237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
9977237f183SYan Zheng 
9987237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
9993cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
10003cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
10013cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1002da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
10030b246afaSJeff Mahoney 				     fs_info->nodesize);
10043cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
10057237f183SYan Zheng 
10065d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
10077237f183SYan Zheng 
10087237f183SYan Zheng 	WARN_ON(root->log_root);
10097237f183SYan Zheng 	root->log_root = log_root;
10107237f183SYan Zheng 	root->log_transid = 0;
1011d1433debSMiao Xie 	root->log_transid_committed = -1;
1012257c62e1SChris Mason 	root->last_log_commit = 0;
1013e02119d5SChris Mason 	return 0;
1014e02119d5SChris Mason }
1015e02119d5SChris Mason 
101649d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
101749d11beaSJosef Bacik 					      struct btrfs_path *path,
1018cb517eabSMiao Xie 					      struct btrfs_key *key)
1019e02119d5SChris Mason {
1020e02119d5SChris Mason 	struct btrfs_root *root;
1021789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1022e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
102384234f3aSYan Zheng 	u64 generation;
1024cb517eabSMiao Xie 	int ret;
1025581c1760SQu Wenruo 	int level;
1026cb517eabSMiao Xie 
102796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
102849d11beaSJosef Bacik 	if (!root)
102949d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
10300f7d52f4SChris Mason 
1031cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1032cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
10330f7d52f4SChris Mason 	if (ret) {
103413a8a7c8SYan, Zheng 		if (ret > 0)
103513a8a7c8SYan, Zheng 			ret = -ENOENT;
103649d11beaSJosef Bacik 		goto fail;
10370f7d52f4SChris Mason 	}
103813a8a7c8SYan, Zheng 
103984234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1040581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
1041789d6a3aSQu Wenruo 	check.level = level;
1042789d6a3aSQu Wenruo 	check.transid = generation;
1043789d6a3aSQu Wenruo 	check.owner_root = key->objectid;
1044789d6a3aSQu Wenruo 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1045789d6a3aSQu Wenruo 				     &check);
104664c043deSLiu Bo 	if (IS_ERR(root->node)) {
104764c043deSLiu Bo 		ret = PTR_ERR(root->node);
10488c38938cSJosef Bacik 		root->node = NULL;
104949d11beaSJosef Bacik 		goto fail;
10504eb150d6SQu Wenruo 	}
10514eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1052cb517eabSMiao Xie 		ret = -EIO;
105349d11beaSJosef Bacik 		goto fail;
1054416bc658SJosef Bacik 	}
105588c602abSQu Wenruo 
105688c602abSQu Wenruo 	/*
105788c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
105888c602abSQu Wenruo 	 * match its root node owner
105988c602abSQu Wenruo 	 */
106088c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
106188c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
106288c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
106388c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
106488c602abSQu Wenruo 		btrfs_crit(fs_info,
106588c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
106688c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
106788c602abSQu Wenruo 			   btrfs_header_owner(root->node),
106888c602abSQu Wenruo 			   root->root_key.objectid);
106988c602abSQu Wenruo 		ret = -EUCLEAN;
107088c602abSQu Wenruo 		goto fail;
107188c602abSQu Wenruo 	}
10725d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1073cb517eabSMiao Xie 	return root;
107449d11beaSJosef Bacik fail:
107500246528SJosef Bacik 	btrfs_put_root(root);
107649d11beaSJosef Bacik 	return ERR_PTR(ret);
107749d11beaSJosef Bacik }
107849d11beaSJosef Bacik 
107949d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
108049d11beaSJosef Bacik 					struct btrfs_key *key)
108149d11beaSJosef Bacik {
108249d11beaSJosef Bacik 	struct btrfs_root *root;
108349d11beaSJosef Bacik 	struct btrfs_path *path;
108449d11beaSJosef Bacik 
108549d11beaSJosef Bacik 	path = btrfs_alloc_path();
108649d11beaSJosef Bacik 	if (!path)
108749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
108849d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
108949d11beaSJosef Bacik 	btrfs_free_path(path);
109049d11beaSJosef Bacik 
109149d11beaSJosef Bacik 	return root;
1092cb517eabSMiao Xie }
1093cb517eabSMiao Xie 
10942dfb1e43SQu Wenruo /*
10952dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
10962dfb1e43SQu Wenruo  *
10972dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
10982dfb1e43SQu Wenruo  */
10992dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1100cb517eabSMiao Xie {
1101cb517eabSMiao Xie 	int ret;
1102cb517eabSMiao Xie 
11030b548539SDavid Sterba 	btrfs_drew_lock_init(&root->snapshot_lock);
11048257b2dcSMiao Xie 
1105aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
110637f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
110792a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1108f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1109f39e4571SJosef Bacik 	}
1110f39e4571SJosef Bacik 
1111851fd730SQu Wenruo 	/*
1112851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1113851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1114851fd730SQu Wenruo 	 */
1115851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1116851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
11172dfb1e43SQu Wenruo 		if (!anon_dev) {
1118cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1119cb517eabSMiao Xie 			if (ret)
1120876d2cf1SLiu Bo 				goto fail;
11212dfb1e43SQu Wenruo 		} else {
11222dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
11232dfb1e43SQu Wenruo 		}
1124851fd730SQu Wenruo 	}
1125f32e48e9SChandan Rajendra 
1126f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1127453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1128f32e48e9SChandan Rajendra 	if (ret) {
1129f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1130876d2cf1SLiu Bo 		goto fail;
1131f32e48e9SChandan Rajendra 	}
1132f32e48e9SChandan Rajendra 
11336b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1134f32e48e9SChandan Rajendra 
1135f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1136f32e48e9SChandan Rajendra 
1137cb517eabSMiao Xie 	return 0;
1138cb517eabSMiao Xie fail:
113984db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1140cb517eabSMiao Xie 	return ret;
1141cb517eabSMiao Xie }
1142cb517eabSMiao Xie 
1143a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1144cb517eabSMiao Xie 					       u64 root_id)
1145cb517eabSMiao Xie {
1146cb517eabSMiao Xie 	struct btrfs_root *root;
1147cb517eabSMiao Xie 
1148fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1149fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1150fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
115100246528SJosef Bacik 	root = btrfs_grab_root(root);
1152fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1153cb517eabSMiao Xie 	return root;
1154cb517eabSMiao Xie }
1155cb517eabSMiao Xie 
115649d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
115749d11beaSJosef Bacik 						u64 objectid)
115849d11beaSJosef Bacik {
1159abed4aaaSJosef Bacik 	struct btrfs_key key = {
1160abed4aaaSJosef Bacik 		.objectid = objectid,
1161abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1162abed4aaaSJosef Bacik 		.offset = 0,
1163abed4aaaSJosef Bacik 	};
1164abed4aaaSJosef Bacik 
1165e91909aaSChristoph Hellwig 	switch (objectid) {
1166e91909aaSChristoph Hellwig 	case BTRFS_ROOT_TREE_OBJECTID:
116749d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
1168e91909aaSChristoph Hellwig 	case BTRFS_EXTENT_TREE_OBJECTID:
1169abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1170e91909aaSChristoph Hellwig 	case BTRFS_CHUNK_TREE_OBJECTID:
117149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
1172e91909aaSChristoph Hellwig 	case BTRFS_DEV_TREE_OBJECTID:
117349d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
1174e91909aaSChristoph Hellwig 	case BTRFS_CSUM_TREE_OBJECTID:
1175abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1176e91909aaSChristoph Hellwig 	case BTRFS_QUOTA_TREE_OBJECTID:
117785724171SChristoph Hellwig 		return btrfs_grab_root(fs_info->quota_root);
1178e91909aaSChristoph Hellwig 	case BTRFS_UUID_TREE_OBJECTID:
117985724171SChristoph Hellwig 		return btrfs_grab_root(fs_info->uuid_root);
1180e91909aaSChristoph Hellwig 	case BTRFS_BLOCK_GROUP_TREE_OBJECTID:
118185724171SChristoph Hellwig 		return btrfs_grab_root(fs_info->block_group_root);
1182e91909aaSChristoph Hellwig 	case BTRFS_FREE_SPACE_TREE_OBJECTID:
118385724171SChristoph Hellwig 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1184e91909aaSChristoph Hellwig 	default:
118549d11beaSJosef Bacik 		return NULL;
118649d11beaSJosef Bacik 	}
1187e91909aaSChristoph Hellwig }
118849d11beaSJosef Bacik 
1189cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1190cb517eabSMiao Xie 			 struct btrfs_root *root)
1191cb517eabSMiao Xie {
1192cb517eabSMiao Xie 	int ret;
1193cb517eabSMiao Xie 
1194fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1195fc7cbcd4SDavid Sterba 	if (ret)
1196fc7cbcd4SDavid Sterba 		return ret;
1197fc7cbcd4SDavid Sterba 
1198fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1199fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1200fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1201fc7cbcd4SDavid Sterba 				root);
1202af01d2e5SJosef Bacik 	if (ret == 0) {
120300246528SJosef Bacik 		btrfs_grab_root(root);
1204fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1205af01d2e5SJosef Bacik 	}
1206fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1207fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1208cb517eabSMiao Xie 
1209cb517eabSMiao Xie 	return ret;
1210cb517eabSMiao Xie }
1211cb517eabSMiao Xie 
1212bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1213bd647ce3SJosef Bacik {
1214bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1215bd647ce3SJosef Bacik 	struct btrfs_root *root;
1216bd647ce3SJosef Bacik 
1217bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1218457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1219457f1864SJosef Bacik 
1220bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1221bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1222457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
122371008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1224bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1225bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
122600246528SJosef Bacik 			btrfs_put_root(root);
122700246528SJosef Bacik 		btrfs_put_root(root);
1228bd647ce3SJosef Bacik 	}
1229bd647ce3SJosef Bacik #endif
1230bd647ce3SJosef Bacik }
1231bd647ce3SJosef Bacik 
1232abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1233abed4aaaSJosef Bacik {
1234abed4aaaSJosef Bacik 	struct btrfs_root *root;
1235abed4aaaSJosef Bacik 	struct rb_node *node;
1236abed4aaaSJosef Bacik 
1237abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1238abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1239abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1240abed4aaaSJosef Bacik 		btrfs_put_root(root);
1241abed4aaaSJosef Bacik 	}
1242abed4aaaSJosef Bacik }
1243abed4aaaSJosef Bacik 
12440d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
12450d4b0463SJosef Bacik {
1246141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1247141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
12485deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1249141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1250141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1251141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1252141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
12530d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
12540d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1255abed4aaaSJosef Bacik 	free_global_roots(fs_info);
125600246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
125700246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
125800246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
125900246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
126000246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
126100246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1262aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
12639c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1264bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
12653fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
12660d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
12670d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
12688481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
12690d4b0463SJosef Bacik 	kvfree(fs_info);
12700d4b0463SJosef Bacik }
12710d4b0463SJosef Bacik 
12720d4b0463SJosef Bacik 
12732dfb1e43SQu Wenruo /*
12742dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
12752dfb1e43SQu Wenruo  *
12762dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
12772dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
12782dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
12792dfb1e43SQu Wenruo  *
12802dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
12812dfb1e43SQu Wenruo  *
12822dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
12832dfb1e43SQu Wenruo  *	 same root objectid.
12842dfb1e43SQu Wenruo  *
12852dfb1e43SQu Wenruo  * @objectid:	root id
12862dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
12872dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
12882dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
12892dfb1e43SQu Wenruo  *		for orphan roots
12902dfb1e43SQu Wenruo  */
12912dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
12922dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
12932dfb1e43SQu Wenruo 					     bool check_ref)
12945eda7b5eSChris Mason {
12955eda7b5eSChris Mason 	struct btrfs_root *root;
1296381cf658SDavid Sterba 	struct btrfs_path *path;
12971d4c08e0SDavid Sterba 	struct btrfs_key key;
12985eda7b5eSChris Mason 	int ret;
12995eda7b5eSChris Mason 
130049d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
130149d11beaSJosef Bacik 	if (root)
130249d11beaSJosef Bacik 		return root;
13034df27c4dSYan, Zheng again:
130456e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
130548475471SStefan Behrens 	if (root) {
13062dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
13072dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1308bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
130900246528SJosef Bacik 			btrfs_put_root(root);
131048475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1311bc44d7c4SJosef Bacik 		}
13125eda7b5eSChris Mason 		return root;
131348475471SStefan Behrens 	}
13145eda7b5eSChris Mason 
131556e9357aSDavid Sterba 	key.objectid = objectid;
131656e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
131756e9357aSDavid Sterba 	key.offset = (u64)-1;
131856e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
13195eda7b5eSChris Mason 	if (IS_ERR(root))
13205eda7b5eSChris Mason 		return root;
13213394e160SChris Mason 
1322c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1323d68fc57bSYan, Zheng 		ret = -ENOENT;
1324d68fc57bSYan, Zheng 		goto fail;
1325d68fc57bSYan, Zheng 	}
1326d68fc57bSYan, Zheng 
13272dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1328cb517eabSMiao Xie 	if (ret)
1329cb517eabSMiao Xie 		goto fail;
1330cb517eabSMiao Xie 
1331381cf658SDavid Sterba 	path = btrfs_alloc_path();
1332381cf658SDavid Sterba 	if (!path) {
1333381cf658SDavid Sterba 		ret = -ENOMEM;
1334381cf658SDavid Sterba 		goto fail;
1335381cf658SDavid Sterba 	}
13361d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
13371d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
133856e9357aSDavid Sterba 	key.offset = objectid;
13391d4c08e0SDavid Sterba 
13401d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1341381cf658SDavid Sterba 	btrfs_free_path(path);
1342d68fc57bSYan, Zheng 	if (ret < 0)
1343d68fc57bSYan, Zheng 		goto fail;
1344d68fc57bSYan, Zheng 	if (ret == 0)
134527cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1346d68fc57bSYan, Zheng 
1347cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
13480f7d52f4SChris Mason 	if (ret) {
1349168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
135000246528SJosef Bacik 			btrfs_put_root(root);
13514df27c4dSYan, Zheng 			goto again;
1352168a2f77SJia-Ju Bai 		}
13534df27c4dSYan, Zheng 		goto fail;
13544df27c4dSYan, Zheng 	}
1355edbd8d4eSChris Mason 	return root;
13564df27c4dSYan, Zheng fail:
135733fab972SFilipe Manana 	/*
135833fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1359143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
136033fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
136133fab972SFilipe Manana 	 * and once again by our caller.
136233fab972SFilipe Manana 	 */
136333fab972SFilipe Manana 	if (anon_dev)
136433fab972SFilipe Manana 		root->anon_dev = 0;
13658c38938cSJosef Bacik 	btrfs_put_root(root);
13664df27c4dSYan, Zheng 	return ERR_PTR(ret);
1367edbd8d4eSChris Mason }
1368edbd8d4eSChris Mason 
13692dfb1e43SQu Wenruo /*
13702dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
13712dfb1e43SQu Wenruo  *
13722dfb1e43SQu Wenruo  * @objectid:	tree objectid
13732dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
13742dfb1e43SQu Wenruo  *		one reference
13752dfb1e43SQu Wenruo  */
13762dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
13772dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
13782dfb1e43SQu Wenruo {
13792dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
13802dfb1e43SQu Wenruo }
13812dfb1e43SQu Wenruo 
13822dfb1e43SQu Wenruo /*
13832dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
13842dfb1e43SQu Wenruo  * the anonymous block device id
13852dfb1e43SQu Wenruo  *
13862dfb1e43SQu Wenruo  * @objectid:	tree objectid
13872dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
13882dfb1e43SQu Wenruo  *		parameter value
13892dfb1e43SQu Wenruo  */
13902dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
13912dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
13922dfb1e43SQu Wenruo {
13932dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
13942dfb1e43SQu Wenruo }
13952dfb1e43SQu Wenruo 
13968b712842SChris Mason /*
139749d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
139849d11beaSJosef Bacik  * @fs_info:	the fs_info
139949d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
140049d11beaSJosef Bacik  *
140149d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
140249d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
140349d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
140449d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
140549d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
140649d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
140749d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
140849d11beaSJosef Bacik  * backref code is finished using the root.
140949d11beaSJosef Bacik  */
141049d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
141149d11beaSJosef Bacik 						 struct btrfs_path *path,
141249d11beaSJosef Bacik 						 u64 objectid)
141349d11beaSJosef Bacik {
141449d11beaSJosef Bacik 	struct btrfs_root *root;
141549d11beaSJosef Bacik 	struct btrfs_key key;
141649d11beaSJosef Bacik 
141749d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
141849d11beaSJosef Bacik 
141949d11beaSJosef Bacik 	/*
142049d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
142149d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
142249d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
142349d11beaSJosef Bacik 	 * != NULL just return it.
142449d11beaSJosef Bacik 	 */
142549d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
142649d11beaSJosef Bacik 	if (root)
142749d11beaSJosef Bacik 		return root;
142849d11beaSJosef Bacik 
142949d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
143049d11beaSJosef Bacik 	if (root)
143149d11beaSJosef Bacik 		return root;
143249d11beaSJosef Bacik 
143349d11beaSJosef Bacik 	key.objectid = objectid;
143449d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
143549d11beaSJosef Bacik 	key.offset = (u64)-1;
143649d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
143749d11beaSJosef Bacik 	btrfs_release_path(path);
143849d11beaSJosef Bacik 
143949d11beaSJosef Bacik 	return root;
144049d11beaSJosef Bacik }
144149d11beaSJosef Bacik 
1442a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1443a74a4b97SChris Mason {
14440d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1445d0278245SMiao Xie 	int again;
1446a74a4b97SChris Mason 
1447d6fd0ae2SOmar Sandoval 	while (1) {
1448d0278245SMiao Xie 		again = 0;
14499d1a2a3aSDavid Sterba 
1450fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1451fd340d0fSJosef Bacik 
1452d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
14532ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1454d0278245SMiao Xie 			goto sleep;
1455d0278245SMiao Xie 
145690c711abSZygo Blaxell 		/*
145790c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
145890c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
145990c711abSZygo Blaxell 		 */
14600b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
146190c711abSZygo Blaxell 			goto sleep;
146290c711abSZygo Blaxell 
14630b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1464d0278245SMiao Xie 			goto sleep;
1465d0278245SMiao Xie 
1466dc7f370cSMiao Xie 		/*
1467dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1468dc7f370cSMiao Xie 		 * during the above check and trylock.
1469dc7f370cSMiao Xie 		 */
14702ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
14710b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1472dc7f370cSMiao Xie 			goto sleep;
1473dc7f370cSMiao Xie 		}
1474dc7f370cSMiao Xie 
1475b7625f46SQu Wenruo 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1476b7625f46SQu Wenruo 			btrfs_sysfs_feature_update(fs_info);
1477b7625f46SQu Wenruo 
14782ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1479c2d6cb16SFilipe Manana 
148033c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
14810b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1482a74a4b97SChris Mason 
1483d0278245SMiao Xie 		/*
148405323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
148505323cd1SMiao Xie 		 * needn't do anything special here.
1486d0278245SMiao Xie 		 */
14870b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
148867c5e7d4SFilipe Manana 
148967c5e7d4SFilipe Manana 		/*
1490f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
149167c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
149267c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1493f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
149467c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
149567c5e7d4SFilipe Manana 		 * unused block groups.
149667c5e7d4SFilipe Manana 		 */
14970b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
149818bb8bbfSJohannes Thumshirn 
149918bb8bbfSJohannes Thumshirn 		/*
150018bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
150118bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
150218bb8bbfSJohannes Thumshirn 		 * space.
150318bb8bbfSJohannes Thumshirn 		 */
150418bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1505d0278245SMiao Xie sleep:
1506a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1507d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1508d6fd0ae2SOmar Sandoval 			kthread_parkme();
1509d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1510d6fd0ae2SOmar Sandoval 			return 0;
1511838fe188SJiri Kosina 		if (!again) {
1512a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1513a74a4b97SChris Mason 			schedule();
1514a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1515a74a4b97SChris Mason 		}
1516da288d28SFilipe Manana 	}
1517a74a4b97SChris Mason }
1518a74a4b97SChris Mason 
1519a74a4b97SChris Mason static int transaction_kthread(void *arg)
1520a74a4b97SChris Mason {
1521a74a4b97SChris Mason 	struct btrfs_root *root = arg;
15220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1523a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1524a74a4b97SChris Mason 	struct btrfs_transaction *cur;
15258929ecfaSYan, Zheng 	u64 transid;
1526643900beSNikolay Borisov 	time64_t delta;
1527a74a4b97SChris Mason 	unsigned long delay;
1528914b2007SJan Kara 	bool cannot_commit;
1529a74a4b97SChris Mason 
1530a74a4b97SChris Mason 	do {
1531914b2007SJan Kara 		cannot_commit = false;
1532ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
15330b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1534a74a4b97SChris Mason 
15350b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
15360b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1537a74a4b97SChris Mason 		if (!cur) {
15380b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1539a74a4b97SChris Mason 			goto sleep;
1540a74a4b97SChris Mason 		}
154131153d81SYan Zheng 
1542643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1543fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1544fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1545643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
15460b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1547fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1548fb8a7e94SNikolay Borisov 			delay = min(delay,
1549fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1550a74a4b97SChris Mason 			goto sleep;
1551a74a4b97SChris Mason 		}
15528929ecfaSYan, Zheng 		transid = cur->transid;
15530b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
155456bec294SChris Mason 
155579787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1556354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1557914b2007SJan Kara 		if (IS_ERR(trans)) {
1558354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1559914b2007SJan Kara 				cannot_commit = true;
156079787eaaSJeff Mahoney 			goto sleep;
1561914b2007SJan Kara 		}
15628929ecfaSYan, Zheng 		if (transid == trans->transid) {
15633a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
15648929ecfaSYan, Zheng 		} else {
15653a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
15668929ecfaSYan, Zheng 		}
1567a74a4b97SChris Mason sleep:
15680b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
15690b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1570a74a4b97SChris Mason 
157184961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
15722ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
15738929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
15740b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1575914b2007SJan Kara 				 cannot_commit))
1576bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1577a74a4b97SChris Mason 	} while (!kthread_should_stop());
1578a74a4b97SChris Mason 	return 0;
1579a74a4b97SChris Mason }
1580a74a4b97SChris Mason 
1581af31f5e5SChris Mason /*
158201f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
158301f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
158401f0f9daSNikolay Borisov  * anything.
1585af31f5e5SChris Mason  *
1586af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1587af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1588af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1589af31f5e5SChris Mason  */
159001f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1591af31f5e5SChris Mason {
159201f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1593af31f5e5SChris Mason 	u64 cur;
1594af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1595af31f5e5SChris Mason 	int i;
1596af31f5e5SChris Mason 
1597af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1598af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1599af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1600af31f5e5SChris Mason 		if (cur == newest_gen)
160101f0f9daSNikolay Borisov 			return i;
1602af31f5e5SChris Mason 	}
1603af31f5e5SChris Mason 
160401f0f9daSNikolay Borisov 	return -EINVAL;
1605af31f5e5SChris Mason }
1606af31f5e5SChris Mason 
1607af31f5e5SChris Mason /*
1608af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1609af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1610af31f5e5SChris Mason  * done
1611af31f5e5SChris Mason  */
1612af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1613af31f5e5SChris Mason {
16146ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1615af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1616af31f5e5SChris Mason 
1617af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1618af31f5e5SChris Mason 
1619af31f5e5SChris Mason 	/*
1620af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1621af31f5e5SChris Mason 	 * regardless of which ones we use today
1622af31f5e5SChris Mason 	 */
1623af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1624af31f5e5SChris Mason 
1625af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1626af31f5e5SChris Mason 
1627af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1628af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1629af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1630af31f5e5SChris Mason 
1631af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1632af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1633af31f5e5SChris Mason 
1634af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1635af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1636af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1637af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1638af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1639af31f5e5SChris Mason 
16401c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
16419c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1642f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
16439c54e80dSJosef Bacik 
16449c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
16459c54e80dSJosef Bacik 					     extent_root->node->start);
1646af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
164729cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
1648af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
164929cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
1650af31f5e5SChris Mason 
1651f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1652f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
1653f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
1654f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
1655f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
16569c54e80dSJosef Bacik 	}
1657af31f5e5SChris Mason 
16587c7e82a7SChris Mason 	/*
16597c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
16607c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
16617c7e82a7SChris Mason 	 */
16627c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
16637c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
16647c7e82a7SChris Mason 					 info->fs_root->node->start);
1665af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1666af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1667af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1668af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
16697c7e82a7SChris Mason 	}
1670af31f5e5SChris Mason 
1671af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1672af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1673af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1674af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1675af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1676af31f5e5SChris Mason 
1677af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1678af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1679af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1680af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1681af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1682af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1683af31f5e5SChris Mason 
1684af31f5e5SChris Mason 	/*
1685af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1686af31f5e5SChris Mason 	 * for the next commit
1687af31f5e5SChris Mason 	 */
1688af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1689af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1690af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1691af31f5e5SChris Mason }
1692af31f5e5SChris Mason 
1693af31f5e5SChris Mason /*
1694bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1695bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1696bd2336b2SNikolay Borisov  *
1697bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1698bd2336b2SNikolay Borisov  * priority - priority of backup root required
1699bd2336b2SNikolay Borisov  *
1700bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1701bd2336b2SNikolay Borisov  */
1702bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1703bd2336b2SNikolay Borisov {
1704bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1705bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1706bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1707bd2336b2SNikolay Borisov 
1708bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1709bd2336b2SNikolay Borisov 		if (priority == 0)
1710bd2336b2SNikolay Borisov 			return backup_index;
1711bd2336b2SNikolay Borisov 
1712bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1713bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1714bd2336b2SNikolay Borisov 	} else {
1715bd2336b2SNikolay Borisov 		return -EINVAL;
1716bd2336b2SNikolay Borisov 	}
1717bd2336b2SNikolay Borisov 
1718bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1719bd2336b2SNikolay Borisov 
1720bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1721bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1722bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1723bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1724bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1725bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1726bd2336b2SNikolay Borisov 
1727bd2336b2SNikolay Borisov 	/*
1728bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1729bd2336b2SNikolay Borisov 	 * need a fsck
1730bd2336b2SNikolay Borisov 	 */
1731bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1732bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1733bd2336b2SNikolay Borisov 
1734bd2336b2SNikolay Borisov 	return backup_index;
1735bd2336b2SNikolay Borisov }
1736bd2336b2SNikolay Borisov 
17377abadb64SLiu Bo /* helper to cleanup workers */
17387abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
17397abadb64SLiu Bo {
1740dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1741afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
17425cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1743d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
1744d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
1745385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
1746385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
1747fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
1748fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
1749fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1750fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
17515b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1752e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1753a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1754fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1755b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1756b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1757a9b9477dSFilipe Manana 	/*
1758a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1759a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1760a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1761a9b9477dSFilipe Manana 	 */
1762d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
1763d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
17647abadb64SLiu Bo }
17657abadb64SLiu Bo 
17662e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
17672e9f5954SRashika {
17682e9f5954SRashika 	if (root) {
17692e9f5954SRashika 		free_extent_buffer(root->node);
17702e9f5954SRashika 		free_extent_buffer(root->commit_root);
17712e9f5954SRashika 		root->node = NULL;
17722e9f5954SRashika 		root->commit_root = NULL;
17732e9f5954SRashika 	}
17742e9f5954SRashika }
17752e9f5954SRashika 
1776abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1777abed4aaaSJosef Bacik {
1778abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
1779abed4aaaSJosef Bacik 
1780abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
1781abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
1782abed4aaaSJosef Bacik 					     rb_node)
1783abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
1784abed4aaaSJosef Bacik }
1785abed4aaaSJosef Bacik 
1786af31f5e5SChris Mason /* helper to cleanup tree roots */
17874273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1788af31f5e5SChris Mason {
17892e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1790655b09feSJosef Bacik 
1791abed4aaaSJosef Bacik 	free_global_root_pointers(info);
17922e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
17932e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
17942e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
17958c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
1796aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
17979c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
17984273eaffSAnand Jain 	if (free_chunk_root)
17992e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
1800af31f5e5SChris Mason }
1801af31f5e5SChris Mason 
18028c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
18038c38938cSJosef Bacik {
18048c38938cSJosef Bacik 	if (!root)
18058c38938cSJosef Bacik 		return;
18068c38938cSJosef Bacik 
18078c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
18088c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
18091dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
18108c38938cSJosef Bacik 		if (root->anon_dev)
18118c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
1812923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
18138c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1814fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
18158c38938cSJosef Bacik 		list_del_init(&root->leak_list);
1816fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
18178c38938cSJosef Bacik #endif
18188c38938cSJosef Bacik 		kfree(root);
18198c38938cSJosef Bacik 	}
18208c38938cSJosef Bacik }
18218c38938cSJosef Bacik 
1822faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1823171f6537SJosef Bacik {
1824fc7cbcd4SDavid Sterba 	int ret;
1825fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
1826fc7cbcd4SDavid Sterba 	int i;
1827171f6537SJosef Bacik 
1828171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
1829fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
1830171f6537SJosef Bacik 				     struct btrfs_root, root_list);
1831fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
1832171f6537SJosef Bacik 
1833fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1834fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1835fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
1836171f6537SJosef Bacik 	}
1837171f6537SJosef Bacik 
1838fc7cbcd4SDavid Sterba 	while (1) {
1839fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1840fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
1841fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
1842fc7cbcd4SDavid Sterba 		if (!ret)
1843fc7cbcd4SDavid Sterba 			break;
1844fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
1845fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1846171f6537SJosef Bacik 	}
1847171f6537SJosef Bacik }
1848af31f5e5SChris Mason 
1849638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1850638aa7edSEric Sandeen {
1851638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
1852638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
1853638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
1854638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
1855638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
1856638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
1857ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
1858638aa7edSEric Sandeen }
1859638aa7edSEric Sandeen 
1860779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1861779a65a4SEric Sandeen {
1862779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
1863779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
1864779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
1865779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
1866779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
1867779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
1868907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
1869779a65a4SEric Sandeen }
1870779a65a4SEric Sandeen 
1871dcb2137cSChristoph Hellwig static int btrfs_init_btree_inode(struct super_block *sb)
1872f37938e0SEric Sandeen {
1873dcb2137cSChristoph Hellwig 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1874e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1875e256927bSJosef Bacik 					      fs_info->tree_root);
1876dcb2137cSChristoph Hellwig 	struct inode *inode;
1877dcb2137cSChristoph Hellwig 
1878dcb2137cSChristoph Hellwig 	inode = new_inode(sb);
1879dcb2137cSChristoph Hellwig 	if (!inode)
1880dcb2137cSChristoph Hellwig 		return -ENOMEM;
18812ff7e61eSJeff Mahoney 
18822ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
18832ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
1884f37938e0SEric Sandeen 	/*
1885f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
1886f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
1887f37938e0SEric Sandeen 	 * the devices in the system
1888f37938e0SEric Sandeen 	 */
18892ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
18902ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
1891dcb2137cSChristoph Hellwig 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1892f37938e0SEric Sandeen 
18932ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
189443eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
189535da5a7eSDavid Sterba 			    IO_TREE_BTREE_INODE_IO);
18962ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1897f37938e0SEric Sandeen 
18985c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1899adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
1900adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
1901adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
19022ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1903e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
1904dcb2137cSChristoph Hellwig 	fs_info->btree_inode = inode;
1905dcb2137cSChristoph Hellwig 
1906dcb2137cSChristoph Hellwig 	return 0;
1907f37938e0SEric Sandeen }
1908f37938e0SEric Sandeen 
1909ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1910ad618368SEric Sandeen {
1911ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1912129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
19137f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1914ad618368SEric Sandeen }
1915ad618368SEric Sandeen 
1916f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1917f9e92e40SEric Sandeen {
1918f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
1919f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
1920f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
1921f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1922f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
1923f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
1924d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
1925011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
1926f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
1927f9e92e40SEric Sandeen }
1928f9e92e40SEric Sandeen 
1929d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
19302a458198SEric Sandeen {
1931f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
19326f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
193358e814fcSTejun Heo 	unsigned int ordered_flags = WQ_MEM_RECLAIM | WQ_FREEZABLE;
19342a458198SEric Sandeen 
19352a458198SEric Sandeen 	fs_info->workers =
1936a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
19372a458198SEric Sandeen 
19382a458198SEric Sandeen 	fs_info->delalloc_workers =
1939cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
1940cb001095SJeff Mahoney 				      flags, max_active, 2);
19412a458198SEric Sandeen 
19422a458198SEric Sandeen 	fs_info->flush_workers =
1943cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1944cb001095SJeff Mahoney 				      flags, max_active, 0);
19452a458198SEric Sandeen 
19462a458198SEric Sandeen 	fs_info->caching_workers =
1947cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
19482a458198SEric Sandeen 
19492a458198SEric Sandeen 	fs_info->fixup_workers =
195058e814fcSTejun Heo 		btrfs_alloc_ordered_workqueue(fs_info, "fixup", ordered_flags);
19512a458198SEric Sandeen 
19522a458198SEric Sandeen 	fs_info->endio_workers =
1953d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
19542a458198SEric Sandeen 	fs_info->endio_meta_workers =
1955d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
1956385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
19572a458198SEric Sandeen 	fs_info->endio_write_workers =
1958cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1959cb001095SJeff Mahoney 				      max_active, 2);
1960fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
1961fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
19622a458198SEric Sandeen 	fs_info->endio_freespace_worker =
1963cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
1964cb001095SJeff Mahoney 				      max_active, 0);
19652a458198SEric Sandeen 	fs_info->delayed_workers =
1966cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1967cb001095SJeff Mahoney 				      max_active, 0);
19682a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
196958e814fcSTejun Heo 		btrfs_alloc_ordered_workqueue(fs_info, "qgroup-rescan",
197058e814fcSTejun Heo 					      ordered_flags);
1971b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
197258e814fcSTejun Heo 		alloc_ordered_workqueue("btrfs_discard", WQ_FREEZABLE);
19732a458198SEric Sandeen 
19748bfec2e4SChristoph Hellwig 	if (!(fs_info->workers &&
1975a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
19762a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
1977fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
19781a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
19792a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
1980f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
1981f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
1982b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
19832a458198SEric Sandeen 		return -ENOMEM;
19842a458198SEric Sandeen 	}
19852a458198SEric Sandeen 
19862a458198SEric Sandeen 	return 0;
19872a458198SEric Sandeen }
19882a458198SEric Sandeen 
19896d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
19906d97c6e3SJohannes Thumshirn {
19916d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
1992b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
19936d97c6e3SJohannes Thumshirn 
1994b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
19956d97c6e3SJohannes Thumshirn 
19966d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
19976d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
1998b4e967beSDavid Sterba 			  csum_driver);
19996d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
20006d97c6e3SJohannes Thumshirn 	}
20016d97c6e3SJohannes Thumshirn 
20026d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
20036d97c6e3SJohannes Thumshirn 
200468d99ab0SChristoph Hellwig 	/*
200568d99ab0SChristoph Hellwig 	 * Check if the checksum implementation is a fast accelerated one.
200668d99ab0SChristoph Hellwig 	 * As-is this is a bit of a hack and should be replaced once the csum
200768d99ab0SChristoph Hellwig 	 * implementations provide that information themselves.
200868d99ab0SChristoph Hellwig 	 */
200968d99ab0SChristoph Hellwig 	switch (csum_type) {
201068d99ab0SChristoph Hellwig 	case BTRFS_CSUM_TYPE_CRC32:
201168d99ab0SChristoph Hellwig 		if (!strstr(crypto_shash_driver_name(csum_shash), "generic"))
201268d99ab0SChristoph Hellwig 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
201368d99ab0SChristoph Hellwig 		break;
2014*efcfcbc6SDavid Sterba 	case BTRFS_CSUM_TYPE_XXHASH:
2015*efcfcbc6SDavid Sterba 		set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2016*efcfcbc6SDavid Sterba 		break;
201768d99ab0SChristoph Hellwig 	default:
201868d99ab0SChristoph Hellwig 		break;
201968d99ab0SChristoph Hellwig 	}
202068d99ab0SChristoph Hellwig 
2021c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2022c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2023c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
20246d97c6e3SJohannes Thumshirn 	return 0;
20256d97c6e3SJohannes Thumshirn }
20266d97c6e3SJohannes Thumshirn 
202763443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
202863443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
202963443bf5SEric Sandeen {
203063443bf5SEric Sandeen 	int ret;
2031789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
203263443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
203363443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
203463443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2035581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
203663443bf5SEric Sandeen 
203763443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2038f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
203963443bf5SEric Sandeen 		return -EIO;
204063443bf5SEric Sandeen 	}
204163443bf5SEric Sandeen 
204296dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
204396dfcb46SJosef Bacik 					 GFP_KERNEL);
204463443bf5SEric Sandeen 	if (!log_tree_root)
204563443bf5SEric Sandeen 		return -ENOMEM;
204663443bf5SEric Sandeen 
2047789d6a3aSQu Wenruo 	check.level = level;
2048789d6a3aSQu Wenruo 	check.transid = fs_info->generation + 1;
2049789d6a3aSQu Wenruo 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2050789d6a3aSQu Wenruo 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
205164c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2052f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
20530eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
20548c38938cSJosef Bacik 		log_tree_root->node = NULL;
205500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
20560eeff236SLiu Bo 		return ret;
20574eb150d6SQu Wenruo 	}
20584eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2059f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
206000246528SJosef Bacik 		btrfs_put_root(log_tree_root);
206163443bf5SEric Sandeen 		return -EIO;
206263443bf5SEric Sandeen 	}
20634eb150d6SQu Wenruo 
206463443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
206563443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
206663443bf5SEric Sandeen 	if (ret) {
20670b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
206863443bf5SEric Sandeen 				      "Failed to recover log tree");
206900246528SJosef Bacik 		btrfs_put_root(log_tree_root);
207063443bf5SEric Sandeen 		return ret;
207163443bf5SEric Sandeen 	}
207263443bf5SEric Sandeen 
2073bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
20746bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
207563443bf5SEric Sandeen 		if (ret)
207663443bf5SEric Sandeen 			return ret;
207763443bf5SEric Sandeen 	}
207863443bf5SEric Sandeen 
207963443bf5SEric Sandeen 	return 0;
208063443bf5SEric Sandeen }
208163443bf5SEric Sandeen 
2082abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2083abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2084abed4aaaSJosef Bacik 				      const char *name)
2085abed4aaaSJosef Bacik {
2086abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2087abed4aaaSJosef Bacik 	struct btrfs_root *root;
2088f7238e50SJosef Bacik 	u64 max_global_id = 0;
2089abed4aaaSJosef Bacik 	int ret;
2090abed4aaaSJosef Bacik 	struct btrfs_key key = {
2091abed4aaaSJosef Bacik 		.objectid = objectid,
2092abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2093abed4aaaSJosef Bacik 		.offset = 0,
2094abed4aaaSJosef Bacik 	};
2095abed4aaaSJosef Bacik 	bool found = false;
2096abed4aaaSJosef Bacik 
2097abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2098abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2099abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2100abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2101abed4aaaSJosef Bacik 		return 0;
2102abed4aaaSJosef Bacik 	}
2103abed4aaaSJosef Bacik 
2104abed4aaaSJosef Bacik 	while (1) {
2105abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2106abed4aaaSJosef Bacik 		if (ret < 0)
2107abed4aaaSJosef Bacik 			break;
2108abed4aaaSJosef Bacik 
2109abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2110abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2111abed4aaaSJosef Bacik 			if (ret) {
2112abed4aaaSJosef Bacik 				if (ret > 0)
2113abed4aaaSJosef Bacik 					ret = 0;
2114abed4aaaSJosef Bacik 				break;
2115abed4aaaSJosef Bacik 			}
2116abed4aaaSJosef Bacik 		}
2117abed4aaaSJosef Bacik 		ret = 0;
2118abed4aaaSJosef Bacik 
2119abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2120abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2121abed4aaaSJosef Bacik 			break;
2122abed4aaaSJosef Bacik 		btrfs_release_path(path);
2123abed4aaaSJosef Bacik 
2124f7238e50SJosef Bacik 		/*
2125f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2126f7238e50SJosef Bacik 		 * everybody.
2127f7238e50SJosef Bacik 		 */
2128f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2129f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2130f7238e50SJosef Bacik 
2131abed4aaaSJosef Bacik 		found = true;
2132abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2133abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2134abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2135abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2136abed4aaaSJosef Bacik 			break;
2137abed4aaaSJosef Bacik 		}
2138abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2139abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2140abed4aaaSJosef Bacik 		if (ret) {
2141abed4aaaSJosef Bacik 			btrfs_put_root(root);
2142abed4aaaSJosef Bacik 			break;
2143abed4aaaSJosef Bacik 		}
2144abed4aaaSJosef Bacik 		key.offset++;
2145abed4aaaSJosef Bacik 	}
2146abed4aaaSJosef Bacik 	btrfs_release_path(path);
2147abed4aaaSJosef Bacik 
2148f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2149f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2150f7238e50SJosef Bacik 
2151abed4aaaSJosef Bacik 	if (!found || ret) {
2152abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2153abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2154abed4aaaSJosef Bacik 
2155abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2156abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2157abed4aaaSJosef Bacik 		else
2158abed4aaaSJosef Bacik 			ret = 0;
2159abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2160abed4aaaSJosef Bacik 	}
2161abed4aaaSJosef Bacik 	return ret;
2162abed4aaaSJosef Bacik }
2163abed4aaaSJosef Bacik 
2164abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2165abed4aaaSJosef Bacik {
2166abed4aaaSJosef Bacik 	struct btrfs_path *path;
2167abed4aaaSJosef Bacik 	int ret = 0;
2168abed4aaaSJosef Bacik 
2169abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2170abed4aaaSJosef Bacik 	if (!path)
2171abed4aaaSJosef Bacik 		return -ENOMEM;
2172abed4aaaSJosef Bacik 
2173abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2174abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2175abed4aaaSJosef Bacik 	if (ret)
2176abed4aaaSJosef Bacik 		goto out;
2177abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2178abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2179abed4aaaSJosef Bacik 	if (ret)
2180abed4aaaSJosef Bacik 		goto out;
2181abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2182abed4aaaSJosef Bacik 		goto out;
2183abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2184abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2185abed4aaaSJosef Bacik 					 "free space");
2186abed4aaaSJosef Bacik out:
2187abed4aaaSJosef Bacik 	btrfs_free_path(path);
2188abed4aaaSJosef Bacik 	return ret;
2189abed4aaaSJosef Bacik }
2190abed4aaaSJosef Bacik 
21916bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
21924bbcaa64SEric Sandeen {
21936bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2194a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
21954bbcaa64SEric Sandeen 	struct btrfs_key location;
21964bbcaa64SEric Sandeen 	int ret;
21974bbcaa64SEric Sandeen 
21986bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
21996bccf3abSJeff Mahoney 
2200abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2201abed4aaaSJosef Bacik 	if (ret)
2202abed4aaaSJosef Bacik 		return ret;
2203abed4aaaSJosef Bacik 
22044bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
22054bbcaa64SEric Sandeen 	location.offset = 0;
22064bbcaa64SEric Sandeen 
22071c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
220814033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
220914033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
221014033b08SQu Wenruo 		if (IS_ERR(root)) {
221114033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
221214033b08SQu Wenruo 				ret = PTR_ERR(root);
221314033b08SQu Wenruo 				goto out;
221414033b08SQu Wenruo 			}
221514033b08SQu Wenruo 		} else {
221614033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
221714033b08SQu Wenruo 			fs_info->block_group_root = root;
221814033b08SQu Wenruo 		}
221914033b08SQu Wenruo 	}
222014033b08SQu Wenruo 
222114033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2222a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2223f50f4353SLiu Bo 	if (IS_ERR(root)) {
222442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2225f50f4353SLiu Bo 			ret = PTR_ERR(root);
2226f50f4353SLiu Bo 			goto out;
2227f50f4353SLiu Bo 		}
222842437a63SJosef Bacik 	} else {
2229a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2230a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
223142437a63SJosef Bacik 	}
2232820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2233a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2234a8d1b164SJohannes Thumshirn 	if (ret)
2235a8d1b164SJohannes Thumshirn 		goto out;
22364bbcaa64SEric Sandeen 
2237aeb935a4SQu Wenruo 	/*
2238aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2239aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2240aeb935a4SQu Wenruo 	 */
224156e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
224256e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2243aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
224442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2245aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2246aeb935a4SQu Wenruo 			goto out;
2247aeb935a4SQu Wenruo 		}
224842437a63SJosef Bacik 	} else {
2249aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2250aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
225142437a63SJosef Bacik 	}
2252aeb935a4SQu Wenruo 
22534bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2254a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2255a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2256a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2257afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2258a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
22594bbcaa64SEric Sandeen 	}
22604bbcaa64SEric Sandeen 
22614bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2262a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2263a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
226442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2265a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
22664bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2267f50f4353SLiu Bo 				goto out;
226842437a63SJosef Bacik 		}
22694bbcaa64SEric Sandeen 	} else {
2270a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2271a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
22724bbcaa64SEric Sandeen 	}
22734bbcaa64SEric Sandeen 
22744bbcaa64SEric Sandeen 	return 0;
2275f50f4353SLiu Bo out:
2276f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2277f50f4353SLiu Bo 		   location.objectid, ret);
2278f50f4353SLiu Bo 	return ret;
22794bbcaa64SEric Sandeen }
22804bbcaa64SEric Sandeen 
2281069ec957SQu Wenruo /*
2282069ec957SQu Wenruo  * Real super block validation
2283069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2284069ec957SQu Wenruo  *
2285069ec957SQu Wenruo  * @sb:		super block to check
2286069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2287069ec957SQu Wenruo  * 		0	the primary (1st) sb
2288069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2289069ec957SQu Wenruo  * 	       -1	skip bytenr check
2290069ec957SQu Wenruo  */
2291a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2292069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
229321a852b0SQu Wenruo {
229421a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
229521a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
229621a852b0SQu Wenruo 	int ret = 0;
229721a852b0SQu Wenruo 
229821a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
229921a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
230021a852b0SQu Wenruo 		ret = -EINVAL;
230121a852b0SQu Wenruo 	}
230221a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
230321a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
230421a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
230521a852b0SQu Wenruo 		ret = -EINVAL;
230621a852b0SQu Wenruo 	}
230721a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
230821a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
230921a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
231021a852b0SQu Wenruo 		ret = -EINVAL;
231121a852b0SQu Wenruo 	}
231221a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
231321a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
231421a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
231521a852b0SQu Wenruo 		ret = -EINVAL;
231621a852b0SQu Wenruo 	}
231721a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
231821a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
231921a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
232021a852b0SQu Wenruo 		ret = -EINVAL;
232121a852b0SQu Wenruo 	}
232221a852b0SQu Wenruo 
232321a852b0SQu Wenruo 	/*
232421a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
232521a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
232621a852b0SQu Wenruo 	 */
232721a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
232821a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
232921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
233021a852b0SQu Wenruo 		ret = -EINVAL;
233121a852b0SQu Wenruo 	}
23320bb3eb3eSQu Wenruo 
23330bb3eb3eSQu Wenruo 	/*
23341a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
23351a42daabSQu Wenruo 	 *
23361a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
23371a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
23381a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
23391a42daabSQu Wenruo 	 * beginning.
23400bb3eb3eSQu Wenruo 	 */
23411a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
234221a852b0SQu Wenruo 		btrfs_err(fs_info,
23430bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
234421a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
234521a852b0SQu Wenruo 		ret = -EINVAL;
234621a852b0SQu Wenruo 	}
23470bb3eb3eSQu Wenruo 
234821a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
234921a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
235021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
235121a852b0SQu Wenruo 		ret = -EINVAL;
235221a852b0SQu Wenruo 	}
235321a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
235421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
235521a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
235621a852b0SQu Wenruo 		ret = -EINVAL;
235721a852b0SQu Wenruo 	}
235821a852b0SQu Wenruo 
235921a852b0SQu Wenruo 	/* Root alignment check */
236021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
236121a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
236221a852b0SQu Wenruo 			   btrfs_super_root(sb));
236321a852b0SQu Wenruo 		ret = -EINVAL;
236421a852b0SQu Wenruo 	}
236521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
236621a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
236721a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
236821a852b0SQu Wenruo 		ret = -EINVAL;
236921a852b0SQu Wenruo 	}
237021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
237121a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
237221a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
237321a852b0SQu Wenruo 		ret = -EINVAL;
237421a852b0SQu Wenruo 	}
237521a852b0SQu Wenruo 
2376aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2377aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2378aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2379aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2380aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2381aefd7f70SNikolay Borisov 		ret = -EINVAL;
2382aefd7f70SNikolay Borisov 	}
2383aefd7f70SNikolay Borisov 
2384aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2385aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2386aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2387aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2388aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2389aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2390aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2391aefd7f70SNikolay Borisov 		ret = -EINVAL;
2392aefd7f70SNikolay Borisov 	}
2393aefd7f70SNikolay Borisov 
239425984a5aSAnand Jain 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
239525984a5aSAnand Jain 		   BTRFS_FSID_SIZE) != 0) {
239625984a5aSAnand Jain 		btrfs_err(fs_info,
239725984a5aSAnand Jain 			"dev_item UUID does not match metadata fsid: %pU != %pU",
239825984a5aSAnand Jain 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
239925984a5aSAnand Jain 		ret = -EINVAL;
240025984a5aSAnand Jain 	}
240125984a5aSAnand Jain 
24021c56ab99SQu Wenruo 	/*
24031c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
24041c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
24051c56ab99SQu Wenruo 	 */
24061c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
24071c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
24081c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
24091c56ab99SQu Wenruo 		btrfs_err(fs_info,
24101c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
24111c56ab99SQu Wenruo 		ret = -EINVAL;
24121c56ab99SQu Wenruo 	}
24131c56ab99SQu Wenruo 
241421a852b0SQu Wenruo 	/*
241521a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
241621a852b0SQu Wenruo 	 * done later
241721a852b0SQu Wenruo 	 */
241821a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
241921a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
242021a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
242121a852b0SQu Wenruo 		ret = -EINVAL;
242221a852b0SQu Wenruo 	}
242321a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
242421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
242521a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
242621a852b0SQu Wenruo 		ret = -EINVAL;
242721a852b0SQu Wenruo 	}
242821a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
242921a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
243021a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
243121a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
243221a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
243321a852b0SQu Wenruo 		ret = -EINVAL;
243421a852b0SQu Wenruo 	}
243521a852b0SQu Wenruo 
2436069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2437069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
243821a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
243921a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
244021a852b0SQu Wenruo 		ret = -EINVAL;
244121a852b0SQu Wenruo 	}
244221a852b0SQu Wenruo 
244321a852b0SQu Wenruo 	/*
244421a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
244521a852b0SQu Wenruo 	 * and one chunk
244621a852b0SQu Wenruo 	 */
244721a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
244821a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
244921a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
245021a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
245121a852b0SQu Wenruo 		ret = -EINVAL;
245221a852b0SQu Wenruo 	}
245321a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
245421a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
245521a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
245621a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
245721a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
245821a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
245921a852b0SQu Wenruo 		ret = -EINVAL;
246021a852b0SQu Wenruo 	}
246121a852b0SQu Wenruo 
246221a852b0SQu Wenruo 	/*
246321a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
246421a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
246521a852b0SQu Wenruo 	 */
246621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
246721a852b0SQu Wenruo 		btrfs_warn(fs_info,
246821a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
246921a852b0SQu Wenruo 			btrfs_super_generation(sb),
247021a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
247121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
247221a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
247321a852b0SQu Wenruo 		btrfs_warn(fs_info,
247421a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
247521a852b0SQu Wenruo 			btrfs_super_generation(sb),
247621a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
247721a852b0SQu Wenruo 
247821a852b0SQu Wenruo 	return ret;
247921a852b0SQu Wenruo }
248021a852b0SQu Wenruo 
2481069ec957SQu Wenruo /*
2482069ec957SQu Wenruo  * Validation of super block at mount time.
2483069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2484069ec957SQu Wenruo  * flags will be skipped.
2485069ec957SQu Wenruo  */
2486069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2487069ec957SQu Wenruo {
2488a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2489069ec957SQu Wenruo }
2490069ec957SQu Wenruo 
249175cb857dSQu Wenruo /*
249275cb857dSQu Wenruo  * Validation of super block at write time.
249375cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
249475cb857dSQu Wenruo  * overwritten soon.
249575cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
249675cb857dSQu Wenruo  */
249775cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
249875cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
249975cb857dSQu Wenruo {
250075cb857dSQu Wenruo 	int ret;
250175cb857dSQu Wenruo 
2502a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
250375cb857dSQu Wenruo 	if (ret < 0)
250475cb857dSQu Wenruo 		goto out;
2505e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
250675cb857dSQu Wenruo 		ret = -EUCLEAN;
250775cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
250875cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
250975cb857dSQu Wenruo 		goto out;
251075cb857dSQu Wenruo 	}
251175cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
251275cb857dSQu Wenruo 		ret = -EUCLEAN;
251375cb857dSQu Wenruo 		btrfs_err(fs_info,
251475cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
251575cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
251675cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
251775cb857dSQu Wenruo 		goto out;
251875cb857dSQu Wenruo 	}
251975cb857dSQu Wenruo out:
252075cb857dSQu Wenruo 	if (ret < 0)
252175cb857dSQu Wenruo 		btrfs_err(fs_info,
252275cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
252375cb857dSQu Wenruo 	return ret;
252475cb857dSQu Wenruo }
252575cb857dSQu Wenruo 
2526bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2527bd676446SJosef Bacik {
2528789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2529789d6a3aSQu Wenruo 		.level = level,
2530789d6a3aSQu Wenruo 		.transid = gen,
2531789d6a3aSQu Wenruo 		.owner_root = root->root_key.objectid
2532789d6a3aSQu Wenruo 	};
2533bd676446SJosef Bacik 	int ret = 0;
2534bd676446SJosef Bacik 
2535789d6a3aSQu Wenruo 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2536bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2537bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2538bd676446SJosef Bacik 		root->node = NULL;
25394eb150d6SQu Wenruo 		return ret;
25404eb150d6SQu Wenruo 	}
25414eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2542bd676446SJosef Bacik 		free_extent_buffer(root->node);
2543bd676446SJosef Bacik 		root->node = NULL;
25444eb150d6SQu Wenruo 		return -EIO;
2545bd676446SJosef Bacik 	}
2546bd676446SJosef Bacik 
2547bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2548bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2549bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2550bd676446SJosef Bacik 	return ret;
2551bd676446SJosef Bacik }
2552bd676446SJosef Bacik 
2553bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2554bd676446SJosef Bacik {
2555bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2556bd676446SJosef Bacik 	u64 gen, bytenr;
2557bd676446SJosef Bacik 	int level, ret;
2558bd676446SJosef Bacik 
2559bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2560bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2561bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2562bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
25639c54e80dSJosef Bacik 	if (ret) {
2564bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2565bd676446SJosef Bacik 		return ret;
2566bd676446SJosef Bacik 	}
25679c54e80dSJosef Bacik 	return 0;
25689c54e80dSJosef Bacik }
25699c54e80dSJosef Bacik 
25706ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2571b8522a1eSNikolay Borisov {
25726ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2573b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2574b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2575b8522a1eSNikolay Borisov 	bool handle_error = false;
2576b8522a1eSNikolay Borisov 	int ret = 0;
2577b8522a1eSNikolay Borisov 	int i;
2578b8522a1eSNikolay Borisov 
2579b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2580b8522a1eSNikolay Borisov 		if (handle_error) {
2581b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2582b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2583b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2584b8522a1eSNikolay Borisov 
2585b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2586b8522a1eSNikolay Borisov 				break;
2587b8522a1eSNikolay Borisov 
2588b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2589b8522a1eSNikolay Borisov 
2590b8522a1eSNikolay Borisov 			/*
2591b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2592b8522a1eSNikolay Borisov 			 * valid
2593b8522a1eSNikolay Borisov 			 */
2594b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2595b8522a1eSNikolay Borisov 
2596b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2597b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2598b8522a1eSNikolay Borisov 
2599745806fbSQu Wenruo 			btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2600b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
26016ef108ddSNikolay Borisov 			backup_index = ret;
2602b8522a1eSNikolay Borisov 			if (ret < 0)
2603b8522a1eSNikolay Borisov 				return ret;
2604b8522a1eSNikolay Borisov 		}
2605b8522a1eSNikolay Borisov 
2606bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2607bd676446SJosef Bacik 		if (ret) {
2608217f5004SNikolay Borisov 			handle_error = true;
2609b8522a1eSNikolay Borisov 			continue;
2610b8522a1eSNikolay Borisov 		}
2611b8522a1eSNikolay Borisov 
2612336a0d8dSNikolay Borisov 		/*
2613336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2614336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2615336a0d8dSNikolay Borisov 		 */
2616453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2617b8522a1eSNikolay Borisov 		if (ret < 0) {
2618b8522a1eSNikolay Borisov 			handle_error = true;
2619b8522a1eSNikolay Borisov 			continue;
2620b8522a1eSNikolay Borisov 		}
2621b8522a1eSNikolay Borisov 
26226b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2623b8522a1eSNikolay Borisov 
2624b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2625b8522a1eSNikolay Borisov 		if (ret < 0) {
2626b8522a1eSNikolay Borisov 			handle_error = true;
2627b8522a1eSNikolay Borisov 			continue;
2628b8522a1eSNikolay Borisov 		}
2629b8522a1eSNikolay Borisov 
2630b8522a1eSNikolay Borisov 		/* All successful */
2631bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2632bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2633d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
26346ef108ddSNikolay Borisov 
26356ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26366ef108ddSNikolay Borisov 		if (backup_index < 0) {
26376ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26386ef108ddSNikolay Borisov 		} else {
26396ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26406ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26416ef108ddSNikolay Borisov 		}
2642b8522a1eSNikolay Borisov 		break;
2643b8522a1eSNikolay Borisov 	}
2644b8522a1eSNikolay Borisov 
2645b8522a1eSNikolay Borisov 	return ret;
2646b8522a1eSNikolay Borisov }
2647b8522a1eSNikolay Borisov 
26488260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2649eb60ceacSChris Mason {
2650fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
265101cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26528fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2653facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
265424bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2655eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
265611833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2657eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2658a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2659fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
266024bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26614cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2662ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2663f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
266447ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
266540ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2666afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2667c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2668f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2669abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2670d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2671f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
26727585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2673573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
26740bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
26755f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2676de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
267719c00ddcSChris Mason 
2678e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
26795a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
26808b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
26815f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
26823e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
26833e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
26843e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
26853e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
26863e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
26873e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
26883e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
26893e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2690e1489b4fSIoannis Angelakopoulos 
26910b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
26926324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2693f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
269447ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
269518bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2696afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2697bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2698bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
26993fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
27003fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2701bd647ce3SJosef Bacik #endif
2702c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
270366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
270466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
270566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
270666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
270766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
270866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
270966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2710ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2711ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2712ba2c4d4eSJosef Bacik 
2713771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
27144cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2715034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2716fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2717abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
271895ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27199ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27204cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2721a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2722f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27238b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2724fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2725c8b97818SChris Mason 
2726b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2727b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27280afbaf8cSChris Mason 
2729199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2730199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
273169fe2d75SJosef Bacik 
2732638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
273321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
273421adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
273521adbd5cSStefan Behrens #endif
2736779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
273757056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2738a2de733cSArne Jansen 
273916b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
274008dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
27410f9dd46cSJosef Bacik 
2742fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
274335da5a7eSDavid Sterba 			    IO_TREE_FS_EXCLUDED_EXTENTS);
274439279cc3SChris Mason 
27455a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2746e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2747925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2748a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2749a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27501bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27519e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2752c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
275376dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2754803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2755fa9c0d79SChris Mason 
2756ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2757f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2758b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2759416ac51dSArne Jansen 
2760fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2761fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2762fa9c0d79SChris Mason 
2763e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2764f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2765bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27664854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2767034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
27683768f368SChris Mason 
2769da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2770da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2771da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2772ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2773da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2774da17066cSJeff Mahoney 
2775f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2776f7b12a62SNaohiro Aota 
2777eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2778eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2779eede2bf3SOmar Sandoval 
278018bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
278118bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
27828260edbaSJosef Bacik }
27838260edbaSJosef Bacik 
27848260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
27858260edbaSJosef Bacik {
27868260edbaSJosef Bacik 	int ret;
27878260edbaSJosef Bacik 
27888260edbaSJosef Bacik 	fs_info->sb = sb;
27898260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
27908260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
27919e967495SFilipe Manana 
27925deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2793ae18c37aSJosef Bacik 	if (ret)
2794ae18c37aSJosef Bacik 		return ret;
2795ae18c37aSJosef Bacik 
2796ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2797ae18c37aSJosef Bacik 	if (ret)
2798c75e8394SJosef Bacik 		return ret;
2799ae18c37aSJosef Bacik 
2800ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2801ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2802ae18c37aSJosef Bacik 
2803ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2804ae18c37aSJosef Bacik 	if (ret)
2805c75e8394SJosef Bacik 		return ret;
2806ae18c37aSJosef Bacik 
2807ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2808ae18c37aSJosef Bacik 			GFP_KERNEL);
2809ae18c37aSJosef Bacik 	if (ret)
2810c75e8394SJosef Bacik 		return ret;
2811ae18c37aSJosef Bacik 
2812ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2813ae18c37aSJosef Bacik 					GFP_KERNEL);
2814c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2815c75e8394SJosef Bacik 		return -ENOMEM;
2816ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2817ae18c37aSJosef Bacik 
2818a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
2819a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2820a0a1db70SFilipe Manana 
2821c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2822ae18c37aSJosef Bacik }
2823ae18c37aSJosef Bacik 
282497f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
282597f4dd09SNikolay Borisov {
28260d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
282797f4dd09SNikolay Borisov 	int ret;
282897f4dd09SNikolay Borisov 
282997f4dd09SNikolay Borisov 	/*
283097f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
283197f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
283297f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
283397f4dd09SNikolay Borisov 	 */
283497f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
283597f4dd09SNikolay Borisov 	if (ret < 0) {
2836c94bec2cSJosef Bacik 		if (ret != -EINTR)
2837c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2838c94bec2cSJosef Bacik 				   ret);
283997f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
284097f4dd09SNikolay Borisov 		return ret;
284197f4dd09SNikolay Borisov 	}
284297f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
284397f4dd09SNikolay Borisov }
284497f4dd09SNikolay Borisov 
284597f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
284697f4dd09SNikolay Borisov {
284797f4dd09SNikolay Borisov 	struct task_struct *task;
284897f4dd09SNikolay Borisov 
284997f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
285097f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
285197f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
285297f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
285397f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
285497f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
285597f4dd09SNikolay Borisov 		return PTR_ERR(task);
285697f4dd09SNikolay Borisov 	}
285797f4dd09SNikolay Borisov 
285897f4dd09SNikolay Borisov 	return 0;
285997f4dd09SNikolay Borisov }
286097f4dd09SNikolay Borisov 
286144c0ca21SBoris Burkov /*
28628cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
28638cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
28648cd29088SBoris Burkov  * code paths.
28658cd29088SBoris Burkov  */
28668cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
28678cd29088SBoris Burkov {
28688cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
28698b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
28708cd29088SBoris Burkov }
28718cd29088SBoris Burkov 
28728cd29088SBoris Burkov /*
287344c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
287444c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
287544c0ca21SBoris Burkov  */
287644c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
287744c0ca21SBoris Burkov {
287844c0ca21SBoris Burkov 	int ret;
287994846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
28801d6a4fc8SQu Wenruo 	bool rebuild_free_space_tree = false;
28818b228324SBoris Burkov 
28828b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
28838b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
28841d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
28858b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
28868b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
28878b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
28881d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
28898b228324SBoris Burkov 	}
28908b228324SBoris Burkov 
28911d6a4fc8SQu Wenruo 	if (rebuild_free_space_tree) {
28921d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "rebuilding free space tree");
28931d6a4fc8SQu Wenruo 		ret = btrfs_rebuild_free_space_tree(fs_info);
28948b228324SBoris Burkov 		if (ret) {
28958b228324SBoris Burkov 			btrfs_warn(fs_info,
28961d6a4fc8SQu Wenruo 				   "failed to rebuild free space tree: %d", ret);
28971d6a4fc8SQu Wenruo 			goto out;
28981d6a4fc8SQu Wenruo 		}
28991d6a4fc8SQu Wenruo 	}
29001d6a4fc8SQu Wenruo 
29011d6a4fc8SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
29021d6a4fc8SQu Wenruo 	    !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
29031d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "disabling free space tree");
29041d6a4fc8SQu Wenruo 		ret = btrfs_delete_free_space_tree(fs_info);
29051d6a4fc8SQu Wenruo 		if (ret) {
29061d6a4fc8SQu Wenruo 			btrfs_warn(fs_info,
29071d6a4fc8SQu Wenruo 				   "failed to disable free space tree: %d", ret);
29088b228324SBoris Burkov 			goto out;
29098b228324SBoris Burkov 		}
29108b228324SBoris Burkov 	}
291144c0ca21SBoris Burkov 
29128d488a8cSFilipe Manana 	/*
29138d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
29148d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
2915fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
29168d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
29178d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
29188d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
29198d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
29208d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
29218d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
29228d488a8cSFilipe Manana 	 */
29238d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
29248d488a8cSFilipe Manana 	if (ret)
29258d488a8cSFilipe Manana 		goto out;
29268d488a8cSFilipe Manana 
292744c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
292844c0ca21SBoris Burkov 	if (ret)
292944c0ca21SBoris Burkov 		goto out;
293044c0ca21SBoris Burkov 
29318f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
29328f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
29338f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
29348f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
29358f1c21d7SBoris Burkov 		goto out;
29368f1c21d7SBoris Burkov 	}
29378f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
29388f1c21d7SBoris Burkov 
293944c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
29407eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
294144c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
294244c0ca21SBoris Burkov 	if (ret < 0) {
294344c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
294444c0ca21SBoris Burkov 		goto out;
294544c0ca21SBoris Burkov 	}
294644c0ca21SBoris Burkov 
29475011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
29485011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
29495011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
29505011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
29515011139aSBoris Burkov 		if (ret) {
29525011139aSBoris Burkov 			btrfs_warn(fs_info,
29535011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
29545011139aSBoris Burkov 			goto out;
29555011139aSBoris Burkov 		}
29565011139aSBoris Burkov 	}
29575011139aSBoris Burkov 
295894846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
295994846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
296094846229SBoris Burkov 		if (ret)
296194846229SBoris Burkov 			goto out;
296294846229SBoris Burkov 	}
296394846229SBoris Burkov 
296444c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
296544c0ca21SBoris Burkov 	if (ret)
296644c0ca21SBoris Burkov 		goto out;
296744c0ca21SBoris Burkov 
296844c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
296944c0ca21SBoris Burkov 	if (ret) {
297044c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
297144c0ca21SBoris Burkov 		goto out;
297244c0ca21SBoris Burkov 	}
297344c0ca21SBoris Burkov 
297444c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
297544c0ca21SBoris Burkov 
297644c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
297744c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
297844c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
297944c0ca21SBoris Burkov 		if (ret) {
298044c0ca21SBoris Burkov 			btrfs_warn(fs_info,
298144c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
298244c0ca21SBoris Burkov 			goto out;
298344c0ca21SBoris Burkov 		}
298444c0ca21SBoris Burkov 	}
298544c0ca21SBoris Burkov 
298644c0ca21SBoris Burkov out:
298744c0ca21SBoris Burkov 	return ret;
298844c0ca21SBoris Burkov }
298944c0ca21SBoris Burkov 
2990d7f67ac9SQu Wenruo /*
2991d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
2992d7f67ac9SQu Wenruo  *
29932ba48b20SQu Wenruo  * @is_rw_mount:	If the mount is read-write.
29942ba48b20SQu Wenruo  *
2995d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
2996d7f67ac9SQu Wenruo  * feature dependencies).
2997d7f67ac9SQu Wenruo  *
2998d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
2999d7f67ac9SQu Wenruo  * btrfs_validate_super().
3000d7f67ac9SQu Wenruo  *
3001d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3002d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3003d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3004d7f67ac9SQu Wenruo  */
30052ba48b20SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3006d7f67ac9SQu Wenruo {
3007d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3008d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3009d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3010d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3011d7f67ac9SQu Wenruo 
3012d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3013d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3014d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3015d7f67ac9SQu Wenruo 		    incompat);
3016d7f67ac9SQu Wenruo 		return -EINVAL;
3017d7f67ac9SQu Wenruo 	}
3018d7f67ac9SQu Wenruo 
3019d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3020d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3021d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3022d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3023d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3024d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3025d7f67ac9SQu Wenruo 		return -EINVAL;
3026d7f67ac9SQu Wenruo 	}
3027d7f67ac9SQu Wenruo 
3028d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3029d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3030d7f67ac9SQu Wenruo 
3031d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3032d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3033d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3034d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3035d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3036d7f67ac9SQu Wenruo 
3037d7f67ac9SQu Wenruo 	/*
3038d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3039d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3040d7f67ac9SQu Wenruo 	 */
3041d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3042d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3043d7f67ac9SQu Wenruo 
30442ba48b20SQu Wenruo 	if (compat_ro_unsupp && is_rw_mount) {
3045d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3046d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3047d7f67ac9SQu Wenruo 		       compat_ro);
3048d7f67ac9SQu Wenruo 		return -EINVAL;
3049d7f67ac9SQu Wenruo 	}
3050d7f67ac9SQu Wenruo 
3051d7f67ac9SQu Wenruo 	/*
3052d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3053d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3054d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3055d7f67ac9SQu Wenruo 	 */
3056d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3057d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3058d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3059d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3060d7f67ac9SQu Wenruo 			  compat_ro);
3061d7f67ac9SQu Wenruo 		return -EINVAL;
3062d7f67ac9SQu Wenruo 	}
3063d7f67ac9SQu Wenruo 
3064d7f67ac9SQu Wenruo 	/*
3065d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3066d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3067d7f67ac9SQu Wenruo 	 */
3068d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3069d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3070d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3071d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3072d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3073d7f67ac9SQu Wenruo 		return -EINVAL;
3074d7f67ac9SQu Wenruo 	}
3075d7f67ac9SQu Wenruo 
3076d7f67ac9SQu Wenruo 	/*
3077d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3078d7f67ac9SQu Wenruo 	 *
3079d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3080d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3081d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3082d7f67ac9SQu Wenruo 	 */
3083d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3084d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3085d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3086d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3087d7f67ac9SQu Wenruo 		return -EINVAL;
3088d7f67ac9SQu Wenruo 	}
3089d7f67ac9SQu Wenruo 
3090d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3091d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3092d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3093d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3094d7f67ac9SQu Wenruo 
3095d7f67ac9SQu Wenruo 	return 0;
3096d7f67ac9SQu Wenruo }
3097d7f67ac9SQu Wenruo 
3098ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3099ae18c37aSJosef Bacik 		      char *options)
3100ae18c37aSJosef Bacik {
3101ae18c37aSJosef Bacik 	u32 sectorsize;
3102ae18c37aSJosef Bacik 	u32 nodesize;
3103ae18c37aSJosef Bacik 	u32 stripesize;
3104ae18c37aSJosef Bacik 	u64 generation;
3105ae18c37aSJosef Bacik 	u64 features;
3106ae18c37aSJosef Bacik 	u16 csum_type;
3107ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3108ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3109ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3110ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3111ae18c37aSJosef Bacik 	int ret;
3112ae18c37aSJosef Bacik 	int level;
3113ae18c37aSJosef Bacik 
31148260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
31154871c33bSQu Wenruo 	if (ret)
3116ae18c37aSJosef Bacik 		goto fail;
311753b381b3SDavid Woodhouse 
3118ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3119ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3120ae18c37aSJosef Bacik 				     GFP_KERNEL);
3121ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3122ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3123ae18c37aSJosef Bacik 				      GFP_KERNEL);
3124ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3125ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
31264871c33bSQu Wenruo 		ret = -ENOMEM;
3127c75e8394SJosef Bacik 		goto fail;
3128ae18c37aSJosef Bacik 	}
3129ae18c37aSJosef Bacik 
3130dcb2137cSChristoph Hellwig 	ret = btrfs_init_btree_inode(sb);
31314871c33bSQu Wenruo 	if (ret)
3132c75e8394SJosef Bacik 		goto fail;
3133ae18c37aSJosef Bacik 
3134d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
31351104a885SDavid Sterba 
31361104a885SDavid Sterba 	/*
31371104a885SDavid Sterba 	 * Read super block and check the signature bytes only
31381104a885SDavid Sterba 	 */
3139d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
31408f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
31414871c33bSQu Wenruo 		ret = PTR_ERR(disk_super);
314216cdcec7SMiao Xie 		goto fail_alloc;
314320b45077SDave Young 	}
314439279cc3SChris Mason 
31451104a885SDavid Sterba 	/*
3146260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
31478dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
31488dc3f22cSJohannes Thumshirn 	 */
31498f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
315051bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
31518dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
315251bce6c9SJohannes Thumshirn 			  csum_type);
31534871c33bSQu Wenruo 		ret = -EINVAL;
31548f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31558dc3f22cSJohannes Thumshirn 		goto fail_alloc;
31568dc3f22cSJohannes Thumshirn 	}
31578dc3f22cSJohannes Thumshirn 
315883c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
315983c68bbcSSu Yue 
31606d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
31616d97c6e3SJohannes Thumshirn 	if (ret) {
31628f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31636d97c6e3SJohannes Thumshirn 		goto fail_alloc;
31646d97c6e3SJohannes Thumshirn 	}
31656d97c6e3SJohannes Thumshirn 
31668dc3f22cSJohannes Thumshirn 	/*
31671104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
31681104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
31691104a885SDavid Sterba 	 */
31703d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
317105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
31724871c33bSQu Wenruo 		ret = -EINVAL;
31738f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3174141386e1SJosef Bacik 		goto fail_alloc;
31751104a885SDavid Sterba 	}
31761104a885SDavid Sterba 
31771104a885SDavid Sterba 	/*
31781104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
31791104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
31801104a885SDavid Sterba 	 * the whole block of INFO_SIZE
31811104a885SDavid Sterba 	 */
31828f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
31838f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
31845f39d397SChris Mason 
3185fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3186fbc6feaeSNikolay Borisov 
31870b86a832SChris Mason 
3188fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3189fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3190fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3191fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3192fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3193fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3194fbc6feaeSNikolay Borisov 	}
3195fbc6feaeSNikolay Borisov 
3196fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3197fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3198de37aa51SNikolay Borisov 
3199069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
32001104a885SDavid Sterba 	if (ret) {
320105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
32024871c33bSQu Wenruo 		ret = -EINVAL;
3203141386e1SJosef Bacik 		goto fail_alloc;
32041104a885SDavid Sterba 	}
32051104a885SDavid Sterba 
32064871c33bSQu Wenruo 	if (!btrfs_super_root(disk_super)) {
32074871c33bSQu Wenruo 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
32084871c33bSQu Wenruo 		ret = -EINVAL;
3209141386e1SJosef Bacik 		goto fail_alloc;
32104871c33bSQu Wenruo 	}
32110f7d52f4SChris Mason 
3212acce952bSliubo 	/* check FS state, whether FS is broken. */
321387533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
321487533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3215acce952bSliubo 
321675e7cb7fSLiu Bo 	/*
321775e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
321875e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
321975e7cb7fSLiu Bo 	 */
322075e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
322175e7cb7fSLiu Bo 
32226f93e834SAnand Jain 
32236f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
32246f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
32256f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
32266f93e834SAnand Jain 	stripesize = sectorsize;
32276f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
32286f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
32296f93e834SAnand Jain 
32306f93e834SAnand Jain 	fs_info->nodesize = nodesize;
32316f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
32326f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
32336f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
32346f93e834SAnand Jain 	fs_info->stripesize = stripesize;
32356f93e834SAnand Jain 
32362ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
32374871c33bSQu Wenruo 	if (ret)
3238141386e1SJosef Bacik 		goto fail_alloc;
3239dfe25020SChris Mason 
32402ba48b20SQu Wenruo 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
32414871c33bSQu Wenruo 	if (ret < 0)
3242141386e1SJosef Bacik 		goto fail_alloc;
3243f2b636e8SJosef Bacik 
32448481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
32458481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
32468481dd80SQu Wenruo 
32479f73f1aeSQu Wenruo 		/*
32489f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
32499f73f1aeSQu Wenruo 		 * going to be deprecated.
32509f73f1aeSQu Wenruo 		 *
32519f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
32529f73f1aeSQu Wenruo 		 */
32539f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
32549f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
32559f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
32569f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
32579f73f1aeSQu Wenruo 
325895ea0486SQu Wenruo 		btrfs_warn(fs_info,
325995ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
32600bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
32618481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
32624871c33bSQu Wenruo 		if (!subpage_info) {
32634871c33bSQu Wenruo 			ret = -ENOMEM;
32648481dd80SQu Wenruo 			goto fail_alloc;
32654871c33bSQu Wenruo 		}
32668481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
32678481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3268c8050b3bSQu Wenruo 	}
32690bb3eb3eSQu Wenruo 
3270d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
32714871c33bSQu Wenruo 	if (ret)
32720dc3b84aSJosef Bacik 		goto fail_sb_buffer;
32734543df7eSChris Mason 
32749e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
32759e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
32764575c9ccSChris Mason 
3277a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3278a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3279de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3280db94535dSChris Mason 
3281925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
32826bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3283925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
328484eed90fSChris Mason 	if (ret) {
328505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
32865d4f98a2SYan Zheng 		goto fail_sb_buffer;
328784eed90fSChris Mason 	}
32880b86a832SChris Mason 
328984234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3290581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3291bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3292bd676446SJosef Bacik 			      generation, level);
3293bd676446SJosef Bacik 	if (ret) {
329405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3295af31f5e5SChris Mason 		goto fail_tree_roots;
329683121942SDavid Woodhouse 	}
32970b86a832SChris Mason 
3298e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3299c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3300c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3301e17cade2SChris Mason 
33025b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
33032b82032cSYan Zheng 	if (ret) {
330405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3305af31f5e5SChris Mason 		goto fail_tree_roots;
33062b82032cSYan Zheng 	}
33070b86a832SChris Mason 
33088dabb742SStefan Behrens 	/*
3309bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3310bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3311bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
33121a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3313bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
33148dabb742SStefan Behrens 	 */
3315bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3316d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
331705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
33184871c33bSQu Wenruo 		ret = -EIO;
3319a6b0d5c8SChris Mason 		goto fail_tree_roots;
3320a6b0d5c8SChris Mason 	}
3321a6b0d5c8SChris Mason 
3322b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
33234bbcaa64SEric Sandeen 	if (ret)
3324b8522a1eSNikolay Borisov 		goto fail_tree_roots;
33258929ecfaSYan, Zheng 
332675ec1db8SJosef Bacik 	/*
332773651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
332873651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
332973651042SNaohiro Aota 	 * zoned incompat feature flag set.
333073651042SNaohiro Aota 	 */
333173651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
333273651042SNaohiro Aota 	if (ret) {
333373651042SNaohiro Aota 		btrfs_err(fs_info,
33344871c33bSQu Wenruo 			  "zoned: failed to read device zone info: %d", ret);
333573651042SNaohiro Aota 		goto fail_block_groups;
333673651042SNaohiro Aota 	}
333773651042SNaohiro Aota 
333873651042SNaohiro Aota 	/*
333975ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
334075ec1db8SJosef Bacik 	 * check the generation here so we can set the
334175ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
334275ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
334375ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
334475ec1db8SJosef Bacik 	 * even though it was perfectly fine.
334575ec1db8SJosef Bacik 	 */
334675ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
334775ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
334875ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
334975ec1db8SJosef Bacik 
3350cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3351cf90d884SQu Wenruo 	if (ret) {
3352cf90d884SQu Wenruo 		btrfs_err(fs_info,
3353cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3354cf90d884SQu Wenruo 			  ret);
3355cf90d884SQu Wenruo 		goto fail_block_groups;
3356cf90d884SQu Wenruo 	}
335768310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
335868310a5eSIlya Dryomov 	if (ret) {
335905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
336068310a5eSIlya Dryomov 		goto fail_block_groups;
336168310a5eSIlya Dryomov 	}
336268310a5eSIlya Dryomov 
3363733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3364733f4fbbSStefan Behrens 	if (ret) {
336505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3366733f4fbbSStefan Behrens 		goto fail_block_groups;
3367733f4fbbSStefan Behrens 	}
3368733f4fbbSStefan Behrens 
33698dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
33708dabb742SStefan Behrens 	if (ret) {
337105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
33728dabb742SStefan Behrens 		goto fail_block_groups;
33738dabb742SStefan Behrens 	}
33748dabb742SStefan Behrens 
3375b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3376b70f5097SNaohiro Aota 	if (ret) {
3377b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3378b70f5097SNaohiro Aota 			  ret);
3379b70f5097SNaohiro Aota 		goto fail_block_groups;
3380b70f5097SNaohiro Aota 	}
3381b70f5097SNaohiro Aota 
3382c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3383b7c35e81SAnand Jain 	if (ret) {
338405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
338505135f59SDavid Sterba 				ret);
3386b7c35e81SAnand Jain 		goto fail_block_groups;
3387b7c35e81SAnand Jain 	}
3388b7c35e81SAnand Jain 
338996f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
33905ac1d209SJeff Mahoney 	if (ret) {
339105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3392b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
33935ac1d209SJeff Mahoney 	}
33945ac1d209SJeff Mahoney 
3395c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3396c59021f8Sliubo 	if (ret) {
339705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
33982365dd3cSAnand Jain 		goto fail_sysfs;
3399c59021f8Sliubo 	}
3400c59021f8Sliubo 
34015b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
34021b1d1f66SJosef Bacik 	if (ret) {
340305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
34042365dd3cSAnand Jain 		goto fail_sysfs;
34051b1d1f66SJosef Bacik 	}
34064330e183SQu Wenruo 
340716beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
340816beac87SNaohiro Aota 
34095c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
34105c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
341105135f59SDavid Sterba 		btrfs_warn(fs_info,
341252042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
34134871c33bSQu Wenruo 		ret = -EINVAL;
34142365dd3cSAnand Jain 		goto fail_sysfs;
3415292fd7fcSStefan Behrens 	}
34169078a3e1SChris Mason 
341733c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3418a74a4b97SChris Mason 					       "btrfs-cleaner");
34194871c33bSQu Wenruo 	if (IS_ERR(fs_info->cleaner_kthread)) {
34204871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->cleaner_kthread);
34212365dd3cSAnand Jain 		goto fail_sysfs;
34224871c33bSQu Wenruo 	}
3423a74a4b97SChris Mason 
3424a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3425a74a4b97SChris Mason 						   tree_root,
3426a74a4b97SChris Mason 						   "btrfs-transaction");
34274871c33bSQu Wenruo 	if (IS_ERR(fs_info->transaction_kthread)) {
34284871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->transaction_kthread);
34293f157a2fSChris Mason 		goto fail_cleaner;
34304871c33bSQu Wenruo 	}
3431a74a4b97SChris Mason 
3432583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3433c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3434583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3435c289811cSChris Mason 	}
3436c289811cSChris Mason 
3437572d9ab7SDavid Sterba 	/*
343863a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
343963a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
344063a7cb13SDavid Sterba 	 * nodiscard for the same mount.
344163a7cb13SDavid Sterba 	 */
344263a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
344363a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
344463a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
344563a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
344663a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
344763a7cb13SDavid Sterba 				   "auto enabling async discard");
344863a7cb13SDavid Sterba 	}
344963a7cb13SDavid Sterba 
345021adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
34510b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
34522ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
34530b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3454cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
345521adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
345621adbd5cSStefan Behrens 		if (ret)
345705135f59SDavid Sterba 			btrfs_warn(fs_info,
345805135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
345905135f59SDavid Sterba 				ret);
346021adbd5cSStefan Behrens 	}
346121adbd5cSStefan Behrens #endif
3462bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3463bcef60f2SArne Jansen 	if (ret)
3464bcef60f2SArne Jansen 		goto fail_trans_kthread;
346521adbd5cSStefan Behrens 
3466fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3467fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3468fd708b81SJosef Bacik 
346996da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
347096da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
34710b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3472e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
347363443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
34744871c33bSQu Wenruo 		if (ret)
347528c16cbbSWang Shilong 			goto fail_qgroup;
3476e556ce2cSYan Zheng 	}
34771a40e23bSZheng Yan 
347856e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
34793140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
34804871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->fs_root);
34814871c33bSQu Wenruo 		btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3482315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3483bcef60f2SArne Jansen 		goto fail_qgroup;
34843140c9a3SDan Carpenter 	}
3485c289811cSChris Mason 
3486bc98a42cSDavid Howells 	if (sb_rdonly(sb))
34878cd29088SBoris Burkov 		goto clear_oneshot;
34882b6ba629SIlya Dryomov 
348944c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
34902b6ba629SIlya Dryomov 	if (ret) {
34916bccf3abSJeff Mahoney 		close_ctree(fs_info);
34922b6ba629SIlya Dryomov 		return ret;
3493e3acc2a6SJosef Bacik 	}
3494b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3495b382a324SJan Schmidt 
349644c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
349744c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
349844c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
349905135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
350070f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
350170f80175SStefan Behrens 		if (ret) {
350205135f59SDavid Sterba 			btrfs_warn(fs_info,
350305135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
35046bccf3abSJeff Mahoney 			close_ctree(fs_info);
350570f80175SStefan Behrens 			return ret;
350670f80175SStefan Behrens 		}
3507f7a81ea4SStefan Behrens 	}
350894846229SBoris Burkov 
3509afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
351047ab2a6cSJosef Bacik 
3511b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3512b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3513b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3514b4be6aefSJosef Bacik 
35158cd29088SBoris Burkov clear_oneshot:
35168cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3517ad2b2c80SAl Viro 	return 0;
351839279cc3SChris Mason 
3519bcef60f2SArne Jansen fail_qgroup:
3520bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
35217c2ca468SChris Mason fail_trans_kthread:
35227c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
35232ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3524faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
35253f157a2fSChris Mason fail_cleaner:
3526a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
35277c2ca468SChris Mason 
35287c2ca468SChris Mason 	/*
35297c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
35307c2ca468SChris Mason 	 * kthreads
35317c2ca468SChris Mason 	 */
35327c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
35337c2ca468SChris Mason 
35342365dd3cSAnand Jain fail_sysfs:
35356618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
35362365dd3cSAnand Jain 
3537b7c35e81SAnand Jain fail_fsdev_sysfs:
3538b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3539b7c35e81SAnand Jain 
35401b1d1f66SJosef Bacik fail_block_groups:
354154067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3542af31f5e5SChris Mason 
3543af31f5e5SChris Mason fail_tree_roots:
35449e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
35459e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
35464273eaffSAnand Jain 	free_root_pointers(fs_info, true);
35472b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3548af31f5e5SChris Mason 
354939279cc3SChris Mason fail_sb_buffer:
35507abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
35515cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
355216cdcec7SMiao Xie fail_alloc:
3553586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3554586e46e2SIlya Dryomov 
35554543df7eSChris Mason 	iput(fs_info->btree_inode);
35567e662854SQinghuang Feng fail:
3557586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
35584871c33bSQu Wenruo 	ASSERT(ret < 0);
35594871c33bSQu Wenruo 	return ret;
3560eb60ceacSChris Mason }
3561663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3562eb60ceacSChris Mason 
3563314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3564f2984462SChris Mason {
3565314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3566314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3567314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3568314b6dd0SJohannes Thumshirn 	struct page *page;
3569442a4f63SStefan Behrens 
3570314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3571314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3572314b6dd0SJohannes Thumshirn 
3573314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3574fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3575314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3576cb3e217bSQu Wenruo 				btrfs_dev_name(device),
3577314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3578314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3579314b6dd0SJohannes Thumshirn 			SetPageError(page);
3580314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3581314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3582314b6dd0SJohannes Thumshirn 		} else {
3583314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3584f2984462SChris Mason 		}
3585314b6dd0SJohannes Thumshirn 
3586314b6dd0SJohannes Thumshirn 		put_page(page);
3587314b6dd0SJohannes Thumshirn 		unlock_page(page);
3588314b6dd0SJohannes Thumshirn 	}
3589314b6dd0SJohannes Thumshirn 
3590314b6dd0SJohannes Thumshirn 	bio_put(bio);
3591f2984462SChris Mason }
3592f2984462SChris Mason 
35938f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3594a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
359529c36d72SAnand Jain {
359629c36d72SAnand Jain 	struct btrfs_super_block *super;
35978f32380dSJohannes Thumshirn 	struct page *page;
359812659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
35998f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
360012659251SNaohiro Aota 	int ret;
360129c36d72SAnand Jain 
360212659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
360312659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
360412659251SNaohiro Aota 	if (ret == -ENOENT)
360512659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
360612659251SNaohiro Aota 	else if (ret)
360712659251SNaohiro Aota 		return ERR_PTR(ret);
360812659251SNaohiro Aota 
3609cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
36108f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
361129c36d72SAnand Jain 
3612a05d3c91SQu Wenruo 	if (drop_cache) {
3613a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3614a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3615a05d3c91SQu Wenruo 
3616a05d3c91SQu Wenruo 		/*
3617a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3618a05d3c91SQu Wenruo 		 * always read from the device.
3619a05d3c91SQu Wenruo 		 */
3620a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3621a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3622a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3623a05d3c91SQu Wenruo 	}
3624a05d3c91SQu Wenruo 
36258f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
36268f32380dSJohannes Thumshirn 	if (IS_ERR(page))
36278f32380dSJohannes Thumshirn 		return ERR_CAST(page);
362829c36d72SAnand Jain 
36298f32380dSJohannes Thumshirn 	super = page_address(page);
363096c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
363196c2e067SAnand Jain 		btrfs_release_disk_super(super);
363296c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
363396c2e067SAnand Jain 	}
363496c2e067SAnand Jain 
363512659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
36368f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
36378f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
363829c36d72SAnand Jain 	}
363929c36d72SAnand Jain 
36408f32380dSJohannes Thumshirn 	return super;
364129c36d72SAnand Jain }
364229c36d72SAnand Jain 
364329c36d72SAnand Jain 
36448f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3645a512bbf8SYan Zheng {
36468f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3647a512bbf8SYan Zheng 	int i;
3648a512bbf8SYan Zheng 	u64 transid = 0;
3649a512bbf8SYan Zheng 
3650a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3651a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3652a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3653a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3654a512bbf8SYan Zheng 	 */
3655a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3656a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
36578f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3658a512bbf8SYan Zheng 			continue;
3659a512bbf8SYan Zheng 
3660a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
36618f32380dSJohannes Thumshirn 			if (latest)
36628f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
36638f32380dSJohannes Thumshirn 
36648f32380dSJohannes Thumshirn 			latest = super;
3665a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3666a512bbf8SYan Zheng 		}
3667a512bbf8SYan Zheng 	}
366892fc03fbSAnand Jain 
36698f32380dSJohannes Thumshirn 	return super;
3670a512bbf8SYan Zheng }
3671a512bbf8SYan Zheng 
36724eedeb75SHisashi Hifumi /*
3673abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3674314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
36754eedeb75SHisashi Hifumi  *
3676abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3677abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3678abbb3b8eSDavid Sterba  * same for write and wait phases.
36794eedeb75SHisashi Hifumi  *
3680314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
36814eedeb75SHisashi Hifumi  */
3682a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3683abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3684a512bbf8SYan Zheng {
3685d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3686314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3687d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3688a512bbf8SYan Zheng 	int i;
3689a512bbf8SYan Zheng 	int errors = 0;
369012659251SNaohiro Aota 	int ret;
369112659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3692a512bbf8SYan Zheng 
3693a512bbf8SYan Zheng 	if (max_mirrors == 0)
3694a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3695a512bbf8SYan Zheng 
3696d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3697d5178578SJohannes Thumshirn 
3698a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3699314b6dd0SJohannes Thumshirn 		struct page *page;
3700314b6dd0SJohannes Thumshirn 		struct bio *bio;
3701314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3702314b6dd0SJohannes Thumshirn 
370312659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
370412659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
370512659251SNaohiro Aota 		if (ret == -ENOENT) {
370612659251SNaohiro Aota 			continue;
370712659251SNaohiro Aota 		} else if (ret < 0) {
370812659251SNaohiro Aota 			btrfs_err(device->fs_info,
370912659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
371012659251SNaohiro Aota 				i);
371112659251SNaohiro Aota 			errors++;
371212659251SNaohiro Aota 			continue;
371312659251SNaohiro Aota 		}
3714935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3715935e5cc9SMiao Xie 		    device->commit_total_bytes)
3716a512bbf8SYan Zheng 			break;
3717a512bbf8SYan Zheng 
371812659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3719a512bbf8SYan Zheng 
3720fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3721fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3722fd08001fSEric Biggers 				    sb->csum);
3723a512bbf8SYan Zheng 
3724314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3725314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3726314b6dd0SJohannes Thumshirn 		if (!page) {
3727fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3728314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3729f14d104dSDavid Sterba 			    bytenr);
3730634554dcSJosef Bacik 			errors++;
3731634554dcSJosef Bacik 			continue;
3732634554dcSJosef Bacik 		}
3733634554dcSJosef Bacik 
3734314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3735314b6dd0SJohannes Thumshirn 		get_page(page);
3736a512bbf8SYan Zheng 
3737314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3738314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3739a512bbf8SYan Zheng 
3740387125fcSChris Mason 		/*
3741314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3742314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3743314b6dd0SJohannes Thumshirn 		 * checking.
3744387125fcSChris Mason 		 */
374507888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
374607888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
374707888c66SChristoph Hellwig 				GFP_NOFS);
3748314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3749314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3750314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3751314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3752314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3753314b6dd0SJohannes Thumshirn 
3754314b6dd0SJohannes Thumshirn 		/*
3755314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3756314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3757314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3758314b6dd0SJohannes Thumshirn 		 */
37591b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3760314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3761314b6dd0SJohannes Thumshirn 
376258ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
376358ff51f1SChristoph Hellwig 		submit_bio(bio);
37648376d9e1SNaohiro Aota 
37658376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
37668376d9e1SNaohiro Aota 			errors++;
3767a512bbf8SYan Zheng 	}
3768a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3769a512bbf8SYan Zheng }
3770a512bbf8SYan Zheng 
3771387125fcSChris Mason /*
3772abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3773abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3774abbb3b8eSDavid Sterba  *
3775314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3776abbb3b8eSDavid Sterba  * date.
3777abbb3b8eSDavid Sterba  */
3778abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3779abbb3b8eSDavid Sterba {
3780abbb3b8eSDavid Sterba 	int i;
3781abbb3b8eSDavid Sterba 	int errors = 0;
3782b6a535faSHoward McLauchlan 	bool primary_failed = false;
378312659251SNaohiro Aota 	int ret;
3784abbb3b8eSDavid Sterba 	u64 bytenr;
3785abbb3b8eSDavid Sterba 
3786abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3787abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3788abbb3b8eSDavid Sterba 
3789abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3790314b6dd0SJohannes Thumshirn 		struct page *page;
3791314b6dd0SJohannes Thumshirn 
379212659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
379312659251SNaohiro Aota 		if (ret == -ENOENT) {
379412659251SNaohiro Aota 			break;
379512659251SNaohiro Aota 		} else if (ret < 0) {
379612659251SNaohiro Aota 			errors++;
379712659251SNaohiro Aota 			if (i == 0)
379812659251SNaohiro Aota 				primary_failed = true;
379912659251SNaohiro Aota 			continue;
380012659251SNaohiro Aota 		}
3801abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3802abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3803abbb3b8eSDavid Sterba 			break;
3804abbb3b8eSDavid Sterba 
3805314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3806314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3807314b6dd0SJohannes Thumshirn 		if (!page) {
3808abbb3b8eSDavid Sterba 			errors++;
3809b6a535faSHoward McLauchlan 			if (i == 0)
3810b6a535faSHoward McLauchlan 				primary_failed = true;
3811abbb3b8eSDavid Sterba 			continue;
3812abbb3b8eSDavid Sterba 		}
3813314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3814314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3815314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3816abbb3b8eSDavid Sterba 			errors++;
3817b6a535faSHoward McLauchlan 			if (i == 0)
3818b6a535faSHoward McLauchlan 				primary_failed = true;
3819b6a535faSHoward McLauchlan 		}
3820abbb3b8eSDavid Sterba 
3821314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3822314b6dd0SJohannes Thumshirn 		put_page(page);
3823abbb3b8eSDavid Sterba 
3824314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3825314b6dd0SJohannes Thumshirn 		put_page(page);
3826abbb3b8eSDavid Sterba 	}
3827abbb3b8eSDavid Sterba 
3828b6a535faSHoward McLauchlan 	/* log error, force error return */
3829b6a535faSHoward McLauchlan 	if (primary_failed) {
3830b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3831b6a535faSHoward McLauchlan 			  device->devid);
3832b6a535faSHoward McLauchlan 		return -1;
3833b6a535faSHoward McLauchlan 	}
3834b6a535faSHoward McLauchlan 
3835abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3836abbb3b8eSDavid Sterba }
3837abbb3b8eSDavid Sterba 
3838abbb3b8eSDavid Sterba /*
3839387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3840387125fcSChris Mason  * for the barrier when it is done
3841387125fcSChris Mason  */
38424246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3843387125fcSChris Mason {
3844f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
3845387125fcSChris Mason 	complete(bio->bi_private);
3846387125fcSChris Mason }
3847387125fcSChris Mason 
3848387125fcSChris Mason /*
38494fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
38504fc6441aSAnand Jain  * done in the waiting counterpart.
3851387125fcSChris Mason  */
38524fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3853387125fcSChris Mason {
3854f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
3855387125fcSChris Mason 
3856bfd3ea94SAnand Jain 	device->last_flush_error = BLK_STS_OK;
3857bfd3ea94SAnand Jain 
3858a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3859a91cf0ffSWang Yugui 	/*
3860a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
3861a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
3862a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
3863a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
3864a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
3865a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
3866a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
3867a91cf0ffSWang Yugui 	 * non-debug builds.
3868a91cf0ffSWang Yugui 	 */
386908e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
38704fc6441aSAnand Jain 		return;
3871a91cf0ffSWang Yugui #endif
3872387125fcSChris Mason 
3873f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
3874f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
3875387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
3876387125fcSChris Mason 	init_completion(&device->flush_wait);
3877387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3878387125fcSChris Mason 
387958ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
388058ff51f1SChristoph Hellwig 	submit_bio(bio);
38811c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
38824fc6441aSAnand Jain }
3883387125fcSChris Mason 
38844fc6441aSAnand Jain /*
38854fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
38861b465784SAnand Jain  * Return true for any error, and false otherwise.
38874fc6441aSAnand Jain  */
38881b465784SAnand Jain static bool wait_dev_flush(struct btrfs_device *device)
38894fc6441aSAnand Jain {
3890f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
38914fc6441aSAnand Jain 
38927e812f20SAnand Jain 	if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
38931b465784SAnand Jain 		return false;
38944fc6441aSAnand Jain 
38952980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
38964fc6441aSAnand Jain 
3897bfd3ea94SAnand Jain 	if (bio->bi_status) {
3898bfd3ea94SAnand Jain 		device->last_flush_error = bio->bi_status;
3899bfd3ea94SAnand Jain 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
39001b465784SAnand Jain 		return true;
3901bfd3ea94SAnand Jain 	}
3902bfd3ea94SAnand Jain 
39031b465784SAnand Jain 	return false;
3904387125fcSChris Mason }
3905387125fcSChris Mason 
3906387125fcSChris Mason /*
3907387125fcSChris Mason  * send an empty flush down to each device in parallel,
3908387125fcSChris Mason  * then wait for them
3909387125fcSChris Mason  */
3910387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3911387125fcSChris Mason {
3912387125fcSChris Mason 	struct list_head *head;
3913387125fcSChris Mason 	struct btrfs_device *dev;
39145af3e8ccSStefan Behrens 	int errors_wait = 0;
3915387125fcSChris Mason 
39161538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3917387125fcSChris Mason 	/* send down all the barriers */
3918387125fcSChris Mason 	head = &info->fs_devices->devices;
39191538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3920e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3921f88ba6a2SHidetoshi Seto 			continue;
3922cea7c8bfSAnand Jain 		if (!dev->bdev)
3923387125fcSChris Mason 			continue;
3924e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3925ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3926387125fcSChris Mason 			continue;
3927387125fcSChris Mason 
39284fc6441aSAnand Jain 		write_dev_flush(dev);
3929387125fcSChris Mason 	}
3930387125fcSChris Mason 
3931387125fcSChris Mason 	/* wait for all the barriers */
39321538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3933e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3934f88ba6a2SHidetoshi Seto 			continue;
3935387125fcSChris Mason 		if (!dev->bdev) {
39365af3e8ccSStefan Behrens 			errors_wait++;
3937387125fcSChris Mason 			continue;
3938387125fcSChris Mason 		}
3939e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3940ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3941387125fcSChris Mason 			continue;
3942387125fcSChris Mason 
39431b465784SAnand Jain 		if (wait_dev_flush(dev))
39445af3e8ccSStefan Behrens 			errors_wait++;
3945387125fcSChris Mason 	}
3946401b41e5SAnand Jain 
3947401b41e5SAnand Jain 	/*
3948de38a206SAnand Jain 	 * Checks last_flush_error of disks in order to determine the device
3949de38a206SAnand Jain 	 * state.
3950401b41e5SAnand Jain 	 */
3951de38a206SAnand Jain 	if (errors_wait && !btrfs_check_rw_degradable(info, NULL))
3952de38a206SAnand Jain 		return -EIO;
3953de38a206SAnand Jain 
3954387125fcSChris Mason 	return 0;
3955387125fcSChris Mason }
3956387125fcSChris Mason 
3957943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3958943c6e99SZhao Lei {
39598789f4feSZhao Lei 	int raid_type;
39608789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3961943c6e99SZhao Lei 
39628789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
39638789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
39648c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39658789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
39668789f4feSZhao Lei 				    tolerated_failures);
3967943c6e99SZhao Lei 
39688789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
39698789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
39708789f4feSZhao Lei 			continue;
397141a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
39728789f4feSZhao Lei 			continue;
39738c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39748789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
39758789f4feSZhao Lei 				    tolerated_failures);
39768789f4feSZhao Lei 	}
3977943c6e99SZhao Lei 
39788789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3979ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
39808789f4feSZhao Lei 		min_tolerated = 0;
39818789f4feSZhao Lei 	}
39828789f4feSZhao Lei 
39838789f4feSZhao Lei 	return min_tolerated;
3984943c6e99SZhao Lei }
3985943c6e99SZhao Lei 
3986eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3987f2984462SChris Mason {
3988e5e9a520SChris Mason 	struct list_head *head;
3989f2984462SChris Mason 	struct btrfs_device *dev;
3990a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3991f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3992f2984462SChris Mason 	int ret;
3993f2984462SChris Mason 	int do_barriers;
3994a236aed1SChris Mason 	int max_errors;
3995a236aed1SChris Mason 	int total_errors = 0;
3996a061fc8dSChris Mason 	u64 flags;
3997f2984462SChris Mason 
39980b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3999fed3b381SLiu Bo 
4000fed3b381SLiu Bo 	/*
4001fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4002fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4003fed3b381SLiu Bo 	 * been consistent on disk.
4004fed3b381SLiu Bo 	 */
4005fed3b381SLiu Bo 	if (max_mirrors == 0)
40060b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4007f2984462SChris Mason 
40080b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4009a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4010e5e9a520SChris Mason 
40110b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
40120b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
40130b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4014387125fcSChris Mason 
40155af3e8ccSStefan Behrens 	if (do_barriers) {
40160b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
40175af3e8ccSStefan Behrens 		if (ret) {
40185af3e8ccSStefan Behrens 			mutex_unlock(
40190b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
40200b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
40215af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
40225af3e8ccSStefan Behrens 			return ret;
40235af3e8ccSStefan Behrens 		}
40245af3e8ccSStefan Behrens 	}
4025387125fcSChris Mason 
40261538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4027dfe25020SChris Mason 		if (!dev->bdev) {
4028dfe25020SChris Mason 			total_errors++;
4029dfe25020SChris Mason 			continue;
4030dfe25020SChris Mason 		}
4031e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4032ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4033dfe25020SChris Mason 			continue;
4034dfe25020SChris Mason 
40352b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4036a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4037a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
40387df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4039935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4040ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4041ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4042a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4043a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4044a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4045a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
40467239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
40477239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4048a512bbf8SYan Zheng 
4049a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4050a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4051f2984462SChris Mason 
405275cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
405375cb857dSQu Wenruo 		if (ret < 0) {
405475cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
405575cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
405675cb857dSQu Wenruo 				"unexpected superblock corruption detected");
405775cb857dSQu Wenruo 			return -EUCLEAN;
405875cb857dSQu Wenruo 		}
405975cb857dSQu Wenruo 
4060abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4061a236aed1SChris Mason 		if (ret)
4062a236aed1SChris Mason 			total_errors++;
4063f2984462SChris Mason 	}
4064a236aed1SChris Mason 	if (total_errors > max_errors) {
40650b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4066d397712bSChris Mason 			  total_errors);
40670b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
406879787eaaSJeff Mahoney 
40699d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
40700b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40710b246afaSJeff Mahoney 				      "%d errors while writing supers",
40720b246afaSJeff Mahoney 				      total_errors);
40739d565ba4SStefan Behrens 		return -EIO;
4074a236aed1SChris Mason 	}
4075f2984462SChris Mason 
4076a512bbf8SYan Zheng 	total_errors = 0;
40771538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4078dfe25020SChris Mason 		if (!dev->bdev)
4079dfe25020SChris Mason 			continue;
4080e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4081ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4082dfe25020SChris Mason 			continue;
4083dfe25020SChris Mason 
4084abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4085a512bbf8SYan Zheng 		if (ret)
40861259ab75SChris Mason 			total_errors++;
4087f2984462SChris Mason 	}
40880b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4089a236aed1SChris Mason 	if (total_errors > max_errors) {
40900b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40910b246afaSJeff Mahoney 				      "%d errors while writing supers",
40920b246afaSJeff Mahoney 				      total_errors);
409379787eaaSJeff Mahoney 		return -EIO;
4094a236aed1SChris Mason 	}
4095f2984462SChris Mason 	return 0;
4096f2984462SChris Mason }
4097f2984462SChris Mason 
4098cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4099cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4100cb517eabSMiao Xie 				  struct btrfs_root *root)
41012619ba1fSChris Mason {
41024785e24fSJosef Bacik 	bool drop_ref = false;
41034785e24fSJosef Bacik 
4104fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4105fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4106fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4107fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
41084785e24fSJosef Bacik 		drop_ref = true;
4109fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
411076dda93cSYan, Zheng 
411184961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4112ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
41131c1ea4f7SLiu Bo 		if (root->reloc_root) {
411400246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
41151c1ea4f7SLiu Bo 			root->reloc_root = NULL;
41161c1ea4f7SLiu Bo 		}
41171c1ea4f7SLiu Bo 	}
41183321719eSLiu Bo 
41194785e24fSJosef Bacik 	if (drop_ref)
412000246528SJosef Bacik 		btrfs_put_root(root);
41212619ba1fSChris Mason }
41222619ba1fSChris Mason 
4123c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4124c146afadSYan Zheng {
4125fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4126fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4127fc7cbcd4SDavid Sterba 	int i = 0;
412865d33fd7SQu Wenruo 	int err = 0;
4129fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4130c146afadSYan Zheng 
4131c146afadSYan Zheng 	while (1) {
4132fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4133fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4134fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4135fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4136fc7cbcd4SDavid Sterba 		if (!ret) {
4137fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4138c146afadSYan Zheng 			break;
413965d33fd7SQu Wenruo 		}
4140fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
414166b4ffd1SJosef Bacik 
4142fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4143fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4144fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4145fc7cbcd4SDavid Sterba 				gang[i] = NULL;
414665d33fd7SQu Wenruo 				continue;
4147c146afadSYan Zheng 			}
4148fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4149fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4150fc7cbcd4SDavid Sterba 		}
4151fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4152fc7cbcd4SDavid Sterba 
4153fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4154fc7cbcd4SDavid Sterba 			if (!gang[i])
4155fc7cbcd4SDavid Sterba 				continue;
4156fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4157fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4158fc7cbcd4SDavid Sterba 			if (err)
41596989627dSJosef Bacik 				goto out;
4160fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4161fc7cbcd4SDavid Sterba 		}
4162fc7cbcd4SDavid Sterba 		root_objectid++;
4163c146afadSYan Zheng 	}
41646989627dSJosef Bacik out:
4165fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4166fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4167fc7cbcd4SDavid Sterba 		if (gang[i])
4168fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
416965d33fd7SQu Wenruo 	}
417065d33fd7SQu Wenruo 	return err;
4171c146afadSYan Zheng }
4172c146afadSYan Zheng 
41736bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4174c146afadSYan Zheng {
41756bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4176c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4177c146afadSYan Zheng 
41780b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41792ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41800b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
41810b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4182c71bf099SYan, Zheng 
4183c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
41840b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41850b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4186c71bf099SYan, Zheng 
41877a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
41883612b495STsutomu Itoh 	if (IS_ERR(trans))
41893612b495STsutomu Itoh 		return PTR_ERR(trans);
41903a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4191c146afadSYan Zheng }
4192c146afadSYan Zheng 
419336c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
419436c86a9eSQu Wenruo {
419536c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
419636c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
419736c86a9eSQu Wenruo 	bool found = false;
419836c86a9eSQu Wenruo 
419936c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
420036c86a9eSQu Wenruo 		return;
420136c86a9eSQu Wenruo 
420236c86a9eSQu Wenruo 	/*
420336c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
420436c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
420536c86a9eSQu Wenruo 	 */
420636c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
420736c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
420836c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
420936c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
421036c86a9eSQu Wenruo 		u64 cur = 0;
421136c86a9eSQu Wenruo 		u64 found_start;
421236c86a9eSQu Wenruo 		u64 found_end;
421336c86a9eSQu Wenruo 
421436c86a9eSQu Wenruo 		found = true;
421536c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
421636c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
421736c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
421836c86a9eSQu Wenruo 			cur = found_end + 1;
421936c86a9eSQu Wenruo 		}
422036c86a9eSQu Wenruo 		btrfs_warn(fs_info,
422136c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
422236c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
422336c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
422436c86a9eSQu Wenruo 
422536c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
422636c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
422736c86a9eSQu Wenruo 		list_del_init(&trans->list);
422836c86a9eSQu Wenruo 
422936c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
423036c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
423136c86a9eSQu Wenruo 	}
423236c86a9eSQu Wenruo 	ASSERT(!found);
423336c86a9eSQu Wenruo }
423436c86a9eSQu Wenruo 
4235b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4236eb60ceacSChris Mason {
4237c146afadSYan Zheng 	int ret;
4238e089f05cSChris Mason 
4239afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
424031e70e52SFilipe Manana 
424131e70e52SFilipe Manana 	/*
42428a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
42438a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
42448a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
42458a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
42468a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
42478a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
42488a1f1e3dSFilipe Manana 	 * return 1.
42498a1f1e3dSFilipe Manana 	 */
42508a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
42518a1f1e3dSFilipe Manana 
42528a1f1e3dSFilipe Manana 	/*
425331e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
425431e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
425531e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
425631e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
425731e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
425831e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
425931e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
426031e70e52SFilipe Manana 	 */
426131e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4262d6fd0ae2SOmar Sandoval 	/*
4263d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4264d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4265d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4266d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4267d6fd0ae2SOmar Sandoval 	 */
4268d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4269a2135011SChris Mason 
42707343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4271d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
42727343dd61SJustin Maggard 
4273803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4274803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4275803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4276803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4277803b2f54SStefan Behrens 
4278837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4279aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4280837d5b6eSIlya Dryomov 
42818dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
42828dabb742SStefan Behrens 
4283aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
42844cb5300bSChris Mason 
42854cb5300bSChris Mason 	/* wait for any defraggers to finish */
42864cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
42874cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
42884cb5300bSChris Mason 
42894cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
429026176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
42914cb5300bSChris Mason 
4292a362bb86SFilipe Manana 	/*
4293a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4294a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4295a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4296a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4297a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4298a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4299a362bb86SFilipe Manana 	 * no one else to run iputs.
4300a362bb86SFilipe Manana 	 *
4301a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4302a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4303a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4304a362bb86SFilipe Manana 	 * through some other means.
4305a362bb86SFilipe Manana 	 *
4306a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4307a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4308a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4309a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4310a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4311a362bb86SFilipe Manana 	 */
4312a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4313a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4314a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4315a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4316a362bb86SFilipe Manana 
431721c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
431857056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4319576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
432021c7e756SMiao Xie 
4321b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4322b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4323b0643e59SDennis Zhou 
4324bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4325e44163e1SJeff Mahoney 		/*
4326d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4327d6fd0ae2SOmar Sandoval 		 * unused block groups.
4328e44163e1SJeff Mahoney 		 */
43290b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4330e44163e1SJeff Mahoney 
4331f0cc2cd7SFilipe Manana 		/*
4332f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4333f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4334f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4335f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4336f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4337f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4338f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4339f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4340f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4341f0cc2cd7SFilipe Manana 		 */
4342f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4343f0cc2cd7SFilipe Manana 
43446bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4345d397712bSChris Mason 		if (ret)
434604892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4347c146afadSYan Zheng 	}
4348ed2ff2cbSChris Mason 
434984961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
43502ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4351acce952bSliubo 
4352e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4353e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
43548929ecfaSYan, Zheng 
4355e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4356afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4357f25784b3SYan Zheng 
43585958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
43595958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
43605958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
43615958253cSQu Wenruo 	}
43625958253cSQu Wenruo 
436304892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4364fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4365bcef60f2SArne Jansen 
4366963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
436704892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4368963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4369b0c68f8bSChris Mason 	}
437031153d81SYan Zheng 
43715deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
43724297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
43735deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
43744297ff84SJosef Bacik 
43756618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4376b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
43775ac1d209SJeff Mahoney 
43781a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
43791a4319ccSLiu Bo 
4380de348ee0SWang Shilong 	/*
4381de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4382de348ee0SWang Shilong 	 * submit after we stopping all workers.
4383de348ee0SWang Shilong 	 */
4384de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
438596192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
438696192499SJosef Bacik 
43870a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
438836c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
43890a31daa4SFilipe Manana 
4390afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
43914273eaffSAnand Jain 	free_root_pointers(fs_info, true);
43928c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
43939ad6b7bcSChris Mason 
43944e19443dSJosef Bacik 	/*
43954e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
43964e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
43974e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
43984e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
43994e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
44004e19443dSJosef Bacik 	 */
44014e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
44024e19443dSJosef Bacik 
440313e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4404d6bfde87SChris Mason 
440521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
44060b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
44072ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
440821adbd5cSStefan Behrens #endif
440921adbd5cSStefan Behrens 
44100b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
441168c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4412eb60ceacSChris Mason }
4413eb60ceacSChris Mason 
44145f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
44155f39d397SChris Mason {
44162f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
44175f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4418b4ce94deSChris Mason 
441906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
442006ea65a3SJosef Bacik 	/*
442106ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
442252042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
442306ea65a3SJosef Bacik 	 * outside of the sanity tests.
442406ea65a3SJosef Bacik 	 */
4425b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
442606ea65a3SJosef Bacik 		return;
442706ea65a3SJosef Bacik #endif
442849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
44290b246afaSJeff Mahoney 	if (transid != fs_info->generation)
44305d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
44310b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
4432f18cc978SChristoph Hellwig 	set_extent_buffer_dirty(buf);
44331f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
443469fc6cbbSQu Wenruo 	/*
443585d8a826SJosef Bacik 	 * btrfs_check_leaf() won't check item data if we don't have WRITTEN
443685d8a826SJosef Bacik 	 * set, so this will only validate the basic structure of the items.
443769fc6cbbSQu Wenruo 	 */
443885d8a826SJosef Bacik 	if (btrfs_header_level(buf) == 0 && btrfs_check_leaf(buf)) {
4439a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
44401f21ef0aSFilipe Manana 		ASSERT(0);
44411f21ef0aSFilipe Manana 	}
44421f21ef0aSFilipe Manana #endif
4443eb60ceacSChris Mason }
4444eb60ceacSChris Mason 
44452ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4446b53d3f5dSLiu Bo 					int flush_delayed)
444735b7e476SChris Mason {
4448188de649SChris Mason 	/*
4449188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4450188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4451188de649SChris Mason 	 */
4452e2d84521SMiao Xie 	int ret;
4453d6bfde87SChris Mason 
44546933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4455d6bfde87SChris Mason 		return;
4456d6bfde87SChris Mason 
4457b53d3f5dSLiu Bo 	if (flush_delayed)
44582ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
445916cdcec7SMiao Xie 
4460d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4461d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4462d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4463e2d84521SMiao Xie 	if (ret > 0) {
44640b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
446516cdcec7SMiao Xie 	}
446616cdcec7SMiao Xie }
446716cdcec7SMiao Xie 
44682ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
446916cdcec7SMiao Xie {
44702ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
447135b7e476SChris Mason }
4472b53d3f5dSLiu Bo 
44732ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4474b53d3f5dSLiu Bo {
44752ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4476d6bfde87SChris Mason }
44776b80053dSChris Mason 
44782ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4479acce952bSliubo {
4480fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4481fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4482fe816d0fSNikolay Borisov 
44830b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
44842ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
44850b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4486acce952bSliubo 
44870b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
44880b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4489acce952bSliubo }
4490acce952bSliubo 
4491ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4492ef67963dSJosef Bacik {
4493fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4494fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4495fc7cbcd4SDavid Sterba 	int ret;
4496ef67963dSJosef Bacik 
4497fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4498fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4499fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4500fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4501fc7cbcd4SDavid Sterba 		int i;
4502ef67963dSJosef Bacik 
4503fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4504fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4505fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4506fc7cbcd4SDavid Sterba 
4507fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4508fc7cbcd4SDavid Sterba 			if (!gang[i])
4509ef67963dSJosef Bacik 				continue;
4510fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4511fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4512fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4513ef67963dSJosef Bacik 		}
4514fc7cbcd4SDavid Sterba 		root_objectid++;
4515fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4516ef67963dSJosef Bacik 	}
4517fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4518ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4519ef67963dSJosef Bacik }
4520ef67963dSJosef Bacik 
4521143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4522acce952bSliubo {
4523acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4524acce952bSliubo 
4525199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4526779880efSJosef Bacik 	/*
4527779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4528779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4529779880efSJosef Bacik 	 */
4530199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4531779880efSJosef Bacik 			    root_extent_list)
4532779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4533199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4534199c2a9cSMiao Xie }
4535199c2a9cSMiao Xie 
4536199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4537199c2a9cSMiao Xie {
4538199c2a9cSMiao Xie 	struct btrfs_root *root;
4539199c2a9cSMiao Xie 	struct list_head splice;
4540199c2a9cSMiao Xie 
4541199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4542199c2a9cSMiao Xie 
4543199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4544199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4545199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4546199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4547199c2a9cSMiao Xie 					ordered_root);
45481de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
45491de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4550199c2a9cSMiao Xie 
45512a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4552199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4553199c2a9cSMiao Xie 
45542a85d9caSLiu Bo 		cond_resched();
45552a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4556199c2a9cSMiao Xie 	}
4557199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
455874d5d229SJosef Bacik 
455974d5d229SJosef Bacik 	/*
456074d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
456174d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
456274d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
456374d5d229SJosef Bacik 	 * actually get run and error out properly.
456474d5d229SJosef Bacik 	 */
456574d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4566acce952bSliubo }
4567acce952bSliubo 
456899f09ce3SFilipe Manana static void btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
45692ff7e61eSJeff Mahoney 				       struct btrfs_fs_info *fs_info)
4570acce952bSliubo {
4571acce952bSliubo 	struct rb_node *node;
4572acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4573acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4574acce952bSliubo 
4575acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4576acce952bSliubo 
4577acce952bSliubo 	spin_lock(&delayed_refs->lock);
4578d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4579cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4580b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
458199f09ce3SFilipe Manana 		return;
4582acce952bSliubo 	}
4583acce952bSliubo 
45845c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4585d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
45860e0adbcfSJosef Bacik 		struct rb_node *n;
4587e78417d1SJosef Bacik 		bool pin_bytes = false;
4588acce952bSliubo 
4589d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4590d7df2c79SJosef Bacik 				href_node);
45913069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4592b939d1abSJosef Bacik 			continue;
45933069bd26SJosef Bacik 
4594d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4595e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
45960e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
45970e0adbcfSJosef Bacik 				       ref_node);
4598e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
45990e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
46001d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
46011d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4602d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4603d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4604d7df2c79SJosef Bacik 		}
460554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4606e78417d1SJosef Bacik 			pin_bytes = true;
460778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4608fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4609d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4610acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4611e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4612acce952bSliubo 
4613f603bb94SNikolay Borisov 		if (pin_bytes) {
4614f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4615f603bb94SNikolay Borisov 
4616f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4617f603bb94SNikolay Borisov 			BUG_ON(!cache);
4618f603bb94SNikolay Borisov 
4619f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4620f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4621f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4622f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4623f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4624f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4625f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4626f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4627f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4628f603bb94SNikolay Borisov 
4629f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4630f603bb94SNikolay Borisov 
4631f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4632f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4633f603bb94SNikolay Borisov 		}
463431890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4635d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4636acce952bSliubo 		cond_resched();
4637acce952bSliubo 		spin_lock(&delayed_refs->lock);
4638acce952bSliubo 	}
463981f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4640acce952bSliubo 
4641acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4642acce952bSliubo }
4643acce952bSliubo 
4644143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4645acce952bSliubo {
4646acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4647acce952bSliubo 	struct list_head splice;
4648acce952bSliubo 
4649acce952bSliubo 	INIT_LIST_HEAD(&splice);
4650acce952bSliubo 
4651eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4652eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4653acce952bSliubo 
4654acce952bSliubo 	while (!list_empty(&splice)) {
4655fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4656eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4657acce952bSliubo 					       delalloc_inodes);
4658fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4659eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4660acce952bSliubo 
4661fe816d0fSNikolay Borisov 		/*
4662fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4663fe816d0fSNikolay Borisov 		 * meanwhile.
4664fe816d0fSNikolay Borisov 		 */
4665fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4666fe816d0fSNikolay Borisov 		if (inode) {
4667597441b3SJosef Bacik 			unsigned int nofs_flag;
4668597441b3SJosef Bacik 
4669597441b3SJosef Bacik 			nofs_flag = memalloc_nofs_save();
4670fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4671597441b3SJosef Bacik 			memalloc_nofs_restore(nofs_flag);
4672fe816d0fSNikolay Borisov 			iput(inode);
4673fe816d0fSNikolay Borisov 		}
4674eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4675acce952bSliubo 	}
4676eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4677eb73c1b7SMiao Xie }
4678eb73c1b7SMiao Xie 
4679eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4680eb73c1b7SMiao Xie {
4681eb73c1b7SMiao Xie 	struct btrfs_root *root;
4682eb73c1b7SMiao Xie 	struct list_head splice;
4683eb73c1b7SMiao Xie 
4684eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4685eb73c1b7SMiao Xie 
4686eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4687eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4688eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4689eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4690eb73c1b7SMiao Xie 					 delalloc_root);
469100246528SJosef Bacik 		root = btrfs_grab_root(root);
4692eb73c1b7SMiao Xie 		BUG_ON(!root);
4693eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4694eb73c1b7SMiao Xie 
4695eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
469600246528SJosef Bacik 		btrfs_put_root(root);
4697eb73c1b7SMiao Xie 
4698eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4699eb73c1b7SMiao Xie 	}
4700eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4701acce952bSliubo }
4702acce952bSliubo 
47032ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4704acce952bSliubo 					struct extent_io_tree *dirty_pages,
4705acce952bSliubo 					int mark)
4706acce952bSliubo {
4707acce952bSliubo 	int ret;
4708acce952bSliubo 	struct extent_buffer *eb;
4709acce952bSliubo 	u64 start = 0;
4710acce952bSliubo 	u64 end;
4711acce952bSliubo 
4712acce952bSliubo 	while (1) {
4713acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4714e6138876SJosef Bacik 					    mark, NULL);
4715acce952bSliubo 		if (ret)
4716acce952bSliubo 			break;
4717acce952bSliubo 
471891166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4719acce952bSliubo 		while (start <= end) {
47200b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
47210b246afaSJeff Mahoney 			start += fs_info->nodesize;
4722fd8b2b61SJosef Bacik 			if (!eb)
4723acce952bSliubo 				continue;
4724acce952bSliubo 
4725c4e54a65SJosef Bacik 			btrfs_tree_lock(eb);
4726c4e54a65SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4727190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(NULL, eb);
4728c4e54a65SJosef Bacik 			btrfs_tree_unlock(eb);
4729c4e54a65SJosef Bacik 
4730fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4731acce952bSliubo 		}
4732acce952bSliubo 	}
4733acce952bSliubo 
4734acce952bSliubo 	return ret;
4735acce952bSliubo }
4736acce952bSliubo 
47372ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4738fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4739acce952bSliubo {
4740acce952bSliubo 	u64 start;
4741acce952bSliubo 	u64 end;
4742acce952bSliubo 	int ret;
4743acce952bSliubo 
4744acce952bSliubo 	while (1) {
47450e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
47460e6ec385SFilipe Manana 
4747fcd5e742SLu Fengqi 		/*
4748fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4749fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4750fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4751fcd5e742SLu Fengqi 		 * the same extent range.
4752fcd5e742SLu Fengqi 		 */
4753fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4754acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
47550e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4756fcd5e742SLu Fengqi 		if (ret) {
4757fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4758acce952bSliubo 			break;
4759fcd5e742SLu Fengqi 		}
4760acce952bSliubo 
47610e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
47620e6ec385SFilipe Manana 		free_extent_state(cached_state);
47632ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4764fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4765acce952bSliubo 		cond_resched();
4766acce952bSliubo 	}
4767acce952bSliubo 
4768acce952bSliubo 	return 0;
4769acce952bSliubo }
4770acce952bSliubo 
477132da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4772c79a1751SLiu Bo {
4773c79a1751SLiu Bo 	struct inode *inode;
4774c79a1751SLiu Bo 
4775c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4776c79a1751SLiu Bo 	if (inode) {
4777597441b3SJosef Bacik 		unsigned int nofs_flag;
4778597441b3SJosef Bacik 
4779597441b3SJosef Bacik 		nofs_flag = memalloc_nofs_save();
4780c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4781597441b3SJosef Bacik 		memalloc_nofs_restore(nofs_flag);
4782597441b3SJosef Bacik 
4783c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4784c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4785c79a1751SLiu Bo 		iput(inode);
4786c79a1751SLiu Bo 	}
4787bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4788c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4789c79a1751SLiu Bo }
4790c79a1751SLiu Bo 
4791c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
47922ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4793c79a1751SLiu Bo {
479432da5386SDavid Sterba 	struct btrfs_block_group *cache;
4795c79a1751SLiu Bo 
4796c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4797c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4798c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
479932da5386SDavid Sterba 					 struct btrfs_block_group,
4800c79a1751SLiu Bo 					 dirty_list);
4801c79a1751SLiu Bo 
4802c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4803c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4804c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4805c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4806c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4807c79a1751SLiu Bo 		}
4808c79a1751SLiu Bo 
4809c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4810c79a1751SLiu Bo 		spin_lock(&cache->lock);
4811c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4812c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4813c79a1751SLiu Bo 
4814c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4815c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4816ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4817c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4818c79a1751SLiu Bo 	}
4819c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4820c79a1751SLiu Bo 
482145ae2c18SNikolay Borisov 	/*
482245ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
482345ae2c18SNikolay Borisov 	 * to use it without any locking
482445ae2c18SNikolay Borisov 	 */
4825c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4826c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
482732da5386SDavid Sterba 					 struct btrfs_block_group,
4828c79a1751SLiu Bo 					 io_list);
4829c79a1751SLiu Bo 
4830c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4831c79a1751SLiu Bo 		spin_lock(&cache->lock);
4832c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4833c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4834c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4835c79a1751SLiu Bo 	}
4836c79a1751SLiu Bo }
4837c79a1751SLiu Bo 
483849b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
48392ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
484049b25e05SJeff Mahoney {
4841bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4842bbbf7243SNikolay Borisov 
48432ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4844c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4845c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4846c79a1751SLiu Bo 
4847bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4848bbbf7243SNikolay Borisov 				 post_commit_list) {
4849bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4850bbbf7243SNikolay Borisov 	}
4851bbbf7243SNikolay Borisov 
48522ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
485349b25e05SJeff Mahoney 
48544a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
48550b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
485649b25e05SJeff Mahoney 
48574a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
48580b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
485949b25e05SJeff Mahoney 
4860ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
486167cde344SMiao Xie 
48622ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
486349b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4864fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
486549b25e05SJeff Mahoney 
48664a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
48674a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
486849b25e05SJeff Mahoney }
486949b25e05SJeff Mahoney 
48702ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4871acce952bSliubo {
4872acce952bSliubo 	struct btrfs_transaction *t;
4873acce952bSliubo 
48740b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4875acce952bSliubo 
48760b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
48770b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
48780b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4879724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4880724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
48819b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
48820b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
48832ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4884724e2315SJosef Bacik 			btrfs_put_transaction(t);
48850b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4886724e2315SJosef Bacik 			continue;
4887724e2315SJosef Bacik 		}
48880b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4889724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
48900b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4891724e2315SJosef Bacik 			/*
4892724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4893724e2315SJosef Bacik 			 * handle open currently for this transaction.
4894724e2315SJosef Bacik 			 */
4895724e2315SJosef Bacik 			wait_event(t->writer_wait,
4896724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4897724e2315SJosef Bacik 		} else {
48980b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4899724e2315SJosef Bacik 		}
49002ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4901724e2315SJosef Bacik 
49020b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
49030b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
49040b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4905724e2315SJosef Bacik 		list_del_init(&t->list);
49060b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4907a4abeea4SJosef Bacik 
4908724e2315SJosef Bacik 		btrfs_put_transaction(t);
49092e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
49100b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4911724e2315SJosef Bacik 	}
49120b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
49130b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4914ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4915ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
49160b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4917ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
49180b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4919acce952bSliubo 
4920acce952bSliubo 	return 0;
4921acce952bSliubo }
4922ec7d6dfdSNikolay Borisov 
4923453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4924ec7d6dfdSNikolay Borisov {
4925ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
4926ec7d6dfdSNikolay Borisov 	int ret;
4927ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
4928ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
4929ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
4930ec7d6dfdSNikolay Borisov 	int slot;
4931ec7d6dfdSNikolay Borisov 
4932ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
4933ec7d6dfdSNikolay Borisov 	if (!path)
4934ec7d6dfdSNikolay Borisov 		return -ENOMEM;
4935ec7d6dfdSNikolay Borisov 
4936ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4937ec7d6dfdSNikolay Borisov 	search_key.type = -1;
4938ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
4939ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4940ec7d6dfdSNikolay Borisov 	if (ret < 0)
4941ec7d6dfdSNikolay Borisov 		goto error;
4942ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
4943ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
4944ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
4945ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
4946ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
494723125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
494823125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
4949ec7d6dfdSNikolay Borisov 	} else {
495023125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4951ec7d6dfdSNikolay Borisov 	}
4952ec7d6dfdSNikolay Borisov 	ret = 0;
4953ec7d6dfdSNikolay Borisov error:
4954ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
4955ec7d6dfdSNikolay Borisov 	return ret;
4956ec7d6dfdSNikolay Borisov }
4957ec7d6dfdSNikolay Borisov 
4958543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4959ec7d6dfdSNikolay Borisov {
4960ec7d6dfdSNikolay Borisov 	int ret;
4961ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
4962ec7d6dfdSNikolay Borisov 
49636b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4964ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
4965ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
4966ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
4967ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
4968ec7d6dfdSNikolay Borisov 		goto out;
4969ec7d6dfdSNikolay Borisov 	}
4970ec7d6dfdSNikolay Borisov 
497123125104SNikolay Borisov 	*objectid = root->free_objectid++;
4972ec7d6dfdSNikolay Borisov 	ret = 0;
4973ec7d6dfdSNikolay Borisov out:
4974ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
4975ec7d6dfdSNikolay Borisov 	return ret;
4976ec7d6dfdSNikolay Borisov }
4977