xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 1a1a2851)
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"
46c7f13d42SJosef Bacik #include "fs.h"
4707e81dc9SJosef Bacik #include "accessors.h"
48a0231804SJosef Bacik #include "extent-tree.h"
4945c40c8fSJosef Bacik #include "root-tree.h"
5059b818e0SJosef Bacik #include "defrag.h"
51c7a03b52SJosef Bacik #include "uuid-tree.h"
5267707479SJosef Bacik #include "relocation.h"
532fc6822cSJosef Bacik #include "scrub.h"
54c03b2207SJosef Bacik #include "super.h"
55eb60ceacSChris Mason 
56319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
57319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
58319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
59319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
60e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
61e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
62319e4d06SQu Wenruo 
63143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
64acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
652ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
66143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
672ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
68acce952bSliubo 					struct extent_io_tree *dirty_pages,
69acce952bSliubo 					int mark);
702ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
71acce952bSliubo 				       struct extent_io_tree *pinned_extents);
722ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
732ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
74ce9adaa5SChris Mason 
75141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
76141386e1SJosef Bacik {
77141386e1SJosef Bacik 	if (fs_info->csum_shash)
78141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
79141386e1SJosef Bacik }
80141386e1SJosef Bacik 
81d352ac68SChris Mason /*
82d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
83d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
84d352ac68SChris Mason  * just before they are sent down the IO stack.
85d352ac68SChris Mason  */
8644b8bd7eSChris Mason struct async_submit_bio {
878896a08dSQu Wenruo 	struct inode *inode;
8844b8bd7eSChris Mason 	struct bio *bio;
89a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
9044b8bd7eSChris Mason 	int mirror_num;
911941b64bSQu Wenruo 
921941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
931941b64bSQu Wenruo 	u64 dio_file_offset;
948b712842SChris Mason 	struct btrfs_work work;
954e4cbee9SChristoph Hellwig 	blk_status_t status;
9644b8bd7eSChris Mason };
9744b8bd7eSChris Mason 
9885d4e461SChris Mason /*
992996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
100d352ac68SChris Mason  */
101c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
10219c00ddcSChris Mason {
103d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
1047280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
105a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
106d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
10719c00ddcSChris Mason 	char *kaddr;
108e9be5a30SDavid Sterba 	int i;
109d5178578SJohannes Thumshirn 
110d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
111d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
112a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
113e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
114a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
11519c00ddcSChris Mason 
116e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
117e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
118e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
11919c00ddcSChris Mason 	}
12071a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
121d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
12219c00ddcSChris Mason }
12319c00ddcSChris Mason 
124d352ac68SChris Mason /*
125d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
126d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
127d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
128d352ac68SChris Mason  * in the wrong place.
129d352ac68SChris Mason  */
1301259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
131b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
132b9fab919SChris Mason 				 int atomic)
1331259ab75SChris Mason {
1342ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
1351259ab75SChris Mason 	int ret;
1361259ab75SChris Mason 
1371259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
1381259ab75SChris Mason 		return 0;
1391259ab75SChris Mason 
140b9fab919SChris Mason 	if (atomic)
141b9fab919SChris Mason 		return -EAGAIN;
142b9fab919SChris Mason 
143570eb97bSJosef Bacik 	lock_extent(io_tree, eb->start, eb->start + eb->len - 1, &cached_state);
1440b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
1451259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
1461259ab75SChris Mason 		ret = 0;
1471259ab75SChris Mason 		goto out;
1481259ab75SChris Mason 	}
14994647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
1508f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1518f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
15229549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1531259ab75SChris Mason 	ret = 1;
1540b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
15533958dc6SChris Mason out:
156570eb97bSJosef Bacik 	unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
157e43bbe5eSDavid Sterba 		      &cached_state);
1581259ab75SChris Mason 	return ret;
1591259ab75SChris Mason }
1601259ab75SChris Mason 
161e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
162e7e16f48SJohannes Thumshirn {
163e7e16f48SJohannes Thumshirn 	switch (csum_type) {
164e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1653951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1663831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
167352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
168e7e16f48SJohannes Thumshirn 		return true;
169e7e16f48SJohannes Thumshirn 	default:
170e7e16f48SJohannes Thumshirn 		return false;
171e7e16f48SJohannes Thumshirn 	}
172e7e16f48SJohannes Thumshirn }
173e7e16f48SJohannes Thumshirn 
174d352ac68SChris Mason /*
1751104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1761104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1771104a885SDavid Sterba  */
1783d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1793d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1801104a885SDavid Sterba {
18151bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
182d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
183d5178578SJohannes Thumshirn 
184d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1851104a885SDavid Sterba 
1861104a885SDavid Sterba 	/*
1871104a885SDavid Sterba 	 * The super_block structure does not span the whole
18851bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
18951bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1901104a885SDavid Sterba 	 */
1913d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
192fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1931104a885SDavid Sterba 
19455fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
195e7e16f48SJohannes Thumshirn 		return 1;
1961104a885SDavid Sterba 
197e7e16f48SJohannes Thumshirn 	return 0;
1981104a885SDavid Sterba }
1991104a885SDavid Sterba 
200e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
201ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
202581c1760SQu Wenruo {
203e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
204581c1760SQu Wenruo 	int found_level;
205581c1760SQu Wenruo 	struct btrfs_key found_key;
206581c1760SQu Wenruo 	int ret;
207581c1760SQu Wenruo 
208581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
209581c1760SQu Wenruo 	if (found_level != level) {
21063489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
21163489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
212581c1760SQu Wenruo 		btrfs_err(fs_info,
213581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
214581c1760SQu Wenruo 			  eb->start, level, found_level);
215581c1760SQu Wenruo 		return -EIO;
216581c1760SQu Wenruo 	}
217581c1760SQu Wenruo 
218581c1760SQu Wenruo 	if (!first_key)
219581c1760SQu Wenruo 		return 0;
220581c1760SQu Wenruo 
2215d41be6fSQu Wenruo 	/*
2225d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
2235d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
2245d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
2255d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
2265d41be6fSQu Wenruo 	 */
2275d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
2285d41be6fSQu Wenruo 		return 0;
22962fdaa52SQu Wenruo 
23062fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
23162fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
23262fdaa52SQu Wenruo 		btrfs_err(fs_info,
23362fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
23462fdaa52SQu Wenruo 			  eb->start);
23562fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
23662fdaa52SQu Wenruo 		return -EUCLEAN;
23762fdaa52SQu Wenruo 	}
23862fdaa52SQu Wenruo 
239581c1760SQu Wenruo 	if (found_level)
240581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
241581c1760SQu Wenruo 	else
242581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
243581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
244581c1760SQu Wenruo 
245581c1760SQu Wenruo 	if (ret) {
24663489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
24763489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
248581c1760SQu Wenruo 		btrfs_err(fs_info,
249ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
250ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
251ff76a864SLiu Bo 			  first_key->type, first_key->offset,
252ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
253ff76a864SLiu Bo 			  found_key.offset);
254581c1760SQu Wenruo 	}
255581c1760SQu Wenruo 	return ret;
256581c1760SQu Wenruo }
257581c1760SQu Wenruo 
2581104a885SDavid Sterba /*
259d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
260d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
261581c1760SQu Wenruo  *
262581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
263581c1760SQu Wenruo  * @level:		expected level, mandatory check
264581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
265d352ac68SChris Mason  */
2666a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
267581c1760SQu Wenruo 			     u64 parent_transid, int level,
268581c1760SQu Wenruo 			     struct btrfs_key *first_key)
269f188591eSChris Mason {
2705ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
271f188591eSChris Mason 	struct extent_io_tree *io_tree;
272ea466794SJosef Bacik 	int failed = 0;
273f188591eSChris Mason 	int ret;
274f188591eSChris Mason 	int num_copies = 0;
275f188591eSChris Mason 	int mirror_num = 0;
276ea466794SJosef Bacik 	int failed_mirror = 0;
277f188591eSChris Mason 
2780b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
279f188591eSChris Mason 	while (1) {
280f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
281c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
282256dd1bbSStefan Behrens 		if (!ret) {
283581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
284b9fab919SChris Mason 						   parent_transid, 0))
285256dd1bbSStefan Behrens 				ret = -EIO;
286e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
287ff76a864SLiu Bo 						first_key, parent_transid))
288581c1760SQu Wenruo 				ret = -EUCLEAN;
289581c1760SQu Wenruo 			else
290581c1760SQu Wenruo 				break;
291256dd1bbSStefan Behrens 		}
292d397712bSChris Mason 
2930b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
294f188591eSChris Mason 					      eb->start, eb->len);
2954235298eSChris Mason 		if (num_copies == 1)
296ea466794SJosef Bacik 			break;
2974235298eSChris Mason 
2985cf1ab56SJosef Bacik 		if (!failed_mirror) {
2995cf1ab56SJosef Bacik 			failed = 1;
3005cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
3015cf1ab56SJosef Bacik 		}
3025cf1ab56SJosef Bacik 
303f188591eSChris Mason 		mirror_num++;
304ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
305ea466794SJosef Bacik 			mirror_num++;
306ea466794SJosef Bacik 
3074235298eSChris Mason 		if (mirror_num > num_copies)
308ea466794SJosef Bacik 			break;
309f188591eSChris Mason 	}
310ea466794SJosef Bacik 
311c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
31220a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
313ea466794SJosef Bacik 
314ea466794SJosef Bacik 	return ret;
315f188591eSChris Mason }
31619c00ddcSChris Mason 
317eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
318eca0f6f6SQu Wenruo {
319eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
320eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
321eca0f6f6SQu Wenruo 	int ret;
322eca0f6f6SQu Wenruo 
323eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
324eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
325eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
326eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
327eca0f6f6SQu Wenruo 
328eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
329eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
330eca0f6f6SQu Wenruo 	else
331eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
332eca0f6f6SQu Wenruo 
3333777369fSQu Wenruo 	if (ret < 0)
3343777369fSQu Wenruo 		goto error;
3353777369fSQu Wenruo 
3363777369fSQu Wenruo 	/*
3373777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
3383777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
3393777369fSQu Wenruo 	 */
3403777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
3413777369fSQu Wenruo 		ret = -EUCLEAN;
342eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
3433777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
3443777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
3453777369fSQu Wenruo 			  fs_info->last_trans_committed);
3463777369fSQu Wenruo 		goto error;
347eca0f6f6SQu Wenruo 	}
348eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
349eca0f6f6SQu Wenruo 
350eca0f6f6SQu Wenruo 	return 0;
3513777369fSQu Wenruo 
3523777369fSQu Wenruo error:
3533777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
3543777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
3553777369fSQu Wenruo 		  eb->start);
3563777369fSQu Wenruo 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
3573777369fSQu Wenruo 	return ret;
358eca0f6f6SQu Wenruo }
359eca0f6f6SQu Wenruo 
360eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
361eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
362eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
363eca0f6f6SQu Wenruo {
364eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
365eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
366eca0f6f6SQu Wenruo 	u64 cur;
367eca0f6f6SQu Wenruo 	int ret = 0;
368eca0f6f6SQu Wenruo 
369eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
370eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
371eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
372eca0f6f6SQu Wenruo 		bool uptodate;
373eca0f6f6SQu Wenruo 
374eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
375eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
376eca0f6f6SQu Wenruo 						       fs_info->nodesize);
377eca0f6f6SQu Wenruo 
37801cd3909SDavid Sterba 		/* A dirty eb shouldn't disappear from buffer_radix */
379eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
380eca0f6f6SQu Wenruo 			return -EUCLEAN;
381eca0f6f6SQu Wenruo 
382eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
383eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
384eca0f6f6SQu Wenruo 			return -EUCLEAN;
385eca0f6f6SQu Wenruo 		}
386eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
387eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
388eca0f6f6SQu Wenruo 			return -EUCLEAN;
389eca0f6f6SQu Wenruo 		}
390eca0f6f6SQu Wenruo 
391eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
392eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
393eca0f6f6SQu Wenruo 		if (ret < 0)
394eca0f6f6SQu Wenruo 			return ret;
395eca0f6f6SQu Wenruo 	}
396eca0f6f6SQu Wenruo 	return ret;
397eca0f6f6SQu Wenruo }
398eca0f6f6SQu Wenruo 
399d352ac68SChris Mason /*
400ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
401ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
402ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
403d352ac68SChris Mason  */
404ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
40519c00ddcSChris Mason {
406ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
4074eee4fa4SMiao Xie 	u64 start = page_offset(page);
40819c00ddcSChris Mason 	u64 found_start;
40919c00ddcSChris Mason 	struct extent_buffer *eb;
410eca0f6f6SQu Wenruo 
411fbca46ebSQu Wenruo 	if (fs_info->nodesize < PAGE_SIZE)
412eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
413f188591eSChris Mason 
4144f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4154f2de97aSJosef Bacik 	if (page != eb->pages[0])
4164f2de97aSJosef Bacik 		return 0;
4170f805531SAlex Lyakas 
41819c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
419d3575156SNaohiro Aota 
420d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
421d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
422d3575156SNaohiro Aota 		return 0;
423d3575156SNaohiro Aota 	}
424d3575156SNaohiro Aota 
4250f805531SAlex Lyakas 	/*
4260f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4270f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4280f805531SAlex Lyakas 	 */
4290f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4300f805531SAlex Lyakas 		return -EUCLEAN;
4310f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4320f805531SAlex Lyakas 		return -EUCLEAN;
4330f805531SAlex Lyakas 
434eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
43519c00ddcSChris Mason }
43619c00ddcSChris Mason 
437b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4382b82032cSYan Zheng {
439b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
440944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
44144880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
442944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
4432b82032cSYan Zheng 
4449a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
4459a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
4467239ff4bSNikolay Borisov 	/*
447944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
448944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
449944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
4507239ff4bSNikolay Borisov 	 */
451944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
4527239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
4537239ff4bSNikolay Borisov 	else
4547239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
4557239ff4bSNikolay Borisov 
456944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
457944d3f9fSNikolay Borisov 		return 0;
458944d3f9fSNikolay Borisov 
459944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
460944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
461944d3f9fSNikolay Borisov 			return 0;
462944d3f9fSNikolay Borisov 
463944d3f9fSNikolay Borisov 	return 1;
4642b82032cSYan Zheng }
4652b82032cSYan Zheng 
46677bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
46777bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
468ce9adaa5SChris Mason {
46977bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
470ce9adaa5SChris Mason 	u64 found_start;
47177bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
47277bf40a2SQu Wenruo 	u8 found_level;
4732996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
474dfd29eedSDavid Sterba 	const u8 *header_csum;
47577bf40a2SQu Wenruo 	int ret = 0;
476ea466794SJosef Bacik 
477ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
478727011e0SChris Mason 	if (found_start != eb->start) {
4798f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
4808f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
4818f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
482f188591eSChris Mason 		ret = -EIO;
48377bf40a2SQu Wenruo 		goto out;
484ce9adaa5SChris Mason 	}
485b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
4868f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
4878f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
4881259ab75SChris Mason 		ret = -EIO;
48977bf40a2SQu Wenruo 		goto out;
4901259ab75SChris Mason 	}
491ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
4921c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
4938f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
4948f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
4958f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
4961c24c3ceSJosef Bacik 		ret = -EIO;
49777bf40a2SQu Wenruo 		goto out;
4981c24c3ceSJosef Bacik 	}
499ce9adaa5SChris Mason 
500c67b3892SDavid Sterba 	csum_tree_block(eb, result);
501dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
502dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
503a826d6dcSJosef Bacik 
504dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
5052996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
5068f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5078f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
508dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
50935be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
51035be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5112996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
51277bf40a2SQu Wenruo 		goto out;
5132996e1f8SJohannes Thumshirn 	}
5142996e1f8SJohannes Thumshirn 
515a826d6dcSJosef Bacik 	/*
516a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
517a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
518a826d6dcSJosef Bacik 	 * return -EIO.
519a826d6dcSJosef Bacik 	 */
5201c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
521a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
522a826d6dcSJosef Bacik 		ret = -EIO;
523a826d6dcSJosef Bacik 	}
524ce9adaa5SChris Mason 
525813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
526053ab70fSLiu Bo 		ret = -EIO;
527053ab70fSLiu Bo 
5280b32f4bbSJosef Bacik 	if (!ret)
5290b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
53075391f0dSQu Wenruo 	else
53175391f0dSQu Wenruo 		btrfs_err(fs_info,
5328f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
5338f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
53477bf40a2SQu Wenruo out:
53577bf40a2SQu Wenruo 	return ret;
53677bf40a2SQu Wenruo }
53777bf40a2SQu Wenruo 
538371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
539371cdc07SQu Wenruo 				   int mirror)
540371cdc07SQu Wenruo {
541371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
542371cdc07SQu Wenruo 	struct extent_buffer *eb;
543371cdc07SQu Wenruo 	bool reads_done;
544371cdc07SQu Wenruo 	int ret = 0;
545371cdc07SQu Wenruo 
546371cdc07SQu Wenruo 	/*
547371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
548371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
549371cdc07SQu Wenruo 	 */
550371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
551371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
552371cdc07SQu Wenruo 
553371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
554371cdc07SQu Wenruo 	/*
555371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
556371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
557371cdc07SQu Wenruo 	 */
558371cdc07SQu Wenruo 	ASSERT(eb);
559371cdc07SQu Wenruo 
560371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
561371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
562371cdc07SQu Wenruo 	ASSERT(reads_done);
563371cdc07SQu Wenruo 
564371cdc07SQu Wenruo 	eb->read_mirror = mirror;
565371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
566371cdc07SQu Wenruo 		ret = -EIO;
567371cdc07SQu Wenruo 		goto err;
568371cdc07SQu Wenruo 	}
569371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
570371cdc07SQu Wenruo 	if (ret < 0)
571371cdc07SQu Wenruo 		goto err;
572371cdc07SQu Wenruo 
573371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
574371cdc07SQu Wenruo 
575371cdc07SQu Wenruo 	free_extent_buffer(eb);
576371cdc07SQu Wenruo 	return ret;
577371cdc07SQu Wenruo err:
578371cdc07SQu Wenruo 	/*
579371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
580371cdc07SQu Wenruo 	 * make sure it has something to decrement.
581371cdc07SQu Wenruo 	 */
582371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
583371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
584371cdc07SQu Wenruo 	free_extent_buffer(eb);
585371cdc07SQu Wenruo 	return ret;
586371cdc07SQu Wenruo }
587371cdc07SQu Wenruo 
588c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
58977bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
59077bf40a2SQu Wenruo 				   int mirror)
59177bf40a2SQu Wenruo {
59277bf40a2SQu Wenruo 	struct extent_buffer *eb;
59377bf40a2SQu Wenruo 	int ret = 0;
59477bf40a2SQu Wenruo 	int reads_done;
59577bf40a2SQu Wenruo 
59677bf40a2SQu Wenruo 	ASSERT(page->private);
597371cdc07SQu Wenruo 
598fbca46ebSQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
599371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
600371cdc07SQu Wenruo 
60177bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
60277bf40a2SQu Wenruo 
60377bf40a2SQu Wenruo 	/*
60477bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
60577bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
60677bf40a2SQu Wenruo 	 */
60777bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
60877bf40a2SQu Wenruo 
60977bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
61077bf40a2SQu Wenruo 	if (!reads_done)
61177bf40a2SQu Wenruo 		goto err;
61277bf40a2SQu Wenruo 
61377bf40a2SQu Wenruo 	eb->read_mirror = mirror;
61477bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
61577bf40a2SQu Wenruo 		ret = -EIO;
61677bf40a2SQu Wenruo 		goto err;
61777bf40a2SQu Wenruo 	}
61877bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
619ce9adaa5SChris Mason err:
62053b381b3SDavid Woodhouse 	if (ret) {
62153b381b3SDavid Woodhouse 		/*
62253b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
62353b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
62453b381b3SDavid Woodhouse 		 * to decrement
62553b381b3SDavid Woodhouse 		 */
62653b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6270b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
62853b381b3SDavid Woodhouse 	}
6290b32f4bbSJosef Bacik 	free_extent_buffer(eb);
63077bf40a2SQu Wenruo 
631f188591eSChris Mason 	return ret;
632ce9adaa5SChris Mason }
633ce9adaa5SChris Mason 
6344a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
6354a69a410SChris Mason {
6364a69a410SChris Mason 	struct async_submit_bio *async;
6374e4cbee9SChristoph Hellwig 	blk_status_t ret;
6384a69a410SChris Mason 
6394a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
6401941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
6411941b64bSQu Wenruo 				      async->dio_file_offset);
64279787eaaSJeff Mahoney 	if (ret)
6434e4cbee9SChristoph Hellwig 		async->status = ret;
6444a69a410SChris Mason }
6454a69a410SChris Mason 
64606ea01b1SDavid Sterba /*
64706ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
64806ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
64906ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
65006ea01b1SDavid Sterba  *
65106ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
65206ea01b1SDavid Sterba  * inserted into the tree.
65306ea01b1SDavid Sterba  */
6544a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
6558b712842SChris Mason {
656917f32a2SChristoph Hellwig 	struct async_submit_bio *async =
657917f32a2SChristoph Hellwig 		container_of(work, struct  async_submit_bio, work);
658917f32a2SChristoph Hellwig 	struct inode *inode = async->inode;
659917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(async->bio);
6604854ddd0SChris Mason 
661bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
6624e4cbee9SChristoph Hellwig 	if (async->status) {
663917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, async->status);
66479787eaaSJeff Mahoney 		return;
66579787eaaSJeff Mahoney 	}
66679787eaaSJeff Mahoney 
667ec39f769SChris Mason 	/*
668ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
669ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
670ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
671ec39f769SChris Mason 	 */
672ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
6731a722d8fSChristoph Hellwig 	btrfs_submit_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
6744a69a410SChris Mason }
6754a69a410SChris Mason 
6764a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
6774a69a410SChris Mason {
6784a69a410SChris Mason 	struct async_submit_bio *async;
6794a69a410SChris Mason 
6804a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
6818b712842SChris Mason 	kfree(async);
6828b712842SChris Mason }
6838b712842SChris Mason 
684ea1f0cedSChristoph Hellwig /*
685ea1f0cedSChristoph Hellwig  * Submit bio to an async queue.
686ea1f0cedSChristoph Hellwig  *
687ea1f0cedSChristoph Hellwig  * Retrun:
688ea1f0cedSChristoph Hellwig  * - true if the work has been succesfuly submitted
689ea1f0cedSChristoph Hellwig  * - false in case of error
690ea1f0cedSChristoph Hellwig  */
691ea1f0cedSChristoph Hellwig bool btrfs_wq_submit_bio(struct inode *inode, struct bio *bio, int mirror_num,
692ea1f0cedSChristoph Hellwig 			 u64 dio_file_offset,
693e288c080SDavid Sterba 			 extent_submit_bio_start_t *submit_bio_start)
69444b8bd7eSChris Mason {
6958896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
69644b8bd7eSChris Mason 	struct async_submit_bio *async;
69744b8bd7eSChris Mason 
69844b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
69944b8bd7eSChris Mason 	if (!async)
700ea1f0cedSChristoph Hellwig 		return false;
70144b8bd7eSChris Mason 
7028896a08dSQu Wenruo 	async->inode = inode;
70344b8bd7eSChris Mason 	async->bio = bio;
70444b8bd7eSChris Mason 	async->mirror_num = mirror_num;
7054a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
7064a69a410SChris Mason 
707a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
708a0cac0ecSOmar Sandoval 			run_one_async_free);
7094a69a410SChris Mason 
7101941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
7118c8bee1dSChris Mason 
7124e4cbee9SChristoph Hellwig 	async->status = 0;
71379787eaaSJeff Mahoney 
71467f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
715a31b4a43SChristoph Hellwig 		btrfs_queue_work(fs_info->hipri_workers, &async->work);
716a31b4a43SChristoph Hellwig 	else
7175cdc7ad3SQu Wenruo 		btrfs_queue_work(fs_info->workers, &async->work);
718ea1f0cedSChristoph Hellwig 	return true;
71944b8bd7eSChris Mason }
72044b8bd7eSChris Mason 
7214e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
722ce3ed71aSChris Mason {
7232c30c71bSKent Overstreet 	struct bio_vec *bvec;
724ce3ed71aSChris Mason 	struct btrfs_root *root;
7252b070cfeSChristoph Hellwig 	int ret = 0;
7266dc4f100SMing Lei 	struct bvec_iter_all iter_all;
727ce3ed71aSChris Mason 
728c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
7292b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
730ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
731ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
73279787eaaSJeff Mahoney 		if (ret)
73379787eaaSJeff Mahoney 			break;
734ce3ed71aSChris Mason 	}
7352c30c71bSKent Overstreet 
7364e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
737ce3ed71aSChris Mason }
738ce3ed71aSChris Mason 
7398896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
7401941b64bSQu Wenruo 					   u64 dio_file_offset)
74122c59948SChris Mason {
7428b712842SChris Mason 	/*
7438b712842SChris Mason 	 * when we're called for a write, we're already in the async
7441a722d8fSChristoph Hellwig 	 * submission context.  Just jump into btrfs_submit_bio.
7458b712842SChris Mason 	 */
74679787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
74722c59948SChris Mason }
74822c59948SChris Mason 
749f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
7509b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
751de0022b9SJosef Bacik {
7524eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
753f4dcfb30SJohannes Thumshirn 		return false;
7546300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
755f4dcfb30SJohannes Thumshirn 		return false;
7569b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
757f4dcfb30SJohannes Thumshirn 		return false;
758f4dcfb30SJohannes Thumshirn 	return true;
759de0022b9SJosef Bacik }
760de0022b9SJosef Bacik 
76194d9e11bSChristoph Hellwig void btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio, int mirror_num)
76244b8bd7eSChris Mason {
7630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
764917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(bio);
7654e4cbee9SChristoph Hellwig 	blk_status_t ret;
766cad321adSChris Mason 
76708a6f464SChristoph Hellwig 	bio->bi_opf |= REQ_META;
76808a6f464SChristoph Hellwig 
769cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
7701a722d8fSChristoph Hellwig 		btrfs_submit_bio(fs_info, bio, mirror_num);
7711a722d8fSChristoph Hellwig 		return;
77244b8bd7eSChris Mason 	}
77344b8bd7eSChris Mason 
774ea1f0cedSChristoph Hellwig 	/*
775ea1f0cedSChristoph Hellwig 	 * Kthread helpers are used to submit writes so that checksumming can
776ea1f0cedSChristoph Hellwig 	 * happen in parallel across all CPUs.
777ea1f0cedSChristoph Hellwig 	 */
778ea1f0cedSChristoph Hellwig 	if (should_async_write(fs_info, BTRFS_I(inode)) &&
779ea1f0cedSChristoph Hellwig 	    btrfs_wq_submit_bio(inode, bio, mirror_num, 0, btree_submit_bio_start))
780ea1f0cedSChristoph Hellwig 		return;
781ea1f0cedSChristoph Hellwig 
782ea1f0cedSChristoph Hellwig 	ret = btree_csum_one_bio(bio);
78394d9e11bSChristoph Hellwig 	if (ret) {
784917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, ret);
785ea1f0cedSChristoph Hellwig 		return;
78694d9e11bSChristoph Hellwig 	}
787ea1f0cedSChristoph Hellwig 
788ea1f0cedSChristoph Hellwig 	btrfs_submit_bio(fs_info, bio, mirror_num);
78961891923SStefan Behrens }
79061891923SStefan Behrens 
7913dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
7928958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
7938958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
794784b4e29SChris Mason {
795784b4e29SChris Mason 	/*
796784b4e29SChris Mason 	 * we can't safely write a btree page from here,
797784b4e29SChris Mason 	 * we haven't done the locking hook
798784b4e29SChris Mason 	 */
7998958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
800784b4e29SChris Mason 		return -EAGAIN;
801784b4e29SChris Mason 	/*
802784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
803784b4e29SChris Mason 	 * We must have no buffers or drop them.
804784b4e29SChris Mason 	 */
8058958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
8068958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
807784b4e29SChris Mason 		return -EAGAIN;
80854184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
809784b4e29SChris Mason }
8108958b551SMatthew Wilcox (Oracle) #else
8118958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
8123dd1462eSJan Beulich #endif
813784b4e29SChris Mason 
8140da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
8150da5468fSChris Mason 			    struct writeback_control *wbc)
8160da5468fSChris Mason {
817e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
818e2d84521SMiao Xie 	int ret;
819e2d84521SMiao Xie 
820d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
821448d640bSChris Mason 
822448d640bSChris Mason 		if (wbc->for_kupdate)
823448d640bSChris Mason 			return 0;
824448d640bSChris Mason 
825e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
826b9473439SChris Mason 		/* this is a bit racy, but that's ok */
827d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
828d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
829d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
830e2d84521SMiao Xie 		if (ret < 0)
831793955bcSChris Mason 			return 0;
832793955bcSChris Mason 	}
8330b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
8340da5468fSChris Mason }
8350da5468fSChris Mason 
836f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
8375f39d397SChris Mason {
838f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
839f913cff3SMatthew Wilcox (Oracle) 		return false;
8400c4e538bSDavid Sterba 
841f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
842d98237b3SChris Mason }
843d98237b3SChris Mason 
844895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
845895586ebSMatthew Wilcox (Oracle) 				 size_t length)
846d98237b3SChris Mason {
847d1310b2eSChris Mason 	struct extent_io_tree *tree;
848895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
849895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
850f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
851895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
852895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
853895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
854895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
855895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
8569ad6b7bcSChris Mason 	}
857d98237b3SChris Mason }
858d98237b3SChris Mason 
859bb146eb2SJosef Bacik #ifdef DEBUG
8600079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
8610079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
8620079c3b1SMatthew Wilcox (Oracle) {
8630079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
864139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
8650b32f4bbSJosef Bacik 	struct extent_buffer *eb;
866139e8cd3SQu Wenruo 	int cur_bit = 0;
8670079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
8680b32f4bbSJosef Bacik 
869139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
8700079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
8710b32f4bbSJosef Bacik 		BUG_ON(!eb);
8720b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
8730b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
87449d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
8750079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
876139e8cd3SQu Wenruo 	}
8770079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
878139e8cd3SQu Wenruo 
879139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
880139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
881139e8cd3SQu Wenruo 		unsigned long flags;
882139e8cd3SQu Wenruo 		u64 cur;
883139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
884139e8cd3SQu Wenruo 
885139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
886139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
887139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
888139e8cd3SQu Wenruo 			cur_bit++;
889139e8cd3SQu Wenruo 			continue;
890139e8cd3SQu Wenruo 		}
891139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
892139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
893139e8cd3SQu Wenruo 
894139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
895139e8cd3SQu Wenruo 		ASSERT(eb);
896139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
897139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
89849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
899139e8cd3SQu Wenruo 		free_extent_buffer(eb);
900139e8cd3SQu Wenruo 
901139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
902139e8cd3SQu Wenruo 	}
9030079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
9040b32f4bbSJosef Bacik }
9050079c3b1SMatthew Wilcox (Oracle) #else
9060079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
9070079c3b1SMatthew Wilcox (Oracle) #endif
9080b32f4bbSJosef Bacik 
9097f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
9100da5468fSChris Mason 	.writepages	= btree_writepages,
911f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
912895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
9138958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
9140079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
915d98237b3SChris Mason };
916123abc88SChris Mason 
9172ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
9182ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
9193fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
9203fbaf258SJosef Bacik 						int level)
9210999df54SChris Mason {
9220b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
9230b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
9243fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
9250999df54SChris Mason }
9260999df54SChris Mason 
927581c1760SQu Wenruo /*
928581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
929581c1760SQu Wenruo  * verification.
930581c1760SQu Wenruo  *
9311b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
932581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
933581c1760SQu Wenruo  * @level:		expected level, mandatory check
934581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
935581c1760SQu Wenruo  */
9362ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
9371b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
9381b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
939e20d96d6SChris Mason {
9405f39d397SChris Mason 	struct extent_buffer *buf = NULL;
94119c00ddcSChris Mason 	int ret;
94219c00ddcSChris Mason 
9433fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
944c871b0f2SLiu Bo 	if (IS_ERR(buf))
945c871b0f2SLiu Bo 		return buf;
946e4204dedSChris Mason 
9476a2e9dc4SFilipe Manana 	ret = btrfs_read_extent_buffer(buf, parent_transid, level, first_key);
9480f0fe8f7SFilipe David Borba Manana 	if (ret) {
949537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
95064c043deSLiu Bo 		return ERR_PTR(ret);
9510f0fe8f7SFilipe David Borba Manana 	}
95288c602abSQu Wenruo 	if (btrfs_check_eb_owner(buf, owner_root)) {
95388c602abSQu Wenruo 		free_extent_buffer_stale(buf);
95488c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
95588c602abSQu Wenruo 	}
9565f39d397SChris Mason 	return buf;
957ce9adaa5SChris Mason 
958eb60ceacSChris Mason }
959eb60ceacSChris Mason 
9606a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
961ed2ff2cbSChris Mason {
9626a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
96355c69072SChris Mason 	if (btrfs_header_generation(buf) ==
964e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
96549d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
966b4ce94deSChris Mason 
967b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
968104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
969e2d84521SMiao Xie 						 -buf->len,
970e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
9710b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
972925baeddSChris Mason 		}
9735f39d397SChris Mason 	}
974ed7b63ebSJosef Bacik }
9755f39d397SChris Mason 
976da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
977e20d96d6SChris Mason 			 u64 objectid)
978d97e63b6SChris Mason {
9797c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
9802e608bd1SJosef Bacik 
9812e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
9822e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
9832e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
98496dfcb46SJosef Bacik 	root->fs_info = fs_info;
9852e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
986cfaa7295SChris Mason 	root->node = NULL;
987a28ec197SChris Mason 	root->commit_root = NULL;
98827cdeb70SMiao Xie 	root->state = 0;
989abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
9900b86a832SChris Mason 
9910f7d52f4SChris Mason 	root->last_trans = 0;
9926b8fad57SNikolay Borisov 	root->free_objectid = 0;
993eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
994199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
9956bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
996088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
9972e608bd1SJosef Bacik 
9982e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
9990b86a832SChris Mason 
10000b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
10015d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1002eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1003eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1004199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1005199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1006d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
10072ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
10082ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
10095d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1010eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1011199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1012f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
10132ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
10142ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
10158287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1016a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1017e02119d5SChris Mason 	mutex_init(&root->log_mutex);
101831f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1019573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1020c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
10217237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
10227237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
10237237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
10248b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
10258b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
10267237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
10277237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
10287237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
10292ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
10300700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
10318ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1032eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
10337237f183SYan Zheng 	root->log_transid = 0;
1034d1433debSMiao Xie 	root->log_transid_committed = -1;
1035257c62e1SChris Mason 	root->last_log_commit = 0;
10362e608bd1SJosef Bacik 	root->anon_dev = 0;
1037e289f03eSFilipe Manana 	if (!dummy) {
103843eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
103943eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1040e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1041e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1042e289f03eSFilipe Manana 	}
1043017e5369SChris Mason 
10445f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1045370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1046bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1047bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1048fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1049bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1050fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1051bd647ce3SJosef Bacik #endif
10523768f368SChris Mason }
10533768f368SChris Mason 
105474e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
105596dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
10566f07e42eSAl Viro {
105774e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
10586f07e42eSAl Viro 	if (root)
105996dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
10606f07e42eSAl Viro 	return root;
10616f07e42eSAl Viro }
10626f07e42eSAl Viro 
106306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
106406ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1065da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
106606ea65a3SJosef Bacik {
106706ea65a3SJosef Bacik 	struct btrfs_root *root;
106806ea65a3SJosef Bacik 
10697c0260eeSJeff Mahoney 	if (!fs_info)
10707c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
10717c0260eeSJeff Mahoney 
107296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
107306ea65a3SJosef Bacik 	if (!root)
107406ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1075da17066cSJeff Mahoney 
1076b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1077faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
107806ea65a3SJosef Bacik 
107906ea65a3SJosef Bacik 	return root;
108006ea65a3SJosef Bacik }
108106ea65a3SJosef Bacik #endif
108206ea65a3SJosef Bacik 
1083abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
1084abed4aaaSJosef Bacik {
1085abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
1086abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
1087abed4aaaSJosef Bacik 
1088abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
1089abed4aaaSJosef Bacik }
1090abed4aaaSJosef Bacik 
1091abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
1092abed4aaaSJosef Bacik {
1093abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
1094abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
1095abed4aaaSJosef Bacik 
1096abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
1097abed4aaaSJosef Bacik }
1098abed4aaaSJosef Bacik 
1099abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
1100abed4aaaSJosef Bacik {
1101abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1102abed4aaaSJosef Bacik 	struct rb_node *tmp;
1103abed4aaaSJosef Bacik 
1104abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1105abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1106abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1107abed4aaaSJosef Bacik 	ASSERT(!tmp);
1108abed4aaaSJosef Bacik 
1109abed4aaaSJosef Bacik 	return tmp ? -EEXIST : 0;
1110abed4aaaSJosef Bacik }
1111abed4aaaSJosef Bacik 
1112abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
1113abed4aaaSJosef Bacik {
1114abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1115abed4aaaSJosef Bacik 
1116abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1117abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
1118abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1119abed4aaaSJosef Bacik }
1120abed4aaaSJosef Bacik 
1121abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1122abed4aaaSJosef Bacik 				     struct btrfs_key *key)
1123abed4aaaSJosef Bacik {
1124abed4aaaSJosef Bacik 	struct rb_node *node;
1125abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
1126abed4aaaSJosef Bacik 
1127abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
1128abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1129abed4aaaSJosef Bacik 	if (node)
1130abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
1131abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
1132abed4aaaSJosef Bacik 
1133abed4aaaSJosef Bacik 	return root;
1134abed4aaaSJosef Bacik }
1135abed4aaaSJosef Bacik 
1136f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1137f7238e50SJosef Bacik {
1138f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
1139f7238e50SJosef Bacik 	u64 ret;
1140f7238e50SJosef Bacik 
1141f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1142f7238e50SJosef Bacik 		return 0;
1143f7238e50SJosef Bacik 
1144f7238e50SJosef Bacik 	if (bytenr)
1145f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
1146f7238e50SJosef Bacik 	else
1147f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1148f7238e50SJosef Bacik 	ASSERT(block_group);
1149f7238e50SJosef Bacik 	if (!block_group)
1150f7238e50SJosef Bacik 		return 0;
1151f7238e50SJosef Bacik 	ret = block_group->global_root_id;
1152f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
1153f7238e50SJosef Bacik 
1154f7238e50SJosef Bacik 	return ret;
1155f7238e50SJosef Bacik }
1156f7238e50SJosef Bacik 
1157abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1158abed4aaaSJosef Bacik {
1159abed4aaaSJosef Bacik 	struct btrfs_key key = {
1160abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1161abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1162f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1163abed4aaaSJosef Bacik 	};
1164abed4aaaSJosef Bacik 
1165abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1166abed4aaaSJosef Bacik }
1167abed4aaaSJosef Bacik 
1168abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1169abed4aaaSJosef Bacik {
1170abed4aaaSJosef Bacik 	struct btrfs_key key = {
1171abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1172abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1173f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1174abed4aaaSJosef Bacik 	};
1175abed4aaaSJosef Bacik 
1176abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1177abed4aaaSJosef Bacik }
1178abed4aaaSJosef Bacik 
117951129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
118051129b33SJosef Bacik {
118151129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
118251129b33SJosef Bacik 		return fs_info->block_group_root;
118351129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
118451129b33SJosef Bacik }
118551129b33SJosef Bacik 
118620897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
118720897f5cSArne Jansen 				     u64 objectid)
118820897f5cSArne Jansen {
11899b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
119020897f5cSArne Jansen 	struct extent_buffer *leaf;
119120897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
119220897f5cSArne Jansen 	struct btrfs_root *root;
119320897f5cSArne Jansen 	struct btrfs_key key;
1194b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
119520897f5cSArne Jansen 	int ret = 0;
119620897f5cSArne Jansen 
1197b89f6d1fSFilipe Manana 	/*
1198b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1199b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1200b89f6d1fSFilipe Manana 	 */
1201b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
120296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1203b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
120420897f5cSArne Jansen 	if (!root)
120520897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
120620897f5cSArne Jansen 
120720897f5cSArne Jansen 	root->root_key.objectid = objectid;
120820897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
120920897f5cSArne Jansen 	root->root_key.offset = 0;
121020897f5cSArne Jansen 
12119631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12129631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
121320897f5cSArne Jansen 	if (IS_ERR(leaf)) {
121420897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12151dd05682STsutomu Itoh 		leaf = NULL;
1216c1b07854SPeng Hao 		goto fail;
121720897f5cSArne Jansen 	}
121820897f5cSArne Jansen 
121920897f5cSArne Jansen 	root->node = leaf;
122020897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
122120897f5cSArne Jansen 
122220897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
122327cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
122420897f5cSArne Jansen 
1225f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1226f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
122720897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
122820897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
122920897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
123020897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
123120897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
123220897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
123320897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
123433d85fdaSQu Wenruo 	if (is_fstree(objectid))
1235807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1236807fc790SAndy Shevchenko 	else
1237807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1238c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
123920897f5cSArne Jansen 
12408a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
12418a6a87cdSBoris Burkov 
124220897f5cSArne Jansen 	key.objectid = objectid;
124320897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
124420897f5cSArne Jansen 	key.offset = 0;
124520897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
124620897f5cSArne Jansen 	if (ret)
124720897f5cSArne Jansen 		goto fail;
124820897f5cSArne Jansen 
124920897f5cSArne Jansen 	return root;
12501dd05682STsutomu Itoh 
12518a6a87cdSBoris Burkov fail:
125200246528SJosef Bacik 	btrfs_put_root(root);
12531dd05682STsutomu Itoh 
12541dd05682STsutomu Itoh 	return ERR_PTR(ret);
125520897f5cSArne Jansen }
125620897f5cSArne Jansen 
12577237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1258e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
12590f7d52f4SChris Mason {
12600f7d52f4SChris Mason 	struct btrfs_root *root;
1261e02119d5SChris Mason 
126296dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1263e02119d5SChris Mason 	if (!root)
12647237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1265e02119d5SChris Mason 
1266e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1267e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1268e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
126927cdeb70SMiao Xie 
12706ab6ebb7SNaohiro Aota 	return root;
12716ab6ebb7SNaohiro Aota }
12726ab6ebb7SNaohiro Aota 
12736ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
12746ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
12756ab6ebb7SNaohiro Aota {
12766ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
12776ab6ebb7SNaohiro Aota 
12787237f183SYan Zheng 	/*
127992a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
128027cdeb70SMiao Xie 	 *
128192a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
128292a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
128392a7cc42SQu Wenruo 	 *
128492a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
128592a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
12867237f183SYan Zheng 	 */
1287e02119d5SChris Mason 
12884d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12899631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
12906ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
12916ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1292e02119d5SChris Mason 
12937237f183SYan Zheng 	root->node = leaf;
1294e02119d5SChris Mason 
1295e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1296e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12976ab6ebb7SNaohiro Aota 
12986ab6ebb7SNaohiro Aota 	return 0;
12997237f183SYan Zheng }
13007237f183SYan Zheng 
13017237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13027237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13037237f183SYan Zheng {
13047237f183SYan Zheng 	struct btrfs_root *log_root;
13057237f183SYan Zheng 
13067237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13077237f183SYan Zheng 	if (IS_ERR(log_root))
13087237f183SYan Zheng 		return PTR_ERR(log_root);
13096ab6ebb7SNaohiro Aota 
13103ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13113ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13123ddebf27SNaohiro Aota 
13136ab6ebb7SNaohiro Aota 		if (ret) {
13146ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13156ab6ebb7SNaohiro Aota 			return ret;
13166ab6ebb7SNaohiro Aota 		}
13173ddebf27SNaohiro Aota 	}
13186ab6ebb7SNaohiro Aota 
13197237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13207237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13217237f183SYan Zheng 	return 0;
13227237f183SYan Zheng }
13237237f183SYan Zheng 
13247237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13257237f183SYan Zheng 		       struct btrfs_root *root)
13267237f183SYan Zheng {
13270b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13287237f183SYan Zheng 	struct btrfs_root *log_root;
13297237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13306ab6ebb7SNaohiro Aota 	int ret;
13317237f183SYan Zheng 
13320b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13337237f183SYan Zheng 	if (IS_ERR(log_root))
13347237f183SYan Zheng 		return PTR_ERR(log_root);
13357237f183SYan Zheng 
13366ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13376ab6ebb7SNaohiro Aota 	if (ret) {
13386ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
13396ab6ebb7SNaohiro Aota 		return ret;
13406ab6ebb7SNaohiro Aota 	}
13416ab6ebb7SNaohiro Aota 
13427237f183SYan Zheng 	log_root->last_trans = trans->transid;
13437237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13447237f183SYan Zheng 
13457237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13463cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13473cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13483cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1349da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13500b246afaSJeff Mahoney 				     fs_info->nodesize);
13513cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13527237f183SYan Zheng 
13535d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13547237f183SYan Zheng 
13557237f183SYan Zheng 	WARN_ON(root->log_root);
13567237f183SYan Zheng 	root->log_root = log_root;
13577237f183SYan Zheng 	root->log_transid = 0;
1358d1433debSMiao Xie 	root->log_transid_committed = -1;
1359257c62e1SChris Mason 	root->last_log_commit = 0;
1360e02119d5SChris Mason 	return 0;
1361e02119d5SChris Mason }
1362e02119d5SChris Mason 
136349d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
136449d11beaSJosef Bacik 					      struct btrfs_path *path,
1365cb517eabSMiao Xie 					      struct btrfs_key *key)
1366e02119d5SChris Mason {
1367e02119d5SChris Mason 	struct btrfs_root *root;
1368e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
136984234f3aSYan Zheng 	u64 generation;
1370cb517eabSMiao Xie 	int ret;
1371581c1760SQu Wenruo 	int level;
1372cb517eabSMiao Xie 
137396dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
137449d11beaSJosef Bacik 	if (!root)
137549d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
13760f7d52f4SChris Mason 
1377cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1378cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
13790f7d52f4SChris Mason 	if (ret) {
138013a8a7c8SYan, Zheng 		if (ret > 0)
138113a8a7c8SYan, Zheng 			ret = -ENOENT;
138249d11beaSJosef Bacik 		goto fail;
13830f7d52f4SChris Mason 	}
138413a8a7c8SYan, Zheng 
138584234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1386581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
13872ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
13882ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
13891b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
139064c043deSLiu Bo 	if (IS_ERR(root->node)) {
139164c043deSLiu Bo 		ret = PTR_ERR(root->node);
13928c38938cSJosef Bacik 		root->node = NULL;
139349d11beaSJosef Bacik 		goto fail;
13944eb150d6SQu Wenruo 	}
13954eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1396cb517eabSMiao Xie 		ret = -EIO;
139749d11beaSJosef Bacik 		goto fail;
1398416bc658SJosef Bacik 	}
139988c602abSQu Wenruo 
140088c602abSQu Wenruo 	/*
140188c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
140288c602abSQu Wenruo 	 * match its root node owner
140388c602abSQu Wenruo 	 */
140488c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
140588c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
140688c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
140788c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
140888c602abSQu Wenruo 		btrfs_crit(fs_info,
140988c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
141088c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
141188c602abSQu Wenruo 			   btrfs_header_owner(root->node),
141288c602abSQu Wenruo 			   root->root_key.objectid);
141388c602abSQu Wenruo 		ret = -EUCLEAN;
141488c602abSQu Wenruo 		goto fail;
141588c602abSQu Wenruo 	}
14165d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1417cb517eabSMiao Xie 	return root;
141849d11beaSJosef Bacik fail:
141900246528SJosef Bacik 	btrfs_put_root(root);
142049d11beaSJosef Bacik 	return ERR_PTR(ret);
142149d11beaSJosef Bacik }
142249d11beaSJosef Bacik 
142349d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
142449d11beaSJosef Bacik 					struct btrfs_key *key)
142549d11beaSJosef Bacik {
142649d11beaSJosef Bacik 	struct btrfs_root *root;
142749d11beaSJosef Bacik 	struct btrfs_path *path;
142849d11beaSJosef Bacik 
142949d11beaSJosef Bacik 	path = btrfs_alloc_path();
143049d11beaSJosef Bacik 	if (!path)
143149d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
143249d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
143349d11beaSJosef Bacik 	btrfs_free_path(path);
143449d11beaSJosef Bacik 
143549d11beaSJosef Bacik 	return root;
1436cb517eabSMiao Xie }
1437cb517eabSMiao Xie 
14382dfb1e43SQu Wenruo /*
14392dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14402dfb1e43SQu Wenruo  *
14412dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14422dfb1e43SQu Wenruo  */
14432dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1444cb517eabSMiao Xie {
1445cb517eabSMiao Xie 	int ret;
1446dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1447cb517eabSMiao Xie 
1448dcc3eb96SNikolay Borisov 	/*
1449dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1450dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1451dcc3eb96SNikolay Borisov 	 */
1452dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1453dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1454dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1455dcc3eb96SNikolay Borisov 	if (ret)
14568257b2dcSMiao Xie 		goto fail;
14578257b2dcSMiao Xie 
1458aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
145937f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
146092a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1461f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1462f39e4571SJosef Bacik 	}
1463f39e4571SJosef Bacik 
1464851fd730SQu Wenruo 	/*
1465851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1466851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1467851fd730SQu Wenruo 	 */
1468851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1469851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
14702dfb1e43SQu Wenruo 		if (!anon_dev) {
1471cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1472cb517eabSMiao Xie 			if (ret)
1473876d2cf1SLiu Bo 				goto fail;
14742dfb1e43SQu Wenruo 		} else {
14752dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
14762dfb1e43SQu Wenruo 		}
1477851fd730SQu Wenruo 	}
1478f32e48e9SChandan Rajendra 
1479f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1480453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1481f32e48e9SChandan Rajendra 	if (ret) {
1482f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1483876d2cf1SLiu Bo 		goto fail;
1484f32e48e9SChandan Rajendra 	}
1485f32e48e9SChandan Rajendra 
14866b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1487f32e48e9SChandan Rajendra 
1488f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1489f32e48e9SChandan Rajendra 
1490cb517eabSMiao Xie 	return 0;
1491cb517eabSMiao Xie fail:
149284db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1493cb517eabSMiao Xie 	return ret;
1494cb517eabSMiao Xie }
1495cb517eabSMiao Xie 
1496a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1497cb517eabSMiao Xie 					       u64 root_id)
1498cb517eabSMiao Xie {
1499cb517eabSMiao Xie 	struct btrfs_root *root;
1500cb517eabSMiao Xie 
1501fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1502fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1503fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1504bc44d7c4SJosef Bacik 	if (root)
150500246528SJosef Bacik 		root = btrfs_grab_root(root);
1506fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1507cb517eabSMiao Xie 	return root;
1508cb517eabSMiao Xie }
1509cb517eabSMiao Xie 
151049d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
151149d11beaSJosef Bacik 						u64 objectid)
151249d11beaSJosef Bacik {
1513abed4aaaSJosef Bacik 	struct btrfs_key key = {
1514abed4aaaSJosef Bacik 		.objectid = objectid,
1515abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1516abed4aaaSJosef Bacik 		.offset = 0,
1517abed4aaaSJosef Bacik 	};
1518abed4aaaSJosef Bacik 
151949d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
152049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
152149d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1522abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
152349d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
152449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
152549d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
152649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
152749d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1528abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
152949d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
153049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
153149d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
153249d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
153349d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
153449d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
153514033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
153614033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
153714033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1538abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1539abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1540abed4aaaSJosef Bacik 
1541abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1542abed4aaaSJosef Bacik 	}
154349d11beaSJosef Bacik 	return NULL;
154449d11beaSJosef Bacik }
154549d11beaSJosef Bacik 
1546cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1547cb517eabSMiao Xie 			 struct btrfs_root *root)
1548cb517eabSMiao Xie {
1549cb517eabSMiao Xie 	int ret;
1550cb517eabSMiao Xie 
1551fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1552fc7cbcd4SDavid Sterba 	if (ret)
1553fc7cbcd4SDavid Sterba 		return ret;
1554fc7cbcd4SDavid Sterba 
1555fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1556fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1557fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1558fc7cbcd4SDavid Sterba 				root);
1559af01d2e5SJosef Bacik 	if (ret == 0) {
156000246528SJosef Bacik 		btrfs_grab_root(root);
1561fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1562af01d2e5SJosef Bacik 	}
1563fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1564fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1565cb517eabSMiao Xie 
1566cb517eabSMiao Xie 	return ret;
1567cb517eabSMiao Xie }
1568cb517eabSMiao Xie 
1569bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1570bd647ce3SJosef Bacik {
1571bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1572bd647ce3SJosef Bacik 	struct btrfs_root *root;
1573bd647ce3SJosef Bacik 
1574bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1575457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1576457f1864SJosef Bacik 
1577bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1578bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1579457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
158071008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1581bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1582bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
158300246528SJosef Bacik 			btrfs_put_root(root);
158400246528SJosef Bacik 		btrfs_put_root(root);
1585bd647ce3SJosef Bacik 	}
1586bd647ce3SJosef Bacik #endif
1587bd647ce3SJosef Bacik }
1588bd647ce3SJosef Bacik 
1589abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1590abed4aaaSJosef Bacik {
1591abed4aaaSJosef Bacik 	struct btrfs_root *root;
1592abed4aaaSJosef Bacik 	struct rb_node *node;
1593abed4aaaSJosef Bacik 
1594abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1595abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1596abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1597abed4aaaSJosef Bacik 		btrfs_put_root(root);
1598abed4aaaSJosef Bacik 	}
1599abed4aaaSJosef Bacik }
1600abed4aaaSJosef Bacik 
16010d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
16020d4b0463SJosef Bacik {
1603141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1604141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
16055deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1606141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1607141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1608141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1609141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
16100d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16110d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1612abed4aaaSJosef Bacik 	free_global_roots(fs_info);
161300246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
161400246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
161500246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
161600246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
161700246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
161800246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1619aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
16209c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1621bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16223fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16230d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16240d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16258481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
16260d4b0463SJosef Bacik 	kvfree(fs_info);
16270d4b0463SJosef Bacik }
16280d4b0463SJosef Bacik 
16290d4b0463SJosef Bacik 
16302dfb1e43SQu Wenruo /*
16312dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
16322dfb1e43SQu Wenruo  *
16332dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
16342dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
16352dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
16362dfb1e43SQu Wenruo  *
16372dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
16382dfb1e43SQu Wenruo  *
16392dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
16402dfb1e43SQu Wenruo  *	 same root objectid.
16412dfb1e43SQu Wenruo  *
16422dfb1e43SQu Wenruo  * @objectid:	root id
16432dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
16442dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16452dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16462dfb1e43SQu Wenruo  *		for orphan roots
16472dfb1e43SQu Wenruo  */
16482dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16492dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16502dfb1e43SQu Wenruo 					     bool check_ref)
16515eda7b5eSChris Mason {
16525eda7b5eSChris Mason 	struct btrfs_root *root;
1653381cf658SDavid Sterba 	struct btrfs_path *path;
16541d4c08e0SDavid Sterba 	struct btrfs_key key;
16555eda7b5eSChris Mason 	int ret;
16565eda7b5eSChris Mason 
165749d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
165849d11beaSJosef Bacik 	if (root)
165949d11beaSJosef Bacik 		return root;
16604df27c4dSYan, Zheng again:
166156e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
166248475471SStefan Behrens 	if (root) {
16632dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16642dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1665bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
166600246528SJosef Bacik 			btrfs_put_root(root);
166748475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1668bc44d7c4SJosef Bacik 		}
16695eda7b5eSChris Mason 		return root;
167048475471SStefan Behrens 	}
16715eda7b5eSChris Mason 
167256e9357aSDavid Sterba 	key.objectid = objectid;
167356e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
167456e9357aSDavid Sterba 	key.offset = (u64)-1;
167556e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16765eda7b5eSChris Mason 	if (IS_ERR(root))
16775eda7b5eSChris Mason 		return root;
16783394e160SChris Mason 
1679c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1680d68fc57bSYan, Zheng 		ret = -ENOENT;
1681d68fc57bSYan, Zheng 		goto fail;
1682d68fc57bSYan, Zheng 	}
1683d68fc57bSYan, Zheng 
16842dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1685cb517eabSMiao Xie 	if (ret)
1686cb517eabSMiao Xie 		goto fail;
1687cb517eabSMiao Xie 
1688381cf658SDavid Sterba 	path = btrfs_alloc_path();
1689381cf658SDavid Sterba 	if (!path) {
1690381cf658SDavid Sterba 		ret = -ENOMEM;
1691381cf658SDavid Sterba 		goto fail;
1692381cf658SDavid Sterba 	}
16931d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
16941d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
169556e9357aSDavid Sterba 	key.offset = objectid;
16961d4c08e0SDavid Sterba 
16971d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1698381cf658SDavid Sterba 	btrfs_free_path(path);
1699d68fc57bSYan, Zheng 	if (ret < 0)
1700d68fc57bSYan, Zheng 		goto fail;
1701d68fc57bSYan, Zheng 	if (ret == 0)
170227cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1703d68fc57bSYan, Zheng 
1704cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17050f7d52f4SChris Mason 	if (ret) {
1706168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
170700246528SJosef Bacik 			btrfs_put_root(root);
17084df27c4dSYan, Zheng 			goto again;
1709168a2f77SJia-Ju Bai 		}
17104df27c4dSYan, Zheng 		goto fail;
17114df27c4dSYan, Zheng 	}
1712edbd8d4eSChris Mason 	return root;
17134df27c4dSYan, Zheng fail:
171433fab972SFilipe Manana 	/*
171533fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1716143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
171733fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
171833fab972SFilipe Manana 	 * and once again by our caller.
171933fab972SFilipe Manana 	 */
172033fab972SFilipe Manana 	if (anon_dev)
172133fab972SFilipe Manana 		root->anon_dev = 0;
17228c38938cSJosef Bacik 	btrfs_put_root(root);
17234df27c4dSYan, Zheng 	return ERR_PTR(ret);
1724edbd8d4eSChris Mason }
1725edbd8d4eSChris Mason 
17262dfb1e43SQu Wenruo /*
17272dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
17282dfb1e43SQu Wenruo  *
17292dfb1e43SQu Wenruo  * @objectid:	tree objectid
17302dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
17312dfb1e43SQu Wenruo  *		one reference
17322dfb1e43SQu Wenruo  */
17332dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
17342dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
17352dfb1e43SQu Wenruo {
17362dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
17372dfb1e43SQu Wenruo }
17382dfb1e43SQu Wenruo 
17392dfb1e43SQu Wenruo /*
17402dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
17412dfb1e43SQu Wenruo  * the anonymous block device id
17422dfb1e43SQu Wenruo  *
17432dfb1e43SQu Wenruo  * @objectid:	tree objectid
17442dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
17452dfb1e43SQu Wenruo  *		parameter value
17462dfb1e43SQu Wenruo  */
17472dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
17482dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
17492dfb1e43SQu Wenruo {
17502dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
17512dfb1e43SQu Wenruo }
17522dfb1e43SQu Wenruo 
17538b712842SChris Mason /*
175449d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
175549d11beaSJosef Bacik  * @fs_info:	the fs_info
175649d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
175749d11beaSJosef Bacik  *
175849d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
175949d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
176049d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
176149d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
176249d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
176349d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
176449d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
176549d11beaSJosef Bacik  * backref code is finished using the root.
176649d11beaSJosef Bacik  */
176749d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
176849d11beaSJosef Bacik 						 struct btrfs_path *path,
176949d11beaSJosef Bacik 						 u64 objectid)
177049d11beaSJosef Bacik {
177149d11beaSJosef Bacik 	struct btrfs_root *root;
177249d11beaSJosef Bacik 	struct btrfs_key key;
177349d11beaSJosef Bacik 
177449d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
177549d11beaSJosef Bacik 
177649d11beaSJosef Bacik 	/*
177749d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
177849d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
177949d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
178049d11beaSJosef Bacik 	 * != NULL just return it.
178149d11beaSJosef Bacik 	 */
178249d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
178349d11beaSJosef Bacik 	if (root)
178449d11beaSJosef Bacik 		return root;
178549d11beaSJosef Bacik 
178649d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
178749d11beaSJosef Bacik 	if (root)
178849d11beaSJosef Bacik 		return root;
178949d11beaSJosef Bacik 
179049d11beaSJosef Bacik 	key.objectid = objectid;
179149d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
179249d11beaSJosef Bacik 	key.offset = (u64)-1;
179349d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
179449d11beaSJosef Bacik 	btrfs_release_path(path);
179549d11beaSJosef Bacik 
179649d11beaSJosef Bacik 	return root;
179749d11beaSJosef Bacik }
179849d11beaSJosef Bacik 
1799a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1800a74a4b97SChris Mason {
18010d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1802d0278245SMiao Xie 	int again;
1803a74a4b97SChris Mason 
1804d6fd0ae2SOmar Sandoval 	while (1) {
1805d0278245SMiao Xie 		again = 0;
18069d1a2a3aSDavid Sterba 
1807fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1808fd340d0fSJosef Bacik 
1809d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18102ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1811d0278245SMiao Xie 			goto sleep;
1812d0278245SMiao Xie 
181390c711abSZygo Blaxell 		/*
181490c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
181590c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
181690c711abSZygo Blaxell 		 */
18170b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
181890c711abSZygo Blaxell 			goto sleep;
181990c711abSZygo Blaxell 
18200b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1821d0278245SMiao Xie 			goto sleep;
1822d0278245SMiao Xie 
1823dc7f370cSMiao Xie 		/*
1824dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1825dc7f370cSMiao Xie 		 * during the above check and trylock.
1826dc7f370cSMiao Xie 		 */
18272ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18280b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1829dc7f370cSMiao Xie 			goto sleep;
1830dc7f370cSMiao Xie 		}
1831dc7f370cSMiao Xie 
18322ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1833c2d6cb16SFilipe Manana 
183433c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
18350b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1836a74a4b97SChris Mason 
1837d0278245SMiao Xie 		/*
183805323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
183905323cd1SMiao Xie 		 * needn't do anything special here.
1840d0278245SMiao Xie 		 */
18410b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
184267c5e7d4SFilipe Manana 
184367c5e7d4SFilipe Manana 		/*
1844f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
184567c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
184667c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1847f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
184867c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
184967c5e7d4SFilipe Manana 		 * unused block groups.
185067c5e7d4SFilipe Manana 		 */
18510b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
185218bb8bbfSJohannes Thumshirn 
185318bb8bbfSJohannes Thumshirn 		/*
185418bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
185518bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
185618bb8bbfSJohannes Thumshirn 		 * space.
185718bb8bbfSJohannes Thumshirn 		 */
185818bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1859d0278245SMiao Xie sleep:
1860a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1861d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1862d6fd0ae2SOmar Sandoval 			kthread_parkme();
1863d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1864d6fd0ae2SOmar Sandoval 			return 0;
1865838fe188SJiri Kosina 		if (!again) {
1866a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1867a74a4b97SChris Mason 			schedule();
1868a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1869a74a4b97SChris Mason 		}
1870da288d28SFilipe Manana 	}
1871a74a4b97SChris Mason }
1872a74a4b97SChris Mason 
1873a74a4b97SChris Mason static int transaction_kthread(void *arg)
1874a74a4b97SChris Mason {
1875a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1877a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1878a74a4b97SChris Mason 	struct btrfs_transaction *cur;
18798929ecfaSYan, Zheng 	u64 transid;
1880643900beSNikolay Borisov 	time64_t delta;
1881a74a4b97SChris Mason 	unsigned long delay;
1882914b2007SJan Kara 	bool cannot_commit;
1883a74a4b97SChris Mason 
1884a74a4b97SChris Mason 	do {
1885914b2007SJan Kara 		cannot_commit = false;
1886ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
18870b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1888a74a4b97SChris Mason 
18890b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
18900b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1891a74a4b97SChris Mason 		if (!cur) {
18920b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1893a74a4b97SChris Mason 			goto sleep;
1894a74a4b97SChris Mason 		}
189531153d81SYan Zheng 
1896643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1897fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1898fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1899643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
19000b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1901fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1902fb8a7e94SNikolay Borisov 			delay = min(delay,
1903fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1904a74a4b97SChris Mason 			goto sleep;
1905a74a4b97SChris Mason 		}
19068929ecfaSYan, Zheng 		transid = cur->transid;
19070b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
190856bec294SChris Mason 
190979787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1910354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1911914b2007SJan Kara 		if (IS_ERR(trans)) {
1912354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1913914b2007SJan Kara 				cannot_commit = true;
191479787eaaSJeff Mahoney 			goto sleep;
1915914b2007SJan Kara 		}
19168929ecfaSYan, Zheng 		if (transid == trans->transid) {
19173a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19188929ecfaSYan, Zheng 		} else {
19193a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19208929ecfaSYan, Zheng 		}
1921a74a4b97SChris Mason sleep:
19220b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19230b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1924a74a4b97SChris Mason 
192584961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
19262ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
19278929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19280b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1929914b2007SJan Kara 				 cannot_commit))
1930bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1931a74a4b97SChris Mason 	} while (!kthread_should_stop());
1932a74a4b97SChris Mason 	return 0;
1933a74a4b97SChris Mason }
1934a74a4b97SChris Mason 
1935af31f5e5SChris Mason /*
193601f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
193701f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
193801f0f9daSNikolay Borisov  * anything.
1939af31f5e5SChris Mason  *
1940af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1941af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1942af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1943af31f5e5SChris Mason  */
194401f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1945af31f5e5SChris Mason {
194601f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1947af31f5e5SChris Mason 	u64 cur;
1948af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1949af31f5e5SChris Mason 	int i;
1950af31f5e5SChris Mason 
1951af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1952af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1953af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1954af31f5e5SChris Mason 		if (cur == newest_gen)
195501f0f9daSNikolay Borisov 			return i;
1956af31f5e5SChris Mason 	}
1957af31f5e5SChris Mason 
195801f0f9daSNikolay Borisov 	return -EINVAL;
1959af31f5e5SChris Mason }
1960af31f5e5SChris Mason 
1961af31f5e5SChris Mason /*
1962af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1963af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1964af31f5e5SChris Mason  * done
1965af31f5e5SChris Mason  */
1966af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1967af31f5e5SChris Mason {
19686ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1969af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1970af31f5e5SChris Mason 
1971af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1972af31f5e5SChris Mason 
1973af31f5e5SChris Mason 	/*
1974af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1975af31f5e5SChris Mason 	 * regardless of which ones we use today
1976af31f5e5SChris Mason 	 */
1977af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1978af31f5e5SChris Mason 
1979af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1980af31f5e5SChris Mason 
1981af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1982af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1983af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1984af31f5e5SChris Mason 
1985af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1986af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1987af31f5e5SChris Mason 
1988af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1989af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1990af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1991af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1992af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1993af31f5e5SChris Mason 
19941c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
19959c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1996f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
19979c54e80dSJosef Bacik 
19989c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
19999c54e80dSJosef Bacik 					     extent_root->node->start);
2000af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
200129cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
2002af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
200329cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
2004af31f5e5SChris Mason 
2005f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
2006f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
2007f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
2008f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
2009f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
20109c54e80dSJosef Bacik 	}
2011af31f5e5SChris Mason 
20127c7e82a7SChris Mason 	/*
20137c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20147c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20157c7e82a7SChris Mason 	 */
20167c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20177c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20187c7e82a7SChris Mason 					 info->fs_root->node->start);
2019af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2020af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2021af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2022af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20237c7e82a7SChris Mason 	}
2024af31f5e5SChris Mason 
2025af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2026af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2027af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2028af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2029af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2030af31f5e5SChris Mason 
2031af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2032af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2033af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2034af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2035af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2036af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2037af31f5e5SChris Mason 
2038af31f5e5SChris Mason 	/*
2039af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2040af31f5e5SChris Mason 	 * for the next commit
2041af31f5e5SChris Mason 	 */
2042af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2043af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2044af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2045af31f5e5SChris Mason }
2046af31f5e5SChris Mason 
2047af31f5e5SChris Mason /*
2048bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2049bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2050bd2336b2SNikolay Borisov  *
2051bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2052bd2336b2SNikolay Borisov  * priority - priority of backup root required
2053bd2336b2SNikolay Borisov  *
2054bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2055bd2336b2SNikolay Borisov  */
2056bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2057bd2336b2SNikolay Borisov {
2058bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2059bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2060bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2061bd2336b2SNikolay Borisov 
2062bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2063bd2336b2SNikolay Borisov 		if (priority == 0)
2064bd2336b2SNikolay Borisov 			return backup_index;
2065bd2336b2SNikolay Borisov 
2066bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2067bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2068bd2336b2SNikolay Borisov 	} else {
2069bd2336b2SNikolay Borisov 		return -EINVAL;
2070bd2336b2SNikolay Borisov 	}
2071bd2336b2SNikolay Borisov 
2072bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2073bd2336b2SNikolay Borisov 
2074bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2075bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2076bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2077bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2078bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2079bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2080bd2336b2SNikolay Borisov 
2081bd2336b2SNikolay Borisov 	/*
2082bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2083bd2336b2SNikolay Borisov 	 * need a fsck
2084bd2336b2SNikolay Borisov 	 */
2085bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2086bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2087bd2336b2SNikolay Borisov 
2088bd2336b2SNikolay Borisov 	return backup_index;
2089bd2336b2SNikolay Borisov }
2090bd2336b2SNikolay Borisov 
20917abadb64SLiu Bo /* helper to cleanup workers */
20927abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20937abadb64SLiu Bo {
2094dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2095afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
2096a31b4a43SChristoph Hellwig 	btrfs_destroy_workqueue(fs_info->hipri_workers);
20975cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2098d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
2099d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
2100385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
2101385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
2102fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
2103fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
2104fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2105fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
21065b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2107e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2108a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2109fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2110b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2111b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2112a9b9477dSFilipe Manana 	/*
2113a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2114a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2115a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2116a9b9477dSFilipe Manana 	 */
2117d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
2118d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
21197abadb64SLiu Bo }
21207abadb64SLiu Bo 
21212e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21222e9f5954SRashika {
21232e9f5954SRashika 	if (root) {
21242e9f5954SRashika 		free_extent_buffer(root->node);
21252e9f5954SRashika 		free_extent_buffer(root->commit_root);
21262e9f5954SRashika 		root->node = NULL;
21272e9f5954SRashika 		root->commit_root = NULL;
21282e9f5954SRashika 	}
21292e9f5954SRashika }
21302e9f5954SRashika 
2131abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2132abed4aaaSJosef Bacik {
2133abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
2134abed4aaaSJosef Bacik 
2135abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
2136abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
2137abed4aaaSJosef Bacik 					     rb_node)
2138abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
2139abed4aaaSJosef Bacik }
2140abed4aaaSJosef Bacik 
2141af31f5e5SChris Mason /* helper to cleanup tree roots */
21424273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2143af31f5e5SChris Mason {
21442e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2145655b09feSJosef Bacik 
2146abed4aaaSJosef Bacik 	free_global_root_pointers(info);
21472e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21482e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21492e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21508c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2151aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
21529c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
21534273eaffSAnand Jain 	if (free_chunk_root)
21542e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2155af31f5e5SChris Mason }
2156af31f5e5SChris Mason 
21578c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
21588c38938cSJosef Bacik {
21598c38938cSJosef Bacik 	if (!root)
21608c38938cSJosef Bacik 		return;
21618c38938cSJosef Bacik 
21628c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21638c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21641dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21658c38938cSJosef Bacik 		if (root->anon_dev)
21668c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21678c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2168923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21698c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2170fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21718c38938cSJosef Bacik 		list_del_init(&root->leak_list);
2172fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21738c38938cSJosef Bacik #endif
21748c38938cSJosef Bacik 		kfree(root);
21758c38938cSJosef Bacik 	}
21768c38938cSJosef Bacik }
21778c38938cSJosef Bacik 
2178faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2179171f6537SJosef Bacik {
2180fc7cbcd4SDavid Sterba 	int ret;
2181fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
2182fc7cbcd4SDavid Sterba 	int i;
2183171f6537SJosef Bacik 
2184171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2185fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
2186171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2187fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
2188171f6537SJosef Bacik 
2189fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2190fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2191fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
2192171f6537SJosef Bacik 	}
2193171f6537SJosef Bacik 
2194fc7cbcd4SDavid Sterba 	while (1) {
2195fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2196fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
2197fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
2198fc7cbcd4SDavid Sterba 		if (!ret)
2199fc7cbcd4SDavid Sterba 			break;
2200fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
2201fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2202171f6537SJosef Bacik 	}
2203171f6537SJosef Bacik }
2204af31f5e5SChris Mason 
2205638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2206638aa7edSEric Sandeen {
2207638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2208638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2209638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2210638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2211638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2212638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2213ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2214638aa7edSEric Sandeen }
2215638aa7edSEric Sandeen 
2216779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2217779a65a4SEric Sandeen {
2218779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2219779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2220779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2221779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2222779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2223779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2224907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2225779a65a4SEric Sandeen }
2226779a65a4SEric Sandeen 
22276bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2228f37938e0SEric Sandeen {
22292ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
2230e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
2231e256927bSJosef Bacik 					      fs_info->tree_root);
22322ff7e61eSJeff Mahoney 
22332ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
22342ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2235f37938e0SEric Sandeen 	/*
2236f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2237f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2238f37938e0SEric Sandeen 	 * the devices in the system
2239f37938e0SEric Sandeen 	 */
22402ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
22412ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2242f37938e0SEric Sandeen 
22432ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
224443eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
2245efb0645bSJosef Bacik 			    IO_TREE_BTREE_INODE_IO, NULL);
22462ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2247f37938e0SEric Sandeen 
22485c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2249adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
2250adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
2251adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
22522ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2253e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
2254f37938e0SEric Sandeen }
2255f37938e0SEric Sandeen 
2256ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2257ad618368SEric Sandeen {
2258ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2259129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
22607f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2261ad618368SEric Sandeen }
2262ad618368SEric Sandeen 
2263f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2264f9e92e40SEric Sandeen {
2265f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2266f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2267f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2268f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2269f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2270f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2271d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2272011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
2273f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2274f9e92e40SEric Sandeen }
2275f9e92e40SEric Sandeen 
2276d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
22772a458198SEric Sandeen {
2278f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22796f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22802a458198SEric Sandeen 
22812a458198SEric Sandeen 	fs_info->workers =
2282a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
2283a31b4a43SChristoph Hellwig 	fs_info->hipri_workers =
2284a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker-high",
2285cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22862a458198SEric Sandeen 
22872a458198SEric Sandeen 	fs_info->delalloc_workers =
2288cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2289cb001095SJeff Mahoney 				      flags, max_active, 2);
22902a458198SEric Sandeen 
22912a458198SEric Sandeen 	fs_info->flush_workers =
2292cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2293cb001095SJeff Mahoney 				      flags, max_active, 0);
22942a458198SEric Sandeen 
22952a458198SEric Sandeen 	fs_info->caching_workers =
2296cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
22972a458198SEric Sandeen 
22982a458198SEric Sandeen 	fs_info->fixup_workers =
2299cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23002a458198SEric Sandeen 
23012a458198SEric Sandeen 	fs_info->endio_workers =
2302d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
23032a458198SEric Sandeen 	fs_info->endio_meta_workers =
2304d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
2305385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
23062a458198SEric Sandeen 	fs_info->endio_write_workers =
2307cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2308cb001095SJeff Mahoney 				      max_active, 2);
2309fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
2310fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
23112a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2312cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2313cb001095SJeff Mahoney 				      max_active, 0);
23142a458198SEric Sandeen 	fs_info->delayed_workers =
2315cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2316cb001095SJeff Mahoney 				      max_active, 0);
23172a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2318cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2319b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2320b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23212a458198SEric Sandeen 
2322a31b4a43SChristoph Hellwig 	if (!(fs_info->workers && fs_info->hipri_workers &&
2323a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
23242a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2325fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
2326*1a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
23272a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2328f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2329f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2330b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
23312a458198SEric Sandeen 		return -ENOMEM;
23322a458198SEric Sandeen 	}
23332a458198SEric Sandeen 
23342a458198SEric Sandeen 	return 0;
23352a458198SEric Sandeen }
23362a458198SEric Sandeen 
23376d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
23386d97c6e3SJohannes Thumshirn {
23396d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2340b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
23416d97c6e3SJohannes Thumshirn 
2342b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
23436d97c6e3SJohannes Thumshirn 
23446d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
23456d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2346b4e967beSDavid Sterba 			  csum_driver);
23476d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
23486d97c6e3SJohannes Thumshirn 	}
23496d97c6e3SJohannes Thumshirn 
23506d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23516d97c6e3SJohannes Thumshirn 
2352c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2353c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2354c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
23556d97c6e3SJohannes Thumshirn 	return 0;
23566d97c6e3SJohannes Thumshirn }
23576d97c6e3SJohannes Thumshirn 
235863443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
235963443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
236063443bf5SEric Sandeen {
236163443bf5SEric Sandeen 	int ret;
236263443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
236363443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
236463443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2365581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
236663443bf5SEric Sandeen 
236763443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2368f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
236963443bf5SEric Sandeen 		return -EIO;
237063443bf5SEric Sandeen 	}
237163443bf5SEric Sandeen 
237296dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
237396dfcb46SJosef Bacik 					 GFP_KERNEL);
237463443bf5SEric Sandeen 	if (!log_tree_root)
237563443bf5SEric Sandeen 		return -ENOMEM;
237663443bf5SEric Sandeen 
23772ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
23781b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
23791b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
23801b7ec85eSJosef Bacik 					      NULL);
238164c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2382f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
23830eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
23848c38938cSJosef Bacik 		log_tree_root->node = NULL;
238500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
23860eeff236SLiu Bo 		return ret;
23874eb150d6SQu Wenruo 	}
23884eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2389f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
239000246528SJosef Bacik 		btrfs_put_root(log_tree_root);
239163443bf5SEric Sandeen 		return -EIO;
239263443bf5SEric Sandeen 	}
23934eb150d6SQu Wenruo 
239463443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
239563443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
239663443bf5SEric Sandeen 	if (ret) {
23970b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
239863443bf5SEric Sandeen 				      "Failed to recover log tree");
239900246528SJosef Bacik 		btrfs_put_root(log_tree_root);
240063443bf5SEric Sandeen 		return ret;
240163443bf5SEric Sandeen 	}
240263443bf5SEric Sandeen 
2403bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
24046bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
240563443bf5SEric Sandeen 		if (ret)
240663443bf5SEric Sandeen 			return ret;
240763443bf5SEric Sandeen 	}
240863443bf5SEric Sandeen 
240963443bf5SEric Sandeen 	return 0;
241063443bf5SEric Sandeen }
241163443bf5SEric Sandeen 
2412abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2413abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2414abed4aaaSJosef Bacik 				      const char *name)
2415abed4aaaSJosef Bacik {
2416abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2417abed4aaaSJosef Bacik 	struct btrfs_root *root;
2418f7238e50SJosef Bacik 	u64 max_global_id = 0;
2419abed4aaaSJosef Bacik 	int ret;
2420abed4aaaSJosef Bacik 	struct btrfs_key key = {
2421abed4aaaSJosef Bacik 		.objectid = objectid,
2422abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2423abed4aaaSJosef Bacik 		.offset = 0,
2424abed4aaaSJosef Bacik 	};
2425abed4aaaSJosef Bacik 	bool found = false;
2426abed4aaaSJosef Bacik 
2427abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2428abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2429abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2430abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2431abed4aaaSJosef Bacik 		return 0;
2432abed4aaaSJosef Bacik 	}
2433abed4aaaSJosef Bacik 
2434abed4aaaSJosef Bacik 	while (1) {
2435abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2436abed4aaaSJosef Bacik 		if (ret < 0)
2437abed4aaaSJosef Bacik 			break;
2438abed4aaaSJosef Bacik 
2439abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2440abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2441abed4aaaSJosef Bacik 			if (ret) {
2442abed4aaaSJosef Bacik 				if (ret > 0)
2443abed4aaaSJosef Bacik 					ret = 0;
2444abed4aaaSJosef Bacik 				break;
2445abed4aaaSJosef Bacik 			}
2446abed4aaaSJosef Bacik 		}
2447abed4aaaSJosef Bacik 		ret = 0;
2448abed4aaaSJosef Bacik 
2449abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2450abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2451abed4aaaSJosef Bacik 			break;
2452abed4aaaSJosef Bacik 		btrfs_release_path(path);
2453abed4aaaSJosef Bacik 
2454f7238e50SJosef Bacik 		/*
2455f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2456f7238e50SJosef Bacik 		 * everybody.
2457f7238e50SJosef Bacik 		 */
2458f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2459f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2460f7238e50SJosef Bacik 
2461abed4aaaSJosef Bacik 		found = true;
2462abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2463abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2464abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2465abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2466abed4aaaSJosef Bacik 			break;
2467abed4aaaSJosef Bacik 		}
2468abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2469abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2470abed4aaaSJosef Bacik 		if (ret) {
2471abed4aaaSJosef Bacik 			btrfs_put_root(root);
2472abed4aaaSJosef Bacik 			break;
2473abed4aaaSJosef Bacik 		}
2474abed4aaaSJosef Bacik 		key.offset++;
2475abed4aaaSJosef Bacik 	}
2476abed4aaaSJosef Bacik 	btrfs_release_path(path);
2477abed4aaaSJosef Bacik 
2478f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2479f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2480f7238e50SJosef Bacik 
2481abed4aaaSJosef Bacik 	if (!found || ret) {
2482abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2483abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2484abed4aaaSJosef Bacik 
2485abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2486abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2487abed4aaaSJosef Bacik 		else
2488abed4aaaSJosef Bacik 			ret = 0;
2489abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2490abed4aaaSJosef Bacik 	}
2491abed4aaaSJosef Bacik 	return ret;
2492abed4aaaSJosef Bacik }
2493abed4aaaSJosef Bacik 
2494abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2495abed4aaaSJosef Bacik {
2496abed4aaaSJosef Bacik 	struct btrfs_path *path;
2497abed4aaaSJosef Bacik 	int ret = 0;
2498abed4aaaSJosef Bacik 
2499abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2500abed4aaaSJosef Bacik 	if (!path)
2501abed4aaaSJosef Bacik 		return -ENOMEM;
2502abed4aaaSJosef Bacik 
2503abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2504abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2505abed4aaaSJosef Bacik 	if (ret)
2506abed4aaaSJosef Bacik 		goto out;
2507abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2508abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2509abed4aaaSJosef Bacik 	if (ret)
2510abed4aaaSJosef Bacik 		goto out;
2511abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2512abed4aaaSJosef Bacik 		goto out;
2513abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2514abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2515abed4aaaSJosef Bacik 					 "free space");
2516abed4aaaSJosef Bacik out:
2517abed4aaaSJosef Bacik 	btrfs_free_path(path);
2518abed4aaaSJosef Bacik 	return ret;
2519abed4aaaSJosef Bacik }
2520abed4aaaSJosef Bacik 
25216bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
25224bbcaa64SEric Sandeen {
25236bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2524a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
25254bbcaa64SEric Sandeen 	struct btrfs_key location;
25264bbcaa64SEric Sandeen 	int ret;
25274bbcaa64SEric Sandeen 
25286bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
25296bccf3abSJeff Mahoney 
2530abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2531abed4aaaSJosef Bacik 	if (ret)
2532abed4aaaSJosef Bacik 		return ret;
2533abed4aaaSJosef Bacik 
25344bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
25354bbcaa64SEric Sandeen 	location.offset = 0;
25364bbcaa64SEric Sandeen 
25371c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
253814033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
253914033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
254014033b08SQu Wenruo 		if (IS_ERR(root)) {
254114033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
254214033b08SQu Wenruo 				ret = PTR_ERR(root);
254314033b08SQu Wenruo 				goto out;
254414033b08SQu Wenruo 			}
254514033b08SQu Wenruo 		} else {
254614033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
254714033b08SQu Wenruo 			fs_info->block_group_root = root;
254814033b08SQu Wenruo 		}
254914033b08SQu Wenruo 	}
255014033b08SQu Wenruo 
255114033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2552a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2553f50f4353SLiu Bo 	if (IS_ERR(root)) {
255442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2555f50f4353SLiu Bo 			ret = PTR_ERR(root);
2556f50f4353SLiu Bo 			goto out;
2557f50f4353SLiu Bo 		}
255842437a63SJosef Bacik 	} else {
2559a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2560a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
256142437a63SJosef Bacik 	}
2562820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2563a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2564a8d1b164SJohannes Thumshirn 	if (ret)
2565a8d1b164SJohannes Thumshirn 		goto out;
25664bbcaa64SEric Sandeen 
2567aeb935a4SQu Wenruo 	/*
2568aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2569aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2570aeb935a4SQu Wenruo 	 */
257156e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
257256e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2573aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
257442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2575aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2576aeb935a4SQu Wenruo 			goto out;
2577aeb935a4SQu Wenruo 		}
257842437a63SJosef Bacik 	} else {
2579aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2580aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
258142437a63SJosef Bacik 	}
2582aeb935a4SQu Wenruo 
25834bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2584a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2585a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2586a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2587afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2588a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25894bbcaa64SEric Sandeen 	}
25904bbcaa64SEric Sandeen 
25914bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2592a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2593a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
259442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2595a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25964bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2597f50f4353SLiu Bo 				goto out;
259842437a63SJosef Bacik 		}
25994bbcaa64SEric Sandeen 	} else {
2600a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2601a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
26024bbcaa64SEric Sandeen 	}
26034bbcaa64SEric Sandeen 
26044bbcaa64SEric Sandeen 	return 0;
2605f50f4353SLiu Bo out:
2606f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2607f50f4353SLiu Bo 		   location.objectid, ret);
2608f50f4353SLiu Bo 	return ret;
26094bbcaa64SEric Sandeen }
26104bbcaa64SEric Sandeen 
2611069ec957SQu Wenruo /*
2612069ec957SQu Wenruo  * Real super block validation
2613069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2614069ec957SQu Wenruo  *
2615069ec957SQu Wenruo  * @sb:		super block to check
2616069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2617069ec957SQu Wenruo  * 		0	the primary (1st) sb
2618069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2619069ec957SQu Wenruo  * 	       -1	skip bytenr check
2620069ec957SQu Wenruo  */
2621a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2622069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
262321a852b0SQu Wenruo {
262421a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
262521a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
262621a852b0SQu Wenruo 	int ret = 0;
262721a852b0SQu Wenruo 
262821a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
262921a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
263021a852b0SQu Wenruo 		ret = -EINVAL;
263121a852b0SQu Wenruo 	}
263221a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
263321a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
263421a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
263521a852b0SQu Wenruo 		ret = -EINVAL;
263621a852b0SQu Wenruo 	}
263721a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
263821a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
263921a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
264021a852b0SQu Wenruo 		ret = -EINVAL;
264121a852b0SQu Wenruo 	}
264221a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
264321a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
264421a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
264521a852b0SQu Wenruo 		ret = -EINVAL;
264621a852b0SQu Wenruo 	}
264721a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
264821a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
264921a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
265021a852b0SQu Wenruo 		ret = -EINVAL;
265121a852b0SQu Wenruo 	}
265221a852b0SQu Wenruo 
265321a852b0SQu Wenruo 	/*
265421a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
265521a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
265621a852b0SQu Wenruo 	 */
265721a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
265821a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
265921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
266021a852b0SQu Wenruo 		ret = -EINVAL;
266121a852b0SQu Wenruo 	}
26620bb3eb3eSQu Wenruo 
26630bb3eb3eSQu Wenruo 	/*
26641a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
26651a42daabSQu Wenruo 	 *
26661a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
26671a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
26681a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
26691a42daabSQu Wenruo 	 * beginning.
26700bb3eb3eSQu Wenruo 	 */
26711a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
267221a852b0SQu Wenruo 		btrfs_err(fs_info,
26730bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
267421a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
267521a852b0SQu Wenruo 		ret = -EINVAL;
267621a852b0SQu Wenruo 	}
26770bb3eb3eSQu Wenruo 
267821a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
267921a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
268021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
268121a852b0SQu Wenruo 		ret = -EINVAL;
268221a852b0SQu Wenruo 	}
268321a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
268421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
268521a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
268621a852b0SQu Wenruo 		ret = -EINVAL;
268721a852b0SQu Wenruo 	}
268821a852b0SQu Wenruo 
268921a852b0SQu Wenruo 	/* Root alignment check */
269021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
269121a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
269221a852b0SQu Wenruo 			   btrfs_super_root(sb));
269321a852b0SQu Wenruo 		ret = -EINVAL;
269421a852b0SQu Wenruo 	}
269521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
269621a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
269721a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
269821a852b0SQu Wenruo 		ret = -EINVAL;
269921a852b0SQu Wenruo 	}
270021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
270121a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
270221a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
270321a852b0SQu Wenruo 		ret = -EINVAL;
270421a852b0SQu Wenruo 	}
270521a852b0SQu Wenruo 
2706aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2707aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2708aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2709aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2710aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2711aefd7f70SNikolay Borisov 		ret = -EINVAL;
2712aefd7f70SNikolay Borisov 	}
2713aefd7f70SNikolay Borisov 
2714aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2715aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2716aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2717aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2718aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2719aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2720aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2721aefd7f70SNikolay Borisov 		ret = -EINVAL;
2722aefd7f70SNikolay Borisov 	}
2723aefd7f70SNikolay Borisov 
27241c56ab99SQu Wenruo 	/*
27251c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
27261c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
27271c56ab99SQu Wenruo 	 */
27281c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
27291c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
27301c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
27311c56ab99SQu Wenruo 		btrfs_err(fs_info,
27321c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
27331c56ab99SQu Wenruo 		ret = -EINVAL;
27341c56ab99SQu Wenruo 	}
27351c56ab99SQu Wenruo 
2736de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
27377239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
273821a852b0SQu Wenruo 		btrfs_err(fs_info,
27397239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2740de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
274121a852b0SQu Wenruo 		ret = -EINVAL;
274221a852b0SQu Wenruo 	}
274321a852b0SQu Wenruo 
274421a852b0SQu Wenruo 	/*
274521a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
274621a852b0SQu Wenruo 	 * done later
274721a852b0SQu Wenruo 	 */
274821a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
274921a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
275021a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
275121a852b0SQu Wenruo 		ret = -EINVAL;
275221a852b0SQu Wenruo 	}
275321a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
275421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
275521a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
275621a852b0SQu Wenruo 		ret = -EINVAL;
275721a852b0SQu Wenruo 	}
275821a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
275921a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
276021a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
276121a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
276221a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
276321a852b0SQu Wenruo 		ret = -EINVAL;
276421a852b0SQu Wenruo 	}
276521a852b0SQu Wenruo 
2766069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2767069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
276821a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
276921a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
277021a852b0SQu Wenruo 		ret = -EINVAL;
277121a852b0SQu Wenruo 	}
277221a852b0SQu Wenruo 
277321a852b0SQu Wenruo 	/*
277421a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
277521a852b0SQu Wenruo 	 * and one chunk
277621a852b0SQu Wenruo 	 */
277721a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
277821a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
277921a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
278021a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
278121a852b0SQu Wenruo 		ret = -EINVAL;
278221a852b0SQu Wenruo 	}
278321a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
278421a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
278521a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
278621a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
278721a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
278821a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
278921a852b0SQu Wenruo 		ret = -EINVAL;
279021a852b0SQu Wenruo 	}
279121a852b0SQu Wenruo 
279221a852b0SQu Wenruo 	/*
279321a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
279421a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
279521a852b0SQu Wenruo 	 */
279621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
279721a852b0SQu Wenruo 		btrfs_warn(fs_info,
279821a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
279921a852b0SQu Wenruo 			btrfs_super_generation(sb),
280021a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
280121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
280221a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
280321a852b0SQu Wenruo 		btrfs_warn(fs_info,
280421a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
280521a852b0SQu Wenruo 			btrfs_super_generation(sb),
280621a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
280721a852b0SQu Wenruo 
280821a852b0SQu Wenruo 	return ret;
280921a852b0SQu Wenruo }
281021a852b0SQu Wenruo 
2811069ec957SQu Wenruo /*
2812069ec957SQu Wenruo  * Validation of super block at mount time.
2813069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2814069ec957SQu Wenruo  * flags will be skipped.
2815069ec957SQu Wenruo  */
2816069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2817069ec957SQu Wenruo {
2818a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2819069ec957SQu Wenruo }
2820069ec957SQu Wenruo 
282175cb857dSQu Wenruo /*
282275cb857dSQu Wenruo  * Validation of super block at write time.
282375cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
282475cb857dSQu Wenruo  * overwritten soon.
282575cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
282675cb857dSQu Wenruo  */
282775cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
282875cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
282975cb857dSQu Wenruo {
283075cb857dSQu Wenruo 	int ret;
283175cb857dSQu Wenruo 
2832a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
283375cb857dSQu Wenruo 	if (ret < 0)
283475cb857dSQu Wenruo 		goto out;
2835e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
283675cb857dSQu Wenruo 		ret = -EUCLEAN;
283775cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
283875cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
283975cb857dSQu Wenruo 		goto out;
284075cb857dSQu Wenruo 	}
284175cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
284275cb857dSQu Wenruo 		ret = -EUCLEAN;
284375cb857dSQu Wenruo 		btrfs_err(fs_info,
284475cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
284575cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
284675cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
284775cb857dSQu Wenruo 		goto out;
284875cb857dSQu Wenruo 	}
284975cb857dSQu Wenruo out:
285075cb857dSQu Wenruo 	if (ret < 0)
285175cb857dSQu Wenruo 		btrfs_err(fs_info,
285275cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
285375cb857dSQu Wenruo 	return ret;
285475cb857dSQu Wenruo }
285575cb857dSQu Wenruo 
2856bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2857bd676446SJosef Bacik {
2858bd676446SJosef Bacik 	int ret = 0;
2859bd676446SJosef Bacik 
2860bd676446SJosef Bacik 	root->node = read_tree_block(root->fs_info, bytenr,
2861bd676446SJosef Bacik 				     root->root_key.objectid, gen, level, NULL);
2862bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2863bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2864bd676446SJosef Bacik 		root->node = NULL;
28654eb150d6SQu Wenruo 		return ret;
28664eb150d6SQu Wenruo 	}
28674eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2868bd676446SJosef Bacik 		free_extent_buffer(root->node);
2869bd676446SJosef Bacik 		root->node = NULL;
28704eb150d6SQu Wenruo 		return -EIO;
2871bd676446SJosef Bacik 	}
2872bd676446SJosef Bacik 
2873bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2874bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2875bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2876bd676446SJosef Bacik 	return ret;
2877bd676446SJosef Bacik }
2878bd676446SJosef Bacik 
2879bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2880bd676446SJosef Bacik {
2881bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2882bd676446SJosef Bacik 	u64 gen, bytenr;
2883bd676446SJosef Bacik 	int level, ret;
2884bd676446SJosef Bacik 
2885bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2886bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2887bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2888bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
28899c54e80dSJosef Bacik 	if (ret) {
2890bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2891bd676446SJosef Bacik 		return ret;
2892bd676446SJosef Bacik 	}
28939c54e80dSJosef Bacik 	return 0;
28949c54e80dSJosef Bacik }
28959c54e80dSJosef Bacik 
28966ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2897b8522a1eSNikolay Borisov {
28986ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2899b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2900b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2901b8522a1eSNikolay Borisov 	bool handle_error = false;
2902b8522a1eSNikolay Borisov 	int ret = 0;
2903b8522a1eSNikolay Borisov 	int i;
2904b8522a1eSNikolay Borisov 
2905b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2906b8522a1eSNikolay Borisov 		if (handle_error) {
2907b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2908b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2909b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2910b8522a1eSNikolay Borisov 
2911b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2912b8522a1eSNikolay Borisov 				break;
2913b8522a1eSNikolay Borisov 
2914b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2915b8522a1eSNikolay Borisov 
2916b8522a1eSNikolay Borisov 			/*
2917b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2918b8522a1eSNikolay Borisov 			 * valid
2919b8522a1eSNikolay Borisov 			 */
2920b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2921b8522a1eSNikolay Borisov 
2922b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2923b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2924b8522a1eSNikolay Borisov 
2925b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
29266ef108ddSNikolay Borisov 			backup_index = ret;
2927b8522a1eSNikolay Borisov 			if (ret < 0)
2928b8522a1eSNikolay Borisov 				return ret;
2929b8522a1eSNikolay Borisov 		}
2930b8522a1eSNikolay Borisov 
2931bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2932bd676446SJosef Bacik 		if (ret) {
2933217f5004SNikolay Borisov 			handle_error = true;
2934b8522a1eSNikolay Borisov 			continue;
2935b8522a1eSNikolay Borisov 		}
2936b8522a1eSNikolay Borisov 
2937336a0d8dSNikolay Borisov 		/*
2938336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2939336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2940336a0d8dSNikolay Borisov 		 */
2941453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2942b8522a1eSNikolay Borisov 		if (ret < 0) {
2943b8522a1eSNikolay Borisov 			handle_error = true;
2944b8522a1eSNikolay Borisov 			continue;
2945b8522a1eSNikolay Borisov 		}
2946b8522a1eSNikolay Borisov 
29476b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2948b8522a1eSNikolay Borisov 
2949b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2950b8522a1eSNikolay Borisov 		if (ret < 0) {
2951b8522a1eSNikolay Borisov 			handle_error = true;
2952b8522a1eSNikolay Borisov 			continue;
2953b8522a1eSNikolay Borisov 		}
2954b8522a1eSNikolay Borisov 
2955b8522a1eSNikolay Borisov 		/* All successful */
2956bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2957bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2958d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
29596ef108ddSNikolay Borisov 
29606ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
29616ef108ddSNikolay Borisov 		if (backup_index < 0) {
29626ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
29636ef108ddSNikolay Borisov 		} else {
29646ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
29656ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
29666ef108ddSNikolay Borisov 		}
2967b8522a1eSNikolay Borisov 		break;
2968b8522a1eSNikolay Borisov 	}
2969b8522a1eSNikolay Borisov 
2970b8522a1eSNikolay Borisov 	return ret;
2971b8522a1eSNikolay Borisov }
2972b8522a1eSNikolay Borisov 
29738260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2974eb60ceacSChris Mason {
2975fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
297601cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
29778fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2978facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
297924bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2980eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
298111833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2982eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2983a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2984fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
298524bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
29864cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2987ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2988f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
298947ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
299040ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2991afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2992c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2993f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2994abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2995d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2996f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
29977585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2998573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
29990bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
30005f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
3001de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
300219c00ddcSChris Mason 
3003e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
30045a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
30058b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
30065f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
30073e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
30083e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
30093e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
30103e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
30113e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
30123e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
30133e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
30143e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
3015e1489b4fSIoannis Angelakopoulos 
30160b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
30176324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
3018f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
301947ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
302018bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
3021afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
3022bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
3023bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
30243fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
30253fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
3026bd647ce3SJosef Bacik #endif
3027c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
302866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
302966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
303066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
303166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
303266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
303366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
303466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
3035ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
3036ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
3037ba2c4d4eSJosef Bacik 
3038771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
30394cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
3040034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
3041fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
3042abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
304395ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
30449ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
30454cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
3046a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
3047f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
30488b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
3049f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
3050fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
3051c8b97818SChris Mason 
3052b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
3053b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
30540afbaf8cSChris Mason 
3055199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
3056199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
305769fe2d75SJosef Bacik 
3058638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
305921adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
306021adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
306121adbd5cSStefan Behrens #endif
3062779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
306357056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
3064a2de733cSArne Jansen 
306516b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
306608dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
30670f9dd46cSJosef Bacik 
3068fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
3069fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
307039279cc3SChris Mason 
30715a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
3072e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
3073925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
3074a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
3075a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
30761bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
30779e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
3078c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
307976dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
3080803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
3081fa9c0d79SChris Mason 
3082ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
3083f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
3084b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
3085416ac51dSArne Jansen 
3086fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3087fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3088fa9c0d79SChris Mason 
3089e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
3090f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
3091bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
30924854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
3093034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
30943768f368SChris Mason 
3095da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
3096da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
3097da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
3098ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
3099da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
3100da17066cSJeff Mahoney 
3101f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
3102f7b12a62SNaohiro Aota 
3103eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
3104eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
3105eede2bf3SOmar Sandoval 
310618bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
310718bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
31088260edbaSJosef Bacik }
31098260edbaSJosef Bacik 
31108260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
31118260edbaSJosef Bacik {
31128260edbaSJosef Bacik 	int ret;
31138260edbaSJosef Bacik 
31148260edbaSJosef Bacik 	fs_info->sb = sb;
31158260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
31168260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
31179e967495SFilipe Manana 
31185deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3119ae18c37aSJosef Bacik 	if (ret)
3120ae18c37aSJosef Bacik 		return ret;
3121ae18c37aSJosef Bacik 
3122ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3123ae18c37aSJosef Bacik 	if (ret)
3124c75e8394SJosef Bacik 		return ret;
3125ae18c37aSJosef Bacik 
3126ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3127ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3128ae18c37aSJosef Bacik 
3129ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3130ae18c37aSJosef Bacik 	if (ret)
3131c75e8394SJosef Bacik 		return ret;
3132ae18c37aSJosef Bacik 
3133ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3134ae18c37aSJosef Bacik 			GFP_KERNEL);
3135ae18c37aSJosef Bacik 	if (ret)
3136c75e8394SJosef Bacik 		return ret;
3137ae18c37aSJosef Bacik 
3138ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3139ae18c37aSJosef Bacik 					GFP_KERNEL);
3140c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3141c75e8394SJosef Bacik 		return -ENOMEM;
3142ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3143ae18c37aSJosef Bacik 
3144a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3145a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3146a0a1db70SFilipe Manana 
3147c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3148ae18c37aSJosef Bacik }
3149ae18c37aSJosef Bacik 
315097f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
315197f4dd09SNikolay Borisov {
31520d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
315397f4dd09SNikolay Borisov 	int ret;
315497f4dd09SNikolay Borisov 
315597f4dd09SNikolay Borisov 	/*
315697f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
315797f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
315897f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
315997f4dd09SNikolay Borisov 	 */
316097f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
316197f4dd09SNikolay Borisov 	if (ret < 0) {
3162c94bec2cSJosef Bacik 		if (ret != -EINTR)
3163c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3164c94bec2cSJosef Bacik 				   ret);
316597f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
316697f4dd09SNikolay Borisov 		return ret;
316797f4dd09SNikolay Borisov 	}
316897f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
316997f4dd09SNikolay Borisov }
317097f4dd09SNikolay Borisov 
317197f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
317297f4dd09SNikolay Borisov {
317397f4dd09SNikolay Borisov 	struct task_struct *task;
317497f4dd09SNikolay Borisov 
317597f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
317697f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
317797f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
317897f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
317997f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
318097f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
318197f4dd09SNikolay Borisov 		return PTR_ERR(task);
318297f4dd09SNikolay Borisov 	}
318397f4dd09SNikolay Borisov 
318497f4dd09SNikolay Borisov 	return 0;
318597f4dd09SNikolay Borisov }
318697f4dd09SNikolay Borisov 
318744c0ca21SBoris Burkov /*
31888cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
31898cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
31908cd29088SBoris Burkov  * code paths.
31918cd29088SBoris Burkov  */
31928cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
31938cd29088SBoris Burkov {
31948cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
31958b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
31968cd29088SBoris Burkov }
31978cd29088SBoris Burkov 
31988cd29088SBoris Burkov /*
319944c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
320044c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
320144c0ca21SBoris Burkov  */
320244c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
320344c0ca21SBoris Burkov {
320444c0ca21SBoris Burkov 	int ret;
320594846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
32068b228324SBoris Burkov 	bool clear_free_space_tree = false;
32078b228324SBoris Burkov 
32088b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
32098b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32108b228324SBoris Burkov 		clear_free_space_tree = true;
32118b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
32128b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
32138b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
32148b228324SBoris Burkov 		clear_free_space_tree = true;
32158b228324SBoris Burkov 	}
32168b228324SBoris Burkov 
32178b228324SBoris Burkov 	if (clear_free_space_tree) {
32188b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
32198b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
32208b228324SBoris Burkov 		if (ret) {
32218b228324SBoris Burkov 			btrfs_warn(fs_info,
32228b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
32238b228324SBoris Burkov 			goto out;
32248b228324SBoris Burkov 		}
32258b228324SBoris Burkov 	}
322644c0ca21SBoris Burkov 
32278d488a8cSFilipe Manana 	/*
32288d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
32298d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3230fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
32318d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
32328d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
32338d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
32348d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
32358d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
32368d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
32378d488a8cSFilipe Manana 	 */
32388d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
32398d488a8cSFilipe Manana 	if (ret)
32408d488a8cSFilipe Manana 		goto out;
32418d488a8cSFilipe Manana 
324244c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
324344c0ca21SBoris Burkov 	if (ret)
324444c0ca21SBoris Burkov 		goto out;
324544c0ca21SBoris Burkov 
32468f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
32478f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
32488f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
32498f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
32508f1c21d7SBoris Burkov 		goto out;
32518f1c21d7SBoris Burkov 	}
32528f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
32538f1c21d7SBoris Burkov 
325444c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
32557eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
325644c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
325744c0ca21SBoris Burkov 	if (ret < 0) {
325844c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
325944c0ca21SBoris Burkov 		goto out;
326044c0ca21SBoris Burkov 	}
326144c0ca21SBoris Burkov 
32625011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
32635011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32645011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
32655011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
32665011139aSBoris Burkov 		if (ret) {
32675011139aSBoris Burkov 			btrfs_warn(fs_info,
32685011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
32695011139aSBoris Burkov 			goto out;
32705011139aSBoris Burkov 		}
32715011139aSBoris Burkov 	}
32725011139aSBoris Burkov 
327394846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
327494846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
327594846229SBoris Burkov 		if (ret)
327694846229SBoris Burkov 			goto out;
327794846229SBoris Burkov 	}
327894846229SBoris Burkov 
327944c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
328044c0ca21SBoris Burkov 	if (ret)
328144c0ca21SBoris Burkov 		goto out;
328244c0ca21SBoris Burkov 
328344c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
328444c0ca21SBoris Burkov 	if (ret) {
328544c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
328644c0ca21SBoris Burkov 		goto out;
328744c0ca21SBoris Burkov 	}
328844c0ca21SBoris Burkov 
328944c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
329044c0ca21SBoris Burkov 
329144c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
329244c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
329344c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
329444c0ca21SBoris Burkov 		if (ret) {
329544c0ca21SBoris Burkov 			btrfs_warn(fs_info,
329644c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
329744c0ca21SBoris Burkov 			goto out;
329844c0ca21SBoris Burkov 		}
329944c0ca21SBoris Burkov 	}
330044c0ca21SBoris Burkov 
330144c0ca21SBoris Burkov out:
330244c0ca21SBoris Burkov 	return ret;
330344c0ca21SBoris Burkov }
330444c0ca21SBoris Burkov 
3305d7f67ac9SQu Wenruo /*
3306d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
3307d7f67ac9SQu Wenruo  *
3308d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
3309d7f67ac9SQu Wenruo  * feature dependencies).
3310d7f67ac9SQu Wenruo  *
3311d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
3312d7f67ac9SQu Wenruo  * btrfs_validate_super().
3313d7f67ac9SQu Wenruo  *
3314d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3315d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3316d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3317d7f67ac9SQu Wenruo  */
3318d7f67ac9SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, struct super_block *sb)
3319d7f67ac9SQu Wenruo {
3320d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3321d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3322d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3323d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3324d7f67ac9SQu Wenruo 
3325d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3326d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3327d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3328d7f67ac9SQu Wenruo 		    incompat);
3329d7f67ac9SQu Wenruo 		return -EINVAL;
3330d7f67ac9SQu Wenruo 	}
3331d7f67ac9SQu Wenruo 
3332d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3333d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3334d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3335d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3336d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3337d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3338d7f67ac9SQu Wenruo 		return -EINVAL;
3339d7f67ac9SQu Wenruo 	}
3340d7f67ac9SQu Wenruo 
3341d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3342d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3343d7f67ac9SQu Wenruo 
3344d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3345d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3346d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3347d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3348d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3349d7f67ac9SQu Wenruo 
3350d7f67ac9SQu Wenruo 	/*
3351d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3352d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3353d7f67ac9SQu Wenruo 	 */
3354d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3355d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3356d7f67ac9SQu Wenruo 
3357d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && !sb_rdonly(sb)) {
3358d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3359d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3360d7f67ac9SQu Wenruo 		       compat_ro);
3361d7f67ac9SQu Wenruo 		return -EINVAL;
3362d7f67ac9SQu Wenruo 	}
3363d7f67ac9SQu Wenruo 
3364d7f67ac9SQu Wenruo 	/*
3365d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3366d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3367d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3368d7f67ac9SQu Wenruo 	 */
3369d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3370d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3371d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3372d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3373d7f67ac9SQu Wenruo 			  compat_ro);
3374d7f67ac9SQu Wenruo 		return -EINVAL;
3375d7f67ac9SQu Wenruo 	}
3376d7f67ac9SQu Wenruo 
3377d7f67ac9SQu Wenruo 	/*
3378d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3379d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3380d7f67ac9SQu Wenruo 	 */
3381d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3382d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3383d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3384d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3385d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3386d7f67ac9SQu Wenruo 		return -EINVAL;
3387d7f67ac9SQu Wenruo 	}
3388d7f67ac9SQu Wenruo 
3389d7f67ac9SQu Wenruo 	/*
3390d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3391d7f67ac9SQu Wenruo 	 *
3392d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3393d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3394d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3395d7f67ac9SQu Wenruo 	 */
3396d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3397d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3398d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3399d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3400d7f67ac9SQu Wenruo 		return -EINVAL;
3401d7f67ac9SQu Wenruo 	}
3402d7f67ac9SQu Wenruo 
3403d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3404d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3405d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3406d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3407d7f67ac9SQu Wenruo 
3408d7f67ac9SQu Wenruo 	return 0;
3409d7f67ac9SQu Wenruo }
3410d7f67ac9SQu Wenruo 
3411ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3412ae18c37aSJosef Bacik 		      char *options)
3413ae18c37aSJosef Bacik {
3414ae18c37aSJosef Bacik 	u32 sectorsize;
3415ae18c37aSJosef Bacik 	u32 nodesize;
3416ae18c37aSJosef Bacik 	u32 stripesize;
3417ae18c37aSJosef Bacik 	u64 generation;
3418ae18c37aSJosef Bacik 	u64 features;
3419ae18c37aSJosef Bacik 	u16 csum_type;
3420ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3421ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3422ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3423ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3424ae18c37aSJosef Bacik 	int ret;
3425ae18c37aSJosef Bacik 	int err = -EINVAL;
3426ae18c37aSJosef Bacik 	int level;
3427ae18c37aSJosef Bacik 
34288260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
342953b381b3SDavid Woodhouse 	if (ret) {
343083c8266aSDavid Sterba 		err = ret;
3431ae18c37aSJosef Bacik 		goto fail;
343253b381b3SDavid Woodhouse 	}
343353b381b3SDavid Woodhouse 
3434ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3435ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3436ae18c37aSJosef Bacik 				     GFP_KERNEL);
3437ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3438ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3439ae18c37aSJosef Bacik 				      GFP_KERNEL);
3440ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3441ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3442ae18c37aSJosef Bacik 		err = -ENOMEM;
3443c75e8394SJosef Bacik 		goto fail;
3444ae18c37aSJosef Bacik 	}
3445ae18c37aSJosef Bacik 
3446ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3447ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3448ae18c37aSJosef Bacik 		err = -ENOMEM;
3449c75e8394SJosef Bacik 		goto fail;
3450ae18c37aSJosef Bacik 	}
3451ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3452ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3453ae18c37aSJosef Bacik 
3454d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
34551104a885SDavid Sterba 
34561104a885SDavid Sterba 	/*
34571104a885SDavid Sterba 	 * Read super block and check the signature bytes only
34581104a885SDavid Sterba 	 */
3459d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
34608f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
34618f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
346216cdcec7SMiao Xie 		goto fail_alloc;
346320b45077SDave Young 	}
346439279cc3SChris Mason 
34651104a885SDavid Sterba 	/*
3466260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
34678dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
34688dc3f22cSJohannes Thumshirn 	 */
34698f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
347051bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
34718dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
347251bce6c9SJohannes Thumshirn 			  csum_type);
34738dc3f22cSJohannes Thumshirn 		err = -EINVAL;
34748f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
34758dc3f22cSJohannes Thumshirn 		goto fail_alloc;
34768dc3f22cSJohannes Thumshirn 	}
34778dc3f22cSJohannes Thumshirn 
347883c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
347983c68bbcSSu Yue 
34806d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
34816d97c6e3SJohannes Thumshirn 	if (ret) {
34826d97c6e3SJohannes Thumshirn 		err = ret;
34838f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
34846d97c6e3SJohannes Thumshirn 		goto fail_alloc;
34856d97c6e3SJohannes Thumshirn 	}
34866d97c6e3SJohannes Thumshirn 
34878dc3f22cSJohannes Thumshirn 	/*
34881104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
34891104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
34901104a885SDavid Sterba 	 */
34913d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
349205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
34931104a885SDavid Sterba 		err = -EINVAL;
34948f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3495141386e1SJosef Bacik 		goto fail_alloc;
34961104a885SDavid Sterba 	}
34971104a885SDavid Sterba 
34981104a885SDavid Sterba 	/*
34991104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
35001104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
35011104a885SDavid Sterba 	 * the whole block of INFO_SIZE
35021104a885SDavid Sterba 	 */
35038f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
35048f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
35055f39d397SChris Mason 
3506fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3507fbc6feaeSNikolay Borisov 
35080b86a832SChris Mason 
3509fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3510fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3511fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3512fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3513fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3514fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3515fbc6feaeSNikolay Borisov 	}
3516fbc6feaeSNikolay Borisov 
3517fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3518fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3519de37aa51SNikolay Borisov 
3520069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
35211104a885SDavid Sterba 	if (ret) {
352205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
35231104a885SDavid Sterba 		err = -EINVAL;
3524141386e1SJosef Bacik 		goto fail_alloc;
35251104a885SDavid Sterba 	}
35261104a885SDavid Sterba 
35270f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3528141386e1SJosef Bacik 		goto fail_alloc;
35290f7d52f4SChris Mason 
3530acce952bSliubo 	/* check FS state, whether FS is broken. */
353187533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
353287533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3533acce952bSliubo 
353475e7cb7fSLiu Bo 	/*
353575e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
353675e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
353775e7cb7fSLiu Bo 	 */
353875e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
353975e7cb7fSLiu Bo 
35406f93e834SAnand Jain 
35416f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
35426f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
35436f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
35446f93e834SAnand Jain 	stripesize = sectorsize;
35456f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
35466f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
35476f93e834SAnand Jain 
35486f93e834SAnand Jain 	fs_info->nodesize = nodesize;
35496f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
35506f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
35516f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
35526f93e834SAnand Jain 	fs_info->stripesize = stripesize;
35536f93e834SAnand Jain 
35542ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
35552b82032cSYan Zheng 	if (ret) {
35562b82032cSYan Zheng 		err = ret;
3557141386e1SJosef Bacik 		goto fail_alloc;
35582b82032cSYan Zheng 	}
3559dfe25020SChris Mason 
3560d7f67ac9SQu Wenruo 	ret = btrfs_check_features(fs_info, sb);
3561d7f67ac9SQu Wenruo 	if (ret < 0) {
3562d7f67ac9SQu Wenruo 		err = ret;
3563141386e1SJosef Bacik 		goto fail_alloc;
3564f2b636e8SJosef Bacik 	}
3565f2b636e8SJosef Bacik 
35668481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
35678481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
35688481dd80SQu Wenruo 
35699f73f1aeSQu Wenruo 		/*
35709f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
35719f73f1aeSQu Wenruo 		 * going to be deprecated.
35729f73f1aeSQu Wenruo 		 *
35739f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
35749f73f1aeSQu Wenruo 		 */
35759f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
35769f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
35779f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
35789f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
35799f73f1aeSQu Wenruo 
358095ea0486SQu Wenruo 		btrfs_warn(fs_info,
358195ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
35820bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
35838481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
35848481dd80SQu Wenruo 		if (!subpage_info)
35858481dd80SQu Wenruo 			goto fail_alloc;
35868481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
35878481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3588c8050b3bSQu Wenruo 	}
35890bb3eb3eSQu Wenruo 
3590d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
35912a458198SEric Sandeen 	if (ret) {
35922a458198SEric Sandeen 		err = ret;
35930dc3b84aSJosef Bacik 		goto fail_sb_buffer;
35940dc3b84aSJosef Bacik 	}
35954543df7eSChris Mason 
35969e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
35979e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
35984575c9ccSChris Mason 
3599a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3600a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3601de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3602db94535dSChris Mason 
3603925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
36046bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3605925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
360684eed90fSChris Mason 	if (ret) {
360705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
36085d4f98a2SYan Zheng 		goto fail_sb_buffer;
360984eed90fSChris Mason 	}
36100b86a832SChris Mason 
361184234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3612581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3613bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3614bd676446SJosef Bacik 			      generation, level);
3615bd676446SJosef Bacik 	if (ret) {
361605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3617af31f5e5SChris Mason 		goto fail_tree_roots;
361883121942SDavid Woodhouse 	}
36190b86a832SChris Mason 
3620e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3621c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3622c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3623e17cade2SChris Mason 
36245b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
36252b82032cSYan Zheng 	if (ret) {
362605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3627af31f5e5SChris Mason 		goto fail_tree_roots;
36282b82032cSYan Zheng 	}
36290b86a832SChris Mason 
36308dabb742SStefan Behrens 	/*
3631bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3632bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3633bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
36341a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3635bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
36368dabb742SStefan Behrens 	 */
3637bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3638d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
363905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3640a6b0d5c8SChris Mason 		goto fail_tree_roots;
3641a6b0d5c8SChris Mason 	}
3642a6b0d5c8SChris Mason 
3643b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
36444bbcaa64SEric Sandeen 	if (ret)
3645b8522a1eSNikolay Borisov 		goto fail_tree_roots;
36468929ecfaSYan, Zheng 
364775ec1db8SJosef Bacik 	/*
364873651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
364973651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
365073651042SNaohiro Aota 	 * zoned incompat feature flag set.
365173651042SNaohiro Aota 	 */
365273651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
365373651042SNaohiro Aota 	if (ret) {
365473651042SNaohiro Aota 		btrfs_err(fs_info,
365573651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
365673651042SNaohiro Aota 			  ret);
365773651042SNaohiro Aota 		goto fail_block_groups;
365873651042SNaohiro Aota 	}
365973651042SNaohiro Aota 
366073651042SNaohiro Aota 	/*
366175ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
366275ec1db8SJosef Bacik 	 * check the generation here so we can set the
366375ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
366475ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
366575ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
366675ec1db8SJosef Bacik 	 * even though it was perfectly fine.
366775ec1db8SJosef Bacik 	 */
366875ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
366975ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
367075ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
367175ec1db8SJosef Bacik 
3672cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3673cf90d884SQu Wenruo 	if (ret) {
3674cf90d884SQu Wenruo 		btrfs_err(fs_info,
3675cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3676cf90d884SQu Wenruo 			  ret);
3677cf90d884SQu Wenruo 		goto fail_block_groups;
3678cf90d884SQu Wenruo 	}
367968310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
368068310a5eSIlya Dryomov 	if (ret) {
368105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
368268310a5eSIlya Dryomov 		goto fail_block_groups;
368368310a5eSIlya Dryomov 	}
368468310a5eSIlya Dryomov 
3685733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3686733f4fbbSStefan Behrens 	if (ret) {
368705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3688733f4fbbSStefan Behrens 		goto fail_block_groups;
3689733f4fbbSStefan Behrens 	}
3690733f4fbbSStefan Behrens 
36918dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
36928dabb742SStefan Behrens 	if (ret) {
369305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
36948dabb742SStefan Behrens 		goto fail_block_groups;
36958dabb742SStefan Behrens 	}
36968dabb742SStefan Behrens 
3697b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3698b70f5097SNaohiro Aota 	if (ret) {
3699b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3700b70f5097SNaohiro Aota 			  ret);
3701b70f5097SNaohiro Aota 		goto fail_block_groups;
3702b70f5097SNaohiro Aota 	}
3703b70f5097SNaohiro Aota 
3704c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3705b7c35e81SAnand Jain 	if (ret) {
370605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
370705135f59SDavid Sterba 				ret);
3708b7c35e81SAnand Jain 		goto fail_block_groups;
3709b7c35e81SAnand Jain 	}
3710b7c35e81SAnand Jain 
371196f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
37125ac1d209SJeff Mahoney 	if (ret) {
371305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3714b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
37155ac1d209SJeff Mahoney 	}
37165ac1d209SJeff Mahoney 
3717c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3718c59021f8Sliubo 	if (ret) {
371905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
37202365dd3cSAnand Jain 		goto fail_sysfs;
3721c59021f8Sliubo 	}
3722c59021f8Sliubo 
37235b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
37241b1d1f66SJosef Bacik 	if (ret) {
372505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
37262365dd3cSAnand Jain 		goto fail_sysfs;
37271b1d1f66SJosef Bacik 	}
37284330e183SQu Wenruo 
372916beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
373016beac87SNaohiro Aota 
37315c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
37325c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
373305135f59SDavid Sterba 		btrfs_warn(fs_info,
373452042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
37352365dd3cSAnand Jain 		goto fail_sysfs;
3736292fd7fcSStefan Behrens 	}
37379078a3e1SChris Mason 
373833c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3739a74a4b97SChris Mason 					       "btrfs-cleaner");
374057506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
37412365dd3cSAnand Jain 		goto fail_sysfs;
3742a74a4b97SChris Mason 
3743a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3744a74a4b97SChris Mason 						   tree_root,
3745a74a4b97SChris Mason 						   "btrfs-transaction");
374657506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
37473f157a2fSChris Mason 		goto fail_cleaner;
3748a74a4b97SChris Mason 
3749583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3750c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3751583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3752c289811cSChris Mason 	}
3753c289811cSChris Mason 
3754572d9ab7SDavid Sterba 	/*
375563a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
375663a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
375763a7cb13SDavid Sterba 	 * nodiscard for the same mount.
375863a7cb13SDavid Sterba 	 */
375963a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
376063a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
376163a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
376263a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
376363a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
376463a7cb13SDavid Sterba 				   "auto enabling async discard");
376563a7cb13SDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, NODISCARD);
376663a7cb13SDavid Sterba 	}
376763a7cb13SDavid Sterba 
376821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
37690b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
37702ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
37710b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3772cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
377321adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
377421adbd5cSStefan Behrens 		if (ret)
377505135f59SDavid Sterba 			btrfs_warn(fs_info,
377605135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
377705135f59SDavid Sterba 				ret);
377821adbd5cSStefan Behrens 	}
377921adbd5cSStefan Behrens #endif
3780bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3781bcef60f2SArne Jansen 	if (ret)
3782bcef60f2SArne Jansen 		goto fail_trans_kthread;
378321adbd5cSStefan Behrens 
3784fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3785fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3786fd708b81SJosef Bacik 
378796da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
378896da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
37890b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3790e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
379163443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
379279787eaaSJeff Mahoney 		if (ret) {
379363443bf5SEric Sandeen 			err = ret;
379428c16cbbSWang Shilong 			goto fail_qgroup;
3795e556ce2cSYan Zheng 		}
3796e02119d5SChris Mason 	}
37971a40e23bSZheng Yan 
379856e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
37993140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
38003140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3801f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3802315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3803bcef60f2SArne Jansen 		goto fail_qgroup;
38043140c9a3SDan Carpenter 	}
3805c289811cSChris Mason 
3806bc98a42cSDavid Howells 	if (sb_rdonly(sb))
38078cd29088SBoris Burkov 		goto clear_oneshot;
38082b6ba629SIlya Dryomov 
380944c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
38102b6ba629SIlya Dryomov 	if (ret) {
38116bccf3abSJeff Mahoney 		close_ctree(fs_info);
38122b6ba629SIlya Dryomov 		return ret;
3813e3acc2a6SJosef Bacik 	}
3814b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3815b382a324SJan Schmidt 
381644c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
381744c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
381844c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
381905135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
382070f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
382170f80175SStefan Behrens 		if (ret) {
382205135f59SDavid Sterba 			btrfs_warn(fs_info,
382305135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
38246bccf3abSJeff Mahoney 			close_ctree(fs_info);
382570f80175SStefan Behrens 			return ret;
382670f80175SStefan Behrens 		}
3827f7a81ea4SStefan Behrens 	}
382894846229SBoris Burkov 
3829afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
383047ab2a6cSJosef Bacik 
3831b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3832b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3833b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3834b4be6aefSJosef Bacik 
38358cd29088SBoris Burkov clear_oneshot:
38368cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3837ad2b2c80SAl Viro 	return 0;
383839279cc3SChris Mason 
3839bcef60f2SArne Jansen fail_qgroup:
3840bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
38417c2ca468SChris Mason fail_trans_kthread:
38427c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
38432ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3844faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
38453f157a2fSChris Mason fail_cleaner:
3846a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
38477c2ca468SChris Mason 
38487c2ca468SChris Mason 	/*
38497c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
38507c2ca468SChris Mason 	 * kthreads
38517c2ca468SChris Mason 	 */
38527c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
38537c2ca468SChris Mason 
38542365dd3cSAnand Jain fail_sysfs:
38556618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
38562365dd3cSAnand Jain 
3857b7c35e81SAnand Jain fail_fsdev_sysfs:
3858b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3859b7c35e81SAnand Jain 
38601b1d1f66SJosef Bacik fail_block_groups:
386154067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3862af31f5e5SChris Mason 
3863af31f5e5SChris Mason fail_tree_roots:
38649e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
38659e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
38664273eaffSAnand Jain 	free_root_pointers(fs_info, true);
38672b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3868af31f5e5SChris Mason 
386939279cc3SChris Mason fail_sb_buffer:
38707abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
38715cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
387216cdcec7SMiao Xie fail_alloc:
3873586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3874586e46e2SIlya Dryomov 
38754543df7eSChris Mason 	iput(fs_info->btree_inode);
38767e662854SQinghuang Feng fail:
3877586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3878ad2b2c80SAl Viro 	return err;
3879eb60ceacSChris Mason }
3880663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3881eb60ceacSChris Mason 
3882314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3883f2984462SChris Mason {
3884314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3885314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3886314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3887314b6dd0SJohannes Thumshirn 	struct page *page;
3888442a4f63SStefan Behrens 
3889314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3890314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3891314b6dd0SJohannes Thumshirn 
3892314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3893fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3894314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3895314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3896314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3897314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3898314b6dd0SJohannes Thumshirn 			SetPageError(page);
3899314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3900314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3901314b6dd0SJohannes Thumshirn 		} else {
3902314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3903f2984462SChris Mason 		}
3904314b6dd0SJohannes Thumshirn 
3905314b6dd0SJohannes Thumshirn 		put_page(page);
3906314b6dd0SJohannes Thumshirn 		unlock_page(page);
3907314b6dd0SJohannes Thumshirn 	}
3908314b6dd0SJohannes Thumshirn 
3909314b6dd0SJohannes Thumshirn 	bio_put(bio);
3910f2984462SChris Mason }
3911f2984462SChris Mason 
39128f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3913a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
391429c36d72SAnand Jain {
391529c36d72SAnand Jain 	struct btrfs_super_block *super;
39168f32380dSJohannes Thumshirn 	struct page *page;
391712659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
39188f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
391912659251SNaohiro Aota 	int ret;
392029c36d72SAnand Jain 
392112659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
392212659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
392312659251SNaohiro Aota 	if (ret == -ENOENT)
392412659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
392512659251SNaohiro Aota 	else if (ret)
392612659251SNaohiro Aota 		return ERR_PTR(ret);
392712659251SNaohiro Aota 
3928cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
39298f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
393029c36d72SAnand Jain 
3931a05d3c91SQu Wenruo 	if (drop_cache) {
3932a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3933a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3934a05d3c91SQu Wenruo 
3935a05d3c91SQu Wenruo 		/*
3936a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3937a05d3c91SQu Wenruo 		 * always read from the device.
3938a05d3c91SQu Wenruo 		 */
3939a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3940a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3941a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3942a05d3c91SQu Wenruo 	}
3943a05d3c91SQu Wenruo 
39448f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
39458f32380dSJohannes Thumshirn 	if (IS_ERR(page))
39468f32380dSJohannes Thumshirn 		return ERR_CAST(page);
394729c36d72SAnand Jain 
39488f32380dSJohannes Thumshirn 	super = page_address(page);
394996c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
395096c2e067SAnand Jain 		btrfs_release_disk_super(super);
395196c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
395296c2e067SAnand Jain 	}
395396c2e067SAnand Jain 
395412659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
39558f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
39568f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
395729c36d72SAnand Jain 	}
395829c36d72SAnand Jain 
39598f32380dSJohannes Thumshirn 	return super;
396029c36d72SAnand Jain }
396129c36d72SAnand Jain 
396229c36d72SAnand Jain 
39638f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3964a512bbf8SYan Zheng {
39658f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3966a512bbf8SYan Zheng 	int i;
3967a512bbf8SYan Zheng 	u64 transid = 0;
3968a512bbf8SYan Zheng 
3969a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3970a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3971a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3972a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3973a512bbf8SYan Zheng 	 */
3974a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3975a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
39768f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3977a512bbf8SYan Zheng 			continue;
3978a512bbf8SYan Zheng 
3979a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
39808f32380dSJohannes Thumshirn 			if (latest)
39818f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
39828f32380dSJohannes Thumshirn 
39838f32380dSJohannes Thumshirn 			latest = super;
3984a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3985a512bbf8SYan Zheng 		}
3986a512bbf8SYan Zheng 	}
398792fc03fbSAnand Jain 
39888f32380dSJohannes Thumshirn 	return super;
3989a512bbf8SYan Zheng }
3990a512bbf8SYan Zheng 
39914eedeb75SHisashi Hifumi /*
3992abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3993314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
39944eedeb75SHisashi Hifumi  *
3995abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3996abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3997abbb3b8eSDavid Sterba  * same for write and wait phases.
39984eedeb75SHisashi Hifumi  *
3999314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
40004eedeb75SHisashi Hifumi  */
4001a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
4002abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
4003a512bbf8SYan Zheng {
4004d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
4005314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
4006d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
4007a512bbf8SYan Zheng 	int i;
4008a512bbf8SYan Zheng 	int errors = 0;
400912659251SNaohiro Aota 	int ret;
401012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
4011a512bbf8SYan Zheng 
4012a512bbf8SYan Zheng 	if (max_mirrors == 0)
4013a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4014a512bbf8SYan Zheng 
4015d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
4016d5178578SJohannes Thumshirn 
4017a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
4018314b6dd0SJohannes Thumshirn 		struct page *page;
4019314b6dd0SJohannes Thumshirn 		struct bio *bio;
4020314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
4021314b6dd0SJohannes Thumshirn 
402212659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
402312659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
402412659251SNaohiro Aota 		if (ret == -ENOENT) {
402512659251SNaohiro Aota 			continue;
402612659251SNaohiro Aota 		} else if (ret < 0) {
402712659251SNaohiro Aota 			btrfs_err(device->fs_info,
402812659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
402912659251SNaohiro Aota 				i);
403012659251SNaohiro Aota 			errors++;
403112659251SNaohiro Aota 			continue;
403212659251SNaohiro Aota 		}
4033935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4034935e5cc9SMiao Xie 		    device->commit_total_bytes)
4035a512bbf8SYan Zheng 			break;
4036a512bbf8SYan Zheng 
403712659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
4038a512bbf8SYan Zheng 
4039fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
4040fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
4041fd08001fSEric Biggers 				    sb->csum);
4042a512bbf8SYan Zheng 
4043314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
4044314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
4045314b6dd0SJohannes Thumshirn 		if (!page) {
4046fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
4047314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
4048f14d104dSDavid Sterba 			    bytenr);
4049634554dcSJosef Bacik 			errors++;
4050634554dcSJosef Bacik 			continue;
4051634554dcSJosef Bacik 		}
4052634554dcSJosef Bacik 
4053314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
4054314b6dd0SJohannes Thumshirn 		get_page(page);
4055a512bbf8SYan Zheng 
4056314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
4057314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
4058a512bbf8SYan Zheng 
4059387125fcSChris Mason 		/*
4060314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
4061314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
4062314b6dd0SJohannes Thumshirn 		 * checking.
4063387125fcSChris Mason 		 */
406407888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
406507888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
406607888c66SChristoph Hellwig 				GFP_NOFS);
4067314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
4068314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
4069314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
4070314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
4071314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
4072314b6dd0SJohannes Thumshirn 
4073314b6dd0SJohannes Thumshirn 		/*
4074314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
4075314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
4076314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
4077314b6dd0SJohannes Thumshirn 		 */
40781b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
4079314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
4080314b6dd0SJohannes Thumshirn 
408158ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
408258ff51f1SChristoph Hellwig 		submit_bio(bio);
40838376d9e1SNaohiro Aota 
40848376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
40858376d9e1SNaohiro Aota 			errors++;
4086a512bbf8SYan Zheng 	}
4087a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
4088a512bbf8SYan Zheng }
4089a512bbf8SYan Zheng 
4090387125fcSChris Mason /*
4091abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
4092abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
4093abbb3b8eSDavid Sterba  *
4094314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
4095abbb3b8eSDavid Sterba  * date.
4096abbb3b8eSDavid Sterba  */
4097abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4098abbb3b8eSDavid Sterba {
4099abbb3b8eSDavid Sterba 	int i;
4100abbb3b8eSDavid Sterba 	int errors = 0;
4101b6a535faSHoward McLauchlan 	bool primary_failed = false;
410212659251SNaohiro Aota 	int ret;
4103abbb3b8eSDavid Sterba 	u64 bytenr;
4104abbb3b8eSDavid Sterba 
4105abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
4106abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4107abbb3b8eSDavid Sterba 
4108abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
4109314b6dd0SJohannes Thumshirn 		struct page *page;
4110314b6dd0SJohannes Thumshirn 
411112659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
411212659251SNaohiro Aota 		if (ret == -ENOENT) {
411312659251SNaohiro Aota 			break;
411412659251SNaohiro Aota 		} else if (ret < 0) {
411512659251SNaohiro Aota 			errors++;
411612659251SNaohiro Aota 			if (i == 0)
411712659251SNaohiro Aota 				primary_failed = true;
411812659251SNaohiro Aota 			continue;
411912659251SNaohiro Aota 		}
4120abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4121abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
4122abbb3b8eSDavid Sterba 			break;
4123abbb3b8eSDavid Sterba 
4124314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
4125314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
4126314b6dd0SJohannes Thumshirn 		if (!page) {
4127abbb3b8eSDavid Sterba 			errors++;
4128b6a535faSHoward McLauchlan 			if (i == 0)
4129b6a535faSHoward McLauchlan 				primary_failed = true;
4130abbb3b8eSDavid Sterba 			continue;
4131abbb3b8eSDavid Sterba 		}
4132314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4133314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4134314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4135abbb3b8eSDavid Sterba 			errors++;
4136b6a535faSHoward McLauchlan 			if (i == 0)
4137b6a535faSHoward McLauchlan 				primary_failed = true;
4138b6a535faSHoward McLauchlan 		}
4139abbb3b8eSDavid Sterba 
4140314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4141314b6dd0SJohannes Thumshirn 		put_page(page);
4142abbb3b8eSDavid Sterba 
4143314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4144314b6dd0SJohannes Thumshirn 		put_page(page);
4145abbb3b8eSDavid Sterba 	}
4146abbb3b8eSDavid Sterba 
4147b6a535faSHoward McLauchlan 	/* log error, force error return */
4148b6a535faSHoward McLauchlan 	if (primary_failed) {
4149b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4150b6a535faSHoward McLauchlan 			  device->devid);
4151b6a535faSHoward McLauchlan 		return -1;
4152b6a535faSHoward McLauchlan 	}
4153b6a535faSHoward McLauchlan 
4154abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4155abbb3b8eSDavid Sterba }
4156abbb3b8eSDavid Sterba 
4157abbb3b8eSDavid Sterba /*
4158387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4159387125fcSChris Mason  * for the barrier when it is done
4160387125fcSChris Mason  */
41614246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4162387125fcSChris Mason {
4163f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
4164387125fcSChris Mason 	complete(bio->bi_private);
4165387125fcSChris Mason }
4166387125fcSChris Mason 
4167387125fcSChris Mason /*
41684fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
41694fc6441aSAnand Jain  * done in the waiting counterpart.
4170387125fcSChris Mason  */
41714fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4172387125fcSChris Mason {
4173f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
4174387125fcSChris Mason 
4175a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4176a91cf0ffSWang Yugui 	/*
4177a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4178a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4179a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4180a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4181a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4182a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4183a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4184a91cf0ffSWang Yugui 	 * non-debug builds.
4185a91cf0ffSWang Yugui 	 */
418608e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
41874fc6441aSAnand Jain 		return;
4188a91cf0ffSWang Yugui #endif
4189387125fcSChris Mason 
4190f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
4191f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4192387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
4193387125fcSChris Mason 	init_completion(&device->flush_wait);
4194387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4195387125fcSChris Mason 
419658ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
419758ff51f1SChristoph Hellwig 	submit_bio(bio);
41981c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
41994fc6441aSAnand Jain }
4200387125fcSChris Mason 
42014fc6441aSAnand Jain /*
42024fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
42034fc6441aSAnand Jain  */
42048c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
42054fc6441aSAnand Jain {
4206f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
42074fc6441aSAnand Jain 
42081c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
420958efbc9fSOmar Sandoval 		return BLK_STS_OK;
42104fc6441aSAnand Jain 
42111c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
42122980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
42134fc6441aSAnand Jain 
42148c27cb35SLinus Torvalds 	return bio->bi_status;
4215387125fcSChris Mason }
4216387125fcSChris Mason 
4217d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4218401b41e5SAnand Jain {
42196528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4220401b41e5SAnand Jain 		return -EIO;
4221387125fcSChris Mason 	return 0;
4222387125fcSChris Mason }
4223387125fcSChris Mason 
4224387125fcSChris Mason /*
4225387125fcSChris Mason  * send an empty flush down to each device in parallel,
4226387125fcSChris Mason  * then wait for them
4227387125fcSChris Mason  */
4228387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4229387125fcSChris Mason {
4230387125fcSChris Mason 	struct list_head *head;
4231387125fcSChris Mason 	struct btrfs_device *dev;
42325af3e8ccSStefan Behrens 	int errors_wait = 0;
42334e4cbee9SChristoph Hellwig 	blk_status_t ret;
4234387125fcSChris Mason 
42351538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4236387125fcSChris Mason 	/* send down all the barriers */
4237387125fcSChris Mason 	head = &info->fs_devices->devices;
42381538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4239e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4240f88ba6a2SHidetoshi Seto 			continue;
4241cea7c8bfSAnand Jain 		if (!dev->bdev)
4242387125fcSChris Mason 			continue;
4243e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4244ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4245387125fcSChris Mason 			continue;
4246387125fcSChris Mason 
42474fc6441aSAnand Jain 		write_dev_flush(dev);
424858efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4249387125fcSChris Mason 	}
4250387125fcSChris Mason 
4251387125fcSChris Mason 	/* wait for all the barriers */
42521538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4253e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4254f88ba6a2SHidetoshi Seto 			continue;
4255387125fcSChris Mason 		if (!dev->bdev) {
42565af3e8ccSStefan Behrens 			errors_wait++;
4257387125fcSChris Mason 			continue;
4258387125fcSChris Mason 		}
4259e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4260ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4261387125fcSChris Mason 			continue;
4262387125fcSChris Mason 
42634fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4264401b41e5SAnand Jain 		if (ret) {
4265401b41e5SAnand Jain 			dev->last_flush_error = ret;
426666b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
426766b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
42685af3e8ccSStefan Behrens 			errors_wait++;
4269387125fcSChris Mason 		}
4270401b41e5SAnand Jain 	}
4271401b41e5SAnand Jain 
4272cea7c8bfSAnand Jain 	if (errors_wait) {
4273401b41e5SAnand Jain 		/*
4274401b41e5SAnand Jain 		 * At some point we need the status of all disks
4275401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4276401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4277401b41e5SAnand Jain 		 */
4278d10b82feSQu Wenruo 		return check_barrier_error(info);
4279401b41e5SAnand Jain 	}
4280387125fcSChris Mason 	return 0;
4281387125fcSChris Mason }
4282387125fcSChris Mason 
4283943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4284943c6e99SZhao Lei {
42858789f4feSZhao Lei 	int raid_type;
42868789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4287943c6e99SZhao Lei 
42888789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
42898789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
42908c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
42918789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
42928789f4feSZhao Lei 				    tolerated_failures);
4293943c6e99SZhao Lei 
42948789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
42958789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
42968789f4feSZhao Lei 			continue;
429741a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
42988789f4feSZhao Lei 			continue;
42998c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
43008789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
43018789f4feSZhao Lei 				    tolerated_failures);
43028789f4feSZhao Lei 	}
4303943c6e99SZhao Lei 
43048789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4305ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
43068789f4feSZhao Lei 		min_tolerated = 0;
43078789f4feSZhao Lei 	}
43088789f4feSZhao Lei 
43098789f4feSZhao Lei 	return min_tolerated;
4310943c6e99SZhao Lei }
4311943c6e99SZhao Lei 
4312eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4313f2984462SChris Mason {
4314e5e9a520SChris Mason 	struct list_head *head;
4315f2984462SChris Mason 	struct btrfs_device *dev;
4316a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4317f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4318f2984462SChris Mason 	int ret;
4319f2984462SChris Mason 	int do_barriers;
4320a236aed1SChris Mason 	int max_errors;
4321a236aed1SChris Mason 	int total_errors = 0;
4322a061fc8dSChris Mason 	u64 flags;
4323f2984462SChris Mason 
43240b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4325fed3b381SLiu Bo 
4326fed3b381SLiu Bo 	/*
4327fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4328fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4329fed3b381SLiu Bo 	 * been consistent on disk.
4330fed3b381SLiu Bo 	 */
4331fed3b381SLiu Bo 	if (max_mirrors == 0)
43320b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4333f2984462SChris Mason 
43340b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4335a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4336e5e9a520SChris Mason 
43370b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
43380b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
43390b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4340387125fcSChris Mason 
43415af3e8ccSStefan Behrens 	if (do_barriers) {
43420b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
43435af3e8ccSStefan Behrens 		if (ret) {
43445af3e8ccSStefan Behrens 			mutex_unlock(
43450b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
43460b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
43475af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
43485af3e8ccSStefan Behrens 			return ret;
43495af3e8ccSStefan Behrens 		}
43505af3e8ccSStefan Behrens 	}
4351387125fcSChris Mason 
43521538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4353dfe25020SChris Mason 		if (!dev->bdev) {
4354dfe25020SChris Mason 			total_errors++;
4355dfe25020SChris Mason 			continue;
4356dfe25020SChris Mason 		}
4357e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4358ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4359dfe25020SChris Mason 			continue;
4360dfe25020SChris Mason 
43612b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4362a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4363a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
43647df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4365935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4366ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4367ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4368a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4369a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4370a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4371a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
43727239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
43737239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4374a512bbf8SYan Zheng 
4375a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4376a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4377f2984462SChris Mason 
437875cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
437975cb857dSQu Wenruo 		if (ret < 0) {
438075cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
438175cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
438275cb857dSQu Wenruo 				"unexpected superblock corruption detected");
438375cb857dSQu Wenruo 			return -EUCLEAN;
438475cb857dSQu Wenruo 		}
438575cb857dSQu Wenruo 
4386abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4387a236aed1SChris Mason 		if (ret)
4388a236aed1SChris Mason 			total_errors++;
4389f2984462SChris Mason 	}
4390a236aed1SChris Mason 	if (total_errors > max_errors) {
43910b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4392d397712bSChris Mason 			  total_errors);
43930b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
439479787eaaSJeff Mahoney 
43959d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
43960b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
43970b246afaSJeff Mahoney 				      "%d errors while writing supers",
43980b246afaSJeff Mahoney 				      total_errors);
43999d565ba4SStefan Behrens 		return -EIO;
4400a236aed1SChris Mason 	}
4401f2984462SChris Mason 
4402a512bbf8SYan Zheng 	total_errors = 0;
44031538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4404dfe25020SChris Mason 		if (!dev->bdev)
4405dfe25020SChris Mason 			continue;
4406e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4407ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4408dfe25020SChris Mason 			continue;
4409dfe25020SChris Mason 
4410abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4411a512bbf8SYan Zheng 		if (ret)
44121259ab75SChris Mason 			total_errors++;
4413f2984462SChris Mason 	}
44140b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4415a236aed1SChris Mason 	if (total_errors > max_errors) {
44160b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
44170b246afaSJeff Mahoney 				      "%d errors while writing supers",
44180b246afaSJeff Mahoney 				      total_errors);
441979787eaaSJeff Mahoney 		return -EIO;
4420a236aed1SChris Mason 	}
4421f2984462SChris Mason 	return 0;
4422f2984462SChris Mason }
4423f2984462SChris Mason 
4424cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4425cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4426cb517eabSMiao Xie 				  struct btrfs_root *root)
44272619ba1fSChris Mason {
44284785e24fSJosef Bacik 	bool drop_ref = false;
44294785e24fSJosef Bacik 
4430fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4431fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4432fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4433fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
44344785e24fSJosef Bacik 		drop_ref = true;
4435fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
443676dda93cSYan, Zheng 
443784961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4438ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
44391c1ea4f7SLiu Bo 		if (root->reloc_root) {
444000246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
44411c1ea4f7SLiu Bo 			root->reloc_root = NULL;
44421c1ea4f7SLiu Bo 		}
44431c1ea4f7SLiu Bo 	}
44443321719eSLiu Bo 
44454785e24fSJosef Bacik 	if (drop_ref)
444600246528SJosef Bacik 		btrfs_put_root(root);
44472619ba1fSChris Mason }
44482619ba1fSChris Mason 
4449c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4450c146afadSYan Zheng {
4451fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4452fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4453fc7cbcd4SDavid Sterba 	int i = 0;
445465d33fd7SQu Wenruo 	int err = 0;
4455fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4456c146afadSYan Zheng 
4457c146afadSYan Zheng 	while (1) {
4458fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4459fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4460fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4461fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4462fc7cbcd4SDavid Sterba 		if (!ret) {
4463fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4464c146afadSYan Zheng 			break;
446565d33fd7SQu Wenruo 		}
4466fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
446766b4ffd1SJosef Bacik 
4468fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4469fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4470fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4471fc7cbcd4SDavid Sterba 				gang[i] = NULL;
447265d33fd7SQu Wenruo 				continue;
4473c146afadSYan Zheng 			}
4474fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4475fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4476fc7cbcd4SDavid Sterba 		}
4477fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4478fc7cbcd4SDavid Sterba 
4479fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4480fc7cbcd4SDavid Sterba 			if (!gang[i])
4481fc7cbcd4SDavid Sterba 				continue;
4482fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4483fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4484fc7cbcd4SDavid Sterba 			if (err)
4485fc7cbcd4SDavid Sterba 				break;
4486fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4487fc7cbcd4SDavid Sterba 		}
4488fc7cbcd4SDavid Sterba 		root_objectid++;
4489c146afadSYan Zheng 	}
449065d33fd7SQu Wenruo 
4491fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4492fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4493fc7cbcd4SDavid Sterba 		if (gang[i])
4494fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
449565d33fd7SQu Wenruo 	}
449665d33fd7SQu Wenruo 	return err;
4497c146afadSYan Zheng }
4498c146afadSYan Zheng 
44996bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4500c146afadSYan Zheng {
45016bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4502c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4503c146afadSYan Zheng 
45040b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45052ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45060b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
45070b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4508c71bf099SYan, Zheng 
4509c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
45100b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45110b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4512c71bf099SYan, Zheng 
45137a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
45143612b495STsutomu Itoh 	if (IS_ERR(trans))
45153612b495STsutomu Itoh 		return PTR_ERR(trans);
45163a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4517c146afadSYan Zheng }
4518c146afadSYan Zheng 
451936c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
452036c86a9eSQu Wenruo {
452136c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
452236c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
452336c86a9eSQu Wenruo 	bool found = false;
452436c86a9eSQu Wenruo 
452536c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
452636c86a9eSQu Wenruo 		return;
452736c86a9eSQu Wenruo 
452836c86a9eSQu Wenruo 	/*
452936c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
453036c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
453136c86a9eSQu Wenruo 	 */
453236c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
453336c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
453436c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
453536c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
453636c86a9eSQu Wenruo 		u64 cur = 0;
453736c86a9eSQu Wenruo 		u64 found_start;
453836c86a9eSQu Wenruo 		u64 found_end;
453936c86a9eSQu Wenruo 
454036c86a9eSQu Wenruo 		found = true;
454136c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
454236c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
454336c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
454436c86a9eSQu Wenruo 			cur = found_end + 1;
454536c86a9eSQu Wenruo 		}
454636c86a9eSQu Wenruo 		btrfs_warn(fs_info,
454736c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
454836c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
454936c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
455036c86a9eSQu Wenruo 
455136c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
455236c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
455336c86a9eSQu Wenruo 		list_del_init(&trans->list);
455436c86a9eSQu Wenruo 
455536c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
455636c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
455736c86a9eSQu Wenruo 	}
455836c86a9eSQu Wenruo 	ASSERT(!found);
455936c86a9eSQu Wenruo }
456036c86a9eSQu Wenruo 
4561b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4562eb60ceacSChris Mason {
4563c146afadSYan Zheng 	int ret;
4564e089f05cSChris Mason 
4565afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
456631e70e52SFilipe Manana 
456731e70e52SFilipe Manana 	/*
45688a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
45698a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
45708a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
45718a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
45728a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
45738a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
45748a1f1e3dSFilipe Manana 	 * return 1.
45758a1f1e3dSFilipe Manana 	 */
45768a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
45778a1f1e3dSFilipe Manana 
45788a1f1e3dSFilipe Manana 	/*
457931e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
458031e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
458131e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
458231e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
458331e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
458431e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
458531e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
458631e70e52SFilipe Manana 	 */
458731e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4588d6fd0ae2SOmar Sandoval 	/*
4589d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4590d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4591d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4592d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4593d6fd0ae2SOmar Sandoval 	 */
4594d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4595a2135011SChris Mason 
45967343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4597d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
45987343dd61SJustin Maggard 
4599803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4600803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4601803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4602803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4603803b2f54SStefan Behrens 
4604837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4605aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4606837d5b6eSIlya Dryomov 
46078dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
46088dabb742SStefan Behrens 
4609aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
46104cb5300bSChris Mason 
46114cb5300bSChris Mason 	/* wait for any defraggers to finish */
46124cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
46134cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
46144cb5300bSChris Mason 
46154cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
461626176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
46174cb5300bSChris Mason 
4618a362bb86SFilipe Manana 	/*
4619a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4620a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4621a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4622a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4623a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4624a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4625a362bb86SFilipe Manana 	 * no one else to run iputs.
4626a362bb86SFilipe Manana 	 *
4627a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4628a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4629a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4630a362bb86SFilipe Manana 	 * through some other means.
4631a362bb86SFilipe Manana 	 *
4632a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4633a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4634a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4635a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4636a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4637a362bb86SFilipe Manana 	 */
4638a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4639a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4640a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4641a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4642a362bb86SFilipe Manana 
464321c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
464457056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4645576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
464621c7e756SMiao Xie 
4647b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4648b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4649b0643e59SDennis Zhou 
4650bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4651e44163e1SJeff Mahoney 		/*
4652d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4653d6fd0ae2SOmar Sandoval 		 * unused block groups.
4654e44163e1SJeff Mahoney 		 */
46550b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4656e44163e1SJeff Mahoney 
4657f0cc2cd7SFilipe Manana 		/*
4658f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4659f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4660f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4661f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4662f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4663f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4664f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4665f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4666f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4667f0cc2cd7SFilipe Manana 		 */
4668f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4669f0cc2cd7SFilipe Manana 
46706bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4671d397712bSChris Mason 		if (ret)
467204892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4673c146afadSYan Zheng 	}
4674ed2ff2cbSChris Mason 
467584961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
46762ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4677acce952bSliubo 
4678e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4679e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
46808929ecfaSYan, Zheng 
4681e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4682afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4683f25784b3SYan Zheng 
46845958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
46855958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
46865958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
46875958253cSQu Wenruo 	}
46885958253cSQu Wenruo 
468904892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4690fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4691bcef60f2SArne Jansen 
4692963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
469304892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4694963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4695b0c68f8bSChris Mason 	}
469631153d81SYan Zheng 
46975deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
46984297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
46995deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
47004297ff84SJosef Bacik 
47016618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4702b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
47035ac1d209SJeff Mahoney 
47041a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
47051a4319ccSLiu Bo 
4706de348ee0SWang Shilong 	/*
4707de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4708de348ee0SWang Shilong 	 * submit after we stopping all workers.
4709de348ee0SWang Shilong 	 */
4710de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
471196192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
471296192499SJosef Bacik 
47130a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
471436c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
47150a31daa4SFilipe Manana 
4716afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
47174273eaffSAnand Jain 	free_root_pointers(fs_info, true);
47188c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
47199ad6b7bcSChris Mason 
47204e19443dSJosef Bacik 	/*
47214e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
47224e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
47234e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
47244e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
47254e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
47264e19443dSJosef Bacik 	 */
47274e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
47284e19443dSJosef Bacik 
472913e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4730d6bfde87SChris Mason 
473121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
47320b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
47332ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
473421adbd5cSStefan Behrens #endif
473521adbd5cSStefan Behrens 
47360b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
473768c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4738eb60ceacSChris Mason }
4739eb60ceacSChris Mason 
4740b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4741b9fab919SChris Mason 			  int atomic)
4742ccd467d6SChris Mason {
47431259ab75SChris Mason 	int ret;
4744727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
47451259ab75SChris Mason 
47460b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
47471259ab75SChris Mason 	if (!ret)
47481259ab75SChris Mason 		return ret;
47491259ab75SChris Mason 
47501259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4751b9fab919SChris Mason 				    parent_transid, atomic);
4752b9fab919SChris Mason 	if (ret == -EAGAIN)
4753b9fab919SChris Mason 		return ret;
47541259ab75SChris Mason 	return !ret;
47555f39d397SChris Mason }
47566702ed49SChris Mason 
47575f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
47585f39d397SChris Mason {
47592f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
47605f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4761b9473439SChris Mason 	int was_dirty;
4762b4ce94deSChris Mason 
476306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
476406ea65a3SJosef Bacik 	/*
476506ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
476652042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
476706ea65a3SJosef Bacik 	 * outside of the sanity tests.
476806ea65a3SJosef Bacik 	 */
4769b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
477006ea65a3SJosef Bacik 		return;
477106ea65a3SJosef Bacik #endif
477249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
47730b246afaSJeff Mahoney 	if (transid != fs_info->generation)
47745d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
47750b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
47760b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4777e2d84521SMiao Xie 	if (!was_dirty)
4778104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4779e2d84521SMiao Xie 					 buf->len,
47800b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
47811f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
478269fc6cbbSQu Wenruo 	/*
478369fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
478469fc6cbbSQu Wenruo 	 * but item data not updated.
478569fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
478669fc6cbbSQu Wenruo 	 */
478769fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4788cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4789a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
47901f21ef0aSFilipe Manana 		ASSERT(0);
47911f21ef0aSFilipe Manana 	}
47921f21ef0aSFilipe Manana #endif
4793eb60ceacSChris Mason }
4794eb60ceacSChris Mason 
47952ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4796b53d3f5dSLiu Bo 					int flush_delayed)
479735b7e476SChris Mason {
4798188de649SChris Mason 	/*
4799188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4800188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4801188de649SChris Mason 	 */
4802e2d84521SMiao Xie 	int ret;
4803d6bfde87SChris Mason 
48046933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4805d6bfde87SChris Mason 		return;
4806d6bfde87SChris Mason 
4807b53d3f5dSLiu Bo 	if (flush_delayed)
48082ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
480916cdcec7SMiao Xie 
4810d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4811d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4812d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4813e2d84521SMiao Xie 	if (ret > 0) {
48140b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
481516cdcec7SMiao Xie 	}
481616cdcec7SMiao Xie }
481716cdcec7SMiao Xie 
48182ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
481916cdcec7SMiao Xie {
48202ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
482135b7e476SChris Mason }
4822b53d3f5dSLiu Bo 
48232ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4824b53d3f5dSLiu Bo {
48252ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4826d6bfde87SChris Mason }
48276b80053dSChris Mason 
48282ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4829acce952bSliubo {
4830fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4831fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4832fe816d0fSNikolay Borisov 
48330b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
48342ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
48350b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4836acce952bSliubo 
48370b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
48380b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4839acce952bSliubo }
4840acce952bSliubo 
4841ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4842ef67963dSJosef Bacik {
4843fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4844fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4845fc7cbcd4SDavid Sterba 	int ret;
4846ef67963dSJosef Bacik 
4847fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4848fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4849fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4850fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4851fc7cbcd4SDavid Sterba 		int i;
4852ef67963dSJosef Bacik 
4853fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4854fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4855fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4856fc7cbcd4SDavid Sterba 
4857fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4858fc7cbcd4SDavid Sterba 			if (!gang[i])
4859ef67963dSJosef Bacik 				continue;
4860fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4861fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4862fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4863ef67963dSJosef Bacik 		}
4864fc7cbcd4SDavid Sterba 		root_objectid++;
4865fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4866ef67963dSJosef Bacik 	}
4867fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4868ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4869ef67963dSJosef Bacik }
4870ef67963dSJosef Bacik 
4871143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4872acce952bSliubo {
4873acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4874acce952bSliubo 
4875199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4876779880efSJosef Bacik 	/*
4877779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4878779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4879779880efSJosef Bacik 	 */
4880199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4881779880efSJosef Bacik 			    root_extent_list)
4882779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4883199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4884199c2a9cSMiao Xie }
4885199c2a9cSMiao Xie 
4886199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4887199c2a9cSMiao Xie {
4888199c2a9cSMiao Xie 	struct btrfs_root *root;
4889199c2a9cSMiao Xie 	struct list_head splice;
4890199c2a9cSMiao Xie 
4891199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4892199c2a9cSMiao Xie 
4893199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4894199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4895199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4896199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4897199c2a9cSMiao Xie 					ordered_root);
48981de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
48991de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4900199c2a9cSMiao Xie 
49012a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4902199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4903199c2a9cSMiao Xie 
49042a85d9caSLiu Bo 		cond_resched();
49052a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4906199c2a9cSMiao Xie 	}
4907199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
490874d5d229SJosef Bacik 
490974d5d229SJosef Bacik 	/*
491074d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
491174d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
491274d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
491374d5d229SJosef Bacik 	 * actually get run and error out properly.
491474d5d229SJosef Bacik 	 */
491574d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4916acce952bSliubo }
4917acce952bSliubo 
491835a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
49192ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4920acce952bSliubo {
4921acce952bSliubo 	struct rb_node *node;
4922acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4923acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4924acce952bSliubo 	int ret = 0;
4925acce952bSliubo 
4926acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4927acce952bSliubo 
4928acce952bSliubo 	spin_lock(&delayed_refs->lock);
4929d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4930cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4931b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4932acce952bSliubo 		return ret;
4933acce952bSliubo 	}
4934acce952bSliubo 
49355c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4936d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
49370e0adbcfSJosef Bacik 		struct rb_node *n;
4938e78417d1SJosef Bacik 		bool pin_bytes = false;
4939acce952bSliubo 
4940d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4941d7df2c79SJosef Bacik 				href_node);
49423069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4943b939d1abSJosef Bacik 			continue;
49443069bd26SJosef Bacik 
4945d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4946e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
49470e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
49480e0adbcfSJosef Bacik 				       ref_node);
4949d7df2c79SJosef Bacik 			ref->in_tree = 0;
4950e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
49510e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
49521d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
49531d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4954d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4955d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4956d7df2c79SJosef Bacik 		}
495754067ae9SJosef Bacik 		if (head->must_insert_reserved)
4958e78417d1SJosef Bacik 			pin_bytes = true;
495978a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4960fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4961d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4962acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4963e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4964acce952bSliubo 
4965f603bb94SNikolay Borisov 		if (pin_bytes) {
4966f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4967f603bb94SNikolay Borisov 
4968f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4969f603bb94SNikolay Borisov 			BUG_ON(!cache);
4970f603bb94SNikolay Borisov 
4971f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4972f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4973f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4974f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4975f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4976f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4977f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4978f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4979f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4980f603bb94SNikolay Borisov 
4981f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4982f603bb94SNikolay Borisov 
4983f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4984f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4985f603bb94SNikolay Borisov 		}
498631890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4987d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4988acce952bSliubo 		cond_resched();
4989acce952bSliubo 		spin_lock(&delayed_refs->lock);
4990acce952bSliubo 	}
499181f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4992acce952bSliubo 
4993acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4994acce952bSliubo 
4995acce952bSliubo 	return ret;
4996acce952bSliubo }
4997acce952bSliubo 
4998143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4999acce952bSliubo {
5000acce952bSliubo 	struct btrfs_inode *btrfs_inode;
5001acce952bSliubo 	struct list_head splice;
5002acce952bSliubo 
5003acce952bSliubo 	INIT_LIST_HEAD(&splice);
5004acce952bSliubo 
5005eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
5006eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
5007acce952bSliubo 
5008acce952bSliubo 	while (!list_empty(&splice)) {
5009fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
5010eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
5011acce952bSliubo 					       delalloc_inodes);
5012fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
5013eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
5014acce952bSliubo 
5015fe816d0fSNikolay Borisov 		/*
5016fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
5017fe816d0fSNikolay Borisov 		 * meanwhile.
5018fe816d0fSNikolay Borisov 		 */
5019fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
5020fe816d0fSNikolay Borisov 		if (inode) {
5021fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
5022fe816d0fSNikolay Borisov 			iput(inode);
5023fe816d0fSNikolay Borisov 		}
5024eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
5025acce952bSliubo 	}
5026eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
5027eb73c1b7SMiao Xie }
5028eb73c1b7SMiao Xie 
5029eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
5030eb73c1b7SMiao Xie {
5031eb73c1b7SMiao Xie 	struct btrfs_root *root;
5032eb73c1b7SMiao Xie 	struct list_head splice;
5033eb73c1b7SMiao Xie 
5034eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
5035eb73c1b7SMiao Xie 
5036eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
5037eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
5038eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
5039eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
5040eb73c1b7SMiao Xie 					 delalloc_root);
504100246528SJosef Bacik 		root = btrfs_grab_root(root);
5042eb73c1b7SMiao Xie 		BUG_ON(!root);
5043eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
5044eb73c1b7SMiao Xie 
5045eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
504600246528SJosef Bacik 		btrfs_put_root(root);
5047eb73c1b7SMiao Xie 
5048eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
5049eb73c1b7SMiao Xie 	}
5050eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
5051acce952bSliubo }
5052acce952bSliubo 
50532ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
5054acce952bSliubo 					struct extent_io_tree *dirty_pages,
5055acce952bSliubo 					int mark)
5056acce952bSliubo {
5057acce952bSliubo 	int ret;
5058acce952bSliubo 	struct extent_buffer *eb;
5059acce952bSliubo 	u64 start = 0;
5060acce952bSliubo 	u64 end;
5061acce952bSliubo 
5062acce952bSliubo 	while (1) {
5063acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
5064e6138876SJosef Bacik 					    mark, NULL);
5065acce952bSliubo 		if (ret)
5066acce952bSliubo 			break;
5067acce952bSliubo 
506891166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
5069acce952bSliubo 		while (start <= end) {
50700b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
50710b246afaSJeff Mahoney 			start += fs_info->nodesize;
5072fd8b2b61SJosef Bacik 			if (!eb)
5073acce952bSliubo 				continue;
5074fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
5075acce952bSliubo 
5076fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
5077fd8b2b61SJosef Bacik 					       &eb->bflags))
5078fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
5079fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
5080acce952bSliubo 		}
5081acce952bSliubo 	}
5082acce952bSliubo 
5083acce952bSliubo 	return ret;
5084acce952bSliubo }
5085acce952bSliubo 
50862ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
5087fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
5088acce952bSliubo {
5089acce952bSliubo 	u64 start;
5090acce952bSliubo 	u64 end;
5091acce952bSliubo 	int ret;
5092acce952bSliubo 
5093acce952bSliubo 	while (1) {
50940e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
50950e6ec385SFilipe Manana 
5096fcd5e742SLu Fengqi 		/*
5097fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
5098fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
5099fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5100fcd5e742SLu Fengqi 		 * the same extent range.
5101fcd5e742SLu Fengqi 		 */
5102fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
5103acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
51040e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
5105fcd5e742SLu Fengqi 		if (ret) {
5106fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5107acce952bSliubo 			break;
5108fcd5e742SLu Fengqi 		}
5109acce952bSliubo 
51100e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
51110e6ec385SFilipe Manana 		free_extent_state(cached_state);
51122ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
5113fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5114acce952bSliubo 		cond_resched();
5115acce952bSliubo 	}
5116acce952bSliubo 
5117acce952bSliubo 	return 0;
5118acce952bSliubo }
5119acce952bSliubo 
512032da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
5121c79a1751SLiu Bo {
5122c79a1751SLiu Bo 	struct inode *inode;
5123c79a1751SLiu Bo 
5124c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
5125c79a1751SLiu Bo 	if (inode) {
5126c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
5127c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
5128c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
5129c79a1751SLiu Bo 		iput(inode);
5130c79a1751SLiu Bo 	}
5131bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
5132c79a1751SLiu Bo 	btrfs_put_block_group(cache);
5133c79a1751SLiu Bo }
5134c79a1751SLiu Bo 
5135c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
51362ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5137c79a1751SLiu Bo {
513832da5386SDavid Sterba 	struct btrfs_block_group *cache;
5139c79a1751SLiu Bo 
5140c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5141c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5142c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
514332da5386SDavid Sterba 					 struct btrfs_block_group,
5144c79a1751SLiu Bo 					 dirty_list);
5145c79a1751SLiu Bo 
5146c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5147c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5148c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5149c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5150c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5151c79a1751SLiu Bo 		}
5152c79a1751SLiu Bo 
5153c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5154c79a1751SLiu Bo 		spin_lock(&cache->lock);
5155c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5156c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5157c79a1751SLiu Bo 
5158c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5159c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5160ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5161c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5162c79a1751SLiu Bo 	}
5163c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5164c79a1751SLiu Bo 
516545ae2c18SNikolay Borisov 	/*
516645ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
516745ae2c18SNikolay Borisov 	 * to use it without any locking
516845ae2c18SNikolay Borisov 	 */
5169c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5170c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
517132da5386SDavid Sterba 					 struct btrfs_block_group,
5172c79a1751SLiu Bo 					 io_list);
5173c79a1751SLiu Bo 
5174c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5175c79a1751SLiu Bo 		spin_lock(&cache->lock);
5176c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5177c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5178c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5179c79a1751SLiu Bo 	}
5180c79a1751SLiu Bo }
5181c79a1751SLiu Bo 
518249b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
51832ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
518449b25e05SJeff Mahoney {
5185bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5186bbbf7243SNikolay Borisov 
51872ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5188c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5189c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5190c79a1751SLiu Bo 
5191bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5192bbbf7243SNikolay Borisov 				 post_commit_list) {
5193bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5194bbbf7243SNikolay Borisov 	}
5195bbbf7243SNikolay Borisov 
51962ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
519749b25e05SJeff Mahoney 
51984a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
51990b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
520049b25e05SJeff Mahoney 
52014a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
52020b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
520349b25e05SJeff Mahoney 
5204ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
520567cde344SMiao Xie 
52062ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
520749b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5208fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
520949b25e05SJeff Mahoney 
5210d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
5211d3575156SNaohiro Aota 
52124a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
52134a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
521449b25e05SJeff Mahoney }
521549b25e05SJeff Mahoney 
52162ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5217acce952bSliubo {
5218acce952bSliubo 	struct btrfs_transaction *t;
5219acce952bSliubo 
52200b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5221acce952bSliubo 
52220b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
52230b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
52240b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5225724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5226724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
52279b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
52280b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
52292ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5230724e2315SJosef Bacik 			btrfs_put_transaction(t);
52310b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5232724e2315SJosef Bacik 			continue;
5233724e2315SJosef Bacik 		}
52340b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5235724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
52360b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5237724e2315SJosef Bacik 			/*
5238724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5239724e2315SJosef Bacik 			 * handle open currently for this transaction.
5240724e2315SJosef Bacik 			 */
5241724e2315SJosef Bacik 			wait_event(t->writer_wait,
5242724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5243724e2315SJosef Bacik 		} else {
52440b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5245724e2315SJosef Bacik 		}
52462ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5247724e2315SJosef Bacik 
52480b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
52490b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
52500b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5251724e2315SJosef Bacik 		list_del_init(&t->list);
52520b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5253a4abeea4SJosef Bacik 
5254724e2315SJosef Bacik 		btrfs_put_transaction(t);
52552e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
52560b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5257724e2315SJosef Bacik 	}
52580b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
52590b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5260ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5261ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
52620b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5263ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
52640b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5265acce952bSliubo 
5266acce952bSliubo 	return 0;
5267acce952bSliubo }
5268ec7d6dfdSNikolay Borisov 
5269453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5270ec7d6dfdSNikolay Borisov {
5271ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5272ec7d6dfdSNikolay Borisov 	int ret;
5273ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5274ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5275ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5276ec7d6dfdSNikolay Borisov 	int slot;
5277ec7d6dfdSNikolay Borisov 
5278ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5279ec7d6dfdSNikolay Borisov 	if (!path)
5280ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5281ec7d6dfdSNikolay Borisov 
5282ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5283ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5284ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5285ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5286ec7d6dfdSNikolay Borisov 	if (ret < 0)
5287ec7d6dfdSNikolay Borisov 		goto error;
5288ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5289ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5290ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5291ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5292ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
529323125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
529423125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5295ec7d6dfdSNikolay Borisov 	} else {
529623125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5297ec7d6dfdSNikolay Borisov 	}
5298ec7d6dfdSNikolay Borisov 	ret = 0;
5299ec7d6dfdSNikolay Borisov error:
5300ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5301ec7d6dfdSNikolay Borisov 	return ret;
5302ec7d6dfdSNikolay Borisov }
5303ec7d6dfdSNikolay Borisov 
5304543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5305ec7d6dfdSNikolay Borisov {
5306ec7d6dfdSNikolay Borisov 	int ret;
5307ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5308ec7d6dfdSNikolay Borisov 
53096b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5310ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5311ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5312ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5313ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5314ec7d6dfdSNikolay Borisov 		goto out;
5315ec7d6dfdSNikolay Borisov 	}
5316ec7d6dfdSNikolay Borisov 
531723125104SNikolay Borisov 	*objectid = root->free_objectid++;
5318ec7d6dfdSNikolay Borisov 	ret = 0;
5319ec7d6dfdSNikolay Borisov out:
5320ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5321ec7d6dfdSNikolay Borisov 	return ret;
5322ec7d6dfdSNikolay Borisov }
5323