xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 413fb1bc)
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 
63143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
64acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
652ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
66143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
672ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
68acce952bSliubo 					struct extent_io_tree *dirty_pages,
69acce952bSliubo 					int mark);
702ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
71acce952bSliubo 				       struct extent_io_tree *pinned_extents);
722ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
732ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
74ce9adaa5SChris Mason 
75141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
76141386e1SJosef Bacik {
77141386e1SJosef Bacik 	if (fs_info->csum_shash)
78141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
79141386e1SJosef Bacik }
80141386e1SJosef Bacik 
81d352ac68SChris Mason /*
822996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
83d352ac68SChris Mason  */
84c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
8519c00ddcSChris Mason {
86d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
877280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
88a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
89d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
9019c00ddcSChris Mason 	char *kaddr;
91e9be5a30SDavid Sterba 	int i;
92d5178578SJohannes Thumshirn 
93d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
94d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
95a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
96e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
97a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
9819c00ddcSChris Mason 
995ad9b471Spengfuyuan 	for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
100e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
101e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
10219c00ddcSChris Mason 	}
10371a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
104d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
10519c00ddcSChris Mason }
10619c00ddcSChris Mason 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
109d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
110d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
111d352ac68SChris Mason  * in the wrong place.
112d352ac68SChris Mason  */
113d87e6575SChristoph Hellwig int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid, int atomic)
1141259ab75SChris Mason {
115d87e6575SChristoph Hellwig 	if (!extent_buffer_uptodate(eb))
116d87e6575SChristoph Hellwig 		return 0;
1171259ab75SChris Mason 
1181259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
119d87e6575SChristoph Hellwig 		return 1;
1201259ab75SChris Mason 
121b9fab919SChris Mason 	if (atomic)
122b9fab919SChris Mason 		return -EAGAIN;
123b9fab919SChris Mason 
124d87e6575SChristoph Hellwig 	if (!extent_buffer_uptodate(eb) ||
125d87e6575SChristoph Hellwig 	    btrfs_header_generation(eb) != parent_transid) {
12694647322SDavid Sterba 		btrfs_err_rl(eb->fs_info,
1278f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1288f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
12929549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1300b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
1319e2aff90SChristoph Hellwig 		return 0;
132d87e6575SChristoph Hellwig 	}
1339e2aff90SChristoph Hellwig 	return 1;
1341259ab75SChris Mason }
1351259ab75SChris Mason 
136e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
137e7e16f48SJohannes Thumshirn {
138e7e16f48SJohannes Thumshirn 	switch (csum_type) {
139e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1403951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1413831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
142352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
143e7e16f48SJohannes Thumshirn 		return true;
144e7e16f48SJohannes Thumshirn 	default:
145e7e16f48SJohannes Thumshirn 		return false;
146e7e16f48SJohannes Thumshirn 	}
147e7e16f48SJohannes Thumshirn }
148e7e16f48SJohannes Thumshirn 
149d352ac68SChris Mason /*
1501104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1511104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1521104a885SDavid Sterba  */
1533d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1543d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1551104a885SDavid Sterba {
15651bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
157d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
158d5178578SJohannes Thumshirn 
159d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1601104a885SDavid Sterba 
1611104a885SDavid Sterba 	/*
1621104a885SDavid Sterba 	 * The super_block structure does not span the whole
16351bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
16451bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1651104a885SDavid Sterba 	 */
1663d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
167fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1681104a885SDavid Sterba 
16955fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
170e7e16f48SJohannes Thumshirn 		return 1;
1711104a885SDavid Sterba 
172e7e16f48SJohannes Thumshirn 	return 0;
1731104a885SDavid Sterba }
1741104a885SDavid Sterba 
175bacf60e5SChristoph Hellwig static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
176bacf60e5SChristoph Hellwig 				      int mirror_num)
177bacf60e5SChristoph Hellwig {
178bacf60e5SChristoph Hellwig 	struct btrfs_fs_info *fs_info = eb->fs_info;
179bacf60e5SChristoph Hellwig 	int i, num_pages = num_extent_pages(eb);
180bacf60e5SChristoph Hellwig 	int ret = 0;
181bacf60e5SChristoph Hellwig 
182bacf60e5SChristoph Hellwig 	if (sb_rdonly(fs_info->sb))
183bacf60e5SChristoph Hellwig 		return -EROFS;
184bacf60e5SChristoph Hellwig 
185bacf60e5SChristoph Hellwig 	for (i = 0; i < num_pages; i++) {
186bacf60e5SChristoph Hellwig 		struct page *p = eb->pages[i];
187917ac778SQu Wenruo 		u64 start = max_t(u64, eb->start, page_offset(p));
188917ac778SQu Wenruo 		u64 end = min_t(u64, eb->start + eb->len, page_offset(p) + PAGE_SIZE);
189917ac778SQu Wenruo 		u32 len = end - start;
190bacf60e5SChristoph Hellwig 
191917ac778SQu Wenruo 		ret = btrfs_repair_io_failure(fs_info, 0, start, len,
192917ac778SQu Wenruo 				start, p, offset_in_page(start), mirror_num);
193bacf60e5SChristoph Hellwig 		if (ret)
194bacf60e5SChristoph Hellwig 			break;
195bacf60e5SChristoph Hellwig 	}
196bacf60e5SChristoph Hellwig 
197bacf60e5SChristoph Hellwig 	return ret;
198bacf60e5SChristoph Hellwig }
199bacf60e5SChristoph Hellwig 
2001104a885SDavid Sterba /*
201d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
202d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
203581c1760SQu Wenruo  *
204789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see the comments of the
205789d6a3aSQu Wenruo  *			structure for details.
206d352ac68SChris Mason  */
2076a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
208789d6a3aSQu Wenruo 			     struct btrfs_tree_parent_check *check)
209f188591eSChris Mason {
2105ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
211ea466794SJosef Bacik 	int failed = 0;
212f188591eSChris Mason 	int ret;
213f188591eSChris Mason 	int num_copies = 0;
214f188591eSChris Mason 	int mirror_num = 0;
215ea466794SJosef Bacik 	int failed_mirror = 0;
216f188591eSChris Mason 
217789d6a3aSQu Wenruo 	ASSERT(check);
218789d6a3aSQu Wenruo 
219f188591eSChris Mason 	while (1) {
220f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
221947a6299SQu Wenruo 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
222947a6299SQu Wenruo 		if (!ret)
223581c1760SQu Wenruo 			break;
224d397712bSChris Mason 
2250b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
226f188591eSChris Mason 					      eb->start, eb->len);
2274235298eSChris Mason 		if (num_copies == 1)
228ea466794SJosef Bacik 			break;
2294235298eSChris Mason 
2305cf1ab56SJosef Bacik 		if (!failed_mirror) {
2315cf1ab56SJosef Bacik 			failed = 1;
2325cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
2335cf1ab56SJosef Bacik 		}
2345cf1ab56SJosef Bacik 
235f188591eSChris Mason 		mirror_num++;
236ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
237ea466794SJosef Bacik 			mirror_num++;
238ea466794SJosef Bacik 
2394235298eSChris Mason 		if (mirror_num > num_copies)
240ea466794SJosef Bacik 			break;
241f188591eSChris Mason 	}
242ea466794SJosef Bacik 
243c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
24420a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
245ea466794SJosef Bacik 
246ea466794SJosef Bacik 	return ret;
247f188591eSChris Mason }
24819c00ddcSChris Mason 
24931d89399SChristoph Hellwig /*
25031d89399SChristoph Hellwig  * Checksum a dirty tree block before IO.
25131d89399SChristoph Hellwig  */
25231d89399SChristoph Hellwig blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)
253eca0f6f6SQu Wenruo {
25431d89399SChristoph Hellwig 	struct extent_buffer *eb = bbio->private;
255eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
25631d89399SChristoph Hellwig 	u64 found_start = btrfs_header_bytenr(eb);
257eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
258eca0f6f6SQu Wenruo 	int ret;
259eca0f6f6SQu Wenruo 
26031d89399SChristoph Hellwig 	/* Btree blocks are always contiguous on disk. */
26131d89399SChristoph Hellwig 	if (WARN_ON_ONCE(bbio->file_offset != eb->start))
26231d89399SChristoph Hellwig 		return BLK_STS_IOERR;
26331d89399SChristoph Hellwig 	if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
26431d89399SChristoph Hellwig 		return BLK_STS_IOERR;
26531d89399SChristoph Hellwig 
26631d89399SChristoph Hellwig 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
26731d89399SChristoph Hellwig 		WARN_ON_ONCE(found_start != 0);
26831d89399SChristoph Hellwig 		return BLK_STS_OK;
26931d89399SChristoph Hellwig 	}
27031d89399SChristoph Hellwig 
27131d89399SChristoph Hellwig 	if (WARN_ON_ONCE(found_start != eb->start))
27231d89399SChristoph Hellwig 		return BLK_STS_IOERR;
27331d89399SChristoph Hellwig 	if (WARN_ON(!btrfs_page_test_uptodate(fs_info, eb->pages[0], eb->start,
27431d89399SChristoph Hellwig 					      eb->len)))
27531d89399SChristoph Hellwig 		return BLK_STS_IOERR;
27631d89399SChristoph Hellwig 
277eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
278eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
279eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
280eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
281eca0f6f6SQu Wenruo 
282eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
283eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
284eca0f6f6SQu Wenruo 	else
28585d8a826SJosef Bacik 		ret = btrfs_check_leaf(eb);
286eca0f6f6SQu Wenruo 
2873777369fSQu Wenruo 	if (ret < 0)
2883777369fSQu Wenruo 		goto error;
2893777369fSQu Wenruo 
2903777369fSQu Wenruo 	/*
2913777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
2923777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
2933777369fSQu Wenruo 	 */
2943777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
2953777369fSQu Wenruo 		ret = -EUCLEAN;
296eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
2973777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
2983777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
2993777369fSQu Wenruo 			  fs_info->last_trans_committed);
3003777369fSQu Wenruo 		goto error;
301eca0f6f6SQu Wenruo 	}
302eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
30331d89399SChristoph Hellwig 	return BLK_STS_OK;
3043777369fSQu Wenruo 
3053777369fSQu Wenruo error:
3063777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
3073777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
3083777369fSQu Wenruo 		  eb->start);
30916199ad9SFilipe Manana 	/*
31016199ad9SFilipe Manana 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
31116199ad9SFilipe Manana 	 * a transaction in case there's a bad log tree extent buffer, we just
31216199ad9SFilipe Manana 	 * fallback to a transaction commit. Still we want to know when there is
31316199ad9SFilipe Manana 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
31416199ad9SFilipe Manana 	 */
31516199ad9SFilipe Manana 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
31616199ad9SFilipe Manana 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
317deb6216fSChristoph Hellwig 	return errno_to_blk_status(ret);
318deb6216fSChristoph Hellwig }
319deb6216fSChristoph Hellwig 
320*413fb1bcSAnand Jain static bool check_tree_block_fsid(struct extent_buffer *eb)
3212b82032cSYan Zheng {
322b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
323944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
32444880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
325944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
3262b82032cSYan Zheng 
3279a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
3289a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
3297239ff4bSNikolay Borisov 	/*
330944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
331944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
332944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
3337239ff4bSNikolay Borisov 	 */
334944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
3357239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
3367239ff4bSNikolay Borisov 	else
3377239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
3387239ff4bSNikolay Borisov 
339944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
340*413fb1bcSAnand Jain 		return false;
341944d3f9fSNikolay Borisov 
342944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
343944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
344*413fb1bcSAnand Jain 			return false;
345944d3f9fSNikolay Borisov 
346*413fb1bcSAnand Jain 	return true;
3472b82032cSYan Zheng }
3482b82032cSYan Zheng 
34977bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
350046b562bSChristoph Hellwig int btrfs_validate_extent_buffer(struct extent_buffer *eb,
351947a6299SQu Wenruo 				 struct btrfs_tree_parent_check *check)
352ce9adaa5SChris Mason {
35377bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
354ce9adaa5SChris Mason 	u64 found_start;
35577bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
35677bf40a2SQu Wenruo 	u8 found_level;
3572996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
358dfd29eedSDavid Sterba 	const u8 *header_csum;
35977bf40a2SQu Wenruo 	int ret = 0;
360ea466794SJosef Bacik 
361947a6299SQu Wenruo 	ASSERT(check);
362947a6299SQu Wenruo 
363ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
364727011e0SChris Mason 	if (found_start != eb->start) {
3658f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
3668f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
3678f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
368f188591eSChris Mason 		ret = -EIO;
36977bf40a2SQu Wenruo 		goto out;
370ce9adaa5SChris Mason 	}
371b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
3728f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
3738f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
3741259ab75SChris Mason 		ret = -EIO;
37577bf40a2SQu Wenruo 		goto out;
3761259ab75SChris Mason 	}
377ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
3781c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
3798f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
3808f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
3818f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
3821c24c3ceSJosef Bacik 		ret = -EIO;
38377bf40a2SQu Wenruo 		goto out;
3841c24c3ceSJosef Bacik 	}
385ce9adaa5SChris Mason 
386c67b3892SDavid Sterba 	csum_tree_block(eb, result);
387dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
388dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
389a826d6dcSJosef Bacik 
390dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
3912996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
3928f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
3938f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
394dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
39535be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
39635be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
3972996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
39877bf40a2SQu Wenruo 		goto out;
3992996e1f8SJohannes Thumshirn 	}
4002996e1f8SJohannes Thumshirn 
401947a6299SQu Wenruo 	if (found_level != check->level) {
40277177ed1SQu Wenruo 		btrfs_err(fs_info,
40377177ed1SQu Wenruo 		"level verify failed on logical %llu mirror %u wanted %u found %u",
40477177ed1SQu Wenruo 			  eb->start, eb->read_mirror, check->level, found_level);
405947a6299SQu Wenruo 		ret = -EIO;
406947a6299SQu Wenruo 		goto out;
407947a6299SQu Wenruo 	}
408947a6299SQu Wenruo 	if (unlikely(check->transid &&
409947a6299SQu Wenruo 		     btrfs_header_generation(eb) != check->transid)) {
410947a6299SQu Wenruo 		btrfs_err_rl(eb->fs_info,
411947a6299SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
412947a6299SQu Wenruo 				eb->start, eb->read_mirror, check->transid,
413947a6299SQu Wenruo 				btrfs_header_generation(eb));
414947a6299SQu Wenruo 		ret = -EIO;
415947a6299SQu Wenruo 		goto out;
416947a6299SQu Wenruo 	}
417947a6299SQu Wenruo 	if (check->has_first_key) {
418947a6299SQu Wenruo 		struct btrfs_key *expect_key = &check->first_key;
419947a6299SQu Wenruo 		struct btrfs_key found_key;
420947a6299SQu Wenruo 
421947a6299SQu Wenruo 		if (found_level)
422947a6299SQu Wenruo 			btrfs_node_key_to_cpu(eb, &found_key, 0);
423947a6299SQu Wenruo 		else
424947a6299SQu Wenruo 			btrfs_item_key_to_cpu(eb, &found_key, 0);
425947a6299SQu Wenruo 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
426947a6299SQu Wenruo 			btrfs_err(fs_info,
427947a6299SQu Wenruo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
428947a6299SQu Wenruo 				  eb->start, check->transid,
429947a6299SQu Wenruo 				  expect_key->objectid,
430947a6299SQu Wenruo 				  expect_key->type, expect_key->offset,
431947a6299SQu Wenruo 				  found_key.objectid, found_key.type,
432947a6299SQu Wenruo 				  found_key.offset);
433947a6299SQu Wenruo 			ret = -EUCLEAN;
434947a6299SQu Wenruo 			goto out;
435947a6299SQu Wenruo 		}
436947a6299SQu Wenruo 	}
437947a6299SQu Wenruo 	if (check->owner_root) {
438947a6299SQu Wenruo 		ret = btrfs_check_eb_owner(eb, check->owner_root);
439947a6299SQu Wenruo 		if (ret < 0)
440947a6299SQu Wenruo 			goto out;
441947a6299SQu Wenruo 	}
442947a6299SQu Wenruo 
443a826d6dcSJosef Bacik 	/*
444a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
445a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
446a826d6dcSJosef Bacik 	 * return -EIO.
447a826d6dcSJosef Bacik 	 */
44885d8a826SJosef Bacik 	if (found_level == 0 && btrfs_check_leaf(eb)) {
449a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
450a826d6dcSJosef Bacik 		ret = -EIO;
451a826d6dcSJosef Bacik 	}
452ce9adaa5SChris Mason 
453813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
454053ab70fSLiu Bo 		ret = -EIO;
455053ab70fSLiu Bo 
456aebcc159SChristoph Hellwig 	if (ret)
45775391f0dSQu Wenruo 		btrfs_err(fs_info,
4588f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
4598f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
46077bf40a2SQu Wenruo out:
46177bf40a2SQu Wenruo 	return ret;
46277bf40a2SQu Wenruo }
46377bf40a2SQu Wenruo 
4643dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
4658958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
4668958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
467784b4e29SChris Mason {
468784b4e29SChris Mason 	/*
469784b4e29SChris Mason 	 * we can't safely write a btree page from here,
470784b4e29SChris Mason 	 * we haven't done the locking hook
471784b4e29SChris Mason 	 */
4728958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
473784b4e29SChris Mason 		return -EAGAIN;
474784b4e29SChris Mason 	/*
475784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
476784b4e29SChris Mason 	 * We must have no buffers or drop them.
477784b4e29SChris Mason 	 */
4788958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
4798958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
480784b4e29SChris Mason 		return -EAGAIN;
48154184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
482784b4e29SChris Mason }
4838958b551SMatthew Wilcox (Oracle) #else
4848958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
4853dd1462eSJan Beulich #endif
486784b4e29SChris Mason 
4870da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
4880da5468fSChris Mason 			    struct writeback_control *wbc)
4890da5468fSChris Mason {
490e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
491e2d84521SMiao Xie 	int ret;
492e2d84521SMiao Xie 
493d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
494448d640bSChris Mason 
495448d640bSChris Mason 		if (wbc->for_kupdate)
496448d640bSChris Mason 			return 0;
497448d640bSChris Mason 
498e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
499b9473439SChris Mason 		/* this is a bit racy, but that's ok */
500d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
501d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
502d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
503e2d84521SMiao Xie 		if (ret < 0)
504793955bcSChris Mason 			return 0;
505793955bcSChris Mason 	}
5060b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
5070da5468fSChris Mason }
5080da5468fSChris Mason 
509f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
5105f39d397SChris Mason {
511f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
512f913cff3SMatthew Wilcox (Oracle) 		return false;
5130c4e538bSDavid Sterba 
514f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
515d98237b3SChris Mason }
516d98237b3SChris Mason 
517895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
518895586ebSMatthew Wilcox (Oracle) 				 size_t length)
519d98237b3SChris Mason {
520d1310b2eSChris Mason 	struct extent_io_tree *tree;
521895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
522895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
523f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
524895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
525895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
526895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
527895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
528895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
5299ad6b7bcSChris Mason 	}
530d98237b3SChris Mason }
531d98237b3SChris Mason 
532bb146eb2SJosef Bacik #ifdef DEBUG
5330079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
5340079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
5350079c3b1SMatthew Wilcox (Oracle) {
5360079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
537139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
5380b32f4bbSJosef Bacik 	struct extent_buffer *eb;
539139e8cd3SQu Wenruo 	int cur_bit = 0;
5400079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
5410b32f4bbSJosef Bacik 
542139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
5430079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
5440b32f4bbSJosef Bacik 		BUG_ON(!eb);
5450b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
5460b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
54749d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
5480079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
549139e8cd3SQu Wenruo 	}
5500079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
551139e8cd3SQu Wenruo 
552139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
553139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
554139e8cd3SQu Wenruo 		unsigned long flags;
555139e8cd3SQu Wenruo 		u64 cur;
556139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
557139e8cd3SQu Wenruo 
558139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
559139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
560139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
561139e8cd3SQu Wenruo 			cur_bit++;
562139e8cd3SQu Wenruo 			continue;
563139e8cd3SQu Wenruo 		}
564139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
565139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
566139e8cd3SQu Wenruo 
567139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
568139e8cd3SQu Wenruo 		ASSERT(eb);
569139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
570139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
57149d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
572139e8cd3SQu Wenruo 		free_extent_buffer(eb);
573139e8cd3SQu Wenruo 
574139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
575139e8cd3SQu Wenruo 	}
5760079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
5770b32f4bbSJosef Bacik }
5780079c3b1SMatthew Wilcox (Oracle) #else
5790079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
5800079c3b1SMatthew Wilcox (Oracle) #endif
5810b32f4bbSJosef Bacik 
5827f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
5830da5468fSChris Mason 	.writepages	= btree_writepages,
584f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
585895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
5868958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
5870079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
588d98237b3SChris Mason };
589123abc88SChris Mason 
5902ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
5912ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
5923fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
5933fbaf258SJosef Bacik 						int level)
5940999df54SChris Mason {
5950b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
5960b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
5973fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
5980999df54SChris Mason }
5990999df54SChris Mason 
600581c1760SQu Wenruo /*
601581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
602581c1760SQu Wenruo  * verification.
603581c1760SQu Wenruo  *
604789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see comments of the
605789d6a3aSQu Wenruo  *			structure for details.
606581c1760SQu Wenruo  */
6072ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
608789d6a3aSQu Wenruo 				      struct btrfs_tree_parent_check *check)
609e20d96d6SChris Mason {
6105f39d397SChris Mason 	struct extent_buffer *buf = NULL;
61119c00ddcSChris Mason 	int ret;
61219c00ddcSChris Mason 
613789d6a3aSQu Wenruo 	ASSERT(check);
614789d6a3aSQu Wenruo 
615789d6a3aSQu Wenruo 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
616789d6a3aSQu Wenruo 					   check->level);
617c871b0f2SLiu Bo 	if (IS_ERR(buf))
618c871b0f2SLiu Bo 		return buf;
619e4204dedSChris Mason 
620789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(buf, check);
6210f0fe8f7SFilipe David Borba Manana 	if (ret) {
622537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
62364c043deSLiu Bo 		return ERR_PTR(ret);
6240f0fe8f7SFilipe David Borba Manana 	}
625789d6a3aSQu Wenruo 	if (btrfs_check_eb_owner(buf, check->owner_root)) {
62688c602abSQu Wenruo 		free_extent_buffer_stale(buf);
62788c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
62888c602abSQu Wenruo 	}
6295f39d397SChris Mason 	return buf;
630ce9adaa5SChris Mason 
631eb60ceacSChris Mason }
632eb60ceacSChris Mason 
633da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
634e20d96d6SChris Mason 			 u64 objectid)
635d97e63b6SChris Mason {
6367c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
6372e608bd1SJosef Bacik 
6382e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
6392e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
6402e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
64196dfcb46SJosef Bacik 	root->fs_info = fs_info;
6422e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
643cfaa7295SChris Mason 	root->node = NULL;
644a28ec197SChris Mason 	root->commit_root = NULL;
64527cdeb70SMiao Xie 	root->state = 0;
646abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
6470b86a832SChris Mason 
6480f7d52f4SChris Mason 	root->last_trans = 0;
6496b8fad57SNikolay Borisov 	root->free_objectid = 0;
650eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
651199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
6526bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
653088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
6542e608bd1SJosef Bacik 
6552e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
6560b86a832SChris Mason 
6570b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
6585d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
659eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
660eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
661199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
662199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
663d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
6642ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
6652ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
6665d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
667eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
668199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
669f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
6702ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
6712ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
6728287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
673a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
674e02119d5SChris Mason 	mutex_init(&root->log_mutex);
67531f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
676573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
677c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
6787237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
6797237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
6807237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
6818b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
6828b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
6837237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
6847237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
6857237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
6862ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
6870700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
6888ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
689eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
6907237f183SYan Zheng 	root->log_transid = 0;
691d1433debSMiao Xie 	root->log_transid_committed = -1;
692257c62e1SChris Mason 	root->last_log_commit = 0;
6932e608bd1SJosef Bacik 	root->anon_dev = 0;
694e289f03eSFilipe Manana 	if (!dummy) {
69543eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
69635da5a7eSDavid Sterba 				    IO_TREE_ROOT_DIRTY_LOG_PAGES);
697e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
69835da5a7eSDavid Sterba 				    IO_TREE_LOG_CSUM_RANGE);
699e289f03eSFilipe Manana 	}
700017e5369SChris Mason 
7015f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
702370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
703bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
704bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
705fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
706bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
707fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
708bd647ce3SJosef Bacik #endif
7093768f368SChris Mason }
7103768f368SChris Mason 
71174e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
71296dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
7136f07e42eSAl Viro {
71474e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
7156f07e42eSAl Viro 	if (root)
71696dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
7176f07e42eSAl Viro 	return root;
7186f07e42eSAl Viro }
7196f07e42eSAl Viro 
72006ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
72106ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
722da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
72306ea65a3SJosef Bacik {
72406ea65a3SJosef Bacik 	struct btrfs_root *root;
72506ea65a3SJosef Bacik 
7267c0260eeSJeff Mahoney 	if (!fs_info)
7277c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
7287c0260eeSJeff Mahoney 
72996dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
73006ea65a3SJosef Bacik 	if (!root)
73106ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
732da17066cSJeff Mahoney 
733b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
734faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
73506ea65a3SJosef Bacik 
73606ea65a3SJosef Bacik 	return root;
73706ea65a3SJosef Bacik }
73806ea65a3SJosef Bacik #endif
73906ea65a3SJosef Bacik 
740abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
741abed4aaaSJosef Bacik {
742abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
743abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
744abed4aaaSJosef Bacik 
745abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
746abed4aaaSJosef Bacik }
747abed4aaaSJosef Bacik 
748abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
749abed4aaaSJosef Bacik {
750abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
751abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
752abed4aaaSJosef Bacik 
753abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
754abed4aaaSJosef Bacik }
755abed4aaaSJosef Bacik 
756abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
757abed4aaaSJosef Bacik {
758abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
759abed4aaaSJosef Bacik 	struct rb_node *tmp;
760745806fbSQu Wenruo 	int ret = 0;
761abed4aaaSJosef Bacik 
762abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
763abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
764abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
765abed4aaaSJosef Bacik 
766745806fbSQu Wenruo 	if (tmp) {
767745806fbSQu Wenruo 		ret = -EEXIST;
768745806fbSQu Wenruo 		btrfs_warn(fs_info, "global root %llu %llu already exists",
769745806fbSQu Wenruo 				root->root_key.objectid, root->root_key.offset);
770745806fbSQu Wenruo 	}
771745806fbSQu Wenruo 	return ret;
772abed4aaaSJosef Bacik }
773abed4aaaSJosef Bacik 
774abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
775abed4aaaSJosef Bacik {
776abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
777abed4aaaSJosef Bacik 
778abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
779abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
780abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
781abed4aaaSJosef Bacik }
782abed4aaaSJosef Bacik 
783abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
784abed4aaaSJosef Bacik 				     struct btrfs_key *key)
785abed4aaaSJosef Bacik {
786abed4aaaSJosef Bacik 	struct rb_node *node;
787abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
788abed4aaaSJosef Bacik 
789abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
790abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
791abed4aaaSJosef Bacik 	if (node)
792abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
793abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
794abed4aaaSJosef Bacik 
795abed4aaaSJosef Bacik 	return root;
796abed4aaaSJosef Bacik }
797abed4aaaSJosef Bacik 
798f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
799f7238e50SJosef Bacik {
800f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
801f7238e50SJosef Bacik 	u64 ret;
802f7238e50SJosef Bacik 
803f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
804f7238e50SJosef Bacik 		return 0;
805f7238e50SJosef Bacik 
806f7238e50SJosef Bacik 	if (bytenr)
807f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
808f7238e50SJosef Bacik 	else
809f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
810f7238e50SJosef Bacik 	ASSERT(block_group);
811f7238e50SJosef Bacik 	if (!block_group)
812f7238e50SJosef Bacik 		return 0;
813f7238e50SJosef Bacik 	ret = block_group->global_root_id;
814f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
815f7238e50SJosef Bacik 
816f7238e50SJosef Bacik 	return ret;
817f7238e50SJosef Bacik }
818f7238e50SJosef Bacik 
819abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
820abed4aaaSJosef Bacik {
821abed4aaaSJosef Bacik 	struct btrfs_key key = {
822abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
823abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
824f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
825abed4aaaSJosef Bacik 	};
826abed4aaaSJosef Bacik 
827abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
828abed4aaaSJosef Bacik }
829abed4aaaSJosef Bacik 
830abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
831abed4aaaSJosef Bacik {
832abed4aaaSJosef Bacik 	struct btrfs_key key = {
833abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
834abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
835f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
836abed4aaaSJosef Bacik 	};
837abed4aaaSJosef Bacik 
838abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
839abed4aaaSJosef Bacik }
840abed4aaaSJosef Bacik 
84151129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
84251129b33SJosef Bacik {
84351129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
84451129b33SJosef Bacik 		return fs_info->block_group_root;
84551129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
84651129b33SJosef Bacik }
84751129b33SJosef Bacik 
84820897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
84920897f5cSArne Jansen 				     u64 objectid)
85020897f5cSArne Jansen {
8519b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
85220897f5cSArne Jansen 	struct extent_buffer *leaf;
85320897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
85420897f5cSArne Jansen 	struct btrfs_root *root;
85520897f5cSArne Jansen 	struct btrfs_key key;
856b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
85720897f5cSArne Jansen 	int ret = 0;
85820897f5cSArne Jansen 
859b89f6d1fSFilipe Manana 	/*
860b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
861b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
862b89f6d1fSFilipe Manana 	 */
863b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
86496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
865b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
86620897f5cSArne Jansen 	if (!root)
86720897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
86820897f5cSArne Jansen 
86920897f5cSArne Jansen 	root->root_key.objectid = objectid;
87020897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
87120897f5cSArne Jansen 	root->root_key.offset = 0;
87220897f5cSArne Jansen 
8739631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
8749631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
87520897f5cSArne Jansen 	if (IS_ERR(leaf)) {
87620897f5cSArne Jansen 		ret = PTR_ERR(leaf);
8771dd05682STsutomu Itoh 		leaf = NULL;
878c1b07854SPeng Hao 		goto fail;
87920897f5cSArne Jansen 	}
88020897f5cSArne Jansen 
88120897f5cSArne Jansen 	root->node = leaf;
88220897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
88320897f5cSArne Jansen 
88420897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
88527cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
88620897f5cSArne Jansen 
887f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
888f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
88920897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
89020897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
89120897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
89220897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
89320897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
89420897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
89520897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
89633d85fdaSQu Wenruo 	if (is_fstree(objectid))
897807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
898807fc790SAndy Shevchenko 	else
899807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
900c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
90120897f5cSArne Jansen 
9028a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
9038a6a87cdSBoris Burkov 
90420897f5cSArne Jansen 	key.objectid = objectid;
90520897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
90620897f5cSArne Jansen 	key.offset = 0;
90720897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
90820897f5cSArne Jansen 	if (ret)
90920897f5cSArne Jansen 		goto fail;
91020897f5cSArne Jansen 
91120897f5cSArne Jansen 	return root;
9121dd05682STsutomu Itoh 
9138a6a87cdSBoris Burkov fail:
91400246528SJosef Bacik 	btrfs_put_root(root);
9151dd05682STsutomu Itoh 
9161dd05682STsutomu Itoh 	return ERR_PTR(ret);
91720897f5cSArne Jansen }
91820897f5cSArne Jansen 
9197237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
920e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
9210f7d52f4SChris Mason {
9220f7d52f4SChris Mason 	struct btrfs_root *root;
923e02119d5SChris Mason 
92496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
925e02119d5SChris Mason 	if (!root)
9267237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
927e02119d5SChris Mason 
928e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
929e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
930e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
93127cdeb70SMiao Xie 
9326ab6ebb7SNaohiro Aota 	return root;
9336ab6ebb7SNaohiro Aota }
9346ab6ebb7SNaohiro Aota 
9356ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
9366ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
9376ab6ebb7SNaohiro Aota {
9386ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
9396ab6ebb7SNaohiro Aota 
9407237f183SYan Zheng 	/*
94192a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
94227cdeb70SMiao Xie 	 *
94392a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
94492a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
94592a7cc42SQu Wenruo 	 *
94692a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
94792a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
9487237f183SYan Zheng 	 */
949e02119d5SChris Mason 
9504d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
9519631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
9526ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
9536ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
954e02119d5SChris Mason 
9557237f183SYan Zheng 	root->node = leaf;
956e02119d5SChris Mason 
957e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
958e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
9596ab6ebb7SNaohiro Aota 
9606ab6ebb7SNaohiro Aota 	return 0;
9617237f183SYan Zheng }
9627237f183SYan Zheng 
9637237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
9647237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
9657237f183SYan Zheng {
9667237f183SYan Zheng 	struct btrfs_root *log_root;
9677237f183SYan Zheng 
9687237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
9697237f183SYan Zheng 	if (IS_ERR(log_root))
9707237f183SYan Zheng 		return PTR_ERR(log_root);
9716ab6ebb7SNaohiro Aota 
9723ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
9733ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
9743ddebf27SNaohiro Aota 
9756ab6ebb7SNaohiro Aota 		if (ret) {
9766ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
9776ab6ebb7SNaohiro Aota 			return ret;
9786ab6ebb7SNaohiro Aota 		}
9793ddebf27SNaohiro Aota 	}
9806ab6ebb7SNaohiro Aota 
9817237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
9827237f183SYan Zheng 	fs_info->log_root_tree = log_root;
9837237f183SYan Zheng 	return 0;
9847237f183SYan Zheng }
9857237f183SYan Zheng 
9867237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
9877237f183SYan Zheng 		       struct btrfs_root *root)
9887237f183SYan Zheng {
9890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9907237f183SYan Zheng 	struct btrfs_root *log_root;
9917237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
9926ab6ebb7SNaohiro Aota 	int ret;
9937237f183SYan Zheng 
9940b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
9957237f183SYan Zheng 	if (IS_ERR(log_root))
9967237f183SYan Zheng 		return PTR_ERR(log_root);
9977237f183SYan Zheng 
9986ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
9996ab6ebb7SNaohiro Aota 	if (ret) {
10006ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
10016ab6ebb7SNaohiro Aota 		return ret;
10026ab6ebb7SNaohiro Aota 	}
10036ab6ebb7SNaohiro Aota 
10047237f183SYan Zheng 	log_root->last_trans = trans->transid;
10057237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
10067237f183SYan Zheng 
10077237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
10083cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
10093cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
10103cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1011da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
10120b246afaSJeff Mahoney 				     fs_info->nodesize);
10133cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
10147237f183SYan Zheng 
10155d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
10167237f183SYan Zheng 
10177237f183SYan Zheng 	WARN_ON(root->log_root);
10187237f183SYan Zheng 	root->log_root = log_root;
10197237f183SYan Zheng 	root->log_transid = 0;
1020d1433debSMiao Xie 	root->log_transid_committed = -1;
1021257c62e1SChris Mason 	root->last_log_commit = 0;
1022e02119d5SChris Mason 	return 0;
1023e02119d5SChris Mason }
1024e02119d5SChris Mason 
102549d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
102649d11beaSJosef Bacik 					      struct btrfs_path *path,
1027cb517eabSMiao Xie 					      struct btrfs_key *key)
1028e02119d5SChris Mason {
1029e02119d5SChris Mason 	struct btrfs_root *root;
1030789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1031e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
103284234f3aSYan Zheng 	u64 generation;
1033cb517eabSMiao Xie 	int ret;
1034581c1760SQu Wenruo 	int level;
1035cb517eabSMiao Xie 
103696dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
103749d11beaSJosef Bacik 	if (!root)
103849d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
10390f7d52f4SChris Mason 
1040cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1041cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
10420f7d52f4SChris Mason 	if (ret) {
104313a8a7c8SYan, Zheng 		if (ret > 0)
104413a8a7c8SYan, Zheng 			ret = -ENOENT;
104549d11beaSJosef Bacik 		goto fail;
10460f7d52f4SChris Mason 	}
104713a8a7c8SYan, Zheng 
104884234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1049581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
1050789d6a3aSQu Wenruo 	check.level = level;
1051789d6a3aSQu Wenruo 	check.transid = generation;
1052789d6a3aSQu Wenruo 	check.owner_root = key->objectid;
1053789d6a3aSQu Wenruo 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1054789d6a3aSQu Wenruo 				     &check);
105564c043deSLiu Bo 	if (IS_ERR(root->node)) {
105664c043deSLiu Bo 		ret = PTR_ERR(root->node);
10578c38938cSJosef Bacik 		root->node = NULL;
105849d11beaSJosef Bacik 		goto fail;
10594eb150d6SQu Wenruo 	}
10604eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1061cb517eabSMiao Xie 		ret = -EIO;
106249d11beaSJosef Bacik 		goto fail;
1063416bc658SJosef Bacik 	}
106488c602abSQu Wenruo 
106588c602abSQu Wenruo 	/*
106688c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
106788c602abSQu Wenruo 	 * match its root node owner
106888c602abSQu Wenruo 	 */
106988c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
107088c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
107188c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
107288c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
107388c602abSQu Wenruo 		btrfs_crit(fs_info,
107488c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
107588c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
107688c602abSQu Wenruo 			   btrfs_header_owner(root->node),
107788c602abSQu Wenruo 			   root->root_key.objectid);
107888c602abSQu Wenruo 		ret = -EUCLEAN;
107988c602abSQu Wenruo 		goto fail;
108088c602abSQu Wenruo 	}
10815d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1082cb517eabSMiao Xie 	return root;
108349d11beaSJosef Bacik fail:
108400246528SJosef Bacik 	btrfs_put_root(root);
108549d11beaSJosef Bacik 	return ERR_PTR(ret);
108649d11beaSJosef Bacik }
108749d11beaSJosef Bacik 
108849d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
108949d11beaSJosef Bacik 					struct btrfs_key *key)
109049d11beaSJosef Bacik {
109149d11beaSJosef Bacik 	struct btrfs_root *root;
109249d11beaSJosef Bacik 	struct btrfs_path *path;
109349d11beaSJosef Bacik 
109449d11beaSJosef Bacik 	path = btrfs_alloc_path();
109549d11beaSJosef Bacik 	if (!path)
109649d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
109749d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
109849d11beaSJosef Bacik 	btrfs_free_path(path);
109949d11beaSJosef Bacik 
110049d11beaSJosef Bacik 	return root;
1101cb517eabSMiao Xie }
1102cb517eabSMiao Xie 
11032dfb1e43SQu Wenruo /*
11042dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
11052dfb1e43SQu Wenruo  *
11062dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
11072dfb1e43SQu Wenruo  */
11082dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1109cb517eabSMiao Xie {
1110cb517eabSMiao Xie 	int ret;
1111cb517eabSMiao Xie 
11120b548539SDavid Sterba 	btrfs_drew_lock_init(&root->snapshot_lock);
11138257b2dcSMiao Xie 
1114aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
111537f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
111692a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1117f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1118f39e4571SJosef Bacik 	}
1119f39e4571SJosef Bacik 
1120851fd730SQu Wenruo 	/*
1121851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1122851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1123851fd730SQu Wenruo 	 */
1124851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1125851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
11262dfb1e43SQu Wenruo 		if (!anon_dev) {
1127cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1128cb517eabSMiao Xie 			if (ret)
1129876d2cf1SLiu Bo 				goto fail;
11302dfb1e43SQu Wenruo 		} else {
11312dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
11322dfb1e43SQu Wenruo 		}
1133851fd730SQu Wenruo 	}
1134f32e48e9SChandan Rajendra 
1135f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1136453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1137f32e48e9SChandan Rajendra 	if (ret) {
1138f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1139876d2cf1SLiu Bo 		goto fail;
1140f32e48e9SChandan Rajendra 	}
1141f32e48e9SChandan Rajendra 
11426b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1143f32e48e9SChandan Rajendra 
1144f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1145f32e48e9SChandan Rajendra 
1146cb517eabSMiao Xie 	return 0;
1147cb517eabSMiao Xie fail:
114884db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1149cb517eabSMiao Xie 	return ret;
1150cb517eabSMiao Xie }
1151cb517eabSMiao Xie 
1152a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1153cb517eabSMiao Xie 					       u64 root_id)
1154cb517eabSMiao Xie {
1155cb517eabSMiao Xie 	struct btrfs_root *root;
1156cb517eabSMiao Xie 
1157fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1158fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1159fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1160bc44d7c4SJosef Bacik 	if (root)
116100246528SJosef Bacik 		root = btrfs_grab_root(root);
1162fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1163cb517eabSMiao Xie 	return root;
1164cb517eabSMiao Xie }
1165cb517eabSMiao Xie 
116649d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
116749d11beaSJosef Bacik 						u64 objectid)
116849d11beaSJosef Bacik {
1169abed4aaaSJosef Bacik 	struct btrfs_key key = {
1170abed4aaaSJosef Bacik 		.objectid = objectid,
1171abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1172abed4aaaSJosef Bacik 		.offset = 0,
1173abed4aaaSJosef Bacik 	};
1174abed4aaaSJosef Bacik 
117549d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
117649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
117749d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1178abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
117949d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
118049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
118149d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
118249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
118349d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1184abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
118549d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
118649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
118749d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
118849d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
118949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
119049d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
119114033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
119214033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
119314033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1194abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1195abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1196abed4aaaSJosef Bacik 
1197abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1198abed4aaaSJosef Bacik 	}
119949d11beaSJosef Bacik 	return NULL;
120049d11beaSJosef Bacik }
120149d11beaSJosef Bacik 
1202cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1203cb517eabSMiao Xie 			 struct btrfs_root *root)
1204cb517eabSMiao Xie {
1205cb517eabSMiao Xie 	int ret;
1206cb517eabSMiao Xie 
1207fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1208fc7cbcd4SDavid Sterba 	if (ret)
1209fc7cbcd4SDavid Sterba 		return ret;
1210fc7cbcd4SDavid Sterba 
1211fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1212fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1213fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1214fc7cbcd4SDavid Sterba 				root);
1215af01d2e5SJosef Bacik 	if (ret == 0) {
121600246528SJosef Bacik 		btrfs_grab_root(root);
1217fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1218af01d2e5SJosef Bacik 	}
1219fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1220fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1221cb517eabSMiao Xie 
1222cb517eabSMiao Xie 	return ret;
1223cb517eabSMiao Xie }
1224cb517eabSMiao Xie 
1225bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1226bd647ce3SJosef Bacik {
1227bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1228bd647ce3SJosef Bacik 	struct btrfs_root *root;
1229bd647ce3SJosef Bacik 
1230bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1231457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1232457f1864SJosef Bacik 
1233bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1234bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1235457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
123671008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1237bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1238bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
123900246528SJosef Bacik 			btrfs_put_root(root);
124000246528SJosef Bacik 		btrfs_put_root(root);
1241bd647ce3SJosef Bacik 	}
1242bd647ce3SJosef Bacik #endif
1243bd647ce3SJosef Bacik }
1244bd647ce3SJosef Bacik 
1245abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1246abed4aaaSJosef Bacik {
1247abed4aaaSJosef Bacik 	struct btrfs_root *root;
1248abed4aaaSJosef Bacik 	struct rb_node *node;
1249abed4aaaSJosef Bacik 
1250abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1251abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1252abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1253abed4aaaSJosef Bacik 		btrfs_put_root(root);
1254abed4aaaSJosef Bacik 	}
1255abed4aaaSJosef Bacik }
1256abed4aaaSJosef Bacik 
12570d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
12580d4b0463SJosef Bacik {
1259141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1260141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
12615deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1262141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1263141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1264141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1265141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
12660d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
12670d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1268abed4aaaSJosef Bacik 	free_global_roots(fs_info);
126900246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
127000246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
127100246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
127200246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
127300246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
127400246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1275aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
12769c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1277bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
12783fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
12790d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
12800d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
12818481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
12820d4b0463SJosef Bacik 	kvfree(fs_info);
12830d4b0463SJosef Bacik }
12840d4b0463SJosef Bacik 
12850d4b0463SJosef Bacik 
12862dfb1e43SQu Wenruo /*
12872dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
12882dfb1e43SQu Wenruo  *
12892dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
12902dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
12912dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
12922dfb1e43SQu Wenruo  *
12932dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
12942dfb1e43SQu Wenruo  *
12952dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
12962dfb1e43SQu Wenruo  *	 same root objectid.
12972dfb1e43SQu Wenruo  *
12982dfb1e43SQu Wenruo  * @objectid:	root id
12992dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
13002dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
13012dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
13022dfb1e43SQu Wenruo  *		for orphan roots
13032dfb1e43SQu Wenruo  */
13042dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
13052dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
13062dfb1e43SQu Wenruo 					     bool check_ref)
13075eda7b5eSChris Mason {
13085eda7b5eSChris Mason 	struct btrfs_root *root;
1309381cf658SDavid Sterba 	struct btrfs_path *path;
13101d4c08e0SDavid Sterba 	struct btrfs_key key;
13115eda7b5eSChris Mason 	int ret;
13125eda7b5eSChris Mason 
131349d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
131449d11beaSJosef Bacik 	if (root)
131549d11beaSJosef Bacik 		return root;
13164df27c4dSYan, Zheng again:
131756e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
131848475471SStefan Behrens 	if (root) {
13192dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
13202dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1321bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
132200246528SJosef Bacik 			btrfs_put_root(root);
132348475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1324bc44d7c4SJosef Bacik 		}
13255eda7b5eSChris Mason 		return root;
132648475471SStefan Behrens 	}
13275eda7b5eSChris Mason 
132856e9357aSDavid Sterba 	key.objectid = objectid;
132956e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
133056e9357aSDavid Sterba 	key.offset = (u64)-1;
133156e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
13325eda7b5eSChris Mason 	if (IS_ERR(root))
13335eda7b5eSChris Mason 		return root;
13343394e160SChris Mason 
1335c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1336d68fc57bSYan, Zheng 		ret = -ENOENT;
1337d68fc57bSYan, Zheng 		goto fail;
1338d68fc57bSYan, Zheng 	}
1339d68fc57bSYan, Zheng 
13402dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1341cb517eabSMiao Xie 	if (ret)
1342cb517eabSMiao Xie 		goto fail;
1343cb517eabSMiao Xie 
1344381cf658SDavid Sterba 	path = btrfs_alloc_path();
1345381cf658SDavid Sterba 	if (!path) {
1346381cf658SDavid Sterba 		ret = -ENOMEM;
1347381cf658SDavid Sterba 		goto fail;
1348381cf658SDavid Sterba 	}
13491d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
13501d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
135156e9357aSDavid Sterba 	key.offset = objectid;
13521d4c08e0SDavid Sterba 
13531d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1354381cf658SDavid Sterba 	btrfs_free_path(path);
1355d68fc57bSYan, Zheng 	if (ret < 0)
1356d68fc57bSYan, Zheng 		goto fail;
1357d68fc57bSYan, Zheng 	if (ret == 0)
135827cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1359d68fc57bSYan, Zheng 
1360cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
13610f7d52f4SChris Mason 	if (ret) {
1362168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
136300246528SJosef Bacik 			btrfs_put_root(root);
13644df27c4dSYan, Zheng 			goto again;
1365168a2f77SJia-Ju Bai 		}
13664df27c4dSYan, Zheng 		goto fail;
13674df27c4dSYan, Zheng 	}
1368edbd8d4eSChris Mason 	return root;
13694df27c4dSYan, Zheng fail:
137033fab972SFilipe Manana 	/*
137133fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1372143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
137333fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
137433fab972SFilipe Manana 	 * and once again by our caller.
137533fab972SFilipe Manana 	 */
137633fab972SFilipe Manana 	if (anon_dev)
137733fab972SFilipe Manana 		root->anon_dev = 0;
13788c38938cSJosef Bacik 	btrfs_put_root(root);
13794df27c4dSYan, Zheng 	return ERR_PTR(ret);
1380edbd8d4eSChris Mason }
1381edbd8d4eSChris Mason 
13822dfb1e43SQu Wenruo /*
13832dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
13842dfb1e43SQu Wenruo  *
13852dfb1e43SQu Wenruo  * @objectid:	tree objectid
13862dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
13872dfb1e43SQu Wenruo  *		one reference
13882dfb1e43SQu Wenruo  */
13892dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
13902dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
13912dfb1e43SQu Wenruo {
13922dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
13932dfb1e43SQu Wenruo }
13942dfb1e43SQu Wenruo 
13952dfb1e43SQu Wenruo /*
13962dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
13972dfb1e43SQu Wenruo  * the anonymous block device id
13982dfb1e43SQu Wenruo  *
13992dfb1e43SQu Wenruo  * @objectid:	tree objectid
14002dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
14012dfb1e43SQu Wenruo  *		parameter value
14022dfb1e43SQu Wenruo  */
14032dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
14042dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
14052dfb1e43SQu Wenruo {
14062dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
14072dfb1e43SQu Wenruo }
14082dfb1e43SQu Wenruo 
14098b712842SChris Mason /*
141049d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
141149d11beaSJosef Bacik  * @fs_info:	the fs_info
141249d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
141349d11beaSJosef Bacik  *
141449d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
141549d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
141649d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
141749d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
141849d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
141949d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
142049d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
142149d11beaSJosef Bacik  * backref code is finished using the root.
142249d11beaSJosef Bacik  */
142349d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
142449d11beaSJosef Bacik 						 struct btrfs_path *path,
142549d11beaSJosef Bacik 						 u64 objectid)
142649d11beaSJosef Bacik {
142749d11beaSJosef Bacik 	struct btrfs_root *root;
142849d11beaSJosef Bacik 	struct btrfs_key key;
142949d11beaSJosef Bacik 
143049d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
143149d11beaSJosef Bacik 
143249d11beaSJosef Bacik 	/*
143349d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
143449d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
143549d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
143649d11beaSJosef Bacik 	 * != NULL just return it.
143749d11beaSJosef Bacik 	 */
143849d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
143949d11beaSJosef Bacik 	if (root)
144049d11beaSJosef Bacik 		return root;
144149d11beaSJosef Bacik 
144249d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
144349d11beaSJosef Bacik 	if (root)
144449d11beaSJosef Bacik 		return root;
144549d11beaSJosef Bacik 
144649d11beaSJosef Bacik 	key.objectid = objectid;
144749d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
144849d11beaSJosef Bacik 	key.offset = (u64)-1;
144949d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
145049d11beaSJosef Bacik 	btrfs_release_path(path);
145149d11beaSJosef Bacik 
145249d11beaSJosef Bacik 	return root;
145349d11beaSJosef Bacik }
145449d11beaSJosef Bacik 
1455a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1456a74a4b97SChris Mason {
14570d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1458d0278245SMiao Xie 	int again;
1459a74a4b97SChris Mason 
1460d6fd0ae2SOmar Sandoval 	while (1) {
1461d0278245SMiao Xie 		again = 0;
14629d1a2a3aSDavid Sterba 
1463fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1464fd340d0fSJosef Bacik 
1465d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
14662ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1467d0278245SMiao Xie 			goto sleep;
1468d0278245SMiao Xie 
146990c711abSZygo Blaxell 		/*
147090c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
147190c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
147290c711abSZygo Blaxell 		 */
14730b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
147490c711abSZygo Blaxell 			goto sleep;
147590c711abSZygo Blaxell 
14760b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1477d0278245SMiao Xie 			goto sleep;
1478d0278245SMiao Xie 
1479dc7f370cSMiao Xie 		/*
1480dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1481dc7f370cSMiao Xie 		 * during the above check and trylock.
1482dc7f370cSMiao Xie 		 */
14832ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
14840b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1485dc7f370cSMiao Xie 			goto sleep;
1486dc7f370cSMiao Xie 		}
1487dc7f370cSMiao Xie 
1488b7625f46SQu Wenruo 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1489b7625f46SQu Wenruo 			btrfs_sysfs_feature_update(fs_info);
1490b7625f46SQu Wenruo 
14912ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1492c2d6cb16SFilipe Manana 
149333c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
14940b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1495a74a4b97SChris Mason 
1496d0278245SMiao Xie 		/*
149705323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
149805323cd1SMiao Xie 		 * needn't do anything special here.
1499d0278245SMiao Xie 		 */
15000b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
150167c5e7d4SFilipe Manana 
150267c5e7d4SFilipe Manana 		/*
1503f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
150467c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
150567c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1506f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
150767c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
150867c5e7d4SFilipe Manana 		 * unused block groups.
150967c5e7d4SFilipe Manana 		 */
15100b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
151118bb8bbfSJohannes Thumshirn 
151218bb8bbfSJohannes Thumshirn 		/*
151318bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
151418bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
151518bb8bbfSJohannes Thumshirn 		 * space.
151618bb8bbfSJohannes Thumshirn 		 */
151718bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1518d0278245SMiao Xie sleep:
1519a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1520d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1521d6fd0ae2SOmar Sandoval 			kthread_parkme();
1522d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1523d6fd0ae2SOmar Sandoval 			return 0;
1524838fe188SJiri Kosina 		if (!again) {
1525a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1526a74a4b97SChris Mason 			schedule();
1527a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1528a74a4b97SChris Mason 		}
1529da288d28SFilipe Manana 	}
1530a74a4b97SChris Mason }
1531a74a4b97SChris Mason 
1532a74a4b97SChris Mason static int transaction_kthread(void *arg)
1533a74a4b97SChris Mason {
1534a74a4b97SChris Mason 	struct btrfs_root *root = arg;
15350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1536a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1537a74a4b97SChris Mason 	struct btrfs_transaction *cur;
15388929ecfaSYan, Zheng 	u64 transid;
1539643900beSNikolay Borisov 	time64_t delta;
1540a74a4b97SChris Mason 	unsigned long delay;
1541914b2007SJan Kara 	bool cannot_commit;
1542a74a4b97SChris Mason 
1543a74a4b97SChris Mason 	do {
1544914b2007SJan Kara 		cannot_commit = false;
1545ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
15460b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1547a74a4b97SChris Mason 
15480b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
15490b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1550a74a4b97SChris Mason 		if (!cur) {
15510b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1552a74a4b97SChris Mason 			goto sleep;
1553a74a4b97SChris Mason 		}
155431153d81SYan Zheng 
1555643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1556fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1557fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1558643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
15590b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1560fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1561fb8a7e94SNikolay Borisov 			delay = min(delay,
1562fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1563a74a4b97SChris Mason 			goto sleep;
1564a74a4b97SChris Mason 		}
15658929ecfaSYan, Zheng 		transid = cur->transid;
15660b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
156756bec294SChris Mason 
156879787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1569354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1570914b2007SJan Kara 		if (IS_ERR(trans)) {
1571354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1572914b2007SJan Kara 				cannot_commit = true;
157379787eaaSJeff Mahoney 			goto sleep;
1574914b2007SJan Kara 		}
15758929ecfaSYan, Zheng 		if (transid == trans->transid) {
15763a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
15778929ecfaSYan, Zheng 		} else {
15783a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
15798929ecfaSYan, Zheng 		}
1580a74a4b97SChris Mason sleep:
15810b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
15820b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1583a74a4b97SChris Mason 
158484961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
15852ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
15868929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
15870b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1588914b2007SJan Kara 				 cannot_commit))
1589bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1590a74a4b97SChris Mason 	} while (!kthread_should_stop());
1591a74a4b97SChris Mason 	return 0;
1592a74a4b97SChris Mason }
1593a74a4b97SChris Mason 
1594af31f5e5SChris Mason /*
159501f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
159601f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
159701f0f9daSNikolay Borisov  * anything.
1598af31f5e5SChris Mason  *
1599af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1600af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1601af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1602af31f5e5SChris Mason  */
160301f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1604af31f5e5SChris Mason {
160501f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1606af31f5e5SChris Mason 	u64 cur;
1607af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1608af31f5e5SChris Mason 	int i;
1609af31f5e5SChris Mason 
1610af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1611af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1612af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1613af31f5e5SChris Mason 		if (cur == newest_gen)
161401f0f9daSNikolay Borisov 			return i;
1615af31f5e5SChris Mason 	}
1616af31f5e5SChris Mason 
161701f0f9daSNikolay Borisov 	return -EINVAL;
1618af31f5e5SChris Mason }
1619af31f5e5SChris Mason 
1620af31f5e5SChris Mason /*
1621af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1622af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1623af31f5e5SChris Mason  * done
1624af31f5e5SChris Mason  */
1625af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1626af31f5e5SChris Mason {
16276ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1628af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1629af31f5e5SChris Mason 
1630af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1631af31f5e5SChris Mason 
1632af31f5e5SChris Mason 	/*
1633af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1634af31f5e5SChris Mason 	 * regardless of which ones we use today
1635af31f5e5SChris Mason 	 */
1636af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1637af31f5e5SChris Mason 
1638af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1639af31f5e5SChris Mason 
1640af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1641af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1642af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1643af31f5e5SChris Mason 
1644af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1645af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1646af31f5e5SChris Mason 
1647af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1648af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1649af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1650af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1651af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1652af31f5e5SChris Mason 
16531c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
16549c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1655f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
16569c54e80dSJosef Bacik 
16579c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
16589c54e80dSJosef Bacik 					     extent_root->node->start);
1659af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
166029cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
1661af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
166229cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
1663af31f5e5SChris Mason 
1664f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1665f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
1666f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
1667f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
1668f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
16699c54e80dSJosef Bacik 	}
1670af31f5e5SChris Mason 
16717c7e82a7SChris Mason 	/*
16727c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
16737c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
16747c7e82a7SChris Mason 	 */
16757c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
16767c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
16777c7e82a7SChris Mason 					 info->fs_root->node->start);
1678af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1679af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1680af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1681af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
16827c7e82a7SChris Mason 	}
1683af31f5e5SChris Mason 
1684af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1685af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1686af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1687af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1688af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1689af31f5e5SChris Mason 
1690af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1691af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1692af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1693af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1694af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1695af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1696af31f5e5SChris Mason 
1697af31f5e5SChris Mason 	/*
1698af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1699af31f5e5SChris Mason 	 * for the next commit
1700af31f5e5SChris Mason 	 */
1701af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1702af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1703af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1704af31f5e5SChris Mason }
1705af31f5e5SChris Mason 
1706af31f5e5SChris Mason /*
1707bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1708bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1709bd2336b2SNikolay Borisov  *
1710bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1711bd2336b2SNikolay Borisov  * priority - priority of backup root required
1712bd2336b2SNikolay Borisov  *
1713bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1714bd2336b2SNikolay Borisov  */
1715bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1716bd2336b2SNikolay Borisov {
1717bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1718bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1719bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1720bd2336b2SNikolay Borisov 
1721bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1722bd2336b2SNikolay Borisov 		if (priority == 0)
1723bd2336b2SNikolay Borisov 			return backup_index;
1724bd2336b2SNikolay Borisov 
1725bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1726bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1727bd2336b2SNikolay Borisov 	} else {
1728bd2336b2SNikolay Borisov 		return -EINVAL;
1729bd2336b2SNikolay Borisov 	}
1730bd2336b2SNikolay Borisov 
1731bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1732bd2336b2SNikolay Borisov 
1733bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1734bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1735bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1736bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1737bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1738bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1739bd2336b2SNikolay Borisov 
1740bd2336b2SNikolay Borisov 	/*
1741bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1742bd2336b2SNikolay Borisov 	 * need a fsck
1743bd2336b2SNikolay Borisov 	 */
1744bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1745bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1746bd2336b2SNikolay Borisov 
1747bd2336b2SNikolay Borisov 	return backup_index;
1748bd2336b2SNikolay Borisov }
1749bd2336b2SNikolay Borisov 
17507abadb64SLiu Bo /* helper to cleanup workers */
17517abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
17527abadb64SLiu Bo {
1753dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1754afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
17555cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1756d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
1757d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
1758385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
1759385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
1760fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
1761fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
1762fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1763fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
17645b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1765e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1766a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1767fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1768b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1769b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1770a9b9477dSFilipe Manana 	/*
1771a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1772a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1773a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1774a9b9477dSFilipe Manana 	 */
1775d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
1776d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
17777abadb64SLiu Bo }
17787abadb64SLiu Bo 
17792e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
17802e9f5954SRashika {
17812e9f5954SRashika 	if (root) {
17822e9f5954SRashika 		free_extent_buffer(root->node);
17832e9f5954SRashika 		free_extent_buffer(root->commit_root);
17842e9f5954SRashika 		root->node = NULL;
17852e9f5954SRashika 		root->commit_root = NULL;
17862e9f5954SRashika 	}
17872e9f5954SRashika }
17882e9f5954SRashika 
1789abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1790abed4aaaSJosef Bacik {
1791abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
1792abed4aaaSJosef Bacik 
1793abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
1794abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
1795abed4aaaSJosef Bacik 					     rb_node)
1796abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
1797abed4aaaSJosef Bacik }
1798abed4aaaSJosef Bacik 
1799af31f5e5SChris Mason /* helper to cleanup tree roots */
18004273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1801af31f5e5SChris Mason {
18022e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1803655b09feSJosef Bacik 
1804abed4aaaSJosef Bacik 	free_global_root_pointers(info);
18052e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
18062e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
18072e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
18088c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
1809aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
18109c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
18114273eaffSAnand Jain 	if (free_chunk_root)
18122e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
1813af31f5e5SChris Mason }
1814af31f5e5SChris Mason 
18158c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
18168c38938cSJosef Bacik {
18178c38938cSJosef Bacik 	if (!root)
18188c38938cSJosef Bacik 		return;
18198c38938cSJosef Bacik 
18208c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
18218c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
18221dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
18238c38938cSJosef Bacik 		if (root->anon_dev)
18248c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
1825923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
18268c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1827fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
18288c38938cSJosef Bacik 		list_del_init(&root->leak_list);
1829fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
18308c38938cSJosef Bacik #endif
18318c38938cSJosef Bacik 		kfree(root);
18328c38938cSJosef Bacik 	}
18338c38938cSJosef Bacik }
18348c38938cSJosef Bacik 
1835faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1836171f6537SJosef Bacik {
1837fc7cbcd4SDavid Sterba 	int ret;
1838fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
1839fc7cbcd4SDavid Sterba 	int i;
1840171f6537SJosef Bacik 
1841171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
1842fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
1843171f6537SJosef Bacik 				     struct btrfs_root, root_list);
1844fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
1845171f6537SJosef Bacik 
1846fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1847fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1848fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
1849171f6537SJosef Bacik 	}
1850171f6537SJosef Bacik 
1851fc7cbcd4SDavid Sterba 	while (1) {
1852fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1853fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
1854fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
1855fc7cbcd4SDavid Sterba 		if (!ret)
1856fc7cbcd4SDavid Sterba 			break;
1857fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
1858fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1859171f6537SJosef Bacik 	}
1860171f6537SJosef Bacik }
1861af31f5e5SChris Mason 
1862638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1863638aa7edSEric Sandeen {
1864638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
1865638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
1866638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
1867638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
1868638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
1869638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
1870ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
1871638aa7edSEric Sandeen }
1872638aa7edSEric Sandeen 
1873779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1874779a65a4SEric Sandeen {
1875779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
1876779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
1877779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
1878779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
1879779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
1880779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
1881907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
1882779a65a4SEric Sandeen }
1883779a65a4SEric Sandeen 
1884dcb2137cSChristoph Hellwig static int btrfs_init_btree_inode(struct super_block *sb)
1885f37938e0SEric Sandeen {
1886dcb2137cSChristoph Hellwig 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1887e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1888e256927bSJosef Bacik 					      fs_info->tree_root);
1889dcb2137cSChristoph Hellwig 	struct inode *inode;
1890dcb2137cSChristoph Hellwig 
1891dcb2137cSChristoph Hellwig 	inode = new_inode(sb);
1892dcb2137cSChristoph Hellwig 	if (!inode)
1893dcb2137cSChristoph Hellwig 		return -ENOMEM;
18942ff7e61eSJeff Mahoney 
18952ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
18962ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
1897f37938e0SEric Sandeen 	/*
1898f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
1899f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
1900f37938e0SEric Sandeen 	 * the devices in the system
1901f37938e0SEric Sandeen 	 */
19022ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
19032ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
1904dcb2137cSChristoph Hellwig 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1905f37938e0SEric Sandeen 
19062ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
190743eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
190835da5a7eSDavid Sterba 			    IO_TREE_BTREE_INODE_IO);
19092ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1910f37938e0SEric Sandeen 
19115c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1912adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
1913adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
1914adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
19152ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1916e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
1917dcb2137cSChristoph Hellwig 	fs_info->btree_inode = inode;
1918dcb2137cSChristoph Hellwig 
1919dcb2137cSChristoph Hellwig 	return 0;
1920f37938e0SEric Sandeen }
1921f37938e0SEric Sandeen 
1922ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1923ad618368SEric Sandeen {
1924ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1925129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
19267f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1927ad618368SEric Sandeen }
1928ad618368SEric Sandeen 
1929f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1930f9e92e40SEric Sandeen {
1931f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
1932f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
1933f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
1934f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1935f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
1936f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
1937d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
1938011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
1939f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
1940f9e92e40SEric Sandeen }
1941f9e92e40SEric Sandeen 
1942d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
19432a458198SEric Sandeen {
1944f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
19456f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
19462a458198SEric Sandeen 
19472a458198SEric Sandeen 	fs_info->workers =
1948a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
19492a458198SEric Sandeen 
19502a458198SEric Sandeen 	fs_info->delalloc_workers =
1951cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
1952cb001095SJeff Mahoney 				      flags, max_active, 2);
19532a458198SEric Sandeen 
19542a458198SEric Sandeen 	fs_info->flush_workers =
1955cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1956cb001095SJeff Mahoney 				      flags, max_active, 0);
19572a458198SEric Sandeen 
19582a458198SEric Sandeen 	fs_info->caching_workers =
1959cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
19602a458198SEric Sandeen 
19612a458198SEric Sandeen 	fs_info->fixup_workers =
1962cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
19632a458198SEric Sandeen 
19642a458198SEric Sandeen 	fs_info->endio_workers =
1965d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
19662a458198SEric Sandeen 	fs_info->endio_meta_workers =
1967d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
1968385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
19692a458198SEric Sandeen 	fs_info->endio_write_workers =
1970cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1971cb001095SJeff Mahoney 				      max_active, 2);
1972fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
1973fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
19742a458198SEric Sandeen 	fs_info->endio_freespace_worker =
1975cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
1976cb001095SJeff Mahoney 				      max_active, 0);
19772a458198SEric Sandeen 	fs_info->delayed_workers =
1978cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1979cb001095SJeff Mahoney 				      max_active, 0);
19802a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
1981cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
1982b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
1983b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
19842a458198SEric Sandeen 
19858bfec2e4SChristoph Hellwig 	if (!(fs_info->workers &&
1986a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
19872a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
1988fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
19891a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
19902a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
1991f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
1992f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
1993b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
19942a458198SEric Sandeen 		return -ENOMEM;
19952a458198SEric Sandeen 	}
19962a458198SEric Sandeen 
19972a458198SEric Sandeen 	return 0;
19982a458198SEric Sandeen }
19992a458198SEric Sandeen 
20006d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
20016d97c6e3SJohannes Thumshirn {
20026d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2003b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
20046d97c6e3SJohannes Thumshirn 
2005b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
20066d97c6e3SJohannes Thumshirn 
20076d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
20086d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2009b4e967beSDavid Sterba 			  csum_driver);
20106d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
20116d97c6e3SJohannes Thumshirn 	}
20126d97c6e3SJohannes Thumshirn 
20136d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
20146d97c6e3SJohannes Thumshirn 
201568d99ab0SChristoph Hellwig 	/*
201668d99ab0SChristoph Hellwig 	 * Check if the checksum implementation is a fast accelerated one.
201768d99ab0SChristoph Hellwig 	 * As-is this is a bit of a hack and should be replaced once the csum
201868d99ab0SChristoph Hellwig 	 * implementations provide that information themselves.
201968d99ab0SChristoph Hellwig 	 */
202068d99ab0SChristoph Hellwig 	switch (csum_type) {
202168d99ab0SChristoph Hellwig 	case BTRFS_CSUM_TYPE_CRC32:
202268d99ab0SChristoph Hellwig 		if (!strstr(crypto_shash_driver_name(csum_shash), "generic"))
202368d99ab0SChristoph Hellwig 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
202468d99ab0SChristoph Hellwig 		break;
202568d99ab0SChristoph Hellwig 	default:
202668d99ab0SChristoph Hellwig 		break;
202768d99ab0SChristoph Hellwig 	}
202868d99ab0SChristoph Hellwig 
2029c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2030c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2031c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
20326d97c6e3SJohannes Thumshirn 	return 0;
20336d97c6e3SJohannes Thumshirn }
20346d97c6e3SJohannes Thumshirn 
203563443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
203663443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
203763443bf5SEric Sandeen {
203863443bf5SEric Sandeen 	int ret;
2039789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
204063443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
204163443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
204263443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2043581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
204463443bf5SEric Sandeen 
204563443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2046f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
204763443bf5SEric Sandeen 		return -EIO;
204863443bf5SEric Sandeen 	}
204963443bf5SEric Sandeen 
205096dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
205196dfcb46SJosef Bacik 					 GFP_KERNEL);
205263443bf5SEric Sandeen 	if (!log_tree_root)
205363443bf5SEric Sandeen 		return -ENOMEM;
205463443bf5SEric Sandeen 
2055789d6a3aSQu Wenruo 	check.level = level;
2056789d6a3aSQu Wenruo 	check.transid = fs_info->generation + 1;
2057789d6a3aSQu Wenruo 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2058789d6a3aSQu Wenruo 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
205964c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2060f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
20610eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
20628c38938cSJosef Bacik 		log_tree_root->node = NULL;
206300246528SJosef Bacik 		btrfs_put_root(log_tree_root);
20640eeff236SLiu Bo 		return ret;
20654eb150d6SQu Wenruo 	}
20664eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2067f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
206800246528SJosef Bacik 		btrfs_put_root(log_tree_root);
206963443bf5SEric Sandeen 		return -EIO;
207063443bf5SEric Sandeen 	}
20714eb150d6SQu Wenruo 
207263443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
207363443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
207463443bf5SEric Sandeen 	if (ret) {
20750b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
207663443bf5SEric Sandeen 				      "Failed to recover log tree");
207700246528SJosef Bacik 		btrfs_put_root(log_tree_root);
207863443bf5SEric Sandeen 		return ret;
207963443bf5SEric Sandeen 	}
208063443bf5SEric Sandeen 
2081bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
20826bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
208363443bf5SEric Sandeen 		if (ret)
208463443bf5SEric Sandeen 			return ret;
208563443bf5SEric Sandeen 	}
208663443bf5SEric Sandeen 
208763443bf5SEric Sandeen 	return 0;
208863443bf5SEric Sandeen }
208963443bf5SEric Sandeen 
2090abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2091abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2092abed4aaaSJosef Bacik 				      const char *name)
2093abed4aaaSJosef Bacik {
2094abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2095abed4aaaSJosef Bacik 	struct btrfs_root *root;
2096f7238e50SJosef Bacik 	u64 max_global_id = 0;
2097abed4aaaSJosef Bacik 	int ret;
2098abed4aaaSJosef Bacik 	struct btrfs_key key = {
2099abed4aaaSJosef Bacik 		.objectid = objectid,
2100abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2101abed4aaaSJosef Bacik 		.offset = 0,
2102abed4aaaSJosef Bacik 	};
2103abed4aaaSJosef Bacik 	bool found = false;
2104abed4aaaSJosef Bacik 
2105abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2106abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2107abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2108abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2109abed4aaaSJosef Bacik 		return 0;
2110abed4aaaSJosef Bacik 	}
2111abed4aaaSJosef Bacik 
2112abed4aaaSJosef Bacik 	while (1) {
2113abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2114abed4aaaSJosef Bacik 		if (ret < 0)
2115abed4aaaSJosef Bacik 			break;
2116abed4aaaSJosef Bacik 
2117abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2118abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2119abed4aaaSJosef Bacik 			if (ret) {
2120abed4aaaSJosef Bacik 				if (ret > 0)
2121abed4aaaSJosef Bacik 					ret = 0;
2122abed4aaaSJosef Bacik 				break;
2123abed4aaaSJosef Bacik 			}
2124abed4aaaSJosef Bacik 		}
2125abed4aaaSJosef Bacik 		ret = 0;
2126abed4aaaSJosef Bacik 
2127abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2128abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2129abed4aaaSJosef Bacik 			break;
2130abed4aaaSJosef Bacik 		btrfs_release_path(path);
2131abed4aaaSJosef Bacik 
2132f7238e50SJosef Bacik 		/*
2133f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2134f7238e50SJosef Bacik 		 * everybody.
2135f7238e50SJosef Bacik 		 */
2136f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2137f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2138f7238e50SJosef Bacik 
2139abed4aaaSJosef Bacik 		found = true;
2140abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2141abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2142abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2143abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2144abed4aaaSJosef Bacik 			break;
2145abed4aaaSJosef Bacik 		}
2146abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2147abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2148abed4aaaSJosef Bacik 		if (ret) {
2149abed4aaaSJosef Bacik 			btrfs_put_root(root);
2150abed4aaaSJosef Bacik 			break;
2151abed4aaaSJosef Bacik 		}
2152abed4aaaSJosef Bacik 		key.offset++;
2153abed4aaaSJosef Bacik 	}
2154abed4aaaSJosef Bacik 	btrfs_release_path(path);
2155abed4aaaSJosef Bacik 
2156f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2157f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2158f7238e50SJosef Bacik 
2159abed4aaaSJosef Bacik 	if (!found || ret) {
2160abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2161abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2162abed4aaaSJosef Bacik 
2163abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2164abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2165abed4aaaSJosef Bacik 		else
2166abed4aaaSJosef Bacik 			ret = 0;
2167abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2168abed4aaaSJosef Bacik 	}
2169abed4aaaSJosef Bacik 	return ret;
2170abed4aaaSJosef Bacik }
2171abed4aaaSJosef Bacik 
2172abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2173abed4aaaSJosef Bacik {
2174abed4aaaSJosef Bacik 	struct btrfs_path *path;
2175abed4aaaSJosef Bacik 	int ret = 0;
2176abed4aaaSJosef Bacik 
2177abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2178abed4aaaSJosef Bacik 	if (!path)
2179abed4aaaSJosef Bacik 		return -ENOMEM;
2180abed4aaaSJosef Bacik 
2181abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2182abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2183abed4aaaSJosef Bacik 	if (ret)
2184abed4aaaSJosef Bacik 		goto out;
2185abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2186abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2187abed4aaaSJosef Bacik 	if (ret)
2188abed4aaaSJosef Bacik 		goto out;
2189abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2190abed4aaaSJosef Bacik 		goto out;
2191abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2192abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2193abed4aaaSJosef Bacik 					 "free space");
2194abed4aaaSJosef Bacik out:
2195abed4aaaSJosef Bacik 	btrfs_free_path(path);
2196abed4aaaSJosef Bacik 	return ret;
2197abed4aaaSJosef Bacik }
2198abed4aaaSJosef Bacik 
21996bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
22004bbcaa64SEric Sandeen {
22016bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2202a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
22034bbcaa64SEric Sandeen 	struct btrfs_key location;
22044bbcaa64SEric Sandeen 	int ret;
22054bbcaa64SEric Sandeen 
22066bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
22076bccf3abSJeff Mahoney 
2208abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2209abed4aaaSJosef Bacik 	if (ret)
2210abed4aaaSJosef Bacik 		return ret;
2211abed4aaaSJosef Bacik 
22124bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
22134bbcaa64SEric Sandeen 	location.offset = 0;
22144bbcaa64SEric Sandeen 
22151c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
221614033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
221714033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
221814033b08SQu Wenruo 		if (IS_ERR(root)) {
221914033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
222014033b08SQu Wenruo 				ret = PTR_ERR(root);
222114033b08SQu Wenruo 				goto out;
222214033b08SQu Wenruo 			}
222314033b08SQu Wenruo 		} else {
222414033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
222514033b08SQu Wenruo 			fs_info->block_group_root = root;
222614033b08SQu Wenruo 		}
222714033b08SQu Wenruo 	}
222814033b08SQu Wenruo 
222914033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2230a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2231f50f4353SLiu Bo 	if (IS_ERR(root)) {
223242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2233f50f4353SLiu Bo 			ret = PTR_ERR(root);
2234f50f4353SLiu Bo 			goto out;
2235f50f4353SLiu Bo 		}
223642437a63SJosef Bacik 	} else {
2237a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2238a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
223942437a63SJosef Bacik 	}
2240820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2241a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2242a8d1b164SJohannes Thumshirn 	if (ret)
2243a8d1b164SJohannes Thumshirn 		goto out;
22444bbcaa64SEric Sandeen 
2245aeb935a4SQu Wenruo 	/*
2246aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2247aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2248aeb935a4SQu Wenruo 	 */
224956e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
225056e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2251aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
225242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2253aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2254aeb935a4SQu Wenruo 			goto out;
2255aeb935a4SQu Wenruo 		}
225642437a63SJosef Bacik 	} else {
2257aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2258aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
225942437a63SJosef Bacik 	}
2260aeb935a4SQu Wenruo 
22614bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2262a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2263a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2264a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2265afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2266a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
22674bbcaa64SEric Sandeen 	}
22684bbcaa64SEric Sandeen 
22694bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2270a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2271a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
227242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2273a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
22744bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2275f50f4353SLiu Bo 				goto out;
227642437a63SJosef Bacik 		}
22774bbcaa64SEric Sandeen 	} else {
2278a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2279a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
22804bbcaa64SEric Sandeen 	}
22814bbcaa64SEric Sandeen 
22824bbcaa64SEric Sandeen 	return 0;
2283f50f4353SLiu Bo out:
2284f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2285f50f4353SLiu Bo 		   location.objectid, ret);
2286f50f4353SLiu Bo 	return ret;
22874bbcaa64SEric Sandeen }
22884bbcaa64SEric Sandeen 
2289069ec957SQu Wenruo /*
2290069ec957SQu Wenruo  * Real super block validation
2291069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2292069ec957SQu Wenruo  *
2293069ec957SQu Wenruo  * @sb:		super block to check
2294069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2295069ec957SQu Wenruo  * 		0	the primary (1st) sb
2296069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2297069ec957SQu Wenruo  * 	       -1	skip bytenr check
2298069ec957SQu Wenruo  */
2299a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2300069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
230121a852b0SQu Wenruo {
230221a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
230321a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
230421a852b0SQu Wenruo 	int ret = 0;
230521a852b0SQu Wenruo 
230621a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
230721a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
230821a852b0SQu Wenruo 		ret = -EINVAL;
230921a852b0SQu Wenruo 	}
231021a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
231121a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
231221a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
231321a852b0SQu Wenruo 		ret = -EINVAL;
231421a852b0SQu Wenruo 	}
231521a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
231621a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
231721a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
231821a852b0SQu Wenruo 		ret = -EINVAL;
231921a852b0SQu Wenruo 	}
232021a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
232121a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
232221a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
232321a852b0SQu Wenruo 		ret = -EINVAL;
232421a852b0SQu Wenruo 	}
232521a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
232621a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
232721a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
232821a852b0SQu Wenruo 		ret = -EINVAL;
232921a852b0SQu Wenruo 	}
233021a852b0SQu Wenruo 
233121a852b0SQu Wenruo 	/*
233221a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
233321a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
233421a852b0SQu Wenruo 	 */
233521a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
233621a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
233721a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
233821a852b0SQu Wenruo 		ret = -EINVAL;
233921a852b0SQu Wenruo 	}
23400bb3eb3eSQu Wenruo 
23410bb3eb3eSQu Wenruo 	/*
23421a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
23431a42daabSQu Wenruo 	 *
23441a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
23451a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
23461a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
23471a42daabSQu Wenruo 	 * beginning.
23480bb3eb3eSQu Wenruo 	 */
23491a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
235021a852b0SQu Wenruo 		btrfs_err(fs_info,
23510bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
235221a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
235321a852b0SQu Wenruo 		ret = -EINVAL;
235421a852b0SQu Wenruo 	}
23550bb3eb3eSQu Wenruo 
235621a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
235721a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
235821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
235921a852b0SQu Wenruo 		ret = -EINVAL;
236021a852b0SQu Wenruo 	}
236121a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
236221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
236321a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
236421a852b0SQu Wenruo 		ret = -EINVAL;
236521a852b0SQu Wenruo 	}
236621a852b0SQu Wenruo 
236721a852b0SQu Wenruo 	/* Root alignment check */
236821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
236921a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
237021a852b0SQu Wenruo 			   btrfs_super_root(sb));
237121a852b0SQu Wenruo 		ret = -EINVAL;
237221a852b0SQu Wenruo 	}
237321a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
237421a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
237521a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
237621a852b0SQu Wenruo 		ret = -EINVAL;
237721a852b0SQu Wenruo 	}
237821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
237921a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
238021a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
238121a852b0SQu Wenruo 		ret = -EINVAL;
238221a852b0SQu Wenruo 	}
238321a852b0SQu Wenruo 
2384aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2385aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2386aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2387aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2388aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2389aefd7f70SNikolay Borisov 		ret = -EINVAL;
2390aefd7f70SNikolay Borisov 	}
2391aefd7f70SNikolay Borisov 
2392aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2393aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2394aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2395aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2396aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2397aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2398aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2399aefd7f70SNikolay Borisov 		ret = -EINVAL;
2400aefd7f70SNikolay Borisov 	}
2401aefd7f70SNikolay Borisov 
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 
2414de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
24157239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
241621a852b0SQu Wenruo 		btrfs_err(fs_info,
24177239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2418de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
241921a852b0SQu Wenruo 		ret = -EINVAL;
242021a852b0SQu Wenruo 	}
242121a852b0SQu Wenruo 
242221a852b0SQu Wenruo 	/*
242321a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
242421a852b0SQu Wenruo 	 * done later
242521a852b0SQu Wenruo 	 */
242621a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
242721a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
242821a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
242921a852b0SQu Wenruo 		ret = -EINVAL;
243021a852b0SQu Wenruo 	}
243121a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
243221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
243321a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
243421a852b0SQu Wenruo 		ret = -EINVAL;
243521a852b0SQu Wenruo 	}
243621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
243721a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
243821a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
243921a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
244021a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
244121a852b0SQu Wenruo 		ret = -EINVAL;
244221a852b0SQu Wenruo 	}
244321a852b0SQu Wenruo 
2444069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2445069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
244621a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
244721a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
244821a852b0SQu Wenruo 		ret = -EINVAL;
244921a852b0SQu Wenruo 	}
245021a852b0SQu Wenruo 
245121a852b0SQu Wenruo 	/*
245221a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
245321a852b0SQu Wenruo 	 * and one chunk
245421a852b0SQu Wenruo 	 */
245521a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
245621a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
245721a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
245821a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
245921a852b0SQu Wenruo 		ret = -EINVAL;
246021a852b0SQu Wenruo 	}
246121a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
246221a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
246321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
246421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
246521a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
246621a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
246721a852b0SQu Wenruo 		ret = -EINVAL;
246821a852b0SQu Wenruo 	}
246921a852b0SQu Wenruo 
247021a852b0SQu Wenruo 	/*
247121a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
247221a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
247321a852b0SQu Wenruo 	 */
247421a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
247521a852b0SQu Wenruo 		btrfs_warn(fs_info,
247621a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
247721a852b0SQu Wenruo 			btrfs_super_generation(sb),
247821a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
247921a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
248021a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
248121a852b0SQu Wenruo 		btrfs_warn(fs_info,
248221a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
248321a852b0SQu Wenruo 			btrfs_super_generation(sb),
248421a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
248521a852b0SQu Wenruo 
248621a852b0SQu Wenruo 	return ret;
248721a852b0SQu Wenruo }
248821a852b0SQu Wenruo 
2489069ec957SQu Wenruo /*
2490069ec957SQu Wenruo  * Validation of super block at mount time.
2491069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2492069ec957SQu Wenruo  * flags will be skipped.
2493069ec957SQu Wenruo  */
2494069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2495069ec957SQu Wenruo {
2496a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2497069ec957SQu Wenruo }
2498069ec957SQu Wenruo 
249975cb857dSQu Wenruo /*
250075cb857dSQu Wenruo  * Validation of super block at write time.
250175cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
250275cb857dSQu Wenruo  * overwritten soon.
250375cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
250475cb857dSQu Wenruo  */
250575cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
250675cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
250775cb857dSQu Wenruo {
250875cb857dSQu Wenruo 	int ret;
250975cb857dSQu Wenruo 
2510a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
251175cb857dSQu Wenruo 	if (ret < 0)
251275cb857dSQu Wenruo 		goto out;
2513e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
251475cb857dSQu Wenruo 		ret = -EUCLEAN;
251575cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
251675cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
251775cb857dSQu Wenruo 		goto out;
251875cb857dSQu Wenruo 	}
251975cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
252075cb857dSQu Wenruo 		ret = -EUCLEAN;
252175cb857dSQu Wenruo 		btrfs_err(fs_info,
252275cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
252375cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
252475cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
252575cb857dSQu Wenruo 		goto out;
252675cb857dSQu Wenruo 	}
252775cb857dSQu Wenruo out:
252875cb857dSQu Wenruo 	if (ret < 0)
252975cb857dSQu Wenruo 		btrfs_err(fs_info,
253075cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
253175cb857dSQu Wenruo 	return ret;
253275cb857dSQu Wenruo }
253375cb857dSQu Wenruo 
2534bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2535bd676446SJosef Bacik {
2536789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2537789d6a3aSQu Wenruo 		.level = level,
2538789d6a3aSQu Wenruo 		.transid = gen,
2539789d6a3aSQu Wenruo 		.owner_root = root->root_key.objectid
2540789d6a3aSQu Wenruo 	};
2541bd676446SJosef Bacik 	int ret = 0;
2542bd676446SJosef Bacik 
2543789d6a3aSQu Wenruo 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2544bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2545bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2546bd676446SJosef Bacik 		root->node = NULL;
25474eb150d6SQu Wenruo 		return ret;
25484eb150d6SQu Wenruo 	}
25494eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2550bd676446SJosef Bacik 		free_extent_buffer(root->node);
2551bd676446SJosef Bacik 		root->node = NULL;
25524eb150d6SQu Wenruo 		return -EIO;
2553bd676446SJosef Bacik 	}
2554bd676446SJosef Bacik 
2555bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2556bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2557bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2558bd676446SJosef Bacik 	return ret;
2559bd676446SJosef Bacik }
2560bd676446SJosef Bacik 
2561bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2562bd676446SJosef Bacik {
2563bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2564bd676446SJosef Bacik 	u64 gen, bytenr;
2565bd676446SJosef Bacik 	int level, ret;
2566bd676446SJosef Bacik 
2567bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2568bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2569bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2570bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
25719c54e80dSJosef Bacik 	if (ret) {
2572bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2573bd676446SJosef Bacik 		return ret;
2574bd676446SJosef Bacik 	}
25759c54e80dSJosef Bacik 	return 0;
25769c54e80dSJosef Bacik }
25779c54e80dSJosef Bacik 
25786ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2579b8522a1eSNikolay Borisov {
25806ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2581b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2582b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2583b8522a1eSNikolay Borisov 	bool handle_error = false;
2584b8522a1eSNikolay Borisov 	int ret = 0;
2585b8522a1eSNikolay Borisov 	int i;
2586b8522a1eSNikolay Borisov 
2587b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2588b8522a1eSNikolay Borisov 		if (handle_error) {
2589b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2590b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2591b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2592b8522a1eSNikolay Borisov 
2593b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2594b8522a1eSNikolay Borisov 				break;
2595b8522a1eSNikolay Borisov 
2596b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2597b8522a1eSNikolay Borisov 
2598b8522a1eSNikolay Borisov 			/*
2599b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2600b8522a1eSNikolay Borisov 			 * valid
2601b8522a1eSNikolay Borisov 			 */
2602b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2603b8522a1eSNikolay Borisov 
2604b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2605b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2606b8522a1eSNikolay Borisov 
2607745806fbSQu Wenruo 			btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2608b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
26096ef108ddSNikolay Borisov 			backup_index = ret;
2610b8522a1eSNikolay Borisov 			if (ret < 0)
2611b8522a1eSNikolay Borisov 				return ret;
2612b8522a1eSNikolay Borisov 		}
2613b8522a1eSNikolay Borisov 
2614bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2615bd676446SJosef Bacik 		if (ret) {
2616217f5004SNikolay Borisov 			handle_error = true;
2617b8522a1eSNikolay Borisov 			continue;
2618b8522a1eSNikolay Borisov 		}
2619b8522a1eSNikolay Borisov 
2620336a0d8dSNikolay Borisov 		/*
2621336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2622336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2623336a0d8dSNikolay Borisov 		 */
2624453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2625b8522a1eSNikolay Borisov 		if (ret < 0) {
2626b8522a1eSNikolay Borisov 			handle_error = true;
2627b8522a1eSNikolay Borisov 			continue;
2628b8522a1eSNikolay Borisov 		}
2629b8522a1eSNikolay Borisov 
26306b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2631b8522a1eSNikolay Borisov 
2632b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2633b8522a1eSNikolay Borisov 		if (ret < 0) {
2634b8522a1eSNikolay Borisov 			handle_error = true;
2635b8522a1eSNikolay Borisov 			continue;
2636b8522a1eSNikolay Borisov 		}
2637b8522a1eSNikolay Borisov 
2638b8522a1eSNikolay Borisov 		/* All successful */
2639bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2640bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2641d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
26426ef108ddSNikolay Borisov 
26436ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26446ef108ddSNikolay Borisov 		if (backup_index < 0) {
26456ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26466ef108ddSNikolay Borisov 		} else {
26476ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26486ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26496ef108ddSNikolay Borisov 		}
2650b8522a1eSNikolay Borisov 		break;
2651b8522a1eSNikolay Borisov 	}
2652b8522a1eSNikolay Borisov 
2653b8522a1eSNikolay Borisov 	return ret;
2654b8522a1eSNikolay Borisov }
2655b8522a1eSNikolay Borisov 
26568260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2657eb60ceacSChris Mason {
2658fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
265901cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26608fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2661facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
266224bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2663eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
266411833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2665eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2666a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2667fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
266824bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26694cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2670ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2671f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
267247ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
267340ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2674afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2675c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2676f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2677abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2678d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2679f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
26807585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2681573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
26820bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
26835f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2684de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
268519c00ddcSChris Mason 
2686e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
26875a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
26888b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
26895f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
26903e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
26913e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
26923e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
26933e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
26943e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
26953e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
26963e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
26973e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2698e1489b4fSIoannis Angelakopoulos 
26990b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
27006324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2701f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
270247ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
270318bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2704afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2705bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2706bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
27073fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
27083fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2709bd647ce3SJosef Bacik #endif
2710c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
271166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
271266d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
271366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
271466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
271566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
271666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
271766d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2718ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2719ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2720ba2c4d4eSJosef Bacik 
2721771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
27224cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2723034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2724fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2725abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
272695ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27279ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27284cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2729a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2730f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27318b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2732fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2733c8b97818SChris Mason 
2734b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2735b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27360afbaf8cSChris Mason 
2737199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2738199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
273969fe2d75SJosef Bacik 
2740638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
274121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
274221adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
274321adbd5cSStefan Behrens #endif
2744779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
274557056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2746a2de733cSArne Jansen 
274716b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
274808dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
27490f9dd46cSJosef Bacik 
2750fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
275135da5a7eSDavid Sterba 			    IO_TREE_FS_EXCLUDED_EXTENTS);
275239279cc3SChris Mason 
27535a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2754e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2755925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2756a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2757a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27581bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27599e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2760c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
276176dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2762803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2763fa9c0d79SChris Mason 
2764ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2765f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2766b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2767416ac51dSArne Jansen 
2768fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2769fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2770fa9c0d79SChris Mason 
2771e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2772f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2773bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27744854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2775034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
27763768f368SChris Mason 
2777da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2778da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2779da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2780ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2781da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2782da17066cSJeff Mahoney 
2783f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2784f7b12a62SNaohiro Aota 
2785eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2786eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2787eede2bf3SOmar Sandoval 
278818bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
278918bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
27908260edbaSJosef Bacik }
27918260edbaSJosef Bacik 
27928260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
27938260edbaSJosef Bacik {
27948260edbaSJosef Bacik 	int ret;
27958260edbaSJosef Bacik 
27968260edbaSJosef Bacik 	fs_info->sb = sb;
27978260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
27988260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
27999e967495SFilipe Manana 
28005deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2801ae18c37aSJosef Bacik 	if (ret)
2802ae18c37aSJosef Bacik 		return ret;
2803ae18c37aSJosef Bacik 
2804ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2805ae18c37aSJosef Bacik 	if (ret)
2806c75e8394SJosef Bacik 		return ret;
2807ae18c37aSJosef Bacik 
2808ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2809ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2810ae18c37aSJosef Bacik 
2811ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2812ae18c37aSJosef Bacik 	if (ret)
2813c75e8394SJosef Bacik 		return ret;
2814ae18c37aSJosef Bacik 
2815ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2816ae18c37aSJosef Bacik 			GFP_KERNEL);
2817ae18c37aSJosef Bacik 	if (ret)
2818c75e8394SJosef Bacik 		return ret;
2819ae18c37aSJosef Bacik 
2820ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2821ae18c37aSJosef Bacik 					GFP_KERNEL);
2822c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2823c75e8394SJosef Bacik 		return -ENOMEM;
2824ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2825ae18c37aSJosef Bacik 
2826a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
2827a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2828a0a1db70SFilipe Manana 
2829c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2830ae18c37aSJosef Bacik }
2831ae18c37aSJosef Bacik 
283297f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
283397f4dd09SNikolay Borisov {
28340d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
283597f4dd09SNikolay Borisov 	int ret;
283697f4dd09SNikolay Borisov 
283797f4dd09SNikolay Borisov 	/*
283897f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
283997f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
284097f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
284197f4dd09SNikolay Borisov 	 */
284297f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
284397f4dd09SNikolay Borisov 	if (ret < 0) {
2844c94bec2cSJosef Bacik 		if (ret != -EINTR)
2845c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2846c94bec2cSJosef Bacik 				   ret);
284797f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
284897f4dd09SNikolay Borisov 		return ret;
284997f4dd09SNikolay Borisov 	}
285097f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
285197f4dd09SNikolay Borisov }
285297f4dd09SNikolay Borisov 
285397f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
285497f4dd09SNikolay Borisov {
285597f4dd09SNikolay Borisov 	struct task_struct *task;
285697f4dd09SNikolay Borisov 
285797f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
285897f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
285997f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
286097f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
286197f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
286297f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
286397f4dd09SNikolay Borisov 		return PTR_ERR(task);
286497f4dd09SNikolay Borisov 	}
286597f4dd09SNikolay Borisov 
286697f4dd09SNikolay Borisov 	return 0;
286797f4dd09SNikolay Borisov }
286897f4dd09SNikolay Borisov 
286944c0ca21SBoris Burkov /*
28708cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
28718cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
28728cd29088SBoris Burkov  * code paths.
28738cd29088SBoris Burkov  */
28748cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
28758cd29088SBoris Burkov {
28768cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
28778b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
28788cd29088SBoris Burkov }
28798cd29088SBoris Burkov 
28808cd29088SBoris Burkov /*
288144c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
288244c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
288344c0ca21SBoris Burkov  */
288444c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
288544c0ca21SBoris Burkov {
288644c0ca21SBoris Burkov 	int ret;
288794846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
28881d6a4fc8SQu Wenruo 	bool rebuild_free_space_tree = false;
28898b228324SBoris Burkov 
28908b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
28918b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
28921d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
28938b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
28948b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
28958b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
28961d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
28978b228324SBoris Burkov 	}
28988b228324SBoris Burkov 
28991d6a4fc8SQu Wenruo 	if (rebuild_free_space_tree) {
29001d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "rebuilding free space tree");
29011d6a4fc8SQu Wenruo 		ret = btrfs_rebuild_free_space_tree(fs_info);
29028b228324SBoris Burkov 		if (ret) {
29038b228324SBoris Burkov 			btrfs_warn(fs_info,
29041d6a4fc8SQu Wenruo 				   "failed to rebuild free space tree: %d", ret);
29051d6a4fc8SQu Wenruo 			goto out;
29061d6a4fc8SQu Wenruo 		}
29071d6a4fc8SQu Wenruo 	}
29081d6a4fc8SQu Wenruo 
29091d6a4fc8SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
29101d6a4fc8SQu Wenruo 	    !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
29111d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "disabling free space tree");
29121d6a4fc8SQu Wenruo 		ret = btrfs_delete_free_space_tree(fs_info);
29131d6a4fc8SQu Wenruo 		if (ret) {
29141d6a4fc8SQu Wenruo 			btrfs_warn(fs_info,
29151d6a4fc8SQu Wenruo 				   "failed to disable free space tree: %d", ret);
29168b228324SBoris Burkov 			goto out;
29178b228324SBoris Burkov 		}
29188b228324SBoris Burkov 	}
291944c0ca21SBoris Burkov 
29208d488a8cSFilipe Manana 	/*
29218d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
29228d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
2923fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
29248d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
29258d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
29268d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
29278d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
29288d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
29298d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
29308d488a8cSFilipe Manana 	 */
29318d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
29328d488a8cSFilipe Manana 	if (ret)
29338d488a8cSFilipe Manana 		goto out;
29348d488a8cSFilipe Manana 
293544c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
293644c0ca21SBoris Burkov 	if (ret)
293744c0ca21SBoris Burkov 		goto out;
293844c0ca21SBoris Burkov 
29398f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
29408f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
29418f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
29428f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
29438f1c21d7SBoris Burkov 		goto out;
29448f1c21d7SBoris Burkov 	}
29458f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
29468f1c21d7SBoris Burkov 
294744c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
29487eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
294944c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
295044c0ca21SBoris Burkov 	if (ret < 0) {
295144c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
295244c0ca21SBoris Burkov 		goto out;
295344c0ca21SBoris Burkov 	}
295444c0ca21SBoris Burkov 
29555011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
29565011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
29575011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
29585011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
29595011139aSBoris Burkov 		if (ret) {
29605011139aSBoris Burkov 			btrfs_warn(fs_info,
29615011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
29625011139aSBoris Burkov 			goto out;
29635011139aSBoris Burkov 		}
29645011139aSBoris Burkov 	}
29655011139aSBoris Burkov 
296694846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
296794846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
296894846229SBoris Burkov 		if (ret)
296994846229SBoris Burkov 			goto out;
297094846229SBoris Burkov 	}
297194846229SBoris Burkov 
297244c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
297344c0ca21SBoris Burkov 	if (ret)
297444c0ca21SBoris Burkov 		goto out;
297544c0ca21SBoris Burkov 
297644c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
297744c0ca21SBoris Burkov 	if (ret) {
297844c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
297944c0ca21SBoris Burkov 		goto out;
298044c0ca21SBoris Burkov 	}
298144c0ca21SBoris Burkov 
298244c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
298344c0ca21SBoris Burkov 
298444c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
298544c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
298644c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
298744c0ca21SBoris Burkov 		if (ret) {
298844c0ca21SBoris Burkov 			btrfs_warn(fs_info,
298944c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
299044c0ca21SBoris Burkov 			goto out;
299144c0ca21SBoris Burkov 		}
299244c0ca21SBoris Burkov 	}
299344c0ca21SBoris Burkov 
299444c0ca21SBoris Burkov out:
299544c0ca21SBoris Burkov 	return ret;
299644c0ca21SBoris Burkov }
299744c0ca21SBoris Burkov 
2998d7f67ac9SQu Wenruo /*
2999d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
3000d7f67ac9SQu Wenruo  *
30012ba48b20SQu Wenruo  * @is_rw_mount:	If the mount is read-write.
30022ba48b20SQu Wenruo  *
3003d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
3004d7f67ac9SQu Wenruo  * feature dependencies).
3005d7f67ac9SQu Wenruo  *
3006d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
3007d7f67ac9SQu Wenruo  * btrfs_validate_super().
3008d7f67ac9SQu Wenruo  *
3009d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3010d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3011d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3012d7f67ac9SQu Wenruo  */
30132ba48b20SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3014d7f67ac9SQu Wenruo {
3015d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3016d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3017d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3018d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3019d7f67ac9SQu Wenruo 
3020d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3021d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3022d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3023d7f67ac9SQu Wenruo 		    incompat);
3024d7f67ac9SQu Wenruo 		return -EINVAL;
3025d7f67ac9SQu Wenruo 	}
3026d7f67ac9SQu Wenruo 
3027d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3028d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3029d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3030d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3031d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3032d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3033d7f67ac9SQu Wenruo 		return -EINVAL;
3034d7f67ac9SQu Wenruo 	}
3035d7f67ac9SQu Wenruo 
3036d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3037d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3038d7f67ac9SQu Wenruo 
3039d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3040d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3041d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3042d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3043d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3044d7f67ac9SQu Wenruo 
3045d7f67ac9SQu Wenruo 	/*
3046d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3047d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3048d7f67ac9SQu Wenruo 	 */
3049d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3050d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3051d7f67ac9SQu Wenruo 
30522ba48b20SQu Wenruo 	if (compat_ro_unsupp && is_rw_mount) {
3053d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3054d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3055d7f67ac9SQu Wenruo 		       compat_ro);
3056d7f67ac9SQu Wenruo 		return -EINVAL;
3057d7f67ac9SQu Wenruo 	}
3058d7f67ac9SQu Wenruo 
3059d7f67ac9SQu Wenruo 	/*
3060d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3061d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3062d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3063d7f67ac9SQu Wenruo 	 */
3064d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3065d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3066d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3067d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3068d7f67ac9SQu Wenruo 			  compat_ro);
3069d7f67ac9SQu Wenruo 		return -EINVAL;
3070d7f67ac9SQu Wenruo 	}
3071d7f67ac9SQu Wenruo 
3072d7f67ac9SQu Wenruo 	/*
3073d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3074d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3075d7f67ac9SQu Wenruo 	 */
3076d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3077d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3078d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3079d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3080d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3081d7f67ac9SQu Wenruo 		return -EINVAL;
3082d7f67ac9SQu Wenruo 	}
3083d7f67ac9SQu Wenruo 
3084d7f67ac9SQu Wenruo 	/*
3085d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3086d7f67ac9SQu Wenruo 	 *
3087d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3088d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3089d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3090d7f67ac9SQu Wenruo 	 */
3091d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3092d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3093d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3094d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3095d7f67ac9SQu Wenruo 		return -EINVAL;
3096d7f67ac9SQu Wenruo 	}
3097d7f67ac9SQu Wenruo 
3098d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3099d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3100d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3101d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3102d7f67ac9SQu Wenruo 
3103d7f67ac9SQu Wenruo 	return 0;
3104d7f67ac9SQu Wenruo }
3105d7f67ac9SQu Wenruo 
3106ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3107ae18c37aSJosef Bacik 		      char *options)
3108ae18c37aSJosef Bacik {
3109ae18c37aSJosef Bacik 	u32 sectorsize;
3110ae18c37aSJosef Bacik 	u32 nodesize;
3111ae18c37aSJosef Bacik 	u32 stripesize;
3112ae18c37aSJosef Bacik 	u64 generation;
3113ae18c37aSJosef Bacik 	u64 features;
3114ae18c37aSJosef Bacik 	u16 csum_type;
3115ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3116ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3117ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3118ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3119ae18c37aSJosef Bacik 	int ret;
3120ae18c37aSJosef Bacik 	int level;
3121ae18c37aSJosef Bacik 
31228260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
31234871c33bSQu Wenruo 	if (ret)
3124ae18c37aSJosef Bacik 		goto fail;
312553b381b3SDavid Woodhouse 
3126ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3127ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3128ae18c37aSJosef Bacik 				     GFP_KERNEL);
3129ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3130ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3131ae18c37aSJosef Bacik 				      GFP_KERNEL);
3132ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3133ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
31344871c33bSQu Wenruo 		ret = -ENOMEM;
3135c75e8394SJosef Bacik 		goto fail;
3136ae18c37aSJosef Bacik 	}
3137ae18c37aSJosef Bacik 
3138dcb2137cSChristoph Hellwig 	ret = btrfs_init_btree_inode(sb);
31394871c33bSQu Wenruo 	if (ret)
3140c75e8394SJosef Bacik 		goto fail;
3141ae18c37aSJosef Bacik 
3142d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
31431104a885SDavid Sterba 
31441104a885SDavid Sterba 	/*
31451104a885SDavid Sterba 	 * Read super block and check the signature bytes only
31461104a885SDavid Sterba 	 */
3147d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
31488f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
31494871c33bSQu Wenruo 		ret = PTR_ERR(disk_super);
315016cdcec7SMiao Xie 		goto fail_alloc;
315120b45077SDave Young 	}
315239279cc3SChris Mason 
31531104a885SDavid Sterba 	/*
3154260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
31558dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
31568dc3f22cSJohannes Thumshirn 	 */
31578f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
315851bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
31598dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
316051bce6c9SJohannes Thumshirn 			  csum_type);
31614871c33bSQu Wenruo 		ret = -EINVAL;
31628f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31638dc3f22cSJohannes Thumshirn 		goto fail_alloc;
31648dc3f22cSJohannes Thumshirn 	}
31658dc3f22cSJohannes Thumshirn 
316683c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
316783c68bbcSSu Yue 
31686d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
31696d97c6e3SJohannes Thumshirn 	if (ret) {
31708f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31716d97c6e3SJohannes Thumshirn 		goto fail_alloc;
31726d97c6e3SJohannes Thumshirn 	}
31736d97c6e3SJohannes Thumshirn 
31748dc3f22cSJohannes Thumshirn 	/*
31751104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
31761104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
31771104a885SDavid Sterba 	 */
31783d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
317905135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
31804871c33bSQu Wenruo 		ret = -EINVAL;
31818f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3182141386e1SJosef Bacik 		goto fail_alloc;
31831104a885SDavid Sterba 	}
31841104a885SDavid Sterba 
31851104a885SDavid Sterba 	/*
31861104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
31871104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
31881104a885SDavid Sterba 	 * the whole block of INFO_SIZE
31891104a885SDavid Sterba 	 */
31908f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
31918f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
31925f39d397SChris Mason 
3193fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3194fbc6feaeSNikolay Borisov 
31950b86a832SChris Mason 
3196fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3197fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3198fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3199fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3200fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3201fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3202fbc6feaeSNikolay Borisov 	}
3203fbc6feaeSNikolay Borisov 
3204fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3205fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3206de37aa51SNikolay Borisov 
3207069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
32081104a885SDavid Sterba 	if (ret) {
320905135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
32104871c33bSQu Wenruo 		ret = -EINVAL;
3211141386e1SJosef Bacik 		goto fail_alloc;
32121104a885SDavid Sterba 	}
32131104a885SDavid Sterba 
32144871c33bSQu Wenruo 	if (!btrfs_super_root(disk_super)) {
32154871c33bSQu Wenruo 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
32164871c33bSQu Wenruo 		ret = -EINVAL;
3217141386e1SJosef Bacik 		goto fail_alloc;
32184871c33bSQu Wenruo 	}
32190f7d52f4SChris Mason 
3220acce952bSliubo 	/* check FS state, whether FS is broken. */
322187533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
322287533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3223acce952bSliubo 
322475e7cb7fSLiu Bo 	/*
322575e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
322675e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
322775e7cb7fSLiu Bo 	 */
322875e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
322975e7cb7fSLiu Bo 
32306f93e834SAnand Jain 
32316f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
32326f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
32336f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
32346f93e834SAnand Jain 	stripesize = sectorsize;
32356f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
32366f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
32376f93e834SAnand Jain 
32386f93e834SAnand Jain 	fs_info->nodesize = nodesize;
32396f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
32406f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
32416f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
32426f93e834SAnand Jain 	fs_info->stripesize = stripesize;
32436f93e834SAnand Jain 
32442ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
32454871c33bSQu Wenruo 	if (ret)
3246141386e1SJosef Bacik 		goto fail_alloc;
3247dfe25020SChris Mason 
32482ba48b20SQu Wenruo 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
32494871c33bSQu Wenruo 	if (ret < 0)
3250141386e1SJosef Bacik 		goto fail_alloc;
3251f2b636e8SJosef Bacik 
32528481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
32538481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
32548481dd80SQu Wenruo 
32559f73f1aeSQu Wenruo 		/*
32569f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
32579f73f1aeSQu Wenruo 		 * going to be deprecated.
32589f73f1aeSQu Wenruo 		 *
32599f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
32609f73f1aeSQu Wenruo 		 */
32619f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
32629f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
32639f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
32649f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
32659f73f1aeSQu Wenruo 
326695ea0486SQu Wenruo 		btrfs_warn(fs_info,
326795ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
32680bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
32698481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
32704871c33bSQu Wenruo 		if (!subpage_info) {
32714871c33bSQu Wenruo 			ret = -ENOMEM;
32728481dd80SQu Wenruo 			goto fail_alloc;
32734871c33bSQu Wenruo 		}
32748481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
32758481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3276c8050b3bSQu Wenruo 	}
32770bb3eb3eSQu Wenruo 
3278d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
32794871c33bSQu Wenruo 	if (ret)
32800dc3b84aSJosef Bacik 		goto fail_sb_buffer;
32814543df7eSChris Mason 
32829e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
32839e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
32844575c9ccSChris Mason 
3285a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3286a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3287de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3288db94535dSChris Mason 
3289925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
32906bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3291925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
329284eed90fSChris Mason 	if (ret) {
329305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
32945d4f98a2SYan Zheng 		goto fail_sb_buffer;
329584eed90fSChris Mason 	}
32960b86a832SChris Mason 
329784234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3298581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3299bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3300bd676446SJosef Bacik 			      generation, level);
3301bd676446SJosef Bacik 	if (ret) {
330205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3303af31f5e5SChris Mason 		goto fail_tree_roots;
330483121942SDavid Woodhouse 	}
33050b86a832SChris Mason 
3306e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3307c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3308c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3309e17cade2SChris Mason 
33105b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
33112b82032cSYan Zheng 	if (ret) {
331205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3313af31f5e5SChris Mason 		goto fail_tree_roots;
33142b82032cSYan Zheng 	}
33150b86a832SChris Mason 
33168dabb742SStefan Behrens 	/*
3317bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3318bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3319bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
33201a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3321bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
33228dabb742SStefan Behrens 	 */
3323bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3324d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
332505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
33264871c33bSQu Wenruo 		ret = -EIO;
3327a6b0d5c8SChris Mason 		goto fail_tree_roots;
3328a6b0d5c8SChris Mason 	}
3329a6b0d5c8SChris Mason 
3330b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
33314bbcaa64SEric Sandeen 	if (ret)
3332b8522a1eSNikolay Borisov 		goto fail_tree_roots;
33338929ecfaSYan, Zheng 
333475ec1db8SJosef Bacik 	/*
333573651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
333673651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
333773651042SNaohiro Aota 	 * zoned incompat feature flag set.
333873651042SNaohiro Aota 	 */
333973651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
334073651042SNaohiro Aota 	if (ret) {
334173651042SNaohiro Aota 		btrfs_err(fs_info,
33424871c33bSQu Wenruo 			  "zoned: failed to read device zone info: %d", ret);
334373651042SNaohiro Aota 		goto fail_block_groups;
334473651042SNaohiro Aota 	}
334573651042SNaohiro Aota 
334673651042SNaohiro Aota 	/*
334775ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
334875ec1db8SJosef Bacik 	 * check the generation here so we can set the
334975ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
335075ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
335175ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
335275ec1db8SJosef Bacik 	 * even though it was perfectly fine.
335375ec1db8SJosef Bacik 	 */
335475ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
335575ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
335675ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
335775ec1db8SJosef Bacik 
3358cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3359cf90d884SQu Wenruo 	if (ret) {
3360cf90d884SQu Wenruo 		btrfs_err(fs_info,
3361cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3362cf90d884SQu Wenruo 			  ret);
3363cf90d884SQu Wenruo 		goto fail_block_groups;
3364cf90d884SQu Wenruo 	}
336568310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
336668310a5eSIlya Dryomov 	if (ret) {
336705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
336868310a5eSIlya Dryomov 		goto fail_block_groups;
336968310a5eSIlya Dryomov 	}
337068310a5eSIlya Dryomov 
3371733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3372733f4fbbSStefan Behrens 	if (ret) {
337305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3374733f4fbbSStefan Behrens 		goto fail_block_groups;
3375733f4fbbSStefan Behrens 	}
3376733f4fbbSStefan Behrens 
33778dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
33788dabb742SStefan Behrens 	if (ret) {
337905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
33808dabb742SStefan Behrens 		goto fail_block_groups;
33818dabb742SStefan Behrens 	}
33828dabb742SStefan Behrens 
3383b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3384b70f5097SNaohiro Aota 	if (ret) {
3385b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3386b70f5097SNaohiro Aota 			  ret);
3387b70f5097SNaohiro Aota 		goto fail_block_groups;
3388b70f5097SNaohiro Aota 	}
3389b70f5097SNaohiro Aota 
3390c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3391b7c35e81SAnand Jain 	if (ret) {
339205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
339305135f59SDavid Sterba 				ret);
3394b7c35e81SAnand Jain 		goto fail_block_groups;
3395b7c35e81SAnand Jain 	}
3396b7c35e81SAnand Jain 
339796f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
33985ac1d209SJeff Mahoney 	if (ret) {
339905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3400b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
34015ac1d209SJeff Mahoney 	}
34025ac1d209SJeff Mahoney 
3403c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3404c59021f8Sliubo 	if (ret) {
340505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
34062365dd3cSAnand Jain 		goto fail_sysfs;
3407c59021f8Sliubo 	}
3408c59021f8Sliubo 
34095b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
34101b1d1f66SJosef Bacik 	if (ret) {
341105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
34122365dd3cSAnand Jain 		goto fail_sysfs;
34131b1d1f66SJosef Bacik 	}
34144330e183SQu Wenruo 
341516beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
341616beac87SNaohiro Aota 
34175c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
34185c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
341905135f59SDavid Sterba 		btrfs_warn(fs_info,
342052042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
34214871c33bSQu Wenruo 		ret = -EINVAL;
34222365dd3cSAnand Jain 		goto fail_sysfs;
3423292fd7fcSStefan Behrens 	}
34249078a3e1SChris Mason 
342533c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3426a74a4b97SChris Mason 					       "btrfs-cleaner");
34274871c33bSQu Wenruo 	if (IS_ERR(fs_info->cleaner_kthread)) {
34284871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->cleaner_kthread);
34292365dd3cSAnand Jain 		goto fail_sysfs;
34304871c33bSQu Wenruo 	}
3431a74a4b97SChris Mason 
3432a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3433a74a4b97SChris Mason 						   tree_root,
3434a74a4b97SChris Mason 						   "btrfs-transaction");
34354871c33bSQu Wenruo 	if (IS_ERR(fs_info->transaction_kthread)) {
34364871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->transaction_kthread);
34373f157a2fSChris Mason 		goto fail_cleaner;
34384871c33bSQu Wenruo 	}
3439a74a4b97SChris Mason 
3440583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3441c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3442583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3443c289811cSChris Mason 	}
3444c289811cSChris Mason 
3445572d9ab7SDavid Sterba 	/*
344663a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
344763a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
344863a7cb13SDavid Sterba 	 * nodiscard for the same mount.
344963a7cb13SDavid Sterba 	 */
345063a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
345163a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
345263a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
345363a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
345463a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
345563a7cb13SDavid Sterba 				   "auto enabling async discard");
345663a7cb13SDavid Sterba 	}
345763a7cb13SDavid Sterba 
345821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
34590b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
34602ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
34610b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3462cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
346321adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
346421adbd5cSStefan Behrens 		if (ret)
346505135f59SDavid Sterba 			btrfs_warn(fs_info,
346605135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
346705135f59SDavid Sterba 				ret);
346821adbd5cSStefan Behrens 	}
346921adbd5cSStefan Behrens #endif
3470bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3471bcef60f2SArne Jansen 	if (ret)
3472bcef60f2SArne Jansen 		goto fail_trans_kthread;
347321adbd5cSStefan Behrens 
3474fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3475fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3476fd708b81SJosef Bacik 
347796da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
347896da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
34790b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3480e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
348163443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
34824871c33bSQu Wenruo 		if (ret)
348328c16cbbSWang Shilong 			goto fail_qgroup;
3484e556ce2cSYan Zheng 	}
34851a40e23bSZheng Yan 
348656e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
34873140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
34884871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->fs_root);
34894871c33bSQu Wenruo 		btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3490315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3491bcef60f2SArne Jansen 		goto fail_qgroup;
34923140c9a3SDan Carpenter 	}
3493c289811cSChris Mason 
3494bc98a42cSDavid Howells 	if (sb_rdonly(sb))
34958cd29088SBoris Burkov 		goto clear_oneshot;
34962b6ba629SIlya Dryomov 
349744c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
34982b6ba629SIlya Dryomov 	if (ret) {
34996bccf3abSJeff Mahoney 		close_ctree(fs_info);
35002b6ba629SIlya Dryomov 		return ret;
3501e3acc2a6SJosef Bacik 	}
3502b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3503b382a324SJan Schmidt 
350444c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
350544c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
350644c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
350705135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
350870f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
350970f80175SStefan Behrens 		if (ret) {
351005135f59SDavid Sterba 			btrfs_warn(fs_info,
351105135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
35126bccf3abSJeff Mahoney 			close_ctree(fs_info);
351370f80175SStefan Behrens 			return ret;
351470f80175SStefan Behrens 		}
3515f7a81ea4SStefan Behrens 	}
351694846229SBoris Burkov 
3517afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
351847ab2a6cSJosef Bacik 
3519b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3520b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3521b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3522b4be6aefSJosef Bacik 
35238cd29088SBoris Burkov clear_oneshot:
35248cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3525ad2b2c80SAl Viro 	return 0;
352639279cc3SChris Mason 
3527bcef60f2SArne Jansen fail_qgroup:
3528bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
35297c2ca468SChris Mason fail_trans_kthread:
35307c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
35312ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3532faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
35333f157a2fSChris Mason fail_cleaner:
3534a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
35357c2ca468SChris Mason 
35367c2ca468SChris Mason 	/*
35377c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
35387c2ca468SChris Mason 	 * kthreads
35397c2ca468SChris Mason 	 */
35407c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
35417c2ca468SChris Mason 
35422365dd3cSAnand Jain fail_sysfs:
35436618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
35442365dd3cSAnand Jain 
3545b7c35e81SAnand Jain fail_fsdev_sysfs:
3546b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3547b7c35e81SAnand Jain 
35481b1d1f66SJosef Bacik fail_block_groups:
354954067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3550af31f5e5SChris Mason 
3551af31f5e5SChris Mason fail_tree_roots:
35529e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
35539e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
35544273eaffSAnand Jain 	free_root_pointers(fs_info, true);
35552b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3556af31f5e5SChris Mason 
355739279cc3SChris Mason fail_sb_buffer:
35587abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
35595cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
356016cdcec7SMiao Xie fail_alloc:
3561586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3562586e46e2SIlya Dryomov 
35634543df7eSChris Mason 	iput(fs_info->btree_inode);
35647e662854SQinghuang Feng fail:
3565586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
35664871c33bSQu Wenruo 	ASSERT(ret < 0);
35674871c33bSQu Wenruo 	return ret;
3568eb60ceacSChris Mason }
3569663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3570eb60ceacSChris Mason 
3571314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3572f2984462SChris Mason {
3573314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3574314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3575314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3576314b6dd0SJohannes Thumshirn 	struct page *page;
3577442a4f63SStefan Behrens 
3578314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3579314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3580314b6dd0SJohannes Thumshirn 
3581314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3582fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3583314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3584cb3e217bSQu Wenruo 				btrfs_dev_name(device),
3585314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3586314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3587314b6dd0SJohannes Thumshirn 			SetPageError(page);
3588314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3589314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3590314b6dd0SJohannes Thumshirn 		} else {
3591314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3592f2984462SChris Mason 		}
3593314b6dd0SJohannes Thumshirn 
3594314b6dd0SJohannes Thumshirn 		put_page(page);
3595314b6dd0SJohannes Thumshirn 		unlock_page(page);
3596314b6dd0SJohannes Thumshirn 	}
3597314b6dd0SJohannes Thumshirn 
3598314b6dd0SJohannes Thumshirn 	bio_put(bio);
3599f2984462SChris Mason }
3600f2984462SChris Mason 
36018f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3602a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
360329c36d72SAnand Jain {
360429c36d72SAnand Jain 	struct btrfs_super_block *super;
36058f32380dSJohannes Thumshirn 	struct page *page;
360612659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
36078f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
360812659251SNaohiro Aota 	int ret;
360929c36d72SAnand Jain 
361012659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
361112659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
361212659251SNaohiro Aota 	if (ret == -ENOENT)
361312659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
361412659251SNaohiro Aota 	else if (ret)
361512659251SNaohiro Aota 		return ERR_PTR(ret);
361612659251SNaohiro Aota 
3617cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
36188f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
361929c36d72SAnand Jain 
3620a05d3c91SQu Wenruo 	if (drop_cache) {
3621a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3622a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3623a05d3c91SQu Wenruo 
3624a05d3c91SQu Wenruo 		/*
3625a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3626a05d3c91SQu Wenruo 		 * always read from the device.
3627a05d3c91SQu Wenruo 		 */
3628a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3629a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3630a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3631a05d3c91SQu Wenruo 	}
3632a05d3c91SQu Wenruo 
36338f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
36348f32380dSJohannes Thumshirn 	if (IS_ERR(page))
36358f32380dSJohannes Thumshirn 		return ERR_CAST(page);
363629c36d72SAnand Jain 
36378f32380dSJohannes Thumshirn 	super = page_address(page);
363896c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
363996c2e067SAnand Jain 		btrfs_release_disk_super(super);
364096c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
364196c2e067SAnand Jain 	}
364296c2e067SAnand Jain 
364312659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
36448f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
36458f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
364629c36d72SAnand Jain 	}
364729c36d72SAnand Jain 
36488f32380dSJohannes Thumshirn 	return super;
364929c36d72SAnand Jain }
365029c36d72SAnand Jain 
365129c36d72SAnand Jain 
36528f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3653a512bbf8SYan Zheng {
36548f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3655a512bbf8SYan Zheng 	int i;
3656a512bbf8SYan Zheng 	u64 transid = 0;
3657a512bbf8SYan Zheng 
3658a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3659a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3660a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3661a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3662a512bbf8SYan Zheng 	 */
3663a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3664a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
36658f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3666a512bbf8SYan Zheng 			continue;
3667a512bbf8SYan Zheng 
3668a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
36698f32380dSJohannes Thumshirn 			if (latest)
36708f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
36718f32380dSJohannes Thumshirn 
36728f32380dSJohannes Thumshirn 			latest = super;
3673a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3674a512bbf8SYan Zheng 		}
3675a512bbf8SYan Zheng 	}
367692fc03fbSAnand Jain 
36778f32380dSJohannes Thumshirn 	return super;
3678a512bbf8SYan Zheng }
3679a512bbf8SYan Zheng 
36804eedeb75SHisashi Hifumi /*
3681abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3682314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
36834eedeb75SHisashi Hifumi  *
3684abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3685abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3686abbb3b8eSDavid Sterba  * same for write and wait phases.
36874eedeb75SHisashi Hifumi  *
3688314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
36894eedeb75SHisashi Hifumi  */
3690a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3691abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3692a512bbf8SYan Zheng {
3693d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3694314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3695d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3696a512bbf8SYan Zheng 	int i;
3697a512bbf8SYan Zheng 	int errors = 0;
369812659251SNaohiro Aota 	int ret;
369912659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3700a512bbf8SYan Zheng 
3701a512bbf8SYan Zheng 	if (max_mirrors == 0)
3702a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3703a512bbf8SYan Zheng 
3704d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3705d5178578SJohannes Thumshirn 
3706a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3707314b6dd0SJohannes Thumshirn 		struct page *page;
3708314b6dd0SJohannes Thumshirn 		struct bio *bio;
3709314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3710314b6dd0SJohannes Thumshirn 
371112659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
371212659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
371312659251SNaohiro Aota 		if (ret == -ENOENT) {
371412659251SNaohiro Aota 			continue;
371512659251SNaohiro Aota 		} else if (ret < 0) {
371612659251SNaohiro Aota 			btrfs_err(device->fs_info,
371712659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
371812659251SNaohiro Aota 				i);
371912659251SNaohiro Aota 			errors++;
372012659251SNaohiro Aota 			continue;
372112659251SNaohiro Aota 		}
3722935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3723935e5cc9SMiao Xie 		    device->commit_total_bytes)
3724a512bbf8SYan Zheng 			break;
3725a512bbf8SYan Zheng 
372612659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3727a512bbf8SYan Zheng 
3728fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3729fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3730fd08001fSEric Biggers 				    sb->csum);
3731a512bbf8SYan Zheng 
3732314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3733314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3734314b6dd0SJohannes Thumshirn 		if (!page) {
3735fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3736314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3737f14d104dSDavid Sterba 			    bytenr);
3738634554dcSJosef Bacik 			errors++;
3739634554dcSJosef Bacik 			continue;
3740634554dcSJosef Bacik 		}
3741634554dcSJosef Bacik 
3742314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3743314b6dd0SJohannes Thumshirn 		get_page(page);
3744a512bbf8SYan Zheng 
3745314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3746314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3747a512bbf8SYan Zheng 
3748387125fcSChris Mason 		/*
3749314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3750314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3751314b6dd0SJohannes Thumshirn 		 * checking.
3752387125fcSChris Mason 		 */
375307888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
375407888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
375507888c66SChristoph Hellwig 				GFP_NOFS);
3756314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3757314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3758314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3759314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3760314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3761314b6dd0SJohannes Thumshirn 
3762314b6dd0SJohannes Thumshirn 		/*
3763314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3764314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3765314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3766314b6dd0SJohannes Thumshirn 		 */
37671b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3768314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3769314b6dd0SJohannes Thumshirn 
377058ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
377158ff51f1SChristoph Hellwig 		submit_bio(bio);
37728376d9e1SNaohiro Aota 
37738376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
37748376d9e1SNaohiro Aota 			errors++;
3775a512bbf8SYan Zheng 	}
3776a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3777a512bbf8SYan Zheng }
3778a512bbf8SYan Zheng 
3779387125fcSChris Mason /*
3780abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3781abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3782abbb3b8eSDavid Sterba  *
3783314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3784abbb3b8eSDavid Sterba  * date.
3785abbb3b8eSDavid Sterba  */
3786abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3787abbb3b8eSDavid Sterba {
3788abbb3b8eSDavid Sterba 	int i;
3789abbb3b8eSDavid Sterba 	int errors = 0;
3790b6a535faSHoward McLauchlan 	bool primary_failed = false;
379112659251SNaohiro Aota 	int ret;
3792abbb3b8eSDavid Sterba 	u64 bytenr;
3793abbb3b8eSDavid Sterba 
3794abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3795abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3796abbb3b8eSDavid Sterba 
3797abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3798314b6dd0SJohannes Thumshirn 		struct page *page;
3799314b6dd0SJohannes Thumshirn 
380012659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
380112659251SNaohiro Aota 		if (ret == -ENOENT) {
380212659251SNaohiro Aota 			break;
380312659251SNaohiro Aota 		} else if (ret < 0) {
380412659251SNaohiro Aota 			errors++;
380512659251SNaohiro Aota 			if (i == 0)
380612659251SNaohiro Aota 				primary_failed = true;
380712659251SNaohiro Aota 			continue;
380812659251SNaohiro Aota 		}
3809abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3810abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3811abbb3b8eSDavid Sterba 			break;
3812abbb3b8eSDavid Sterba 
3813314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3814314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3815314b6dd0SJohannes Thumshirn 		if (!page) {
3816abbb3b8eSDavid Sterba 			errors++;
3817b6a535faSHoward McLauchlan 			if (i == 0)
3818b6a535faSHoward McLauchlan 				primary_failed = true;
3819abbb3b8eSDavid Sterba 			continue;
3820abbb3b8eSDavid Sterba 		}
3821314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3822314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3823314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3824abbb3b8eSDavid Sterba 			errors++;
3825b6a535faSHoward McLauchlan 			if (i == 0)
3826b6a535faSHoward McLauchlan 				primary_failed = true;
3827b6a535faSHoward McLauchlan 		}
3828abbb3b8eSDavid Sterba 
3829314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3830314b6dd0SJohannes Thumshirn 		put_page(page);
3831abbb3b8eSDavid Sterba 
3832314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3833314b6dd0SJohannes Thumshirn 		put_page(page);
3834abbb3b8eSDavid Sterba 	}
3835abbb3b8eSDavid Sterba 
3836b6a535faSHoward McLauchlan 	/* log error, force error return */
3837b6a535faSHoward McLauchlan 	if (primary_failed) {
3838b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3839b6a535faSHoward McLauchlan 			  device->devid);
3840b6a535faSHoward McLauchlan 		return -1;
3841b6a535faSHoward McLauchlan 	}
3842b6a535faSHoward McLauchlan 
3843abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3844abbb3b8eSDavid Sterba }
3845abbb3b8eSDavid Sterba 
3846abbb3b8eSDavid Sterba /*
3847387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3848387125fcSChris Mason  * for the barrier when it is done
3849387125fcSChris Mason  */
38504246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3851387125fcSChris Mason {
3852f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
3853387125fcSChris Mason 	complete(bio->bi_private);
3854387125fcSChris Mason }
3855387125fcSChris Mason 
3856387125fcSChris Mason /*
38574fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
38584fc6441aSAnand Jain  * done in the waiting counterpart.
3859387125fcSChris Mason  */
38604fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3861387125fcSChris Mason {
3862f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
3863387125fcSChris Mason 
3864bfd3ea94SAnand Jain 	device->last_flush_error = BLK_STS_OK;
3865bfd3ea94SAnand Jain 
3866a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3867a91cf0ffSWang Yugui 	/*
3868a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
3869a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
3870a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
3871a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
3872a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
3873a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
3874a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
3875a91cf0ffSWang Yugui 	 * non-debug builds.
3876a91cf0ffSWang Yugui 	 */
387708e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
38784fc6441aSAnand Jain 		return;
3879a91cf0ffSWang Yugui #endif
3880387125fcSChris Mason 
3881f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
3882f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
3883387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
3884387125fcSChris Mason 	init_completion(&device->flush_wait);
3885387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3886387125fcSChris Mason 
388758ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
388858ff51f1SChristoph Hellwig 	submit_bio(bio);
38891c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
38904fc6441aSAnand Jain }
3891387125fcSChris Mason 
38924fc6441aSAnand Jain /*
38934fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
38941b465784SAnand Jain  * Return true for any error, and false otherwise.
38954fc6441aSAnand Jain  */
38961b465784SAnand Jain static bool wait_dev_flush(struct btrfs_device *device)
38974fc6441aSAnand Jain {
3898f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
38994fc6441aSAnand Jain 
39007e812f20SAnand Jain 	if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
39011b465784SAnand Jain 		return false;
39024fc6441aSAnand Jain 
39032980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
39044fc6441aSAnand Jain 
3905bfd3ea94SAnand Jain 	if (bio->bi_status) {
3906bfd3ea94SAnand Jain 		device->last_flush_error = bio->bi_status;
3907bfd3ea94SAnand Jain 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
39081b465784SAnand Jain 		return true;
3909bfd3ea94SAnand Jain 	}
3910bfd3ea94SAnand Jain 
39111b465784SAnand Jain 	return false;
3912387125fcSChris Mason }
3913387125fcSChris Mason 
3914387125fcSChris Mason /*
3915387125fcSChris Mason  * send an empty flush down to each device in parallel,
3916387125fcSChris Mason  * then wait for them
3917387125fcSChris Mason  */
3918387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3919387125fcSChris Mason {
3920387125fcSChris Mason 	struct list_head *head;
3921387125fcSChris Mason 	struct btrfs_device *dev;
39225af3e8ccSStefan Behrens 	int errors_wait = 0;
3923387125fcSChris Mason 
39241538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3925387125fcSChris Mason 	/* send down all the barriers */
3926387125fcSChris Mason 	head = &info->fs_devices->devices;
39271538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3928e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3929f88ba6a2SHidetoshi Seto 			continue;
3930cea7c8bfSAnand Jain 		if (!dev->bdev)
3931387125fcSChris Mason 			continue;
3932e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3933ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3934387125fcSChris Mason 			continue;
3935387125fcSChris Mason 
39364fc6441aSAnand Jain 		write_dev_flush(dev);
3937387125fcSChris Mason 	}
3938387125fcSChris Mason 
3939387125fcSChris Mason 	/* wait for all the barriers */
39401538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3941e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3942f88ba6a2SHidetoshi Seto 			continue;
3943387125fcSChris Mason 		if (!dev->bdev) {
39445af3e8ccSStefan Behrens 			errors_wait++;
3945387125fcSChris Mason 			continue;
3946387125fcSChris Mason 		}
3947e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3948ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3949387125fcSChris Mason 			continue;
3950387125fcSChris Mason 
39511b465784SAnand Jain 		if (wait_dev_flush(dev))
39525af3e8ccSStefan Behrens 			errors_wait++;
3953387125fcSChris Mason 	}
3954401b41e5SAnand Jain 
3955401b41e5SAnand Jain 	/*
3956de38a206SAnand Jain 	 * Checks last_flush_error of disks in order to determine the device
3957de38a206SAnand Jain 	 * state.
3958401b41e5SAnand Jain 	 */
3959de38a206SAnand Jain 	if (errors_wait && !btrfs_check_rw_degradable(info, NULL))
3960de38a206SAnand Jain 		return -EIO;
3961de38a206SAnand Jain 
3962387125fcSChris Mason 	return 0;
3963387125fcSChris Mason }
3964387125fcSChris Mason 
3965943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3966943c6e99SZhao Lei {
39678789f4feSZhao Lei 	int raid_type;
39688789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3969943c6e99SZhao Lei 
39708789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
39718789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
39728c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39738789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
39748789f4feSZhao Lei 				    tolerated_failures);
3975943c6e99SZhao Lei 
39768789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
39778789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
39788789f4feSZhao Lei 			continue;
397941a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
39808789f4feSZhao Lei 			continue;
39818c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39828789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
39838789f4feSZhao Lei 				    tolerated_failures);
39848789f4feSZhao Lei 	}
3985943c6e99SZhao Lei 
39868789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3987ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
39888789f4feSZhao Lei 		min_tolerated = 0;
39898789f4feSZhao Lei 	}
39908789f4feSZhao Lei 
39918789f4feSZhao Lei 	return min_tolerated;
3992943c6e99SZhao Lei }
3993943c6e99SZhao Lei 
3994eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3995f2984462SChris Mason {
3996e5e9a520SChris Mason 	struct list_head *head;
3997f2984462SChris Mason 	struct btrfs_device *dev;
3998a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3999f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4000f2984462SChris Mason 	int ret;
4001f2984462SChris Mason 	int do_barriers;
4002a236aed1SChris Mason 	int max_errors;
4003a236aed1SChris Mason 	int total_errors = 0;
4004a061fc8dSChris Mason 	u64 flags;
4005f2984462SChris Mason 
40060b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4007fed3b381SLiu Bo 
4008fed3b381SLiu Bo 	/*
4009fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4010fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4011fed3b381SLiu Bo 	 * been consistent on disk.
4012fed3b381SLiu Bo 	 */
4013fed3b381SLiu Bo 	if (max_mirrors == 0)
40140b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4015f2984462SChris Mason 
40160b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4017a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4018e5e9a520SChris Mason 
40190b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
40200b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
40210b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4022387125fcSChris Mason 
40235af3e8ccSStefan Behrens 	if (do_barriers) {
40240b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
40255af3e8ccSStefan Behrens 		if (ret) {
40265af3e8ccSStefan Behrens 			mutex_unlock(
40270b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
40280b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
40295af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
40305af3e8ccSStefan Behrens 			return ret;
40315af3e8ccSStefan Behrens 		}
40325af3e8ccSStefan Behrens 	}
4033387125fcSChris Mason 
40341538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4035dfe25020SChris Mason 		if (!dev->bdev) {
4036dfe25020SChris Mason 			total_errors++;
4037dfe25020SChris Mason 			continue;
4038dfe25020SChris Mason 		}
4039e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4040ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4041dfe25020SChris Mason 			continue;
4042dfe25020SChris Mason 
40432b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4044a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4045a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
40467df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4047935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4048ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4049ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4050a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4051a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4052a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4053a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
40547239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
40557239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4056a512bbf8SYan Zheng 
4057a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4058a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4059f2984462SChris Mason 
406075cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
406175cb857dSQu Wenruo 		if (ret < 0) {
406275cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
406375cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
406475cb857dSQu Wenruo 				"unexpected superblock corruption detected");
406575cb857dSQu Wenruo 			return -EUCLEAN;
406675cb857dSQu Wenruo 		}
406775cb857dSQu Wenruo 
4068abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4069a236aed1SChris Mason 		if (ret)
4070a236aed1SChris Mason 			total_errors++;
4071f2984462SChris Mason 	}
4072a236aed1SChris Mason 	if (total_errors > max_errors) {
40730b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4074d397712bSChris Mason 			  total_errors);
40750b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
407679787eaaSJeff Mahoney 
40779d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
40780b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40790b246afaSJeff Mahoney 				      "%d errors while writing supers",
40800b246afaSJeff Mahoney 				      total_errors);
40819d565ba4SStefan Behrens 		return -EIO;
4082a236aed1SChris Mason 	}
4083f2984462SChris Mason 
4084a512bbf8SYan Zheng 	total_errors = 0;
40851538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4086dfe25020SChris Mason 		if (!dev->bdev)
4087dfe25020SChris Mason 			continue;
4088e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4089ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4090dfe25020SChris Mason 			continue;
4091dfe25020SChris Mason 
4092abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4093a512bbf8SYan Zheng 		if (ret)
40941259ab75SChris Mason 			total_errors++;
4095f2984462SChris Mason 	}
40960b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4097a236aed1SChris Mason 	if (total_errors > max_errors) {
40980b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40990b246afaSJeff Mahoney 				      "%d errors while writing supers",
41000b246afaSJeff Mahoney 				      total_errors);
410179787eaaSJeff Mahoney 		return -EIO;
4102a236aed1SChris Mason 	}
4103f2984462SChris Mason 	return 0;
4104f2984462SChris Mason }
4105f2984462SChris Mason 
4106cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4107cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4108cb517eabSMiao Xie 				  struct btrfs_root *root)
41092619ba1fSChris Mason {
41104785e24fSJosef Bacik 	bool drop_ref = false;
41114785e24fSJosef Bacik 
4112fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4113fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4114fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4115fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
41164785e24fSJosef Bacik 		drop_ref = true;
4117fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
411876dda93cSYan, Zheng 
411984961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4120ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
41211c1ea4f7SLiu Bo 		if (root->reloc_root) {
412200246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
41231c1ea4f7SLiu Bo 			root->reloc_root = NULL;
41241c1ea4f7SLiu Bo 		}
41251c1ea4f7SLiu Bo 	}
41263321719eSLiu Bo 
41274785e24fSJosef Bacik 	if (drop_ref)
412800246528SJosef Bacik 		btrfs_put_root(root);
41292619ba1fSChris Mason }
41302619ba1fSChris Mason 
4131c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4132c146afadSYan Zheng {
4133fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4134fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4135fc7cbcd4SDavid Sterba 	int i = 0;
413665d33fd7SQu Wenruo 	int err = 0;
4137fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4138c146afadSYan Zheng 
4139c146afadSYan Zheng 	while (1) {
4140fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4141fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4142fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4143fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4144fc7cbcd4SDavid Sterba 		if (!ret) {
4145fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4146c146afadSYan Zheng 			break;
414765d33fd7SQu Wenruo 		}
4148fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
414966b4ffd1SJosef Bacik 
4150fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4151fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4152fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4153fc7cbcd4SDavid Sterba 				gang[i] = NULL;
415465d33fd7SQu Wenruo 				continue;
4155c146afadSYan Zheng 			}
4156fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4157fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4158fc7cbcd4SDavid Sterba 		}
4159fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4160fc7cbcd4SDavid Sterba 
4161fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4162fc7cbcd4SDavid Sterba 			if (!gang[i])
4163fc7cbcd4SDavid Sterba 				continue;
4164fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4165fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4166fc7cbcd4SDavid Sterba 			if (err)
41676989627dSJosef Bacik 				goto out;
4168fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4169fc7cbcd4SDavid Sterba 		}
4170fc7cbcd4SDavid Sterba 		root_objectid++;
4171c146afadSYan Zheng 	}
41726989627dSJosef Bacik out:
4173fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4174fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4175fc7cbcd4SDavid Sterba 		if (gang[i])
4176fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
417765d33fd7SQu Wenruo 	}
417865d33fd7SQu Wenruo 	return err;
4179c146afadSYan Zheng }
4180c146afadSYan Zheng 
41816bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4182c146afadSYan Zheng {
41836bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4184c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4185c146afadSYan Zheng 
41860b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41872ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41880b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
41890b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4190c71bf099SYan, Zheng 
4191c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
41920b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41930b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4194c71bf099SYan, Zheng 
41957a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
41963612b495STsutomu Itoh 	if (IS_ERR(trans))
41973612b495STsutomu Itoh 		return PTR_ERR(trans);
41983a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4199c146afadSYan Zheng }
4200c146afadSYan Zheng 
420136c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
420236c86a9eSQu Wenruo {
420336c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
420436c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
420536c86a9eSQu Wenruo 	bool found = false;
420636c86a9eSQu Wenruo 
420736c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
420836c86a9eSQu Wenruo 		return;
420936c86a9eSQu Wenruo 
421036c86a9eSQu Wenruo 	/*
421136c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
421236c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
421336c86a9eSQu Wenruo 	 */
421436c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
421536c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
421636c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
421736c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
421836c86a9eSQu Wenruo 		u64 cur = 0;
421936c86a9eSQu Wenruo 		u64 found_start;
422036c86a9eSQu Wenruo 		u64 found_end;
422136c86a9eSQu Wenruo 
422236c86a9eSQu Wenruo 		found = true;
422336c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
422436c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
422536c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
422636c86a9eSQu Wenruo 			cur = found_end + 1;
422736c86a9eSQu Wenruo 		}
422836c86a9eSQu Wenruo 		btrfs_warn(fs_info,
422936c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
423036c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
423136c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
423236c86a9eSQu Wenruo 
423336c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
423436c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
423536c86a9eSQu Wenruo 		list_del_init(&trans->list);
423636c86a9eSQu Wenruo 
423736c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
423836c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
423936c86a9eSQu Wenruo 	}
424036c86a9eSQu Wenruo 	ASSERT(!found);
424136c86a9eSQu Wenruo }
424236c86a9eSQu Wenruo 
4243b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4244eb60ceacSChris Mason {
4245c146afadSYan Zheng 	int ret;
4246e089f05cSChris Mason 
4247afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
424831e70e52SFilipe Manana 
424931e70e52SFilipe Manana 	/*
42508a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
42518a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
42528a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
42538a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
42548a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
42558a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
42568a1f1e3dSFilipe Manana 	 * return 1.
42578a1f1e3dSFilipe Manana 	 */
42588a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
42598a1f1e3dSFilipe Manana 
42608a1f1e3dSFilipe Manana 	/*
426131e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
426231e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
426331e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
426431e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
426531e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
426631e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
426731e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
426831e70e52SFilipe Manana 	 */
426931e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4270d6fd0ae2SOmar Sandoval 	/*
4271d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4272d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4273d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4274d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4275d6fd0ae2SOmar Sandoval 	 */
4276d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4277a2135011SChris Mason 
42787343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4279d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
42807343dd61SJustin Maggard 
4281803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4282803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4283803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4284803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4285803b2f54SStefan Behrens 
4286837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4287aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4288837d5b6eSIlya Dryomov 
42898dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
42908dabb742SStefan Behrens 
4291aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
42924cb5300bSChris Mason 
42934cb5300bSChris Mason 	/* wait for any defraggers to finish */
42944cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
42954cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
42964cb5300bSChris Mason 
42974cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
429826176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
42994cb5300bSChris Mason 
4300a362bb86SFilipe Manana 	/*
4301a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4302a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4303a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4304a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4305a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4306a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4307a362bb86SFilipe Manana 	 * no one else to run iputs.
4308a362bb86SFilipe Manana 	 *
4309a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4310a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4311a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4312a362bb86SFilipe Manana 	 * through some other means.
4313a362bb86SFilipe Manana 	 *
4314a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4315a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4316a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4317a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4318a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4319a362bb86SFilipe Manana 	 */
4320a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4321a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4322a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4323a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4324a362bb86SFilipe Manana 
432521c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
432657056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4327576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
432821c7e756SMiao Xie 
4329b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4330b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4331b0643e59SDennis Zhou 
4332bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4333e44163e1SJeff Mahoney 		/*
4334d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4335d6fd0ae2SOmar Sandoval 		 * unused block groups.
4336e44163e1SJeff Mahoney 		 */
43370b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4338e44163e1SJeff Mahoney 
4339f0cc2cd7SFilipe Manana 		/*
4340f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4341f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4342f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4343f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4344f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4345f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4346f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4347f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4348f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4349f0cc2cd7SFilipe Manana 		 */
4350f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4351f0cc2cd7SFilipe Manana 
43526bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4353d397712bSChris Mason 		if (ret)
435404892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4355c146afadSYan Zheng 	}
4356ed2ff2cbSChris Mason 
435784961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
43582ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4359acce952bSliubo 
4360e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4361e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
43628929ecfaSYan, Zheng 
4363e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4364afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4365f25784b3SYan Zheng 
43665958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
43675958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
43685958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
43695958253cSQu Wenruo 	}
43705958253cSQu Wenruo 
437104892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4372fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4373bcef60f2SArne Jansen 
4374963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
437504892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4376963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4377b0c68f8bSChris Mason 	}
437831153d81SYan Zheng 
43795deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
43804297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
43815deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
43824297ff84SJosef Bacik 
43836618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4384b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
43855ac1d209SJeff Mahoney 
43861a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
43871a4319ccSLiu Bo 
4388de348ee0SWang Shilong 	/*
4389de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4390de348ee0SWang Shilong 	 * submit after we stopping all workers.
4391de348ee0SWang Shilong 	 */
4392de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
439396192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
439496192499SJosef Bacik 
43950a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
439636c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
43970a31daa4SFilipe Manana 
4398afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
43994273eaffSAnand Jain 	free_root_pointers(fs_info, true);
44008c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
44019ad6b7bcSChris Mason 
44024e19443dSJosef Bacik 	/*
44034e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
44044e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
44054e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
44064e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
44074e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
44084e19443dSJosef Bacik 	 */
44094e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
44104e19443dSJosef Bacik 
441113e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4412d6bfde87SChris Mason 
441321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
44140b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
44152ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
441621adbd5cSStefan Behrens #endif
441721adbd5cSStefan Behrens 
44180b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
441968c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4420eb60ceacSChris Mason }
4421eb60ceacSChris Mason 
44225f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
44235f39d397SChris Mason {
44242f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
44255f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4426b4ce94deSChris Mason 
442706ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
442806ea65a3SJosef Bacik 	/*
442906ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
443052042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
443106ea65a3SJosef Bacik 	 * outside of the sanity tests.
443206ea65a3SJosef Bacik 	 */
4433b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
443406ea65a3SJosef Bacik 		return;
443506ea65a3SJosef Bacik #endif
443649d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
44370b246afaSJeff Mahoney 	if (transid != fs_info->generation)
44385d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
44390b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
4440f18cc978SChristoph Hellwig 	set_extent_buffer_dirty(buf);
44411f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
444269fc6cbbSQu Wenruo 	/*
444385d8a826SJosef Bacik 	 * btrfs_check_leaf() won't check item data if we don't have WRITTEN
444485d8a826SJosef Bacik 	 * set, so this will only validate the basic structure of the items.
444569fc6cbbSQu Wenruo 	 */
444685d8a826SJosef Bacik 	if (btrfs_header_level(buf) == 0 && btrfs_check_leaf(buf)) {
4447a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
44481f21ef0aSFilipe Manana 		ASSERT(0);
44491f21ef0aSFilipe Manana 	}
44501f21ef0aSFilipe Manana #endif
4451eb60ceacSChris Mason }
4452eb60ceacSChris Mason 
44532ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4454b53d3f5dSLiu Bo 					int flush_delayed)
445535b7e476SChris Mason {
4456188de649SChris Mason 	/*
4457188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4458188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4459188de649SChris Mason 	 */
4460e2d84521SMiao Xie 	int ret;
4461d6bfde87SChris Mason 
44626933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4463d6bfde87SChris Mason 		return;
4464d6bfde87SChris Mason 
4465b53d3f5dSLiu Bo 	if (flush_delayed)
44662ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
446716cdcec7SMiao Xie 
4468d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4469d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4470d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4471e2d84521SMiao Xie 	if (ret > 0) {
44720b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
447316cdcec7SMiao Xie 	}
447416cdcec7SMiao Xie }
447516cdcec7SMiao Xie 
44762ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
447716cdcec7SMiao Xie {
44782ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
447935b7e476SChris Mason }
4480b53d3f5dSLiu Bo 
44812ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4482b53d3f5dSLiu Bo {
44832ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4484d6bfde87SChris Mason }
44856b80053dSChris Mason 
44862ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4487acce952bSliubo {
4488fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4489fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4490fe816d0fSNikolay Borisov 
44910b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
44922ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
44930b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4494acce952bSliubo 
44950b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
44960b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4497acce952bSliubo }
4498acce952bSliubo 
4499ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4500ef67963dSJosef Bacik {
4501fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4502fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4503fc7cbcd4SDavid Sterba 	int ret;
4504ef67963dSJosef Bacik 
4505fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4506fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4507fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4508fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4509fc7cbcd4SDavid Sterba 		int i;
4510ef67963dSJosef Bacik 
4511fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4512fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4513fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4514fc7cbcd4SDavid Sterba 
4515fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4516fc7cbcd4SDavid Sterba 			if (!gang[i])
4517ef67963dSJosef Bacik 				continue;
4518fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4519fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4520fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4521ef67963dSJosef Bacik 		}
4522fc7cbcd4SDavid Sterba 		root_objectid++;
4523fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4524ef67963dSJosef Bacik 	}
4525fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4526ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4527ef67963dSJosef Bacik }
4528ef67963dSJosef Bacik 
4529143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4530acce952bSliubo {
4531acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4532acce952bSliubo 
4533199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4534779880efSJosef Bacik 	/*
4535779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4536779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4537779880efSJosef Bacik 	 */
4538199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4539779880efSJosef Bacik 			    root_extent_list)
4540779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4541199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4542199c2a9cSMiao Xie }
4543199c2a9cSMiao Xie 
4544199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4545199c2a9cSMiao Xie {
4546199c2a9cSMiao Xie 	struct btrfs_root *root;
4547199c2a9cSMiao Xie 	struct list_head splice;
4548199c2a9cSMiao Xie 
4549199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4550199c2a9cSMiao Xie 
4551199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4552199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4553199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4554199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4555199c2a9cSMiao Xie 					ordered_root);
45561de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
45571de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4558199c2a9cSMiao Xie 
45592a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4560199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4561199c2a9cSMiao Xie 
45622a85d9caSLiu Bo 		cond_resched();
45632a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4564199c2a9cSMiao Xie 	}
4565199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
456674d5d229SJosef Bacik 
456774d5d229SJosef Bacik 	/*
456874d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
456974d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
457074d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
457174d5d229SJosef Bacik 	 * actually get run and error out properly.
457274d5d229SJosef Bacik 	 */
457374d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4574acce952bSliubo }
4575acce952bSliubo 
457635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
45772ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4578acce952bSliubo {
4579acce952bSliubo 	struct rb_node *node;
4580acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4581acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4582acce952bSliubo 	int ret = 0;
4583acce952bSliubo 
4584acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4585acce952bSliubo 
4586acce952bSliubo 	spin_lock(&delayed_refs->lock);
4587d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4588cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4589b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4590acce952bSliubo 		return ret;
4591acce952bSliubo 	}
4592acce952bSliubo 
45935c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4594d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
45950e0adbcfSJosef Bacik 		struct rb_node *n;
4596e78417d1SJosef Bacik 		bool pin_bytes = false;
4597acce952bSliubo 
4598d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4599d7df2c79SJosef Bacik 				href_node);
46003069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4601b939d1abSJosef Bacik 			continue;
46023069bd26SJosef Bacik 
4603d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4604e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
46050e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
46060e0adbcfSJosef Bacik 				       ref_node);
4607d7df2c79SJosef Bacik 			ref->in_tree = 0;
4608e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
46090e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
46101d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
46111d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4612d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4613d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4614d7df2c79SJosef Bacik 		}
461554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4616e78417d1SJosef Bacik 			pin_bytes = true;
461778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4618fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4619d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4620acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4621e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4622acce952bSliubo 
4623f603bb94SNikolay Borisov 		if (pin_bytes) {
4624f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4625f603bb94SNikolay Borisov 
4626f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4627f603bb94SNikolay Borisov 			BUG_ON(!cache);
4628f603bb94SNikolay Borisov 
4629f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4630f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4631f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4632f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4633f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4634f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4635f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4636f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4637f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4638f603bb94SNikolay Borisov 
4639f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4640f603bb94SNikolay Borisov 
4641f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4642f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4643f603bb94SNikolay Borisov 		}
464431890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4645d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4646acce952bSliubo 		cond_resched();
4647acce952bSliubo 		spin_lock(&delayed_refs->lock);
4648acce952bSliubo 	}
464981f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4650acce952bSliubo 
4651acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4652acce952bSliubo 
4653acce952bSliubo 	return ret;
4654acce952bSliubo }
4655acce952bSliubo 
4656143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4657acce952bSliubo {
4658acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4659acce952bSliubo 	struct list_head splice;
4660acce952bSliubo 
4661acce952bSliubo 	INIT_LIST_HEAD(&splice);
4662acce952bSliubo 
4663eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4664eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4665acce952bSliubo 
4666acce952bSliubo 	while (!list_empty(&splice)) {
4667fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4668eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4669acce952bSliubo 					       delalloc_inodes);
4670fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4671eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4672acce952bSliubo 
4673fe816d0fSNikolay Borisov 		/*
4674fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4675fe816d0fSNikolay Borisov 		 * meanwhile.
4676fe816d0fSNikolay Borisov 		 */
4677fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4678fe816d0fSNikolay Borisov 		if (inode) {
4679597441b3SJosef Bacik 			unsigned int nofs_flag;
4680597441b3SJosef Bacik 
4681597441b3SJosef Bacik 			nofs_flag = memalloc_nofs_save();
4682fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4683597441b3SJosef Bacik 			memalloc_nofs_restore(nofs_flag);
4684fe816d0fSNikolay Borisov 			iput(inode);
4685fe816d0fSNikolay Borisov 		}
4686eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4687acce952bSliubo 	}
4688eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4689eb73c1b7SMiao Xie }
4690eb73c1b7SMiao Xie 
4691eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4692eb73c1b7SMiao Xie {
4693eb73c1b7SMiao Xie 	struct btrfs_root *root;
4694eb73c1b7SMiao Xie 	struct list_head splice;
4695eb73c1b7SMiao Xie 
4696eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4697eb73c1b7SMiao Xie 
4698eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4699eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4700eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4701eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4702eb73c1b7SMiao Xie 					 delalloc_root);
470300246528SJosef Bacik 		root = btrfs_grab_root(root);
4704eb73c1b7SMiao Xie 		BUG_ON(!root);
4705eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4706eb73c1b7SMiao Xie 
4707eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
470800246528SJosef Bacik 		btrfs_put_root(root);
4709eb73c1b7SMiao Xie 
4710eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4711eb73c1b7SMiao Xie 	}
4712eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4713acce952bSliubo }
4714acce952bSliubo 
47152ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4716acce952bSliubo 					struct extent_io_tree *dirty_pages,
4717acce952bSliubo 					int mark)
4718acce952bSliubo {
4719acce952bSliubo 	int ret;
4720acce952bSliubo 	struct extent_buffer *eb;
4721acce952bSliubo 	u64 start = 0;
4722acce952bSliubo 	u64 end;
4723acce952bSliubo 
4724acce952bSliubo 	while (1) {
4725acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4726e6138876SJosef Bacik 					    mark, NULL);
4727acce952bSliubo 		if (ret)
4728acce952bSliubo 			break;
4729acce952bSliubo 
473091166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4731acce952bSliubo 		while (start <= end) {
47320b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
47330b246afaSJeff Mahoney 			start += fs_info->nodesize;
4734fd8b2b61SJosef Bacik 			if (!eb)
4735acce952bSliubo 				continue;
4736acce952bSliubo 
4737c4e54a65SJosef Bacik 			btrfs_tree_lock(eb);
4738c4e54a65SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4739190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(NULL, eb);
4740c4e54a65SJosef Bacik 			btrfs_tree_unlock(eb);
4741c4e54a65SJosef Bacik 
4742fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4743acce952bSliubo 		}
4744acce952bSliubo 	}
4745acce952bSliubo 
4746acce952bSliubo 	return ret;
4747acce952bSliubo }
4748acce952bSliubo 
47492ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4750fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4751acce952bSliubo {
4752acce952bSliubo 	u64 start;
4753acce952bSliubo 	u64 end;
4754acce952bSliubo 	int ret;
4755acce952bSliubo 
4756acce952bSliubo 	while (1) {
47570e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
47580e6ec385SFilipe Manana 
4759fcd5e742SLu Fengqi 		/*
4760fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4761fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4762fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4763fcd5e742SLu Fengqi 		 * the same extent range.
4764fcd5e742SLu Fengqi 		 */
4765fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4766acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
47670e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4768fcd5e742SLu Fengqi 		if (ret) {
4769fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4770acce952bSliubo 			break;
4771fcd5e742SLu Fengqi 		}
4772acce952bSliubo 
47730e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
47740e6ec385SFilipe Manana 		free_extent_state(cached_state);
47752ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4776fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4777acce952bSliubo 		cond_resched();
4778acce952bSliubo 	}
4779acce952bSliubo 
4780acce952bSliubo 	return 0;
4781acce952bSliubo }
4782acce952bSliubo 
478332da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4784c79a1751SLiu Bo {
4785c79a1751SLiu Bo 	struct inode *inode;
4786c79a1751SLiu Bo 
4787c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4788c79a1751SLiu Bo 	if (inode) {
4789597441b3SJosef Bacik 		unsigned int nofs_flag;
4790597441b3SJosef Bacik 
4791597441b3SJosef Bacik 		nofs_flag = memalloc_nofs_save();
4792c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4793597441b3SJosef Bacik 		memalloc_nofs_restore(nofs_flag);
4794597441b3SJosef Bacik 
4795c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4796c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4797c79a1751SLiu Bo 		iput(inode);
4798c79a1751SLiu Bo 	}
4799bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4800c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4801c79a1751SLiu Bo }
4802c79a1751SLiu Bo 
4803c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
48042ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4805c79a1751SLiu Bo {
480632da5386SDavid Sterba 	struct btrfs_block_group *cache;
4807c79a1751SLiu Bo 
4808c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4809c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4810c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
481132da5386SDavid Sterba 					 struct btrfs_block_group,
4812c79a1751SLiu Bo 					 dirty_list);
4813c79a1751SLiu Bo 
4814c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4815c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4816c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4817c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4818c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4819c79a1751SLiu Bo 		}
4820c79a1751SLiu Bo 
4821c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4822c79a1751SLiu Bo 		spin_lock(&cache->lock);
4823c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4824c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4825c79a1751SLiu Bo 
4826c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4827c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4828ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4829c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4830c79a1751SLiu Bo 	}
4831c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4832c79a1751SLiu Bo 
483345ae2c18SNikolay Borisov 	/*
483445ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
483545ae2c18SNikolay Borisov 	 * to use it without any locking
483645ae2c18SNikolay Borisov 	 */
4837c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4838c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
483932da5386SDavid Sterba 					 struct btrfs_block_group,
4840c79a1751SLiu Bo 					 io_list);
4841c79a1751SLiu Bo 
4842c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4843c79a1751SLiu Bo 		spin_lock(&cache->lock);
4844c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4845c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4846c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4847c79a1751SLiu Bo 	}
4848c79a1751SLiu Bo }
4849c79a1751SLiu Bo 
485049b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
48512ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
485249b25e05SJeff Mahoney {
4853bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4854bbbf7243SNikolay Borisov 
48552ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4856c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4857c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4858c79a1751SLiu Bo 
4859bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4860bbbf7243SNikolay Borisov 				 post_commit_list) {
4861bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4862bbbf7243SNikolay Borisov 	}
4863bbbf7243SNikolay Borisov 
48642ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
486549b25e05SJeff Mahoney 
48664a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
48670b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
486849b25e05SJeff Mahoney 
48694a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
48700b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
487149b25e05SJeff Mahoney 
4872ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
487367cde344SMiao Xie 
48742ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
487549b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4876fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
487749b25e05SJeff Mahoney 
48784a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
48794a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
488049b25e05SJeff Mahoney }
488149b25e05SJeff Mahoney 
48822ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4883acce952bSliubo {
4884acce952bSliubo 	struct btrfs_transaction *t;
4885acce952bSliubo 
48860b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4887acce952bSliubo 
48880b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
48890b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
48900b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4891724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4892724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
48939b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
48940b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
48952ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4896724e2315SJosef Bacik 			btrfs_put_transaction(t);
48970b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4898724e2315SJosef Bacik 			continue;
4899724e2315SJosef Bacik 		}
49000b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4901724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
49020b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4903724e2315SJosef Bacik 			/*
4904724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4905724e2315SJosef Bacik 			 * handle open currently for this transaction.
4906724e2315SJosef Bacik 			 */
4907724e2315SJosef Bacik 			wait_event(t->writer_wait,
4908724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4909724e2315SJosef Bacik 		} else {
49100b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4911724e2315SJosef Bacik 		}
49122ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4913724e2315SJosef Bacik 
49140b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
49150b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
49160b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4917724e2315SJosef Bacik 		list_del_init(&t->list);
49180b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4919a4abeea4SJosef Bacik 
4920724e2315SJosef Bacik 		btrfs_put_transaction(t);
49212e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
49220b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4923724e2315SJosef Bacik 	}
49240b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
49250b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4926ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4927ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
49280b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4929ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
49300b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4931acce952bSliubo 
4932acce952bSliubo 	return 0;
4933acce952bSliubo }
4934ec7d6dfdSNikolay Borisov 
4935453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4936ec7d6dfdSNikolay Borisov {
4937ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
4938ec7d6dfdSNikolay Borisov 	int ret;
4939ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
4940ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
4941ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
4942ec7d6dfdSNikolay Borisov 	int slot;
4943ec7d6dfdSNikolay Borisov 
4944ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
4945ec7d6dfdSNikolay Borisov 	if (!path)
4946ec7d6dfdSNikolay Borisov 		return -ENOMEM;
4947ec7d6dfdSNikolay Borisov 
4948ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4949ec7d6dfdSNikolay Borisov 	search_key.type = -1;
4950ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
4951ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4952ec7d6dfdSNikolay Borisov 	if (ret < 0)
4953ec7d6dfdSNikolay Borisov 		goto error;
4954ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
4955ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
4956ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
4957ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
4958ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
495923125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
496023125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
4961ec7d6dfdSNikolay Borisov 	} else {
496223125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4963ec7d6dfdSNikolay Borisov 	}
4964ec7d6dfdSNikolay Borisov 	ret = 0;
4965ec7d6dfdSNikolay Borisov error:
4966ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
4967ec7d6dfdSNikolay Borisov 	return ret;
4968ec7d6dfdSNikolay Borisov }
4969ec7d6dfdSNikolay Borisov 
4970543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4971ec7d6dfdSNikolay Borisov {
4972ec7d6dfdSNikolay Borisov 	int ret;
4973ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
4974ec7d6dfdSNikolay Borisov 
49756b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4976ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
4977ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
4978ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
4979ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
4980ec7d6dfdSNikolay Borisov 		goto out;
4981ec7d6dfdSNikolay Borisov 	}
4982ec7d6dfdSNikolay Borisov 
498323125104SNikolay Borisov 	*objectid = root->free_objectid++;
4984ec7d6dfdSNikolay Borisov 	ret = 0;
4985ec7d6dfdSNikolay Borisov out:
4986ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
4987ec7d6dfdSNikolay Borisov 	return ret;
4988ec7d6dfdSNikolay Borisov }
4989