xref: /openbmc/linux/fs/btrfs/disk-io.c (revision e256927b)
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"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41aac0023cSJosef Bacik #include "block-group.h"
42b0643e59SDennis Zhou #include "discard.h"
43f603bb94SNikolay Borisov #include "space-info.h"
44b70f5097SNaohiro Aota #include "zoned.h"
45139e8cd3SQu Wenruo #include "subpage.h"
46eb60ceacSChris Mason 
47319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
48319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
53319e4d06SQu Wenruo 
54143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
55acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
562ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
57143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
582ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
59acce952bSliubo 					struct extent_io_tree *dirty_pages,
60acce952bSliubo 					int mark);
612ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
62acce952bSliubo 				       struct extent_io_tree *pinned_extents);
632ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
642ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
65ce9adaa5SChris Mason 
66141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
67141386e1SJosef Bacik {
68141386e1SJosef Bacik 	if (fs_info->csum_shash)
69141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
70141386e1SJosef Bacik }
71141386e1SJosef Bacik 
72d352ac68SChris Mason /*
73d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
74d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
75d352ac68SChris Mason  * just before they are sent down the IO stack.
76d352ac68SChris Mason  */
7744b8bd7eSChris Mason struct async_submit_bio {
788896a08dSQu Wenruo 	struct inode *inode;
7944b8bd7eSChris Mason 	struct bio *bio;
80a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
8144b8bd7eSChris Mason 	int mirror_num;
821941b64bSQu Wenruo 
831941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
841941b64bSQu Wenruo 	u64 dio_file_offset;
858b712842SChris Mason 	struct btrfs_work work;
864e4cbee9SChristoph Hellwig 	blk_status_t status;
8744b8bd7eSChris Mason };
8844b8bd7eSChris Mason 
8985d4e461SChris Mason /*
902996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
91d352ac68SChris Mason  */
92c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
9319c00ddcSChris Mason {
94d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
957280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
96a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
97d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
9819c00ddcSChris Mason 	char *kaddr;
99e9be5a30SDavid Sterba 	int i;
100d5178578SJohannes Thumshirn 
101d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
102d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
103a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
104e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
105a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
10619c00ddcSChris Mason 
107e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
108e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
109e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
11019c00ddcSChris Mason 	}
11171a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
112d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
11319c00ddcSChris Mason }
11419c00ddcSChris Mason 
115d352ac68SChris Mason /*
116d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
117d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
118d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
119d352ac68SChris Mason  * in the wrong place.
120d352ac68SChris Mason  */
1211259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
122b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
123b9fab919SChris Mason 				 int atomic)
1241259ab75SChris Mason {
1252ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
1261259ab75SChris Mason 	int ret;
1271259ab75SChris Mason 
1281259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
1291259ab75SChris Mason 		return 0;
1301259ab75SChris Mason 
131b9fab919SChris Mason 	if (atomic)
132b9fab919SChris Mason 		return -EAGAIN;
133b9fab919SChris Mason 
134570eb97bSJosef Bacik 	lock_extent(io_tree, eb->start, eb->start + eb->len - 1, &cached_state);
1350b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
1361259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
1371259ab75SChris Mason 		ret = 0;
1381259ab75SChris Mason 		goto out;
1391259ab75SChris Mason 	}
14094647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
1418f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1428f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
14329549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1441259ab75SChris Mason 	ret = 1;
1450b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
14633958dc6SChris Mason out:
147570eb97bSJosef Bacik 	unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
148e43bbe5eSDavid Sterba 		      &cached_state);
1491259ab75SChris Mason 	return ret;
1501259ab75SChris Mason }
1511259ab75SChris Mason 
152e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
153e7e16f48SJohannes Thumshirn {
154e7e16f48SJohannes Thumshirn 	switch (csum_type) {
155e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1563951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1573831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
158352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
159e7e16f48SJohannes Thumshirn 		return true;
160e7e16f48SJohannes Thumshirn 	default:
161e7e16f48SJohannes Thumshirn 		return false;
162e7e16f48SJohannes Thumshirn 	}
163e7e16f48SJohannes Thumshirn }
164e7e16f48SJohannes Thumshirn 
165d352ac68SChris Mason /*
1661104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1671104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1681104a885SDavid Sterba  */
169ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
170ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
1711104a885SDavid Sterba {
1721104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
1731104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
17451bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
175d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
176d5178578SJohannes Thumshirn 
177d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1781104a885SDavid Sterba 
1791104a885SDavid Sterba 	/*
1801104a885SDavid Sterba 	 * The super_block structure does not span the whole
18151bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
18251bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1831104a885SDavid Sterba 	 */
184fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
185fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1861104a885SDavid Sterba 
18755fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
188e7e16f48SJohannes Thumshirn 		return 1;
1891104a885SDavid Sterba 
190e7e16f48SJohannes Thumshirn 	return 0;
1911104a885SDavid Sterba }
1921104a885SDavid Sterba 
193e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
194ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
195581c1760SQu Wenruo {
196e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
197581c1760SQu Wenruo 	int found_level;
198581c1760SQu Wenruo 	struct btrfs_key found_key;
199581c1760SQu Wenruo 	int ret;
200581c1760SQu Wenruo 
201581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
202581c1760SQu Wenruo 	if (found_level != level) {
20363489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
20463489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
205581c1760SQu Wenruo 		btrfs_err(fs_info,
206581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
207581c1760SQu Wenruo 			  eb->start, level, found_level);
208581c1760SQu Wenruo 		return -EIO;
209581c1760SQu Wenruo 	}
210581c1760SQu Wenruo 
211581c1760SQu Wenruo 	if (!first_key)
212581c1760SQu Wenruo 		return 0;
213581c1760SQu Wenruo 
2145d41be6fSQu Wenruo 	/*
2155d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
2165d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
2175d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
2185d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
2195d41be6fSQu Wenruo 	 */
2205d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
2215d41be6fSQu Wenruo 		return 0;
22262fdaa52SQu Wenruo 
22362fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
22462fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
22562fdaa52SQu Wenruo 		btrfs_err(fs_info,
22662fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
22762fdaa52SQu Wenruo 			  eb->start);
22862fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
22962fdaa52SQu Wenruo 		return -EUCLEAN;
23062fdaa52SQu Wenruo 	}
23162fdaa52SQu Wenruo 
232581c1760SQu Wenruo 	if (found_level)
233581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
234581c1760SQu Wenruo 	else
235581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
236581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
237581c1760SQu Wenruo 
238581c1760SQu Wenruo 	if (ret) {
23963489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
24063489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
241581c1760SQu Wenruo 		btrfs_err(fs_info,
242ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
243ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
244ff76a864SLiu Bo 			  first_key->type, first_key->offset,
245ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
246ff76a864SLiu Bo 			  found_key.offset);
247581c1760SQu Wenruo 	}
248581c1760SQu Wenruo 	return ret;
249581c1760SQu Wenruo }
250581c1760SQu Wenruo 
2511104a885SDavid Sterba /*
252d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
253d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
254581c1760SQu Wenruo  *
255581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
256581c1760SQu Wenruo  * @level:		expected level, mandatory check
257581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
258d352ac68SChris Mason  */
2596a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
260581c1760SQu Wenruo 			     u64 parent_transid, int level,
261581c1760SQu Wenruo 			     struct btrfs_key *first_key)
262f188591eSChris Mason {
2635ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
264f188591eSChris Mason 	struct extent_io_tree *io_tree;
265ea466794SJosef Bacik 	int failed = 0;
266f188591eSChris Mason 	int ret;
267f188591eSChris Mason 	int num_copies = 0;
268f188591eSChris Mason 	int mirror_num = 0;
269ea466794SJosef Bacik 	int failed_mirror = 0;
270f188591eSChris Mason 
2710b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
272f188591eSChris Mason 	while (1) {
273f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
274c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
275256dd1bbSStefan Behrens 		if (!ret) {
276581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
277b9fab919SChris Mason 						   parent_transid, 0))
278256dd1bbSStefan Behrens 				ret = -EIO;
279e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
280ff76a864SLiu Bo 						first_key, parent_transid))
281581c1760SQu Wenruo 				ret = -EUCLEAN;
282581c1760SQu Wenruo 			else
283581c1760SQu Wenruo 				break;
284256dd1bbSStefan Behrens 		}
285d397712bSChris Mason 
2860b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
287f188591eSChris Mason 					      eb->start, eb->len);
2884235298eSChris Mason 		if (num_copies == 1)
289ea466794SJosef Bacik 			break;
2904235298eSChris Mason 
2915cf1ab56SJosef Bacik 		if (!failed_mirror) {
2925cf1ab56SJosef Bacik 			failed = 1;
2935cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
2945cf1ab56SJosef Bacik 		}
2955cf1ab56SJosef Bacik 
296f188591eSChris Mason 		mirror_num++;
297ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
298ea466794SJosef Bacik 			mirror_num++;
299ea466794SJosef Bacik 
3004235298eSChris Mason 		if (mirror_num > num_copies)
301ea466794SJosef Bacik 			break;
302f188591eSChris Mason 	}
303ea466794SJosef Bacik 
304c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
30520a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
306ea466794SJosef Bacik 
307ea466794SJosef Bacik 	return ret;
308f188591eSChris Mason }
30919c00ddcSChris Mason 
310eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
311eca0f6f6SQu Wenruo {
312eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
313eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
314eca0f6f6SQu Wenruo 	int ret;
315eca0f6f6SQu Wenruo 
316eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
317eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
318eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
319eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
320eca0f6f6SQu Wenruo 
321eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
322eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
323eca0f6f6SQu Wenruo 	else
324eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
325eca0f6f6SQu Wenruo 
3263777369fSQu Wenruo 	if (ret < 0)
3273777369fSQu Wenruo 		goto error;
3283777369fSQu Wenruo 
3293777369fSQu Wenruo 	/*
3303777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
3313777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
3323777369fSQu Wenruo 	 */
3333777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
3343777369fSQu Wenruo 		ret = -EUCLEAN;
335eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
3363777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
3373777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
3383777369fSQu Wenruo 			  fs_info->last_trans_committed);
3393777369fSQu Wenruo 		goto error;
340eca0f6f6SQu Wenruo 	}
341eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
342eca0f6f6SQu Wenruo 
343eca0f6f6SQu Wenruo 	return 0;
3443777369fSQu Wenruo 
3453777369fSQu Wenruo error:
3463777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
3473777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
3483777369fSQu Wenruo 		  eb->start);
3493777369fSQu Wenruo 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
3503777369fSQu Wenruo 	return ret;
351eca0f6f6SQu Wenruo }
352eca0f6f6SQu Wenruo 
353eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
354eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
355eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
356eca0f6f6SQu Wenruo {
357eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
358eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
359eca0f6f6SQu Wenruo 	u64 cur;
360eca0f6f6SQu Wenruo 	int ret = 0;
361eca0f6f6SQu Wenruo 
362eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
363eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
364eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
365eca0f6f6SQu Wenruo 		bool uptodate;
366eca0f6f6SQu Wenruo 
367eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
368eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
369eca0f6f6SQu Wenruo 						       fs_info->nodesize);
370eca0f6f6SQu Wenruo 
37101cd3909SDavid Sterba 		/* A dirty eb shouldn't disappear from buffer_radix */
372eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
373eca0f6f6SQu Wenruo 			return -EUCLEAN;
374eca0f6f6SQu Wenruo 
375eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
376eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
377eca0f6f6SQu Wenruo 			return -EUCLEAN;
378eca0f6f6SQu Wenruo 		}
379eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
380eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
381eca0f6f6SQu Wenruo 			return -EUCLEAN;
382eca0f6f6SQu Wenruo 		}
383eca0f6f6SQu Wenruo 
384eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
385eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
386eca0f6f6SQu Wenruo 		if (ret < 0)
387eca0f6f6SQu Wenruo 			return ret;
388eca0f6f6SQu Wenruo 	}
389eca0f6f6SQu Wenruo 	return ret;
390eca0f6f6SQu Wenruo }
391eca0f6f6SQu Wenruo 
392d352ac68SChris Mason /*
393ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
394ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
395ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
396d352ac68SChris Mason  */
397ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
39819c00ddcSChris Mason {
399ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
4004eee4fa4SMiao Xie 	u64 start = page_offset(page);
40119c00ddcSChris Mason 	u64 found_start;
40219c00ddcSChris Mason 	struct extent_buffer *eb;
403eca0f6f6SQu Wenruo 
404fbca46ebSQu Wenruo 	if (fs_info->nodesize < PAGE_SIZE)
405eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
406f188591eSChris Mason 
4074f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4084f2de97aSJosef Bacik 	if (page != eb->pages[0])
4094f2de97aSJosef Bacik 		return 0;
4100f805531SAlex Lyakas 
41119c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
412d3575156SNaohiro Aota 
413d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
414d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
415d3575156SNaohiro Aota 		return 0;
416d3575156SNaohiro Aota 	}
417d3575156SNaohiro Aota 
4180f805531SAlex Lyakas 	/*
4190f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4200f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4210f805531SAlex Lyakas 	 */
4220f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4230f805531SAlex Lyakas 		return -EUCLEAN;
4240f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4250f805531SAlex Lyakas 		return -EUCLEAN;
4260f805531SAlex Lyakas 
427eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
42819c00ddcSChris Mason }
42919c00ddcSChris Mason 
430b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4312b82032cSYan Zheng {
432b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
433944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
43444880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
435944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
4362b82032cSYan Zheng 
4379a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
4389a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
4397239ff4bSNikolay Borisov 	/*
440944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
441944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
442944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
4437239ff4bSNikolay Borisov 	 */
444944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
4457239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
4467239ff4bSNikolay Borisov 	else
4477239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
4487239ff4bSNikolay Borisov 
449944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
450944d3f9fSNikolay Borisov 		return 0;
451944d3f9fSNikolay Borisov 
452944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
453944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
454944d3f9fSNikolay Borisov 			return 0;
455944d3f9fSNikolay Borisov 
456944d3f9fSNikolay Borisov 	return 1;
4572b82032cSYan Zheng }
4582b82032cSYan Zheng 
45977bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
46077bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
461ce9adaa5SChris Mason {
46277bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
463ce9adaa5SChris Mason 	u64 found_start;
46477bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
46577bf40a2SQu Wenruo 	u8 found_level;
4662996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
467dfd29eedSDavid Sterba 	const u8 *header_csum;
46877bf40a2SQu Wenruo 	int ret = 0;
469ea466794SJosef Bacik 
470ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
471727011e0SChris Mason 	if (found_start != eb->start) {
4728f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
4738f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
4748f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
475f188591eSChris Mason 		ret = -EIO;
47677bf40a2SQu Wenruo 		goto out;
477ce9adaa5SChris Mason 	}
478b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
4798f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
4808f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
4811259ab75SChris Mason 		ret = -EIO;
48277bf40a2SQu Wenruo 		goto out;
4831259ab75SChris Mason 	}
484ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
4851c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
4868f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
4878f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
4888f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
4891c24c3ceSJosef Bacik 		ret = -EIO;
49077bf40a2SQu Wenruo 		goto out;
4911c24c3ceSJosef Bacik 	}
492ce9adaa5SChris Mason 
493c67b3892SDavid Sterba 	csum_tree_block(eb, result);
494dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
495dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
496a826d6dcSJosef Bacik 
497dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
4982996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
4998f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5008f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
501dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
50235be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
50335be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5042996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
50577bf40a2SQu Wenruo 		goto out;
5062996e1f8SJohannes Thumshirn 	}
5072996e1f8SJohannes Thumshirn 
508a826d6dcSJosef Bacik 	/*
509a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
510a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
511a826d6dcSJosef Bacik 	 * return -EIO.
512a826d6dcSJosef Bacik 	 */
5131c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
514a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
515a826d6dcSJosef Bacik 		ret = -EIO;
516a826d6dcSJosef Bacik 	}
517ce9adaa5SChris Mason 
518813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
519053ab70fSLiu Bo 		ret = -EIO;
520053ab70fSLiu Bo 
5210b32f4bbSJosef Bacik 	if (!ret)
5220b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
52375391f0dSQu Wenruo 	else
52475391f0dSQu Wenruo 		btrfs_err(fs_info,
5258f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
5268f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
52777bf40a2SQu Wenruo out:
52877bf40a2SQu Wenruo 	return ret;
52977bf40a2SQu Wenruo }
53077bf40a2SQu Wenruo 
531371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
532371cdc07SQu Wenruo 				   int mirror)
533371cdc07SQu Wenruo {
534371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
535371cdc07SQu Wenruo 	struct extent_buffer *eb;
536371cdc07SQu Wenruo 	bool reads_done;
537371cdc07SQu Wenruo 	int ret = 0;
538371cdc07SQu Wenruo 
539371cdc07SQu Wenruo 	/*
540371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
541371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
542371cdc07SQu Wenruo 	 */
543371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
544371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
545371cdc07SQu Wenruo 
546371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
547371cdc07SQu Wenruo 	/*
548371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
549371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
550371cdc07SQu Wenruo 	 */
551371cdc07SQu Wenruo 	ASSERT(eb);
552371cdc07SQu Wenruo 
553371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
554371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
555371cdc07SQu Wenruo 	ASSERT(reads_done);
556371cdc07SQu Wenruo 
557371cdc07SQu Wenruo 	eb->read_mirror = mirror;
558371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
559371cdc07SQu Wenruo 		ret = -EIO;
560371cdc07SQu Wenruo 		goto err;
561371cdc07SQu Wenruo 	}
562371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
563371cdc07SQu Wenruo 	if (ret < 0)
564371cdc07SQu Wenruo 		goto err;
565371cdc07SQu Wenruo 
566371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
567371cdc07SQu Wenruo 
568371cdc07SQu Wenruo 	free_extent_buffer(eb);
569371cdc07SQu Wenruo 	return ret;
570371cdc07SQu Wenruo err:
571371cdc07SQu Wenruo 	/*
572371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
573371cdc07SQu Wenruo 	 * make sure it has something to decrement.
574371cdc07SQu Wenruo 	 */
575371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
576371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
577371cdc07SQu Wenruo 	free_extent_buffer(eb);
578371cdc07SQu Wenruo 	return ret;
579371cdc07SQu Wenruo }
580371cdc07SQu Wenruo 
581c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
58277bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
58377bf40a2SQu Wenruo 				   int mirror)
58477bf40a2SQu Wenruo {
58577bf40a2SQu Wenruo 	struct extent_buffer *eb;
58677bf40a2SQu Wenruo 	int ret = 0;
58777bf40a2SQu Wenruo 	int reads_done;
58877bf40a2SQu Wenruo 
58977bf40a2SQu Wenruo 	ASSERT(page->private);
590371cdc07SQu Wenruo 
591fbca46ebSQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
592371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
593371cdc07SQu Wenruo 
59477bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
59577bf40a2SQu Wenruo 
59677bf40a2SQu Wenruo 	/*
59777bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
59877bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
59977bf40a2SQu Wenruo 	 */
60077bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
60177bf40a2SQu Wenruo 
60277bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
60377bf40a2SQu Wenruo 	if (!reads_done)
60477bf40a2SQu Wenruo 		goto err;
60577bf40a2SQu Wenruo 
60677bf40a2SQu Wenruo 	eb->read_mirror = mirror;
60777bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
60877bf40a2SQu Wenruo 		ret = -EIO;
60977bf40a2SQu Wenruo 		goto err;
61077bf40a2SQu Wenruo 	}
61177bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
612ce9adaa5SChris Mason err:
61353b381b3SDavid Woodhouse 	if (ret) {
61453b381b3SDavid Woodhouse 		/*
61553b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
61653b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
61753b381b3SDavid Woodhouse 		 * to decrement
61853b381b3SDavid Woodhouse 		 */
61953b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6200b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
62153b381b3SDavid Woodhouse 	}
6220b32f4bbSJosef Bacik 	free_extent_buffer(eb);
62377bf40a2SQu Wenruo 
624f188591eSChris Mason 	return ret;
625ce9adaa5SChris Mason }
626ce9adaa5SChris Mason 
6274a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
6284a69a410SChris Mason {
6294a69a410SChris Mason 	struct async_submit_bio *async;
6304e4cbee9SChristoph Hellwig 	blk_status_t ret;
6314a69a410SChris Mason 
6324a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
6331941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
6341941b64bSQu Wenruo 				      async->dio_file_offset);
63579787eaaSJeff Mahoney 	if (ret)
6364e4cbee9SChristoph Hellwig 		async->status = ret;
6374a69a410SChris Mason }
6384a69a410SChris Mason 
63906ea01b1SDavid Sterba /*
64006ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
64106ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
64206ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
64306ea01b1SDavid Sterba  *
64406ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
64506ea01b1SDavid Sterba  * inserted into the tree.
64606ea01b1SDavid Sterba  */
6474a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
6488b712842SChris Mason {
649917f32a2SChristoph Hellwig 	struct async_submit_bio *async =
650917f32a2SChristoph Hellwig 		container_of(work, struct  async_submit_bio, work);
651917f32a2SChristoph Hellwig 	struct inode *inode = async->inode;
652917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(async->bio);
6534854ddd0SChris Mason 
654bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
6554e4cbee9SChristoph Hellwig 	if (async->status) {
656917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, async->status);
65779787eaaSJeff Mahoney 		return;
65879787eaaSJeff Mahoney 	}
65979787eaaSJeff Mahoney 
660ec39f769SChris Mason 	/*
661ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
662ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
663ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
664ec39f769SChris Mason 	 */
665ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
6661a722d8fSChristoph Hellwig 	btrfs_submit_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
6674a69a410SChris Mason }
6684a69a410SChris Mason 
6694a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
6704a69a410SChris Mason {
6714a69a410SChris Mason 	struct async_submit_bio *async;
6724a69a410SChris Mason 
6734a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
6748b712842SChris Mason 	kfree(async);
6758b712842SChris Mason }
6768b712842SChris Mason 
677ea1f0cedSChristoph Hellwig /*
678ea1f0cedSChristoph Hellwig  * Submit bio to an async queue.
679ea1f0cedSChristoph Hellwig  *
680ea1f0cedSChristoph Hellwig  * Retrun:
681ea1f0cedSChristoph Hellwig  * - true if the work has been succesfuly submitted
682ea1f0cedSChristoph Hellwig  * - false in case of error
683ea1f0cedSChristoph Hellwig  */
684ea1f0cedSChristoph Hellwig bool btrfs_wq_submit_bio(struct inode *inode, struct bio *bio, int mirror_num,
685ea1f0cedSChristoph Hellwig 			 u64 dio_file_offset,
686e288c080SDavid Sterba 			 extent_submit_bio_start_t *submit_bio_start)
68744b8bd7eSChris Mason {
6888896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
68944b8bd7eSChris Mason 	struct async_submit_bio *async;
69044b8bd7eSChris Mason 
69144b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
69244b8bd7eSChris Mason 	if (!async)
693ea1f0cedSChristoph Hellwig 		return false;
69444b8bd7eSChris Mason 
6958896a08dSQu Wenruo 	async->inode = inode;
69644b8bd7eSChris Mason 	async->bio = bio;
69744b8bd7eSChris Mason 	async->mirror_num = mirror_num;
6984a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
6994a69a410SChris Mason 
700a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
701a0cac0ecSOmar Sandoval 			run_one_async_free);
7024a69a410SChris Mason 
7031941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
7048c8bee1dSChris Mason 
7054e4cbee9SChristoph Hellwig 	async->status = 0;
70679787eaaSJeff Mahoney 
70767f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
708a31b4a43SChristoph Hellwig 		btrfs_queue_work(fs_info->hipri_workers, &async->work);
709a31b4a43SChristoph Hellwig 	else
7105cdc7ad3SQu Wenruo 		btrfs_queue_work(fs_info->workers, &async->work);
711ea1f0cedSChristoph Hellwig 	return true;
71244b8bd7eSChris Mason }
71344b8bd7eSChris Mason 
7144e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
715ce3ed71aSChris Mason {
7162c30c71bSKent Overstreet 	struct bio_vec *bvec;
717ce3ed71aSChris Mason 	struct btrfs_root *root;
7182b070cfeSChristoph Hellwig 	int ret = 0;
7196dc4f100SMing Lei 	struct bvec_iter_all iter_all;
720ce3ed71aSChris Mason 
721c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
7222b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
723ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
724ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
72579787eaaSJeff Mahoney 		if (ret)
72679787eaaSJeff Mahoney 			break;
727ce3ed71aSChris Mason 	}
7282c30c71bSKent Overstreet 
7294e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
730ce3ed71aSChris Mason }
731ce3ed71aSChris Mason 
7328896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
7331941b64bSQu Wenruo 					   u64 dio_file_offset)
73422c59948SChris Mason {
7358b712842SChris Mason 	/*
7368b712842SChris Mason 	 * when we're called for a write, we're already in the async
7371a722d8fSChristoph Hellwig 	 * submission context.  Just jump into btrfs_submit_bio.
7388b712842SChris Mason 	 */
73979787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
74022c59948SChris Mason }
74122c59948SChris Mason 
742f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
7439b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
744de0022b9SJosef Bacik {
7454eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
746f4dcfb30SJohannes Thumshirn 		return false;
7476300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
748f4dcfb30SJohannes Thumshirn 		return false;
7499b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
750f4dcfb30SJohannes Thumshirn 		return false;
751f4dcfb30SJohannes Thumshirn 	return true;
752de0022b9SJosef Bacik }
753de0022b9SJosef Bacik 
75494d9e11bSChristoph Hellwig void btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio, int mirror_num)
75544b8bd7eSChris Mason {
7560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
757917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(bio);
7584e4cbee9SChristoph Hellwig 	blk_status_t ret;
759cad321adSChris Mason 
76008a6f464SChristoph Hellwig 	bio->bi_opf |= REQ_META;
76108a6f464SChristoph Hellwig 
762cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
7631a722d8fSChristoph Hellwig 		btrfs_submit_bio(fs_info, bio, mirror_num);
7641a722d8fSChristoph Hellwig 		return;
76544b8bd7eSChris Mason 	}
76644b8bd7eSChris Mason 
767ea1f0cedSChristoph Hellwig 	/*
768ea1f0cedSChristoph Hellwig 	 * Kthread helpers are used to submit writes so that checksumming can
769ea1f0cedSChristoph Hellwig 	 * happen in parallel across all CPUs.
770ea1f0cedSChristoph Hellwig 	 */
771ea1f0cedSChristoph Hellwig 	if (should_async_write(fs_info, BTRFS_I(inode)) &&
772ea1f0cedSChristoph Hellwig 	    btrfs_wq_submit_bio(inode, bio, mirror_num, 0, btree_submit_bio_start))
773ea1f0cedSChristoph Hellwig 		return;
774ea1f0cedSChristoph Hellwig 
775ea1f0cedSChristoph Hellwig 	ret = btree_csum_one_bio(bio);
77694d9e11bSChristoph Hellwig 	if (ret) {
777917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, ret);
778ea1f0cedSChristoph Hellwig 		return;
77994d9e11bSChristoph Hellwig 	}
780ea1f0cedSChristoph Hellwig 
781ea1f0cedSChristoph Hellwig 	btrfs_submit_bio(fs_info, bio, mirror_num);
78261891923SStefan Behrens }
78361891923SStefan Behrens 
7843dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
7858958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
7868958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
787784b4e29SChris Mason {
788784b4e29SChris Mason 	/*
789784b4e29SChris Mason 	 * we can't safely write a btree page from here,
790784b4e29SChris Mason 	 * we haven't done the locking hook
791784b4e29SChris Mason 	 */
7928958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
793784b4e29SChris Mason 		return -EAGAIN;
794784b4e29SChris Mason 	/*
795784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
796784b4e29SChris Mason 	 * We must have no buffers or drop them.
797784b4e29SChris Mason 	 */
7988958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
7998958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
800784b4e29SChris Mason 		return -EAGAIN;
80154184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
802784b4e29SChris Mason }
8038958b551SMatthew Wilcox (Oracle) #else
8048958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
8053dd1462eSJan Beulich #endif
806784b4e29SChris Mason 
8070da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
8080da5468fSChris Mason 			    struct writeback_control *wbc)
8090da5468fSChris Mason {
810e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
811e2d84521SMiao Xie 	int ret;
812e2d84521SMiao Xie 
813d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
814448d640bSChris Mason 
815448d640bSChris Mason 		if (wbc->for_kupdate)
816448d640bSChris Mason 			return 0;
817448d640bSChris Mason 
818e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
819b9473439SChris Mason 		/* this is a bit racy, but that's ok */
820d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
821d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
822d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
823e2d84521SMiao Xie 		if (ret < 0)
824793955bcSChris Mason 			return 0;
825793955bcSChris Mason 	}
8260b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
8270da5468fSChris Mason }
8280da5468fSChris Mason 
829f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
8305f39d397SChris Mason {
831f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
832f913cff3SMatthew Wilcox (Oracle) 		return false;
8330c4e538bSDavid Sterba 
834f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
835d98237b3SChris Mason }
836d98237b3SChris Mason 
837895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
838895586ebSMatthew Wilcox (Oracle) 				 size_t length)
839d98237b3SChris Mason {
840d1310b2eSChris Mason 	struct extent_io_tree *tree;
841895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
842895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
843f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
844895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
845895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
846895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
847895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
848895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
8499ad6b7bcSChris Mason 	}
850d98237b3SChris Mason }
851d98237b3SChris Mason 
852bb146eb2SJosef Bacik #ifdef DEBUG
8530079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
8540079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
8550079c3b1SMatthew Wilcox (Oracle) {
8560079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
857139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
8580b32f4bbSJosef Bacik 	struct extent_buffer *eb;
859139e8cd3SQu Wenruo 	int cur_bit = 0;
8600079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
8610b32f4bbSJosef Bacik 
862139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
8630079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
8640b32f4bbSJosef Bacik 		BUG_ON(!eb);
8650b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
8660b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
86749d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
8680079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
869139e8cd3SQu Wenruo 	}
8700079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
871139e8cd3SQu Wenruo 
872139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
873139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
874139e8cd3SQu Wenruo 		unsigned long flags;
875139e8cd3SQu Wenruo 		u64 cur;
876139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
877139e8cd3SQu Wenruo 
878139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
879139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
880139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
881139e8cd3SQu Wenruo 			cur_bit++;
882139e8cd3SQu Wenruo 			continue;
883139e8cd3SQu Wenruo 		}
884139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
885139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
886139e8cd3SQu Wenruo 
887139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
888139e8cd3SQu Wenruo 		ASSERT(eb);
889139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
890139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
89149d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
892139e8cd3SQu Wenruo 		free_extent_buffer(eb);
893139e8cd3SQu Wenruo 
894139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
895139e8cd3SQu Wenruo 	}
8960079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
8970b32f4bbSJosef Bacik }
8980079c3b1SMatthew Wilcox (Oracle) #else
8990079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
9000079c3b1SMatthew Wilcox (Oracle) #endif
9010b32f4bbSJosef Bacik 
9027f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
9030da5468fSChris Mason 	.writepages	= btree_writepages,
904f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
905895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
9068958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
9070079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
908d98237b3SChris Mason };
909123abc88SChris Mason 
9102ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
9112ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
9123fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
9133fbaf258SJosef Bacik 						int level)
9140999df54SChris Mason {
9150b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
9160b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
9173fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
9180999df54SChris Mason }
9190999df54SChris Mason 
920581c1760SQu Wenruo /*
921581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
922581c1760SQu Wenruo  * verification.
923581c1760SQu Wenruo  *
9241b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
925581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
926581c1760SQu Wenruo  * @level:		expected level, mandatory check
927581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
928581c1760SQu Wenruo  */
9292ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
9301b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
9311b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
932e20d96d6SChris Mason {
9335f39d397SChris Mason 	struct extent_buffer *buf = NULL;
93419c00ddcSChris Mason 	int ret;
93519c00ddcSChris Mason 
9363fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
937c871b0f2SLiu Bo 	if (IS_ERR(buf))
938c871b0f2SLiu Bo 		return buf;
939e4204dedSChris Mason 
9406a2e9dc4SFilipe Manana 	ret = btrfs_read_extent_buffer(buf, parent_transid, level, first_key);
9410f0fe8f7SFilipe David Borba Manana 	if (ret) {
942537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
94364c043deSLiu Bo 		return ERR_PTR(ret);
9440f0fe8f7SFilipe David Borba Manana 	}
94588c602abSQu Wenruo 	if (btrfs_check_eb_owner(buf, owner_root)) {
94688c602abSQu Wenruo 		free_extent_buffer_stale(buf);
94788c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
94888c602abSQu Wenruo 	}
9495f39d397SChris Mason 	return buf;
950ce9adaa5SChris Mason 
951eb60ceacSChris Mason }
952eb60ceacSChris Mason 
9536a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
954ed2ff2cbSChris Mason {
9556a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
95655c69072SChris Mason 	if (btrfs_header_generation(buf) ==
957e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
95849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
959b4ce94deSChris Mason 
960b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
961104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
962e2d84521SMiao Xie 						 -buf->len,
963e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
9640b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
965925baeddSChris Mason 		}
9665f39d397SChris Mason 	}
967ed7b63ebSJosef Bacik }
9685f39d397SChris Mason 
969da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
970e20d96d6SChris Mason 			 u64 objectid)
971d97e63b6SChris Mason {
9727c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
9732e608bd1SJosef Bacik 
9742e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
9752e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
9762e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
97796dfcb46SJosef Bacik 	root->fs_info = fs_info;
9782e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
979cfaa7295SChris Mason 	root->node = NULL;
980a28ec197SChris Mason 	root->commit_root = NULL;
98127cdeb70SMiao Xie 	root->state = 0;
982abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
9830b86a832SChris Mason 
9840f7d52f4SChris Mason 	root->last_trans = 0;
9856b8fad57SNikolay Borisov 	root->free_objectid = 0;
986eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
987199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
9886bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
989088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
9902e608bd1SJosef Bacik 
9912e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
9920b86a832SChris Mason 
9930b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
9945d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
995eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
996eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
997199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
998199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
999d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
10002ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
10012ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
10025d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1003eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1004199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1005f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
10062ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
10072ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
10088287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1009a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1010e02119d5SChris Mason 	mutex_init(&root->log_mutex);
101131f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1012573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1013c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
10147237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
10157237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
10167237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
10178b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
10188b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
10197237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
10207237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
10217237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
10222ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
10230700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
10248ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1025eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
10267237f183SYan Zheng 	root->log_transid = 0;
1027d1433debSMiao Xie 	root->log_transid_committed = -1;
1028257c62e1SChris Mason 	root->last_log_commit = 0;
10292e608bd1SJosef Bacik 	root->anon_dev = 0;
1030e289f03eSFilipe Manana 	if (!dummy) {
103143eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
103243eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1033e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1034e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1035e289f03eSFilipe Manana 	}
1036017e5369SChris Mason 
10375f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1038370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1039bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1040bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1041fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1042bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1043fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1044bd647ce3SJosef Bacik #endif
10453768f368SChris Mason }
10463768f368SChris Mason 
104774e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
104896dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
10496f07e42eSAl Viro {
105074e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
10516f07e42eSAl Viro 	if (root)
105296dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
10536f07e42eSAl Viro 	return root;
10546f07e42eSAl Viro }
10556f07e42eSAl Viro 
105606ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
105706ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1058da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
105906ea65a3SJosef Bacik {
106006ea65a3SJosef Bacik 	struct btrfs_root *root;
106106ea65a3SJosef Bacik 
10627c0260eeSJeff Mahoney 	if (!fs_info)
10637c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
10647c0260eeSJeff Mahoney 
106596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
106606ea65a3SJosef Bacik 	if (!root)
106706ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1068da17066cSJeff Mahoney 
1069b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1070faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
107106ea65a3SJosef Bacik 
107206ea65a3SJosef Bacik 	return root;
107306ea65a3SJosef Bacik }
107406ea65a3SJosef Bacik #endif
107506ea65a3SJosef Bacik 
1076abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
1077abed4aaaSJosef Bacik {
1078abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
1079abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
1080abed4aaaSJosef Bacik 
1081abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
1082abed4aaaSJosef Bacik }
1083abed4aaaSJosef Bacik 
1084abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
1085abed4aaaSJosef Bacik {
1086abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
1087abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
1088abed4aaaSJosef Bacik 
1089abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
1090abed4aaaSJosef Bacik }
1091abed4aaaSJosef Bacik 
1092abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
1093abed4aaaSJosef Bacik {
1094abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1095abed4aaaSJosef Bacik 	struct rb_node *tmp;
1096abed4aaaSJosef Bacik 
1097abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1098abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1099abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1100abed4aaaSJosef Bacik 	ASSERT(!tmp);
1101abed4aaaSJosef Bacik 
1102abed4aaaSJosef Bacik 	return tmp ? -EEXIST : 0;
1103abed4aaaSJosef Bacik }
1104abed4aaaSJosef Bacik 
1105abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
1106abed4aaaSJosef Bacik {
1107abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1108abed4aaaSJosef Bacik 
1109abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1110abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
1111abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1112abed4aaaSJosef Bacik }
1113abed4aaaSJosef Bacik 
1114abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1115abed4aaaSJosef Bacik 				     struct btrfs_key *key)
1116abed4aaaSJosef Bacik {
1117abed4aaaSJosef Bacik 	struct rb_node *node;
1118abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
1119abed4aaaSJosef Bacik 
1120abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
1121abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1122abed4aaaSJosef Bacik 	if (node)
1123abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
1124abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
1125abed4aaaSJosef Bacik 
1126abed4aaaSJosef Bacik 	return root;
1127abed4aaaSJosef Bacik }
1128abed4aaaSJosef Bacik 
1129f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1130f7238e50SJosef Bacik {
1131f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
1132f7238e50SJosef Bacik 	u64 ret;
1133f7238e50SJosef Bacik 
1134f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1135f7238e50SJosef Bacik 		return 0;
1136f7238e50SJosef Bacik 
1137f7238e50SJosef Bacik 	if (bytenr)
1138f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
1139f7238e50SJosef Bacik 	else
1140f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1141f7238e50SJosef Bacik 	ASSERT(block_group);
1142f7238e50SJosef Bacik 	if (!block_group)
1143f7238e50SJosef Bacik 		return 0;
1144f7238e50SJosef Bacik 	ret = block_group->global_root_id;
1145f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
1146f7238e50SJosef Bacik 
1147f7238e50SJosef Bacik 	return ret;
1148f7238e50SJosef Bacik }
1149f7238e50SJosef Bacik 
1150abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1151abed4aaaSJosef Bacik {
1152abed4aaaSJosef Bacik 	struct btrfs_key key = {
1153abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1154abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1155f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1156abed4aaaSJosef Bacik 	};
1157abed4aaaSJosef Bacik 
1158abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1159abed4aaaSJosef Bacik }
1160abed4aaaSJosef Bacik 
1161abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1162abed4aaaSJosef Bacik {
1163abed4aaaSJosef Bacik 	struct btrfs_key key = {
1164abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1165abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1166f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1167abed4aaaSJosef Bacik 	};
1168abed4aaaSJosef Bacik 
1169abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1170abed4aaaSJosef Bacik }
1171abed4aaaSJosef Bacik 
117220897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
117320897f5cSArne Jansen 				     u64 objectid)
117420897f5cSArne Jansen {
11759b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
117620897f5cSArne Jansen 	struct extent_buffer *leaf;
117720897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
117820897f5cSArne Jansen 	struct btrfs_root *root;
117920897f5cSArne Jansen 	struct btrfs_key key;
1180b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
118120897f5cSArne Jansen 	int ret = 0;
118220897f5cSArne Jansen 
1183b89f6d1fSFilipe Manana 	/*
1184b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1185b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1186b89f6d1fSFilipe Manana 	 */
1187b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
118896dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1189b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
119020897f5cSArne Jansen 	if (!root)
119120897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
119220897f5cSArne Jansen 
119320897f5cSArne Jansen 	root->root_key.objectid = objectid;
119420897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
119520897f5cSArne Jansen 	root->root_key.offset = 0;
119620897f5cSArne Jansen 
11979631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
11989631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
119920897f5cSArne Jansen 	if (IS_ERR(leaf)) {
120020897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12011dd05682STsutomu Itoh 		leaf = NULL;
12028a6a87cdSBoris Burkov 		goto fail_unlock;
120320897f5cSArne Jansen 	}
120420897f5cSArne Jansen 
120520897f5cSArne Jansen 	root->node = leaf;
120620897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
120720897f5cSArne Jansen 
120820897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
120927cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
121020897f5cSArne Jansen 
1211f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1212f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
121320897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
121420897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
121520897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
121620897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
121720897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
121820897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
121920897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
122033d85fdaSQu Wenruo 	if (is_fstree(objectid))
1221807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1222807fc790SAndy Shevchenko 	else
1223807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1224c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
122520897f5cSArne Jansen 
12268a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
12278a6a87cdSBoris Burkov 
122820897f5cSArne Jansen 	key.objectid = objectid;
122920897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
123020897f5cSArne Jansen 	key.offset = 0;
123120897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
123220897f5cSArne Jansen 	if (ret)
123320897f5cSArne Jansen 		goto fail;
123420897f5cSArne Jansen 
123520897f5cSArne Jansen 	return root;
12361dd05682STsutomu Itoh 
12378a6a87cdSBoris Burkov fail_unlock:
12388c38938cSJosef Bacik 	if (leaf)
12391dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
12408a6a87cdSBoris Burkov fail:
124100246528SJosef Bacik 	btrfs_put_root(root);
12421dd05682STsutomu Itoh 
12431dd05682STsutomu Itoh 	return ERR_PTR(ret);
124420897f5cSArne Jansen }
124520897f5cSArne Jansen 
12467237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1247e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
12480f7d52f4SChris Mason {
12490f7d52f4SChris Mason 	struct btrfs_root *root;
1250e02119d5SChris Mason 
125196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1252e02119d5SChris Mason 	if (!root)
12537237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1254e02119d5SChris Mason 
1255e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1256e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1257e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
125827cdeb70SMiao Xie 
12596ab6ebb7SNaohiro Aota 	return root;
12606ab6ebb7SNaohiro Aota }
12616ab6ebb7SNaohiro Aota 
12626ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
12636ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
12646ab6ebb7SNaohiro Aota {
12656ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
12666ab6ebb7SNaohiro Aota 
12677237f183SYan Zheng 	/*
126892a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
126927cdeb70SMiao Xie 	 *
127092a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
127192a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
127292a7cc42SQu Wenruo 	 *
127392a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
127492a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
12757237f183SYan Zheng 	 */
1276e02119d5SChris Mason 
12774d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12789631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
12796ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
12806ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1281e02119d5SChris Mason 
12827237f183SYan Zheng 	root->node = leaf;
1283e02119d5SChris Mason 
1284e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1285e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12866ab6ebb7SNaohiro Aota 
12876ab6ebb7SNaohiro Aota 	return 0;
12887237f183SYan Zheng }
12897237f183SYan Zheng 
12907237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
12917237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
12927237f183SYan Zheng {
12937237f183SYan Zheng 	struct btrfs_root *log_root;
12947237f183SYan Zheng 
12957237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
12967237f183SYan Zheng 	if (IS_ERR(log_root))
12977237f183SYan Zheng 		return PTR_ERR(log_root);
12986ab6ebb7SNaohiro Aota 
12993ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13003ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13013ddebf27SNaohiro Aota 
13026ab6ebb7SNaohiro Aota 		if (ret) {
13036ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13046ab6ebb7SNaohiro Aota 			return ret;
13056ab6ebb7SNaohiro Aota 		}
13063ddebf27SNaohiro Aota 	}
13076ab6ebb7SNaohiro Aota 
13087237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13097237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13107237f183SYan Zheng 	return 0;
13117237f183SYan Zheng }
13127237f183SYan Zheng 
13137237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13147237f183SYan Zheng 		       struct btrfs_root *root)
13157237f183SYan Zheng {
13160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13177237f183SYan Zheng 	struct btrfs_root *log_root;
13187237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13196ab6ebb7SNaohiro Aota 	int ret;
13207237f183SYan Zheng 
13210b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13227237f183SYan Zheng 	if (IS_ERR(log_root))
13237237f183SYan Zheng 		return PTR_ERR(log_root);
13247237f183SYan Zheng 
13256ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13266ab6ebb7SNaohiro Aota 	if (ret) {
13276ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
13286ab6ebb7SNaohiro Aota 		return ret;
13296ab6ebb7SNaohiro Aota 	}
13306ab6ebb7SNaohiro Aota 
13317237f183SYan Zheng 	log_root->last_trans = trans->transid;
13327237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13337237f183SYan Zheng 
13347237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13353cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13363cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13373cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1338da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13390b246afaSJeff Mahoney 				     fs_info->nodesize);
13403cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13417237f183SYan Zheng 
13425d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13437237f183SYan Zheng 
13447237f183SYan Zheng 	WARN_ON(root->log_root);
13457237f183SYan Zheng 	root->log_root = log_root;
13467237f183SYan Zheng 	root->log_transid = 0;
1347d1433debSMiao Xie 	root->log_transid_committed = -1;
1348257c62e1SChris Mason 	root->last_log_commit = 0;
1349e02119d5SChris Mason 	return 0;
1350e02119d5SChris Mason }
1351e02119d5SChris Mason 
135249d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
135349d11beaSJosef Bacik 					      struct btrfs_path *path,
1354cb517eabSMiao Xie 					      struct btrfs_key *key)
1355e02119d5SChris Mason {
1356e02119d5SChris Mason 	struct btrfs_root *root;
1357e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
135884234f3aSYan Zheng 	u64 generation;
1359cb517eabSMiao Xie 	int ret;
1360581c1760SQu Wenruo 	int level;
1361cb517eabSMiao Xie 
136296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
136349d11beaSJosef Bacik 	if (!root)
136449d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
13650f7d52f4SChris Mason 
1366cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1367cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
13680f7d52f4SChris Mason 	if (ret) {
136913a8a7c8SYan, Zheng 		if (ret > 0)
137013a8a7c8SYan, Zheng 			ret = -ENOENT;
137149d11beaSJosef Bacik 		goto fail;
13720f7d52f4SChris Mason 	}
137313a8a7c8SYan, Zheng 
137484234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1375581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
13762ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
13772ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
13781b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
137964c043deSLiu Bo 	if (IS_ERR(root->node)) {
138064c043deSLiu Bo 		ret = PTR_ERR(root->node);
13818c38938cSJosef Bacik 		root->node = NULL;
138249d11beaSJosef Bacik 		goto fail;
13834eb150d6SQu Wenruo 	}
13844eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1385cb517eabSMiao Xie 		ret = -EIO;
138649d11beaSJosef Bacik 		goto fail;
1387416bc658SJosef Bacik 	}
138888c602abSQu Wenruo 
138988c602abSQu Wenruo 	/*
139088c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
139188c602abSQu Wenruo 	 * match its root node owner
139288c602abSQu Wenruo 	 */
139388c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
139488c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
139588c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
139688c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
139788c602abSQu Wenruo 		btrfs_crit(fs_info,
139888c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
139988c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
140088c602abSQu Wenruo 			   btrfs_header_owner(root->node),
140188c602abSQu Wenruo 			   root->root_key.objectid);
140288c602abSQu Wenruo 		ret = -EUCLEAN;
140388c602abSQu Wenruo 		goto fail;
140488c602abSQu Wenruo 	}
14055d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1406cb517eabSMiao Xie 	return root;
140749d11beaSJosef Bacik fail:
140800246528SJosef Bacik 	btrfs_put_root(root);
140949d11beaSJosef Bacik 	return ERR_PTR(ret);
141049d11beaSJosef Bacik }
141149d11beaSJosef Bacik 
141249d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
141349d11beaSJosef Bacik 					struct btrfs_key *key)
141449d11beaSJosef Bacik {
141549d11beaSJosef Bacik 	struct btrfs_root *root;
141649d11beaSJosef Bacik 	struct btrfs_path *path;
141749d11beaSJosef Bacik 
141849d11beaSJosef Bacik 	path = btrfs_alloc_path();
141949d11beaSJosef Bacik 	if (!path)
142049d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
142149d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
142249d11beaSJosef Bacik 	btrfs_free_path(path);
142349d11beaSJosef Bacik 
142449d11beaSJosef Bacik 	return root;
1425cb517eabSMiao Xie }
1426cb517eabSMiao Xie 
14272dfb1e43SQu Wenruo /*
14282dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14292dfb1e43SQu Wenruo  *
14302dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14312dfb1e43SQu Wenruo  */
14322dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1433cb517eabSMiao Xie {
1434cb517eabSMiao Xie 	int ret;
1435dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1436cb517eabSMiao Xie 
1437dcc3eb96SNikolay Borisov 	/*
1438dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1439dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1440dcc3eb96SNikolay Borisov 	 */
1441dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1442dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1443dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1444dcc3eb96SNikolay Borisov 	if (ret)
14458257b2dcSMiao Xie 		goto fail;
14468257b2dcSMiao Xie 
1447aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
144837f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
144992a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1450f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1451f39e4571SJosef Bacik 	}
1452f39e4571SJosef Bacik 
1453851fd730SQu Wenruo 	/*
1454851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1455851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1456851fd730SQu Wenruo 	 */
1457851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1458851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
14592dfb1e43SQu Wenruo 		if (!anon_dev) {
1460cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1461cb517eabSMiao Xie 			if (ret)
1462876d2cf1SLiu Bo 				goto fail;
14632dfb1e43SQu Wenruo 		} else {
14642dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
14652dfb1e43SQu Wenruo 		}
1466851fd730SQu Wenruo 	}
1467f32e48e9SChandan Rajendra 
1468f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1469453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1470f32e48e9SChandan Rajendra 	if (ret) {
1471f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1472876d2cf1SLiu Bo 		goto fail;
1473f32e48e9SChandan Rajendra 	}
1474f32e48e9SChandan Rajendra 
14756b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1476f32e48e9SChandan Rajendra 
1477f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1478f32e48e9SChandan Rajendra 
1479cb517eabSMiao Xie 	return 0;
1480cb517eabSMiao Xie fail:
148184db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1482cb517eabSMiao Xie 	return ret;
1483cb517eabSMiao Xie }
1484cb517eabSMiao Xie 
1485a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1486cb517eabSMiao Xie 					       u64 root_id)
1487cb517eabSMiao Xie {
1488cb517eabSMiao Xie 	struct btrfs_root *root;
1489cb517eabSMiao Xie 
1490fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1491fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1492fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1493bc44d7c4SJosef Bacik 	if (root)
149400246528SJosef Bacik 		root = btrfs_grab_root(root);
1495fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1496cb517eabSMiao Xie 	return root;
1497cb517eabSMiao Xie }
1498cb517eabSMiao Xie 
149949d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
150049d11beaSJosef Bacik 						u64 objectid)
150149d11beaSJosef Bacik {
1502abed4aaaSJosef Bacik 	struct btrfs_key key = {
1503abed4aaaSJosef Bacik 		.objectid = objectid,
1504abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1505abed4aaaSJosef Bacik 		.offset = 0,
1506abed4aaaSJosef Bacik 	};
1507abed4aaaSJosef Bacik 
150849d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
150949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
151049d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1511abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
151249d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
151349d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
151449d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
151549d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
151649d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1517abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
151849d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
151949d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
152049d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
152149d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
152249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
152349d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
152414033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
152514033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
152614033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1527abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1528abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1529abed4aaaSJosef Bacik 
1530abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1531abed4aaaSJosef Bacik 	}
153249d11beaSJosef Bacik 	return NULL;
153349d11beaSJosef Bacik }
153449d11beaSJosef Bacik 
1535cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1536cb517eabSMiao Xie 			 struct btrfs_root *root)
1537cb517eabSMiao Xie {
1538cb517eabSMiao Xie 	int ret;
1539cb517eabSMiao Xie 
1540fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1541fc7cbcd4SDavid Sterba 	if (ret)
1542fc7cbcd4SDavid Sterba 		return ret;
1543fc7cbcd4SDavid Sterba 
1544fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1545fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1546fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1547fc7cbcd4SDavid Sterba 				root);
1548af01d2e5SJosef Bacik 	if (ret == 0) {
154900246528SJosef Bacik 		btrfs_grab_root(root);
1550fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1551af01d2e5SJosef Bacik 	}
1552fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1553fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1554cb517eabSMiao Xie 
1555cb517eabSMiao Xie 	return ret;
1556cb517eabSMiao Xie }
1557cb517eabSMiao Xie 
1558bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1559bd647ce3SJosef Bacik {
1560bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1561bd647ce3SJosef Bacik 	struct btrfs_root *root;
1562bd647ce3SJosef Bacik 
1563bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1564457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1565457f1864SJosef Bacik 
1566bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1567bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1568457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
156971008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1570bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1571bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
157200246528SJosef Bacik 			btrfs_put_root(root);
157300246528SJosef Bacik 		btrfs_put_root(root);
1574bd647ce3SJosef Bacik 	}
1575bd647ce3SJosef Bacik #endif
1576bd647ce3SJosef Bacik }
1577bd647ce3SJosef Bacik 
1578abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1579abed4aaaSJosef Bacik {
1580abed4aaaSJosef Bacik 	struct btrfs_root *root;
1581abed4aaaSJosef Bacik 	struct rb_node *node;
1582abed4aaaSJosef Bacik 
1583abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1584abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1585abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1586abed4aaaSJosef Bacik 		btrfs_put_root(root);
1587abed4aaaSJosef Bacik 	}
1588abed4aaaSJosef Bacik }
1589abed4aaaSJosef Bacik 
15900d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
15910d4b0463SJosef Bacik {
1592141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1593141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
15945deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1595141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1596141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1597141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1598141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
15990d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16000d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1601abed4aaaSJosef Bacik 	free_global_roots(fs_info);
160200246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
160300246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
160400246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
160500246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
160600246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
160700246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1608aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
16099c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1610bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16113fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16120d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16130d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16148481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
16150d4b0463SJosef Bacik 	kvfree(fs_info);
16160d4b0463SJosef Bacik }
16170d4b0463SJosef Bacik 
16180d4b0463SJosef Bacik 
16192dfb1e43SQu Wenruo /*
16202dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
16212dfb1e43SQu Wenruo  *
16222dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
16232dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
16242dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
16252dfb1e43SQu Wenruo  *
16262dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
16272dfb1e43SQu Wenruo  *
16282dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
16292dfb1e43SQu Wenruo  *	 same root objectid.
16302dfb1e43SQu Wenruo  *
16312dfb1e43SQu Wenruo  * @objectid:	root id
16322dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
16332dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16342dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16352dfb1e43SQu Wenruo  *		for orphan roots
16362dfb1e43SQu Wenruo  */
16372dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16382dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16392dfb1e43SQu Wenruo 					     bool check_ref)
16405eda7b5eSChris Mason {
16415eda7b5eSChris Mason 	struct btrfs_root *root;
1642381cf658SDavid Sterba 	struct btrfs_path *path;
16431d4c08e0SDavid Sterba 	struct btrfs_key key;
16445eda7b5eSChris Mason 	int ret;
16455eda7b5eSChris Mason 
164649d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
164749d11beaSJosef Bacik 	if (root)
164849d11beaSJosef Bacik 		return root;
16494df27c4dSYan, Zheng again:
165056e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
165148475471SStefan Behrens 	if (root) {
16522dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16532dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1654bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
165500246528SJosef Bacik 			btrfs_put_root(root);
165648475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1657bc44d7c4SJosef Bacik 		}
16585eda7b5eSChris Mason 		return root;
165948475471SStefan Behrens 	}
16605eda7b5eSChris Mason 
166156e9357aSDavid Sterba 	key.objectid = objectid;
166256e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
166356e9357aSDavid Sterba 	key.offset = (u64)-1;
166456e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16655eda7b5eSChris Mason 	if (IS_ERR(root))
16665eda7b5eSChris Mason 		return root;
16673394e160SChris Mason 
1668c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1669d68fc57bSYan, Zheng 		ret = -ENOENT;
1670d68fc57bSYan, Zheng 		goto fail;
1671d68fc57bSYan, Zheng 	}
1672d68fc57bSYan, Zheng 
16732dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1674cb517eabSMiao Xie 	if (ret)
1675cb517eabSMiao Xie 		goto fail;
1676cb517eabSMiao Xie 
1677381cf658SDavid Sterba 	path = btrfs_alloc_path();
1678381cf658SDavid Sterba 	if (!path) {
1679381cf658SDavid Sterba 		ret = -ENOMEM;
1680381cf658SDavid Sterba 		goto fail;
1681381cf658SDavid Sterba 	}
16821d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
16831d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
168456e9357aSDavid Sterba 	key.offset = objectid;
16851d4c08e0SDavid Sterba 
16861d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1687381cf658SDavid Sterba 	btrfs_free_path(path);
1688d68fc57bSYan, Zheng 	if (ret < 0)
1689d68fc57bSYan, Zheng 		goto fail;
1690d68fc57bSYan, Zheng 	if (ret == 0)
169127cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1692d68fc57bSYan, Zheng 
1693cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16940f7d52f4SChris Mason 	if (ret) {
1695168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
169600246528SJosef Bacik 			btrfs_put_root(root);
16974df27c4dSYan, Zheng 			goto again;
1698168a2f77SJia-Ju Bai 		}
16994df27c4dSYan, Zheng 		goto fail;
17004df27c4dSYan, Zheng 	}
1701edbd8d4eSChris Mason 	return root;
17024df27c4dSYan, Zheng fail:
170333fab972SFilipe Manana 	/*
170433fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1705143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
170633fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
170733fab972SFilipe Manana 	 * and once again by our caller.
170833fab972SFilipe Manana 	 */
170933fab972SFilipe Manana 	if (anon_dev)
171033fab972SFilipe Manana 		root->anon_dev = 0;
17118c38938cSJosef Bacik 	btrfs_put_root(root);
17124df27c4dSYan, Zheng 	return ERR_PTR(ret);
1713edbd8d4eSChris Mason }
1714edbd8d4eSChris Mason 
17152dfb1e43SQu Wenruo /*
17162dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
17172dfb1e43SQu Wenruo  *
17182dfb1e43SQu Wenruo  * @objectid:	tree objectid
17192dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
17202dfb1e43SQu Wenruo  *		one reference
17212dfb1e43SQu Wenruo  */
17222dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
17232dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
17242dfb1e43SQu Wenruo {
17252dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
17262dfb1e43SQu Wenruo }
17272dfb1e43SQu Wenruo 
17282dfb1e43SQu Wenruo /*
17292dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
17302dfb1e43SQu Wenruo  * the anonymous block device id
17312dfb1e43SQu Wenruo  *
17322dfb1e43SQu Wenruo  * @objectid:	tree objectid
17332dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
17342dfb1e43SQu Wenruo  *		parameter value
17352dfb1e43SQu Wenruo  */
17362dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
17372dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
17382dfb1e43SQu Wenruo {
17392dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
17402dfb1e43SQu Wenruo }
17412dfb1e43SQu Wenruo 
17428b712842SChris Mason /*
174349d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
174449d11beaSJosef Bacik  * @fs_info:	the fs_info
174549d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
174649d11beaSJosef Bacik  *
174749d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
174849d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
174949d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
175049d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
175149d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
175249d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
175349d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
175449d11beaSJosef Bacik  * backref code is finished using the root.
175549d11beaSJosef Bacik  */
175649d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
175749d11beaSJosef Bacik 						 struct btrfs_path *path,
175849d11beaSJosef Bacik 						 u64 objectid)
175949d11beaSJosef Bacik {
176049d11beaSJosef Bacik 	struct btrfs_root *root;
176149d11beaSJosef Bacik 	struct btrfs_key key;
176249d11beaSJosef Bacik 
176349d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
176449d11beaSJosef Bacik 
176549d11beaSJosef Bacik 	/*
176649d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
176749d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
176849d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
176949d11beaSJosef Bacik 	 * != NULL just return it.
177049d11beaSJosef Bacik 	 */
177149d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
177249d11beaSJosef Bacik 	if (root)
177349d11beaSJosef Bacik 		return root;
177449d11beaSJosef Bacik 
177549d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
177649d11beaSJosef Bacik 	if (root)
177749d11beaSJosef Bacik 		return root;
177849d11beaSJosef Bacik 
177949d11beaSJosef Bacik 	key.objectid = objectid;
178049d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
178149d11beaSJosef Bacik 	key.offset = (u64)-1;
178249d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
178349d11beaSJosef Bacik 	btrfs_release_path(path);
178449d11beaSJosef Bacik 
178549d11beaSJosef Bacik 	return root;
178649d11beaSJosef Bacik }
178749d11beaSJosef Bacik 
1788a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1789a74a4b97SChris Mason {
17900d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1791d0278245SMiao Xie 	int again;
1792a74a4b97SChris Mason 
1793d6fd0ae2SOmar Sandoval 	while (1) {
1794d0278245SMiao Xie 		again = 0;
17959d1a2a3aSDavid Sterba 
1796fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1797fd340d0fSJosef Bacik 
1798d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
17992ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1800d0278245SMiao Xie 			goto sleep;
1801d0278245SMiao Xie 
180290c711abSZygo Blaxell 		/*
180390c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
180490c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
180590c711abSZygo Blaxell 		 */
18060b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
180790c711abSZygo Blaxell 			goto sleep;
180890c711abSZygo Blaxell 
18090b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1810d0278245SMiao Xie 			goto sleep;
1811d0278245SMiao Xie 
1812dc7f370cSMiao Xie 		/*
1813dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1814dc7f370cSMiao Xie 		 * during the above check and trylock.
1815dc7f370cSMiao Xie 		 */
18162ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18170b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1818dc7f370cSMiao Xie 			goto sleep;
1819dc7f370cSMiao Xie 		}
1820dc7f370cSMiao Xie 
18212ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1822c2d6cb16SFilipe Manana 
182333c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
18240b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1825a74a4b97SChris Mason 
1826d0278245SMiao Xie 		/*
182705323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
182805323cd1SMiao Xie 		 * needn't do anything special here.
1829d0278245SMiao Xie 		 */
18300b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
183167c5e7d4SFilipe Manana 
183267c5e7d4SFilipe Manana 		/*
1833f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
183467c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
183567c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1836f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
183767c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
183867c5e7d4SFilipe Manana 		 * unused block groups.
183967c5e7d4SFilipe Manana 		 */
18400b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
184118bb8bbfSJohannes Thumshirn 
184218bb8bbfSJohannes Thumshirn 		/*
184318bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
184418bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
184518bb8bbfSJohannes Thumshirn 		 * space.
184618bb8bbfSJohannes Thumshirn 		 */
184718bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1848d0278245SMiao Xie sleep:
1849a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1850d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1851d6fd0ae2SOmar Sandoval 			kthread_parkme();
1852d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1853d6fd0ae2SOmar Sandoval 			return 0;
1854838fe188SJiri Kosina 		if (!again) {
1855a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1856a74a4b97SChris Mason 			schedule();
1857a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1858a74a4b97SChris Mason 		}
1859da288d28SFilipe Manana 	}
1860a74a4b97SChris Mason }
1861a74a4b97SChris Mason 
1862a74a4b97SChris Mason static int transaction_kthread(void *arg)
1863a74a4b97SChris Mason {
1864a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1866a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1867a74a4b97SChris Mason 	struct btrfs_transaction *cur;
18688929ecfaSYan, Zheng 	u64 transid;
1869643900beSNikolay Borisov 	time64_t delta;
1870a74a4b97SChris Mason 	unsigned long delay;
1871914b2007SJan Kara 	bool cannot_commit;
1872a74a4b97SChris Mason 
1873a74a4b97SChris Mason 	do {
1874914b2007SJan Kara 		cannot_commit = false;
1875ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
18760b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1877a74a4b97SChris Mason 
18780b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
18790b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1880a74a4b97SChris Mason 		if (!cur) {
18810b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1882a74a4b97SChris Mason 			goto sleep;
1883a74a4b97SChris Mason 		}
188431153d81SYan Zheng 
1885643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1886fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1887fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1888643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
18890b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1890fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1891fb8a7e94SNikolay Borisov 			delay = min(delay,
1892fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1893a74a4b97SChris Mason 			goto sleep;
1894a74a4b97SChris Mason 		}
18958929ecfaSYan, Zheng 		transid = cur->transid;
18960b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
189756bec294SChris Mason 
189879787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1899354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1900914b2007SJan Kara 		if (IS_ERR(trans)) {
1901354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1902914b2007SJan Kara 				cannot_commit = true;
190379787eaaSJeff Mahoney 			goto sleep;
1904914b2007SJan Kara 		}
19058929ecfaSYan, Zheng 		if (transid == trans->transid) {
19063a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19078929ecfaSYan, Zheng 		} else {
19083a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19098929ecfaSYan, Zheng 		}
1910a74a4b97SChris Mason sleep:
19110b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19120b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1913a74a4b97SChris Mason 
191484961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
19152ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
19168929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19170b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1918914b2007SJan Kara 				 cannot_commit))
1919bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1920a74a4b97SChris Mason 	} while (!kthread_should_stop());
1921a74a4b97SChris Mason 	return 0;
1922a74a4b97SChris Mason }
1923a74a4b97SChris Mason 
1924af31f5e5SChris Mason /*
192501f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
192601f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
192701f0f9daSNikolay Borisov  * anything.
1928af31f5e5SChris Mason  *
1929af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1930af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1931af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1932af31f5e5SChris Mason  */
193301f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1934af31f5e5SChris Mason {
193501f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1936af31f5e5SChris Mason 	u64 cur;
1937af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1938af31f5e5SChris Mason 	int i;
1939af31f5e5SChris Mason 
1940af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1941af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1942af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1943af31f5e5SChris Mason 		if (cur == newest_gen)
194401f0f9daSNikolay Borisov 			return i;
1945af31f5e5SChris Mason 	}
1946af31f5e5SChris Mason 
194701f0f9daSNikolay Borisov 	return -EINVAL;
1948af31f5e5SChris Mason }
1949af31f5e5SChris Mason 
1950af31f5e5SChris Mason /*
1951af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1952af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1953af31f5e5SChris Mason  * done
1954af31f5e5SChris Mason  */
1955af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1956af31f5e5SChris Mason {
19576ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1958af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1959af31f5e5SChris Mason 
1960af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1961af31f5e5SChris Mason 
1962af31f5e5SChris Mason 	/*
1963af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1964af31f5e5SChris Mason 	 * regardless of which ones we use today
1965af31f5e5SChris Mason 	 */
1966af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1967af31f5e5SChris Mason 
1968af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1969af31f5e5SChris Mason 
1970af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1971af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1972af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1973af31f5e5SChris Mason 
1974af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1975af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1976af31f5e5SChris Mason 
1977af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1978af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1979af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1980af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1981af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1982af31f5e5SChris Mason 
19831c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
19849c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1985f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
19869c54e80dSJosef Bacik 
19879c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
19889c54e80dSJosef Bacik 					     extent_root->node->start);
1989af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
199029cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
1991af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
199229cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
1993af31f5e5SChris Mason 
1994f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1995f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
1996f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
1997f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
1998f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
19999c54e80dSJosef Bacik 	}
2000af31f5e5SChris Mason 
20017c7e82a7SChris Mason 	/*
20027c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20037c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20047c7e82a7SChris Mason 	 */
20057c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20067c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20077c7e82a7SChris Mason 					 info->fs_root->node->start);
2008af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2009af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2010af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2011af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20127c7e82a7SChris Mason 	}
2013af31f5e5SChris Mason 
2014af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2015af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2016af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2017af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2018af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2019af31f5e5SChris Mason 
2020af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2021af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2022af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2023af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2024af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2025af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2026af31f5e5SChris Mason 
2027af31f5e5SChris Mason 	/*
2028af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2029af31f5e5SChris Mason 	 * for the next commit
2030af31f5e5SChris Mason 	 */
2031af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2032af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2033af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2034af31f5e5SChris Mason }
2035af31f5e5SChris Mason 
2036af31f5e5SChris Mason /*
2037bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2038bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2039bd2336b2SNikolay Borisov  *
2040bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2041bd2336b2SNikolay Borisov  * priority - priority of backup root required
2042bd2336b2SNikolay Borisov  *
2043bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2044bd2336b2SNikolay Borisov  */
2045bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2046bd2336b2SNikolay Borisov {
2047bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2048bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2049bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2050bd2336b2SNikolay Borisov 
2051bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2052bd2336b2SNikolay Borisov 		if (priority == 0)
2053bd2336b2SNikolay Borisov 			return backup_index;
2054bd2336b2SNikolay Borisov 
2055bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2056bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2057bd2336b2SNikolay Borisov 	} else {
2058bd2336b2SNikolay Borisov 		return -EINVAL;
2059bd2336b2SNikolay Borisov 	}
2060bd2336b2SNikolay Borisov 
2061bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2062bd2336b2SNikolay Borisov 
2063bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2064bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2065bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2066bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2067bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2068bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2069bd2336b2SNikolay Borisov 
2070bd2336b2SNikolay Borisov 	/*
2071bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2072bd2336b2SNikolay Borisov 	 * need a fsck
2073bd2336b2SNikolay Borisov 	 */
2074bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2075bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2076bd2336b2SNikolay Borisov 
2077bd2336b2SNikolay Borisov 	return backup_index;
2078bd2336b2SNikolay Borisov }
2079bd2336b2SNikolay Borisov 
20807abadb64SLiu Bo /* helper to cleanup workers */
20817abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20827abadb64SLiu Bo {
2083dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2084afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
2085a31b4a43SChristoph Hellwig 	btrfs_destroy_workqueue(fs_info->hipri_workers);
20865cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2087d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
2088d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
2089d34e123dSChristoph Hellwig 	if (fs_info->endio_raid56_workers)
2090d34e123dSChristoph Hellwig 		destroy_workqueue(fs_info->endio_raid56_workers);
2091385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
2092385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
2093fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
2094fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
2095fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2096fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
20975b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2098e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2099a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2100fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2101b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2102b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2103a9b9477dSFilipe Manana 	/*
2104a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2105a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2106a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2107a9b9477dSFilipe Manana 	 */
2108d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
2109d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
21107abadb64SLiu Bo }
21117abadb64SLiu Bo 
21122e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21132e9f5954SRashika {
21142e9f5954SRashika 	if (root) {
21152e9f5954SRashika 		free_extent_buffer(root->node);
21162e9f5954SRashika 		free_extent_buffer(root->commit_root);
21172e9f5954SRashika 		root->node = NULL;
21182e9f5954SRashika 		root->commit_root = NULL;
21192e9f5954SRashika 	}
21202e9f5954SRashika }
21212e9f5954SRashika 
2122abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2123abed4aaaSJosef Bacik {
2124abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
2125abed4aaaSJosef Bacik 
2126abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
2127abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
2128abed4aaaSJosef Bacik 					     rb_node)
2129abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
2130abed4aaaSJosef Bacik }
2131abed4aaaSJosef Bacik 
2132af31f5e5SChris Mason /* helper to cleanup tree roots */
21334273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2134af31f5e5SChris Mason {
21352e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2136655b09feSJosef Bacik 
2137abed4aaaSJosef Bacik 	free_global_root_pointers(info);
21382e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21392e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21402e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21418c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2142aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
21439c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
21444273eaffSAnand Jain 	if (free_chunk_root)
21452e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2146af31f5e5SChris Mason }
2147af31f5e5SChris Mason 
21488c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
21498c38938cSJosef Bacik {
21508c38938cSJosef Bacik 	if (!root)
21518c38938cSJosef Bacik 		return;
21528c38938cSJosef Bacik 
21538c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21548c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21551dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21568c38938cSJosef Bacik 		if (root->anon_dev)
21578c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21588c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2159923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21608c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2161fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21628c38938cSJosef Bacik 		list_del_init(&root->leak_list);
2163fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21648c38938cSJosef Bacik #endif
21658c38938cSJosef Bacik 		kfree(root);
21668c38938cSJosef Bacik 	}
21678c38938cSJosef Bacik }
21688c38938cSJosef Bacik 
2169faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2170171f6537SJosef Bacik {
2171fc7cbcd4SDavid Sterba 	int ret;
2172fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
2173fc7cbcd4SDavid Sterba 	int i;
2174171f6537SJosef Bacik 
2175171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2176fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
2177171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2178fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
2179171f6537SJosef Bacik 
2180fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2181fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2182fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
2183171f6537SJosef Bacik 	}
2184171f6537SJosef Bacik 
2185fc7cbcd4SDavid Sterba 	while (1) {
2186fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2187fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
2188fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
2189fc7cbcd4SDavid Sterba 		if (!ret)
2190fc7cbcd4SDavid Sterba 			break;
2191fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
2192fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2193171f6537SJosef Bacik 	}
2194171f6537SJosef Bacik }
2195af31f5e5SChris Mason 
2196638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2197638aa7edSEric Sandeen {
2198638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2199638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2200638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2201638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2202638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2203638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2204ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2205638aa7edSEric Sandeen }
2206638aa7edSEric Sandeen 
2207779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2208779a65a4SEric Sandeen {
2209779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2210779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2211779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2212779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2213779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2214779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2215907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2216779a65a4SEric Sandeen }
2217779a65a4SEric Sandeen 
22186bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2219f37938e0SEric Sandeen {
22202ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
2221*e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
2222*e256927bSJosef Bacik 					      fs_info->tree_root);
22232ff7e61eSJeff Mahoney 
22242ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
22252ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2226f37938e0SEric Sandeen 	/*
2227f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2228f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2229f37938e0SEric Sandeen 	 * the devices in the system
2230f37938e0SEric Sandeen 	 */
22312ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
22322ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2233f37938e0SEric Sandeen 
22342ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
223543eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
2236efb0645bSJosef Bacik 			    IO_TREE_BTREE_INODE_IO, NULL);
22372ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2238f37938e0SEric Sandeen 
22395c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2240adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
2241adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
2242adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
22432ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2244*e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
2245f37938e0SEric Sandeen }
2246f37938e0SEric Sandeen 
2247ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2248ad618368SEric Sandeen {
2249ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2250129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
22517f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2252ad618368SEric Sandeen }
2253ad618368SEric Sandeen 
2254f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2255f9e92e40SEric Sandeen {
2256f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2257f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2258f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2259f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2260f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2261f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2262d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2263011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
2264f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2265f9e92e40SEric Sandeen }
2266f9e92e40SEric Sandeen 
2267d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
22682a458198SEric Sandeen {
2269f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22706f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22712a458198SEric Sandeen 
22722a458198SEric Sandeen 	fs_info->workers =
2273a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
2274a31b4a43SChristoph Hellwig 	fs_info->hipri_workers =
2275a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker-high",
2276cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22772a458198SEric Sandeen 
22782a458198SEric Sandeen 	fs_info->delalloc_workers =
2279cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2280cb001095SJeff Mahoney 				      flags, max_active, 2);
22812a458198SEric Sandeen 
22822a458198SEric Sandeen 	fs_info->flush_workers =
2283cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2284cb001095SJeff Mahoney 				      flags, max_active, 0);
22852a458198SEric Sandeen 
22862a458198SEric Sandeen 	fs_info->caching_workers =
2287cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
22882a458198SEric Sandeen 
22892a458198SEric Sandeen 	fs_info->fixup_workers =
2290cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
22912a458198SEric Sandeen 
22922a458198SEric Sandeen 	fs_info->endio_workers =
2293d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
22942a458198SEric Sandeen 	fs_info->endio_meta_workers =
2295d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
22962a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2297d34e123dSChristoph Hellwig 		alloc_workqueue("btrfs-endio-raid56", flags, max_active);
2298385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
22992a458198SEric Sandeen 	fs_info->endio_write_workers =
2300cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2301cb001095SJeff Mahoney 				      max_active, 2);
2302fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
2303fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
23042a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2305cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2306cb001095SJeff Mahoney 				      max_active, 0);
23072a458198SEric Sandeen 	fs_info->delayed_workers =
2308cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2309cb001095SJeff Mahoney 				      max_active, 0);
23102a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2311cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2312b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2313b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23142a458198SEric Sandeen 
2315a31b4a43SChristoph Hellwig 	if (!(fs_info->workers && fs_info->hipri_workers &&
2316a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
23172a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2318fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
23192a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
23202a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2321f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2322f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2323b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
23242a458198SEric Sandeen 		return -ENOMEM;
23252a458198SEric Sandeen 	}
23262a458198SEric Sandeen 
23272a458198SEric Sandeen 	return 0;
23282a458198SEric Sandeen }
23292a458198SEric Sandeen 
23306d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
23316d97c6e3SJohannes Thumshirn {
23326d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2333b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
23346d97c6e3SJohannes Thumshirn 
2335b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
23366d97c6e3SJohannes Thumshirn 
23376d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
23386d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2339b4e967beSDavid Sterba 			  csum_driver);
23406d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
23416d97c6e3SJohannes Thumshirn 	}
23426d97c6e3SJohannes Thumshirn 
23436d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23446d97c6e3SJohannes Thumshirn 
2345c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2346c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2347c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
23486d97c6e3SJohannes Thumshirn 	return 0;
23496d97c6e3SJohannes Thumshirn }
23506d97c6e3SJohannes Thumshirn 
235163443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
235263443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
235363443bf5SEric Sandeen {
235463443bf5SEric Sandeen 	int ret;
235563443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
235663443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
235763443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2358581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
235963443bf5SEric Sandeen 
236063443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2361f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
236263443bf5SEric Sandeen 		return -EIO;
236363443bf5SEric Sandeen 	}
236463443bf5SEric Sandeen 
236596dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
236696dfcb46SJosef Bacik 					 GFP_KERNEL);
236763443bf5SEric Sandeen 	if (!log_tree_root)
236863443bf5SEric Sandeen 		return -ENOMEM;
236963443bf5SEric Sandeen 
23702ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
23711b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
23721b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
23731b7ec85eSJosef Bacik 					      NULL);
237464c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2375f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
23760eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
23778c38938cSJosef Bacik 		log_tree_root->node = NULL;
237800246528SJosef Bacik 		btrfs_put_root(log_tree_root);
23790eeff236SLiu Bo 		return ret;
23804eb150d6SQu Wenruo 	}
23814eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2382f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
238300246528SJosef Bacik 		btrfs_put_root(log_tree_root);
238463443bf5SEric Sandeen 		return -EIO;
238563443bf5SEric Sandeen 	}
23864eb150d6SQu Wenruo 
238763443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
238863443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
238963443bf5SEric Sandeen 	if (ret) {
23900b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
239163443bf5SEric Sandeen 				      "Failed to recover log tree");
239200246528SJosef Bacik 		btrfs_put_root(log_tree_root);
239363443bf5SEric Sandeen 		return ret;
239463443bf5SEric Sandeen 	}
239563443bf5SEric Sandeen 
2396bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
23976bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
239863443bf5SEric Sandeen 		if (ret)
239963443bf5SEric Sandeen 			return ret;
240063443bf5SEric Sandeen 	}
240163443bf5SEric Sandeen 
240263443bf5SEric Sandeen 	return 0;
240363443bf5SEric Sandeen }
240463443bf5SEric Sandeen 
2405abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2406abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2407abed4aaaSJosef Bacik 				      const char *name)
2408abed4aaaSJosef Bacik {
2409abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2410abed4aaaSJosef Bacik 	struct btrfs_root *root;
2411f7238e50SJosef Bacik 	u64 max_global_id = 0;
2412abed4aaaSJosef Bacik 	int ret;
2413abed4aaaSJosef Bacik 	struct btrfs_key key = {
2414abed4aaaSJosef Bacik 		.objectid = objectid,
2415abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2416abed4aaaSJosef Bacik 		.offset = 0,
2417abed4aaaSJosef Bacik 	};
2418abed4aaaSJosef Bacik 	bool found = false;
2419abed4aaaSJosef Bacik 
2420abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2421abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2422abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2423abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2424abed4aaaSJosef Bacik 		return 0;
2425abed4aaaSJosef Bacik 	}
2426abed4aaaSJosef Bacik 
2427abed4aaaSJosef Bacik 	while (1) {
2428abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2429abed4aaaSJosef Bacik 		if (ret < 0)
2430abed4aaaSJosef Bacik 			break;
2431abed4aaaSJosef Bacik 
2432abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2433abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2434abed4aaaSJosef Bacik 			if (ret) {
2435abed4aaaSJosef Bacik 				if (ret > 0)
2436abed4aaaSJosef Bacik 					ret = 0;
2437abed4aaaSJosef Bacik 				break;
2438abed4aaaSJosef Bacik 			}
2439abed4aaaSJosef Bacik 		}
2440abed4aaaSJosef Bacik 		ret = 0;
2441abed4aaaSJosef Bacik 
2442abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2443abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2444abed4aaaSJosef Bacik 			break;
2445abed4aaaSJosef Bacik 		btrfs_release_path(path);
2446abed4aaaSJosef Bacik 
2447f7238e50SJosef Bacik 		/*
2448f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2449f7238e50SJosef Bacik 		 * everybody.
2450f7238e50SJosef Bacik 		 */
2451f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2452f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2453f7238e50SJosef Bacik 
2454abed4aaaSJosef Bacik 		found = true;
2455abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2456abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2457abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2458abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2459abed4aaaSJosef Bacik 			break;
2460abed4aaaSJosef Bacik 		}
2461abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2462abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2463abed4aaaSJosef Bacik 		if (ret) {
2464abed4aaaSJosef Bacik 			btrfs_put_root(root);
2465abed4aaaSJosef Bacik 			break;
2466abed4aaaSJosef Bacik 		}
2467abed4aaaSJosef Bacik 		key.offset++;
2468abed4aaaSJosef Bacik 	}
2469abed4aaaSJosef Bacik 	btrfs_release_path(path);
2470abed4aaaSJosef Bacik 
2471f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2472f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2473f7238e50SJosef Bacik 
2474abed4aaaSJosef Bacik 	if (!found || ret) {
2475abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2476abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2477abed4aaaSJosef Bacik 
2478abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2479abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2480abed4aaaSJosef Bacik 		else
2481abed4aaaSJosef Bacik 			ret = 0;
2482abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2483abed4aaaSJosef Bacik 	}
2484abed4aaaSJosef Bacik 	return ret;
2485abed4aaaSJosef Bacik }
2486abed4aaaSJosef Bacik 
2487abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2488abed4aaaSJosef Bacik {
2489abed4aaaSJosef Bacik 	struct btrfs_path *path;
2490abed4aaaSJosef Bacik 	int ret = 0;
2491abed4aaaSJosef Bacik 
2492abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2493abed4aaaSJosef Bacik 	if (!path)
2494abed4aaaSJosef Bacik 		return -ENOMEM;
2495abed4aaaSJosef Bacik 
2496abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2497abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2498abed4aaaSJosef Bacik 	if (ret)
2499abed4aaaSJosef Bacik 		goto out;
2500abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2501abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2502abed4aaaSJosef Bacik 	if (ret)
2503abed4aaaSJosef Bacik 		goto out;
2504abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2505abed4aaaSJosef Bacik 		goto out;
2506abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2507abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2508abed4aaaSJosef Bacik 					 "free space");
2509abed4aaaSJosef Bacik out:
2510abed4aaaSJosef Bacik 	btrfs_free_path(path);
2511abed4aaaSJosef Bacik 	return ret;
2512abed4aaaSJosef Bacik }
2513abed4aaaSJosef Bacik 
25146bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
25154bbcaa64SEric Sandeen {
25166bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2517a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
25184bbcaa64SEric Sandeen 	struct btrfs_key location;
25194bbcaa64SEric Sandeen 	int ret;
25204bbcaa64SEric Sandeen 
25216bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
25226bccf3abSJeff Mahoney 
2523abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2524abed4aaaSJosef Bacik 	if (ret)
2525abed4aaaSJosef Bacik 		return ret;
2526abed4aaaSJosef Bacik 
25274bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
25284bbcaa64SEric Sandeen 	location.offset = 0;
25294bbcaa64SEric Sandeen 
25301c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
253114033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
253214033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
253314033b08SQu Wenruo 		if (IS_ERR(root)) {
253414033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
253514033b08SQu Wenruo 				ret = PTR_ERR(root);
253614033b08SQu Wenruo 				goto out;
253714033b08SQu Wenruo 			}
253814033b08SQu Wenruo 		} else {
253914033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
254014033b08SQu Wenruo 			fs_info->block_group_root = root;
254114033b08SQu Wenruo 		}
254214033b08SQu Wenruo 	}
254314033b08SQu Wenruo 
254414033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2545a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2546f50f4353SLiu Bo 	if (IS_ERR(root)) {
254742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2548f50f4353SLiu Bo 			ret = PTR_ERR(root);
2549f50f4353SLiu Bo 			goto out;
2550f50f4353SLiu Bo 		}
255142437a63SJosef Bacik 	} else {
2552a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2553a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
255442437a63SJosef Bacik 	}
2555820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2556820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
25574bbcaa64SEric Sandeen 
2558aeb935a4SQu Wenruo 	/*
2559aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2560aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2561aeb935a4SQu Wenruo 	 */
256256e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
256356e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2564aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
256542437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2566aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2567aeb935a4SQu Wenruo 			goto out;
2568aeb935a4SQu Wenruo 		}
256942437a63SJosef Bacik 	} else {
2570aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2571aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
257242437a63SJosef Bacik 	}
2573aeb935a4SQu Wenruo 
25744bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2575a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2576a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2577a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2578afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2579a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25804bbcaa64SEric Sandeen 	}
25814bbcaa64SEric Sandeen 
25824bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2583a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2584a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
258542437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2586a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25874bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2588f50f4353SLiu Bo 				goto out;
258942437a63SJosef Bacik 		}
25904bbcaa64SEric Sandeen 	} else {
2591a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2592a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25934bbcaa64SEric Sandeen 	}
25944bbcaa64SEric Sandeen 
25954bbcaa64SEric Sandeen 	return 0;
2596f50f4353SLiu Bo out:
2597f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2598f50f4353SLiu Bo 		   location.objectid, ret);
2599f50f4353SLiu Bo 	return ret;
26004bbcaa64SEric Sandeen }
26014bbcaa64SEric Sandeen 
2602069ec957SQu Wenruo /*
2603069ec957SQu Wenruo  * Real super block validation
2604069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2605069ec957SQu Wenruo  *
2606069ec957SQu Wenruo  * @sb:		super block to check
2607069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2608069ec957SQu Wenruo  * 		0	the primary (1st) sb
2609069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2610069ec957SQu Wenruo  * 	       -1	skip bytenr check
2611069ec957SQu Wenruo  */
2612a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2613069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
261421a852b0SQu Wenruo {
261521a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
261621a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
261721a852b0SQu Wenruo 	int ret = 0;
261821a852b0SQu Wenruo 
261921a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
262021a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
262121a852b0SQu Wenruo 		ret = -EINVAL;
262221a852b0SQu Wenruo 	}
262321a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
262421a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
262521a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
262621a852b0SQu Wenruo 		ret = -EINVAL;
262721a852b0SQu Wenruo 	}
262821a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
262921a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
263021a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
263121a852b0SQu Wenruo 		ret = -EINVAL;
263221a852b0SQu Wenruo 	}
263321a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
263421a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
263521a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
263621a852b0SQu Wenruo 		ret = -EINVAL;
263721a852b0SQu Wenruo 	}
263821a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
263921a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
264021a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
264121a852b0SQu Wenruo 		ret = -EINVAL;
264221a852b0SQu Wenruo 	}
264321a852b0SQu Wenruo 
264421a852b0SQu Wenruo 	/*
264521a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
264621a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
264721a852b0SQu Wenruo 	 */
264821a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
264921a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
265021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
265121a852b0SQu Wenruo 		ret = -EINVAL;
265221a852b0SQu Wenruo 	}
26530bb3eb3eSQu Wenruo 
26540bb3eb3eSQu Wenruo 	/*
26551a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
26561a42daabSQu Wenruo 	 *
26571a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
26581a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
26591a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
26601a42daabSQu Wenruo 	 * beginning.
26610bb3eb3eSQu Wenruo 	 */
26621a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
266321a852b0SQu Wenruo 		btrfs_err(fs_info,
26640bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
266521a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
266621a852b0SQu Wenruo 		ret = -EINVAL;
266721a852b0SQu Wenruo 	}
26680bb3eb3eSQu Wenruo 
266921a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
267021a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
267121a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
267221a852b0SQu Wenruo 		ret = -EINVAL;
267321a852b0SQu Wenruo 	}
267421a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
267521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
267621a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
267721a852b0SQu Wenruo 		ret = -EINVAL;
267821a852b0SQu Wenruo 	}
267921a852b0SQu Wenruo 
268021a852b0SQu Wenruo 	/* Root alignment check */
268121a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
268221a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
268321a852b0SQu Wenruo 			   btrfs_super_root(sb));
268421a852b0SQu Wenruo 		ret = -EINVAL;
268521a852b0SQu Wenruo 	}
268621a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
268721a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
268821a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
268921a852b0SQu Wenruo 		ret = -EINVAL;
269021a852b0SQu Wenruo 	}
269121a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
269221a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
269321a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
269421a852b0SQu Wenruo 		ret = -EINVAL;
269521a852b0SQu Wenruo 	}
269621a852b0SQu Wenruo 
2697aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2698aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2699aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2700aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2701aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2702aefd7f70SNikolay Borisov 		ret = -EINVAL;
2703aefd7f70SNikolay Borisov 	}
2704aefd7f70SNikolay Borisov 
2705aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2706aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2707aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2708aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2709aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2710aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2711aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2712aefd7f70SNikolay Borisov 		ret = -EINVAL;
2713aefd7f70SNikolay Borisov 	}
2714aefd7f70SNikolay Borisov 
27151c56ab99SQu Wenruo 	/*
27161c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
27171c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
27181c56ab99SQu Wenruo 	 */
27191c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
27201c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
27211c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
27221c56ab99SQu Wenruo 		btrfs_err(fs_info,
27231c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
27241c56ab99SQu Wenruo 		ret = -EINVAL;
27251c56ab99SQu Wenruo 	}
27261c56ab99SQu Wenruo 
2727de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
27287239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
272921a852b0SQu Wenruo 		btrfs_err(fs_info,
27307239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2731de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
273221a852b0SQu Wenruo 		ret = -EINVAL;
273321a852b0SQu Wenruo 	}
273421a852b0SQu Wenruo 
273521a852b0SQu Wenruo 	/*
273621a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
273721a852b0SQu Wenruo 	 * done later
273821a852b0SQu Wenruo 	 */
273921a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
274021a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
274121a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
274221a852b0SQu Wenruo 		ret = -EINVAL;
274321a852b0SQu Wenruo 	}
274421a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
274521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
274621a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
274721a852b0SQu Wenruo 		ret = -EINVAL;
274821a852b0SQu Wenruo 	}
274921a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
275021a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
275121a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
275221a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
275321a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
275421a852b0SQu Wenruo 		ret = -EINVAL;
275521a852b0SQu Wenruo 	}
275621a852b0SQu Wenruo 
2757069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2758069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
275921a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
276021a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
276121a852b0SQu Wenruo 		ret = -EINVAL;
276221a852b0SQu Wenruo 	}
276321a852b0SQu Wenruo 
276421a852b0SQu Wenruo 	/*
276521a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
276621a852b0SQu Wenruo 	 * and one chunk
276721a852b0SQu Wenruo 	 */
276821a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
276921a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
277021a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
277121a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
277221a852b0SQu Wenruo 		ret = -EINVAL;
277321a852b0SQu Wenruo 	}
277421a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
277521a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
277621a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
277721a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
277821a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
277921a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
278021a852b0SQu Wenruo 		ret = -EINVAL;
278121a852b0SQu Wenruo 	}
278221a852b0SQu Wenruo 
278321a852b0SQu Wenruo 	/*
278421a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
278521a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
278621a852b0SQu Wenruo 	 */
278721a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
278821a852b0SQu Wenruo 		btrfs_warn(fs_info,
278921a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
279021a852b0SQu Wenruo 			btrfs_super_generation(sb),
279121a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
279221a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
279321a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
279421a852b0SQu Wenruo 		btrfs_warn(fs_info,
279521a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
279621a852b0SQu Wenruo 			btrfs_super_generation(sb),
279721a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
279821a852b0SQu Wenruo 
279921a852b0SQu Wenruo 	return ret;
280021a852b0SQu Wenruo }
280121a852b0SQu Wenruo 
2802069ec957SQu Wenruo /*
2803069ec957SQu Wenruo  * Validation of super block at mount time.
2804069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2805069ec957SQu Wenruo  * flags will be skipped.
2806069ec957SQu Wenruo  */
2807069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2808069ec957SQu Wenruo {
2809a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2810069ec957SQu Wenruo }
2811069ec957SQu Wenruo 
281275cb857dSQu Wenruo /*
281375cb857dSQu Wenruo  * Validation of super block at write time.
281475cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
281575cb857dSQu Wenruo  * overwritten soon.
281675cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
281775cb857dSQu Wenruo  */
281875cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
281975cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
282075cb857dSQu Wenruo {
282175cb857dSQu Wenruo 	int ret;
282275cb857dSQu Wenruo 
2823a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
282475cb857dSQu Wenruo 	if (ret < 0)
282575cb857dSQu Wenruo 		goto out;
2826e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
282775cb857dSQu Wenruo 		ret = -EUCLEAN;
282875cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
282975cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
283075cb857dSQu Wenruo 		goto out;
283175cb857dSQu Wenruo 	}
283275cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
283375cb857dSQu Wenruo 		ret = -EUCLEAN;
283475cb857dSQu Wenruo 		btrfs_err(fs_info,
283575cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
283675cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
283775cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
283875cb857dSQu Wenruo 		goto out;
283975cb857dSQu Wenruo 	}
284075cb857dSQu Wenruo out:
284175cb857dSQu Wenruo 	if (ret < 0)
284275cb857dSQu Wenruo 		btrfs_err(fs_info,
284375cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
284475cb857dSQu Wenruo 	return ret;
284575cb857dSQu Wenruo }
284675cb857dSQu Wenruo 
2847bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2848bd676446SJosef Bacik {
2849bd676446SJosef Bacik 	int ret = 0;
2850bd676446SJosef Bacik 
2851bd676446SJosef Bacik 	root->node = read_tree_block(root->fs_info, bytenr,
2852bd676446SJosef Bacik 				     root->root_key.objectid, gen, level, NULL);
2853bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2854bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2855bd676446SJosef Bacik 		root->node = NULL;
28564eb150d6SQu Wenruo 		return ret;
28574eb150d6SQu Wenruo 	}
28584eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2859bd676446SJosef Bacik 		free_extent_buffer(root->node);
2860bd676446SJosef Bacik 		root->node = NULL;
28614eb150d6SQu Wenruo 		return -EIO;
2862bd676446SJosef Bacik 	}
2863bd676446SJosef Bacik 
2864bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2865bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2866bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2867bd676446SJosef Bacik 	return ret;
2868bd676446SJosef Bacik }
2869bd676446SJosef Bacik 
2870bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2871bd676446SJosef Bacik {
2872bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2873bd676446SJosef Bacik 	u64 gen, bytenr;
2874bd676446SJosef Bacik 	int level, ret;
2875bd676446SJosef Bacik 
2876bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2877bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2878bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2879bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
28809c54e80dSJosef Bacik 	if (ret) {
2881bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2882bd676446SJosef Bacik 		return ret;
2883bd676446SJosef Bacik 	}
28849c54e80dSJosef Bacik 	return 0;
28859c54e80dSJosef Bacik }
28869c54e80dSJosef Bacik 
28876ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2888b8522a1eSNikolay Borisov {
28896ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2890b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2891b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2892b8522a1eSNikolay Borisov 	bool handle_error = false;
2893b8522a1eSNikolay Borisov 	int ret = 0;
2894b8522a1eSNikolay Borisov 	int i;
2895b8522a1eSNikolay Borisov 
2896b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2897b8522a1eSNikolay Borisov 		if (handle_error) {
2898b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2899b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2900b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2901b8522a1eSNikolay Borisov 
2902b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2903b8522a1eSNikolay Borisov 				break;
2904b8522a1eSNikolay Borisov 
2905b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2906b8522a1eSNikolay Borisov 
2907b8522a1eSNikolay Borisov 			/*
2908b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2909b8522a1eSNikolay Borisov 			 * valid
2910b8522a1eSNikolay Borisov 			 */
2911b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2912b8522a1eSNikolay Borisov 
2913b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2914b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2915b8522a1eSNikolay Borisov 
2916b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
29176ef108ddSNikolay Borisov 			backup_index = ret;
2918b8522a1eSNikolay Borisov 			if (ret < 0)
2919b8522a1eSNikolay Borisov 				return ret;
2920b8522a1eSNikolay Borisov 		}
2921b8522a1eSNikolay Borisov 
2922bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2923bd676446SJosef Bacik 		if (ret) {
2924217f5004SNikolay Borisov 			handle_error = true;
2925b8522a1eSNikolay Borisov 			continue;
2926b8522a1eSNikolay Borisov 		}
2927b8522a1eSNikolay Borisov 
2928336a0d8dSNikolay Borisov 		/*
2929336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2930336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2931336a0d8dSNikolay Borisov 		 */
2932453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2933b8522a1eSNikolay Borisov 		if (ret < 0) {
2934b8522a1eSNikolay Borisov 			handle_error = true;
2935b8522a1eSNikolay Borisov 			continue;
2936b8522a1eSNikolay Borisov 		}
2937b8522a1eSNikolay Borisov 
29386b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2939b8522a1eSNikolay Borisov 
2940b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2941b8522a1eSNikolay Borisov 		if (ret < 0) {
2942b8522a1eSNikolay Borisov 			handle_error = true;
2943b8522a1eSNikolay Borisov 			continue;
2944b8522a1eSNikolay Borisov 		}
2945b8522a1eSNikolay Borisov 
2946b8522a1eSNikolay Borisov 		/* All successful */
2947bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2948bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2949d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
29506ef108ddSNikolay Borisov 
29516ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
29526ef108ddSNikolay Borisov 		if (backup_index < 0) {
29536ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
29546ef108ddSNikolay Borisov 		} else {
29556ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
29566ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
29576ef108ddSNikolay Borisov 		}
2958b8522a1eSNikolay Borisov 		break;
2959b8522a1eSNikolay Borisov 	}
2960b8522a1eSNikolay Borisov 
2961b8522a1eSNikolay Borisov 	return ret;
2962b8522a1eSNikolay Borisov }
2963b8522a1eSNikolay Borisov 
29648260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2965eb60ceacSChris Mason {
2966fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
296701cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
29688fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2969facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
297024bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2971eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
297211833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2973eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2974a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2975fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
297624bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
29774cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2978ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2979f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
298047ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
298140ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2982afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2983c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2984f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2985abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2986d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2987f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
29887585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2989573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
29900bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
29915f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2992de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
299319c00ddcSChris Mason 
2994e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
29955a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
29968b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
29975f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
29983e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
29993e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
30003e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
30013e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
30023e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
30033e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
30043e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
30053e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
3006e1489b4fSIoannis Angelakopoulos 
30070b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
30086324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
3009f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
301047ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
301118bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
3012afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
3013bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
3014bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
30153fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
30163fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
3017bd647ce3SJosef Bacik #endif
3018c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
301966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
302066d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
302166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
302266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
302366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
302466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
302566d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
3026ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
3027ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
3028ba2c4d4eSJosef Bacik 
3029771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
30304cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
3031034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
3032fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
3033abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
303495ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
30359ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
30364cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
3037a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
3038f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
30398b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
3040f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
3041fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
3042c8b97818SChris Mason 
3043b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
3044b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
30450afbaf8cSChris Mason 
3046199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
3047199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
304869fe2d75SJosef Bacik 
3049638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
305021adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
305121adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
305221adbd5cSStefan Behrens #endif
3053779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
305457056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
3055a2de733cSArne Jansen 
305616b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
305708dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
30580f9dd46cSJosef Bacik 
3059fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
3060fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
306139279cc3SChris Mason 
30625a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
3063e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
3064925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
3065a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
3066a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
30671bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
30689e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
3069c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
307076dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
3071803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
3072fa9c0d79SChris Mason 
3073ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
3074f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
3075b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
3076416ac51dSArne Jansen 
3077fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3078fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3079fa9c0d79SChris Mason 
3080e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
3081f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
3082bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
30834854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
3084034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
30853768f368SChris Mason 
3086da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
3087da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
3088da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
3089ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
3090da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
3091da17066cSJeff Mahoney 
3092f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
3093f7b12a62SNaohiro Aota 
3094eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
3095eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
3096eede2bf3SOmar Sandoval 
309718bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
309818bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
30998260edbaSJosef Bacik }
31008260edbaSJosef Bacik 
31018260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
31028260edbaSJosef Bacik {
31038260edbaSJosef Bacik 	int ret;
31048260edbaSJosef Bacik 
31058260edbaSJosef Bacik 	fs_info->sb = sb;
31068260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
31078260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
31089e967495SFilipe Manana 
31095deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3110ae18c37aSJosef Bacik 	if (ret)
3111ae18c37aSJosef Bacik 		return ret;
3112ae18c37aSJosef Bacik 
3113ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3114ae18c37aSJosef Bacik 	if (ret)
3115c75e8394SJosef Bacik 		return ret;
3116ae18c37aSJosef Bacik 
3117ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3118ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3119ae18c37aSJosef Bacik 
3120ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3121ae18c37aSJosef Bacik 	if (ret)
3122c75e8394SJosef Bacik 		return ret;
3123ae18c37aSJosef Bacik 
3124ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3125ae18c37aSJosef Bacik 			GFP_KERNEL);
3126ae18c37aSJosef Bacik 	if (ret)
3127c75e8394SJosef Bacik 		return ret;
3128ae18c37aSJosef Bacik 
3129ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3130ae18c37aSJosef Bacik 					GFP_KERNEL);
3131c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3132c75e8394SJosef Bacik 		return -ENOMEM;
3133ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3134ae18c37aSJosef Bacik 
3135a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3136a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3137a0a1db70SFilipe Manana 
3138c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3139ae18c37aSJosef Bacik }
3140ae18c37aSJosef Bacik 
314197f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
314297f4dd09SNikolay Borisov {
31430d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
314497f4dd09SNikolay Borisov 	int ret;
314597f4dd09SNikolay Borisov 
314697f4dd09SNikolay Borisov 	/*
314797f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
314897f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
314997f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
315097f4dd09SNikolay Borisov 	 */
315197f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
315297f4dd09SNikolay Borisov 	if (ret < 0) {
3153c94bec2cSJosef Bacik 		if (ret != -EINTR)
3154c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3155c94bec2cSJosef Bacik 				   ret);
315697f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
315797f4dd09SNikolay Borisov 		return ret;
315897f4dd09SNikolay Borisov 	}
315997f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
316097f4dd09SNikolay Borisov }
316197f4dd09SNikolay Borisov 
316297f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
316397f4dd09SNikolay Borisov {
316497f4dd09SNikolay Borisov 	struct task_struct *task;
316597f4dd09SNikolay Borisov 
316697f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
316797f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
316897f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
316997f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
317097f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
317197f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
317297f4dd09SNikolay Borisov 		return PTR_ERR(task);
317397f4dd09SNikolay Borisov 	}
317497f4dd09SNikolay Borisov 
317597f4dd09SNikolay Borisov 	return 0;
317697f4dd09SNikolay Borisov }
317797f4dd09SNikolay Borisov 
317844c0ca21SBoris Burkov /*
31798cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
31808cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
31818cd29088SBoris Burkov  * code paths.
31828cd29088SBoris Burkov  */
31838cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
31848cd29088SBoris Burkov {
31858cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
31868b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
31878cd29088SBoris Burkov }
31888cd29088SBoris Burkov 
31898cd29088SBoris Burkov /*
319044c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
319144c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
319244c0ca21SBoris Burkov  */
319344c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
319444c0ca21SBoris Burkov {
319544c0ca21SBoris Burkov 	int ret;
319694846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
31978b228324SBoris Burkov 	bool clear_free_space_tree = false;
31988b228324SBoris Burkov 
31998b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
32008b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32018b228324SBoris Burkov 		clear_free_space_tree = true;
32028b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
32038b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
32048b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
32058b228324SBoris Burkov 		clear_free_space_tree = true;
32068b228324SBoris Burkov 	}
32078b228324SBoris Burkov 
32088b228324SBoris Burkov 	if (clear_free_space_tree) {
32098b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
32108b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
32118b228324SBoris Burkov 		if (ret) {
32128b228324SBoris Burkov 			btrfs_warn(fs_info,
32138b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
32148b228324SBoris Burkov 			goto out;
32158b228324SBoris Burkov 		}
32168b228324SBoris Burkov 	}
321744c0ca21SBoris Burkov 
32188d488a8cSFilipe Manana 	/*
32198d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
32208d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3221fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
32228d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
32238d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
32248d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
32258d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
32268d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
32278d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
32288d488a8cSFilipe Manana 	 */
32298d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
32308d488a8cSFilipe Manana 	if (ret)
32318d488a8cSFilipe Manana 		goto out;
32328d488a8cSFilipe Manana 
323344c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
323444c0ca21SBoris Burkov 	if (ret)
323544c0ca21SBoris Burkov 		goto out;
323644c0ca21SBoris Burkov 
32378f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
32388f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
32398f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
32408f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
32418f1c21d7SBoris Burkov 		goto out;
32428f1c21d7SBoris Burkov 	}
32438f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
32448f1c21d7SBoris Burkov 
324544c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
32467eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
324744c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
324844c0ca21SBoris Burkov 	if (ret < 0) {
324944c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
325044c0ca21SBoris Burkov 		goto out;
325144c0ca21SBoris Burkov 	}
325244c0ca21SBoris Burkov 
32535011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
32545011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32555011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
32565011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
32575011139aSBoris Burkov 		if (ret) {
32585011139aSBoris Burkov 			btrfs_warn(fs_info,
32595011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
32605011139aSBoris Burkov 			goto out;
32615011139aSBoris Burkov 		}
32625011139aSBoris Burkov 	}
32635011139aSBoris Burkov 
326494846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
326594846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
326694846229SBoris Burkov 		if (ret)
326794846229SBoris Burkov 			goto out;
326894846229SBoris Burkov 	}
326994846229SBoris Burkov 
327044c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
327144c0ca21SBoris Burkov 	if (ret)
327244c0ca21SBoris Burkov 		goto out;
327344c0ca21SBoris Burkov 
327444c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
327544c0ca21SBoris Burkov 	if (ret) {
327644c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
327744c0ca21SBoris Burkov 		goto out;
327844c0ca21SBoris Burkov 	}
327944c0ca21SBoris Burkov 
328044c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
328144c0ca21SBoris Burkov 
328244c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
328344c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
328444c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
328544c0ca21SBoris Burkov 		if (ret) {
328644c0ca21SBoris Burkov 			btrfs_warn(fs_info,
328744c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
328844c0ca21SBoris Burkov 			goto out;
328944c0ca21SBoris Burkov 		}
329044c0ca21SBoris Burkov 	}
329144c0ca21SBoris Burkov 
329244c0ca21SBoris Burkov out:
329344c0ca21SBoris Burkov 	return ret;
329444c0ca21SBoris Burkov }
329544c0ca21SBoris Burkov 
3296ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3297ae18c37aSJosef Bacik 		      char *options)
3298ae18c37aSJosef Bacik {
3299ae18c37aSJosef Bacik 	u32 sectorsize;
3300ae18c37aSJosef Bacik 	u32 nodesize;
3301ae18c37aSJosef Bacik 	u32 stripesize;
3302ae18c37aSJosef Bacik 	u64 generation;
3303ae18c37aSJosef Bacik 	u64 features;
3304ae18c37aSJosef Bacik 	u16 csum_type;
3305ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3306ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3307ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3308ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3309ae18c37aSJosef Bacik 	int ret;
3310ae18c37aSJosef Bacik 	int err = -EINVAL;
3311ae18c37aSJosef Bacik 	int level;
3312ae18c37aSJosef Bacik 
33138260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
331453b381b3SDavid Woodhouse 	if (ret) {
331583c8266aSDavid Sterba 		err = ret;
3316ae18c37aSJosef Bacik 		goto fail;
331753b381b3SDavid Woodhouse 	}
331853b381b3SDavid Woodhouse 
3319ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3320ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3321ae18c37aSJosef Bacik 				     GFP_KERNEL);
3322ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3323ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3324ae18c37aSJosef Bacik 				      GFP_KERNEL);
3325ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3326ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3327ae18c37aSJosef Bacik 		err = -ENOMEM;
3328c75e8394SJosef Bacik 		goto fail;
3329ae18c37aSJosef Bacik 	}
3330ae18c37aSJosef Bacik 
3331ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3332ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3333ae18c37aSJosef Bacik 		err = -ENOMEM;
3334c75e8394SJosef Bacik 		goto fail;
3335ae18c37aSJosef Bacik 	}
3336ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3337ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3338ae18c37aSJosef Bacik 
3339d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
33401104a885SDavid Sterba 
33411104a885SDavid Sterba 	/*
33421104a885SDavid Sterba 	 * Read super block and check the signature bytes only
33431104a885SDavid Sterba 	 */
3344d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
33458f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
33468f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
334716cdcec7SMiao Xie 		goto fail_alloc;
334820b45077SDave Young 	}
334939279cc3SChris Mason 
33501104a885SDavid Sterba 	/*
3351260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
33528dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
33538dc3f22cSJohannes Thumshirn 	 */
33548f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
335551bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
33568dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
335751bce6c9SJohannes Thumshirn 			  csum_type);
33588dc3f22cSJohannes Thumshirn 		err = -EINVAL;
33598f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33608dc3f22cSJohannes Thumshirn 		goto fail_alloc;
33618dc3f22cSJohannes Thumshirn 	}
33628dc3f22cSJohannes Thumshirn 
336383c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
336483c68bbcSSu Yue 
33656d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
33666d97c6e3SJohannes Thumshirn 	if (ret) {
33676d97c6e3SJohannes Thumshirn 		err = ret;
33688f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33696d97c6e3SJohannes Thumshirn 		goto fail_alloc;
33706d97c6e3SJohannes Thumshirn 	}
33716d97c6e3SJohannes Thumshirn 
33728dc3f22cSJohannes Thumshirn 	/*
33731104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
33741104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
33751104a885SDavid Sterba 	 */
33768f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
337705135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
33781104a885SDavid Sterba 		err = -EINVAL;
33798f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3380141386e1SJosef Bacik 		goto fail_alloc;
33811104a885SDavid Sterba 	}
33821104a885SDavid Sterba 
33831104a885SDavid Sterba 	/*
33841104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
33851104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
33861104a885SDavid Sterba 	 * the whole block of INFO_SIZE
33871104a885SDavid Sterba 	 */
33888f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
33898f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
33905f39d397SChris Mason 
3391fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3392fbc6feaeSNikolay Borisov 
33930b86a832SChris Mason 
3394fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3395fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3396fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3397fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3398fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3399fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3400fbc6feaeSNikolay Borisov 	}
3401fbc6feaeSNikolay Borisov 
3402fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3403fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3404de37aa51SNikolay Borisov 
3405069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
34061104a885SDavid Sterba 	if (ret) {
340705135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
34081104a885SDavid Sterba 		err = -EINVAL;
3409141386e1SJosef Bacik 		goto fail_alloc;
34101104a885SDavid Sterba 	}
34111104a885SDavid Sterba 
34120f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3413141386e1SJosef Bacik 		goto fail_alloc;
34140f7d52f4SChris Mason 
3415acce952bSliubo 	/* check FS state, whether FS is broken. */
341687533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
341787533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3418acce952bSliubo 
341975e7cb7fSLiu Bo 	/*
342075e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
342175e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
342275e7cb7fSLiu Bo 	 */
342375e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
342475e7cb7fSLiu Bo 
34256f93e834SAnand Jain 
34266f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
34276f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
34286f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
34296f93e834SAnand Jain 	stripesize = sectorsize;
34306f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
34316f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
34326f93e834SAnand Jain 
34336f93e834SAnand Jain 	fs_info->nodesize = nodesize;
34346f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
34356f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
34366f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
34376f93e834SAnand Jain 	fs_info->stripesize = stripesize;
34386f93e834SAnand Jain 
34392ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
34402b82032cSYan Zheng 	if (ret) {
34412b82032cSYan Zheng 		err = ret;
3442141386e1SJosef Bacik 		goto fail_alloc;
34432b82032cSYan Zheng 	}
3444dfe25020SChris Mason 
3445f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3446f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3447f2b636e8SJosef Bacik 	if (features) {
344805135f59SDavid Sterba 		btrfs_err(fs_info,
3449d5321a0fSQu Wenruo 		    "cannot mount because of unsupported optional features (0x%llx)",
3450c1c9ff7cSGeert Uytterhoeven 		    features);
3451f2b636e8SJosef Bacik 		err = -EINVAL;
3452141386e1SJosef Bacik 		goto fail_alloc;
3453f2b636e8SJosef Bacik 	}
3454f2b636e8SJosef Bacik 
34555d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
34565d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
34570b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3458a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
34595c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
34605c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3461727011e0SChris Mason 
3462727011e0SChris Mason 	/*
3463e26b04c4SNikolay Borisov 	 * Flag our filesystem as having big metadata blocks if they are bigger
3464e26b04c4SNikolay Borisov 	 * than the page size.
3465e26b04c4SNikolay Borisov 	 */
34666b769dacSNikolay Borisov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3467e26b04c4SNikolay Borisov 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3468727011e0SChris Mason 
3469727011e0SChris Mason 	/*
3470bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3471bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3472bc3f116fSChris Mason 	 */
3473bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3474707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
347505135f59SDavid Sterba 		btrfs_err(fs_info,
347605135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
347705135f59SDavid Sterba 			nodesize, sectorsize);
3478141386e1SJosef Bacik 		goto fail_alloc;
3479bc3f116fSChris Mason 	}
3480bc3f116fSChris Mason 
3481ceda0864SMiao Xie 	/*
3482ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3483ceda0864SMiao Xie 	 * update the flag.
3484ceda0864SMiao Xie 	 */
34855d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
34865d4f98a2SYan Zheng 
3487f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3488f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3489bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
349005135f59SDavid Sterba 		btrfs_err(fs_info,
3491d5321a0fSQu Wenruo 	"cannot mount read-write because of unsupported optional features (0x%llx)",
3492c1c9ff7cSGeert Uytterhoeven 		       features);
3493f2b636e8SJosef Bacik 		err = -EINVAL;
3494141386e1SJosef Bacik 		goto fail_alloc;
3495f2b636e8SJosef Bacik 	}
3496dc4d3168SQu Wenruo 	/*
3497dc4d3168SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3498dc4d3168SQu Wenruo 	 * should not cause any metadata write, including log replay.
3499dc4d3168SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3500dc4d3168SQu Wenruo 	 */
3501dc4d3168SQu Wenruo 	if (unlikely(features && btrfs_super_log_root(disk_super) &&
3502dc4d3168SQu Wenruo 		     !btrfs_test_opt(fs_info, NOLOGREPLAY))) {
3503dc4d3168SQu Wenruo 		btrfs_err(fs_info,
3504dc4d3168SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3505dc4d3168SQu Wenruo 			  features);
3506dc4d3168SQu Wenruo 		err = -EINVAL;
3507dc4d3168SQu Wenruo 		goto fail_alloc;
3508dc4d3168SQu Wenruo 	}
3509dc4d3168SQu Wenruo 
351061d92c32SChris Mason 
35118481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
35128481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
35138481dd80SQu Wenruo 
35149f73f1aeSQu Wenruo 		/*
35159f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
35169f73f1aeSQu Wenruo 		 * going to be deprecated.
35179f73f1aeSQu Wenruo 		 *
35189f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
35199f73f1aeSQu Wenruo 		 */
35209f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
35219f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
35229f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
35239f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
35249f73f1aeSQu Wenruo 
352595ea0486SQu Wenruo 		btrfs_warn(fs_info,
352695ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
35270bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
35288481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
35298481dd80SQu Wenruo 		if (!subpage_info)
35308481dd80SQu Wenruo 			goto fail_alloc;
35318481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
35328481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3533c8050b3bSQu Wenruo 	}
35340bb3eb3eSQu Wenruo 
3535d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
35362a458198SEric Sandeen 	if (ret) {
35372a458198SEric Sandeen 		err = ret;
35380dc3b84aSJosef Bacik 		goto fail_sb_buffer;
35390dc3b84aSJosef Bacik 	}
35404543df7eSChris Mason 
35419e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
35429e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
35434575c9ccSChris Mason 
3544a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3545a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3546de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3547db94535dSChris Mason 
3548925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
35496bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3550925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
355184eed90fSChris Mason 	if (ret) {
355205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
35535d4f98a2SYan Zheng 		goto fail_sb_buffer;
355484eed90fSChris Mason 	}
35550b86a832SChris Mason 
355684234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3557581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3558bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3559bd676446SJosef Bacik 			      generation, level);
3560bd676446SJosef Bacik 	if (ret) {
356105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3562af31f5e5SChris Mason 		goto fail_tree_roots;
356383121942SDavid Woodhouse 	}
35640b86a832SChris Mason 
3565e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3566c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3567c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3568e17cade2SChris Mason 
35695b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
35702b82032cSYan Zheng 	if (ret) {
357105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3572af31f5e5SChris Mason 		goto fail_tree_roots;
35732b82032cSYan Zheng 	}
35740b86a832SChris Mason 
35758dabb742SStefan Behrens 	/*
3576bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3577bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3578bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
35791a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3580bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
35818dabb742SStefan Behrens 	 */
3582bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3583d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
358405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3585a6b0d5c8SChris Mason 		goto fail_tree_roots;
3586a6b0d5c8SChris Mason 	}
3587a6b0d5c8SChris Mason 
3588b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
35894bbcaa64SEric Sandeen 	if (ret)
3590b8522a1eSNikolay Borisov 		goto fail_tree_roots;
35918929ecfaSYan, Zheng 
359275ec1db8SJosef Bacik 	/*
359373651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
359473651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
359573651042SNaohiro Aota 	 * zoned incompat feature flag set.
359673651042SNaohiro Aota 	 */
359773651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
359873651042SNaohiro Aota 	if (ret) {
359973651042SNaohiro Aota 		btrfs_err(fs_info,
360073651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
360173651042SNaohiro Aota 			  ret);
360273651042SNaohiro Aota 		goto fail_block_groups;
360373651042SNaohiro Aota 	}
360473651042SNaohiro Aota 
360573651042SNaohiro Aota 	/*
360675ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
360775ec1db8SJosef Bacik 	 * check the generation here so we can set the
360875ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
360975ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
361075ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
361175ec1db8SJosef Bacik 	 * even though it was perfectly fine.
361275ec1db8SJosef Bacik 	 */
361375ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
361475ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
361575ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
361675ec1db8SJosef Bacik 
3617cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3618cf90d884SQu Wenruo 	if (ret) {
3619cf90d884SQu Wenruo 		btrfs_err(fs_info,
3620cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3621cf90d884SQu Wenruo 			  ret);
3622cf90d884SQu Wenruo 		goto fail_block_groups;
3623cf90d884SQu Wenruo 	}
362468310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
362568310a5eSIlya Dryomov 	if (ret) {
362605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
362768310a5eSIlya Dryomov 		goto fail_block_groups;
362868310a5eSIlya Dryomov 	}
362968310a5eSIlya Dryomov 
3630733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3631733f4fbbSStefan Behrens 	if (ret) {
363205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3633733f4fbbSStefan Behrens 		goto fail_block_groups;
3634733f4fbbSStefan Behrens 	}
3635733f4fbbSStefan Behrens 
36368dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
36378dabb742SStefan Behrens 	if (ret) {
363805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
36398dabb742SStefan Behrens 		goto fail_block_groups;
36408dabb742SStefan Behrens 	}
36418dabb742SStefan Behrens 
3642b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3643b70f5097SNaohiro Aota 	if (ret) {
3644b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3645b70f5097SNaohiro Aota 			  ret);
3646b70f5097SNaohiro Aota 		goto fail_block_groups;
3647b70f5097SNaohiro Aota 	}
3648b70f5097SNaohiro Aota 
3649c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3650b7c35e81SAnand Jain 	if (ret) {
365105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
365205135f59SDavid Sterba 				ret);
3653b7c35e81SAnand Jain 		goto fail_block_groups;
3654b7c35e81SAnand Jain 	}
3655b7c35e81SAnand Jain 
365696f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
36575ac1d209SJeff Mahoney 	if (ret) {
365805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3659b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
36605ac1d209SJeff Mahoney 	}
36615ac1d209SJeff Mahoney 
3662c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3663c59021f8Sliubo 	if (ret) {
366405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
36652365dd3cSAnand Jain 		goto fail_sysfs;
3666c59021f8Sliubo 	}
3667c59021f8Sliubo 
36685b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
36691b1d1f66SJosef Bacik 	if (ret) {
367005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
36712365dd3cSAnand Jain 		goto fail_sysfs;
36721b1d1f66SJosef Bacik 	}
36734330e183SQu Wenruo 
367416beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
367516beac87SNaohiro Aota 
36765c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
36775c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
367805135f59SDavid Sterba 		btrfs_warn(fs_info,
367952042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
36802365dd3cSAnand Jain 		goto fail_sysfs;
3681292fd7fcSStefan Behrens 	}
36829078a3e1SChris Mason 
368333c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3684a74a4b97SChris Mason 					       "btrfs-cleaner");
368557506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
36862365dd3cSAnand Jain 		goto fail_sysfs;
3687a74a4b97SChris Mason 
3688a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3689a74a4b97SChris Mason 						   tree_root,
3690a74a4b97SChris Mason 						   "btrfs-transaction");
369157506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
36923f157a2fSChris Mason 		goto fail_cleaner;
3693a74a4b97SChris Mason 
3694583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3695c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3696583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3697c289811cSChris Mason 	}
3698c289811cSChris Mason 
3699572d9ab7SDavid Sterba 	/*
370001327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3701572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3702572d9ab7SDavid Sterba 	 */
3703572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
37043818aea2SQu Wenruo 
370521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
37060b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
37072ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
37080b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3709cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
371021adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
371121adbd5cSStefan Behrens 		if (ret)
371205135f59SDavid Sterba 			btrfs_warn(fs_info,
371305135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
371405135f59SDavid Sterba 				ret);
371521adbd5cSStefan Behrens 	}
371621adbd5cSStefan Behrens #endif
3717bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3718bcef60f2SArne Jansen 	if (ret)
3719bcef60f2SArne Jansen 		goto fail_trans_kthread;
372021adbd5cSStefan Behrens 
3721fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3722fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3723fd708b81SJosef Bacik 
372496da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
372596da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
37260b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3727e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
372863443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
372979787eaaSJeff Mahoney 		if (ret) {
373063443bf5SEric Sandeen 			err = ret;
373128c16cbbSWang Shilong 			goto fail_qgroup;
3732e556ce2cSYan Zheng 		}
3733e02119d5SChris Mason 	}
37341a40e23bSZheng Yan 
373556e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
37363140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
37373140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3738f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3739315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3740bcef60f2SArne Jansen 		goto fail_qgroup;
37413140c9a3SDan Carpenter 	}
3742c289811cSChris Mason 
3743bc98a42cSDavid Howells 	if (sb_rdonly(sb))
37448cd29088SBoris Burkov 		goto clear_oneshot;
37452b6ba629SIlya Dryomov 
374644c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
37472b6ba629SIlya Dryomov 	if (ret) {
37486bccf3abSJeff Mahoney 		close_ctree(fs_info);
37492b6ba629SIlya Dryomov 		return ret;
3750e3acc2a6SJosef Bacik 	}
3751b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3752b382a324SJan Schmidt 
375344c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
375444c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
375544c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
375605135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
375770f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
375870f80175SStefan Behrens 		if (ret) {
375905135f59SDavid Sterba 			btrfs_warn(fs_info,
376005135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
37616bccf3abSJeff Mahoney 			close_ctree(fs_info);
376270f80175SStefan Behrens 			return ret;
376370f80175SStefan Behrens 		}
3764f7a81ea4SStefan Behrens 	}
376594846229SBoris Burkov 
3766afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
376747ab2a6cSJosef Bacik 
3768b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3769b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3770b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3771b4be6aefSJosef Bacik 
37728cd29088SBoris Burkov clear_oneshot:
37738cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3774ad2b2c80SAl Viro 	return 0;
377539279cc3SChris Mason 
3776bcef60f2SArne Jansen fail_qgroup:
3777bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
37787c2ca468SChris Mason fail_trans_kthread:
37797c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
37802ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3781faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
37823f157a2fSChris Mason fail_cleaner:
3783a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
37847c2ca468SChris Mason 
37857c2ca468SChris Mason 	/*
37867c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
37877c2ca468SChris Mason 	 * kthreads
37887c2ca468SChris Mason 	 */
37897c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
37907c2ca468SChris Mason 
37912365dd3cSAnand Jain fail_sysfs:
37926618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
37932365dd3cSAnand Jain 
3794b7c35e81SAnand Jain fail_fsdev_sysfs:
3795b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3796b7c35e81SAnand Jain 
37971b1d1f66SJosef Bacik fail_block_groups:
379854067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3799af31f5e5SChris Mason 
3800af31f5e5SChris Mason fail_tree_roots:
38019e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
38029e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
38034273eaffSAnand Jain 	free_root_pointers(fs_info, true);
38042b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3805af31f5e5SChris Mason 
380639279cc3SChris Mason fail_sb_buffer:
38077abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
38085cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
380916cdcec7SMiao Xie fail_alloc:
3810586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3811586e46e2SIlya Dryomov 
38124543df7eSChris Mason 	iput(fs_info->btree_inode);
38137e662854SQinghuang Feng fail:
3814586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3815ad2b2c80SAl Viro 	return err;
3816eb60ceacSChris Mason }
3817663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3818eb60ceacSChris Mason 
3819314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3820f2984462SChris Mason {
3821314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3822314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3823314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3824314b6dd0SJohannes Thumshirn 	struct page *page;
3825442a4f63SStefan Behrens 
3826314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3827314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3828314b6dd0SJohannes Thumshirn 
3829314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3830fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3831314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3832314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3833314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3834314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3835314b6dd0SJohannes Thumshirn 			SetPageError(page);
3836314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3837314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3838314b6dd0SJohannes Thumshirn 		} else {
3839314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3840f2984462SChris Mason 		}
3841314b6dd0SJohannes Thumshirn 
3842314b6dd0SJohannes Thumshirn 		put_page(page);
3843314b6dd0SJohannes Thumshirn 		unlock_page(page);
3844314b6dd0SJohannes Thumshirn 	}
3845314b6dd0SJohannes Thumshirn 
3846314b6dd0SJohannes Thumshirn 	bio_put(bio);
3847f2984462SChris Mason }
3848f2984462SChris Mason 
38498f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3850a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
385129c36d72SAnand Jain {
385229c36d72SAnand Jain 	struct btrfs_super_block *super;
38538f32380dSJohannes Thumshirn 	struct page *page;
385412659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
38558f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
385612659251SNaohiro Aota 	int ret;
385729c36d72SAnand Jain 
385812659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
385912659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
386012659251SNaohiro Aota 	if (ret == -ENOENT)
386112659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
386212659251SNaohiro Aota 	else if (ret)
386312659251SNaohiro Aota 		return ERR_PTR(ret);
386412659251SNaohiro Aota 
3865cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
38668f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
386729c36d72SAnand Jain 
3868a05d3c91SQu Wenruo 	if (drop_cache) {
3869a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3870a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3871a05d3c91SQu Wenruo 
3872a05d3c91SQu Wenruo 		/*
3873a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3874a05d3c91SQu Wenruo 		 * always read from the device.
3875a05d3c91SQu Wenruo 		 */
3876a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3877a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3878a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3879a05d3c91SQu Wenruo 	}
3880a05d3c91SQu Wenruo 
38818f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
38828f32380dSJohannes Thumshirn 	if (IS_ERR(page))
38838f32380dSJohannes Thumshirn 		return ERR_CAST(page);
388429c36d72SAnand Jain 
38858f32380dSJohannes Thumshirn 	super = page_address(page);
388696c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
388796c2e067SAnand Jain 		btrfs_release_disk_super(super);
388896c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
388996c2e067SAnand Jain 	}
389096c2e067SAnand Jain 
389112659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
38928f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
38938f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
389429c36d72SAnand Jain 	}
389529c36d72SAnand Jain 
38968f32380dSJohannes Thumshirn 	return super;
389729c36d72SAnand Jain }
389829c36d72SAnand Jain 
389929c36d72SAnand Jain 
39008f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3901a512bbf8SYan Zheng {
39028f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3903a512bbf8SYan Zheng 	int i;
3904a512bbf8SYan Zheng 	u64 transid = 0;
3905a512bbf8SYan Zheng 
3906a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3907a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3908a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3909a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3910a512bbf8SYan Zheng 	 */
3911a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3912a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
39138f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3914a512bbf8SYan Zheng 			continue;
3915a512bbf8SYan Zheng 
3916a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
39178f32380dSJohannes Thumshirn 			if (latest)
39188f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
39198f32380dSJohannes Thumshirn 
39208f32380dSJohannes Thumshirn 			latest = super;
3921a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3922a512bbf8SYan Zheng 		}
3923a512bbf8SYan Zheng 	}
392492fc03fbSAnand Jain 
39258f32380dSJohannes Thumshirn 	return super;
3926a512bbf8SYan Zheng }
3927a512bbf8SYan Zheng 
39284eedeb75SHisashi Hifumi /*
3929abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3930314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
39314eedeb75SHisashi Hifumi  *
3932abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3933abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3934abbb3b8eSDavid Sterba  * same for write and wait phases.
39354eedeb75SHisashi Hifumi  *
3936314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
39374eedeb75SHisashi Hifumi  */
3938a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3939abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3940a512bbf8SYan Zheng {
3941d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3942314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3943d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3944a512bbf8SYan Zheng 	int i;
3945a512bbf8SYan Zheng 	int errors = 0;
394612659251SNaohiro Aota 	int ret;
394712659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3948a512bbf8SYan Zheng 
3949a512bbf8SYan Zheng 	if (max_mirrors == 0)
3950a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3951a512bbf8SYan Zheng 
3952d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3953d5178578SJohannes Thumshirn 
3954a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3955314b6dd0SJohannes Thumshirn 		struct page *page;
3956314b6dd0SJohannes Thumshirn 		struct bio *bio;
3957314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3958314b6dd0SJohannes Thumshirn 
395912659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
396012659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
396112659251SNaohiro Aota 		if (ret == -ENOENT) {
396212659251SNaohiro Aota 			continue;
396312659251SNaohiro Aota 		} else if (ret < 0) {
396412659251SNaohiro Aota 			btrfs_err(device->fs_info,
396512659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
396612659251SNaohiro Aota 				i);
396712659251SNaohiro Aota 			errors++;
396812659251SNaohiro Aota 			continue;
396912659251SNaohiro Aota 		}
3970935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3971935e5cc9SMiao Xie 		    device->commit_total_bytes)
3972a512bbf8SYan Zheng 			break;
3973a512bbf8SYan Zheng 
397412659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3975a512bbf8SYan Zheng 
3976fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3977fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3978fd08001fSEric Biggers 				    sb->csum);
3979a512bbf8SYan Zheng 
3980314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3981314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3982314b6dd0SJohannes Thumshirn 		if (!page) {
3983fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3984314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3985f14d104dSDavid Sterba 			    bytenr);
3986634554dcSJosef Bacik 			errors++;
3987634554dcSJosef Bacik 			continue;
3988634554dcSJosef Bacik 		}
3989634554dcSJosef Bacik 
3990314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3991314b6dd0SJohannes Thumshirn 		get_page(page);
3992a512bbf8SYan Zheng 
3993314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3994314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3995a512bbf8SYan Zheng 
3996387125fcSChris Mason 		/*
3997314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3998314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3999314b6dd0SJohannes Thumshirn 		 * checking.
4000387125fcSChris Mason 		 */
400107888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
400207888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
400307888c66SChristoph Hellwig 				GFP_NOFS);
4004314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
4005314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
4006314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
4007314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
4008314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
4009314b6dd0SJohannes Thumshirn 
4010314b6dd0SJohannes Thumshirn 		/*
4011314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
4012314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
4013314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
4014314b6dd0SJohannes Thumshirn 		 */
40151b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
4016314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
4017314b6dd0SJohannes Thumshirn 
401858ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
401958ff51f1SChristoph Hellwig 		submit_bio(bio);
40208376d9e1SNaohiro Aota 
40218376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
40228376d9e1SNaohiro Aota 			errors++;
4023a512bbf8SYan Zheng 	}
4024a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
4025a512bbf8SYan Zheng }
4026a512bbf8SYan Zheng 
4027387125fcSChris Mason /*
4028abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
4029abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
4030abbb3b8eSDavid Sterba  *
4031314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
4032abbb3b8eSDavid Sterba  * date.
4033abbb3b8eSDavid Sterba  */
4034abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4035abbb3b8eSDavid Sterba {
4036abbb3b8eSDavid Sterba 	int i;
4037abbb3b8eSDavid Sterba 	int errors = 0;
4038b6a535faSHoward McLauchlan 	bool primary_failed = false;
403912659251SNaohiro Aota 	int ret;
4040abbb3b8eSDavid Sterba 	u64 bytenr;
4041abbb3b8eSDavid Sterba 
4042abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
4043abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4044abbb3b8eSDavid Sterba 
4045abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
4046314b6dd0SJohannes Thumshirn 		struct page *page;
4047314b6dd0SJohannes Thumshirn 
404812659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
404912659251SNaohiro Aota 		if (ret == -ENOENT) {
405012659251SNaohiro Aota 			break;
405112659251SNaohiro Aota 		} else if (ret < 0) {
405212659251SNaohiro Aota 			errors++;
405312659251SNaohiro Aota 			if (i == 0)
405412659251SNaohiro Aota 				primary_failed = true;
405512659251SNaohiro Aota 			continue;
405612659251SNaohiro Aota 		}
4057abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4058abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
4059abbb3b8eSDavid Sterba 			break;
4060abbb3b8eSDavid Sterba 
4061314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
4062314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
4063314b6dd0SJohannes Thumshirn 		if (!page) {
4064abbb3b8eSDavid Sterba 			errors++;
4065b6a535faSHoward McLauchlan 			if (i == 0)
4066b6a535faSHoward McLauchlan 				primary_failed = true;
4067abbb3b8eSDavid Sterba 			continue;
4068abbb3b8eSDavid Sterba 		}
4069314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4070314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4071314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4072abbb3b8eSDavid Sterba 			errors++;
4073b6a535faSHoward McLauchlan 			if (i == 0)
4074b6a535faSHoward McLauchlan 				primary_failed = true;
4075b6a535faSHoward McLauchlan 		}
4076abbb3b8eSDavid Sterba 
4077314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4078314b6dd0SJohannes Thumshirn 		put_page(page);
4079abbb3b8eSDavid Sterba 
4080314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4081314b6dd0SJohannes Thumshirn 		put_page(page);
4082abbb3b8eSDavid Sterba 	}
4083abbb3b8eSDavid Sterba 
4084b6a535faSHoward McLauchlan 	/* log error, force error return */
4085b6a535faSHoward McLauchlan 	if (primary_failed) {
4086b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4087b6a535faSHoward McLauchlan 			  device->devid);
4088b6a535faSHoward McLauchlan 		return -1;
4089b6a535faSHoward McLauchlan 	}
4090b6a535faSHoward McLauchlan 
4091abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4092abbb3b8eSDavid Sterba }
4093abbb3b8eSDavid Sterba 
4094abbb3b8eSDavid Sterba /*
4095387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4096387125fcSChris Mason  * for the barrier when it is done
4097387125fcSChris Mason  */
40984246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4099387125fcSChris Mason {
4100f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
4101387125fcSChris Mason 	complete(bio->bi_private);
4102387125fcSChris Mason }
4103387125fcSChris Mason 
4104387125fcSChris Mason /*
41054fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
41064fc6441aSAnand Jain  * done in the waiting counterpart.
4107387125fcSChris Mason  */
41084fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4109387125fcSChris Mason {
4110f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
4111387125fcSChris Mason 
4112a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4113a91cf0ffSWang Yugui 	/*
4114a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4115a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4116a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4117a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4118a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4119a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4120a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4121a91cf0ffSWang Yugui 	 * non-debug builds.
4122a91cf0ffSWang Yugui 	 */
412308e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
41244fc6441aSAnand Jain 		return;
4125a91cf0ffSWang Yugui #endif
4126387125fcSChris Mason 
4127f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
4128f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4129387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
4130387125fcSChris Mason 	init_completion(&device->flush_wait);
4131387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4132387125fcSChris Mason 
413358ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
413458ff51f1SChristoph Hellwig 	submit_bio(bio);
41351c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
41364fc6441aSAnand Jain }
4137387125fcSChris Mason 
41384fc6441aSAnand Jain /*
41394fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
41404fc6441aSAnand Jain  */
41418c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
41424fc6441aSAnand Jain {
4143f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
41444fc6441aSAnand Jain 
41451c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
414658efbc9fSOmar Sandoval 		return BLK_STS_OK;
41474fc6441aSAnand Jain 
41481c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
41492980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
41504fc6441aSAnand Jain 
41518c27cb35SLinus Torvalds 	return bio->bi_status;
4152387125fcSChris Mason }
4153387125fcSChris Mason 
4154d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4155401b41e5SAnand Jain {
41566528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4157401b41e5SAnand Jain 		return -EIO;
4158387125fcSChris Mason 	return 0;
4159387125fcSChris Mason }
4160387125fcSChris Mason 
4161387125fcSChris Mason /*
4162387125fcSChris Mason  * send an empty flush down to each device in parallel,
4163387125fcSChris Mason  * then wait for them
4164387125fcSChris Mason  */
4165387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4166387125fcSChris Mason {
4167387125fcSChris Mason 	struct list_head *head;
4168387125fcSChris Mason 	struct btrfs_device *dev;
41695af3e8ccSStefan Behrens 	int errors_wait = 0;
41704e4cbee9SChristoph Hellwig 	blk_status_t ret;
4171387125fcSChris Mason 
41721538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4173387125fcSChris Mason 	/* send down all the barriers */
4174387125fcSChris Mason 	head = &info->fs_devices->devices;
41751538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4176e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4177f88ba6a2SHidetoshi Seto 			continue;
4178cea7c8bfSAnand Jain 		if (!dev->bdev)
4179387125fcSChris Mason 			continue;
4180e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4181ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4182387125fcSChris Mason 			continue;
4183387125fcSChris Mason 
41844fc6441aSAnand Jain 		write_dev_flush(dev);
418558efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4186387125fcSChris Mason 	}
4187387125fcSChris Mason 
4188387125fcSChris Mason 	/* wait for all the barriers */
41891538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4190e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4191f88ba6a2SHidetoshi Seto 			continue;
4192387125fcSChris Mason 		if (!dev->bdev) {
41935af3e8ccSStefan Behrens 			errors_wait++;
4194387125fcSChris Mason 			continue;
4195387125fcSChris Mason 		}
4196e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4197ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4198387125fcSChris Mason 			continue;
4199387125fcSChris Mason 
42004fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4201401b41e5SAnand Jain 		if (ret) {
4202401b41e5SAnand Jain 			dev->last_flush_error = ret;
420366b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
420466b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
42055af3e8ccSStefan Behrens 			errors_wait++;
4206387125fcSChris Mason 		}
4207401b41e5SAnand Jain 	}
4208401b41e5SAnand Jain 
4209cea7c8bfSAnand Jain 	if (errors_wait) {
4210401b41e5SAnand Jain 		/*
4211401b41e5SAnand Jain 		 * At some point we need the status of all disks
4212401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4213401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4214401b41e5SAnand Jain 		 */
4215d10b82feSQu Wenruo 		return check_barrier_error(info);
4216401b41e5SAnand Jain 	}
4217387125fcSChris Mason 	return 0;
4218387125fcSChris Mason }
4219387125fcSChris Mason 
4220943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4221943c6e99SZhao Lei {
42228789f4feSZhao Lei 	int raid_type;
42238789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4224943c6e99SZhao Lei 
42258789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
42268789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
42278c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
42288789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
42298789f4feSZhao Lei 				    tolerated_failures);
4230943c6e99SZhao Lei 
42318789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
42328789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
42338789f4feSZhao Lei 			continue;
423441a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
42358789f4feSZhao Lei 			continue;
42368c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
42378789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
42388789f4feSZhao Lei 				    tolerated_failures);
42398789f4feSZhao Lei 	}
4240943c6e99SZhao Lei 
42418789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4242ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
42438789f4feSZhao Lei 		min_tolerated = 0;
42448789f4feSZhao Lei 	}
42458789f4feSZhao Lei 
42468789f4feSZhao Lei 	return min_tolerated;
4247943c6e99SZhao Lei }
4248943c6e99SZhao Lei 
4249eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4250f2984462SChris Mason {
4251e5e9a520SChris Mason 	struct list_head *head;
4252f2984462SChris Mason 	struct btrfs_device *dev;
4253a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4254f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4255f2984462SChris Mason 	int ret;
4256f2984462SChris Mason 	int do_barriers;
4257a236aed1SChris Mason 	int max_errors;
4258a236aed1SChris Mason 	int total_errors = 0;
4259a061fc8dSChris Mason 	u64 flags;
4260f2984462SChris Mason 
42610b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4262fed3b381SLiu Bo 
4263fed3b381SLiu Bo 	/*
4264fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4265fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4266fed3b381SLiu Bo 	 * been consistent on disk.
4267fed3b381SLiu Bo 	 */
4268fed3b381SLiu Bo 	if (max_mirrors == 0)
42690b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4270f2984462SChris Mason 
42710b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4272a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4273e5e9a520SChris Mason 
42740b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
42750b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
42760b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4277387125fcSChris Mason 
42785af3e8ccSStefan Behrens 	if (do_barriers) {
42790b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
42805af3e8ccSStefan Behrens 		if (ret) {
42815af3e8ccSStefan Behrens 			mutex_unlock(
42820b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
42830b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
42845af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
42855af3e8ccSStefan Behrens 			return ret;
42865af3e8ccSStefan Behrens 		}
42875af3e8ccSStefan Behrens 	}
4288387125fcSChris Mason 
42891538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4290dfe25020SChris Mason 		if (!dev->bdev) {
4291dfe25020SChris Mason 			total_errors++;
4292dfe25020SChris Mason 			continue;
4293dfe25020SChris Mason 		}
4294e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4295ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4296dfe25020SChris Mason 			continue;
4297dfe25020SChris Mason 
42982b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4299a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4300a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
43017df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4302935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4303ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4304ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4305a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4306a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4307a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4308a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
43097239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
43107239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4311a512bbf8SYan Zheng 
4312a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4313a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4314f2984462SChris Mason 
431575cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
431675cb857dSQu Wenruo 		if (ret < 0) {
431775cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
431875cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
431975cb857dSQu Wenruo 				"unexpected superblock corruption detected");
432075cb857dSQu Wenruo 			return -EUCLEAN;
432175cb857dSQu Wenruo 		}
432275cb857dSQu Wenruo 
4323abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4324a236aed1SChris Mason 		if (ret)
4325a236aed1SChris Mason 			total_errors++;
4326f2984462SChris Mason 	}
4327a236aed1SChris Mason 	if (total_errors > max_errors) {
43280b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4329d397712bSChris Mason 			  total_errors);
43300b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
433179787eaaSJeff Mahoney 
43329d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
43330b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
43340b246afaSJeff Mahoney 				      "%d errors while writing supers",
43350b246afaSJeff Mahoney 				      total_errors);
43369d565ba4SStefan Behrens 		return -EIO;
4337a236aed1SChris Mason 	}
4338f2984462SChris Mason 
4339a512bbf8SYan Zheng 	total_errors = 0;
43401538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4341dfe25020SChris Mason 		if (!dev->bdev)
4342dfe25020SChris Mason 			continue;
4343e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4344ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4345dfe25020SChris Mason 			continue;
4346dfe25020SChris Mason 
4347abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4348a512bbf8SYan Zheng 		if (ret)
43491259ab75SChris Mason 			total_errors++;
4350f2984462SChris Mason 	}
43510b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4352a236aed1SChris Mason 	if (total_errors > max_errors) {
43530b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
43540b246afaSJeff Mahoney 				      "%d errors while writing supers",
43550b246afaSJeff Mahoney 				      total_errors);
435679787eaaSJeff Mahoney 		return -EIO;
4357a236aed1SChris Mason 	}
4358f2984462SChris Mason 	return 0;
4359f2984462SChris Mason }
4360f2984462SChris Mason 
4361cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4362cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4363cb517eabSMiao Xie 				  struct btrfs_root *root)
43642619ba1fSChris Mason {
43654785e24fSJosef Bacik 	bool drop_ref = false;
43664785e24fSJosef Bacik 
4367fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4368fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4369fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4370fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
43714785e24fSJosef Bacik 		drop_ref = true;
4372fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
437376dda93cSYan, Zheng 
437484961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4375ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
43761c1ea4f7SLiu Bo 		if (root->reloc_root) {
437700246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
43781c1ea4f7SLiu Bo 			root->reloc_root = NULL;
43791c1ea4f7SLiu Bo 		}
43801c1ea4f7SLiu Bo 	}
43813321719eSLiu Bo 
43824785e24fSJosef Bacik 	if (drop_ref)
438300246528SJosef Bacik 		btrfs_put_root(root);
43842619ba1fSChris Mason }
43852619ba1fSChris Mason 
4386c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4387c146afadSYan Zheng {
4388fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4389fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4390fc7cbcd4SDavid Sterba 	int i = 0;
439165d33fd7SQu Wenruo 	int err = 0;
4392fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4393c146afadSYan Zheng 
4394c146afadSYan Zheng 	while (1) {
4395fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4396fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4397fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4398fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4399fc7cbcd4SDavid Sterba 		if (!ret) {
4400fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4401c146afadSYan Zheng 			break;
440265d33fd7SQu Wenruo 		}
4403fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
440466b4ffd1SJosef Bacik 
4405fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4406fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4407fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4408fc7cbcd4SDavid Sterba 				gang[i] = NULL;
440965d33fd7SQu Wenruo 				continue;
4410c146afadSYan Zheng 			}
4411fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4412fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4413fc7cbcd4SDavid Sterba 		}
4414fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4415fc7cbcd4SDavid Sterba 
4416fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4417fc7cbcd4SDavid Sterba 			if (!gang[i])
4418fc7cbcd4SDavid Sterba 				continue;
4419fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4420fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4421fc7cbcd4SDavid Sterba 			if (err)
4422fc7cbcd4SDavid Sterba 				break;
4423fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4424fc7cbcd4SDavid Sterba 		}
4425fc7cbcd4SDavid Sterba 		root_objectid++;
4426c146afadSYan Zheng 	}
442765d33fd7SQu Wenruo 
4428fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4429fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4430fc7cbcd4SDavid Sterba 		if (gang[i])
4431fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
443265d33fd7SQu Wenruo 	}
443365d33fd7SQu Wenruo 	return err;
4434c146afadSYan Zheng }
4435c146afadSYan Zheng 
44366bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4437c146afadSYan Zheng {
44386bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4439c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4440c146afadSYan Zheng 
44410b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
44422ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
44430b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
44440b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4445c71bf099SYan, Zheng 
4446c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
44470b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
44480b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4449c71bf099SYan, Zheng 
44507a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
44513612b495STsutomu Itoh 	if (IS_ERR(trans))
44523612b495STsutomu Itoh 		return PTR_ERR(trans);
44533a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4454c146afadSYan Zheng }
4455c146afadSYan Zheng 
445636c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
445736c86a9eSQu Wenruo {
445836c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
445936c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
446036c86a9eSQu Wenruo 	bool found = false;
446136c86a9eSQu Wenruo 
446236c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
446336c86a9eSQu Wenruo 		return;
446436c86a9eSQu Wenruo 
446536c86a9eSQu Wenruo 	/*
446636c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
446736c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
446836c86a9eSQu Wenruo 	 */
446936c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
447036c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
447136c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
447236c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
447336c86a9eSQu Wenruo 		u64 cur = 0;
447436c86a9eSQu Wenruo 		u64 found_start;
447536c86a9eSQu Wenruo 		u64 found_end;
447636c86a9eSQu Wenruo 
447736c86a9eSQu Wenruo 		found = true;
447836c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
447936c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
448036c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
448136c86a9eSQu Wenruo 			cur = found_end + 1;
448236c86a9eSQu Wenruo 		}
448336c86a9eSQu Wenruo 		btrfs_warn(fs_info,
448436c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
448536c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
448636c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
448736c86a9eSQu Wenruo 
448836c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
448936c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
449036c86a9eSQu Wenruo 		list_del_init(&trans->list);
449136c86a9eSQu Wenruo 
449236c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
449336c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
449436c86a9eSQu Wenruo 	}
449536c86a9eSQu Wenruo 	ASSERT(!found);
449636c86a9eSQu Wenruo }
449736c86a9eSQu Wenruo 
4498b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4499eb60ceacSChris Mason {
4500c146afadSYan Zheng 	int ret;
4501e089f05cSChris Mason 
4502afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
450331e70e52SFilipe Manana 
450431e70e52SFilipe Manana 	/*
45058a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
45068a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
45078a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
45088a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
45098a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
45108a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
45118a1f1e3dSFilipe Manana 	 * return 1.
45128a1f1e3dSFilipe Manana 	 */
45138a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
45148a1f1e3dSFilipe Manana 
45158a1f1e3dSFilipe Manana 	/*
451631e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
451731e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
451831e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
451931e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
452031e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
452131e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
452231e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
452331e70e52SFilipe Manana 	 */
452431e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4525d6fd0ae2SOmar Sandoval 	/*
4526d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4527d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4528d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4529d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4530d6fd0ae2SOmar Sandoval 	 */
4531d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4532a2135011SChris Mason 
45337343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4534d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
45357343dd61SJustin Maggard 
4536803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4537803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4538803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4539803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4540803b2f54SStefan Behrens 
4541837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4542aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4543837d5b6eSIlya Dryomov 
45448dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
45458dabb742SStefan Behrens 
4546aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
45474cb5300bSChris Mason 
45484cb5300bSChris Mason 	/* wait for any defraggers to finish */
45494cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
45504cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
45514cb5300bSChris Mason 
45524cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
455326176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
45544cb5300bSChris Mason 
4555a362bb86SFilipe Manana 	/*
4556a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4557a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4558a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4559a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4560a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4561a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4562a362bb86SFilipe Manana 	 * no one else to run iputs.
4563a362bb86SFilipe Manana 	 *
4564a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4565a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4566a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4567a362bb86SFilipe Manana 	 * through some other means.
4568a362bb86SFilipe Manana 	 *
4569a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4570a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4571a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4572a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4573a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4574a362bb86SFilipe Manana 	 */
4575a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4576a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4577a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4578a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4579a362bb86SFilipe Manana 
458021c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
458157056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4582576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
458321c7e756SMiao Xie 
4584b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4585b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4586b0643e59SDennis Zhou 
4587bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4588e44163e1SJeff Mahoney 		/*
4589d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4590d6fd0ae2SOmar Sandoval 		 * unused block groups.
4591e44163e1SJeff Mahoney 		 */
45920b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4593e44163e1SJeff Mahoney 
4594f0cc2cd7SFilipe Manana 		/*
4595f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4596f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4597f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4598f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4599f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4600f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4601f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4602f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4603f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4604f0cc2cd7SFilipe Manana 		 */
4605f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4606f0cc2cd7SFilipe Manana 
46076bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4608d397712bSChris Mason 		if (ret)
460904892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4610c146afadSYan Zheng 	}
4611ed2ff2cbSChris Mason 
461284961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
46132ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4614acce952bSliubo 
4615e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4616e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
46178929ecfaSYan, Zheng 
4618e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4619afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4620f25784b3SYan Zheng 
46215958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
46225958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
46235958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
46245958253cSQu Wenruo 	}
46255958253cSQu Wenruo 
462604892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4627fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4628bcef60f2SArne Jansen 
4629963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
463004892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4631963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4632b0c68f8bSChris Mason 	}
463331153d81SYan Zheng 
46345deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
46354297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
46365deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
46374297ff84SJosef Bacik 
46386618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4639b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
46405ac1d209SJeff Mahoney 
46411a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
46421a4319ccSLiu Bo 
4643de348ee0SWang Shilong 	/*
4644de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4645de348ee0SWang Shilong 	 * submit after we stopping all workers.
4646de348ee0SWang Shilong 	 */
4647de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
464896192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
464996192499SJosef Bacik 
46500a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
465136c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
46520a31daa4SFilipe Manana 
4653afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
46544273eaffSAnand Jain 	free_root_pointers(fs_info, true);
46558c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
46569ad6b7bcSChris Mason 
46574e19443dSJosef Bacik 	/*
46584e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
46594e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
46604e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
46614e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
46624e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
46634e19443dSJosef Bacik 	 */
46644e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
46654e19443dSJosef Bacik 
466613e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4667d6bfde87SChris Mason 
466821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
46690b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
46702ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
467121adbd5cSStefan Behrens #endif
467221adbd5cSStefan Behrens 
46730b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
467468c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4675eb60ceacSChris Mason }
4676eb60ceacSChris Mason 
4677b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4678b9fab919SChris Mason 			  int atomic)
4679ccd467d6SChris Mason {
46801259ab75SChris Mason 	int ret;
4681727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
46821259ab75SChris Mason 
46830b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
46841259ab75SChris Mason 	if (!ret)
46851259ab75SChris Mason 		return ret;
46861259ab75SChris Mason 
46871259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4688b9fab919SChris Mason 				    parent_transid, atomic);
4689b9fab919SChris Mason 	if (ret == -EAGAIN)
4690b9fab919SChris Mason 		return ret;
46911259ab75SChris Mason 	return !ret;
46925f39d397SChris Mason }
46936702ed49SChris Mason 
46945f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
46955f39d397SChris Mason {
46962f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
46975f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4698b9473439SChris Mason 	int was_dirty;
4699b4ce94deSChris Mason 
470006ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
470106ea65a3SJosef Bacik 	/*
470206ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
470352042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
470406ea65a3SJosef Bacik 	 * outside of the sanity tests.
470506ea65a3SJosef Bacik 	 */
4706b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
470706ea65a3SJosef Bacik 		return;
470806ea65a3SJosef Bacik #endif
470949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
47100b246afaSJeff Mahoney 	if (transid != fs_info->generation)
47115d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
47120b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
47130b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4714e2d84521SMiao Xie 	if (!was_dirty)
4715104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4716e2d84521SMiao Xie 					 buf->len,
47170b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
47181f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
471969fc6cbbSQu Wenruo 	/*
472069fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
472169fc6cbbSQu Wenruo 	 * but item data not updated.
472269fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
472369fc6cbbSQu Wenruo 	 */
472469fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4725cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4726a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
47271f21ef0aSFilipe Manana 		ASSERT(0);
47281f21ef0aSFilipe Manana 	}
47291f21ef0aSFilipe Manana #endif
4730eb60ceacSChris Mason }
4731eb60ceacSChris Mason 
47322ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4733b53d3f5dSLiu Bo 					int flush_delayed)
473435b7e476SChris Mason {
4735188de649SChris Mason 	/*
4736188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4737188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4738188de649SChris Mason 	 */
4739e2d84521SMiao Xie 	int ret;
4740d6bfde87SChris Mason 
47416933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4742d6bfde87SChris Mason 		return;
4743d6bfde87SChris Mason 
4744b53d3f5dSLiu Bo 	if (flush_delayed)
47452ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
474616cdcec7SMiao Xie 
4747d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4748d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4749d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4750e2d84521SMiao Xie 	if (ret > 0) {
47510b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
475216cdcec7SMiao Xie 	}
475316cdcec7SMiao Xie }
475416cdcec7SMiao Xie 
47552ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
475616cdcec7SMiao Xie {
47572ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
475835b7e476SChris Mason }
4759b53d3f5dSLiu Bo 
47602ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4761b53d3f5dSLiu Bo {
47622ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4763d6bfde87SChris Mason }
47646b80053dSChris Mason 
47652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4766acce952bSliubo {
4767fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4768fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4769fe816d0fSNikolay Borisov 
47700b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
47712ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
47720b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4773acce952bSliubo 
47740b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
47750b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4776acce952bSliubo }
4777acce952bSliubo 
4778ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4779ef67963dSJosef Bacik {
4780fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4781fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4782fc7cbcd4SDavid Sterba 	int ret;
4783ef67963dSJosef Bacik 
4784fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4785fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4786fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4787fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4788fc7cbcd4SDavid Sterba 		int i;
4789ef67963dSJosef Bacik 
4790fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4791fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4792fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4793fc7cbcd4SDavid Sterba 
4794fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4795fc7cbcd4SDavid Sterba 			if (!gang[i])
4796ef67963dSJosef Bacik 				continue;
4797fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4798fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4799fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4800ef67963dSJosef Bacik 		}
4801fc7cbcd4SDavid Sterba 		root_objectid++;
4802fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4803ef67963dSJosef Bacik 	}
4804fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4805ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4806ef67963dSJosef Bacik }
4807ef67963dSJosef Bacik 
4808143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4809acce952bSliubo {
4810acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4811acce952bSliubo 
4812199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4813779880efSJosef Bacik 	/*
4814779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4815779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4816779880efSJosef Bacik 	 */
4817199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4818779880efSJosef Bacik 			    root_extent_list)
4819779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4820199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4821199c2a9cSMiao Xie }
4822199c2a9cSMiao Xie 
4823199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4824199c2a9cSMiao Xie {
4825199c2a9cSMiao Xie 	struct btrfs_root *root;
4826199c2a9cSMiao Xie 	struct list_head splice;
4827199c2a9cSMiao Xie 
4828199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4829199c2a9cSMiao Xie 
4830199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4831199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4832199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4833199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4834199c2a9cSMiao Xie 					ordered_root);
48351de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
48361de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4837199c2a9cSMiao Xie 
48382a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4839199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4840199c2a9cSMiao Xie 
48412a85d9caSLiu Bo 		cond_resched();
48422a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4843199c2a9cSMiao Xie 	}
4844199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
484574d5d229SJosef Bacik 
484674d5d229SJosef Bacik 	/*
484774d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
484874d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
484974d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
485074d5d229SJosef Bacik 	 * actually get run and error out properly.
485174d5d229SJosef Bacik 	 */
485274d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4853acce952bSliubo }
4854acce952bSliubo 
485535a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
48562ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4857acce952bSliubo {
4858acce952bSliubo 	struct rb_node *node;
4859acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4860acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4861acce952bSliubo 	int ret = 0;
4862acce952bSliubo 
4863acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4864acce952bSliubo 
4865acce952bSliubo 	spin_lock(&delayed_refs->lock);
4866d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4867cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4868b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4869acce952bSliubo 		return ret;
4870acce952bSliubo 	}
4871acce952bSliubo 
48725c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4873d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
48740e0adbcfSJosef Bacik 		struct rb_node *n;
4875e78417d1SJosef Bacik 		bool pin_bytes = false;
4876acce952bSliubo 
4877d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4878d7df2c79SJosef Bacik 				href_node);
48793069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4880b939d1abSJosef Bacik 			continue;
48813069bd26SJosef Bacik 
4882d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4883e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
48840e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
48850e0adbcfSJosef Bacik 				       ref_node);
4886d7df2c79SJosef Bacik 			ref->in_tree = 0;
4887e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
48880e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
48891d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
48901d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4891d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4892d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4893d7df2c79SJosef Bacik 		}
489454067ae9SJosef Bacik 		if (head->must_insert_reserved)
4895e78417d1SJosef Bacik 			pin_bytes = true;
489678a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4897fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4898d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4899acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4900e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4901acce952bSliubo 
4902f603bb94SNikolay Borisov 		if (pin_bytes) {
4903f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4904f603bb94SNikolay Borisov 
4905f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4906f603bb94SNikolay Borisov 			BUG_ON(!cache);
4907f603bb94SNikolay Borisov 
4908f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4909f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4910f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4911f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4912f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4913f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4914f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4915f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4916f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4917f603bb94SNikolay Borisov 
4918f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4919f603bb94SNikolay Borisov 
4920f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4921f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4922f603bb94SNikolay Borisov 		}
492331890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4924d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4925acce952bSliubo 		cond_resched();
4926acce952bSliubo 		spin_lock(&delayed_refs->lock);
4927acce952bSliubo 	}
492881f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4929acce952bSliubo 
4930acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4931acce952bSliubo 
4932acce952bSliubo 	return ret;
4933acce952bSliubo }
4934acce952bSliubo 
4935143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4936acce952bSliubo {
4937acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4938acce952bSliubo 	struct list_head splice;
4939acce952bSliubo 
4940acce952bSliubo 	INIT_LIST_HEAD(&splice);
4941acce952bSliubo 
4942eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4943eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4944acce952bSliubo 
4945acce952bSliubo 	while (!list_empty(&splice)) {
4946fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4947eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4948acce952bSliubo 					       delalloc_inodes);
4949fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4950eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4951acce952bSliubo 
4952fe816d0fSNikolay Borisov 		/*
4953fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4954fe816d0fSNikolay Borisov 		 * meanwhile.
4955fe816d0fSNikolay Borisov 		 */
4956fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4957fe816d0fSNikolay Borisov 		if (inode) {
4958fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4959fe816d0fSNikolay Borisov 			iput(inode);
4960fe816d0fSNikolay Borisov 		}
4961eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4962acce952bSliubo 	}
4963eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4964eb73c1b7SMiao Xie }
4965eb73c1b7SMiao Xie 
4966eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4967eb73c1b7SMiao Xie {
4968eb73c1b7SMiao Xie 	struct btrfs_root *root;
4969eb73c1b7SMiao Xie 	struct list_head splice;
4970eb73c1b7SMiao Xie 
4971eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4972eb73c1b7SMiao Xie 
4973eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4974eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4975eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4976eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4977eb73c1b7SMiao Xie 					 delalloc_root);
497800246528SJosef Bacik 		root = btrfs_grab_root(root);
4979eb73c1b7SMiao Xie 		BUG_ON(!root);
4980eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4981eb73c1b7SMiao Xie 
4982eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
498300246528SJosef Bacik 		btrfs_put_root(root);
4984eb73c1b7SMiao Xie 
4985eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4986eb73c1b7SMiao Xie 	}
4987eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4988acce952bSliubo }
4989acce952bSliubo 
49902ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4991acce952bSliubo 					struct extent_io_tree *dirty_pages,
4992acce952bSliubo 					int mark)
4993acce952bSliubo {
4994acce952bSliubo 	int ret;
4995acce952bSliubo 	struct extent_buffer *eb;
4996acce952bSliubo 	u64 start = 0;
4997acce952bSliubo 	u64 end;
4998acce952bSliubo 
4999acce952bSliubo 	while (1) {
5000acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
5001e6138876SJosef Bacik 					    mark, NULL);
5002acce952bSliubo 		if (ret)
5003acce952bSliubo 			break;
5004acce952bSliubo 
500591166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
5006acce952bSliubo 		while (start <= end) {
50070b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
50080b246afaSJeff Mahoney 			start += fs_info->nodesize;
5009fd8b2b61SJosef Bacik 			if (!eb)
5010acce952bSliubo 				continue;
5011fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
5012acce952bSliubo 
5013fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
5014fd8b2b61SJosef Bacik 					       &eb->bflags))
5015fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
5016fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
5017acce952bSliubo 		}
5018acce952bSliubo 	}
5019acce952bSliubo 
5020acce952bSliubo 	return ret;
5021acce952bSliubo }
5022acce952bSliubo 
50232ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
5024fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
5025acce952bSliubo {
5026acce952bSliubo 	u64 start;
5027acce952bSliubo 	u64 end;
5028acce952bSliubo 	int ret;
5029acce952bSliubo 
5030acce952bSliubo 	while (1) {
50310e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
50320e6ec385SFilipe Manana 
5033fcd5e742SLu Fengqi 		/*
5034fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
5035fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
5036fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5037fcd5e742SLu Fengqi 		 * the same extent range.
5038fcd5e742SLu Fengqi 		 */
5039fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
5040acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
50410e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
5042fcd5e742SLu Fengqi 		if (ret) {
5043fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5044acce952bSliubo 			break;
5045fcd5e742SLu Fengqi 		}
5046acce952bSliubo 
50470e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
50480e6ec385SFilipe Manana 		free_extent_state(cached_state);
50492ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
5050fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5051acce952bSliubo 		cond_resched();
5052acce952bSliubo 	}
5053acce952bSliubo 
5054acce952bSliubo 	return 0;
5055acce952bSliubo }
5056acce952bSliubo 
505732da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
5058c79a1751SLiu Bo {
5059c79a1751SLiu Bo 	struct inode *inode;
5060c79a1751SLiu Bo 
5061c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
5062c79a1751SLiu Bo 	if (inode) {
5063c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
5064c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
5065c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
5066c79a1751SLiu Bo 		iput(inode);
5067c79a1751SLiu Bo 	}
5068bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
5069c79a1751SLiu Bo 	btrfs_put_block_group(cache);
5070c79a1751SLiu Bo }
5071c79a1751SLiu Bo 
5072c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
50732ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5074c79a1751SLiu Bo {
507532da5386SDavid Sterba 	struct btrfs_block_group *cache;
5076c79a1751SLiu Bo 
5077c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5078c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5079c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
508032da5386SDavid Sterba 					 struct btrfs_block_group,
5081c79a1751SLiu Bo 					 dirty_list);
5082c79a1751SLiu Bo 
5083c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5084c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5085c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5086c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5087c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5088c79a1751SLiu Bo 		}
5089c79a1751SLiu Bo 
5090c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5091c79a1751SLiu Bo 		spin_lock(&cache->lock);
5092c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5093c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5094c79a1751SLiu Bo 
5095c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5096c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5097ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5098c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5099c79a1751SLiu Bo 	}
5100c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5101c79a1751SLiu Bo 
510245ae2c18SNikolay Borisov 	/*
510345ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
510445ae2c18SNikolay Borisov 	 * to use it without any locking
510545ae2c18SNikolay Borisov 	 */
5106c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5107c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
510832da5386SDavid Sterba 					 struct btrfs_block_group,
5109c79a1751SLiu Bo 					 io_list);
5110c79a1751SLiu Bo 
5111c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5112c79a1751SLiu Bo 		spin_lock(&cache->lock);
5113c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5114c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5115c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5116c79a1751SLiu Bo 	}
5117c79a1751SLiu Bo }
5118c79a1751SLiu Bo 
511949b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
51202ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
512149b25e05SJeff Mahoney {
5122bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5123bbbf7243SNikolay Borisov 
51242ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5125c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5126c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5127c79a1751SLiu Bo 
5128bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5129bbbf7243SNikolay Borisov 				 post_commit_list) {
5130bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5131bbbf7243SNikolay Borisov 	}
5132bbbf7243SNikolay Borisov 
51332ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
513449b25e05SJeff Mahoney 
51354a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
51360b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
513749b25e05SJeff Mahoney 
51384a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
51390b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
514049b25e05SJeff Mahoney 
5141ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
514267cde344SMiao Xie 
51432ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
514449b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5145fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
514649b25e05SJeff Mahoney 
5147d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
5148d3575156SNaohiro Aota 
51494a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
51504a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
515149b25e05SJeff Mahoney }
515249b25e05SJeff Mahoney 
51532ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5154acce952bSliubo {
5155acce952bSliubo 	struct btrfs_transaction *t;
5156acce952bSliubo 
51570b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5158acce952bSliubo 
51590b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
51600b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
51610b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5162724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5163724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
51649b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
51650b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
51662ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5167724e2315SJosef Bacik 			btrfs_put_transaction(t);
51680b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5169724e2315SJosef Bacik 			continue;
5170724e2315SJosef Bacik 		}
51710b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5172724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
51730b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5174724e2315SJosef Bacik 			/*
5175724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5176724e2315SJosef Bacik 			 * handle open currently for this transaction.
5177724e2315SJosef Bacik 			 */
5178724e2315SJosef Bacik 			wait_event(t->writer_wait,
5179724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5180724e2315SJosef Bacik 		} else {
51810b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5182724e2315SJosef Bacik 		}
51832ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5184724e2315SJosef Bacik 
51850b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
51860b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
51870b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5188724e2315SJosef Bacik 		list_del_init(&t->list);
51890b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5190a4abeea4SJosef Bacik 
5191724e2315SJosef Bacik 		btrfs_put_transaction(t);
51922e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
51930b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5194724e2315SJosef Bacik 	}
51950b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
51960b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5197ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5198ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
51990b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5200ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
52010b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5202acce952bSliubo 
5203acce952bSliubo 	return 0;
5204acce952bSliubo }
5205ec7d6dfdSNikolay Borisov 
5206453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5207ec7d6dfdSNikolay Borisov {
5208ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5209ec7d6dfdSNikolay Borisov 	int ret;
5210ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5211ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5212ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5213ec7d6dfdSNikolay Borisov 	int slot;
5214ec7d6dfdSNikolay Borisov 
5215ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5216ec7d6dfdSNikolay Borisov 	if (!path)
5217ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5218ec7d6dfdSNikolay Borisov 
5219ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5220ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5221ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5222ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5223ec7d6dfdSNikolay Borisov 	if (ret < 0)
5224ec7d6dfdSNikolay Borisov 		goto error;
5225ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5226ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5227ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5228ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5229ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
523023125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
523123125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5232ec7d6dfdSNikolay Borisov 	} else {
523323125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5234ec7d6dfdSNikolay Borisov 	}
5235ec7d6dfdSNikolay Borisov 	ret = 0;
5236ec7d6dfdSNikolay Borisov error:
5237ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5238ec7d6dfdSNikolay Borisov 	return ret;
5239ec7d6dfdSNikolay Borisov }
5240ec7d6dfdSNikolay Borisov 
5241543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5242ec7d6dfdSNikolay Borisov {
5243ec7d6dfdSNikolay Borisov 	int ret;
5244ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5245ec7d6dfdSNikolay Borisov 
52466b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5247ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5248ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5249ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5250ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5251ec7d6dfdSNikolay Borisov 		goto out;
5252ec7d6dfdSNikolay Borisov 	}
5253ec7d6dfdSNikolay Borisov 
525423125104SNikolay Borisov 	*objectid = root->free_objectid++;
5255ec7d6dfdSNikolay Borisov 	ret = 0;
5256ec7d6dfdSNikolay Borisov out:
5257ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5258ec7d6dfdSNikolay Borisov 	return ret;
5259ec7d6dfdSNikolay Borisov }
5260