xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 0b548539)
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 
99e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; 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  */
1131259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
114b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
115b9fab919SChris Mason 				 int atomic)
1161259ab75SChris Mason {
1172ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
1181259ab75SChris Mason 	int ret;
1191259ab75SChris Mason 
1201259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
1211259ab75SChris Mason 		return 0;
1221259ab75SChris Mason 
123b9fab919SChris Mason 	if (atomic)
124b9fab919SChris Mason 		return -EAGAIN;
125b9fab919SChris Mason 
126570eb97bSJosef Bacik 	lock_extent(io_tree, eb->start, eb->start + eb->len - 1, &cached_state);
1270b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
1281259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
1291259ab75SChris Mason 		ret = 0;
1301259ab75SChris Mason 		goto out;
1311259ab75SChris Mason 	}
13294647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
1338f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1348f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
13529549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1361259ab75SChris Mason 	ret = 1;
1370b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
13833958dc6SChris Mason out:
139570eb97bSJosef Bacik 	unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
140e43bbe5eSDavid Sterba 		      &cached_state);
1411259ab75SChris Mason 	return ret;
1421259ab75SChris Mason }
1431259ab75SChris Mason 
144e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
145e7e16f48SJohannes Thumshirn {
146e7e16f48SJohannes Thumshirn 	switch (csum_type) {
147e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1483951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1493831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
150352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
151e7e16f48SJohannes Thumshirn 		return true;
152e7e16f48SJohannes Thumshirn 	default:
153e7e16f48SJohannes Thumshirn 		return false;
154e7e16f48SJohannes Thumshirn 	}
155e7e16f48SJohannes Thumshirn }
156e7e16f48SJohannes Thumshirn 
157d352ac68SChris Mason /*
1581104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1591104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1601104a885SDavid Sterba  */
1613d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1623d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1631104a885SDavid Sterba {
16451bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
165d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
166d5178578SJohannes Thumshirn 
167d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1681104a885SDavid Sterba 
1691104a885SDavid Sterba 	/*
1701104a885SDavid Sterba 	 * The super_block structure does not span the whole
17151bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
17251bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1731104a885SDavid Sterba 	 */
1743d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
175fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1761104a885SDavid Sterba 
17755fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
178e7e16f48SJohannes Thumshirn 		return 1;
1791104a885SDavid Sterba 
180e7e16f48SJohannes Thumshirn 	return 0;
1811104a885SDavid Sterba }
1821104a885SDavid Sterba 
183e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
184ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
185581c1760SQu Wenruo {
186e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
187581c1760SQu Wenruo 	int found_level;
188581c1760SQu Wenruo 	struct btrfs_key found_key;
189581c1760SQu Wenruo 	int ret;
190581c1760SQu Wenruo 
191581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
192581c1760SQu Wenruo 	if (found_level != level) {
19363489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
19463489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
195581c1760SQu Wenruo 		btrfs_err(fs_info,
196581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
197581c1760SQu Wenruo 			  eb->start, level, found_level);
198581c1760SQu Wenruo 		return -EIO;
199581c1760SQu Wenruo 	}
200581c1760SQu Wenruo 
201581c1760SQu Wenruo 	if (!first_key)
202581c1760SQu Wenruo 		return 0;
203581c1760SQu Wenruo 
2045d41be6fSQu Wenruo 	/*
2055d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
2065d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
2075d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
2085d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
2095d41be6fSQu Wenruo 	 */
2105d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
2115d41be6fSQu Wenruo 		return 0;
21262fdaa52SQu Wenruo 
21362fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
21462fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
21562fdaa52SQu Wenruo 		btrfs_err(fs_info,
21662fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
21762fdaa52SQu Wenruo 			  eb->start);
21862fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
21962fdaa52SQu Wenruo 		return -EUCLEAN;
22062fdaa52SQu Wenruo 	}
22162fdaa52SQu Wenruo 
222581c1760SQu Wenruo 	if (found_level)
223581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
224581c1760SQu Wenruo 	else
225581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
226581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
227581c1760SQu Wenruo 
228581c1760SQu Wenruo 	if (ret) {
22963489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
23063489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
231581c1760SQu Wenruo 		btrfs_err(fs_info,
232ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
233ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
234ff76a864SLiu Bo 			  first_key->type, first_key->offset,
235ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
236ff76a864SLiu Bo 			  found_key.offset);
237581c1760SQu Wenruo 	}
238581c1760SQu Wenruo 	return ret;
239581c1760SQu Wenruo }
240581c1760SQu Wenruo 
241bacf60e5SChristoph Hellwig static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
242bacf60e5SChristoph Hellwig 				      int mirror_num)
243bacf60e5SChristoph Hellwig {
244bacf60e5SChristoph Hellwig 	struct btrfs_fs_info *fs_info = eb->fs_info;
245bacf60e5SChristoph Hellwig 	u64 start = eb->start;
246bacf60e5SChristoph Hellwig 	int i, num_pages = num_extent_pages(eb);
247bacf60e5SChristoph Hellwig 	int ret = 0;
248bacf60e5SChristoph Hellwig 
249bacf60e5SChristoph Hellwig 	if (sb_rdonly(fs_info->sb))
250bacf60e5SChristoph Hellwig 		return -EROFS;
251bacf60e5SChristoph Hellwig 
252bacf60e5SChristoph Hellwig 	for (i = 0; i < num_pages; i++) {
253bacf60e5SChristoph Hellwig 		struct page *p = eb->pages[i];
254bacf60e5SChristoph Hellwig 
255bacf60e5SChristoph Hellwig 		ret = btrfs_repair_io_failure(fs_info, 0, start, PAGE_SIZE,
256bacf60e5SChristoph Hellwig 				start, p, start - page_offset(p), mirror_num);
257bacf60e5SChristoph Hellwig 		if (ret)
258bacf60e5SChristoph Hellwig 			break;
259bacf60e5SChristoph Hellwig 		start += PAGE_SIZE;
260bacf60e5SChristoph Hellwig 	}
261bacf60e5SChristoph Hellwig 
262bacf60e5SChristoph Hellwig 	return ret;
263bacf60e5SChristoph Hellwig }
264bacf60e5SChristoph Hellwig 
2651104a885SDavid Sterba /*
266d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
267d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
268581c1760SQu Wenruo  *
269789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see the comments of the
270789d6a3aSQu Wenruo  *			structure for details.
271d352ac68SChris Mason  */
2726a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
273789d6a3aSQu Wenruo 			     struct btrfs_tree_parent_check *check)
274f188591eSChris Mason {
2755ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
276ea466794SJosef Bacik 	int failed = 0;
277f188591eSChris Mason 	int ret;
278f188591eSChris Mason 	int num_copies = 0;
279f188591eSChris Mason 	int mirror_num = 0;
280ea466794SJosef Bacik 	int failed_mirror = 0;
281f188591eSChris Mason 
282789d6a3aSQu Wenruo 	ASSERT(check);
283789d6a3aSQu Wenruo 
284f188591eSChris Mason 	while (1) {
285f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
286947a6299SQu Wenruo 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
287947a6299SQu Wenruo 		if (!ret)
288581c1760SQu Wenruo 			break;
289d397712bSChris Mason 
2900b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
291f188591eSChris Mason 					      eb->start, eb->len);
2924235298eSChris Mason 		if (num_copies == 1)
293ea466794SJosef Bacik 			break;
2944235298eSChris Mason 
2955cf1ab56SJosef Bacik 		if (!failed_mirror) {
2965cf1ab56SJosef Bacik 			failed = 1;
2975cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
2985cf1ab56SJosef Bacik 		}
2995cf1ab56SJosef Bacik 
300f188591eSChris Mason 		mirror_num++;
301ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
302ea466794SJosef Bacik 			mirror_num++;
303ea466794SJosef Bacik 
3044235298eSChris Mason 		if (mirror_num > num_copies)
305ea466794SJosef Bacik 			break;
306f188591eSChris Mason 	}
307ea466794SJosef Bacik 
308c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
30920a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
310ea466794SJosef Bacik 
311ea466794SJosef Bacik 	return ret;
312f188591eSChris Mason }
31319c00ddcSChris Mason 
314eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
315eca0f6f6SQu Wenruo {
316eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
317eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
318eca0f6f6SQu Wenruo 	int ret;
319eca0f6f6SQu Wenruo 
320eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
321eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
322eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
323eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
324eca0f6f6SQu Wenruo 
325eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
326eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
327eca0f6f6SQu Wenruo 	else
328eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
329eca0f6f6SQu Wenruo 
3303777369fSQu Wenruo 	if (ret < 0)
3313777369fSQu Wenruo 		goto error;
3323777369fSQu Wenruo 
3333777369fSQu Wenruo 	/*
3343777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
3353777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
3363777369fSQu Wenruo 	 */
3373777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
3383777369fSQu Wenruo 		ret = -EUCLEAN;
339eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
3403777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
3413777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
3423777369fSQu Wenruo 			  fs_info->last_trans_committed);
3433777369fSQu Wenruo 		goto error;
344eca0f6f6SQu Wenruo 	}
345eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
346eca0f6f6SQu Wenruo 
347eca0f6f6SQu Wenruo 	return 0;
3483777369fSQu Wenruo 
3493777369fSQu Wenruo error:
3503777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
3513777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
3523777369fSQu Wenruo 		  eb->start);
35316199ad9SFilipe Manana 	/*
35416199ad9SFilipe Manana 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
35516199ad9SFilipe Manana 	 * a transaction in case there's a bad log tree extent buffer, we just
35616199ad9SFilipe Manana 	 * fallback to a transaction commit. Still we want to know when there is
35716199ad9SFilipe Manana 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
35816199ad9SFilipe Manana 	 */
35916199ad9SFilipe Manana 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
36016199ad9SFilipe Manana 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
3613777369fSQu Wenruo 	return ret;
362eca0f6f6SQu Wenruo }
363eca0f6f6SQu Wenruo 
364eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
365eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
366eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
367eca0f6f6SQu Wenruo {
368eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
369eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
370eca0f6f6SQu Wenruo 	u64 cur;
371eca0f6f6SQu Wenruo 	int ret = 0;
372eca0f6f6SQu Wenruo 
373eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
374eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
375eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
376eca0f6f6SQu Wenruo 		bool uptodate;
377eca0f6f6SQu Wenruo 
378eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
379eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
380eca0f6f6SQu Wenruo 						       fs_info->nodesize);
381eca0f6f6SQu Wenruo 
38201cd3909SDavid Sterba 		/* A dirty eb shouldn't disappear from buffer_radix */
383eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
384eca0f6f6SQu Wenruo 			return -EUCLEAN;
385eca0f6f6SQu Wenruo 
386eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
387eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
388eca0f6f6SQu Wenruo 			return -EUCLEAN;
389eca0f6f6SQu Wenruo 		}
390eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
391eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
392eca0f6f6SQu Wenruo 			return -EUCLEAN;
393eca0f6f6SQu Wenruo 		}
394eca0f6f6SQu Wenruo 
395eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
396eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
397eca0f6f6SQu Wenruo 		if (ret < 0)
398eca0f6f6SQu Wenruo 			return ret;
399eca0f6f6SQu Wenruo 	}
400eca0f6f6SQu Wenruo 	return ret;
401eca0f6f6SQu Wenruo }
402eca0f6f6SQu Wenruo 
403d352ac68SChris Mason /*
404ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
405ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
406ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
407d352ac68SChris Mason  */
408ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
40919c00ddcSChris Mason {
410ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
4114eee4fa4SMiao Xie 	u64 start = page_offset(page);
41219c00ddcSChris Mason 	u64 found_start;
41319c00ddcSChris Mason 	struct extent_buffer *eb;
414eca0f6f6SQu Wenruo 
415fbca46ebSQu Wenruo 	if (fs_info->nodesize < PAGE_SIZE)
416eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
417f188591eSChris Mason 
4184f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4194f2de97aSJosef Bacik 	if (page != eb->pages[0])
4204f2de97aSJosef Bacik 		return 0;
4210f805531SAlex Lyakas 
42219c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
423d3575156SNaohiro Aota 
424d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
425d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
426d3575156SNaohiro Aota 		return 0;
427d3575156SNaohiro Aota 	}
428d3575156SNaohiro Aota 
4290f805531SAlex Lyakas 	/*
4300f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4310f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4320f805531SAlex Lyakas 	 */
4330f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4340f805531SAlex Lyakas 		return -EUCLEAN;
4350f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4360f805531SAlex Lyakas 		return -EUCLEAN;
4370f805531SAlex Lyakas 
438eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
43919c00ddcSChris Mason }
44019c00ddcSChris Mason 
441542e300eSChristoph Hellwig blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)
442deb6216fSChristoph Hellwig {
443542e300eSChristoph Hellwig 	struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
444542e300eSChristoph Hellwig 	struct bvec_iter iter;
445542e300eSChristoph Hellwig 	struct bio_vec bv;
446deb6216fSChristoph Hellwig 	int ret = 0;
447deb6216fSChristoph Hellwig 
448542e300eSChristoph Hellwig 	bio_for_each_segment(bv, &bbio->bio, iter) {
449542e300eSChristoph Hellwig 		ret = csum_dirty_buffer(fs_info, &bv);
450deb6216fSChristoph Hellwig 		if (ret)
451deb6216fSChristoph Hellwig 			break;
452deb6216fSChristoph Hellwig 	}
453deb6216fSChristoph Hellwig 
454deb6216fSChristoph Hellwig 	return errno_to_blk_status(ret);
455deb6216fSChristoph Hellwig }
456deb6216fSChristoph Hellwig 
457b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4582b82032cSYan Zheng {
459b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
460944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
46144880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
462944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
4632b82032cSYan Zheng 
4649a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
4659a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
4667239ff4bSNikolay Borisov 	/*
467944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
468944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
469944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
4707239ff4bSNikolay Borisov 	 */
471944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
4727239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
4737239ff4bSNikolay Borisov 	else
4747239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
4757239ff4bSNikolay Borisov 
476944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
477944d3f9fSNikolay Borisov 		return 0;
478944d3f9fSNikolay Borisov 
479944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
480944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
481944d3f9fSNikolay Borisov 			return 0;
482944d3f9fSNikolay Borisov 
483944d3f9fSNikolay Borisov 	return 1;
4842b82032cSYan Zheng }
4852b82032cSYan Zheng 
48677bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
487947a6299SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb,
488947a6299SQu Wenruo 				  struct btrfs_tree_parent_check *check)
489ce9adaa5SChris Mason {
49077bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
491ce9adaa5SChris Mason 	u64 found_start;
49277bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
49377bf40a2SQu Wenruo 	u8 found_level;
4942996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
495dfd29eedSDavid Sterba 	const u8 *header_csum;
49677bf40a2SQu Wenruo 	int ret = 0;
497ea466794SJosef Bacik 
498947a6299SQu Wenruo 	ASSERT(check);
499947a6299SQu Wenruo 
500ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
501727011e0SChris Mason 	if (found_start != eb->start) {
5028f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
5038f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
5048f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
505f188591eSChris Mason 		ret = -EIO;
50677bf40a2SQu Wenruo 		goto out;
507ce9adaa5SChris Mason 	}
508b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
5098f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
5108f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
5111259ab75SChris Mason 		ret = -EIO;
51277bf40a2SQu Wenruo 		goto out;
5131259ab75SChris Mason 	}
514ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5151c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
5168f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
5178f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
5188f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
5191c24c3ceSJosef Bacik 		ret = -EIO;
52077bf40a2SQu Wenruo 		goto out;
5211c24c3ceSJosef Bacik 	}
522ce9adaa5SChris Mason 
523c67b3892SDavid Sterba 	csum_tree_block(eb, result);
524dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
525dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
526a826d6dcSJosef Bacik 
527dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
5282996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
5298f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5308f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
531dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
53235be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
53335be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5342996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
53577bf40a2SQu Wenruo 		goto out;
5362996e1f8SJohannes Thumshirn 	}
5372996e1f8SJohannes Thumshirn 
538947a6299SQu Wenruo 	if (found_level != check->level) {
53977177ed1SQu Wenruo 		btrfs_err(fs_info,
54077177ed1SQu Wenruo 		"level verify failed on logical %llu mirror %u wanted %u found %u",
54177177ed1SQu Wenruo 			  eb->start, eb->read_mirror, check->level, found_level);
542947a6299SQu Wenruo 		ret = -EIO;
543947a6299SQu Wenruo 		goto out;
544947a6299SQu Wenruo 	}
545947a6299SQu Wenruo 	if (unlikely(check->transid &&
546947a6299SQu Wenruo 		     btrfs_header_generation(eb) != check->transid)) {
547947a6299SQu Wenruo 		btrfs_err_rl(eb->fs_info,
548947a6299SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
549947a6299SQu Wenruo 				eb->start, eb->read_mirror, check->transid,
550947a6299SQu Wenruo 				btrfs_header_generation(eb));
551947a6299SQu Wenruo 		ret = -EIO;
552947a6299SQu Wenruo 		goto out;
553947a6299SQu Wenruo 	}
554947a6299SQu Wenruo 	if (check->has_first_key) {
555947a6299SQu Wenruo 		struct btrfs_key *expect_key = &check->first_key;
556947a6299SQu Wenruo 		struct btrfs_key found_key;
557947a6299SQu Wenruo 
558947a6299SQu Wenruo 		if (found_level)
559947a6299SQu Wenruo 			btrfs_node_key_to_cpu(eb, &found_key, 0);
560947a6299SQu Wenruo 		else
561947a6299SQu Wenruo 			btrfs_item_key_to_cpu(eb, &found_key, 0);
562947a6299SQu Wenruo 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
563947a6299SQu Wenruo 			btrfs_err(fs_info,
564947a6299SQu Wenruo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
565947a6299SQu Wenruo 				  eb->start, check->transid,
566947a6299SQu Wenruo 				  expect_key->objectid,
567947a6299SQu Wenruo 				  expect_key->type, expect_key->offset,
568947a6299SQu Wenruo 				  found_key.objectid, found_key.type,
569947a6299SQu Wenruo 				  found_key.offset);
570947a6299SQu Wenruo 			ret = -EUCLEAN;
571947a6299SQu Wenruo 			goto out;
572947a6299SQu Wenruo 		}
573947a6299SQu Wenruo 	}
574947a6299SQu Wenruo 	if (check->owner_root) {
575947a6299SQu Wenruo 		ret = btrfs_check_eb_owner(eb, check->owner_root);
576947a6299SQu Wenruo 		if (ret < 0)
577947a6299SQu Wenruo 			goto out;
578947a6299SQu Wenruo 	}
579947a6299SQu Wenruo 
580a826d6dcSJosef Bacik 	/*
581a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
582a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
583a826d6dcSJosef Bacik 	 * return -EIO.
584a826d6dcSJosef Bacik 	 */
5851c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
586a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
587a826d6dcSJosef Bacik 		ret = -EIO;
588a826d6dcSJosef Bacik 	}
589ce9adaa5SChris Mason 
590813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
591053ab70fSLiu Bo 		ret = -EIO;
592053ab70fSLiu Bo 
5930b32f4bbSJosef Bacik 	if (!ret)
5940b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
59575391f0dSQu Wenruo 	else
59675391f0dSQu Wenruo 		btrfs_err(fs_info,
5978f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
5988f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
59977bf40a2SQu Wenruo out:
60077bf40a2SQu Wenruo 	return ret;
60177bf40a2SQu Wenruo }
60277bf40a2SQu Wenruo 
603371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
604947a6299SQu Wenruo 				   int mirror, struct btrfs_tree_parent_check *check)
605371cdc07SQu Wenruo {
606371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
607371cdc07SQu Wenruo 	struct extent_buffer *eb;
608371cdc07SQu Wenruo 	bool reads_done;
609371cdc07SQu Wenruo 	int ret = 0;
610371cdc07SQu Wenruo 
611947a6299SQu Wenruo 	ASSERT(check);
612947a6299SQu Wenruo 
613371cdc07SQu Wenruo 	/*
614371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
615371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
616371cdc07SQu Wenruo 	 */
617371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
618371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
619371cdc07SQu Wenruo 
620371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
621371cdc07SQu Wenruo 	/*
622371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
623371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
624371cdc07SQu Wenruo 	 */
625371cdc07SQu Wenruo 	ASSERT(eb);
626371cdc07SQu Wenruo 
627371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
628371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
629371cdc07SQu Wenruo 	ASSERT(reads_done);
630371cdc07SQu Wenruo 
631371cdc07SQu Wenruo 	eb->read_mirror = mirror;
632371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
633371cdc07SQu Wenruo 		ret = -EIO;
634371cdc07SQu Wenruo 		goto err;
635371cdc07SQu Wenruo 	}
636947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, check);
637371cdc07SQu Wenruo 	if (ret < 0)
638371cdc07SQu Wenruo 		goto err;
639371cdc07SQu Wenruo 
640371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
641371cdc07SQu Wenruo 
642371cdc07SQu Wenruo 	free_extent_buffer(eb);
643371cdc07SQu Wenruo 	return ret;
644371cdc07SQu Wenruo err:
645371cdc07SQu Wenruo 	/*
646371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
647371cdc07SQu Wenruo 	 * make sure it has something to decrement.
648371cdc07SQu Wenruo 	 */
649371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
650371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
651371cdc07SQu Wenruo 	free_extent_buffer(eb);
652371cdc07SQu Wenruo 	return ret;
653371cdc07SQu Wenruo }
654371cdc07SQu Wenruo 
655c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
65677bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
65777bf40a2SQu Wenruo 				   int mirror)
65877bf40a2SQu Wenruo {
65977bf40a2SQu Wenruo 	struct extent_buffer *eb;
66077bf40a2SQu Wenruo 	int ret = 0;
66177bf40a2SQu Wenruo 	int reads_done;
66277bf40a2SQu Wenruo 
66377bf40a2SQu Wenruo 	ASSERT(page->private);
664371cdc07SQu Wenruo 
665fbca46ebSQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
666947a6299SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror,
667947a6299SQu Wenruo 					       &bbio->parent_check);
668371cdc07SQu Wenruo 
66977bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
67077bf40a2SQu Wenruo 
67177bf40a2SQu Wenruo 	/*
67277bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
67377bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
67477bf40a2SQu Wenruo 	 */
67577bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
67677bf40a2SQu Wenruo 
67777bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
67877bf40a2SQu Wenruo 	if (!reads_done)
67977bf40a2SQu Wenruo 		goto err;
68077bf40a2SQu Wenruo 
68177bf40a2SQu Wenruo 	eb->read_mirror = mirror;
68277bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
68377bf40a2SQu Wenruo 		ret = -EIO;
68477bf40a2SQu Wenruo 		goto err;
68577bf40a2SQu Wenruo 	}
686947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, &bbio->parent_check);
687ce9adaa5SChris Mason err:
68853b381b3SDavid Woodhouse 	if (ret) {
68953b381b3SDavid Woodhouse 		/*
69053b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
69153b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
69253b381b3SDavid Woodhouse 		 * to decrement
69353b381b3SDavid Woodhouse 		 */
69453b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6950b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
69653b381b3SDavid Woodhouse 	}
6970b32f4bbSJosef Bacik 	free_extent_buffer(eb);
69877bf40a2SQu Wenruo 
699f188591eSChris Mason 	return ret;
700ce9adaa5SChris Mason }
701ce9adaa5SChris Mason 
7023dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
7038958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
7048958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
705784b4e29SChris Mason {
706784b4e29SChris Mason 	/*
707784b4e29SChris Mason 	 * we can't safely write a btree page from here,
708784b4e29SChris Mason 	 * we haven't done the locking hook
709784b4e29SChris Mason 	 */
7108958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
711784b4e29SChris Mason 		return -EAGAIN;
712784b4e29SChris Mason 	/*
713784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
714784b4e29SChris Mason 	 * We must have no buffers or drop them.
715784b4e29SChris Mason 	 */
7168958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
7178958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
718784b4e29SChris Mason 		return -EAGAIN;
71954184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
720784b4e29SChris Mason }
7218958b551SMatthew Wilcox (Oracle) #else
7228958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
7233dd1462eSJan Beulich #endif
724784b4e29SChris Mason 
7250da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
7260da5468fSChris Mason 			    struct writeback_control *wbc)
7270da5468fSChris Mason {
728e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
729e2d84521SMiao Xie 	int ret;
730e2d84521SMiao Xie 
731d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
732448d640bSChris Mason 
733448d640bSChris Mason 		if (wbc->for_kupdate)
734448d640bSChris Mason 			return 0;
735448d640bSChris Mason 
736e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
737b9473439SChris Mason 		/* this is a bit racy, but that's ok */
738d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
739d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
740d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
741e2d84521SMiao Xie 		if (ret < 0)
742793955bcSChris Mason 			return 0;
743793955bcSChris Mason 	}
7440b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
7450da5468fSChris Mason }
7460da5468fSChris Mason 
747f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
7485f39d397SChris Mason {
749f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
750f913cff3SMatthew Wilcox (Oracle) 		return false;
7510c4e538bSDavid Sterba 
752f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
753d98237b3SChris Mason }
754d98237b3SChris Mason 
755895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
756895586ebSMatthew Wilcox (Oracle) 				 size_t length)
757d98237b3SChris Mason {
758d1310b2eSChris Mason 	struct extent_io_tree *tree;
759895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
760895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
761f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
762895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
763895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
764895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
765895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
766895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
7679ad6b7bcSChris Mason 	}
768d98237b3SChris Mason }
769d98237b3SChris Mason 
770bb146eb2SJosef Bacik #ifdef DEBUG
7710079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
7720079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
7730079c3b1SMatthew Wilcox (Oracle) {
7740079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
775139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
7760b32f4bbSJosef Bacik 	struct extent_buffer *eb;
777139e8cd3SQu Wenruo 	int cur_bit = 0;
7780079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
7790b32f4bbSJosef Bacik 
780139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
7810079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
7820b32f4bbSJosef Bacik 		BUG_ON(!eb);
7830b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
7840b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
78549d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
7860079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
787139e8cd3SQu Wenruo 	}
7880079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
789139e8cd3SQu Wenruo 
790139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
791139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
792139e8cd3SQu Wenruo 		unsigned long flags;
793139e8cd3SQu Wenruo 		u64 cur;
794139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
795139e8cd3SQu Wenruo 
796139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
797139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
798139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
799139e8cd3SQu Wenruo 			cur_bit++;
800139e8cd3SQu Wenruo 			continue;
801139e8cd3SQu Wenruo 		}
802139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
803139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
804139e8cd3SQu Wenruo 
805139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
806139e8cd3SQu Wenruo 		ASSERT(eb);
807139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
808139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
80949d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
810139e8cd3SQu Wenruo 		free_extent_buffer(eb);
811139e8cd3SQu Wenruo 
812139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
813139e8cd3SQu Wenruo 	}
8140079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
8150b32f4bbSJosef Bacik }
8160079c3b1SMatthew Wilcox (Oracle) #else
8170079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
8180079c3b1SMatthew Wilcox (Oracle) #endif
8190b32f4bbSJosef Bacik 
8207f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
8210da5468fSChris Mason 	.writepages	= btree_writepages,
822f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
823895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
8248958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
8250079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
826d98237b3SChris Mason };
827123abc88SChris Mason 
8282ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
8292ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
8303fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
8313fbaf258SJosef Bacik 						int level)
8320999df54SChris Mason {
8330b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
8340b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
8353fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
8360999df54SChris Mason }
8370999df54SChris Mason 
838581c1760SQu Wenruo /*
839581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
840581c1760SQu Wenruo  * verification.
841581c1760SQu Wenruo  *
842789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see comments of the
843789d6a3aSQu Wenruo  *			structure for details.
844581c1760SQu Wenruo  */
8452ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
846789d6a3aSQu Wenruo 				      struct btrfs_tree_parent_check *check)
847e20d96d6SChris Mason {
8485f39d397SChris Mason 	struct extent_buffer *buf = NULL;
84919c00ddcSChris Mason 	int ret;
85019c00ddcSChris Mason 
851789d6a3aSQu Wenruo 	ASSERT(check);
852789d6a3aSQu Wenruo 
853789d6a3aSQu Wenruo 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
854789d6a3aSQu Wenruo 					   check->level);
855c871b0f2SLiu Bo 	if (IS_ERR(buf))
856c871b0f2SLiu Bo 		return buf;
857e4204dedSChris Mason 
858789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(buf, check);
8590f0fe8f7SFilipe David Borba Manana 	if (ret) {
860537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
86164c043deSLiu Bo 		return ERR_PTR(ret);
8620f0fe8f7SFilipe David Borba Manana 	}
863789d6a3aSQu Wenruo 	if (btrfs_check_eb_owner(buf, check->owner_root)) {
86488c602abSQu Wenruo 		free_extent_buffer_stale(buf);
86588c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
86688c602abSQu Wenruo 	}
8675f39d397SChris Mason 	return buf;
868ce9adaa5SChris Mason 
869eb60ceacSChris Mason }
870eb60ceacSChris Mason 
871da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
872e20d96d6SChris Mason 			 u64 objectid)
873d97e63b6SChris Mason {
8747c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
8752e608bd1SJosef Bacik 
8762e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
8772e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
8782e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
87996dfcb46SJosef Bacik 	root->fs_info = fs_info;
8802e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
881cfaa7295SChris Mason 	root->node = NULL;
882a28ec197SChris Mason 	root->commit_root = NULL;
88327cdeb70SMiao Xie 	root->state = 0;
884abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
8850b86a832SChris Mason 
8860f7d52f4SChris Mason 	root->last_trans = 0;
8876b8fad57SNikolay Borisov 	root->free_objectid = 0;
888eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
889199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
8906bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
891088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
8922e608bd1SJosef Bacik 
8932e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
8940b86a832SChris Mason 
8950b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
8965d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
897eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
898eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
899199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
900199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
901d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
9022ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
9032ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
9045d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
905eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
906199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
907f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
9082ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
9092ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
9108287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
911a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
912e02119d5SChris Mason 	mutex_init(&root->log_mutex);
91331f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
914573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
915c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
9167237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
9177237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
9187237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
9198b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
9208b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
9217237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
9227237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
9237237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
9242ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
9250700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
9268ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
927eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
9287237f183SYan Zheng 	root->log_transid = 0;
929d1433debSMiao Xie 	root->log_transid_committed = -1;
930257c62e1SChris Mason 	root->last_log_commit = 0;
9312e608bd1SJosef Bacik 	root->anon_dev = 0;
932e289f03eSFilipe Manana 	if (!dummy) {
93343eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
93435da5a7eSDavid Sterba 				    IO_TREE_ROOT_DIRTY_LOG_PAGES);
935e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
93635da5a7eSDavid Sterba 				    IO_TREE_LOG_CSUM_RANGE);
937e289f03eSFilipe Manana 	}
938017e5369SChris Mason 
9395f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
940370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
941bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
942bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
943fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
944bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
945fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
946bd647ce3SJosef Bacik #endif
9473768f368SChris Mason }
9483768f368SChris Mason 
94974e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
95096dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
9516f07e42eSAl Viro {
95274e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
9536f07e42eSAl Viro 	if (root)
95496dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
9556f07e42eSAl Viro 	return root;
9566f07e42eSAl Viro }
9576f07e42eSAl Viro 
95806ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
95906ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
960da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
96106ea65a3SJosef Bacik {
96206ea65a3SJosef Bacik 	struct btrfs_root *root;
96306ea65a3SJosef Bacik 
9647c0260eeSJeff Mahoney 	if (!fs_info)
9657c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
9667c0260eeSJeff Mahoney 
96796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
96806ea65a3SJosef Bacik 	if (!root)
96906ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
970da17066cSJeff Mahoney 
971b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
972faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
97306ea65a3SJosef Bacik 
97406ea65a3SJosef Bacik 	return root;
97506ea65a3SJosef Bacik }
97606ea65a3SJosef Bacik #endif
97706ea65a3SJosef Bacik 
978abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
979abed4aaaSJosef Bacik {
980abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
981abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
982abed4aaaSJosef Bacik 
983abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
984abed4aaaSJosef Bacik }
985abed4aaaSJosef Bacik 
986abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
987abed4aaaSJosef Bacik {
988abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
989abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
990abed4aaaSJosef Bacik 
991abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
992abed4aaaSJosef Bacik }
993abed4aaaSJosef Bacik 
994abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
995abed4aaaSJosef Bacik {
996abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
997abed4aaaSJosef Bacik 	struct rb_node *tmp;
998abed4aaaSJosef Bacik 
999abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1000abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1001abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1002abed4aaaSJosef Bacik 	ASSERT(!tmp);
1003abed4aaaSJosef Bacik 
1004abed4aaaSJosef Bacik 	return tmp ? -EEXIST : 0;
1005abed4aaaSJosef Bacik }
1006abed4aaaSJosef Bacik 
1007abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
1008abed4aaaSJosef Bacik {
1009abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1010abed4aaaSJosef Bacik 
1011abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1012abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
1013abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1014abed4aaaSJosef Bacik }
1015abed4aaaSJosef Bacik 
1016abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1017abed4aaaSJosef Bacik 				     struct btrfs_key *key)
1018abed4aaaSJosef Bacik {
1019abed4aaaSJosef Bacik 	struct rb_node *node;
1020abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
1021abed4aaaSJosef Bacik 
1022abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
1023abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1024abed4aaaSJosef Bacik 	if (node)
1025abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
1026abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
1027abed4aaaSJosef Bacik 
1028abed4aaaSJosef Bacik 	return root;
1029abed4aaaSJosef Bacik }
1030abed4aaaSJosef Bacik 
1031f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1032f7238e50SJosef Bacik {
1033f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
1034f7238e50SJosef Bacik 	u64 ret;
1035f7238e50SJosef Bacik 
1036f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1037f7238e50SJosef Bacik 		return 0;
1038f7238e50SJosef Bacik 
1039f7238e50SJosef Bacik 	if (bytenr)
1040f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
1041f7238e50SJosef Bacik 	else
1042f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1043f7238e50SJosef Bacik 	ASSERT(block_group);
1044f7238e50SJosef Bacik 	if (!block_group)
1045f7238e50SJosef Bacik 		return 0;
1046f7238e50SJosef Bacik 	ret = block_group->global_root_id;
1047f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
1048f7238e50SJosef Bacik 
1049f7238e50SJosef Bacik 	return ret;
1050f7238e50SJosef Bacik }
1051f7238e50SJosef Bacik 
1052abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1053abed4aaaSJosef Bacik {
1054abed4aaaSJosef Bacik 	struct btrfs_key key = {
1055abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1056abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1057f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1058abed4aaaSJosef Bacik 	};
1059abed4aaaSJosef Bacik 
1060abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1061abed4aaaSJosef Bacik }
1062abed4aaaSJosef Bacik 
1063abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1064abed4aaaSJosef Bacik {
1065abed4aaaSJosef Bacik 	struct btrfs_key key = {
1066abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1067abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1068f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1069abed4aaaSJosef Bacik 	};
1070abed4aaaSJosef Bacik 
1071abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1072abed4aaaSJosef Bacik }
1073abed4aaaSJosef Bacik 
107451129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
107551129b33SJosef Bacik {
107651129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
107751129b33SJosef Bacik 		return fs_info->block_group_root;
107851129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
107951129b33SJosef Bacik }
108051129b33SJosef Bacik 
108120897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
108220897f5cSArne Jansen 				     u64 objectid)
108320897f5cSArne Jansen {
10849b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
108520897f5cSArne Jansen 	struct extent_buffer *leaf;
108620897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
108720897f5cSArne Jansen 	struct btrfs_root *root;
108820897f5cSArne Jansen 	struct btrfs_key key;
1089b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
109020897f5cSArne Jansen 	int ret = 0;
109120897f5cSArne Jansen 
1092b89f6d1fSFilipe Manana 	/*
1093b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1094b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1095b89f6d1fSFilipe Manana 	 */
1096b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
109796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1098b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
109920897f5cSArne Jansen 	if (!root)
110020897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
110120897f5cSArne Jansen 
110220897f5cSArne Jansen 	root->root_key.objectid = objectid;
110320897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
110420897f5cSArne Jansen 	root->root_key.offset = 0;
110520897f5cSArne Jansen 
11069631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
11079631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
110820897f5cSArne Jansen 	if (IS_ERR(leaf)) {
110920897f5cSArne Jansen 		ret = PTR_ERR(leaf);
11101dd05682STsutomu Itoh 		leaf = NULL;
1111c1b07854SPeng Hao 		goto fail;
111220897f5cSArne Jansen 	}
111320897f5cSArne Jansen 
111420897f5cSArne Jansen 	root->node = leaf;
111520897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
111620897f5cSArne Jansen 
111720897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
111827cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
111920897f5cSArne Jansen 
1120f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1121f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
112220897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
112320897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
112420897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
112520897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
112620897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
112720897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
112820897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
112933d85fdaSQu Wenruo 	if (is_fstree(objectid))
1130807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1131807fc790SAndy Shevchenko 	else
1132807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1133c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
113420897f5cSArne Jansen 
11358a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
11368a6a87cdSBoris Burkov 
113720897f5cSArne Jansen 	key.objectid = objectid;
113820897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
113920897f5cSArne Jansen 	key.offset = 0;
114020897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
114120897f5cSArne Jansen 	if (ret)
114220897f5cSArne Jansen 		goto fail;
114320897f5cSArne Jansen 
114420897f5cSArne Jansen 	return root;
11451dd05682STsutomu Itoh 
11468a6a87cdSBoris Burkov fail:
114700246528SJosef Bacik 	btrfs_put_root(root);
11481dd05682STsutomu Itoh 
11491dd05682STsutomu Itoh 	return ERR_PTR(ret);
115020897f5cSArne Jansen }
115120897f5cSArne Jansen 
11527237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1153e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
11540f7d52f4SChris Mason {
11550f7d52f4SChris Mason 	struct btrfs_root *root;
1156e02119d5SChris Mason 
115796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1158e02119d5SChris Mason 	if (!root)
11597237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1160e02119d5SChris Mason 
1161e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1162e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1163e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
116427cdeb70SMiao Xie 
11656ab6ebb7SNaohiro Aota 	return root;
11666ab6ebb7SNaohiro Aota }
11676ab6ebb7SNaohiro Aota 
11686ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
11696ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
11706ab6ebb7SNaohiro Aota {
11716ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
11726ab6ebb7SNaohiro Aota 
11737237f183SYan Zheng 	/*
117492a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
117527cdeb70SMiao Xie 	 *
117692a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
117792a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
117892a7cc42SQu Wenruo 	 *
117992a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
118092a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
11817237f183SYan Zheng 	 */
1182e02119d5SChris Mason 
11834d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
11849631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
11856ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
11866ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1187e02119d5SChris Mason 
11887237f183SYan Zheng 	root->node = leaf;
1189e02119d5SChris Mason 
1190e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1191e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
11926ab6ebb7SNaohiro Aota 
11936ab6ebb7SNaohiro Aota 	return 0;
11947237f183SYan Zheng }
11957237f183SYan Zheng 
11967237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
11977237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
11987237f183SYan Zheng {
11997237f183SYan Zheng 	struct btrfs_root *log_root;
12007237f183SYan Zheng 
12017237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
12027237f183SYan Zheng 	if (IS_ERR(log_root))
12037237f183SYan Zheng 		return PTR_ERR(log_root);
12046ab6ebb7SNaohiro Aota 
12053ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
12063ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
12073ddebf27SNaohiro Aota 
12086ab6ebb7SNaohiro Aota 		if (ret) {
12096ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
12106ab6ebb7SNaohiro Aota 			return ret;
12116ab6ebb7SNaohiro Aota 		}
12123ddebf27SNaohiro Aota 	}
12136ab6ebb7SNaohiro Aota 
12147237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
12157237f183SYan Zheng 	fs_info->log_root_tree = log_root;
12167237f183SYan Zheng 	return 0;
12177237f183SYan Zheng }
12187237f183SYan Zheng 
12197237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
12207237f183SYan Zheng 		       struct btrfs_root *root)
12217237f183SYan Zheng {
12220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12237237f183SYan Zheng 	struct btrfs_root *log_root;
12247237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
12256ab6ebb7SNaohiro Aota 	int ret;
12267237f183SYan Zheng 
12270b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
12287237f183SYan Zheng 	if (IS_ERR(log_root))
12297237f183SYan Zheng 		return PTR_ERR(log_root);
12307237f183SYan Zheng 
12316ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
12326ab6ebb7SNaohiro Aota 	if (ret) {
12336ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
12346ab6ebb7SNaohiro Aota 		return ret;
12356ab6ebb7SNaohiro Aota 	}
12366ab6ebb7SNaohiro Aota 
12377237f183SYan Zheng 	log_root->last_trans = trans->transid;
12387237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
12397237f183SYan Zheng 
12407237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
12413cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
12423cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
12433cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1244da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
12450b246afaSJeff Mahoney 				     fs_info->nodesize);
12463cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
12477237f183SYan Zheng 
12485d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
12497237f183SYan Zheng 
12507237f183SYan Zheng 	WARN_ON(root->log_root);
12517237f183SYan Zheng 	root->log_root = log_root;
12527237f183SYan Zheng 	root->log_transid = 0;
1253d1433debSMiao Xie 	root->log_transid_committed = -1;
1254257c62e1SChris Mason 	root->last_log_commit = 0;
1255e02119d5SChris Mason 	return 0;
1256e02119d5SChris Mason }
1257e02119d5SChris Mason 
125849d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
125949d11beaSJosef Bacik 					      struct btrfs_path *path,
1260cb517eabSMiao Xie 					      struct btrfs_key *key)
1261e02119d5SChris Mason {
1262e02119d5SChris Mason 	struct btrfs_root *root;
1263789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1264e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
126584234f3aSYan Zheng 	u64 generation;
1266cb517eabSMiao Xie 	int ret;
1267581c1760SQu Wenruo 	int level;
1268cb517eabSMiao Xie 
126996dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
127049d11beaSJosef Bacik 	if (!root)
127149d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
12720f7d52f4SChris Mason 
1273cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1274cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
12750f7d52f4SChris Mason 	if (ret) {
127613a8a7c8SYan, Zheng 		if (ret > 0)
127713a8a7c8SYan, Zheng 			ret = -ENOENT;
127849d11beaSJosef Bacik 		goto fail;
12790f7d52f4SChris Mason 	}
128013a8a7c8SYan, Zheng 
128184234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1282581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
1283789d6a3aSQu Wenruo 	check.level = level;
1284789d6a3aSQu Wenruo 	check.transid = generation;
1285789d6a3aSQu Wenruo 	check.owner_root = key->objectid;
1286789d6a3aSQu Wenruo 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1287789d6a3aSQu Wenruo 				     &check);
128864c043deSLiu Bo 	if (IS_ERR(root->node)) {
128964c043deSLiu Bo 		ret = PTR_ERR(root->node);
12908c38938cSJosef Bacik 		root->node = NULL;
129149d11beaSJosef Bacik 		goto fail;
12924eb150d6SQu Wenruo 	}
12934eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1294cb517eabSMiao Xie 		ret = -EIO;
129549d11beaSJosef Bacik 		goto fail;
1296416bc658SJosef Bacik 	}
129788c602abSQu Wenruo 
129888c602abSQu Wenruo 	/*
129988c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
130088c602abSQu Wenruo 	 * match its root node owner
130188c602abSQu Wenruo 	 */
130288c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
130388c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
130488c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
130588c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
130688c602abSQu Wenruo 		btrfs_crit(fs_info,
130788c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
130888c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
130988c602abSQu Wenruo 			   btrfs_header_owner(root->node),
131088c602abSQu Wenruo 			   root->root_key.objectid);
131188c602abSQu Wenruo 		ret = -EUCLEAN;
131288c602abSQu Wenruo 		goto fail;
131388c602abSQu Wenruo 	}
13145d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1315cb517eabSMiao Xie 	return root;
131649d11beaSJosef Bacik fail:
131700246528SJosef Bacik 	btrfs_put_root(root);
131849d11beaSJosef Bacik 	return ERR_PTR(ret);
131949d11beaSJosef Bacik }
132049d11beaSJosef Bacik 
132149d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
132249d11beaSJosef Bacik 					struct btrfs_key *key)
132349d11beaSJosef Bacik {
132449d11beaSJosef Bacik 	struct btrfs_root *root;
132549d11beaSJosef Bacik 	struct btrfs_path *path;
132649d11beaSJosef Bacik 
132749d11beaSJosef Bacik 	path = btrfs_alloc_path();
132849d11beaSJosef Bacik 	if (!path)
132949d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
133049d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
133149d11beaSJosef Bacik 	btrfs_free_path(path);
133249d11beaSJosef Bacik 
133349d11beaSJosef Bacik 	return root;
1334cb517eabSMiao Xie }
1335cb517eabSMiao Xie 
13362dfb1e43SQu Wenruo /*
13372dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
13382dfb1e43SQu Wenruo  *
13392dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
13402dfb1e43SQu Wenruo  */
13412dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1342cb517eabSMiao Xie {
1343cb517eabSMiao Xie 	int ret;
1344cb517eabSMiao Xie 
1345*0b548539SDavid Sterba 	btrfs_drew_lock_init(&root->snapshot_lock);
13468257b2dcSMiao Xie 
1347aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
134837f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
134992a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1350f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1351f39e4571SJosef Bacik 	}
1352f39e4571SJosef Bacik 
1353851fd730SQu Wenruo 	/*
1354851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1355851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1356851fd730SQu Wenruo 	 */
1357851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1358851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
13592dfb1e43SQu Wenruo 		if (!anon_dev) {
1360cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1361cb517eabSMiao Xie 			if (ret)
1362876d2cf1SLiu Bo 				goto fail;
13632dfb1e43SQu Wenruo 		} else {
13642dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
13652dfb1e43SQu Wenruo 		}
1366851fd730SQu Wenruo 	}
1367f32e48e9SChandan Rajendra 
1368f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1369453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1370f32e48e9SChandan Rajendra 	if (ret) {
1371f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1372876d2cf1SLiu Bo 		goto fail;
1373f32e48e9SChandan Rajendra 	}
1374f32e48e9SChandan Rajendra 
13756b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1376f32e48e9SChandan Rajendra 
1377f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1378f32e48e9SChandan Rajendra 
1379cb517eabSMiao Xie 	return 0;
1380cb517eabSMiao Xie fail:
138184db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1382cb517eabSMiao Xie 	return ret;
1383cb517eabSMiao Xie }
1384cb517eabSMiao Xie 
1385a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1386cb517eabSMiao Xie 					       u64 root_id)
1387cb517eabSMiao Xie {
1388cb517eabSMiao Xie 	struct btrfs_root *root;
1389cb517eabSMiao Xie 
1390fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1391fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1392fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1393bc44d7c4SJosef Bacik 	if (root)
139400246528SJosef Bacik 		root = btrfs_grab_root(root);
1395fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1396cb517eabSMiao Xie 	return root;
1397cb517eabSMiao Xie }
1398cb517eabSMiao Xie 
139949d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
140049d11beaSJosef Bacik 						u64 objectid)
140149d11beaSJosef Bacik {
1402abed4aaaSJosef Bacik 	struct btrfs_key key = {
1403abed4aaaSJosef Bacik 		.objectid = objectid,
1404abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1405abed4aaaSJosef Bacik 		.offset = 0,
1406abed4aaaSJosef Bacik 	};
1407abed4aaaSJosef Bacik 
140849d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
140949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
141049d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1411abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
141249d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
141349d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
141449d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
141549d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
141649d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1417abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
141849d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
141949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
142049d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
142149d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
142249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
142349d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
142414033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
142514033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
142614033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1427abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1428abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1429abed4aaaSJosef Bacik 
1430abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1431abed4aaaSJosef Bacik 	}
143249d11beaSJosef Bacik 	return NULL;
143349d11beaSJosef Bacik }
143449d11beaSJosef Bacik 
1435cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1436cb517eabSMiao Xie 			 struct btrfs_root *root)
1437cb517eabSMiao Xie {
1438cb517eabSMiao Xie 	int ret;
1439cb517eabSMiao Xie 
1440fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1441fc7cbcd4SDavid Sterba 	if (ret)
1442fc7cbcd4SDavid Sterba 		return ret;
1443fc7cbcd4SDavid Sterba 
1444fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1445fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1446fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1447fc7cbcd4SDavid Sterba 				root);
1448af01d2e5SJosef Bacik 	if (ret == 0) {
144900246528SJosef Bacik 		btrfs_grab_root(root);
1450fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1451af01d2e5SJosef Bacik 	}
1452fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1453fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1454cb517eabSMiao Xie 
1455cb517eabSMiao Xie 	return ret;
1456cb517eabSMiao Xie }
1457cb517eabSMiao Xie 
1458bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1459bd647ce3SJosef Bacik {
1460bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1461bd647ce3SJosef Bacik 	struct btrfs_root *root;
1462bd647ce3SJosef Bacik 
1463bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1464457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1465457f1864SJosef Bacik 
1466bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1467bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1468457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
146971008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1470bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1471bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
147200246528SJosef Bacik 			btrfs_put_root(root);
147300246528SJosef Bacik 		btrfs_put_root(root);
1474bd647ce3SJosef Bacik 	}
1475bd647ce3SJosef Bacik #endif
1476bd647ce3SJosef Bacik }
1477bd647ce3SJosef Bacik 
1478abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1479abed4aaaSJosef Bacik {
1480abed4aaaSJosef Bacik 	struct btrfs_root *root;
1481abed4aaaSJosef Bacik 	struct rb_node *node;
1482abed4aaaSJosef Bacik 
1483abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1484abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1485abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1486abed4aaaSJosef Bacik 		btrfs_put_root(root);
1487abed4aaaSJosef Bacik 	}
1488abed4aaaSJosef Bacik }
1489abed4aaaSJosef Bacik 
14900d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
14910d4b0463SJosef Bacik {
1492141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1493141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
14945deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1495141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1496141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1497141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1498141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
14990d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
15000d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1501abed4aaaSJosef Bacik 	free_global_roots(fs_info);
150200246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
150300246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
150400246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
150500246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
150600246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
150700246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1508aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
15099c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1510bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
15113fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
15120d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
15130d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
15148481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
15150d4b0463SJosef Bacik 	kvfree(fs_info);
15160d4b0463SJosef Bacik }
15170d4b0463SJosef Bacik 
15180d4b0463SJosef Bacik 
15192dfb1e43SQu Wenruo /*
15202dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
15212dfb1e43SQu Wenruo  *
15222dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
15232dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
15242dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
15252dfb1e43SQu Wenruo  *
15262dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
15272dfb1e43SQu Wenruo  *
15282dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
15292dfb1e43SQu Wenruo  *	 same root objectid.
15302dfb1e43SQu Wenruo  *
15312dfb1e43SQu Wenruo  * @objectid:	root id
15322dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
15332dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
15342dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
15352dfb1e43SQu Wenruo  *		for orphan roots
15362dfb1e43SQu Wenruo  */
15372dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
15382dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
15392dfb1e43SQu Wenruo 					     bool check_ref)
15405eda7b5eSChris Mason {
15415eda7b5eSChris Mason 	struct btrfs_root *root;
1542381cf658SDavid Sterba 	struct btrfs_path *path;
15431d4c08e0SDavid Sterba 	struct btrfs_key key;
15445eda7b5eSChris Mason 	int ret;
15455eda7b5eSChris Mason 
154649d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
154749d11beaSJosef Bacik 	if (root)
154849d11beaSJosef Bacik 		return root;
15494df27c4dSYan, Zheng again:
155056e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
155148475471SStefan Behrens 	if (root) {
15522dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
15532dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1554bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
155500246528SJosef Bacik 			btrfs_put_root(root);
155648475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1557bc44d7c4SJosef Bacik 		}
15585eda7b5eSChris Mason 		return root;
155948475471SStefan Behrens 	}
15605eda7b5eSChris Mason 
156156e9357aSDavid Sterba 	key.objectid = objectid;
156256e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
156356e9357aSDavid Sterba 	key.offset = (u64)-1;
156456e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
15655eda7b5eSChris Mason 	if (IS_ERR(root))
15665eda7b5eSChris Mason 		return root;
15673394e160SChris Mason 
1568c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1569d68fc57bSYan, Zheng 		ret = -ENOENT;
1570d68fc57bSYan, Zheng 		goto fail;
1571d68fc57bSYan, Zheng 	}
1572d68fc57bSYan, Zheng 
15732dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1574cb517eabSMiao Xie 	if (ret)
1575cb517eabSMiao Xie 		goto fail;
1576cb517eabSMiao Xie 
1577381cf658SDavid Sterba 	path = btrfs_alloc_path();
1578381cf658SDavid Sterba 	if (!path) {
1579381cf658SDavid Sterba 		ret = -ENOMEM;
1580381cf658SDavid Sterba 		goto fail;
1581381cf658SDavid Sterba 	}
15821d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15831d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
158456e9357aSDavid Sterba 	key.offset = objectid;
15851d4c08e0SDavid Sterba 
15861d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1587381cf658SDavid Sterba 	btrfs_free_path(path);
1588d68fc57bSYan, Zheng 	if (ret < 0)
1589d68fc57bSYan, Zheng 		goto fail;
1590d68fc57bSYan, Zheng 	if (ret == 0)
159127cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1592d68fc57bSYan, Zheng 
1593cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
15940f7d52f4SChris Mason 	if (ret) {
1595168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
159600246528SJosef Bacik 			btrfs_put_root(root);
15974df27c4dSYan, Zheng 			goto again;
1598168a2f77SJia-Ju Bai 		}
15994df27c4dSYan, Zheng 		goto fail;
16004df27c4dSYan, Zheng 	}
1601edbd8d4eSChris Mason 	return root;
16024df27c4dSYan, Zheng fail:
160333fab972SFilipe Manana 	/*
160433fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1605143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
160633fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
160733fab972SFilipe Manana 	 * and once again by our caller.
160833fab972SFilipe Manana 	 */
160933fab972SFilipe Manana 	if (anon_dev)
161033fab972SFilipe Manana 		root->anon_dev = 0;
16118c38938cSJosef Bacik 	btrfs_put_root(root);
16124df27c4dSYan, Zheng 	return ERR_PTR(ret);
1613edbd8d4eSChris Mason }
1614edbd8d4eSChris Mason 
16152dfb1e43SQu Wenruo /*
16162dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
16172dfb1e43SQu Wenruo  *
16182dfb1e43SQu Wenruo  * @objectid:	tree objectid
16192dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
16202dfb1e43SQu Wenruo  *		one reference
16212dfb1e43SQu Wenruo  */
16222dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
16232dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
16242dfb1e43SQu Wenruo {
16252dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
16262dfb1e43SQu Wenruo }
16272dfb1e43SQu Wenruo 
16282dfb1e43SQu Wenruo /*
16292dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
16302dfb1e43SQu Wenruo  * the anonymous block device id
16312dfb1e43SQu Wenruo  *
16322dfb1e43SQu Wenruo  * @objectid:	tree objectid
16332dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
16342dfb1e43SQu Wenruo  *		parameter value
16352dfb1e43SQu Wenruo  */
16362dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
16372dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
16382dfb1e43SQu Wenruo {
16392dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
16402dfb1e43SQu Wenruo }
16412dfb1e43SQu Wenruo 
16428b712842SChris Mason /*
164349d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
164449d11beaSJosef Bacik  * @fs_info:	the fs_info
164549d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
164649d11beaSJosef Bacik  *
164749d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
164849d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
164949d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
165049d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
165149d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
165249d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
165349d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
165449d11beaSJosef Bacik  * backref code is finished using the root.
165549d11beaSJosef Bacik  */
165649d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
165749d11beaSJosef Bacik 						 struct btrfs_path *path,
165849d11beaSJosef Bacik 						 u64 objectid)
165949d11beaSJosef Bacik {
166049d11beaSJosef Bacik 	struct btrfs_root *root;
166149d11beaSJosef Bacik 	struct btrfs_key key;
166249d11beaSJosef Bacik 
166349d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
166449d11beaSJosef Bacik 
166549d11beaSJosef Bacik 	/*
166649d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
166749d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
166849d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
166949d11beaSJosef Bacik 	 * != NULL just return it.
167049d11beaSJosef Bacik 	 */
167149d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
167249d11beaSJosef Bacik 	if (root)
167349d11beaSJosef Bacik 		return root;
167449d11beaSJosef Bacik 
167549d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
167649d11beaSJosef Bacik 	if (root)
167749d11beaSJosef Bacik 		return root;
167849d11beaSJosef Bacik 
167949d11beaSJosef Bacik 	key.objectid = objectid;
168049d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
168149d11beaSJosef Bacik 	key.offset = (u64)-1;
168249d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
168349d11beaSJosef Bacik 	btrfs_release_path(path);
168449d11beaSJosef Bacik 
168549d11beaSJosef Bacik 	return root;
168649d11beaSJosef Bacik }
168749d11beaSJosef Bacik 
1688a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1689a74a4b97SChris Mason {
16900d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1691d0278245SMiao Xie 	int again;
1692a74a4b97SChris Mason 
1693d6fd0ae2SOmar Sandoval 	while (1) {
1694d0278245SMiao Xie 		again = 0;
16959d1a2a3aSDavid Sterba 
1696fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1697fd340d0fSJosef Bacik 
1698d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16992ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1700d0278245SMiao Xie 			goto sleep;
1701d0278245SMiao Xie 
170290c711abSZygo Blaxell 		/*
170390c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
170490c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
170590c711abSZygo Blaxell 		 */
17060b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
170790c711abSZygo Blaxell 			goto sleep;
170890c711abSZygo Blaxell 
17090b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1710d0278245SMiao Xie 			goto sleep;
1711d0278245SMiao Xie 
1712dc7f370cSMiao Xie 		/*
1713dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1714dc7f370cSMiao Xie 		 * during the above check and trylock.
1715dc7f370cSMiao Xie 		 */
17162ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
17170b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1718dc7f370cSMiao Xie 			goto sleep;
1719dc7f370cSMiao Xie 		}
1720dc7f370cSMiao Xie 
1721b7625f46SQu Wenruo 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1722b7625f46SQu Wenruo 			btrfs_sysfs_feature_update(fs_info);
1723b7625f46SQu Wenruo 
17242ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1725c2d6cb16SFilipe Manana 
172633c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
17270b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1728a74a4b97SChris Mason 
1729d0278245SMiao Xie 		/*
173005323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
173105323cd1SMiao Xie 		 * needn't do anything special here.
1732d0278245SMiao Xie 		 */
17330b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
173467c5e7d4SFilipe Manana 
173567c5e7d4SFilipe Manana 		/*
1736f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
173767c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
173867c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1739f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
174067c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
174167c5e7d4SFilipe Manana 		 * unused block groups.
174267c5e7d4SFilipe Manana 		 */
17430b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
174418bb8bbfSJohannes Thumshirn 
174518bb8bbfSJohannes Thumshirn 		/*
174618bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
174718bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
174818bb8bbfSJohannes Thumshirn 		 * space.
174918bb8bbfSJohannes Thumshirn 		 */
175018bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1751d0278245SMiao Xie sleep:
1752a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1753d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1754d6fd0ae2SOmar Sandoval 			kthread_parkme();
1755d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1756d6fd0ae2SOmar Sandoval 			return 0;
1757838fe188SJiri Kosina 		if (!again) {
1758a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1759a74a4b97SChris Mason 			schedule();
1760a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1761a74a4b97SChris Mason 		}
1762da288d28SFilipe Manana 	}
1763a74a4b97SChris Mason }
1764a74a4b97SChris Mason 
1765a74a4b97SChris Mason static int transaction_kthread(void *arg)
1766a74a4b97SChris Mason {
1767a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1769a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1770a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17718929ecfaSYan, Zheng 	u64 transid;
1772643900beSNikolay Borisov 	time64_t delta;
1773a74a4b97SChris Mason 	unsigned long delay;
1774914b2007SJan Kara 	bool cannot_commit;
1775a74a4b97SChris Mason 
1776a74a4b97SChris Mason 	do {
1777914b2007SJan Kara 		cannot_commit = false;
1778ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
17790b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1780a74a4b97SChris Mason 
17810b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17820b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1783a74a4b97SChris Mason 		if (!cur) {
17840b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1785a74a4b97SChris Mason 			goto sleep;
1786a74a4b97SChris Mason 		}
178731153d81SYan Zheng 
1788643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1789fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1790fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1791643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
17920b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1793fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1794fb8a7e94SNikolay Borisov 			delay = min(delay,
1795fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1796a74a4b97SChris Mason 			goto sleep;
1797a74a4b97SChris Mason 		}
17988929ecfaSYan, Zheng 		transid = cur->transid;
17990b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
180056bec294SChris Mason 
180179787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1802354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1803914b2007SJan Kara 		if (IS_ERR(trans)) {
1804354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1805914b2007SJan Kara 				cannot_commit = true;
180679787eaaSJeff Mahoney 			goto sleep;
1807914b2007SJan Kara 		}
18088929ecfaSYan, Zheng 		if (transid == trans->transid) {
18093a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
18108929ecfaSYan, Zheng 		} else {
18113a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18128929ecfaSYan, Zheng 		}
1813a74a4b97SChris Mason sleep:
18140b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
18150b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1816a74a4b97SChris Mason 
181784961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
18182ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
18198929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
18200b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1821914b2007SJan Kara 				 cannot_commit))
1822bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1823a74a4b97SChris Mason 	} while (!kthread_should_stop());
1824a74a4b97SChris Mason 	return 0;
1825a74a4b97SChris Mason }
1826a74a4b97SChris Mason 
1827af31f5e5SChris Mason /*
182801f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
182901f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
183001f0f9daSNikolay Borisov  * anything.
1831af31f5e5SChris Mason  *
1832af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1833af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1834af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1835af31f5e5SChris Mason  */
183601f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1837af31f5e5SChris Mason {
183801f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1839af31f5e5SChris Mason 	u64 cur;
1840af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1841af31f5e5SChris Mason 	int i;
1842af31f5e5SChris Mason 
1843af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1844af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1845af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1846af31f5e5SChris Mason 		if (cur == newest_gen)
184701f0f9daSNikolay Borisov 			return i;
1848af31f5e5SChris Mason 	}
1849af31f5e5SChris Mason 
185001f0f9daSNikolay Borisov 	return -EINVAL;
1851af31f5e5SChris Mason }
1852af31f5e5SChris Mason 
1853af31f5e5SChris Mason /*
1854af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1855af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1856af31f5e5SChris Mason  * done
1857af31f5e5SChris Mason  */
1858af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1859af31f5e5SChris Mason {
18606ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1861af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1862af31f5e5SChris Mason 
1863af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1864af31f5e5SChris Mason 
1865af31f5e5SChris Mason 	/*
1866af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1867af31f5e5SChris Mason 	 * regardless of which ones we use today
1868af31f5e5SChris Mason 	 */
1869af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1870af31f5e5SChris Mason 
1871af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1872af31f5e5SChris Mason 
1873af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1874af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1875af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1876af31f5e5SChris Mason 
1877af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1878af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1879af31f5e5SChris Mason 
1880af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1881af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1882af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1883af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1884af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1885af31f5e5SChris Mason 
18861c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
18879c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1888f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
18899c54e80dSJosef Bacik 
18909c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
18919c54e80dSJosef Bacik 					     extent_root->node->start);
1892af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
189329cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
1894af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
189529cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
1896af31f5e5SChris Mason 
1897f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1898f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
1899f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
1900f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
1901f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
19029c54e80dSJosef Bacik 	}
1903af31f5e5SChris Mason 
19047c7e82a7SChris Mason 	/*
19057c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
19067c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
19077c7e82a7SChris Mason 	 */
19087c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
19097c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
19107c7e82a7SChris Mason 					 info->fs_root->node->start);
1911af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1912af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1913af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1914af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19157c7e82a7SChris Mason 	}
1916af31f5e5SChris Mason 
1917af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1918af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1919af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1920af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1921af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1922af31f5e5SChris Mason 
1923af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1924af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1925af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1926af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1927af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1928af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1929af31f5e5SChris Mason 
1930af31f5e5SChris Mason 	/*
1931af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1932af31f5e5SChris Mason 	 * for the next commit
1933af31f5e5SChris Mason 	 */
1934af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1935af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1936af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1937af31f5e5SChris Mason }
1938af31f5e5SChris Mason 
1939af31f5e5SChris Mason /*
1940bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1941bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1942bd2336b2SNikolay Borisov  *
1943bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1944bd2336b2SNikolay Borisov  * priority - priority of backup root required
1945bd2336b2SNikolay Borisov  *
1946bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1947bd2336b2SNikolay Borisov  */
1948bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1949bd2336b2SNikolay Borisov {
1950bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1951bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1952bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1953bd2336b2SNikolay Borisov 
1954bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1955bd2336b2SNikolay Borisov 		if (priority == 0)
1956bd2336b2SNikolay Borisov 			return backup_index;
1957bd2336b2SNikolay Borisov 
1958bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1959bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1960bd2336b2SNikolay Borisov 	} else {
1961bd2336b2SNikolay Borisov 		return -EINVAL;
1962bd2336b2SNikolay Borisov 	}
1963bd2336b2SNikolay Borisov 
1964bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1965bd2336b2SNikolay Borisov 
1966bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1967bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1968bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1969bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1970bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1971bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1972bd2336b2SNikolay Borisov 
1973bd2336b2SNikolay Borisov 	/*
1974bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1975bd2336b2SNikolay Borisov 	 * need a fsck
1976bd2336b2SNikolay Borisov 	 */
1977bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1978bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1979bd2336b2SNikolay Borisov 
1980bd2336b2SNikolay Borisov 	return backup_index;
1981bd2336b2SNikolay Borisov }
1982bd2336b2SNikolay Borisov 
19837abadb64SLiu Bo /* helper to cleanup workers */
19847abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19857abadb64SLiu Bo {
1986dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1987afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
1988a31b4a43SChristoph Hellwig 	btrfs_destroy_workqueue(fs_info->hipri_workers);
19895cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1990d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
1991d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
1992385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
1993385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
1994fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
1995fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
1996fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1997fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19985b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1999e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2000a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2001fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2002b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2003b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2004a9b9477dSFilipe Manana 	/*
2005a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2006a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2007a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2008a9b9477dSFilipe Manana 	 */
2009d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
2010d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
20117abadb64SLiu Bo }
20127abadb64SLiu Bo 
20132e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20142e9f5954SRashika {
20152e9f5954SRashika 	if (root) {
20162e9f5954SRashika 		free_extent_buffer(root->node);
20172e9f5954SRashika 		free_extent_buffer(root->commit_root);
20182e9f5954SRashika 		root->node = NULL;
20192e9f5954SRashika 		root->commit_root = NULL;
20202e9f5954SRashika 	}
20212e9f5954SRashika }
20222e9f5954SRashika 
2023abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2024abed4aaaSJosef Bacik {
2025abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
2026abed4aaaSJosef Bacik 
2027abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
2028abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
2029abed4aaaSJosef Bacik 					     rb_node)
2030abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
2031abed4aaaSJosef Bacik }
2032abed4aaaSJosef Bacik 
2033af31f5e5SChris Mason /* helper to cleanup tree roots */
20344273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2035af31f5e5SChris Mason {
20362e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2037655b09feSJosef Bacik 
2038abed4aaaSJosef Bacik 	free_global_root_pointers(info);
20392e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
20402e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20412e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20428c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2043aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
20449c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
20454273eaffSAnand Jain 	if (free_chunk_root)
20462e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2047af31f5e5SChris Mason }
2048af31f5e5SChris Mason 
20498c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
20508c38938cSJosef Bacik {
20518c38938cSJosef Bacik 	if (!root)
20528c38938cSJosef Bacik 		return;
20538c38938cSJosef Bacik 
20548c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
20558c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
20561dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
20578c38938cSJosef Bacik 		if (root->anon_dev)
20588c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
2059923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
20608c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2061fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
20628c38938cSJosef Bacik 		list_del_init(&root->leak_list);
2063fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
20648c38938cSJosef Bacik #endif
20658c38938cSJosef Bacik 		kfree(root);
20668c38938cSJosef Bacik 	}
20678c38938cSJosef Bacik }
20688c38938cSJosef Bacik 
2069faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2070171f6537SJosef Bacik {
2071fc7cbcd4SDavid Sterba 	int ret;
2072fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
2073fc7cbcd4SDavid Sterba 	int i;
2074171f6537SJosef Bacik 
2075171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2076fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
2077171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2078fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
2079171f6537SJosef Bacik 
2080fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2081fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2082fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
2083171f6537SJosef Bacik 	}
2084171f6537SJosef Bacik 
2085fc7cbcd4SDavid Sterba 	while (1) {
2086fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2087fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
2088fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
2089fc7cbcd4SDavid Sterba 		if (!ret)
2090fc7cbcd4SDavid Sterba 			break;
2091fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
2092fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2093171f6537SJosef Bacik 	}
2094171f6537SJosef Bacik }
2095af31f5e5SChris Mason 
2096638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2097638aa7edSEric Sandeen {
2098638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2099638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2100638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2101638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2102638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2103638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2104ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2105638aa7edSEric Sandeen }
2106638aa7edSEric Sandeen 
2107779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2108779a65a4SEric Sandeen {
2109779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2110779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2111779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2112779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2113779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2114779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2115907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2116779a65a4SEric Sandeen }
2117779a65a4SEric Sandeen 
2118dcb2137cSChristoph Hellwig static int btrfs_init_btree_inode(struct super_block *sb)
2119f37938e0SEric Sandeen {
2120dcb2137cSChristoph Hellwig 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2121e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
2122e256927bSJosef Bacik 					      fs_info->tree_root);
2123dcb2137cSChristoph Hellwig 	struct inode *inode;
2124dcb2137cSChristoph Hellwig 
2125dcb2137cSChristoph Hellwig 	inode = new_inode(sb);
2126dcb2137cSChristoph Hellwig 	if (!inode)
2127dcb2137cSChristoph Hellwig 		return -ENOMEM;
21282ff7e61eSJeff Mahoney 
21292ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
21302ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2131f37938e0SEric Sandeen 	/*
2132f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2133f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2134f37938e0SEric Sandeen 	 * the devices in the system
2135f37938e0SEric Sandeen 	 */
21362ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
21372ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2138dcb2137cSChristoph Hellwig 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
2139f37938e0SEric Sandeen 
21402ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
214143eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
214235da5a7eSDavid Sterba 			    IO_TREE_BTREE_INODE_IO);
21432ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2144f37938e0SEric Sandeen 
21455c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2146adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
2147adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
2148adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
21492ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2150e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
2151dcb2137cSChristoph Hellwig 	fs_info->btree_inode = inode;
2152dcb2137cSChristoph Hellwig 
2153dcb2137cSChristoph Hellwig 	return 0;
2154f37938e0SEric Sandeen }
2155f37938e0SEric Sandeen 
2156ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2157ad618368SEric Sandeen {
2158ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2159129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
21607f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2161ad618368SEric Sandeen }
2162ad618368SEric Sandeen 
2163f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2164f9e92e40SEric Sandeen {
2165f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2166f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2167f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2168f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2169f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2170f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2171d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2172011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
2173f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2174f9e92e40SEric Sandeen }
2175f9e92e40SEric Sandeen 
2176d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
21772a458198SEric Sandeen {
2178f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21796f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21802a458198SEric Sandeen 
21812a458198SEric Sandeen 	fs_info->workers =
2182a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
2183a31b4a43SChristoph Hellwig 	fs_info->hipri_workers =
2184a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker-high",
2185cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21862a458198SEric Sandeen 
21872a458198SEric Sandeen 	fs_info->delalloc_workers =
2188cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2189cb001095SJeff Mahoney 				      flags, max_active, 2);
21902a458198SEric Sandeen 
21912a458198SEric Sandeen 	fs_info->flush_workers =
2192cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2193cb001095SJeff Mahoney 				      flags, max_active, 0);
21942a458198SEric Sandeen 
21952a458198SEric Sandeen 	fs_info->caching_workers =
2196cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21972a458198SEric Sandeen 
21982a458198SEric Sandeen 	fs_info->fixup_workers =
2199cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
22002a458198SEric Sandeen 
22012a458198SEric Sandeen 	fs_info->endio_workers =
2202d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
22032a458198SEric Sandeen 	fs_info->endio_meta_workers =
2204d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
2205385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
22062a458198SEric Sandeen 	fs_info->endio_write_workers =
2207cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2208cb001095SJeff Mahoney 				      max_active, 2);
2209fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
2210fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
22112a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2212cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2213cb001095SJeff Mahoney 				      max_active, 0);
22142a458198SEric Sandeen 	fs_info->delayed_workers =
2215cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2216cb001095SJeff Mahoney 				      max_active, 0);
22172a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2218cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2219b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2220b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
22212a458198SEric Sandeen 
2222a31b4a43SChristoph Hellwig 	if (!(fs_info->workers && fs_info->hipri_workers &&
2223a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
22242a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2225fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
22261a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
22272a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2228f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2229f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2230b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
22312a458198SEric Sandeen 		return -ENOMEM;
22322a458198SEric Sandeen 	}
22332a458198SEric Sandeen 
22342a458198SEric Sandeen 	return 0;
22352a458198SEric Sandeen }
22362a458198SEric Sandeen 
22376d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
22386d97c6e3SJohannes Thumshirn {
22396d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2240b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
22416d97c6e3SJohannes Thumshirn 
2242b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
22436d97c6e3SJohannes Thumshirn 
22446d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
22456d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2246b4e967beSDavid Sterba 			  csum_driver);
22476d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
22486d97c6e3SJohannes Thumshirn 	}
22496d97c6e3SJohannes Thumshirn 
22506d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
22516d97c6e3SJohannes Thumshirn 
225268d99ab0SChristoph Hellwig 	/*
225368d99ab0SChristoph Hellwig 	 * Check if the checksum implementation is a fast accelerated one.
225468d99ab0SChristoph Hellwig 	 * As-is this is a bit of a hack and should be replaced once the csum
225568d99ab0SChristoph Hellwig 	 * implementations provide that information themselves.
225668d99ab0SChristoph Hellwig 	 */
225768d99ab0SChristoph Hellwig 	switch (csum_type) {
225868d99ab0SChristoph Hellwig 	case BTRFS_CSUM_TYPE_CRC32:
225968d99ab0SChristoph Hellwig 		if (!strstr(crypto_shash_driver_name(csum_shash), "generic"))
226068d99ab0SChristoph Hellwig 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
226168d99ab0SChristoph Hellwig 		break;
226268d99ab0SChristoph Hellwig 	default:
226368d99ab0SChristoph Hellwig 		break;
226468d99ab0SChristoph Hellwig 	}
226568d99ab0SChristoph Hellwig 
2266c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2267c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2268c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
22696d97c6e3SJohannes Thumshirn 	return 0;
22706d97c6e3SJohannes Thumshirn }
22716d97c6e3SJohannes Thumshirn 
227263443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
227363443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
227463443bf5SEric Sandeen {
227563443bf5SEric Sandeen 	int ret;
2276789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
227763443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
227863443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
227963443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2280581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
228163443bf5SEric Sandeen 
228263443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2283f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
228463443bf5SEric Sandeen 		return -EIO;
228563443bf5SEric Sandeen 	}
228663443bf5SEric Sandeen 
228796dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
228896dfcb46SJosef Bacik 					 GFP_KERNEL);
228963443bf5SEric Sandeen 	if (!log_tree_root)
229063443bf5SEric Sandeen 		return -ENOMEM;
229163443bf5SEric Sandeen 
2292789d6a3aSQu Wenruo 	check.level = level;
2293789d6a3aSQu Wenruo 	check.transid = fs_info->generation + 1;
2294789d6a3aSQu Wenruo 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2295789d6a3aSQu Wenruo 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
229664c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2297f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22980eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
22998c38938cSJosef Bacik 		log_tree_root->node = NULL;
230000246528SJosef Bacik 		btrfs_put_root(log_tree_root);
23010eeff236SLiu Bo 		return ret;
23024eb150d6SQu Wenruo 	}
23034eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2304f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
230500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
230663443bf5SEric Sandeen 		return -EIO;
230763443bf5SEric Sandeen 	}
23084eb150d6SQu Wenruo 
230963443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
231063443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
231163443bf5SEric Sandeen 	if (ret) {
23120b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
231363443bf5SEric Sandeen 				      "Failed to recover log tree");
231400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
231563443bf5SEric Sandeen 		return ret;
231663443bf5SEric Sandeen 	}
231763443bf5SEric Sandeen 
2318bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
23196bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
232063443bf5SEric Sandeen 		if (ret)
232163443bf5SEric Sandeen 			return ret;
232263443bf5SEric Sandeen 	}
232363443bf5SEric Sandeen 
232463443bf5SEric Sandeen 	return 0;
232563443bf5SEric Sandeen }
232663443bf5SEric Sandeen 
2327abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2328abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2329abed4aaaSJosef Bacik 				      const char *name)
2330abed4aaaSJosef Bacik {
2331abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2332abed4aaaSJosef Bacik 	struct btrfs_root *root;
2333f7238e50SJosef Bacik 	u64 max_global_id = 0;
2334abed4aaaSJosef Bacik 	int ret;
2335abed4aaaSJosef Bacik 	struct btrfs_key key = {
2336abed4aaaSJosef Bacik 		.objectid = objectid,
2337abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2338abed4aaaSJosef Bacik 		.offset = 0,
2339abed4aaaSJosef Bacik 	};
2340abed4aaaSJosef Bacik 	bool found = false;
2341abed4aaaSJosef Bacik 
2342abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2343abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2344abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2345abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2346abed4aaaSJosef Bacik 		return 0;
2347abed4aaaSJosef Bacik 	}
2348abed4aaaSJosef Bacik 
2349abed4aaaSJosef Bacik 	while (1) {
2350abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2351abed4aaaSJosef Bacik 		if (ret < 0)
2352abed4aaaSJosef Bacik 			break;
2353abed4aaaSJosef Bacik 
2354abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2355abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2356abed4aaaSJosef Bacik 			if (ret) {
2357abed4aaaSJosef Bacik 				if (ret > 0)
2358abed4aaaSJosef Bacik 					ret = 0;
2359abed4aaaSJosef Bacik 				break;
2360abed4aaaSJosef Bacik 			}
2361abed4aaaSJosef Bacik 		}
2362abed4aaaSJosef Bacik 		ret = 0;
2363abed4aaaSJosef Bacik 
2364abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2365abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2366abed4aaaSJosef Bacik 			break;
2367abed4aaaSJosef Bacik 		btrfs_release_path(path);
2368abed4aaaSJosef Bacik 
2369f7238e50SJosef Bacik 		/*
2370f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2371f7238e50SJosef Bacik 		 * everybody.
2372f7238e50SJosef Bacik 		 */
2373f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2374f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2375f7238e50SJosef Bacik 
2376abed4aaaSJosef Bacik 		found = true;
2377abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2378abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2379abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2380abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2381abed4aaaSJosef Bacik 			break;
2382abed4aaaSJosef Bacik 		}
2383abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2384abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2385abed4aaaSJosef Bacik 		if (ret) {
2386abed4aaaSJosef Bacik 			btrfs_put_root(root);
2387abed4aaaSJosef Bacik 			break;
2388abed4aaaSJosef Bacik 		}
2389abed4aaaSJosef Bacik 		key.offset++;
2390abed4aaaSJosef Bacik 	}
2391abed4aaaSJosef Bacik 	btrfs_release_path(path);
2392abed4aaaSJosef Bacik 
2393f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2394f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2395f7238e50SJosef Bacik 
2396abed4aaaSJosef Bacik 	if (!found || ret) {
2397abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2398abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2399abed4aaaSJosef Bacik 
2400abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2401abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2402abed4aaaSJosef Bacik 		else
2403abed4aaaSJosef Bacik 			ret = 0;
2404abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2405abed4aaaSJosef Bacik 	}
2406abed4aaaSJosef Bacik 	return ret;
2407abed4aaaSJosef Bacik }
2408abed4aaaSJosef Bacik 
2409abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2410abed4aaaSJosef Bacik {
2411abed4aaaSJosef Bacik 	struct btrfs_path *path;
2412abed4aaaSJosef Bacik 	int ret = 0;
2413abed4aaaSJosef Bacik 
2414abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2415abed4aaaSJosef Bacik 	if (!path)
2416abed4aaaSJosef Bacik 		return -ENOMEM;
2417abed4aaaSJosef Bacik 
2418abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2419abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2420abed4aaaSJosef Bacik 	if (ret)
2421abed4aaaSJosef Bacik 		goto out;
2422abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2423abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2424abed4aaaSJosef Bacik 	if (ret)
2425abed4aaaSJosef Bacik 		goto out;
2426abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2427abed4aaaSJosef Bacik 		goto out;
2428abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2429abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2430abed4aaaSJosef Bacik 					 "free space");
2431abed4aaaSJosef Bacik out:
2432abed4aaaSJosef Bacik 	btrfs_free_path(path);
2433abed4aaaSJosef Bacik 	return ret;
2434abed4aaaSJosef Bacik }
2435abed4aaaSJosef Bacik 
24366bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
24374bbcaa64SEric Sandeen {
24386bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2439a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
24404bbcaa64SEric Sandeen 	struct btrfs_key location;
24414bbcaa64SEric Sandeen 	int ret;
24424bbcaa64SEric Sandeen 
24436bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
24446bccf3abSJeff Mahoney 
2445abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2446abed4aaaSJosef Bacik 	if (ret)
2447abed4aaaSJosef Bacik 		return ret;
2448abed4aaaSJosef Bacik 
24494bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
24504bbcaa64SEric Sandeen 	location.offset = 0;
24514bbcaa64SEric Sandeen 
24521c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
245314033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
245414033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
245514033b08SQu Wenruo 		if (IS_ERR(root)) {
245614033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
245714033b08SQu Wenruo 				ret = PTR_ERR(root);
245814033b08SQu Wenruo 				goto out;
245914033b08SQu Wenruo 			}
246014033b08SQu Wenruo 		} else {
246114033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
246214033b08SQu Wenruo 			fs_info->block_group_root = root;
246314033b08SQu Wenruo 		}
246414033b08SQu Wenruo 	}
246514033b08SQu Wenruo 
246614033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2467a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2468f50f4353SLiu Bo 	if (IS_ERR(root)) {
246942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2470f50f4353SLiu Bo 			ret = PTR_ERR(root);
2471f50f4353SLiu Bo 			goto out;
2472f50f4353SLiu Bo 		}
247342437a63SJosef Bacik 	} else {
2474a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2475a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
247642437a63SJosef Bacik 	}
2477820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2478a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2479a8d1b164SJohannes Thumshirn 	if (ret)
2480a8d1b164SJohannes Thumshirn 		goto out;
24814bbcaa64SEric Sandeen 
2482aeb935a4SQu Wenruo 	/*
2483aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2484aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2485aeb935a4SQu Wenruo 	 */
248656e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
248756e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2488aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
248942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2490aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2491aeb935a4SQu Wenruo 			goto out;
2492aeb935a4SQu Wenruo 		}
249342437a63SJosef Bacik 	} else {
2494aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2495aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
249642437a63SJosef Bacik 	}
2497aeb935a4SQu Wenruo 
24984bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2499a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2500a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2501a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2502afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2503a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25044bbcaa64SEric Sandeen 	}
25054bbcaa64SEric Sandeen 
25064bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2507a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2508a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
250942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2510a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25114bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2512f50f4353SLiu Bo 				goto out;
251342437a63SJosef Bacik 		}
25144bbcaa64SEric Sandeen 	} else {
2515a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2516a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25174bbcaa64SEric Sandeen 	}
25184bbcaa64SEric Sandeen 
25194bbcaa64SEric Sandeen 	return 0;
2520f50f4353SLiu Bo out:
2521f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2522f50f4353SLiu Bo 		   location.objectid, ret);
2523f50f4353SLiu Bo 	return ret;
25244bbcaa64SEric Sandeen }
25254bbcaa64SEric Sandeen 
2526069ec957SQu Wenruo /*
2527069ec957SQu Wenruo  * Real super block validation
2528069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2529069ec957SQu Wenruo  *
2530069ec957SQu Wenruo  * @sb:		super block to check
2531069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2532069ec957SQu Wenruo  * 		0	the primary (1st) sb
2533069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2534069ec957SQu Wenruo  * 	       -1	skip bytenr check
2535069ec957SQu Wenruo  */
2536a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2537069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
253821a852b0SQu Wenruo {
253921a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
254021a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
254121a852b0SQu Wenruo 	int ret = 0;
254221a852b0SQu Wenruo 
254321a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
254421a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
254521a852b0SQu Wenruo 		ret = -EINVAL;
254621a852b0SQu Wenruo 	}
254721a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
254821a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
254921a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
255021a852b0SQu Wenruo 		ret = -EINVAL;
255121a852b0SQu Wenruo 	}
255221a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
255321a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
255421a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
255521a852b0SQu Wenruo 		ret = -EINVAL;
255621a852b0SQu Wenruo 	}
255721a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
255821a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
255921a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
256021a852b0SQu Wenruo 		ret = -EINVAL;
256121a852b0SQu Wenruo 	}
256221a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
256321a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
256421a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
256521a852b0SQu Wenruo 		ret = -EINVAL;
256621a852b0SQu Wenruo 	}
256721a852b0SQu Wenruo 
256821a852b0SQu Wenruo 	/*
256921a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
257021a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
257121a852b0SQu Wenruo 	 */
257221a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
257321a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
257421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
257521a852b0SQu Wenruo 		ret = -EINVAL;
257621a852b0SQu Wenruo 	}
25770bb3eb3eSQu Wenruo 
25780bb3eb3eSQu Wenruo 	/*
25791a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
25801a42daabSQu Wenruo 	 *
25811a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
25821a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
25831a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
25841a42daabSQu Wenruo 	 * beginning.
25850bb3eb3eSQu Wenruo 	 */
25861a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
258721a852b0SQu Wenruo 		btrfs_err(fs_info,
25880bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
258921a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
259021a852b0SQu Wenruo 		ret = -EINVAL;
259121a852b0SQu Wenruo 	}
25920bb3eb3eSQu Wenruo 
259321a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
259421a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
259521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
259621a852b0SQu Wenruo 		ret = -EINVAL;
259721a852b0SQu Wenruo 	}
259821a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
259921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
260021a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
260121a852b0SQu Wenruo 		ret = -EINVAL;
260221a852b0SQu Wenruo 	}
260321a852b0SQu Wenruo 
260421a852b0SQu Wenruo 	/* Root alignment check */
260521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
260621a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
260721a852b0SQu Wenruo 			   btrfs_super_root(sb));
260821a852b0SQu Wenruo 		ret = -EINVAL;
260921a852b0SQu Wenruo 	}
261021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
261121a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
261221a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
261321a852b0SQu Wenruo 		ret = -EINVAL;
261421a852b0SQu Wenruo 	}
261521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
261621a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
261721a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
261821a852b0SQu Wenruo 		ret = -EINVAL;
261921a852b0SQu Wenruo 	}
262021a852b0SQu Wenruo 
2621aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2622aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2623aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2624aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2625aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2626aefd7f70SNikolay Borisov 		ret = -EINVAL;
2627aefd7f70SNikolay Borisov 	}
2628aefd7f70SNikolay Borisov 
2629aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2630aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2631aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2632aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2633aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2634aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2635aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2636aefd7f70SNikolay Borisov 		ret = -EINVAL;
2637aefd7f70SNikolay Borisov 	}
2638aefd7f70SNikolay Borisov 
26391c56ab99SQu Wenruo 	/*
26401c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
26411c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
26421c56ab99SQu Wenruo 	 */
26431c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
26441c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
26451c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
26461c56ab99SQu Wenruo 		btrfs_err(fs_info,
26471c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
26481c56ab99SQu Wenruo 		ret = -EINVAL;
26491c56ab99SQu Wenruo 	}
26501c56ab99SQu Wenruo 
2651de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
26527239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
265321a852b0SQu Wenruo 		btrfs_err(fs_info,
26547239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2655de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
265621a852b0SQu Wenruo 		ret = -EINVAL;
265721a852b0SQu Wenruo 	}
265821a852b0SQu Wenruo 
265921a852b0SQu Wenruo 	/*
266021a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
266121a852b0SQu Wenruo 	 * done later
266221a852b0SQu Wenruo 	 */
266321a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
266421a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
266521a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
266621a852b0SQu Wenruo 		ret = -EINVAL;
266721a852b0SQu Wenruo 	}
266821a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
266921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
267021a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
267121a852b0SQu Wenruo 		ret = -EINVAL;
267221a852b0SQu Wenruo 	}
267321a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
267421a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
267521a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
267621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
267721a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
267821a852b0SQu Wenruo 		ret = -EINVAL;
267921a852b0SQu Wenruo 	}
268021a852b0SQu Wenruo 
2681069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2682069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
268321a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
268421a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
268521a852b0SQu Wenruo 		ret = -EINVAL;
268621a852b0SQu Wenruo 	}
268721a852b0SQu Wenruo 
268821a852b0SQu Wenruo 	/*
268921a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
269021a852b0SQu Wenruo 	 * and one chunk
269121a852b0SQu Wenruo 	 */
269221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
269321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
269421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
269521a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
269621a852b0SQu Wenruo 		ret = -EINVAL;
269721a852b0SQu Wenruo 	}
269821a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
269921a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
270021a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
270121a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
270221a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
270321a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
270421a852b0SQu Wenruo 		ret = -EINVAL;
270521a852b0SQu Wenruo 	}
270621a852b0SQu Wenruo 
270721a852b0SQu Wenruo 	/*
270821a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
270921a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
271021a852b0SQu Wenruo 	 */
271121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
271221a852b0SQu Wenruo 		btrfs_warn(fs_info,
271321a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
271421a852b0SQu Wenruo 			btrfs_super_generation(sb),
271521a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
271621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
271721a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
271821a852b0SQu Wenruo 		btrfs_warn(fs_info,
271921a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
272021a852b0SQu Wenruo 			btrfs_super_generation(sb),
272121a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
272221a852b0SQu Wenruo 
272321a852b0SQu Wenruo 	return ret;
272421a852b0SQu Wenruo }
272521a852b0SQu Wenruo 
2726069ec957SQu Wenruo /*
2727069ec957SQu Wenruo  * Validation of super block at mount time.
2728069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2729069ec957SQu Wenruo  * flags will be skipped.
2730069ec957SQu Wenruo  */
2731069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2732069ec957SQu Wenruo {
2733a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2734069ec957SQu Wenruo }
2735069ec957SQu Wenruo 
273675cb857dSQu Wenruo /*
273775cb857dSQu Wenruo  * Validation of super block at write time.
273875cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
273975cb857dSQu Wenruo  * overwritten soon.
274075cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
274175cb857dSQu Wenruo  */
274275cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
274375cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
274475cb857dSQu Wenruo {
274575cb857dSQu Wenruo 	int ret;
274675cb857dSQu Wenruo 
2747a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
274875cb857dSQu Wenruo 	if (ret < 0)
274975cb857dSQu Wenruo 		goto out;
2750e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
275175cb857dSQu Wenruo 		ret = -EUCLEAN;
275275cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
275375cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
275475cb857dSQu Wenruo 		goto out;
275575cb857dSQu Wenruo 	}
275675cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
275775cb857dSQu Wenruo 		ret = -EUCLEAN;
275875cb857dSQu Wenruo 		btrfs_err(fs_info,
275975cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
276075cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
276175cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
276275cb857dSQu Wenruo 		goto out;
276375cb857dSQu Wenruo 	}
276475cb857dSQu Wenruo out:
276575cb857dSQu Wenruo 	if (ret < 0)
276675cb857dSQu Wenruo 		btrfs_err(fs_info,
276775cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
276875cb857dSQu Wenruo 	return ret;
276975cb857dSQu Wenruo }
277075cb857dSQu Wenruo 
2771bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2772bd676446SJosef Bacik {
2773789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2774789d6a3aSQu Wenruo 		.level = level,
2775789d6a3aSQu Wenruo 		.transid = gen,
2776789d6a3aSQu Wenruo 		.owner_root = root->root_key.objectid
2777789d6a3aSQu Wenruo 	};
2778bd676446SJosef Bacik 	int ret = 0;
2779bd676446SJosef Bacik 
2780789d6a3aSQu Wenruo 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2781bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2782bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2783bd676446SJosef Bacik 		root->node = NULL;
27844eb150d6SQu Wenruo 		return ret;
27854eb150d6SQu Wenruo 	}
27864eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2787bd676446SJosef Bacik 		free_extent_buffer(root->node);
2788bd676446SJosef Bacik 		root->node = NULL;
27894eb150d6SQu Wenruo 		return -EIO;
2790bd676446SJosef Bacik 	}
2791bd676446SJosef Bacik 
2792bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2793bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2794bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2795bd676446SJosef Bacik 	return ret;
2796bd676446SJosef Bacik }
2797bd676446SJosef Bacik 
2798bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2799bd676446SJosef Bacik {
2800bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2801bd676446SJosef Bacik 	u64 gen, bytenr;
2802bd676446SJosef Bacik 	int level, ret;
2803bd676446SJosef Bacik 
2804bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2805bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2806bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2807bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
28089c54e80dSJosef Bacik 	if (ret) {
2809bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2810bd676446SJosef Bacik 		return ret;
2811bd676446SJosef Bacik 	}
28129c54e80dSJosef Bacik 	return 0;
28139c54e80dSJosef Bacik }
28149c54e80dSJosef Bacik 
28156ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2816b8522a1eSNikolay Borisov {
28176ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2818b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2819b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2820b8522a1eSNikolay Borisov 	bool handle_error = false;
2821b8522a1eSNikolay Borisov 	int ret = 0;
2822b8522a1eSNikolay Borisov 	int i;
2823b8522a1eSNikolay Borisov 
2824b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2825b8522a1eSNikolay Borisov 		if (handle_error) {
2826b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2827b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2828b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2829b8522a1eSNikolay Borisov 
2830b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2831b8522a1eSNikolay Borisov 				break;
2832b8522a1eSNikolay Borisov 
2833b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2834b8522a1eSNikolay Borisov 
2835b8522a1eSNikolay Borisov 			/*
2836b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2837b8522a1eSNikolay Borisov 			 * valid
2838b8522a1eSNikolay Borisov 			 */
2839b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2840b8522a1eSNikolay Borisov 
2841b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2842b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2843b8522a1eSNikolay Borisov 
2844b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
28456ef108ddSNikolay Borisov 			backup_index = ret;
2846b8522a1eSNikolay Borisov 			if (ret < 0)
2847b8522a1eSNikolay Borisov 				return ret;
2848b8522a1eSNikolay Borisov 		}
2849b8522a1eSNikolay Borisov 
2850bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2851bd676446SJosef Bacik 		if (ret) {
2852217f5004SNikolay Borisov 			handle_error = true;
2853b8522a1eSNikolay Borisov 			continue;
2854b8522a1eSNikolay Borisov 		}
2855b8522a1eSNikolay Borisov 
2856336a0d8dSNikolay Borisov 		/*
2857336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2858336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2859336a0d8dSNikolay Borisov 		 */
2860453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2861b8522a1eSNikolay Borisov 		if (ret < 0) {
2862b8522a1eSNikolay Borisov 			handle_error = true;
2863b8522a1eSNikolay Borisov 			continue;
2864b8522a1eSNikolay Borisov 		}
2865b8522a1eSNikolay Borisov 
28666b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2867b8522a1eSNikolay Borisov 
2868b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2869b8522a1eSNikolay Borisov 		if (ret < 0) {
2870b8522a1eSNikolay Borisov 			handle_error = true;
2871b8522a1eSNikolay Borisov 			continue;
2872b8522a1eSNikolay Borisov 		}
2873b8522a1eSNikolay Borisov 
2874b8522a1eSNikolay Borisov 		/* All successful */
2875bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2876bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2877d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
28786ef108ddSNikolay Borisov 
28796ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
28806ef108ddSNikolay Borisov 		if (backup_index < 0) {
28816ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
28826ef108ddSNikolay Borisov 		} else {
28836ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
28846ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
28856ef108ddSNikolay Borisov 		}
2886b8522a1eSNikolay Borisov 		break;
2887b8522a1eSNikolay Borisov 	}
2888b8522a1eSNikolay Borisov 
2889b8522a1eSNikolay Borisov 	return ret;
2890b8522a1eSNikolay Borisov }
2891b8522a1eSNikolay Borisov 
28928260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2893eb60ceacSChris Mason {
2894fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
289501cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
28968fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2897facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
289824bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2899eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
290011833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2901eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2902a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2903fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
290424bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
29054cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2906ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2907f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
290847ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
290940ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2910afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2911c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2912f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2913abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2914d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2915f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
29167585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2917573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
29180bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
29195f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2920de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
292119c00ddcSChris Mason 
2922e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
29235a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
29248b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
29255f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
29263e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
29273e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
29283e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
29293e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
29303e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
29313e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
29323e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
29333e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2934e1489b4fSIoannis Angelakopoulos 
29350b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
29366324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2937f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
293847ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
293918bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2940afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2941bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2942bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
29433fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
29443fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2945bd647ce3SJosef Bacik #endif
2946c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
294766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
294866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
294966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
295066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
295166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
295266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
295366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2954ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2955ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2956ba2c4d4eSJosef Bacik 
2957771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
29584cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2959034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2960fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2961abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
296295ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
29639ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
29644cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2965a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2966f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
29678b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2968f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2969fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2970c8b97818SChris Mason 
2971b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2972b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
29730afbaf8cSChris Mason 
2974199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2975199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
297669fe2d75SJosef Bacik 
2977638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
297821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
297921adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
298021adbd5cSStefan Behrens #endif
2981779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
298257056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2983a2de733cSArne Jansen 
298416b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
298508dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
29860f9dd46cSJosef Bacik 
2987fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
298835da5a7eSDavid Sterba 			    IO_TREE_FS_EXCLUDED_EXTENTS);
298939279cc3SChris Mason 
29905a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2991e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2992925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2993a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2994a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
29951bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
29969e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2997c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
299876dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2999803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
3000fa9c0d79SChris Mason 
3001ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
3002f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
3003b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
3004416ac51dSArne Jansen 
3005fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3006fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3007fa9c0d79SChris Mason 
3008e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
3009f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
3010bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
30114854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
3012034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
30133768f368SChris Mason 
3014da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
3015da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
3016da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
3017ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
3018da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
3019da17066cSJeff Mahoney 
3020f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
3021f7b12a62SNaohiro Aota 
3022eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
3023eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
3024eede2bf3SOmar Sandoval 
302518bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
302618bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
30278260edbaSJosef Bacik }
30288260edbaSJosef Bacik 
30298260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
30308260edbaSJosef Bacik {
30318260edbaSJosef Bacik 	int ret;
30328260edbaSJosef Bacik 
30338260edbaSJosef Bacik 	fs_info->sb = sb;
30348260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
30358260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
30369e967495SFilipe Manana 
30375deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3038ae18c37aSJosef Bacik 	if (ret)
3039ae18c37aSJosef Bacik 		return ret;
3040ae18c37aSJosef Bacik 
3041ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3042ae18c37aSJosef Bacik 	if (ret)
3043c75e8394SJosef Bacik 		return ret;
3044ae18c37aSJosef Bacik 
3045ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3046ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3047ae18c37aSJosef Bacik 
3048ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3049ae18c37aSJosef Bacik 	if (ret)
3050c75e8394SJosef Bacik 		return ret;
3051ae18c37aSJosef Bacik 
3052ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3053ae18c37aSJosef Bacik 			GFP_KERNEL);
3054ae18c37aSJosef Bacik 	if (ret)
3055c75e8394SJosef Bacik 		return ret;
3056ae18c37aSJosef Bacik 
3057ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3058ae18c37aSJosef Bacik 					GFP_KERNEL);
3059c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3060c75e8394SJosef Bacik 		return -ENOMEM;
3061ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3062ae18c37aSJosef Bacik 
3063a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3064a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3065a0a1db70SFilipe Manana 
3066c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3067ae18c37aSJosef Bacik }
3068ae18c37aSJosef Bacik 
306997f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
307097f4dd09SNikolay Borisov {
30710d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
307297f4dd09SNikolay Borisov 	int ret;
307397f4dd09SNikolay Borisov 
307497f4dd09SNikolay Borisov 	/*
307597f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
307697f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
307797f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
307897f4dd09SNikolay Borisov 	 */
307997f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
308097f4dd09SNikolay Borisov 	if (ret < 0) {
3081c94bec2cSJosef Bacik 		if (ret != -EINTR)
3082c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3083c94bec2cSJosef Bacik 				   ret);
308497f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
308597f4dd09SNikolay Borisov 		return ret;
308697f4dd09SNikolay Borisov 	}
308797f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
308897f4dd09SNikolay Borisov }
308997f4dd09SNikolay Borisov 
309097f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
309197f4dd09SNikolay Borisov {
309297f4dd09SNikolay Borisov 	struct task_struct *task;
309397f4dd09SNikolay Borisov 
309497f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
309597f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
309697f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
309797f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
309897f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
309997f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
310097f4dd09SNikolay Borisov 		return PTR_ERR(task);
310197f4dd09SNikolay Borisov 	}
310297f4dd09SNikolay Borisov 
310397f4dd09SNikolay Borisov 	return 0;
310497f4dd09SNikolay Borisov }
310597f4dd09SNikolay Borisov 
310644c0ca21SBoris Burkov /*
31078cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
31088cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
31098cd29088SBoris Burkov  * code paths.
31108cd29088SBoris Burkov  */
31118cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
31128cd29088SBoris Burkov {
31138cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
31148b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
31158cd29088SBoris Burkov }
31168cd29088SBoris Burkov 
31178cd29088SBoris Burkov /*
311844c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
311944c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
312044c0ca21SBoris Burkov  */
312144c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
312244c0ca21SBoris Burkov {
312344c0ca21SBoris Burkov 	int ret;
312494846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
31258b228324SBoris Burkov 	bool clear_free_space_tree = false;
31268b228324SBoris Burkov 
31278b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
31288b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31298b228324SBoris Burkov 		clear_free_space_tree = true;
31308b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
31318b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
31328b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
31338b228324SBoris Burkov 		clear_free_space_tree = true;
31348b228324SBoris Burkov 	}
31358b228324SBoris Burkov 
31368b228324SBoris Burkov 	if (clear_free_space_tree) {
31378b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
31388b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
31398b228324SBoris Burkov 		if (ret) {
31408b228324SBoris Burkov 			btrfs_warn(fs_info,
31418b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
31428b228324SBoris Burkov 			goto out;
31438b228324SBoris Burkov 		}
31448b228324SBoris Burkov 	}
314544c0ca21SBoris Burkov 
31468d488a8cSFilipe Manana 	/*
31478d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
31488d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3149fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
31508d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
31518d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
31528d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
31538d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
31548d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
31558d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
31568d488a8cSFilipe Manana 	 */
31578d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
31588d488a8cSFilipe Manana 	if (ret)
31598d488a8cSFilipe Manana 		goto out;
31608d488a8cSFilipe Manana 
316144c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
316244c0ca21SBoris Burkov 	if (ret)
316344c0ca21SBoris Burkov 		goto out;
316444c0ca21SBoris Burkov 
31658f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
31668f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31678f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31688f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
31698f1c21d7SBoris Burkov 		goto out;
31708f1c21d7SBoris Burkov 	}
31718f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
31728f1c21d7SBoris Burkov 
317344c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
31747eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
317544c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
317644c0ca21SBoris Burkov 	if (ret < 0) {
317744c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
317844c0ca21SBoris Burkov 		goto out;
317944c0ca21SBoris Burkov 	}
318044c0ca21SBoris Burkov 
31815011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
31825011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31835011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
31845011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
31855011139aSBoris Burkov 		if (ret) {
31865011139aSBoris Burkov 			btrfs_warn(fs_info,
31875011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
31885011139aSBoris Burkov 			goto out;
31895011139aSBoris Burkov 		}
31905011139aSBoris Burkov 	}
31915011139aSBoris Burkov 
319294846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
319394846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
319494846229SBoris Burkov 		if (ret)
319594846229SBoris Burkov 			goto out;
319694846229SBoris Burkov 	}
319794846229SBoris Burkov 
319844c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
319944c0ca21SBoris Burkov 	if (ret)
320044c0ca21SBoris Burkov 		goto out;
320144c0ca21SBoris Burkov 
320244c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
320344c0ca21SBoris Burkov 	if (ret) {
320444c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
320544c0ca21SBoris Burkov 		goto out;
320644c0ca21SBoris Burkov 	}
320744c0ca21SBoris Burkov 
320844c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
320944c0ca21SBoris Burkov 
321044c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
321144c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
321244c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
321344c0ca21SBoris Burkov 		if (ret) {
321444c0ca21SBoris Burkov 			btrfs_warn(fs_info,
321544c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
321644c0ca21SBoris Burkov 			goto out;
321744c0ca21SBoris Burkov 		}
321844c0ca21SBoris Burkov 	}
321944c0ca21SBoris Burkov 
322044c0ca21SBoris Burkov out:
322144c0ca21SBoris Burkov 	return ret;
322244c0ca21SBoris Burkov }
322344c0ca21SBoris Burkov 
3224d7f67ac9SQu Wenruo /*
3225d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
3226d7f67ac9SQu Wenruo  *
32272ba48b20SQu Wenruo  * @is_rw_mount:	If the mount is read-write.
32282ba48b20SQu Wenruo  *
3229d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
3230d7f67ac9SQu Wenruo  * feature dependencies).
3231d7f67ac9SQu Wenruo  *
3232d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
3233d7f67ac9SQu Wenruo  * btrfs_validate_super().
3234d7f67ac9SQu Wenruo  *
3235d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3236d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3237d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3238d7f67ac9SQu Wenruo  */
32392ba48b20SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3240d7f67ac9SQu Wenruo {
3241d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3242d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3243d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3244d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3245d7f67ac9SQu Wenruo 
3246d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3247d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3248d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3249d7f67ac9SQu Wenruo 		    incompat);
3250d7f67ac9SQu Wenruo 		return -EINVAL;
3251d7f67ac9SQu Wenruo 	}
3252d7f67ac9SQu Wenruo 
3253d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3254d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3255d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3256d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3257d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3258d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3259d7f67ac9SQu Wenruo 		return -EINVAL;
3260d7f67ac9SQu Wenruo 	}
3261d7f67ac9SQu Wenruo 
3262d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3263d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3264d7f67ac9SQu Wenruo 
3265d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3266d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3267d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3268d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3269d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3270d7f67ac9SQu Wenruo 
3271d7f67ac9SQu Wenruo 	/*
3272d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3273d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3274d7f67ac9SQu Wenruo 	 */
3275d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3276d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3277d7f67ac9SQu Wenruo 
32782ba48b20SQu Wenruo 	if (compat_ro_unsupp && is_rw_mount) {
3279d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3280d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3281d7f67ac9SQu Wenruo 		       compat_ro);
3282d7f67ac9SQu Wenruo 		return -EINVAL;
3283d7f67ac9SQu Wenruo 	}
3284d7f67ac9SQu Wenruo 
3285d7f67ac9SQu Wenruo 	/*
3286d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3287d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3288d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3289d7f67ac9SQu Wenruo 	 */
3290d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3291d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3292d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3293d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3294d7f67ac9SQu Wenruo 			  compat_ro);
3295d7f67ac9SQu Wenruo 		return -EINVAL;
3296d7f67ac9SQu Wenruo 	}
3297d7f67ac9SQu Wenruo 
3298d7f67ac9SQu Wenruo 	/*
3299d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3300d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3301d7f67ac9SQu Wenruo 	 */
3302d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3303d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3304d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3305d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3306d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3307d7f67ac9SQu Wenruo 		return -EINVAL;
3308d7f67ac9SQu Wenruo 	}
3309d7f67ac9SQu Wenruo 
3310d7f67ac9SQu Wenruo 	/*
3311d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3312d7f67ac9SQu Wenruo 	 *
3313d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3314d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3315d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3316d7f67ac9SQu Wenruo 	 */
3317d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3318d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3319d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3320d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3321d7f67ac9SQu Wenruo 		return -EINVAL;
3322d7f67ac9SQu Wenruo 	}
3323d7f67ac9SQu Wenruo 
3324d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3325d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3326d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3327d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3328d7f67ac9SQu Wenruo 
3329d7f67ac9SQu Wenruo 	return 0;
3330d7f67ac9SQu Wenruo }
3331d7f67ac9SQu Wenruo 
3332ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3333ae18c37aSJosef Bacik 		      char *options)
3334ae18c37aSJosef Bacik {
3335ae18c37aSJosef Bacik 	u32 sectorsize;
3336ae18c37aSJosef Bacik 	u32 nodesize;
3337ae18c37aSJosef Bacik 	u32 stripesize;
3338ae18c37aSJosef Bacik 	u64 generation;
3339ae18c37aSJosef Bacik 	u64 features;
3340ae18c37aSJosef Bacik 	u16 csum_type;
3341ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3342ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3343ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3344ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3345ae18c37aSJosef Bacik 	int ret;
3346ae18c37aSJosef Bacik 	int level;
3347ae18c37aSJosef Bacik 
33488260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
33494871c33bSQu Wenruo 	if (ret)
3350ae18c37aSJosef Bacik 		goto fail;
335153b381b3SDavid Woodhouse 
3352ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3353ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3354ae18c37aSJosef Bacik 				     GFP_KERNEL);
3355ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3356ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3357ae18c37aSJosef Bacik 				      GFP_KERNEL);
3358ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3359ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
33604871c33bSQu Wenruo 		ret = -ENOMEM;
3361c75e8394SJosef Bacik 		goto fail;
3362ae18c37aSJosef Bacik 	}
3363ae18c37aSJosef Bacik 
3364dcb2137cSChristoph Hellwig 	ret = btrfs_init_btree_inode(sb);
33654871c33bSQu Wenruo 	if (ret)
3366c75e8394SJosef Bacik 		goto fail;
3367ae18c37aSJosef Bacik 
3368d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
33691104a885SDavid Sterba 
33701104a885SDavid Sterba 	/*
33711104a885SDavid Sterba 	 * Read super block and check the signature bytes only
33721104a885SDavid Sterba 	 */
3373d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
33748f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
33754871c33bSQu Wenruo 		ret = PTR_ERR(disk_super);
337616cdcec7SMiao Xie 		goto fail_alloc;
337720b45077SDave Young 	}
337839279cc3SChris Mason 
33791104a885SDavid Sterba 	/*
3380260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
33818dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
33828dc3f22cSJohannes Thumshirn 	 */
33838f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
338451bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
33858dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
338651bce6c9SJohannes Thumshirn 			  csum_type);
33874871c33bSQu Wenruo 		ret = -EINVAL;
33888f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33898dc3f22cSJohannes Thumshirn 		goto fail_alloc;
33908dc3f22cSJohannes Thumshirn 	}
33918dc3f22cSJohannes Thumshirn 
339283c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
339383c68bbcSSu Yue 
33946d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
33956d97c6e3SJohannes Thumshirn 	if (ret) {
33968f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33976d97c6e3SJohannes Thumshirn 		goto fail_alloc;
33986d97c6e3SJohannes Thumshirn 	}
33996d97c6e3SJohannes Thumshirn 
34008dc3f22cSJohannes Thumshirn 	/*
34011104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
34021104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
34031104a885SDavid Sterba 	 */
34043d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
340505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
34064871c33bSQu Wenruo 		ret = -EINVAL;
34078f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3408141386e1SJosef Bacik 		goto fail_alloc;
34091104a885SDavid Sterba 	}
34101104a885SDavid Sterba 
34111104a885SDavid Sterba 	/*
34121104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
34131104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
34141104a885SDavid Sterba 	 * the whole block of INFO_SIZE
34151104a885SDavid Sterba 	 */
34168f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
34178f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
34185f39d397SChris Mason 
3419fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3420fbc6feaeSNikolay Borisov 
34210b86a832SChris Mason 
3422fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3423fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3424fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3425fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3426fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3427fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3428fbc6feaeSNikolay Borisov 	}
3429fbc6feaeSNikolay Borisov 
3430fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3431fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3432de37aa51SNikolay Borisov 
3433069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
34341104a885SDavid Sterba 	if (ret) {
343505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
34364871c33bSQu Wenruo 		ret = -EINVAL;
3437141386e1SJosef Bacik 		goto fail_alloc;
34381104a885SDavid Sterba 	}
34391104a885SDavid Sterba 
34404871c33bSQu Wenruo 	if (!btrfs_super_root(disk_super)) {
34414871c33bSQu Wenruo 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
34424871c33bSQu Wenruo 		ret = -EINVAL;
3443141386e1SJosef Bacik 		goto fail_alloc;
34444871c33bSQu Wenruo 	}
34450f7d52f4SChris Mason 
3446acce952bSliubo 	/* check FS state, whether FS is broken. */
344787533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
344887533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3449acce952bSliubo 
345075e7cb7fSLiu Bo 	/*
345175e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
345275e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
345375e7cb7fSLiu Bo 	 */
345475e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
345575e7cb7fSLiu Bo 
34566f93e834SAnand Jain 
34576f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
34586f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
34596f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
34606f93e834SAnand Jain 	stripesize = sectorsize;
34616f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
34626f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
34636f93e834SAnand Jain 
34646f93e834SAnand Jain 	fs_info->nodesize = nodesize;
34656f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
34666f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
34676f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
34686f93e834SAnand Jain 	fs_info->stripesize = stripesize;
34696f93e834SAnand Jain 
34702ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
34714871c33bSQu Wenruo 	if (ret)
3472141386e1SJosef Bacik 		goto fail_alloc;
3473dfe25020SChris Mason 
34742ba48b20SQu Wenruo 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
34754871c33bSQu Wenruo 	if (ret < 0)
3476141386e1SJosef Bacik 		goto fail_alloc;
3477f2b636e8SJosef Bacik 
34788481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
34798481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
34808481dd80SQu Wenruo 
34819f73f1aeSQu Wenruo 		/*
34829f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
34839f73f1aeSQu Wenruo 		 * going to be deprecated.
34849f73f1aeSQu Wenruo 		 *
34859f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
34869f73f1aeSQu Wenruo 		 */
34879f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
34889f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
34899f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
34909f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
34919f73f1aeSQu Wenruo 
349295ea0486SQu Wenruo 		btrfs_warn(fs_info,
349395ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
34940bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
34958481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
34964871c33bSQu Wenruo 		if (!subpage_info) {
34974871c33bSQu Wenruo 			ret = -ENOMEM;
34988481dd80SQu Wenruo 			goto fail_alloc;
34994871c33bSQu Wenruo 		}
35008481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
35018481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3502c8050b3bSQu Wenruo 	}
35030bb3eb3eSQu Wenruo 
3504d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
35054871c33bSQu Wenruo 	if (ret)
35060dc3b84aSJosef Bacik 		goto fail_sb_buffer;
35074543df7eSChris Mason 
35089e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
35099e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
35104575c9ccSChris Mason 
3511a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3512a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3513de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3514db94535dSChris Mason 
3515925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
35166bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3517925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
351884eed90fSChris Mason 	if (ret) {
351905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
35205d4f98a2SYan Zheng 		goto fail_sb_buffer;
352184eed90fSChris Mason 	}
35220b86a832SChris Mason 
352384234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3524581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3525bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3526bd676446SJosef Bacik 			      generation, level);
3527bd676446SJosef Bacik 	if (ret) {
352805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3529af31f5e5SChris Mason 		goto fail_tree_roots;
353083121942SDavid Woodhouse 	}
35310b86a832SChris Mason 
3532e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3533c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3534c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3535e17cade2SChris Mason 
35365b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
35372b82032cSYan Zheng 	if (ret) {
353805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3539af31f5e5SChris Mason 		goto fail_tree_roots;
35402b82032cSYan Zheng 	}
35410b86a832SChris Mason 
35428dabb742SStefan Behrens 	/*
3543bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3544bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3545bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
35461a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3547bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
35488dabb742SStefan Behrens 	 */
3549bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3550d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
355105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
35524871c33bSQu Wenruo 		ret = -EIO;
3553a6b0d5c8SChris Mason 		goto fail_tree_roots;
3554a6b0d5c8SChris Mason 	}
3555a6b0d5c8SChris Mason 
3556b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
35574bbcaa64SEric Sandeen 	if (ret)
3558b8522a1eSNikolay Borisov 		goto fail_tree_roots;
35598929ecfaSYan, Zheng 
356075ec1db8SJosef Bacik 	/*
356173651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
356273651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
356373651042SNaohiro Aota 	 * zoned incompat feature flag set.
356473651042SNaohiro Aota 	 */
356573651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
356673651042SNaohiro Aota 	if (ret) {
356773651042SNaohiro Aota 		btrfs_err(fs_info,
35684871c33bSQu Wenruo 			  "zoned: failed to read device zone info: %d", ret);
356973651042SNaohiro Aota 		goto fail_block_groups;
357073651042SNaohiro Aota 	}
357173651042SNaohiro Aota 
357273651042SNaohiro Aota 	/*
357375ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
357475ec1db8SJosef Bacik 	 * check the generation here so we can set the
357575ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
357675ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
357775ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
357875ec1db8SJosef Bacik 	 * even though it was perfectly fine.
357975ec1db8SJosef Bacik 	 */
358075ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
358175ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
358275ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
358375ec1db8SJosef Bacik 
3584cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3585cf90d884SQu Wenruo 	if (ret) {
3586cf90d884SQu Wenruo 		btrfs_err(fs_info,
3587cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3588cf90d884SQu Wenruo 			  ret);
3589cf90d884SQu Wenruo 		goto fail_block_groups;
3590cf90d884SQu Wenruo 	}
359168310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
359268310a5eSIlya Dryomov 	if (ret) {
359305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
359468310a5eSIlya Dryomov 		goto fail_block_groups;
359568310a5eSIlya Dryomov 	}
359668310a5eSIlya Dryomov 
3597733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3598733f4fbbSStefan Behrens 	if (ret) {
359905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3600733f4fbbSStefan Behrens 		goto fail_block_groups;
3601733f4fbbSStefan Behrens 	}
3602733f4fbbSStefan Behrens 
36038dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
36048dabb742SStefan Behrens 	if (ret) {
360505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
36068dabb742SStefan Behrens 		goto fail_block_groups;
36078dabb742SStefan Behrens 	}
36088dabb742SStefan Behrens 
3609b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3610b70f5097SNaohiro Aota 	if (ret) {
3611b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3612b70f5097SNaohiro Aota 			  ret);
3613b70f5097SNaohiro Aota 		goto fail_block_groups;
3614b70f5097SNaohiro Aota 	}
3615b70f5097SNaohiro Aota 
3616c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3617b7c35e81SAnand Jain 	if (ret) {
361805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
361905135f59SDavid Sterba 				ret);
3620b7c35e81SAnand Jain 		goto fail_block_groups;
3621b7c35e81SAnand Jain 	}
3622b7c35e81SAnand Jain 
362396f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
36245ac1d209SJeff Mahoney 	if (ret) {
362505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3626b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
36275ac1d209SJeff Mahoney 	}
36285ac1d209SJeff Mahoney 
3629c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3630c59021f8Sliubo 	if (ret) {
363105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
36322365dd3cSAnand Jain 		goto fail_sysfs;
3633c59021f8Sliubo 	}
3634c59021f8Sliubo 
36355b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
36361b1d1f66SJosef Bacik 	if (ret) {
363705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
36382365dd3cSAnand Jain 		goto fail_sysfs;
36391b1d1f66SJosef Bacik 	}
36404330e183SQu Wenruo 
364116beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
364216beac87SNaohiro Aota 
36435c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
36445c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
364505135f59SDavid Sterba 		btrfs_warn(fs_info,
364652042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
36474871c33bSQu Wenruo 		ret = -EINVAL;
36482365dd3cSAnand Jain 		goto fail_sysfs;
3649292fd7fcSStefan Behrens 	}
36509078a3e1SChris Mason 
365133c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3652a74a4b97SChris Mason 					       "btrfs-cleaner");
36534871c33bSQu Wenruo 	if (IS_ERR(fs_info->cleaner_kthread)) {
36544871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->cleaner_kthread);
36552365dd3cSAnand Jain 		goto fail_sysfs;
36564871c33bSQu Wenruo 	}
3657a74a4b97SChris Mason 
3658a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3659a74a4b97SChris Mason 						   tree_root,
3660a74a4b97SChris Mason 						   "btrfs-transaction");
36614871c33bSQu Wenruo 	if (IS_ERR(fs_info->transaction_kthread)) {
36624871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->transaction_kthread);
36633f157a2fSChris Mason 		goto fail_cleaner;
36644871c33bSQu Wenruo 	}
3665a74a4b97SChris Mason 
3666583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3667c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3668583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3669c289811cSChris Mason 	}
3670c289811cSChris Mason 
3671572d9ab7SDavid Sterba 	/*
367263a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
367363a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
367463a7cb13SDavid Sterba 	 * nodiscard for the same mount.
367563a7cb13SDavid Sterba 	 */
367663a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
367763a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
367863a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
367963a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
368063a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
368163a7cb13SDavid Sterba 				   "auto enabling async discard");
368263a7cb13SDavid Sterba 	}
368363a7cb13SDavid Sterba 
368421adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
36850b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
36862ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
36870b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3688cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
368921adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
369021adbd5cSStefan Behrens 		if (ret)
369105135f59SDavid Sterba 			btrfs_warn(fs_info,
369205135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
369305135f59SDavid Sterba 				ret);
369421adbd5cSStefan Behrens 	}
369521adbd5cSStefan Behrens #endif
3696bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3697bcef60f2SArne Jansen 	if (ret)
3698bcef60f2SArne Jansen 		goto fail_trans_kthread;
369921adbd5cSStefan Behrens 
3700fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3701fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3702fd708b81SJosef Bacik 
370396da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
370496da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
37050b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3706e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
370763443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
37084871c33bSQu Wenruo 		if (ret)
370928c16cbbSWang Shilong 			goto fail_qgroup;
3710e556ce2cSYan Zheng 	}
37111a40e23bSZheng Yan 
371256e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
37133140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
37144871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->fs_root);
37154871c33bSQu Wenruo 		btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3716315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3717bcef60f2SArne Jansen 		goto fail_qgroup;
37183140c9a3SDan Carpenter 	}
3719c289811cSChris Mason 
3720bc98a42cSDavid Howells 	if (sb_rdonly(sb))
37218cd29088SBoris Burkov 		goto clear_oneshot;
37222b6ba629SIlya Dryomov 
372344c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
37242b6ba629SIlya Dryomov 	if (ret) {
37256bccf3abSJeff Mahoney 		close_ctree(fs_info);
37262b6ba629SIlya Dryomov 		return ret;
3727e3acc2a6SJosef Bacik 	}
3728b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3729b382a324SJan Schmidt 
373044c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
373144c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
373244c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
373305135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
373470f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
373570f80175SStefan Behrens 		if (ret) {
373605135f59SDavid Sterba 			btrfs_warn(fs_info,
373705135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
37386bccf3abSJeff Mahoney 			close_ctree(fs_info);
373970f80175SStefan Behrens 			return ret;
374070f80175SStefan Behrens 		}
3741f7a81ea4SStefan Behrens 	}
374294846229SBoris Burkov 
3743afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
374447ab2a6cSJosef Bacik 
3745b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3746b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3747b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3748b4be6aefSJosef Bacik 
37498cd29088SBoris Burkov clear_oneshot:
37508cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3751ad2b2c80SAl Viro 	return 0;
375239279cc3SChris Mason 
3753bcef60f2SArne Jansen fail_qgroup:
3754bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
37557c2ca468SChris Mason fail_trans_kthread:
37567c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
37572ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3758faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
37593f157a2fSChris Mason fail_cleaner:
3760a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
37617c2ca468SChris Mason 
37627c2ca468SChris Mason 	/*
37637c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
37647c2ca468SChris Mason 	 * kthreads
37657c2ca468SChris Mason 	 */
37667c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
37677c2ca468SChris Mason 
37682365dd3cSAnand Jain fail_sysfs:
37696618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
37702365dd3cSAnand Jain 
3771b7c35e81SAnand Jain fail_fsdev_sysfs:
3772b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3773b7c35e81SAnand Jain 
37741b1d1f66SJosef Bacik fail_block_groups:
377554067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3776af31f5e5SChris Mason 
3777af31f5e5SChris Mason fail_tree_roots:
37789e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
37799e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
37804273eaffSAnand Jain 	free_root_pointers(fs_info, true);
37812b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3782af31f5e5SChris Mason 
378339279cc3SChris Mason fail_sb_buffer:
37847abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
37855cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
378616cdcec7SMiao Xie fail_alloc:
3787586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3788586e46e2SIlya Dryomov 
37894543df7eSChris Mason 	iput(fs_info->btree_inode);
37907e662854SQinghuang Feng fail:
3791586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
37924871c33bSQu Wenruo 	ASSERT(ret < 0);
37934871c33bSQu Wenruo 	return ret;
3794eb60ceacSChris Mason }
3795663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3796eb60ceacSChris Mason 
3797314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3798f2984462SChris Mason {
3799314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3800314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3801314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3802314b6dd0SJohannes Thumshirn 	struct page *page;
3803442a4f63SStefan Behrens 
3804314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3805314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3806314b6dd0SJohannes Thumshirn 
3807314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3808fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3809314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3810cb3e217bSQu Wenruo 				btrfs_dev_name(device),
3811314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3812314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3813314b6dd0SJohannes Thumshirn 			SetPageError(page);
3814314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3815314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3816314b6dd0SJohannes Thumshirn 		} else {
3817314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3818f2984462SChris Mason 		}
3819314b6dd0SJohannes Thumshirn 
3820314b6dd0SJohannes Thumshirn 		put_page(page);
3821314b6dd0SJohannes Thumshirn 		unlock_page(page);
3822314b6dd0SJohannes Thumshirn 	}
3823314b6dd0SJohannes Thumshirn 
3824314b6dd0SJohannes Thumshirn 	bio_put(bio);
3825f2984462SChris Mason }
3826f2984462SChris Mason 
38278f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3828a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
382929c36d72SAnand Jain {
383029c36d72SAnand Jain 	struct btrfs_super_block *super;
38318f32380dSJohannes Thumshirn 	struct page *page;
383212659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
38338f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
383412659251SNaohiro Aota 	int ret;
383529c36d72SAnand Jain 
383612659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
383712659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
383812659251SNaohiro Aota 	if (ret == -ENOENT)
383912659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
384012659251SNaohiro Aota 	else if (ret)
384112659251SNaohiro Aota 		return ERR_PTR(ret);
384212659251SNaohiro Aota 
3843cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
38448f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
384529c36d72SAnand Jain 
3846a05d3c91SQu Wenruo 	if (drop_cache) {
3847a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3848a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3849a05d3c91SQu Wenruo 
3850a05d3c91SQu Wenruo 		/*
3851a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3852a05d3c91SQu Wenruo 		 * always read from the device.
3853a05d3c91SQu Wenruo 		 */
3854a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3855a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3856a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3857a05d3c91SQu Wenruo 	}
3858a05d3c91SQu Wenruo 
38598f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
38608f32380dSJohannes Thumshirn 	if (IS_ERR(page))
38618f32380dSJohannes Thumshirn 		return ERR_CAST(page);
386229c36d72SAnand Jain 
38638f32380dSJohannes Thumshirn 	super = page_address(page);
386496c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
386596c2e067SAnand Jain 		btrfs_release_disk_super(super);
386696c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
386796c2e067SAnand Jain 	}
386896c2e067SAnand Jain 
386912659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
38708f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
38718f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
387229c36d72SAnand Jain 	}
387329c36d72SAnand Jain 
38748f32380dSJohannes Thumshirn 	return super;
387529c36d72SAnand Jain }
387629c36d72SAnand Jain 
387729c36d72SAnand Jain 
38788f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3879a512bbf8SYan Zheng {
38808f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3881a512bbf8SYan Zheng 	int i;
3882a512bbf8SYan Zheng 	u64 transid = 0;
3883a512bbf8SYan Zheng 
3884a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3885a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3886a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3887a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3888a512bbf8SYan Zheng 	 */
3889a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3890a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
38918f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3892a512bbf8SYan Zheng 			continue;
3893a512bbf8SYan Zheng 
3894a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
38958f32380dSJohannes Thumshirn 			if (latest)
38968f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
38978f32380dSJohannes Thumshirn 
38988f32380dSJohannes Thumshirn 			latest = super;
3899a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3900a512bbf8SYan Zheng 		}
3901a512bbf8SYan Zheng 	}
390292fc03fbSAnand Jain 
39038f32380dSJohannes Thumshirn 	return super;
3904a512bbf8SYan Zheng }
3905a512bbf8SYan Zheng 
39064eedeb75SHisashi Hifumi /*
3907abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3908314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
39094eedeb75SHisashi Hifumi  *
3910abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3911abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3912abbb3b8eSDavid Sterba  * same for write and wait phases.
39134eedeb75SHisashi Hifumi  *
3914314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
39154eedeb75SHisashi Hifumi  */
3916a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3917abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3918a512bbf8SYan Zheng {
3919d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3920314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3921d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3922a512bbf8SYan Zheng 	int i;
3923a512bbf8SYan Zheng 	int errors = 0;
392412659251SNaohiro Aota 	int ret;
392512659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3926a512bbf8SYan Zheng 
3927a512bbf8SYan Zheng 	if (max_mirrors == 0)
3928a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3929a512bbf8SYan Zheng 
3930d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3931d5178578SJohannes Thumshirn 
3932a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3933314b6dd0SJohannes Thumshirn 		struct page *page;
3934314b6dd0SJohannes Thumshirn 		struct bio *bio;
3935314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3936314b6dd0SJohannes Thumshirn 
393712659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
393812659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
393912659251SNaohiro Aota 		if (ret == -ENOENT) {
394012659251SNaohiro Aota 			continue;
394112659251SNaohiro Aota 		} else if (ret < 0) {
394212659251SNaohiro Aota 			btrfs_err(device->fs_info,
394312659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
394412659251SNaohiro Aota 				i);
394512659251SNaohiro Aota 			errors++;
394612659251SNaohiro Aota 			continue;
394712659251SNaohiro Aota 		}
3948935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3949935e5cc9SMiao Xie 		    device->commit_total_bytes)
3950a512bbf8SYan Zheng 			break;
3951a512bbf8SYan Zheng 
395212659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3953a512bbf8SYan Zheng 
3954fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3955fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3956fd08001fSEric Biggers 				    sb->csum);
3957a512bbf8SYan Zheng 
3958314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3959314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3960314b6dd0SJohannes Thumshirn 		if (!page) {
3961fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3962314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3963f14d104dSDavid Sterba 			    bytenr);
3964634554dcSJosef Bacik 			errors++;
3965634554dcSJosef Bacik 			continue;
3966634554dcSJosef Bacik 		}
3967634554dcSJosef Bacik 
3968314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3969314b6dd0SJohannes Thumshirn 		get_page(page);
3970a512bbf8SYan Zheng 
3971314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3972314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3973a512bbf8SYan Zheng 
3974387125fcSChris Mason 		/*
3975314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3976314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3977314b6dd0SJohannes Thumshirn 		 * checking.
3978387125fcSChris Mason 		 */
397907888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
398007888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
398107888c66SChristoph Hellwig 				GFP_NOFS);
3982314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3983314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3984314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3985314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3986314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3987314b6dd0SJohannes Thumshirn 
3988314b6dd0SJohannes Thumshirn 		/*
3989314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3990314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3991314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3992314b6dd0SJohannes Thumshirn 		 */
39931b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3994314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3995314b6dd0SJohannes Thumshirn 
399658ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
399758ff51f1SChristoph Hellwig 		submit_bio(bio);
39988376d9e1SNaohiro Aota 
39998376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
40008376d9e1SNaohiro Aota 			errors++;
4001a512bbf8SYan Zheng 	}
4002a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
4003a512bbf8SYan Zheng }
4004a512bbf8SYan Zheng 
4005387125fcSChris Mason /*
4006abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
4007abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
4008abbb3b8eSDavid Sterba  *
4009314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
4010abbb3b8eSDavid Sterba  * date.
4011abbb3b8eSDavid Sterba  */
4012abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4013abbb3b8eSDavid Sterba {
4014abbb3b8eSDavid Sterba 	int i;
4015abbb3b8eSDavid Sterba 	int errors = 0;
4016b6a535faSHoward McLauchlan 	bool primary_failed = false;
401712659251SNaohiro Aota 	int ret;
4018abbb3b8eSDavid Sterba 	u64 bytenr;
4019abbb3b8eSDavid Sterba 
4020abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
4021abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4022abbb3b8eSDavid Sterba 
4023abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
4024314b6dd0SJohannes Thumshirn 		struct page *page;
4025314b6dd0SJohannes Thumshirn 
402612659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
402712659251SNaohiro Aota 		if (ret == -ENOENT) {
402812659251SNaohiro Aota 			break;
402912659251SNaohiro Aota 		} else if (ret < 0) {
403012659251SNaohiro Aota 			errors++;
403112659251SNaohiro Aota 			if (i == 0)
403212659251SNaohiro Aota 				primary_failed = true;
403312659251SNaohiro Aota 			continue;
403412659251SNaohiro Aota 		}
4035abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4036abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
4037abbb3b8eSDavid Sterba 			break;
4038abbb3b8eSDavid Sterba 
4039314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
4040314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
4041314b6dd0SJohannes Thumshirn 		if (!page) {
4042abbb3b8eSDavid Sterba 			errors++;
4043b6a535faSHoward McLauchlan 			if (i == 0)
4044b6a535faSHoward McLauchlan 				primary_failed = true;
4045abbb3b8eSDavid Sterba 			continue;
4046abbb3b8eSDavid Sterba 		}
4047314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4048314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4049314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4050abbb3b8eSDavid Sterba 			errors++;
4051b6a535faSHoward McLauchlan 			if (i == 0)
4052b6a535faSHoward McLauchlan 				primary_failed = true;
4053b6a535faSHoward McLauchlan 		}
4054abbb3b8eSDavid Sterba 
4055314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4056314b6dd0SJohannes Thumshirn 		put_page(page);
4057abbb3b8eSDavid Sterba 
4058314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4059314b6dd0SJohannes Thumshirn 		put_page(page);
4060abbb3b8eSDavid Sterba 	}
4061abbb3b8eSDavid Sterba 
4062b6a535faSHoward McLauchlan 	/* log error, force error return */
4063b6a535faSHoward McLauchlan 	if (primary_failed) {
4064b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4065b6a535faSHoward McLauchlan 			  device->devid);
4066b6a535faSHoward McLauchlan 		return -1;
4067b6a535faSHoward McLauchlan 	}
4068b6a535faSHoward McLauchlan 
4069abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4070abbb3b8eSDavid Sterba }
4071abbb3b8eSDavid Sterba 
4072abbb3b8eSDavid Sterba /*
4073387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4074387125fcSChris Mason  * for the barrier when it is done
4075387125fcSChris Mason  */
40764246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4077387125fcSChris Mason {
4078f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
4079387125fcSChris Mason 	complete(bio->bi_private);
4080387125fcSChris Mason }
4081387125fcSChris Mason 
4082387125fcSChris Mason /*
40834fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
40844fc6441aSAnand Jain  * done in the waiting counterpart.
4085387125fcSChris Mason  */
40864fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4087387125fcSChris Mason {
4088f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
4089387125fcSChris Mason 
4090a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4091a91cf0ffSWang Yugui 	/*
4092a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4093a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4094a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4095a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4096a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4097a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4098a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4099a91cf0ffSWang Yugui 	 * non-debug builds.
4100a91cf0ffSWang Yugui 	 */
410108e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
41024fc6441aSAnand Jain 		return;
4103a91cf0ffSWang Yugui #endif
4104387125fcSChris Mason 
4105f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
4106f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4107387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
4108387125fcSChris Mason 	init_completion(&device->flush_wait);
4109387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4110387125fcSChris Mason 
411158ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
411258ff51f1SChristoph Hellwig 	submit_bio(bio);
41131c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
41144fc6441aSAnand Jain }
4115387125fcSChris Mason 
41164fc6441aSAnand Jain /*
41174fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
41184fc6441aSAnand Jain  */
41198c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
41204fc6441aSAnand Jain {
4121f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
41224fc6441aSAnand Jain 
41231c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
412458efbc9fSOmar Sandoval 		return BLK_STS_OK;
41254fc6441aSAnand Jain 
41261c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
41272980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
41284fc6441aSAnand Jain 
41298c27cb35SLinus Torvalds 	return bio->bi_status;
4130387125fcSChris Mason }
4131387125fcSChris Mason 
4132d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4133401b41e5SAnand Jain {
41346528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4135401b41e5SAnand Jain 		return -EIO;
4136387125fcSChris Mason 	return 0;
4137387125fcSChris Mason }
4138387125fcSChris Mason 
4139387125fcSChris Mason /*
4140387125fcSChris Mason  * send an empty flush down to each device in parallel,
4141387125fcSChris Mason  * then wait for them
4142387125fcSChris Mason  */
4143387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4144387125fcSChris Mason {
4145387125fcSChris Mason 	struct list_head *head;
4146387125fcSChris Mason 	struct btrfs_device *dev;
41475af3e8ccSStefan Behrens 	int errors_wait = 0;
41484e4cbee9SChristoph Hellwig 	blk_status_t ret;
4149387125fcSChris Mason 
41501538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4151387125fcSChris Mason 	/* send down all the barriers */
4152387125fcSChris Mason 	head = &info->fs_devices->devices;
41531538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4154e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4155f88ba6a2SHidetoshi Seto 			continue;
4156cea7c8bfSAnand Jain 		if (!dev->bdev)
4157387125fcSChris Mason 			continue;
4158e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4159ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4160387125fcSChris Mason 			continue;
4161387125fcSChris Mason 
41624fc6441aSAnand Jain 		write_dev_flush(dev);
416358efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4164387125fcSChris Mason 	}
4165387125fcSChris Mason 
4166387125fcSChris Mason 	/* wait for all the barriers */
41671538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4168e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4169f88ba6a2SHidetoshi Seto 			continue;
4170387125fcSChris Mason 		if (!dev->bdev) {
41715af3e8ccSStefan Behrens 			errors_wait++;
4172387125fcSChris Mason 			continue;
4173387125fcSChris Mason 		}
4174e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4175ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4176387125fcSChris Mason 			continue;
4177387125fcSChris Mason 
41784fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4179401b41e5SAnand Jain 		if (ret) {
4180401b41e5SAnand Jain 			dev->last_flush_error = ret;
418166b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
418266b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
41835af3e8ccSStefan Behrens 			errors_wait++;
4184387125fcSChris Mason 		}
4185401b41e5SAnand Jain 	}
4186401b41e5SAnand Jain 
4187cea7c8bfSAnand Jain 	if (errors_wait) {
4188401b41e5SAnand Jain 		/*
4189401b41e5SAnand Jain 		 * At some point we need the status of all disks
4190401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4191401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4192401b41e5SAnand Jain 		 */
4193d10b82feSQu Wenruo 		return check_barrier_error(info);
4194401b41e5SAnand Jain 	}
4195387125fcSChris Mason 	return 0;
4196387125fcSChris Mason }
4197387125fcSChris Mason 
4198943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4199943c6e99SZhao Lei {
42008789f4feSZhao Lei 	int raid_type;
42018789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4202943c6e99SZhao Lei 
42038789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
42048789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
42058c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
42068789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
42078789f4feSZhao Lei 				    tolerated_failures);
4208943c6e99SZhao Lei 
42098789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
42108789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
42118789f4feSZhao Lei 			continue;
421241a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
42138789f4feSZhao Lei 			continue;
42148c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
42158789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
42168789f4feSZhao Lei 				    tolerated_failures);
42178789f4feSZhao Lei 	}
4218943c6e99SZhao Lei 
42198789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4220ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
42218789f4feSZhao Lei 		min_tolerated = 0;
42228789f4feSZhao Lei 	}
42238789f4feSZhao Lei 
42248789f4feSZhao Lei 	return min_tolerated;
4225943c6e99SZhao Lei }
4226943c6e99SZhao Lei 
4227eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4228f2984462SChris Mason {
4229e5e9a520SChris Mason 	struct list_head *head;
4230f2984462SChris Mason 	struct btrfs_device *dev;
4231a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4232f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4233f2984462SChris Mason 	int ret;
4234f2984462SChris Mason 	int do_barriers;
4235a236aed1SChris Mason 	int max_errors;
4236a236aed1SChris Mason 	int total_errors = 0;
4237a061fc8dSChris Mason 	u64 flags;
4238f2984462SChris Mason 
42390b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4240fed3b381SLiu Bo 
4241fed3b381SLiu Bo 	/*
4242fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4243fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4244fed3b381SLiu Bo 	 * been consistent on disk.
4245fed3b381SLiu Bo 	 */
4246fed3b381SLiu Bo 	if (max_mirrors == 0)
42470b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4248f2984462SChris Mason 
42490b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4250a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4251e5e9a520SChris Mason 
42520b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
42530b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
42540b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4255387125fcSChris Mason 
42565af3e8ccSStefan Behrens 	if (do_barriers) {
42570b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
42585af3e8ccSStefan Behrens 		if (ret) {
42595af3e8ccSStefan Behrens 			mutex_unlock(
42600b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
42610b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
42625af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
42635af3e8ccSStefan Behrens 			return ret;
42645af3e8ccSStefan Behrens 		}
42655af3e8ccSStefan Behrens 	}
4266387125fcSChris Mason 
42671538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4268dfe25020SChris Mason 		if (!dev->bdev) {
4269dfe25020SChris Mason 			total_errors++;
4270dfe25020SChris Mason 			continue;
4271dfe25020SChris Mason 		}
4272e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4273ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4274dfe25020SChris Mason 			continue;
4275dfe25020SChris Mason 
42762b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4277a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4278a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
42797df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4280935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4281ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4282ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4283a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4284a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4285a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4286a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
42877239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
42887239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4289a512bbf8SYan Zheng 
4290a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4291a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4292f2984462SChris Mason 
429375cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
429475cb857dSQu Wenruo 		if (ret < 0) {
429575cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
429675cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
429775cb857dSQu Wenruo 				"unexpected superblock corruption detected");
429875cb857dSQu Wenruo 			return -EUCLEAN;
429975cb857dSQu Wenruo 		}
430075cb857dSQu Wenruo 
4301abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4302a236aed1SChris Mason 		if (ret)
4303a236aed1SChris Mason 			total_errors++;
4304f2984462SChris Mason 	}
4305a236aed1SChris Mason 	if (total_errors > max_errors) {
43060b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4307d397712bSChris Mason 			  total_errors);
43080b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
430979787eaaSJeff Mahoney 
43109d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
43110b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
43120b246afaSJeff Mahoney 				      "%d errors while writing supers",
43130b246afaSJeff Mahoney 				      total_errors);
43149d565ba4SStefan Behrens 		return -EIO;
4315a236aed1SChris Mason 	}
4316f2984462SChris Mason 
4317a512bbf8SYan Zheng 	total_errors = 0;
43181538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4319dfe25020SChris Mason 		if (!dev->bdev)
4320dfe25020SChris Mason 			continue;
4321e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4322ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4323dfe25020SChris Mason 			continue;
4324dfe25020SChris Mason 
4325abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4326a512bbf8SYan Zheng 		if (ret)
43271259ab75SChris Mason 			total_errors++;
4328f2984462SChris Mason 	}
43290b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4330a236aed1SChris Mason 	if (total_errors > max_errors) {
43310b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
43320b246afaSJeff Mahoney 				      "%d errors while writing supers",
43330b246afaSJeff Mahoney 				      total_errors);
433479787eaaSJeff Mahoney 		return -EIO;
4335a236aed1SChris Mason 	}
4336f2984462SChris Mason 	return 0;
4337f2984462SChris Mason }
4338f2984462SChris Mason 
4339cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4340cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4341cb517eabSMiao Xie 				  struct btrfs_root *root)
43422619ba1fSChris Mason {
43434785e24fSJosef Bacik 	bool drop_ref = false;
43444785e24fSJosef Bacik 
4345fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4346fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4347fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4348fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
43494785e24fSJosef Bacik 		drop_ref = true;
4350fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
435176dda93cSYan, Zheng 
435284961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4353ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
43541c1ea4f7SLiu Bo 		if (root->reloc_root) {
435500246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
43561c1ea4f7SLiu Bo 			root->reloc_root = NULL;
43571c1ea4f7SLiu Bo 		}
43581c1ea4f7SLiu Bo 	}
43593321719eSLiu Bo 
43604785e24fSJosef Bacik 	if (drop_ref)
436100246528SJosef Bacik 		btrfs_put_root(root);
43622619ba1fSChris Mason }
43632619ba1fSChris Mason 
4364c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4365c146afadSYan Zheng {
4366fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4367fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4368fc7cbcd4SDavid Sterba 	int i = 0;
436965d33fd7SQu Wenruo 	int err = 0;
4370fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4371c146afadSYan Zheng 
4372c146afadSYan Zheng 	while (1) {
4373fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4374fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4375fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4376fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4377fc7cbcd4SDavid Sterba 		if (!ret) {
4378fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4379c146afadSYan Zheng 			break;
438065d33fd7SQu Wenruo 		}
4381fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
438266b4ffd1SJosef Bacik 
4383fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4384fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4385fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4386fc7cbcd4SDavid Sterba 				gang[i] = NULL;
438765d33fd7SQu Wenruo 				continue;
4388c146afadSYan Zheng 			}
4389fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4390fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4391fc7cbcd4SDavid Sterba 		}
4392fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4393fc7cbcd4SDavid Sterba 
4394fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4395fc7cbcd4SDavid Sterba 			if (!gang[i])
4396fc7cbcd4SDavid Sterba 				continue;
4397fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4398fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4399fc7cbcd4SDavid Sterba 			if (err)
44006989627dSJosef Bacik 				goto out;
4401fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4402fc7cbcd4SDavid Sterba 		}
4403fc7cbcd4SDavid Sterba 		root_objectid++;
4404c146afadSYan Zheng 	}
44056989627dSJosef Bacik out:
4406fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4407fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4408fc7cbcd4SDavid Sterba 		if (gang[i])
4409fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
441065d33fd7SQu Wenruo 	}
441165d33fd7SQu Wenruo 	return err;
4412c146afadSYan Zheng }
4413c146afadSYan Zheng 
44146bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4415c146afadSYan Zheng {
44166bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4417c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4418c146afadSYan Zheng 
44190b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
44202ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
44210b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
44220b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4423c71bf099SYan, Zheng 
4424c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
44250b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
44260b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4427c71bf099SYan, Zheng 
44287a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
44293612b495STsutomu Itoh 	if (IS_ERR(trans))
44303612b495STsutomu Itoh 		return PTR_ERR(trans);
44313a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4432c146afadSYan Zheng }
4433c146afadSYan Zheng 
443436c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
443536c86a9eSQu Wenruo {
443636c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
443736c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
443836c86a9eSQu Wenruo 	bool found = false;
443936c86a9eSQu Wenruo 
444036c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
444136c86a9eSQu Wenruo 		return;
444236c86a9eSQu Wenruo 
444336c86a9eSQu Wenruo 	/*
444436c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
444536c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
444636c86a9eSQu Wenruo 	 */
444736c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
444836c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
444936c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
445036c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
445136c86a9eSQu Wenruo 		u64 cur = 0;
445236c86a9eSQu Wenruo 		u64 found_start;
445336c86a9eSQu Wenruo 		u64 found_end;
445436c86a9eSQu Wenruo 
445536c86a9eSQu Wenruo 		found = true;
445636c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
445736c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
445836c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
445936c86a9eSQu Wenruo 			cur = found_end + 1;
446036c86a9eSQu Wenruo 		}
446136c86a9eSQu Wenruo 		btrfs_warn(fs_info,
446236c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
446336c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
446436c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
446536c86a9eSQu Wenruo 
446636c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
446736c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
446836c86a9eSQu Wenruo 		list_del_init(&trans->list);
446936c86a9eSQu Wenruo 
447036c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
447136c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
447236c86a9eSQu Wenruo 	}
447336c86a9eSQu Wenruo 	ASSERT(!found);
447436c86a9eSQu Wenruo }
447536c86a9eSQu Wenruo 
4476b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4477eb60ceacSChris Mason {
4478c146afadSYan Zheng 	int ret;
4479e089f05cSChris Mason 
4480afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
448131e70e52SFilipe Manana 
448231e70e52SFilipe Manana 	/*
44838a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
44848a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
44858a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
44868a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
44878a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
44888a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
44898a1f1e3dSFilipe Manana 	 * return 1.
44908a1f1e3dSFilipe Manana 	 */
44918a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
44928a1f1e3dSFilipe Manana 
44938a1f1e3dSFilipe Manana 	/*
449431e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
449531e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
449631e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
449731e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
449831e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
449931e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
450031e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
450131e70e52SFilipe Manana 	 */
450231e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4503d6fd0ae2SOmar Sandoval 	/*
4504d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4505d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4506d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4507d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4508d6fd0ae2SOmar Sandoval 	 */
4509d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4510a2135011SChris Mason 
45117343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4512d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
45137343dd61SJustin Maggard 
4514803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4515803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4516803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4517803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4518803b2f54SStefan Behrens 
4519837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4520aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4521837d5b6eSIlya Dryomov 
45228dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
45238dabb742SStefan Behrens 
4524aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
45254cb5300bSChris Mason 
45264cb5300bSChris Mason 	/* wait for any defraggers to finish */
45274cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
45284cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
45294cb5300bSChris Mason 
45304cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
453126176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
45324cb5300bSChris Mason 
4533a362bb86SFilipe Manana 	/*
4534a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4535a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4536a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4537a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4538a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4539a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4540a362bb86SFilipe Manana 	 * no one else to run iputs.
4541a362bb86SFilipe Manana 	 *
4542a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4543a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4544a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4545a362bb86SFilipe Manana 	 * through some other means.
4546a362bb86SFilipe Manana 	 *
4547a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4548a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4549a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4550a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4551a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4552a362bb86SFilipe Manana 	 */
4553a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4554a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4555a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4556a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4557a362bb86SFilipe Manana 
455821c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
455957056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4560576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
456121c7e756SMiao Xie 
4562b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4563b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4564b0643e59SDennis Zhou 
4565bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4566e44163e1SJeff Mahoney 		/*
4567d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4568d6fd0ae2SOmar Sandoval 		 * unused block groups.
4569e44163e1SJeff Mahoney 		 */
45700b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4571e44163e1SJeff Mahoney 
4572f0cc2cd7SFilipe Manana 		/*
4573f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4574f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4575f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4576f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4577f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4578f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4579f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4580f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4581f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4582f0cc2cd7SFilipe Manana 		 */
4583f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4584f0cc2cd7SFilipe Manana 
45856bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4586d397712bSChris Mason 		if (ret)
458704892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4588c146afadSYan Zheng 	}
4589ed2ff2cbSChris Mason 
459084961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
45912ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4592acce952bSliubo 
4593e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4594e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
45958929ecfaSYan, Zheng 
4596e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4597afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4598f25784b3SYan Zheng 
45995958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
46005958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
46015958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
46025958253cSQu Wenruo 	}
46035958253cSQu Wenruo 
460404892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4605fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4606bcef60f2SArne Jansen 
4607963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
460804892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4609963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4610b0c68f8bSChris Mason 	}
461131153d81SYan Zheng 
46125deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
46134297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
46145deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
46154297ff84SJosef Bacik 
46166618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4617b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
46185ac1d209SJeff Mahoney 
46191a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
46201a4319ccSLiu Bo 
4621de348ee0SWang Shilong 	/*
4622de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4623de348ee0SWang Shilong 	 * submit after we stopping all workers.
4624de348ee0SWang Shilong 	 */
4625de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
462696192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
462796192499SJosef Bacik 
46280a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
462936c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
46300a31daa4SFilipe Manana 
4631afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
46324273eaffSAnand Jain 	free_root_pointers(fs_info, true);
46338c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
46349ad6b7bcSChris Mason 
46354e19443dSJosef Bacik 	/*
46364e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
46374e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
46384e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
46394e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
46404e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
46414e19443dSJosef Bacik 	 */
46424e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
46434e19443dSJosef Bacik 
464413e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4645d6bfde87SChris Mason 
464621adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
46470b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
46482ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
464921adbd5cSStefan Behrens #endif
465021adbd5cSStefan Behrens 
46510b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
465268c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4653eb60ceacSChris Mason }
4654eb60ceacSChris Mason 
4655b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4656b9fab919SChris Mason 			  int atomic)
4657ccd467d6SChris Mason {
46581259ab75SChris Mason 	int ret;
4659727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
46601259ab75SChris Mason 
46610b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
46621259ab75SChris Mason 	if (!ret)
46631259ab75SChris Mason 		return ret;
46641259ab75SChris Mason 
46651259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4666b9fab919SChris Mason 				    parent_transid, atomic);
4667b9fab919SChris Mason 	if (ret == -EAGAIN)
4668b9fab919SChris Mason 		return ret;
46691259ab75SChris Mason 	return !ret;
46705f39d397SChris Mason }
46716702ed49SChris Mason 
46725f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
46735f39d397SChris Mason {
46742f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
46755f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4676b9473439SChris Mason 	int was_dirty;
4677b4ce94deSChris Mason 
467806ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
467906ea65a3SJosef Bacik 	/*
468006ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
468152042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
468206ea65a3SJosef Bacik 	 * outside of the sanity tests.
468306ea65a3SJosef Bacik 	 */
4684b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
468506ea65a3SJosef Bacik 		return;
468606ea65a3SJosef Bacik #endif
468749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
46880b246afaSJeff Mahoney 	if (transid != fs_info->generation)
46895d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
46900b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
46910b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4692e2d84521SMiao Xie 	if (!was_dirty)
4693104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4694e2d84521SMiao Xie 					 buf->len,
46950b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
46961f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
469769fc6cbbSQu Wenruo 	/*
469869fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
469969fc6cbbSQu Wenruo 	 * but item data not updated.
470069fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
470169fc6cbbSQu Wenruo 	 */
470269fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4703cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4704a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
47051f21ef0aSFilipe Manana 		ASSERT(0);
47061f21ef0aSFilipe Manana 	}
47071f21ef0aSFilipe Manana #endif
4708eb60ceacSChris Mason }
4709eb60ceacSChris Mason 
47102ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4711b53d3f5dSLiu Bo 					int flush_delayed)
471235b7e476SChris Mason {
4713188de649SChris Mason 	/*
4714188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4715188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4716188de649SChris Mason 	 */
4717e2d84521SMiao Xie 	int ret;
4718d6bfde87SChris Mason 
47196933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4720d6bfde87SChris Mason 		return;
4721d6bfde87SChris Mason 
4722b53d3f5dSLiu Bo 	if (flush_delayed)
47232ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
472416cdcec7SMiao Xie 
4725d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4726d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4727d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4728e2d84521SMiao Xie 	if (ret > 0) {
47290b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
473016cdcec7SMiao Xie 	}
473116cdcec7SMiao Xie }
473216cdcec7SMiao Xie 
47332ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
473416cdcec7SMiao Xie {
47352ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
473635b7e476SChris Mason }
4737b53d3f5dSLiu Bo 
47382ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4739b53d3f5dSLiu Bo {
47402ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4741d6bfde87SChris Mason }
47426b80053dSChris Mason 
47432ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4744acce952bSliubo {
4745fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4746fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4747fe816d0fSNikolay Borisov 
47480b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
47492ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
47500b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4751acce952bSliubo 
47520b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
47530b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4754acce952bSliubo }
4755acce952bSliubo 
4756ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4757ef67963dSJosef Bacik {
4758fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4759fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4760fc7cbcd4SDavid Sterba 	int ret;
4761ef67963dSJosef Bacik 
4762fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4763fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4764fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4765fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4766fc7cbcd4SDavid Sterba 		int i;
4767ef67963dSJosef Bacik 
4768fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4769fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4770fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4771fc7cbcd4SDavid Sterba 
4772fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4773fc7cbcd4SDavid Sterba 			if (!gang[i])
4774ef67963dSJosef Bacik 				continue;
4775fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4776fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4777fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4778ef67963dSJosef Bacik 		}
4779fc7cbcd4SDavid Sterba 		root_objectid++;
4780fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4781ef67963dSJosef Bacik 	}
4782fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4783ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4784ef67963dSJosef Bacik }
4785ef67963dSJosef Bacik 
4786143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4787acce952bSliubo {
4788acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4789acce952bSliubo 
4790199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4791779880efSJosef Bacik 	/*
4792779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4793779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4794779880efSJosef Bacik 	 */
4795199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4796779880efSJosef Bacik 			    root_extent_list)
4797779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4798199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4799199c2a9cSMiao Xie }
4800199c2a9cSMiao Xie 
4801199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4802199c2a9cSMiao Xie {
4803199c2a9cSMiao Xie 	struct btrfs_root *root;
4804199c2a9cSMiao Xie 	struct list_head splice;
4805199c2a9cSMiao Xie 
4806199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4807199c2a9cSMiao Xie 
4808199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4809199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4810199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4811199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4812199c2a9cSMiao Xie 					ordered_root);
48131de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
48141de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4815199c2a9cSMiao Xie 
48162a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4817199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4818199c2a9cSMiao Xie 
48192a85d9caSLiu Bo 		cond_resched();
48202a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4821199c2a9cSMiao Xie 	}
4822199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
482374d5d229SJosef Bacik 
482474d5d229SJosef Bacik 	/*
482574d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
482674d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
482774d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
482874d5d229SJosef Bacik 	 * actually get run and error out properly.
482974d5d229SJosef Bacik 	 */
483074d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4831acce952bSliubo }
4832acce952bSliubo 
483335a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
48342ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4835acce952bSliubo {
4836acce952bSliubo 	struct rb_node *node;
4837acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4838acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4839acce952bSliubo 	int ret = 0;
4840acce952bSliubo 
4841acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4842acce952bSliubo 
4843acce952bSliubo 	spin_lock(&delayed_refs->lock);
4844d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4845cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4846b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4847acce952bSliubo 		return ret;
4848acce952bSliubo 	}
4849acce952bSliubo 
48505c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4851d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
48520e0adbcfSJosef Bacik 		struct rb_node *n;
4853e78417d1SJosef Bacik 		bool pin_bytes = false;
4854acce952bSliubo 
4855d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4856d7df2c79SJosef Bacik 				href_node);
48573069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4858b939d1abSJosef Bacik 			continue;
48593069bd26SJosef Bacik 
4860d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4861e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
48620e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
48630e0adbcfSJosef Bacik 				       ref_node);
4864d7df2c79SJosef Bacik 			ref->in_tree = 0;
4865e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
48660e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
48671d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
48681d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4869d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4870d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4871d7df2c79SJosef Bacik 		}
487254067ae9SJosef Bacik 		if (head->must_insert_reserved)
4873e78417d1SJosef Bacik 			pin_bytes = true;
487478a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4875fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4876d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4877acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4878e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4879acce952bSliubo 
4880f603bb94SNikolay Borisov 		if (pin_bytes) {
4881f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4882f603bb94SNikolay Borisov 
4883f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4884f603bb94SNikolay Borisov 			BUG_ON(!cache);
4885f603bb94SNikolay Borisov 
4886f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4887f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4888f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4889f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4890f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4891f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4892f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4893f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4894f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4895f603bb94SNikolay Borisov 
4896f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4897f603bb94SNikolay Borisov 
4898f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4899f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4900f603bb94SNikolay Borisov 		}
490131890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4902d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4903acce952bSliubo 		cond_resched();
4904acce952bSliubo 		spin_lock(&delayed_refs->lock);
4905acce952bSliubo 	}
490681f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4907acce952bSliubo 
4908acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4909acce952bSliubo 
4910acce952bSliubo 	return ret;
4911acce952bSliubo }
4912acce952bSliubo 
4913143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4914acce952bSliubo {
4915acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4916acce952bSliubo 	struct list_head splice;
4917acce952bSliubo 
4918acce952bSliubo 	INIT_LIST_HEAD(&splice);
4919acce952bSliubo 
4920eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4921eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4922acce952bSliubo 
4923acce952bSliubo 	while (!list_empty(&splice)) {
4924fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4925eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4926acce952bSliubo 					       delalloc_inodes);
4927fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4928eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4929acce952bSliubo 
4930fe816d0fSNikolay Borisov 		/*
4931fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4932fe816d0fSNikolay Borisov 		 * meanwhile.
4933fe816d0fSNikolay Borisov 		 */
4934fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4935fe816d0fSNikolay Borisov 		if (inode) {
4936fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4937fe816d0fSNikolay Borisov 			iput(inode);
4938fe816d0fSNikolay Borisov 		}
4939eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4940acce952bSliubo 	}
4941eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4942eb73c1b7SMiao Xie }
4943eb73c1b7SMiao Xie 
4944eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4945eb73c1b7SMiao Xie {
4946eb73c1b7SMiao Xie 	struct btrfs_root *root;
4947eb73c1b7SMiao Xie 	struct list_head splice;
4948eb73c1b7SMiao Xie 
4949eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4950eb73c1b7SMiao Xie 
4951eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4952eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4953eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4954eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4955eb73c1b7SMiao Xie 					 delalloc_root);
495600246528SJosef Bacik 		root = btrfs_grab_root(root);
4957eb73c1b7SMiao Xie 		BUG_ON(!root);
4958eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4959eb73c1b7SMiao Xie 
4960eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
496100246528SJosef Bacik 		btrfs_put_root(root);
4962eb73c1b7SMiao Xie 
4963eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4964eb73c1b7SMiao Xie 	}
4965eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4966acce952bSliubo }
4967acce952bSliubo 
49682ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4969acce952bSliubo 					struct extent_io_tree *dirty_pages,
4970acce952bSliubo 					int mark)
4971acce952bSliubo {
4972acce952bSliubo 	int ret;
4973acce952bSliubo 	struct extent_buffer *eb;
4974acce952bSliubo 	u64 start = 0;
4975acce952bSliubo 	u64 end;
4976acce952bSliubo 
4977acce952bSliubo 	while (1) {
4978acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4979e6138876SJosef Bacik 					    mark, NULL);
4980acce952bSliubo 		if (ret)
4981acce952bSliubo 			break;
4982acce952bSliubo 
498391166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4984acce952bSliubo 		while (start <= end) {
49850b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
49860b246afaSJeff Mahoney 			start += fs_info->nodesize;
4987fd8b2b61SJosef Bacik 			if (!eb)
4988acce952bSliubo 				continue;
4989acce952bSliubo 
4990c4e54a65SJosef Bacik 			btrfs_tree_lock(eb);
4991c4e54a65SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4992190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(NULL, eb);
4993c4e54a65SJosef Bacik 			btrfs_tree_unlock(eb);
4994c4e54a65SJosef Bacik 
4995fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4996acce952bSliubo 		}
4997acce952bSliubo 	}
4998acce952bSliubo 
4999acce952bSliubo 	return ret;
5000acce952bSliubo }
5001acce952bSliubo 
50022ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
5003fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
5004acce952bSliubo {
5005acce952bSliubo 	u64 start;
5006acce952bSliubo 	u64 end;
5007acce952bSliubo 	int ret;
5008acce952bSliubo 
5009acce952bSliubo 	while (1) {
50100e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
50110e6ec385SFilipe Manana 
5012fcd5e742SLu Fengqi 		/*
5013fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
5014fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
5015fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5016fcd5e742SLu Fengqi 		 * the same extent range.
5017fcd5e742SLu Fengqi 		 */
5018fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
5019acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
50200e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
5021fcd5e742SLu Fengqi 		if (ret) {
5022fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5023acce952bSliubo 			break;
5024fcd5e742SLu Fengqi 		}
5025acce952bSliubo 
50260e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
50270e6ec385SFilipe Manana 		free_extent_state(cached_state);
50282ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
5029fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5030acce952bSliubo 		cond_resched();
5031acce952bSliubo 	}
5032acce952bSliubo 
5033acce952bSliubo 	return 0;
5034acce952bSliubo }
5035acce952bSliubo 
503632da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
5037c79a1751SLiu Bo {
5038c79a1751SLiu Bo 	struct inode *inode;
5039c79a1751SLiu Bo 
5040c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
5041c79a1751SLiu Bo 	if (inode) {
5042c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
5043c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
5044c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
5045c79a1751SLiu Bo 		iput(inode);
5046c79a1751SLiu Bo 	}
5047bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
5048c79a1751SLiu Bo 	btrfs_put_block_group(cache);
5049c79a1751SLiu Bo }
5050c79a1751SLiu Bo 
5051c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
50522ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5053c79a1751SLiu Bo {
505432da5386SDavid Sterba 	struct btrfs_block_group *cache;
5055c79a1751SLiu Bo 
5056c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5057c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5058c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
505932da5386SDavid Sterba 					 struct btrfs_block_group,
5060c79a1751SLiu Bo 					 dirty_list);
5061c79a1751SLiu Bo 
5062c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5063c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5064c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5065c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5066c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5067c79a1751SLiu Bo 		}
5068c79a1751SLiu Bo 
5069c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5070c79a1751SLiu Bo 		spin_lock(&cache->lock);
5071c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5072c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5073c79a1751SLiu Bo 
5074c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5075c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5076ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5077c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5078c79a1751SLiu Bo 	}
5079c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5080c79a1751SLiu Bo 
508145ae2c18SNikolay Borisov 	/*
508245ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
508345ae2c18SNikolay Borisov 	 * to use it without any locking
508445ae2c18SNikolay Borisov 	 */
5085c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5086c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
508732da5386SDavid Sterba 					 struct btrfs_block_group,
5088c79a1751SLiu Bo 					 io_list);
5089c79a1751SLiu Bo 
5090c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5091c79a1751SLiu Bo 		spin_lock(&cache->lock);
5092c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5093c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5094c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5095c79a1751SLiu Bo 	}
5096c79a1751SLiu Bo }
5097c79a1751SLiu Bo 
509849b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
50992ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
510049b25e05SJeff Mahoney {
5101bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5102bbbf7243SNikolay Borisov 
51032ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5104c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5105c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5106c79a1751SLiu Bo 
5107bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5108bbbf7243SNikolay Borisov 				 post_commit_list) {
5109bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5110bbbf7243SNikolay Borisov 	}
5111bbbf7243SNikolay Borisov 
51122ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
511349b25e05SJeff Mahoney 
51144a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
51150b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
511649b25e05SJeff Mahoney 
51174a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
51180b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
511949b25e05SJeff Mahoney 
5120ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
512167cde344SMiao Xie 
51222ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
512349b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5124fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
512549b25e05SJeff Mahoney 
5126d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
5127d3575156SNaohiro Aota 
51284a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
51294a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
513049b25e05SJeff Mahoney }
513149b25e05SJeff Mahoney 
51322ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5133acce952bSliubo {
5134acce952bSliubo 	struct btrfs_transaction *t;
5135acce952bSliubo 
51360b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5137acce952bSliubo 
51380b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
51390b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
51400b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5141724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5142724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
51439b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
51440b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
51452ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5146724e2315SJosef Bacik 			btrfs_put_transaction(t);
51470b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5148724e2315SJosef Bacik 			continue;
5149724e2315SJosef Bacik 		}
51500b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5151724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
51520b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5153724e2315SJosef Bacik 			/*
5154724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5155724e2315SJosef Bacik 			 * handle open currently for this transaction.
5156724e2315SJosef Bacik 			 */
5157724e2315SJosef Bacik 			wait_event(t->writer_wait,
5158724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5159724e2315SJosef Bacik 		} else {
51600b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5161724e2315SJosef Bacik 		}
51622ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5163724e2315SJosef Bacik 
51640b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
51650b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
51660b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5167724e2315SJosef Bacik 		list_del_init(&t->list);
51680b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5169a4abeea4SJosef Bacik 
5170724e2315SJosef Bacik 		btrfs_put_transaction(t);
51712e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
51720b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5173724e2315SJosef Bacik 	}
51740b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
51750b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5176ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5177ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
51780b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5179ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
51800b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5181acce952bSliubo 
5182acce952bSliubo 	return 0;
5183acce952bSliubo }
5184ec7d6dfdSNikolay Borisov 
5185453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5186ec7d6dfdSNikolay Borisov {
5187ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5188ec7d6dfdSNikolay Borisov 	int ret;
5189ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5190ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5191ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5192ec7d6dfdSNikolay Borisov 	int slot;
5193ec7d6dfdSNikolay Borisov 
5194ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5195ec7d6dfdSNikolay Borisov 	if (!path)
5196ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5197ec7d6dfdSNikolay Borisov 
5198ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5199ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5200ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5201ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5202ec7d6dfdSNikolay Borisov 	if (ret < 0)
5203ec7d6dfdSNikolay Borisov 		goto error;
5204ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5205ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5206ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5207ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5208ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
520923125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
521023125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5211ec7d6dfdSNikolay Borisov 	} else {
521223125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5213ec7d6dfdSNikolay Borisov 	}
5214ec7d6dfdSNikolay Borisov 	ret = 0;
5215ec7d6dfdSNikolay Borisov error:
5216ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5217ec7d6dfdSNikolay Borisov 	return ret;
5218ec7d6dfdSNikolay Borisov }
5219ec7d6dfdSNikolay Borisov 
5220543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5221ec7d6dfdSNikolay Borisov {
5222ec7d6dfdSNikolay Borisov 	int ret;
5223ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5224ec7d6dfdSNikolay Borisov 
52256b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5226ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5227ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5228ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5229ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5230ec7d6dfdSNikolay Borisov 		goto out;
5231ec7d6dfdSNikolay Borisov 	}
5232ec7d6dfdSNikolay Borisov 
523323125104SNikolay Borisov 	*objectid = root->free_objectid++;
5234ec7d6dfdSNikolay Borisov 	ret = 0;
5235ec7d6dfdSNikolay Borisov out:
5236ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5237ec7d6dfdSNikolay Borisov 	return ret;
5238ec7d6dfdSNikolay Borisov }
5239