xref: /openbmc/linux/fs/btrfs/disk-io.c (revision a91cf0ff)
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>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10ce9adaa5SChris Mason #include <linux/workqueue.h>
11a74a4b97SChris Mason #include <linux/kthread.h>
125a0e3ad6STejun Heo #include <linux/slab.h>
13784b4e29SChris Mason #include <linux/migrate.h>
147a36ddecSDavid Sterba #include <linux/ratelimit.h>
156463fe58SStefan Behrens #include <linux/uuid.h>
16803b2f54SStefan Behrens #include <linux/semaphore.h>
17540adea3SMasami Hiramatsu #include <linux/error-injection.h>
189678c543SNikolay Borisov #include <linux/crc32c.h>
19b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
216d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
24e089f05cSChris Mason #include "transaction.h"
250f7d52f4SChris Mason #include "btrfs_inode.h"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41aac0023cSJosef Bacik #include "block-group.h"
42b0643e59SDennis Zhou #include "discard.h"
43f603bb94SNikolay Borisov #include "space-info.h"
44b70f5097SNaohiro Aota #include "zoned.h"
45139e8cd3SQu Wenruo #include "subpage.h"
46eb60ceacSChris Mason 
47319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
48319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
53319e4d06SQu Wenruo 
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
102141386e1SJosef Bacik {
103141386e1SJosef Bacik 	if (fs_info->csum_shash)
104141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
105141386e1SJosef Bacik }
106141386e1SJosef Bacik 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
109d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
110d352ac68SChris Mason  * just before they are sent down the IO stack.
111d352ac68SChris Mason  */
11244b8bd7eSChris Mason struct async_submit_bio {
1138896a08dSQu Wenruo 	struct inode *inode;
11444b8bd7eSChris Mason 	struct bio *bio;
115a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11644b8bd7eSChris Mason 	int mirror_num;
1171941b64bSQu Wenruo 
1181941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
1191941b64bSQu Wenruo 	u64 dio_file_offset;
1208b712842SChris Mason 	struct btrfs_work work;
1214e4cbee9SChristoph Hellwig 	blk_status_t status;
12244b8bd7eSChris Mason };
12344b8bd7eSChris Mason 
12485d4e461SChris Mason /*
12585d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12685d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12785d4e461SChris Mason  * the level the eb occupies in the tree.
1284008c04aSChris Mason  *
12985d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13085d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13185d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1324fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1334fd786e6SMisono Tomohiro  * roots have separate keysets.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13685d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13785d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1384008c04aSChris Mason  *
13985d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14085d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14185d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14285d4e461SChris Mason  *
14385d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14485d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14585d4e461SChris Mason  * needs update as well.
1464008c04aSChris Mason  */
1474008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1484008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1494008c04aSChris Mason #  error
1504008c04aSChris Mason # endif
15185d4e461SChris Mason 
152ab1405aaSDavid Sterba #define DEFINE_LEVEL(stem, level)					\
153ab1405aaSDavid Sterba 	.names[level] = "btrfs-" stem "-0" #level,
154ab1405aaSDavid Sterba 
155ab1405aaSDavid Sterba #define DEFINE_NAME(stem)						\
156ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 0)						\
157ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 1)						\
158ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 2)						\
159ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 3)						\
160ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 4)						\
161ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 5)						\
162ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 6)						\
163ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 7)
164ab1405aaSDavid Sterba 
16585d4e461SChris Mason static struct btrfs_lockdep_keyset {
16685d4e461SChris Mason 	u64			id;		/* root objectid */
167ab1405aaSDavid Sterba 	/* Longest entry: btrfs-free-space-00 */
168387824afSDavid Sterba 	char			names[BTRFS_MAX_LEVEL][20];
169387824afSDavid Sterba 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
17085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
171ab1405aaSDavid Sterba 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
172ab1405aaSDavid Sterba 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
173ab1405aaSDavid Sterba 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
174ab1405aaSDavid Sterba 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
175ab1405aaSDavid Sterba 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
176ab1405aaSDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
177ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
178ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
179ab1405aaSDavid Sterba 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
180ab1405aaSDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
181ab1405aaSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
182ab1405aaSDavid Sterba 	{ .id = 0,				DEFINE_NAME("tree")	},
1834008c04aSChris Mason };
18485d4e461SChris Mason 
185ab1405aaSDavid Sterba #undef DEFINE_LEVEL
186ab1405aaSDavid Sterba #undef DEFINE_NAME
18785d4e461SChris Mason 
18885d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18985d4e461SChris Mason 				    int level)
19085d4e461SChris Mason {
19185d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19285d4e461SChris Mason 
19385d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19485d4e461SChris Mason 
19585d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19685d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19785d4e461SChris Mason 		if (ks->id == objectid)
19885d4e461SChris Mason 			break;
19985d4e461SChris Mason 
20085d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20185d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20285d4e461SChris Mason }
20385d4e461SChris Mason 
2044008c04aSChris Mason #endif
2054008c04aSChris Mason 
206d352ac68SChris Mason /*
2072996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
208d352ac68SChris Mason  */
209c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
21019c00ddcSChris Mason {
211d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
2127280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
213a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
214d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
21519c00ddcSChris Mason 	char *kaddr;
216e9be5a30SDavid Sterba 	int i;
217d5178578SJohannes Thumshirn 
218d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
219d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
220a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
221e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
222a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
22319c00ddcSChris Mason 
224e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
225e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
226e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
22719c00ddcSChris Mason 	}
22871a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
229d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
23019c00ddcSChris Mason }
23119c00ddcSChris Mason 
232d352ac68SChris Mason /*
233d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
234d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
235d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
236d352ac68SChris Mason  * in the wrong place.
237d352ac68SChris Mason  */
2381259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
239b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
240b9fab919SChris Mason 				 int atomic)
2411259ab75SChris Mason {
2422ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2431259ab75SChris Mason 	int ret;
2441259ab75SChris Mason 
2451259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
2461259ab75SChris Mason 		return 0;
2471259ab75SChris Mason 
248b9fab919SChris Mason 	if (atomic)
249b9fab919SChris Mason 		return -EAGAIN;
250b9fab919SChris Mason 
2512ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
252ff13db41SDavid Sterba 			 &cached_state);
2530b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
2541259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
2551259ab75SChris Mason 		ret = 0;
2561259ab75SChris Mason 		goto out;
2571259ab75SChris Mason 	}
25894647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
25994647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
26094647322SDavid Sterba 			eb->start,
26129549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
2621259ab75SChris Mason 	ret = 1;
2630b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
26433958dc6SChris Mason out:
2652ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
266e43bbe5eSDavid Sterba 			     &cached_state);
2671259ab75SChris Mason 	return ret;
2681259ab75SChris Mason }
2691259ab75SChris Mason 
270e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
271e7e16f48SJohannes Thumshirn {
272e7e16f48SJohannes Thumshirn 	switch (csum_type) {
273e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
2743951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
2753831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
276352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
277e7e16f48SJohannes Thumshirn 		return true;
278e7e16f48SJohannes Thumshirn 	default:
279e7e16f48SJohannes Thumshirn 		return false;
280e7e16f48SJohannes Thumshirn 	}
281e7e16f48SJohannes Thumshirn }
282e7e16f48SJohannes Thumshirn 
283d352ac68SChris Mason /*
2841104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
2851104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
2861104a885SDavid Sterba  */
287ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
288ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
2891104a885SDavid Sterba {
2901104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
2911104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
29251bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
293d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
294d5178578SJohannes Thumshirn 
295d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
2961104a885SDavid Sterba 
2971104a885SDavid Sterba 	/*
2981104a885SDavid Sterba 	 * The super_block structure does not span the whole
29951bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
30051bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3011104a885SDavid Sterba 	 */
302fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
303fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3041104a885SDavid Sterba 
30555fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
306e7e16f48SJohannes Thumshirn 		return 1;
3071104a885SDavid Sterba 
308e7e16f48SJohannes Thumshirn 	return 0;
3091104a885SDavid Sterba }
3101104a885SDavid Sterba 
311e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
312ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
313581c1760SQu Wenruo {
314e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
315581c1760SQu Wenruo 	int found_level;
316581c1760SQu Wenruo 	struct btrfs_key found_key;
317581c1760SQu Wenruo 	int ret;
318581c1760SQu Wenruo 
319581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
320581c1760SQu Wenruo 	if (found_level != level) {
32163489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
32263489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
323581c1760SQu Wenruo 		btrfs_err(fs_info,
324581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
325581c1760SQu Wenruo 			  eb->start, level, found_level);
326581c1760SQu Wenruo 		return -EIO;
327581c1760SQu Wenruo 	}
328581c1760SQu Wenruo 
329581c1760SQu Wenruo 	if (!first_key)
330581c1760SQu Wenruo 		return 0;
331581c1760SQu Wenruo 
3325d41be6fSQu Wenruo 	/*
3335d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3345d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
3355d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
3365d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
3375d41be6fSQu Wenruo 	 */
3385d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
3395d41be6fSQu Wenruo 		return 0;
34062fdaa52SQu Wenruo 
34162fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
34262fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
34362fdaa52SQu Wenruo 		btrfs_err(fs_info,
34462fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
34562fdaa52SQu Wenruo 			  eb->start);
34662fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
34762fdaa52SQu Wenruo 		return -EUCLEAN;
34862fdaa52SQu Wenruo 	}
34962fdaa52SQu Wenruo 
350581c1760SQu Wenruo 	if (found_level)
351581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
352581c1760SQu Wenruo 	else
353581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
354581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
355581c1760SQu Wenruo 
356581c1760SQu Wenruo 	if (ret) {
35763489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
35863489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
359581c1760SQu Wenruo 		btrfs_err(fs_info,
360ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
361ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
362ff76a864SLiu Bo 			  first_key->type, first_key->offset,
363ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
364ff76a864SLiu Bo 			  found_key.offset);
365581c1760SQu Wenruo 	}
366581c1760SQu Wenruo 	return ret;
367581c1760SQu Wenruo }
368581c1760SQu Wenruo 
3691104a885SDavid Sterba /*
370d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
371d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
372581c1760SQu Wenruo  *
373581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
374581c1760SQu Wenruo  * @level:		expected level, mandatory check
375581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
376d352ac68SChris Mason  */
3775ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
378581c1760SQu Wenruo 					  u64 parent_transid, int level,
379581c1760SQu Wenruo 					  struct btrfs_key *first_key)
380f188591eSChris Mason {
3815ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
382f188591eSChris Mason 	struct extent_io_tree *io_tree;
383ea466794SJosef Bacik 	int failed = 0;
384f188591eSChris Mason 	int ret;
385f188591eSChris Mason 	int num_copies = 0;
386f188591eSChris Mason 	int mirror_num = 0;
387ea466794SJosef Bacik 	int failed_mirror = 0;
388f188591eSChris Mason 
3890b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
390f188591eSChris Mason 	while (1) {
391f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
392c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
393256dd1bbSStefan Behrens 		if (!ret) {
394581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
395b9fab919SChris Mason 						   parent_transid, 0))
396256dd1bbSStefan Behrens 				ret = -EIO;
397e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
398ff76a864SLiu Bo 						first_key, parent_transid))
399581c1760SQu Wenruo 				ret = -EUCLEAN;
400581c1760SQu Wenruo 			else
401581c1760SQu Wenruo 				break;
402256dd1bbSStefan Behrens 		}
403d397712bSChris Mason 
4040b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
405f188591eSChris Mason 					      eb->start, eb->len);
4064235298eSChris Mason 		if (num_copies == 1)
407ea466794SJosef Bacik 			break;
4084235298eSChris Mason 
4095cf1ab56SJosef Bacik 		if (!failed_mirror) {
4105cf1ab56SJosef Bacik 			failed = 1;
4115cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4125cf1ab56SJosef Bacik 		}
4135cf1ab56SJosef Bacik 
414f188591eSChris Mason 		mirror_num++;
415ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
416ea466794SJosef Bacik 			mirror_num++;
417ea466794SJosef Bacik 
4184235298eSChris Mason 		if (mirror_num > num_copies)
419ea466794SJosef Bacik 			break;
420f188591eSChris Mason 	}
421ea466794SJosef Bacik 
422c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
42320a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
424ea466794SJosef Bacik 
425ea466794SJosef Bacik 	return ret;
426f188591eSChris Mason }
42719c00ddcSChris Mason 
428eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
429eca0f6f6SQu Wenruo {
430eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
431eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
432eca0f6f6SQu Wenruo 	int ret;
433eca0f6f6SQu Wenruo 
434eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
435eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
436eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
437eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
438eca0f6f6SQu Wenruo 
439eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
440eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
441eca0f6f6SQu Wenruo 	else
442eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
443eca0f6f6SQu Wenruo 
444eca0f6f6SQu Wenruo 	if (ret < 0) {
445eca0f6f6SQu Wenruo 		btrfs_print_tree(eb, 0);
446eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
447eca0f6f6SQu Wenruo 			"block=%llu write time tree block corruption detected",
448eca0f6f6SQu Wenruo 			eb->start);
449eca0f6f6SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
450eca0f6f6SQu Wenruo 		return ret;
451eca0f6f6SQu Wenruo 	}
452eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
453eca0f6f6SQu Wenruo 
454eca0f6f6SQu Wenruo 	return 0;
455eca0f6f6SQu Wenruo }
456eca0f6f6SQu Wenruo 
457eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
458eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
459eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
460eca0f6f6SQu Wenruo {
461eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
462eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
463eca0f6f6SQu Wenruo 	u64 cur;
464eca0f6f6SQu Wenruo 	int ret = 0;
465eca0f6f6SQu Wenruo 
466eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
467eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
468eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
469eca0f6f6SQu Wenruo 		bool uptodate;
470eca0f6f6SQu Wenruo 
471eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
472eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
473eca0f6f6SQu Wenruo 						       fs_info->nodesize);
474eca0f6f6SQu Wenruo 
475eca0f6f6SQu Wenruo 		/* A dirty eb shouldn't disappear from buffer_radix */
476eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
477eca0f6f6SQu Wenruo 			return -EUCLEAN;
478eca0f6f6SQu Wenruo 
479eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
480eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
481eca0f6f6SQu Wenruo 			return -EUCLEAN;
482eca0f6f6SQu Wenruo 		}
483eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
484eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
485eca0f6f6SQu Wenruo 			return -EUCLEAN;
486eca0f6f6SQu Wenruo 		}
487eca0f6f6SQu Wenruo 
488eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
489eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
490eca0f6f6SQu Wenruo 		if (ret < 0)
491eca0f6f6SQu Wenruo 			return ret;
492eca0f6f6SQu Wenruo 	}
493eca0f6f6SQu Wenruo 	return ret;
494eca0f6f6SQu Wenruo }
495eca0f6f6SQu Wenruo 
496d352ac68SChris Mason /*
497ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
498ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
499ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
500d352ac68SChris Mason  */
501ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
50219c00ddcSChris Mason {
503ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
5044eee4fa4SMiao Xie 	u64 start = page_offset(page);
50519c00ddcSChris Mason 	u64 found_start;
50619c00ddcSChris Mason 	struct extent_buffer *eb;
507eca0f6f6SQu Wenruo 
508eca0f6f6SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE)
509eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
510f188591eSChris Mason 
5114f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5124f2de97aSJosef Bacik 	if (page != eb->pages[0])
5134f2de97aSJosef Bacik 		return 0;
5140f805531SAlex Lyakas 
51519c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
516d3575156SNaohiro Aota 
517d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
518d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
519d3575156SNaohiro Aota 		return 0;
520d3575156SNaohiro Aota 	}
521d3575156SNaohiro Aota 
5220f805531SAlex Lyakas 	/*
5230f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5240f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5250f805531SAlex Lyakas 	 */
5260f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5270f805531SAlex Lyakas 		return -EUCLEAN;
5280f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5290f805531SAlex Lyakas 		return -EUCLEAN;
5300f805531SAlex Lyakas 
531eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
53219c00ddcSChris Mason }
53319c00ddcSChris Mason 
534b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5352b82032cSYan Zheng {
536b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
537944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
53844880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
539944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5402b82032cSYan Zheng 
5419a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5429a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5437239ff4bSNikolay Borisov 	/*
544944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
545944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
546944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5477239ff4bSNikolay Borisov 	 */
548944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5497239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5507239ff4bSNikolay Borisov 	else
5517239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5527239ff4bSNikolay Borisov 
553944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
554944d3f9fSNikolay Borisov 		return 0;
555944d3f9fSNikolay Borisov 
556944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
557944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
558944d3f9fSNikolay Borisov 			return 0;
559944d3f9fSNikolay Borisov 
560944d3f9fSNikolay Borisov 	return 1;
5612b82032cSYan Zheng }
5622b82032cSYan Zheng 
56377bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
56477bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
565ce9adaa5SChris Mason {
56677bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
567ce9adaa5SChris Mason 	u64 found_start;
56877bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
56977bf40a2SQu Wenruo 	u8 found_level;
5702996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
571dfd29eedSDavid Sterba 	const u8 *header_csum;
57277bf40a2SQu Wenruo 	int ret = 0;
573ea466794SJosef Bacik 
574ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
575727011e0SChris Mason 	if (found_start != eb->start) {
576893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
577893bf4b1SSu Yue 			     eb->start, found_start);
578f188591eSChris Mason 		ret = -EIO;
57977bf40a2SQu Wenruo 		goto out;
580ce9adaa5SChris Mason 	}
581b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
58202873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
58394647322SDavid Sterba 			     eb->start);
5841259ab75SChris Mason 		ret = -EIO;
58577bf40a2SQu Wenruo 		goto out;
5861259ab75SChris Mason 	}
587ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5881c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
589893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
590893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5911c24c3ceSJosef Bacik 		ret = -EIO;
59277bf40a2SQu Wenruo 		goto out;
5931c24c3ceSJosef Bacik 	}
594ce9adaa5SChris Mason 
595c67b3892SDavid Sterba 	csum_tree_block(eb, result);
596dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
597dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
598a826d6dcSJosef Bacik 
599dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
6002996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
601ff14aa79SDavid Sterba 	"checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
602ff14aa79SDavid Sterba 			      eb->start,
603dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
60435be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
60535be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
6062996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
60777bf40a2SQu Wenruo 		goto out;
6082996e1f8SJohannes Thumshirn 	}
6092996e1f8SJohannes Thumshirn 
610a826d6dcSJosef Bacik 	/*
611a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
612a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
613a826d6dcSJosef Bacik 	 * return -EIO.
614a826d6dcSJosef Bacik 	 */
6151c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
616a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
617a826d6dcSJosef Bacik 		ret = -EIO;
618a826d6dcSJosef Bacik 	}
619ce9adaa5SChris Mason 
620813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
621053ab70fSLiu Bo 		ret = -EIO;
622053ab70fSLiu Bo 
6230b32f4bbSJosef Bacik 	if (!ret)
6240b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
62575391f0dSQu Wenruo 	else
62675391f0dSQu Wenruo 		btrfs_err(fs_info,
62775391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
62875391f0dSQu Wenruo 			  eb->start);
62977bf40a2SQu Wenruo out:
63077bf40a2SQu Wenruo 	return ret;
63177bf40a2SQu Wenruo }
63277bf40a2SQu Wenruo 
633371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
634371cdc07SQu Wenruo 				   int mirror)
635371cdc07SQu Wenruo {
636371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
637371cdc07SQu Wenruo 	struct extent_buffer *eb;
638371cdc07SQu Wenruo 	bool reads_done;
639371cdc07SQu Wenruo 	int ret = 0;
640371cdc07SQu Wenruo 
641371cdc07SQu Wenruo 	/*
642371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
643371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
644371cdc07SQu Wenruo 	 */
645371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
646371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
647371cdc07SQu Wenruo 
648371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
649371cdc07SQu Wenruo 	/*
650371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
651371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
652371cdc07SQu Wenruo 	 */
653371cdc07SQu Wenruo 	ASSERT(eb);
654371cdc07SQu Wenruo 
655371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
656371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
657371cdc07SQu Wenruo 	ASSERT(reads_done);
658371cdc07SQu Wenruo 
659371cdc07SQu Wenruo 	eb->read_mirror = mirror;
660371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
661371cdc07SQu Wenruo 		ret = -EIO;
662371cdc07SQu Wenruo 		goto err;
663371cdc07SQu Wenruo 	}
664371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
665371cdc07SQu Wenruo 	if (ret < 0)
666371cdc07SQu Wenruo 		goto err;
667371cdc07SQu Wenruo 
668371cdc07SQu Wenruo 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
669371cdc07SQu Wenruo 		btree_readahead_hook(eb, ret);
670371cdc07SQu Wenruo 
671371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
672371cdc07SQu Wenruo 
673371cdc07SQu Wenruo 	free_extent_buffer(eb);
674371cdc07SQu Wenruo 	return ret;
675371cdc07SQu Wenruo err:
676371cdc07SQu Wenruo 	/*
677371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
678371cdc07SQu Wenruo 	 * make sure it has something to decrement.
679371cdc07SQu Wenruo 	 */
680371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
681371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
682371cdc07SQu Wenruo 	free_extent_buffer(eb);
683371cdc07SQu Wenruo 	return ret;
684371cdc07SQu Wenruo }
685371cdc07SQu Wenruo 
686c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
68777bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
68877bf40a2SQu Wenruo 				   int mirror)
68977bf40a2SQu Wenruo {
69077bf40a2SQu Wenruo 	struct extent_buffer *eb;
69177bf40a2SQu Wenruo 	int ret = 0;
69277bf40a2SQu Wenruo 	int reads_done;
69377bf40a2SQu Wenruo 
69477bf40a2SQu Wenruo 	ASSERT(page->private);
695371cdc07SQu Wenruo 
696371cdc07SQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
697371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
698371cdc07SQu Wenruo 
69977bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
70077bf40a2SQu Wenruo 
70177bf40a2SQu Wenruo 	/*
70277bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
70377bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
70477bf40a2SQu Wenruo 	 */
70577bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
70677bf40a2SQu Wenruo 
70777bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
70877bf40a2SQu Wenruo 	if (!reads_done)
70977bf40a2SQu Wenruo 		goto err;
71077bf40a2SQu Wenruo 
71177bf40a2SQu Wenruo 	eb->read_mirror = mirror;
71277bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
71377bf40a2SQu Wenruo 		ret = -EIO;
71477bf40a2SQu Wenruo 		goto err;
71577bf40a2SQu Wenruo 	}
71677bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
717ce9adaa5SChris Mason err:
71879fb65a1SJosef Bacik 	if (reads_done &&
71979fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
720d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
7214bb31e92SArne Jansen 
72253b381b3SDavid Woodhouse 	if (ret) {
72353b381b3SDavid Woodhouse 		/*
72453b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
72553b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
72653b381b3SDavid Woodhouse 		 * to decrement
72753b381b3SDavid Woodhouse 		 */
72853b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7290b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
73053b381b3SDavid Woodhouse 	}
7310b32f4bbSJosef Bacik 	free_extent_buffer(eb);
73277bf40a2SQu Wenruo 
733f188591eSChris Mason 	return ret;
734ce9adaa5SChris Mason }
735ce9adaa5SChris Mason 
7364246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
737ce9adaa5SChris Mason {
73897eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
739ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7409e0af237SLiu Bo 	struct btrfs_workqueue *wq;
741ce9adaa5SChris Mason 
742ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7434e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
744d20f7043SChris Mason 
745cfe94440SNaohiro Aota 	if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
746a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7479e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
748a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7499e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
750a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7519e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
752a0cac0ecSOmar Sandoval 		else
7539e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7549e0af237SLiu Bo 	} else {
7555c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7569e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
757a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7589e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
759a0cac0ecSOmar Sandoval 		else
7609e0af237SLiu Bo 			wq = fs_info->endio_workers;
7619e0af237SLiu Bo 	}
7629e0af237SLiu Bo 
763a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7649e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
765ce9adaa5SChris Mason }
766ce9adaa5SChris Mason 
7674e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
768bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7690b86a832SChris Mason {
77097eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7718b110e39SMiao Xie 
77297eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
773ce9adaa5SChris Mason 	if (!end_io_wq)
7744e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
775ce9adaa5SChris Mason 
776ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
777ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
77822c59948SChris Mason 	end_io_wq->info = info;
7794e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
780ce9adaa5SChris Mason 	end_io_wq->bio = bio;
78122c59948SChris Mason 	end_io_wq->metadata = metadata;
782ce9adaa5SChris Mason 
783ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
784ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
78522c59948SChris Mason 	return 0;
78622c59948SChris Mason }
78722c59948SChris Mason 
7884a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7894a69a410SChris Mason {
7904a69a410SChris Mason 	struct async_submit_bio *async;
7914e4cbee9SChristoph Hellwig 	blk_status_t ret;
7924a69a410SChris Mason 
7934a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7941941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
7951941b64bSQu Wenruo 				      async->dio_file_offset);
79679787eaaSJeff Mahoney 	if (ret)
7974e4cbee9SChristoph Hellwig 		async->status = ret;
7984a69a410SChris Mason }
7994a69a410SChris Mason 
80006ea01b1SDavid Sterba /*
80106ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
80206ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
80306ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
80406ea01b1SDavid Sterba  *
80506ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
80606ea01b1SDavid Sterba  * inserted into the tree.
80706ea01b1SDavid Sterba  */
8084a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
8098b712842SChris Mason {
8108b712842SChris Mason 	struct async_submit_bio *async;
81106ea01b1SDavid Sterba 	struct inode *inode;
81206ea01b1SDavid Sterba 	blk_status_t ret;
8138b712842SChris Mason 
8148b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8158896a08dSQu Wenruo 	inode = async->inode;
8164854ddd0SChris Mason 
817bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
8184e4cbee9SChristoph Hellwig 	if (async->status) {
8194e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
8204246a0b6SChristoph Hellwig 		bio_endio(async->bio);
82179787eaaSJeff Mahoney 		return;
82279787eaaSJeff Mahoney 	}
82379787eaaSJeff Mahoney 
824ec39f769SChris Mason 	/*
825ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
826ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
827ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
828ec39f769SChris Mason 	 */
829ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
83008635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
83106ea01b1SDavid Sterba 	if (ret) {
83206ea01b1SDavid Sterba 		async->bio->bi_status = ret;
83306ea01b1SDavid Sterba 		bio_endio(async->bio);
83406ea01b1SDavid Sterba 	}
8354a69a410SChris Mason }
8364a69a410SChris Mason 
8374a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8384a69a410SChris Mason {
8394a69a410SChris Mason 	struct async_submit_bio *async;
8404a69a410SChris Mason 
8414a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8428b712842SChris Mason 	kfree(async);
8438b712842SChris Mason }
8448b712842SChris Mason 
8458896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
846c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
8471941b64bSQu Wenruo 				 u64 dio_file_offset,
848e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
84944b8bd7eSChris Mason {
8508896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
85144b8bd7eSChris Mason 	struct async_submit_bio *async;
85244b8bd7eSChris Mason 
85344b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
85444b8bd7eSChris Mason 	if (!async)
8554e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
85644b8bd7eSChris Mason 
8578896a08dSQu Wenruo 	async->inode = inode;
85844b8bd7eSChris Mason 	async->bio = bio;
85944b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8604a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8614a69a410SChris Mason 
862a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
863a0cac0ecSOmar Sandoval 			run_one_async_free);
8644a69a410SChris Mason 
8651941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
8668c8bee1dSChris Mason 
8674e4cbee9SChristoph Hellwig 	async->status = 0;
86879787eaaSJeff Mahoney 
86967f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8705cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
871d313d7a3SChris Mason 
8725cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
87344b8bd7eSChris Mason 	return 0;
87444b8bd7eSChris Mason }
87544b8bd7eSChris Mason 
8764e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
877ce3ed71aSChris Mason {
8782c30c71bSKent Overstreet 	struct bio_vec *bvec;
879ce3ed71aSChris Mason 	struct btrfs_root *root;
8802b070cfeSChristoph Hellwig 	int ret = 0;
8816dc4f100SMing Lei 	struct bvec_iter_all iter_all;
882ce3ed71aSChris Mason 
883c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8842b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
885ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
886ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
88779787eaaSJeff Mahoney 		if (ret)
88879787eaaSJeff Mahoney 			break;
889ce3ed71aSChris Mason 	}
8902c30c71bSKent Overstreet 
8914e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
892ce3ed71aSChris Mason }
893ce3ed71aSChris Mason 
8948896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
8951941b64bSQu Wenruo 					   u64 dio_file_offset)
89622c59948SChris Mason {
8978b712842SChris Mason 	/*
8988b712842SChris Mason 	 * when we're called for a write, we're already in the async
8995443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
9008b712842SChris Mason 	 */
90179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
90222c59948SChris Mason }
90322c59948SChris Mason 
904f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
9059b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
906de0022b9SJosef Bacik {
9074eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
908f4dcfb30SJohannes Thumshirn 		return false;
9096300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
910f4dcfb30SJohannes Thumshirn 		return false;
9119b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
912f4dcfb30SJohannes Thumshirn 		return false;
913f4dcfb30SJohannes Thumshirn 	return true;
914de0022b9SJosef Bacik }
915de0022b9SJosef Bacik 
9161b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
9171b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
91844b8bd7eSChris Mason {
9190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9204e4cbee9SChristoph Hellwig 	blk_status_t ret;
921cad321adSChris Mason 
922cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
923cad321adSChris Mason 		/*
924cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
925cad321adSChris Mason 		 * can happen in the async kernel threads
926cad321adSChris Mason 		 */
9270b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
9280b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
9291d4284bdSChris Mason 		if (ret)
93061891923SStefan Behrens 			goto out_w_error;
93108635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
932f4dcfb30SJohannes Thumshirn 	} else if (!should_async_write(fs_info, BTRFS_I(inode))) {
933de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
934de0022b9SJosef Bacik 		if (ret)
93561891923SStefan Behrens 			goto out_w_error;
93608635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
93761891923SStefan Behrens 	} else {
938cad321adSChris Mason 		/*
93961891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
94061891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
941cad321adSChris Mason 		 */
9428896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
9438896a08dSQu Wenruo 					  0, btree_submit_bio_start);
94444b8bd7eSChris Mason 	}
94544b8bd7eSChris Mason 
9464246a0b6SChristoph Hellwig 	if (ret)
9474246a0b6SChristoph Hellwig 		goto out_w_error;
9484246a0b6SChristoph Hellwig 	return 0;
9494246a0b6SChristoph Hellwig 
95061891923SStefan Behrens out_w_error:
9514e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9524246a0b6SChristoph Hellwig 	bio_endio(bio);
95361891923SStefan Behrens 	return ret;
95461891923SStefan Behrens }
95561891923SStefan Behrens 
9563dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
957784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
958a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
959a6bc32b8SMel Gorman 			enum migrate_mode mode)
960784b4e29SChris Mason {
961784b4e29SChris Mason 	/*
962784b4e29SChris Mason 	 * we can't safely write a btree page from here,
963784b4e29SChris Mason 	 * we haven't done the locking hook
964784b4e29SChris Mason 	 */
965784b4e29SChris Mason 	if (PageDirty(page))
966784b4e29SChris Mason 		return -EAGAIN;
967784b4e29SChris Mason 	/*
968784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
969784b4e29SChris Mason 	 * We must have no buffers or drop them.
970784b4e29SChris Mason 	 */
971784b4e29SChris Mason 	if (page_has_private(page) &&
972784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
973784b4e29SChris Mason 		return -EAGAIN;
974a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
975784b4e29SChris Mason }
9763dd1462eSJan Beulich #endif
977784b4e29SChris Mason 
9780da5468fSChris Mason 
9790da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9800da5468fSChris Mason 			    struct writeback_control *wbc)
9810da5468fSChris Mason {
982e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
983e2d84521SMiao Xie 	int ret;
984e2d84521SMiao Xie 
985d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
986448d640bSChris Mason 
987448d640bSChris Mason 		if (wbc->for_kupdate)
988448d640bSChris Mason 			return 0;
989448d640bSChris Mason 
990e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
991b9473439SChris Mason 		/* this is a bit racy, but that's ok */
992d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
993d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
994d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
995e2d84521SMiao Xie 		if (ret < 0)
996793955bcSChris Mason 			return 0;
997793955bcSChris Mason 	}
9980b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9990da5468fSChris Mason }
10000da5468fSChris Mason 
100170dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
10025f39d397SChris Mason {
100398509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
100498509cfcSChris Mason 		return 0;
10050c4e538bSDavid Sterba 
1006f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1007d98237b3SChris Mason }
1008d98237b3SChris Mason 
1009d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1010d47992f8SLukas Czerner 				 unsigned int length)
1011d98237b3SChris Mason {
1012d1310b2eSChris Mason 	struct extent_io_tree *tree;
1013d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10145f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
10155f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
10169ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1017efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1018efe120a0SFrank Holton 			   "page private not zero on page %llu",
1019efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
1020d1b89bc0SGuoqing Jiang 		detach_page_private(page);
10219ad6b7bcSChris Mason 	}
1022d98237b3SChris Mason }
1023d98237b3SChris Mason 
10240b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10250b32f4bbSJosef Bacik {
1026bb146eb2SJosef Bacik #ifdef DEBUG
1027139e8cd3SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
1028139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
10290b32f4bbSJosef Bacik 	struct extent_buffer *eb;
1030139e8cd3SQu Wenruo 	int cur_bit = 0;
1031139e8cd3SQu Wenruo 	u64 page_start = page_offset(page);
10320b32f4bbSJosef Bacik 
1033139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
10340b32f4bbSJosef Bacik 		BUG_ON(!PagePrivate(page));
10350b32f4bbSJosef Bacik 		eb = (struct extent_buffer *)page->private;
10360b32f4bbSJosef Bacik 		BUG_ON(!eb);
10370b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10380b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
103949d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1040139e8cd3SQu Wenruo 		return __set_page_dirty_nobuffers(page);
1041139e8cd3SQu Wenruo 	}
1042139e8cd3SQu Wenruo 	ASSERT(PagePrivate(page) && page->private);
1043139e8cd3SQu Wenruo 	subpage = (struct btrfs_subpage *)page->private;
1044139e8cd3SQu Wenruo 
1045139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
1046139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
1047139e8cd3SQu Wenruo 		unsigned long flags;
1048139e8cd3SQu Wenruo 		u64 cur;
1049139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
1050139e8cd3SQu Wenruo 
1051139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
1052139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
1053139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
1054139e8cd3SQu Wenruo 			cur_bit++;
1055139e8cd3SQu Wenruo 			continue;
1056139e8cd3SQu Wenruo 		}
1057139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
1058139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
1059139e8cd3SQu Wenruo 
1060139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
1061139e8cd3SQu Wenruo 		ASSERT(eb);
1062139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1063139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
106449d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1065139e8cd3SQu Wenruo 		free_extent_buffer(eb);
1066139e8cd3SQu Wenruo 
1067139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
1068139e8cd3SQu Wenruo 	}
1069bb146eb2SJosef Bacik #endif
10700b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10710b32f4bbSJosef Bacik }
10720b32f4bbSJosef Bacik 
10737f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
10740da5468fSChris Mason 	.writepages	= btree_writepages,
10755f39d397SChris Mason 	.releasepage	= btree_releasepage,
10765f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10775a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1078784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10795a92bc88SChris Mason #endif
10800b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1081d98237b3SChris Mason };
1082123abc88SChris Mason 
10832ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10842ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10853fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
10863fbaf258SJosef Bacik 						int level)
10870999df54SChris Mason {
10880b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10890b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10903fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
10910999df54SChris Mason }
10920999df54SChris Mason 
1093581c1760SQu Wenruo /*
1094581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1095581c1760SQu Wenruo  * verification.
1096581c1760SQu Wenruo  *
10971b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
1098581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1099581c1760SQu Wenruo  * @level:		expected level, mandatory check
1100581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1101581c1760SQu Wenruo  */
11022ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
11031b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
11041b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
1105e20d96d6SChris Mason {
11065f39d397SChris Mason 	struct extent_buffer *buf = NULL;
110719c00ddcSChris Mason 	int ret;
110819c00ddcSChris Mason 
11093fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
1110c871b0f2SLiu Bo 	if (IS_ERR(buf))
1111c871b0f2SLiu Bo 		return buf;
1112e4204dedSChris Mason 
11135ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1114581c1760SQu Wenruo 					     level, first_key);
11150f0fe8f7SFilipe David Borba Manana 	if (ret) {
1116537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
111764c043deSLiu Bo 		return ERR_PTR(ret);
11180f0fe8f7SFilipe David Borba Manana 	}
11195f39d397SChris Mason 	return buf;
1120ce9adaa5SChris Mason 
1121eb60ceacSChris Mason }
1122eb60ceacSChris Mason 
11236a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1124ed2ff2cbSChris Mason {
11256a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
112655c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1127e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
112849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
1129b4ce94deSChris Mason 
1130b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1131104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1132e2d84521SMiao Xie 						 -buf->len,
1133e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
11340b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1135925baeddSChris Mason 		}
11365f39d397SChris Mason 	}
1137ed7b63ebSJosef Bacik }
11385f39d397SChris Mason 
1139da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1140e20d96d6SChris Mason 			 u64 objectid)
1141d97e63b6SChris Mason {
11427c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
114396dfcb46SJosef Bacik 	root->fs_info = fs_info;
1144cfaa7295SChris Mason 	root->node = NULL;
1145a28ec197SChris Mason 	root->commit_root = NULL;
114627cdeb70SMiao Xie 	root->state = 0;
1147d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11480b86a832SChris Mason 
11490f7d52f4SChris Mason 	root->last_trans = 0;
11506b8fad57SNikolay Borisov 	root->free_objectid = 0;
1151eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1152199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11536bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115416cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1155f0486c68SYan, Zheng 	root->block_rsv = NULL;
11560b86a832SChris Mason 
11570b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11585d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1159eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1160eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1161199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1162199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1163d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11642ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11652ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11665d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1167eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1168199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1169f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11702ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11712ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11728287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1173a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1174e02119d5SChris Mason 	mutex_init(&root->log_mutex);
117531f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1176573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1177c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11787237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11797237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11807237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11818b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11828b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11837237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11847237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11857237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11862ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11870700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11888ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1189eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11907237f183SYan Zheng 	root->log_transid = 0;
1191d1433debSMiao Xie 	root->log_transid_committed = -1;
1192257c62e1SChris Mason 	root->last_log_commit = 0;
1193e289f03eSFilipe Manana 	if (!dummy) {
119443eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
119543eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1196e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1197e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1198e289f03eSFilipe Manana 	}
1199017e5369SChris Mason 
12003768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
12013768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
12026702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
12034d775673SChris Mason 	root->root_key.objectid = objectid;
12040ee5dc67SAl Viro 	root->anon_dev = 0;
12058ea05e3aSAlexander Block 
12065f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1207370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1208bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1209bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1210bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1211bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1212bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1213bd647ce3SJosef Bacik #endif
12143768f368SChris Mason }
12153768f368SChris Mason 
121674e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
121796dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
12186f07e42eSAl Viro {
121974e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12206f07e42eSAl Viro 	if (root)
122196dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
12226f07e42eSAl Viro 	return root;
12236f07e42eSAl Viro }
12246f07e42eSAl Viro 
122506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
122606ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1227da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
122806ea65a3SJosef Bacik {
122906ea65a3SJosef Bacik 	struct btrfs_root *root;
123006ea65a3SJosef Bacik 
12317c0260eeSJeff Mahoney 	if (!fs_info)
12327c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12337c0260eeSJeff Mahoney 
123496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
123506ea65a3SJosef Bacik 	if (!root)
123606ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1237da17066cSJeff Mahoney 
1238b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1239faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
124006ea65a3SJosef Bacik 
124106ea65a3SJosef Bacik 	return root;
124206ea65a3SJosef Bacik }
124306ea65a3SJosef Bacik #endif
124406ea65a3SJosef Bacik 
124520897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
124620897f5cSArne Jansen 				     u64 objectid)
124720897f5cSArne Jansen {
12489b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
124920897f5cSArne Jansen 	struct extent_buffer *leaf;
125020897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
125120897f5cSArne Jansen 	struct btrfs_root *root;
125220897f5cSArne Jansen 	struct btrfs_key key;
1253b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
125420897f5cSArne Jansen 	int ret = 0;
125520897f5cSArne Jansen 
1256b89f6d1fSFilipe Manana 	/*
1257b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1258b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1259b89f6d1fSFilipe Manana 	 */
1260b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
126196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1262b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
126320897f5cSArne Jansen 	if (!root)
126420897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
126520897f5cSArne Jansen 
126620897f5cSArne Jansen 	root->root_key.objectid = objectid;
126720897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
126820897f5cSArne Jansen 	root->root_key.offset = 0;
126920897f5cSArne Jansen 
12709631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12719631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
127220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
127320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12741dd05682STsutomu Itoh 		leaf = NULL;
12758a6a87cdSBoris Burkov 		goto fail_unlock;
127620897f5cSArne Jansen 	}
127720897f5cSArne Jansen 
127820897f5cSArne Jansen 	root->node = leaf;
127920897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
128020897f5cSArne Jansen 
128120897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
128227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
128320897f5cSArne Jansen 
1284f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1285f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
128620897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
128720897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
128820897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
128920897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
129020897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
129120897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
129220897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
129333d85fdaSQu Wenruo 	if (is_fstree(objectid))
1294807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1295807fc790SAndy Shevchenko 	else
1296807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1297c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
129820897f5cSArne Jansen 
12998a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
13008a6a87cdSBoris Burkov 
130120897f5cSArne Jansen 	key.objectid = objectid;
130220897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
130320897f5cSArne Jansen 	key.offset = 0;
130420897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
130520897f5cSArne Jansen 	if (ret)
130620897f5cSArne Jansen 		goto fail;
130720897f5cSArne Jansen 
130820897f5cSArne Jansen 	return root;
13091dd05682STsutomu Itoh 
13108a6a87cdSBoris Burkov fail_unlock:
13118c38938cSJosef Bacik 	if (leaf)
13121dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
13138a6a87cdSBoris Burkov fail:
131400246528SJosef Bacik 	btrfs_put_root(root);
13151dd05682STsutomu Itoh 
13161dd05682STsutomu Itoh 	return ERR_PTR(ret);
131720897f5cSArne Jansen }
131820897f5cSArne Jansen 
13197237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1320e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13210f7d52f4SChris Mason {
13220f7d52f4SChris Mason 	struct btrfs_root *root;
1323e02119d5SChris Mason 
132496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1325e02119d5SChris Mason 	if (!root)
13267237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1327e02119d5SChris Mason 
1328e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1329e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1330e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
133127cdeb70SMiao Xie 
13326ab6ebb7SNaohiro Aota 	return root;
13336ab6ebb7SNaohiro Aota }
13346ab6ebb7SNaohiro Aota 
13356ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
13366ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
13376ab6ebb7SNaohiro Aota {
13386ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
13396ab6ebb7SNaohiro Aota 
13407237f183SYan Zheng 	/*
134192a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
134227cdeb70SMiao Xie 	 *
134392a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
134492a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
134592a7cc42SQu Wenruo 	 *
134692a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
134792a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
13487237f183SYan Zheng 	 */
1349e02119d5SChris Mason 
13504d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13519631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
13526ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
13536ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1354e02119d5SChris Mason 
13557237f183SYan Zheng 	root->node = leaf;
1356e02119d5SChris Mason 
1357e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1358e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13596ab6ebb7SNaohiro Aota 
13606ab6ebb7SNaohiro Aota 	return 0;
13617237f183SYan Zheng }
13627237f183SYan Zheng 
13637237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13647237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13657237f183SYan Zheng {
13667237f183SYan Zheng 	struct btrfs_root *log_root;
13677237f183SYan Zheng 
13687237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13697237f183SYan Zheng 	if (IS_ERR(log_root))
13707237f183SYan Zheng 		return PTR_ERR(log_root);
13716ab6ebb7SNaohiro Aota 
13723ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13733ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13743ddebf27SNaohiro Aota 
13756ab6ebb7SNaohiro Aota 		if (ret) {
13766ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13776ab6ebb7SNaohiro Aota 			return ret;
13786ab6ebb7SNaohiro Aota 		}
13793ddebf27SNaohiro Aota 	}
13806ab6ebb7SNaohiro Aota 
13817237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13827237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13837237f183SYan Zheng 	return 0;
13847237f183SYan Zheng }
13857237f183SYan Zheng 
13867237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13877237f183SYan Zheng 		       struct btrfs_root *root)
13887237f183SYan Zheng {
13890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13907237f183SYan Zheng 	struct btrfs_root *log_root;
13917237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13926ab6ebb7SNaohiro Aota 	int ret;
13937237f183SYan Zheng 
13940b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13957237f183SYan Zheng 	if (IS_ERR(log_root))
13967237f183SYan Zheng 		return PTR_ERR(log_root);
13977237f183SYan Zheng 
13986ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13996ab6ebb7SNaohiro Aota 	if (ret) {
14006ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
14016ab6ebb7SNaohiro Aota 		return ret;
14026ab6ebb7SNaohiro Aota 	}
14036ab6ebb7SNaohiro Aota 
14047237f183SYan Zheng 	log_root->last_trans = trans->transid;
14057237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14067237f183SYan Zheng 
14077237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14083cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14093cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14103cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1411da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
14120b246afaSJeff Mahoney 				     fs_info->nodesize);
14133cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14147237f183SYan Zheng 
14155d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14167237f183SYan Zheng 
14177237f183SYan Zheng 	WARN_ON(root->log_root);
14187237f183SYan Zheng 	root->log_root = log_root;
14197237f183SYan Zheng 	root->log_transid = 0;
1420d1433debSMiao Xie 	root->log_transid_committed = -1;
1421257c62e1SChris Mason 	root->last_log_commit = 0;
1422e02119d5SChris Mason 	return 0;
1423e02119d5SChris Mason }
1424e02119d5SChris Mason 
142549d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
142649d11beaSJosef Bacik 					      struct btrfs_path *path,
1427cb517eabSMiao Xie 					      struct btrfs_key *key)
1428e02119d5SChris Mason {
1429e02119d5SChris Mason 	struct btrfs_root *root;
1430e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
143184234f3aSYan Zheng 	u64 generation;
1432cb517eabSMiao Xie 	int ret;
1433581c1760SQu Wenruo 	int level;
1434cb517eabSMiao Xie 
143596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
143649d11beaSJosef Bacik 	if (!root)
143749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
14380f7d52f4SChris Mason 
1439cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1440cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14410f7d52f4SChris Mason 	if (ret) {
144213a8a7c8SYan, Zheng 		if (ret > 0)
144313a8a7c8SYan, Zheng 			ret = -ENOENT;
144449d11beaSJosef Bacik 		goto fail;
14450f7d52f4SChris Mason 	}
144613a8a7c8SYan, Zheng 
144784234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1448581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14492ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14502ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
14511b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
145264c043deSLiu Bo 	if (IS_ERR(root->node)) {
145364c043deSLiu Bo 		ret = PTR_ERR(root->node);
14548c38938cSJosef Bacik 		root->node = NULL;
145549d11beaSJosef Bacik 		goto fail;
1456cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1457cb517eabSMiao Xie 		ret = -EIO;
145849d11beaSJosef Bacik 		goto fail;
1459416bc658SJosef Bacik 	}
14605d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1461cb517eabSMiao Xie 	return root;
146249d11beaSJosef Bacik fail:
146300246528SJosef Bacik 	btrfs_put_root(root);
146449d11beaSJosef Bacik 	return ERR_PTR(ret);
146549d11beaSJosef Bacik }
146649d11beaSJosef Bacik 
146749d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
146849d11beaSJosef Bacik 					struct btrfs_key *key)
146949d11beaSJosef Bacik {
147049d11beaSJosef Bacik 	struct btrfs_root *root;
147149d11beaSJosef Bacik 	struct btrfs_path *path;
147249d11beaSJosef Bacik 
147349d11beaSJosef Bacik 	path = btrfs_alloc_path();
147449d11beaSJosef Bacik 	if (!path)
147549d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
147649d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
147749d11beaSJosef Bacik 	btrfs_free_path(path);
147849d11beaSJosef Bacik 
147949d11beaSJosef Bacik 	return root;
1480cb517eabSMiao Xie }
1481cb517eabSMiao Xie 
14822dfb1e43SQu Wenruo /*
14832dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14842dfb1e43SQu Wenruo  *
14852dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14862dfb1e43SQu Wenruo  */
14872dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1488cb517eabSMiao Xie {
1489cb517eabSMiao Xie 	int ret;
1490dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1491cb517eabSMiao Xie 
1492dcc3eb96SNikolay Borisov 	/*
1493dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1494dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1495dcc3eb96SNikolay Borisov 	 */
1496dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1497dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1498dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1499dcc3eb96SNikolay Borisov 	if (ret)
15008257b2dcSMiao Xie 		goto fail;
15018257b2dcSMiao Xie 
1502aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
150337f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
150492a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1505f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1506f39e4571SJosef Bacik 	}
1507f39e4571SJosef Bacik 
1508851fd730SQu Wenruo 	/*
1509851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1510851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1511851fd730SQu Wenruo 	 */
1512851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1513851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
15142dfb1e43SQu Wenruo 		if (!anon_dev) {
1515cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1516cb517eabSMiao Xie 			if (ret)
1517876d2cf1SLiu Bo 				goto fail;
15182dfb1e43SQu Wenruo 		} else {
15192dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
15202dfb1e43SQu Wenruo 		}
1521851fd730SQu Wenruo 	}
1522f32e48e9SChandan Rajendra 
1523f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1524453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1525f32e48e9SChandan Rajendra 	if (ret) {
1526f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1527876d2cf1SLiu Bo 		goto fail;
1528f32e48e9SChandan Rajendra 	}
1529f32e48e9SChandan Rajendra 
15306b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1531f32e48e9SChandan Rajendra 
1532f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1533f32e48e9SChandan Rajendra 
1534cb517eabSMiao Xie 	return 0;
1535cb517eabSMiao Xie fail:
153684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1537cb517eabSMiao Xie 	return ret;
1538cb517eabSMiao Xie }
1539cb517eabSMiao Xie 
1540a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1541cb517eabSMiao Xie 					       u64 root_id)
1542cb517eabSMiao Xie {
1543cb517eabSMiao Xie 	struct btrfs_root *root;
1544cb517eabSMiao Xie 
1545cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1546cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1547cb517eabSMiao Xie 				 (unsigned long)root_id);
1548bc44d7c4SJosef Bacik 	if (root)
154900246528SJosef Bacik 		root = btrfs_grab_root(root);
1550cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1551cb517eabSMiao Xie 	return root;
1552cb517eabSMiao Xie }
1553cb517eabSMiao Xie 
155449d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
155549d11beaSJosef Bacik 						u64 objectid)
155649d11beaSJosef Bacik {
155749d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
155849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
155949d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
156049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
156149d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
156249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
156349d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
156449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
156549d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
156649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
156749d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
156849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
156949d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
157049d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
157149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
157249d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
157349d11beaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
157449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
157549d11beaSJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
157649d11beaSJosef Bacik 	return NULL;
157749d11beaSJosef Bacik }
157849d11beaSJosef Bacik 
1579cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1580cb517eabSMiao Xie 			 struct btrfs_root *root)
1581cb517eabSMiao Xie {
1582cb517eabSMiao Xie 	int ret;
1583cb517eabSMiao Xie 
1584e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1585cb517eabSMiao Xie 	if (ret)
1586cb517eabSMiao Xie 		return ret;
1587cb517eabSMiao Xie 
1588cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1589cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1590cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1591cb517eabSMiao Xie 				root);
1592af01d2e5SJosef Bacik 	if (ret == 0) {
159300246528SJosef Bacik 		btrfs_grab_root(root);
159427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1595af01d2e5SJosef Bacik 	}
1596cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1597cb517eabSMiao Xie 	radix_tree_preload_end();
1598cb517eabSMiao Xie 
1599cb517eabSMiao Xie 	return ret;
1600cb517eabSMiao Xie }
1601cb517eabSMiao Xie 
1602bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1603bd647ce3SJosef Bacik {
1604bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1605bd647ce3SJosef Bacik 	struct btrfs_root *root;
1606bd647ce3SJosef Bacik 
1607bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1608457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1609457f1864SJosef Bacik 
1610bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1611bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1612457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
161371008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1614bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1615bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
161600246528SJosef Bacik 			btrfs_put_root(root);
161700246528SJosef Bacik 		btrfs_put_root(root);
1618bd647ce3SJosef Bacik 	}
1619bd647ce3SJosef Bacik #endif
1620bd647ce3SJosef Bacik }
1621bd647ce3SJosef Bacik 
16220d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
16230d4b0463SJosef Bacik {
1624141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1625141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
16265deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1627141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1628141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1629141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1630141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
16310d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16320d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
163300246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
163400246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
163500246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
163600246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
163700246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
163800246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
163900246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
164000246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
164100246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1642aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1643bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16443fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16450d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16460d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16478481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
16480d4b0463SJosef Bacik 	kvfree(fs_info);
16490d4b0463SJosef Bacik }
16500d4b0463SJosef Bacik 
16510d4b0463SJosef Bacik 
16522dfb1e43SQu Wenruo /*
16532dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
16542dfb1e43SQu Wenruo  *
16552dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
16562dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
16572dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
16582dfb1e43SQu Wenruo  *
16592dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
16602dfb1e43SQu Wenruo  *
16612dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
16622dfb1e43SQu Wenruo  *	 same root objectid.
16632dfb1e43SQu Wenruo  *
16642dfb1e43SQu Wenruo  * @objectid:	root id
16652dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
16662dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16672dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16682dfb1e43SQu Wenruo  *		for orphan roots
16692dfb1e43SQu Wenruo  */
16702dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16712dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16722dfb1e43SQu Wenruo 					     bool check_ref)
16735eda7b5eSChris Mason {
16745eda7b5eSChris Mason 	struct btrfs_root *root;
1675381cf658SDavid Sterba 	struct btrfs_path *path;
16761d4c08e0SDavid Sterba 	struct btrfs_key key;
16775eda7b5eSChris Mason 	int ret;
16785eda7b5eSChris Mason 
167949d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
168049d11beaSJosef Bacik 	if (root)
168149d11beaSJosef Bacik 		return root;
16824df27c4dSYan, Zheng again:
168356e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
168448475471SStefan Behrens 	if (root) {
16852dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16862dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1687bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
168800246528SJosef Bacik 			btrfs_put_root(root);
168948475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1690bc44d7c4SJosef Bacik 		}
16915eda7b5eSChris Mason 		return root;
169248475471SStefan Behrens 	}
16935eda7b5eSChris Mason 
169456e9357aSDavid Sterba 	key.objectid = objectid;
169556e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
169656e9357aSDavid Sterba 	key.offset = (u64)-1;
169756e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16985eda7b5eSChris Mason 	if (IS_ERR(root))
16995eda7b5eSChris Mason 		return root;
17003394e160SChris Mason 
1701c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1702d68fc57bSYan, Zheng 		ret = -ENOENT;
1703d68fc57bSYan, Zheng 		goto fail;
1704d68fc57bSYan, Zheng 	}
1705d68fc57bSYan, Zheng 
17062dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1707cb517eabSMiao Xie 	if (ret)
1708cb517eabSMiao Xie 		goto fail;
1709cb517eabSMiao Xie 
1710381cf658SDavid Sterba 	path = btrfs_alloc_path();
1711381cf658SDavid Sterba 	if (!path) {
1712381cf658SDavid Sterba 		ret = -ENOMEM;
1713381cf658SDavid Sterba 		goto fail;
1714381cf658SDavid Sterba 	}
17151d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
17161d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
171756e9357aSDavid Sterba 	key.offset = objectid;
17181d4c08e0SDavid Sterba 
17191d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1720381cf658SDavid Sterba 	btrfs_free_path(path);
1721d68fc57bSYan, Zheng 	if (ret < 0)
1722d68fc57bSYan, Zheng 		goto fail;
1723d68fc57bSYan, Zheng 	if (ret == 0)
172427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1725d68fc57bSYan, Zheng 
1726cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17270f7d52f4SChris Mason 	if (ret) {
172800246528SJosef Bacik 		btrfs_put_root(root);
17294785e24fSJosef Bacik 		if (ret == -EEXIST)
17304df27c4dSYan, Zheng 			goto again;
17314df27c4dSYan, Zheng 		goto fail;
17324df27c4dSYan, Zheng 	}
1733edbd8d4eSChris Mason 	return root;
17344df27c4dSYan, Zheng fail:
17358c38938cSJosef Bacik 	btrfs_put_root(root);
17364df27c4dSYan, Zheng 	return ERR_PTR(ret);
1737edbd8d4eSChris Mason }
1738edbd8d4eSChris Mason 
17392dfb1e43SQu Wenruo /*
17402dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
17412dfb1e43SQu Wenruo  *
17422dfb1e43SQu Wenruo  * @objectid:	tree objectid
17432dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
17442dfb1e43SQu Wenruo  *		one reference
17452dfb1e43SQu Wenruo  */
17462dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
17472dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
17482dfb1e43SQu Wenruo {
17492dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
17502dfb1e43SQu Wenruo }
17512dfb1e43SQu Wenruo 
17522dfb1e43SQu Wenruo /*
17532dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
17542dfb1e43SQu Wenruo  * the anonymous block device id
17552dfb1e43SQu Wenruo  *
17562dfb1e43SQu Wenruo  * @objectid:	tree objectid
17572dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
17582dfb1e43SQu Wenruo  *		parameter value
17592dfb1e43SQu Wenruo  */
17602dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
17612dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
17622dfb1e43SQu Wenruo {
17632dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
17642dfb1e43SQu Wenruo }
17652dfb1e43SQu Wenruo 
17668b712842SChris Mason /*
176749d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
176849d11beaSJosef Bacik  * @fs_info:	the fs_info
176949d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
177049d11beaSJosef Bacik  *
177149d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
177249d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
177349d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
177449d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
177549d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
177649d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
177749d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
177849d11beaSJosef Bacik  * backref code is finished using the root.
177949d11beaSJosef Bacik  */
178049d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
178149d11beaSJosef Bacik 						 struct btrfs_path *path,
178249d11beaSJosef Bacik 						 u64 objectid)
178349d11beaSJosef Bacik {
178449d11beaSJosef Bacik 	struct btrfs_root *root;
178549d11beaSJosef Bacik 	struct btrfs_key key;
178649d11beaSJosef Bacik 
178749d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
178849d11beaSJosef Bacik 
178949d11beaSJosef Bacik 	/*
179049d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
179149d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
179249d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
179349d11beaSJosef Bacik 	 * != NULL just return it.
179449d11beaSJosef Bacik 	 */
179549d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
179649d11beaSJosef Bacik 	if (root)
179749d11beaSJosef Bacik 		return root;
179849d11beaSJosef Bacik 
179949d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
180049d11beaSJosef Bacik 	if (root)
180149d11beaSJosef Bacik 		return root;
180249d11beaSJosef Bacik 
180349d11beaSJosef Bacik 	key.objectid = objectid;
180449d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
180549d11beaSJosef Bacik 	key.offset = (u64)-1;
180649d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
180749d11beaSJosef Bacik 	btrfs_release_path(path);
180849d11beaSJosef Bacik 
180949d11beaSJosef Bacik 	return root;
181049d11beaSJosef Bacik }
181149d11beaSJosef Bacik 
181249d11beaSJosef Bacik /*
18138b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
18148b712842SChris Mason  * functions.  This is where read checksum verification actually happens
18158b712842SChris Mason  */
18168b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1817ce9adaa5SChris Mason {
1818ce9adaa5SChris Mason 	struct bio *bio;
181997eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1820ce9adaa5SChris Mason 
182197eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1822ce9adaa5SChris Mason 	bio = end_io_wq->bio;
18238b712842SChris Mason 
18244e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1825ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1826ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
18274246a0b6SChristoph Hellwig 	bio_endio(bio);
18289be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1829ce9adaa5SChris Mason }
183044b8bd7eSChris Mason 
1831a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1832a74a4b97SChris Mason {
1833a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1835d0278245SMiao Xie 	int again;
1836a74a4b97SChris Mason 
1837d6fd0ae2SOmar Sandoval 	while (1) {
1838d0278245SMiao Xie 		again = 0;
18399d1a2a3aSDavid Sterba 
1840fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1841fd340d0fSJosef Bacik 
1842d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18432ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1844d0278245SMiao Xie 			goto sleep;
1845d0278245SMiao Xie 
184690c711abSZygo Blaxell 		/*
184790c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
184890c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
184990c711abSZygo Blaxell 		 */
18500b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
185190c711abSZygo Blaxell 			goto sleep;
185290c711abSZygo Blaxell 
18530b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1854d0278245SMiao Xie 			goto sleep;
1855d0278245SMiao Xie 
1856dc7f370cSMiao Xie 		/*
1857dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1858dc7f370cSMiao Xie 		 * during the above check and trylock.
1859dc7f370cSMiao Xie 		 */
18602ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18610b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1862dc7f370cSMiao Xie 			goto sleep;
1863dc7f370cSMiao Xie 		}
1864dc7f370cSMiao Xie 
18652ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1866c2d6cb16SFilipe Manana 
18679d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
18680b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1869a74a4b97SChris Mason 
1870d0278245SMiao Xie 		/*
187105323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
187205323cd1SMiao Xie 		 * needn't do anything special here.
1873d0278245SMiao Xie 		 */
18740b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
187567c5e7d4SFilipe Manana 
187667c5e7d4SFilipe Manana 		/*
1877f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
187867c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
187967c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1880f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
188167c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
188267c5e7d4SFilipe Manana 		 * unused block groups.
188367c5e7d4SFilipe Manana 		 */
18840b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
188518bb8bbfSJohannes Thumshirn 
188618bb8bbfSJohannes Thumshirn 		/*
188718bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
188818bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
188918bb8bbfSJohannes Thumshirn 		 * space.
189018bb8bbfSJohannes Thumshirn 		 */
189118bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1892d0278245SMiao Xie sleep:
1893a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1894d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1895d6fd0ae2SOmar Sandoval 			kthread_parkme();
1896d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1897d6fd0ae2SOmar Sandoval 			return 0;
1898838fe188SJiri Kosina 		if (!again) {
1899a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1900a74a4b97SChris Mason 			schedule();
1901a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1902a74a4b97SChris Mason 		}
1903da288d28SFilipe Manana 	}
1904a74a4b97SChris Mason }
1905a74a4b97SChris Mason 
1906a74a4b97SChris Mason static int transaction_kthread(void *arg)
1907a74a4b97SChris Mason {
1908a74a4b97SChris Mason 	struct btrfs_root *root = arg;
19090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1910a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1911a74a4b97SChris Mason 	struct btrfs_transaction *cur;
19128929ecfaSYan, Zheng 	u64 transid;
1913643900beSNikolay Borisov 	time64_t delta;
1914a74a4b97SChris Mason 	unsigned long delay;
1915914b2007SJan Kara 	bool cannot_commit;
1916a74a4b97SChris Mason 
1917a74a4b97SChris Mason 	do {
1918914b2007SJan Kara 		cannot_commit = false;
1919ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
19200b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1921a74a4b97SChris Mason 
19220b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
19230b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1924a74a4b97SChris Mason 		if (!cur) {
19250b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1926a74a4b97SChris Mason 			goto sleep;
1927a74a4b97SChris Mason 		}
192831153d81SYan Zheng 
1929643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
19303296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1931643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
19320b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1933fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1934fb8a7e94SNikolay Borisov 			delay = min(delay,
1935fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1936a74a4b97SChris Mason 			goto sleep;
1937a74a4b97SChris Mason 		}
19388929ecfaSYan, Zheng 		transid = cur->transid;
19390b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
194056bec294SChris Mason 
194179787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1942354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1943914b2007SJan Kara 		if (IS_ERR(trans)) {
1944354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1945914b2007SJan Kara 				cannot_commit = true;
194679787eaaSJeff Mahoney 			goto sleep;
1947914b2007SJan Kara 		}
19488929ecfaSYan, Zheng 		if (transid == trans->transid) {
19493a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19508929ecfaSYan, Zheng 		} else {
19513a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19528929ecfaSYan, Zheng 		}
1953a74a4b97SChris Mason sleep:
19540b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19550b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1956a74a4b97SChris Mason 
195784961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
19582ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
19598929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19600b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1961914b2007SJan Kara 				 cannot_commit))
1962bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1963a74a4b97SChris Mason 	} while (!kthread_should_stop());
1964a74a4b97SChris Mason 	return 0;
1965a74a4b97SChris Mason }
1966a74a4b97SChris Mason 
1967af31f5e5SChris Mason /*
196801f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
196901f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
197001f0f9daSNikolay Borisov  * anything.
1971af31f5e5SChris Mason  *
1972af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1973af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1974af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1975af31f5e5SChris Mason  */
197601f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1977af31f5e5SChris Mason {
197801f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1979af31f5e5SChris Mason 	u64 cur;
1980af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1981af31f5e5SChris Mason 	int i;
1982af31f5e5SChris Mason 
1983af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1984af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1985af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1986af31f5e5SChris Mason 		if (cur == newest_gen)
198701f0f9daSNikolay Borisov 			return i;
1988af31f5e5SChris Mason 	}
1989af31f5e5SChris Mason 
199001f0f9daSNikolay Borisov 	return -EINVAL;
1991af31f5e5SChris Mason }
1992af31f5e5SChris Mason 
1993af31f5e5SChris Mason /*
1994af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1995af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1996af31f5e5SChris Mason  * done
1997af31f5e5SChris Mason  */
1998af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1999af31f5e5SChris Mason {
20006ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
2001af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2002af31f5e5SChris Mason 
2003af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2004af31f5e5SChris Mason 
2005af31f5e5SChris Mason 	/*
2006af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2007af31f5e5SChris Mason 	 * regardless of which ones we use today
2008af31f5e5SChris Mason 	 */
2009af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2010af31f5e5SChris Mason 
2011af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2012af31f5e5SChris Mason 
2013af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2014af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2015af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2016af31f5e5SChris Mason 
2017af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2018af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2019af31f5e5SChris Mason 
2020af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2021af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2022af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2023af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2024af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2025af31f5e5SChris Mason 
2026af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
2027af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
2028af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
2029af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
2030af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
2031af31f5e5SChris Mason 
20327c7e82a7SChris Mason 	/*
20337c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20347c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20357c7e82a7SChris Mason 	 */
20367c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20377c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20387c7e82a7SChris Mason 					 info->fs_root->node->start);
2039af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2040af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2041af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2042af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20437c7e82a7SChris Mason 	}
2044af31f5e5SChris Mason 
2045af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2046af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2047af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2048af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2049af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2050af31f5e5SChris Mason 
2051af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
2052af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
2053af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
2054af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
2055af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
2056af31f5e5SChris Mason 
2057af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2058af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2059af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2060af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2061af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2062af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2063af31f5e5SChris Mason 
2064af31f5e5SChris Mason 	/*
2065af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2066af31f5e5SChris Mason 	 * for the next commit
2067af31f5e5SChris Mason 	 */
2068af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2069af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2070af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2071af31f5e5SChris Mason }
2072af31f5e5SChris Mason 
2073af31f5e5SChris Mason /*
2074bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2075bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2076bd2336b2SNikolay Borisov  *
2077bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2078bd2336b2SNikolay Borisov  * priority - priority of backup root required
2079bd2336b2SNikolay Borisov  *
2080bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2081bd2336b2SNikolay Borisov  */
2082bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2083bd2336b2SNikolay Borisov {
2084bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2085bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2086bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2087bd2336b2SNikolay Borisov 
2088bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2089bd2336b2SNikolay Borisov 		if (priority == 0)
2090bd2336b2SNikolay Borisov 			return backup_index;
2091bd2336b2SNikolay Borisov 
2092bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2093bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2094bd2336b2SNikolay Borisov 	} else {
2095bd2336b2SNikolay Borisov 		return -EINVAL;
2096bd2336b2SNikolay Borisov 	}
2097bd2336b2SNikolay Borisov 
2098bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2099bd2336b2SNikolay Borisov 
2100bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2101bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2102bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2103bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2104bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2105bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2106bd2336b2SNikolay Borisov 
2107bd2336b2SNikolay Borisov 	/*
2108bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2109bd2336b2SNikolay Borisov 	 * need a fsck
2110bd2336b2SNikolay Borisov 	 */
2111bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2112bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2113bd2336b2SNikolay Borisov 
2114bd2336b2SNikolay Borisov 	return backup_index;
2115bd2336b2SNikolay Borisov }
2116bd2336b2SNikolay Borisov 
21177abadb64SLiu Bo /* helper to cleanup workers */
21187abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
21197abadb64SLiu Bo {
2120dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2121afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
21225cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2123fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2124fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2125d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2126fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2127fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
21285b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2129e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2130736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2131a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2132fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2133b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2134b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2135a9b9477dSFilipe Manana 	/*
2136a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2137a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2138a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2139a9b9477dSFilipe Manana 	 */
2140a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2141a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
21427abadb64SLiu Bo }
21437abadb64SLiu Bo 
21442e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21452e9f5954SRashika {
21462e9f5954SRashika 	if (root) {
21472e9f5954SRashika 		free_extent_buffer(root->node);
21482e9f5954SRashika 		free_extent_buffer(root->commit_root);
21492e9f5954SRashika 		root->node = NULL;
21502e9f5954SRashika 		root->commit_root = NULL;
21512e9f5954SRashika 	}
21522e9f5954SRashika }
21532e9f5954SRashika 
2154af31f5e5SChris Mason /* helper to cleanup tree roots */
21554273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2156af31f5e5SChris Mason {
21572e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2158655b09feSJosef Bacik 
21592e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21602e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
21612e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
21622e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21632e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21648c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2165aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
21664273eaffSAnand Jain 	if (free_chunk_root)
21672e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
216870f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2169af31f5e5SChris Mason }
2170af31f5e5SChris Mason 
21718c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
21728c38938cSJosef Bacik {
21738c38938cSJosef Bacik 	if (!root)
21748c38938cSJosef Bacik 		return;
21758c38938cSJosef Bacik 
21768c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21778c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21781dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21798c38938cSJosef Bacik 		if (root->anon_dev)
21808c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21818c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2182923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21838c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
21848c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21858c38938cSJosef Bacik 		list_del_init(&root->leak_list);
21868c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21878c38938cSJosef Bacik #endif
21888c38938cSJosef Bacik 		kfree(root);
21898c38938cSJosef Bacik 	}
21908c38938cSJosef Bacik }
21918c38938cSJosef Bacik 
2192faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2193171f6537SJosef Bacik {
2194171f6537SJosef Bacik 	int ret;
2195171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2196171f6537SJosef Bacik 	int i;
2197171f6537SJosef Bacik 
2198171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2199171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2200171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2201171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2202171f6537SJosef Bacik 
22038c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2204cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
220500246528SJosef Bacik 		btrfs_put_root(gang[0]);
2206171f6537SJosef Bacik 	}
2207171f6537SJosef Bacik 
2208171f6537SJosef Bacik 	while (1) {
2209171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2210171f6537SJosef Bacik 					     (void **)gang, 0,
2211171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2212171f6537SJosef Bacik 		if (!ret)
2213171f6537SJosef Bacik 			break;
2214171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2215cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2216171f6537SJosef Bacik 	}
2217171f6537SJosef Bacik }
2218af31f5e5SChris Mason 
2219638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2220638aa7edSEric Sandeen {
2221638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2222638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2223638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2224638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2225638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2226638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2227ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2228638aa7edSEric Sandeen }
2229638aa7edSEric Sandeen 
2230779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2231779a65a4SEric Sandeen {
2232779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2233779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2234779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2235779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2236779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2237779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2238907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2239779a65a4SEric Sandeen }
2240779a65a4SEric Sandeen 
22416bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2242f37938e0SEric Sandeen {
22432ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
22442ff7e61eSJeff Mahoney 
22452ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
22462ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2247f37938e0SEric Sandeen 	/*
2248f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2249f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2250f37938e0SEric Sandeen 	 * the devices in the system
2251f37938e0SEric Sandeen 	 */
22522ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
22532ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2254f37938e0SEric Sandeen 
22552ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
225643eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
22572c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
22587b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
22592ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2260f37938e0SEric Sandeen 
22615c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
22622ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
22632ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
22642ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2265f37938e0SEric Sandeen }
2266f37938e0SEric Sandeen 
2267ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2268ad618368SEric Sandeen {
2269ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2270129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
22717f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2272ad618368SEric Sandeen }
2273ad618368SEric Sandeen 
2274f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2275f9e92e40SEric Sandeen {
2276f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2277f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2278f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2279f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2280f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2281f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2282d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2283f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2284f9e92e40SEric Sandeen }
2285f9e92e40SEric Sandeen 
22862a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
22872a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
22882a458198SEric Sandeen {
2289f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22906f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22912a458198SEric Sandeen 
22922a458198SEric Sandeen 	fs_info->workers =
2293cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2294cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22952a458198SEric Sandeen 
22962a458198SEric Sandeen 	fs_info->delalloc_workers =
2297cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2298cb001095SJeff Mahoney 				      flags, max_active, 2);
22992a458198SEric Sandeen 
23002a458198SEric Sandeen 	fs_info->flush_workers =
2301cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2302cb001095SJeff Mahoney 				      flags, max_active, 0);
23032a458198SEric Sandeen 
23042a458198SEric Sandeen 	fs_info->caching_workers =
2305cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
23062a458198SEric Sandeen 
23072a458198SEric Sandeen 	fs_info->fixup_workers =
2308cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23092a458198SEric Sandeen 
23102a458198SEric Sandeen 	/*
23112a458198SEric Sandeen 	 * endios are largely parallel and should have a very
23122a458198SEric Sandeen 	 * low idle thresh
23132a458198SEric Sandeen 	 */
23142a458198SEric Sandeen 	fs_info->endio_workers =
2315cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
23162a458198SEric Sandeen 	fs_info->endio_meta_workers =
2317cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2318cb001095SJeff Mahoney 				      max_active, 4);
23192a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2320cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2321cb001095SJeff Mahoney 				      max_active, 2);
23222a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2323cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2324cb001095SJeff Mahoney 				      max_active, 4);
23252a458198SEric Sandeen 	fs_info->rmw_workers =
2326cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
23272a458198SEric Sandeen 	fs_info->endio_write_workers =
2328cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2329cb001095SJeff Mahoney 				      max_active, 2);
23302a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2331cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2332cb001095SJeff Mahoney 				      max_active, 0);
23332a458198SEric Sandeen 	fs_info->delayed_workers =
2334cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2335cb001095SJeff Mahoney 				      max_active, 0);
23362a458198SEric Sandeen 	fs_info->readahead_workers =
2337cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2338cb001095SJeff Mahoney 				      max_active, 2);
23392a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2340cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2341b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2342b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23432a458198SEric Sandeen 
23442a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2345ba8a9d07SChris Mason 	      fs_info->flush_workers &&
23462a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
23472a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
23482a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
23492a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
23502a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
23512a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2352b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2353b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
23542a458198SEric Sandeen 		return -ENOMEM;
23552a458198SEric Sandeen 	}
23562a458198SEric Sandeen 
23572a458198SEric Sandeen 	return 0;
23582a458198SEric Sandeen }
23592a458198SEric Sandeen 
23606d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
23616d97c6e3SJohannes Thumshirn {
23626d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2363b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
23646d97c6e3SJohannes Thumshirn 
2365b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
23666d97c6e3SJohannes Thumshirn 
23676d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
23686d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2369b4e967beSDavid Sterba 			  csum_driver);
23706d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
23716d97c6e3SJohannes Thumshirn 	}
23726d97c6e3SJohannes Thumshirn 
23736d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23746d97c6e3SJohannes Thumshirn 
23756d97c6e3SJohannes Thumshirn 	return 0;
23766d97c6e3SJohannes Thumshirn }
23776d97c6e3SJohannes Thumshirn 
237863443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
237963443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
238063443bf5SEric Sandeen {
238163443bf5SEric Sandeen 	int ret;
238263443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
238363443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
238463443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2385581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
238663443bf5SEric Sandeen 
238763443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2388f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
238963443bf5SEric Sandeen 		return -EIO;
239063443bf5SEric Sandeen 	}
239163443bf5SEric Sandeen 
239296dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
239396dfcb46SJosef Bacik 					 GFP_KERNEL);
239463443bf5SEric Sandeen 	if (!log_tree_root)
239563443bf5SEric Sandeen 		return -ENOMEM;
239663443bf5SEric Sandeen 
23972ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
23981b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
23991b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
24001b7ec85eSJosef Bacik 					      NULL);
240164c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2402f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
24030eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
24048c38938cSJosef Bacik 		log_tree_root->node = NULL;
240500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
24060eeff236SLiu Bo 		return ret;
240764c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2408f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
240900246528SJosef Bacik 		btrfs_put_root(log_tree_root);
241063443bf5SEric Sandeen 		return -EIO;
241163443bf5SEric Sandeen 	}
241263443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
241363443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
241463443bf5SEric Sandeen 	if (ret) {
24150b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
241663443bf5SEric Sandeen 				      "Failed to recover log tree");
241700246528SJosef Bacik 		btrfs_put_root(log_tree_root);
241863443bf5SEric Sandeen 		return ret;
241963443bf5SEric Sandeen 	}
242063443bf5SEric Sandeen 
2421bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
24226bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
242363443bf5SEric Sandeen 		if (ret)
242463443bf5SEric Sandeen 			return ret;
242563443bf5SEric Sandeen 	}
242663443bf5SEric Sandeen 
242763443bf5SEric Sandeen 	return 0;
242863443bf5SEric Sandeen }
242963443bf5SEric Sandeen 
24306bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
24314bbcaa64SEric Sandeen {
24326bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2433a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
24344bbcaa64SEric Sandeen 	struct btrfs_key location;
24354bbcaa64SEric Sandeen 	int ret;
24364bbcaa64SEric Sandeen 
24376bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
24386bccf3abSJeff Mahoney 
24394bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
24404bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
24414bbcaa64SEric Sandeen 	location.offset = 0;
24424bbcaa64SEric Sandeen 
2443a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2444f50f4353SLiu Bo 	if (IS_ERR(root)) {
244542437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2446f50f4353SLiu Bo 			ret = PTR_ERR(root);
2447f50f4353SLiu Bo 			goto out;
2448f50f4353SLiu Bo 		}
244942437a63SJosef Bacik 	} else {
2450a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2451a4f3d2c4SDavid Sterba 		fs_info->extent_root = root;
245242437a63SJosef Bacik 	}
24534bbcaa64SEric Sandeen 
24544bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2455a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2456f50f4353SLiu Bo 	if (IS_ERR(root)) {
245742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2458f50f4353SLiu Bo 			ret = PTR_ERR(root);
2459f50f4353SLiu Bo 			goto out;
2460f50f4353SLiu Bo 		}
246142437a63SJosef Bacik 	} else {
2462a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2463a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
246442437a63SJosef Bacik 	}
2465820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2466820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
24674bbcaa64SEric Sandeen 
2468882dbe0cSJosef Bacik 	/* If IGNOREDATACSUMS is set don't bother reading the csum root. */
2469882dbe0cSJosef Bacik 	if (!btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
24704bbcaa64SEric Sandeen 		location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2471a4f3d2c4SDavid Sterba 		root = btrfs_read_tree_root(tree_root, &location);
2472f50f4353SLiu Bo 		if (IS_ERR(root)) {
247342437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2474f50f4353SLiu Bo 				ret = PTR_ERR(root);
2475f50f4353SLiu Bo 				goto out;
2476f50f4353SLiu Bo 			}
247742437a63SJosef Bacik 		} else {
2478a4f3d2c4SDavid Sterba 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2479a4f3d2c4SDavid Sterba 			fs_info->csum_root = root;
248042437a63SJosef Bacik 		}
2481882dbe0cSJosef Bacik 	}
24824bbcaa64SEric Sandeen 
2483aeb935a4SQu Wenruo 	/*
2484aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2485aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2486aeb935a4SQu Wenruo 	 */
248756e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
248856e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2489aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
249042437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2491aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2492aeb935a4SQu Wenruo 			goto out;
2493aeb935a4SQu Wenruo 		}
249442437a63SJosef Bacik 	} else {
2495aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2496aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
249742437a63SJosef Bacik 	}
2498aeb935a4SQu Wenruo 
24994bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2500a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2501a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2502a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2503afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2504a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25054bbcaa64SEric Sandeen 	}
25064bbcaa64SEric Sandeen 
25074bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2508a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2509a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
251042437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2511a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25124bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2513f50f4353SLiu Bo 				goto out;
251442437a63SJosef Bacik 		}
25154bbcaa64SEric Sandeen 	} else {
2516a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2517a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25184bbcaa64SEric Sandeen 	}
25194bbcaa64SEric Sandeen 
252070f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
252170f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
252270f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2523f50f4353SLiu Bo 		if (IS_ERR(root)) {
252442437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2525f50f4353SLiu Bo 				ret = PTR_ERR(root);
2526f50f4353SLiu Bo 				goto out;
2527f50f4353SLiu Bo 			}
252842437a63SJosef Bacik 		}  else {
252970f6d82eSOmar Sandoval 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
253070f6d82eSOmar Sandoval 			fs_info->free_space_root = root;
253170f6d82eSOmar Sandoval 		}
253242437a63SJosef Bacik 	}
253370f6d82eSOmar Sandoval 
25344bbcaa64SEric Sandeen 	return 0;
2535f50f4353SLiu Bo out:
2536f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2537f50f4353SLiu Bo 		   location.objectid, ret);
2538f50f4353SLiu Bo 	return ret;
25394bbcaa64SEric Sandeen }
25404bbcaa64SEric Sandeen 
2541069ec957SQu Wenruo /*
2542069ec957SQu Wenruo  * Real super block validation
2543069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2544069ec957SQu Wenruo  *
2545069ec957SQu Wenruo  * @sb:		super block to check
2546069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2547069ec957SQu Wenruo  * 		0	the primary (1st) sb
2548069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2549069ec957SQu Wenruo  * 	       -1	skip bytenr check
2550069ec957SQu Wenruo  */
2551069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2552069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
255321a852b0SQu Wenruo {
255421a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
255521a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
255621a852b0SQu Wenruo 	int ret = 0;
255721a852b0SQu Wenruo 
255821a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
255921a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
256021a852b0SQu Wenruo 		ret = -EINVAL;
256121a852b0SQu Wenruo 	}
256221a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
256321a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
256421a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
256521a852b0SQu Wenruo 		ret = -EINVAL;
256621a852b0SQu Wenruo 	}
256721a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
256821a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
256921a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
257021a852b0SQu Wenruo 		ret = -EINVAL;
257121a852b0SQu Wenruo 	}
257221a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
257321a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
257421a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
257521a852b0SQu Wenruo 		ret = -EINVAL;
257621a852b0SQu Wenruo 	}
257721a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
257821a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
257921a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
258021a852b0SQu Wenruo 		ret = -EINVAL;
258121a852b0SQu Wenruo 	}
258221a852b0SQu Wenruo 
258321a852b0SQu Wenruo 	/*
258421a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
258521a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
258621a852b0SQu Wenruo 	 */
258721a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
258821a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
258921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
259021a852b0SQu Wenruo 		ret = -EINVAL;
259121a852b0SQu Wenruo 	}
25920bb3eb3eSQu Wenruo 
25930bb3eb3eSQu Wenruo 	/*
25940bb3eb3eSQu Wenruo 	 * For 4K page size, we only support 4K sector size.
259550780d9bSAnand Jain 	 * For 64K page size, we support 64K and 4K sector sizes.
25960bb3eb3eSQu Wenruo 	 */
25970bb3eb3eSQu Wenruo 	if ((PAGE_SIZE == SZ_4K && sectorsize != PAGE_SIZE) ||
25980bb3eb3eSQu Wenruo 	    (PAGE_SIZE == SZ_64K && (sectorsize != SZ_4K &&
25990bb3eb3eSQu Wenruo 				     sectorsize != SZ_64K))) {
260021a852b0SQu Wenruo 		btrfs_err(fs_info,
26010bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
260221a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
260321a852b0SQu Wenruo 		ret = -EINVAL;
260421a852b0SQu Wenruo 	}
26050bb3eb3eSQu Wenruo 
260621a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
260721a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
260821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
260921a852b0SQu Wenruo 		ret = -EINVAL;
261021a852b0SQu Wenruo 	}
261121a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
261221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
261321a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
261421a852b0SQu Wenruo 		ret = -EINVAL;
261521a852b0SQu Wenruo 	}
261621a852b0SQu Wenruo 
261721a852b0SQu Wenruo 	/* Root alignment check */
261821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
261921a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
262021a852b0SQu Wenruo 			   btrfs_super_root(sb));
262121a852b0SQu Wenruo 		ret = -EINVAL;
262221a852b0SQu Wenruo 	}
262321a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
262421a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
262521a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
262621a852b0SQu Wenruo 		ret = -EINVAL;
262721a852b0SQu Wenruo 	}
262821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
262921a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
263021a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
263121a852b0SQu Wenruo 		ret = -EINVAL;
263221a852b0SQu Wenruo 	}
263321a852b0SQu Wenruo 
2634aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2635aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2636aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2637aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2638aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2639aefd7f70SNikolay Borisov 		ret = -EINVAL;
2640aefd7f70SNikolay Borisov 	}
2641aefd7f70SNikolay Borisov 
2642aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2643aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2644aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2645aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2646aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2647aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2648aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2649aefd7f70SNikolay Borisov 		ret = -EINVAL;
2650aefd7f70SNikolay Borisov 	}
2651aefd7f70SNikolay Borisov 
2652de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
26537239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
265421a852b0SQu Wenruo 		btrfs_err(fs_info,
26557239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2656de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
265721a852b0SQu Wenruo 		ret = -EINVAL;
265821a852b0SQu Wenruo 	}
265921a852b0SQu Wenruo 
266021a852b0SQu Wenruo 	/*
266121a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
266221a852b0SQu Wenruo 	 * done later
266321a852b0SQu Wenruo 	 */
266421a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
266521a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
266621a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
266721a852b0SQu Wenruo 		ret = -EINVAL;
266821a852b0SQu Wenruo 	}
266921a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
267021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
267121a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
267221a852b0SQu Wenruo 		ret = -EINVAL;
267321a852b0SQu Wenruo 	}
267421a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
267521a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
267621a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
267721a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
267821a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
267921a852b0SQu Wenruo 		ret = -EINVAL;
268021a852b0SQu Wenruo 	}
268121a852b0SQu Wenruo 
2682069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2683069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
268421a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
268521a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
268621a852b0SQu Wenruo 		ret = -EINVAL;
268721a852b0SQu Wenruo 	}
268821a852b0SQu Wenruo 
268921a852b0SQu Wenruo 	/*
269021a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
269121a852b0SQu Wenruo 	 * and one chunk
269221a852b0SQu Wenruo 	 */
269321a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
269421a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
269521a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
269621a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
269721a852b0SQu Wenruo 		ret = -EINVAL;
269821a852b0SQu Wenruo 	}
269921a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
270021a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
270121a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
270221a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
270321a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
270421a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
270521a852b0SQu Wenruo 		ret = -EINVAL;
270621a852b0SQu Wenruo 	}
270721a852b0SQu Wenruo 
270821a852b0SQu Wenruo 	/*
270921a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
271021a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
271121a852b0SQu Wenruo 	 */
271221a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
271321a852b0SQu Wenruo 		btrfs_warn(fs_info,
271421a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
271521a852b0SQu Wenruo 			btrfs_super_generation(sb),
271621a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
271721a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
271821a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
271921a852b0SQu Wenruo 		btrfs_warn(fs_info,
272021a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
272121a852b0SQu Wenruo 			btrfs_super_generation(sb),
272221a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
272321a852b0SQu Wenruo 
272421a852b0SQu Wenruo 	return ret;
272521a852b0SQu Wenruo }
272621a852b0SQu Wenruo 
2727069ec957SQu Wenruo /*
2728069ec957SQu Wenruo  * Validation of super block at mount time.
2729069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2730069ec957SQu Wenruo  * flags will be skipped.
2731069ec957SQu Wenruo  */
2732069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2733069ec957SQu Wenruo {
2734069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2735069ec957SQu Wenruo }
2736069ec957SQu Wenruo 
273775cb857dSQu Wenruo /*
273875cb857dSQu Wenruo  * Validation of super block at write time.
273975cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
274075cb857dSQu Wenruo  * overwritten soon.
274175cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
274275cb857dSQu Wenruo  */
274375cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
274475cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
274575cb857dSQu Wenruo {
274675cb857dSQu Wenruo 	int ret;
274775cb857dSQu Wenruo 
274875cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
274975cb857dSQu Wenruo 	if (ret < 0)
275075cb857dSQu Wenruo 		goto out;
2751e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
275275cb857dSQu Wenruo 		ret = -EUCLEAN;
275375cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
275475cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
275575cb857dSQu Wenruo 		goto out;
275675cb857dSQu Wenruo 	}
275775cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
275875cb857dSQu Wenruo 		ret = -EUCLEAN;
275975cb857dSQu Wenruo 		btrfs_err(fs_info,
276075cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
276175cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
276275cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
276375cb857dSQu Wenruo 		goto out;
276475cb857dSQu Wenruo 	}
276575cb857dSQu Wenruo out:
276675cb857dSQu Wenruo 	if (ret < 0)
276775cb857dSQu Wenruo 		btrfs_err(fs_info,
276875cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
276975cb857dSQu Wenruo 	return ret;
277075cb857dSQu Wenruo }
277175cb857dSQu Wenruo 
27726ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2773b8522a1eSNikolay Borisov {
27746ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2775b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2776b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2777b8522a1eSNikolay Borisov 	bool handle_error = false;
2778b8522a1eSNikolay Borisov 	int ret = 0;
2779b8522a1eSNikolay Borisov 	int i;
2780b8522a1eSNikolay Borisov 
2781b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2782b8522a1eSNikolay Borisov 		u64 generation;
2783b8522a1eSNikolay Borisov 		int level;
2784b8522a1eSNikolay Borisov 
2785b8522a1eSNikolay Borisov 		if (handle_error) {
2786b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2787b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2788b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2789b8522a1eSNikolay Borisov 
2790b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2791b8522a1eSNikolay Borisov 				break;
2792b8522a1eSNikolay Borisov 
2793b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2794b8522a1eSNikolay Borisov 
2795b8522a1eSNikolay Borisov 			/*
2796b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2797b8522a1eSNikolay Borisov 			 * valid
2798b8522a1eSNikolay Borisov 			 */
2799b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2800b8522a1eSNikolay Borisov 
2801b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2802b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2803b8522a1eSNikolay Borisov 
2804b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
28056ef108ddSNikolay Borisov 			backup_index = ret;
2806b8522a1eSNikolay Borisov 			if (ret < 0)
2807b8522a1eSNikolay Borisov 				return ret;
2808b8522a1eSNikolay Borisov 		}
2809b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2810b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2811b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
28121b7ec85eSJosef Bacik 						  BTRFS_ROOT_TREE_OBJECTID,
2813b8522a1eSNikolay Borisov 						  generation, level, NULL);
28140465337cSJosef Bacik 		if (IS_ERR(tree_root->node)) {
2815217f5004SNikolay Borisov 			handle_error = true;
2816b8522a1eSNikolay Borisov 			ret = PTR_ERR(tree_root->node);
28170465337cSJosef Bacik 			tree_root->node = NULL;
2818217f5004SNikolay Borisov 			btrfs_warn(fs_info, "couldn't read tree root");
2819217f5004SNikolay Borisov 			continue;
2820b8522a1eSNikolay Borisov 
2821217f5004SNikolay Borisov 		} else if (!extent_buffer_uptodate(tree_root->node)) {
2822217f5004SNikolay Borisov 			handle_error = true;
2823217f5004SNikolay Borisov 			ret = -EIO;
2824217f5004SNikolay Borisov 			btrfs_warn(fs_info, "error while reading tree root");
2825b8522a1eSNikolay Borisov 			continue;
2826b8522a1eSNikolay Borisov 		}
2827b8522a1eSNikolay Borisov 
2828b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2829b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2830b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2831b8522a1eSNikolay Borisov 
2832336a0d8dSNikolay Borisov 		/*
2833336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2834336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2835336a0d8dSNikolay Borisov 		 */
2836453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2837b8522a1eSNikolay Borisov 		if (ret < 0) {
2838b8522a1eSNikolay Borisov 			handle_error = true;
2839b8522a1eSNikolay Borisov 			continue;
2840b8522a1eSNikolay Borisov 		}
2841b8522a1eSNikolay Borisov 
28426b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2843b8522a1eSNikolay Borisov 
2844b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2845b8522a1eSNikolay Borisov 		if (ret < 0) {
2846b8522a1eSNikolay Borisov 			handle_error = true;
2847b8522a1eSNikolay Borisov 			continue;
2848b8522a1eSNikolay Borisov 		}
2849b8522a1eSNikolay Borisov 
2850b8522a1eSNikolay Borisov 		/* All successful */
2851b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2852b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
28536ef108ddSNikolay Borisov 
28546ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
28556ef108ddSNikolay Borisov 		if (backup_index < 0) {
28566ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
28576ef108ddSNikolay Borisov 		} else {
28586ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
28596ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
28606ef108ddSNikolay Borisov 		}
2861b8522a1eSNikolay Borisov 		break;
2862b8522a1eSNikolay Borisov 	}
2863b8522a1eSNikolay Borisov 
2864b8522a1eSNikolay Borisov 	return ret;
2865b8522a1eSNikolay Borisov }
2866b8522a1eSNikolay Borisov 
28678260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2868eb60ceacSChris Mason {
286976dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2870f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
28718fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2872facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
287324bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2874eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
287511833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2876eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2877a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
287876dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
287924bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
28804cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2881ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2882f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
288347ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
288440ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2885afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2886c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2887f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2888d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2889f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
28907585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2891573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
28920bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
2893de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
289419c00ddcSChris Mason 
28950b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
28966324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2897f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
289847ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
289918bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2900afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2901bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2902bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
29033fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
29043fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2905bd647ce3SJosef Bacik #endif
2906c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
290766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
290866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
290966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
291066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
291166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
291266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
291366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2914ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2915ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2916ba2c4d4eSJosef Bacik 
2917771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
29184cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
29192fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2920034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2921fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
292295ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
29239ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
29244cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2925a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2926f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
29278b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2928f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
292990519d66SArne Jansen 	/* readahead state */
2930d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
293190519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2932fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2933c8b97818SChris Mason 
2934b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2935b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
29360afbaf8cSChris Mason 
2937199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2938199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
293969fe2d75SJosef Bacik 
2940638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
294121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
294221adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
294321adbd5cSStefan Behrens #endif
2944779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
294557056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2946a2de733cSArne Jansen 
29470f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
29486bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2949a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
29500f9dd46cSJosef Bacik 
2951fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2952fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2953afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
295439279cc3SChris Mason 
29555a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2956e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2957925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2958a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2959a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
29601bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
29619e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2962c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
296376dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2964803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2965fa9c0d79SChris Mason 
2966ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2967f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2968b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2969416ac51dSArne Jansen 
2970fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2971fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2972fa9c0d79SChris Mason 
2973e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2974f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2975bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
29764854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2977034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
29783768f368SChris Mason 
2979da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2980da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2981da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2982ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2983da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2984da17066cSJeff Mahoney 
2985eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2986eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2987eede2bf3SOmar Sandoval 
29881cea5cf0SFilipe Manana 	spin_lock_init(&fs_info->send_reloc_lock);
29899e967495SFilipe Manana 	fs_info->send_in_progress = 0;
299018bb8bbfSJohannes Thumshirn 
299118bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
299218bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
29938260edbaSJosef Bacik }
29948260edbaSJosef Bacik 
29958260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
29968260edbaSJosef Bacik {
29978260edbaSJosef Bacik 	int ret;
29988260edbaSJosef Bacik 
29998260edbaSJosef Bacik 	fs_info->sb = sb;
30008260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
30018260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
30029e967495SFilipe Manana 
30035deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3004ae18c37aSJosef Bacik 	if (ret)
3005ae18c37aSJosef Bacik 		return ret;
3006ae18c37aSJosef Bacik 
3007ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3008ae18c37aSJosef Bacik 	if (ret)
3009c75e8394SJosef Bacik 		return ret;
3010ae18c37aSJosef Bacik 
3011ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3012ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3013ae18c37aSJosef Bacik 
3014ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3015ae18c37aSJosef Bacik 	if (ret)
3016c75e8394SJosef Bacik 		return ret;
3017ae18c37aSJosef Bacik 
3018ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3019ae18c37aSJosef Bacik 			GFP_KERNEL);
3020ae18c37aSJosef Bacik 	if (ret)
3021c75e8394SJosef Bacik 		return ret;
3022ae18c37aSJosef Bacik 
3023ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3024ae18c37aSJosef Bacik 					GFP_KERNEL);
3025c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3026c75e8394SJosef Bacik 		return -ENOMEM;
3027ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3028ae18c37aSJosef Bacik 
3029a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3030a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3031a0a1db70SFilipe Manana 
3032c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3033ae18c37aSJosef Bacik }
3034ae18c37aSJosef Bacik 
303597f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
303697f4dd09SNikolay Borisov {
303797f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
303897f4dd09SNikolay Borisov 	int ret;
303997f4dd09SNikolay Borisov 
304097f4dd09SNikolay Borisov 	/*
304197f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
304297f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
304397f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
304497f4dd09SNikolay Borisov 	 */
304597f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
304697f4dd09SNikolay Borisov 	if (ret < 0) {
3047c94bec2cSJosef Bacik 		if (ret != -EINTR)
3048c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3049c94bec2cSJosef Bacik 				   ret);
305097f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
305197f4dd09SNikolay Borisov 		return ret;
305297f4dd09SNikolay Borisov 	}
305397f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
305497f4dd09SNikolay Borisov }
305597f4dd09SNikolay Borisov 
305697f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
305797f4dd09SNikolay Borisov {
305897f4dd09SNikolay Borisov 	struct task_struct *task;
305997f4dd09SNikolay Borisov 
306097f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
306197f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
306297f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
306397f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
306497f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
306597f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
306697f4dd09SNikolay Borisov 		return PTR_ERR(task);
306797f4dd09SNikolay Borisov 	}
306897f4dd09SNikolay Borisov 
306997f4dd09SNikolay Borisov 	return 0;
307097f4dd09SNikolay Borisov }
307197f4dd09SNikolay Borisov 
307244c0ca21SBoris Burkov /*
30738cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
30748cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
30758cd29088SBoris Burkov  * code paths.
30768cd29088SBoris Burkov  */
30778cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
30788cd29088SBoris Burkov {
30798cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
30808b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
30818cd29088SBoris Burkov }
30828cd29088SBoris Burkov 
30838cd29088SBoris Burkov /*
308444c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
308544c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
308644c0ca21SBoris Burkov  */
308744c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
308844c0ca21SBoris Burkov {
308944c0ca21SBoris Burkov 	int ret;
309094846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
30918b228324SBoris Burkov 	bool clear_free_space_tree = false;
30928b228324SBoris Burkov 
30938b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
30948b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
30958b228324SBoris Burkov 		clear_free_space_tree = true;
30968b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
30978b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
30988b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
30998b228324SBoris Burkov 		clear_free_space_tree = true;
31008b228324SBoris Burkov 	}
31018b228324SBoris Burkov 
31028b228324SBoris Burkov 	if (clear_free_space_tree) {
31038b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
31048b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
31058b228324SBoris Burkov 		if (ret) {
31068b228324SBoris Burkov 			btrfs_warn(fs_info,
31078b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
31088b228324SBoris Burkov 			goto out;
31098b228324SBoris Burkov 		}
31108b228324SBoris Burkov 	}
311144c0ca21SBoris Burkov 
31128d488a8cSFilipe Manana 	/*
31138d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
31148d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
31158d488a8cSFilipe Manana 	 * them into the fs_info->fs_roots_radix tree. This must be done before
31168d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
31178d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
31188d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
31198d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
31208d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
31218d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
31228d488a8cSFilipe Manana 	 */
31238d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
31248d488a8cSFilipe Manana 	if (ret)
31258d488a8cSFilipe Manana 		goto out;
31268d488a8cSFilipe Manana 
312744c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
312844c0ca21SBoris Burkov 	if (ret)
312944c0ca21SBoris Burkov 		goto out;
313044c0ca21SBoris Burkov 
31318f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
31328f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31338f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31348f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
31358f1c21d7SBoris Burkov 		goto out;
31368f1c21d7SBoris Burkov 	}
31378f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
31388f1c21d7SBoris Burkov 
313944c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
314044c0ca21SBoris Burkov 	ret = btrfs_recover_relocation(fs_info->tree_root);
314144c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
314244c0ca21SBoris Burkov 	if (ret < 0) {
314344c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
314444c0ca21SBoris Burkov 		goto out;
314544c0ca21SBoris Burkov 	}
314644c0ca21SBoris Burkov 
31475011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
31485011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31495011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
31505011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
31515011139aSBoris Burkov 		if (ret) {
31525011139aSBoris Burkov 			btrfs_warn(fs_info,
31535011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
31545011139aSBoris Burkov 			goto out;
31555011139aSBoris Burkov 		}
31565011139aSBoris Burkov 	}
31575011139aSBoris Burkov 
315894846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
315994846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
316094846229SBoris Burkov 		if (ret)
316194846229SBoris Burkov 			goto out;
316294846229SBoris Burkov 	}
316394846229SBoris Burkov 
316444c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
316544c0ca21SBoris Burkov 	if (ret)
316644c0ca21SBoris Burkov 		goto out;
316744c0ca21SBoris Burkov 
316844c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
316944c0ca21SBoris Burkov 	if (ret) {
317044c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
317144c0ca21SBoris Burkov 		goto out;
317244c0ca21SBoris Burkov 	}
317344c0ca21SBoris Burkov 
317444c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
317544c0ca21SBoris Burkov 
317644c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
317744c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
317844c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
317944c0ca21SBoris Burkov 		if (ret) {
318044c0ca21SBoris Burkov 			btrfs_warn(fs_info,
318144c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
318244c0ca21SBoris Burkov 			goto out;
318344c0ca21SBoris Burkov 		}
318444c0ca21SBoris Burkov 	}
318544c0ca21SBoris Burkov 
318644c0ca21SBoris Burkov out:
318744c0ca21SBoris Burkov 	return ret;
318844c0ca21SBoris Burkov }
318944c0ca21SBoris Burkov 
3190ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3191ae18c37aSJosef Bacik 		      char *options)
3192ae18c37aSJosef Bacik {
3193ae18c37aSJosef Bacik 	u32 sectorsize;
3194ae18c37aSJosef Bacik 	u32 nodesize;
3195ae18c37aSJosef Bacik 	u32 stripesize;
3196ae18c37aSJosef Bacik 	u64 generation;
3197ae18c37aSJosef Bacik 	u64 features;
3198ae18c37aSJosef Bacik 	u16 csum_type;
3199ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3200ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3201ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3202ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3203ae18c37aSJosef Bacik 	int ret;
3204ae18c37aSJosef Bacik 	int err = -EINVAL;
3205ae18c37aSJosef Bacik 	int level;
3206ae18c37aSJosef Bacik 
32078260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
320853b381b3SDavid Woodhouse 	if (ret) {
320983c8266aSDavid Sterba 		err = ret;
3210ae18c37aSJosef Bacik 		goto fail;
321153b381b3SDavid Woodhouse 	}
321253b381b3SDavid Woodhouse 
3213ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3214ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3215ae18c37aSJosef Bacik 				     GFP_KERNEL);
3216ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3217ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3218ae18c37aSJosef Bacik 				      GFP_KERNEL);
3219ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3220ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3221ae18c37aSJosef Bacik 		err = -ENOMEM;
3222c75e8394SJosef Bacik 		goto fail;
3223ae18c37aSJosef Bacik 	}
3224ae18c37aSJosef Bacik 
3225ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3226ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3227ae18c37aSJosef Bacik 		err = -ENOMEM;
3228c75e8394SJosef Bacik 		goto fail;
3229ae18c37aSJosef Bacik 	}
3230ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3231ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3232ae18c37aSJosef Bacik 
3233d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
32341104a885SDavid Sterba 
32351104a885SDavid Sterba 	/*
32361104a885SDavid Sterba 	 * Read super block and check the signature bytes only
32371104a885SDavid Sterba 	 */
3238d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
32398f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
32408f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
324116cdcec7SMiao Xie 		goto fail_alloc;
324220b45077SDave Young 	}
324339279cc3SChris Mason 
32441104a885SDavid Sterba 	/*
3245260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
32468dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
32478dc3f22cSJohannes Thumshirn 	 */
32488f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
324951bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
32508dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
325151bce6c9SJohannes Thumshirn 			  csum_type);
32528dc3f22cSJohannes Thumshirn 		err = -EINVAL;
32538f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32548dc3f22cSJohannes Thumshirn 		goto fail_alloc;
32558dc3f22cSJohannes Thumshirn 	}
32568dc3f22cSJohannes Thumshirn 
325783c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
325883c68bbcSSu Yue 
32596d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
32606d97c6e3SJohannes Thumshirn 	if (ret) {
32616d97c6e3SJohannes Thumshirn 		err = ret;
32628f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32636d97c6e3SJohannes Thumshirn 		goto fail_alloc;
32646d97c6e3SJohannes Thumshirn 	}
32656d97c6e3SJohannes Thumshirn 
32668dc3f22cSJohannes Thumshirn 	/*
32671104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
32681104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
32691104a885SDavid Sterba 	 */
32708f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
327105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
32721104a885SDavid Sterba 		err = -EINVAL;
32738f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3274141386e1SJosef Bacik 		goto fail_alloc;
32751104a885SDavid Sterba 	}
32761104a885SDavid Sterba 
32771104a885SDavid Sterba 	/*
32781104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
32791104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
32801104a885SDavid Sterba 	 * the whole block of INFO_SIZE
32811104a885SDavid Sterba 	 */
32828f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
32838f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
32845f39d397SChris Mason 
3285fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3286fbc6feaeSNikolay Borisov 
32870b86a832SChris Mason 
3288fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3289fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3290fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3291fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3292fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3293fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3294fbc6feaeSNikolay Borisov 	}
3295fbc6feaeSNikolay Borisov 
3296fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3297fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3298de37aa51SNikolay Borisov 
3299069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
33001104a885SDavid Sterba 	if (ret) {
330105135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
33021104a885SDavid Sterba 		err = -EINVAL;
3303141386e1SJosef Bacik 		goto fail_alloc;
33041104a885SDavid Sterba 	}
33051104a885SDavid Sterba 
33060f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3307141386e1SJosef Bacik 		goto fail_alloc;
33080f7d52f4SChris Mason 
3309acce952bSliubo 	/* check FS state, whether FS is broken. */
331087533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
331187533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3312acce952bSliubo 
331375e7cb7fSLiu Bo 	/*
331475e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
331575e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
331675e7cb7fSLiu Bo 	 */
331775e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
331875e7cb7fSLiu Bo 
33196f93e834SAnand Jain 	/*
33206f93e834SAnand Jain 	 * Flag our filesystem as having big metadata blocks if they are bigger
33216f93e834SAnand Jain 	 * than the page size.
33226f93e834SAnand Jain 	 */
33236f93e834SAnand Jain 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
33246f93e834SAnand Jain 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
33256f93e834SAnand Jain 			btrfs_info(fs_info,
33266f93e834SAnand Jain 				"flagging fs with big metadata feature");
33276f93e834SAnand Jain 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
33286f93e834SAnand Jain 	}
33296f93e834SAnand Jain 
33306f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
33316f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
33326f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
33336f93e834SAnand Jain 	stripesize = sectorsize;
33346f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
33356f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
33366f93e834SAnand Jain 
33376f93e834SAnand Jain 	fs_info->nodesize = nodesize;
33386f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
33396f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
33406f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
33416f93e834SAnand Jain 	fs_info->stripesize = stripesize;
33426f93e834SAnand Jain 
33432ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
33442b82032cSYan Zheng 	if (ret) {
33452b82032cSYan Zheng 		err = ret;
3346141386e1SJosef Bacik 		goto fail_alloc;
33472b82032cSYan Zheng 	}
3348dfe25020SChris Mason 
3349f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3350f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3351f2b636e8SJosef Bacik 	if (features) {
335205135f59SDavid Sterba 		btrfs_err(fs_info,
335305135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3354c1c9ff7cSGeert Uytterhoeven 		    features);
3355f2b636e8SJosef Bacik 		err = -EINVAL;
3356141386e1SJosef Bacik 		goto fail_alloc;
3357f2b636e8SJosef Bacik 	}
3358f2b636e8SJosef Bacik 
33595d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
33605d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
33610b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3362a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
33635c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
33645c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3365727011e0SChris Mason 
33663173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
336705135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
33683173a18fSJosef Bacik 
3369727011e0SChris Mason 	/*
3370bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3371bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3372bc3f116fSChris Mason 	 */
3373bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3374707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
337505135f59SDavid Sterba 		btrfs_err(fs_info,
337605135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
337705135f59SDavid Sterba 			nodesize, sectorsize);
3378141386e1SJosef Bacik 		goto fail_alloc;
3379bc3f116fSChris Mason 	}
3380bc3f116fSChris Mason 
3381ceda0864SMiao Xie 	/*
3382ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3383ceda0864SMiao Xie 	 * update the flag.
3384ceda0864SMiao Xie 	 */
33855d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
33865d4f98a2SYan Zheng 
3387f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3388f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3389bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
339005135f59SDavid Sterba 		btrfs_err(fs_info,
339105135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3392c1c9ff7cSGeert Uytterhoeven 		       features);
3393f2b636e8SJosef Bacik 		err = -EINVAL;
3394141386e1SJosef Bacik 		goto fail_alloc;
3395f2b636e8SJosef Bacik 	}
339661d92c32SChris Mason 
33978481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
33988481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
33998481dd80SQu Wenruo 
340095ea0486SQu Wenruo 		btrfs_warn(fs_info,
340195ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
34020bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
3403c8050b3bSQu Wenruo 		if (btrfs_super_incompat_flags(fs_info->super_copy) &
3404c8050b3bSQu Wenruo 			BTRFS_FEATURE_INCOMPAT_RAID56) {
3405c8050b3bSQu Wenruo 			btrfs_err(fs_info,
3406c8050b3bSQu Wenruo 		"RAID56 is not yet supported for sector size %u with page size %lu",
3407c8050b3bSQu Wenruo 				sectorsize, PAGE_SIZE);
3408c8050b3bSQu Wenruo 			err = -EINVAL;
3409c8050b3bSQu Wenruo 			goto fail_alloc;
3410c8050b3bSQu Wenruo 		}
34118481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
34128481dd80SQu Wenruo 		if (!subpage_info)
34138481dd80SQu Wenruo 			goto fail_alloc;
34148481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
34158481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3416c8050b3bSQu Wenruo 	}
34170bb3eb3eSQu Wenruo 
34182a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
34192a458198SEric Sandeen 	if (ret) {
34202a458198SEric Sandeen 		err = ret;
34210dc3b84aSJosef Bacik 		goto fail_sb_buffer;
34220dc3b84aSJosef Bacik 	}
34234543df7eSChris Mason 
34249e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
34259e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
34264575c9ccSChris Mason 
3427a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3428a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3429de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3430db94535dSChris Mason 
3431925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
34326bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3433925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
343484eed90fSChris Mason 	if (ret) {
343505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
34365d4f98a2SYan Zheng 		goto fail_sb_buffer;
343784eed90fSChris Mason 	}
34380b86a832SChris Mason 
343984234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3440581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
34410b86a832SChris Mason 
34422ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
34430b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
34441b7ec85eSJosef Bacik 					   BTRFS_CHUNK_TREE_OBJECTID,
3445581c1760SQu Wenruo 					   generation, level, NULL);
344664c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
344764c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
344805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3449e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3450e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
345195ab1f64SZhao Lei 		chunk_root->node = NULL;
3452af31f5e5SChris Mason 		goto fail_tree_roots;
345383121942SDavid Woodhouse 	}
34545d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
34555d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
34560b86a832SChris Mason 
3457e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3458c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3459c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3460e17cade2SChris Mason 
34615b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
34622b82032cSYan Zheng 	if (ret) {
346305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3464af31f5e5SChris Mason 		goto fail_tree_roots;
34652b82032cSYan Zheng 	}
34660b86a832SChris Mason 
34678dabb742SStefan Behrens 	/*
3468bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3469bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3470bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
34711a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3472bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
34738dabb742SStefan Behrens 	 */
3474bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3475d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
347605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3477a6b0d5c8SChris Mason 		goto fail_tree_roots;
3478a6b0d5c8SChris Mason 	}
3479a6b0d5c8SChris Mason 
3480b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
34814bbcaa64SEric Sandeen 	if (ret)
3482b8522a1eSNikolay Borisov 		goto fail_tree_roots;
34838929ecfaSYan, Zheng 
348475ec1db8SJosef Bacik 	/*
348573651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
348673651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
348773651042SNaohiro Aota 	 * zoned incompat feature flag set.
348873651042SNaohiro Aota 	 */
348973651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
349073651042SNaohiro Aota 	if (ret) {
349173651042SNaohiro Aota 		btrfs_err(fs_info,
349273651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
349373651042SNaohiro Aota 			  ret);
349473651042SNaohiro Aota 		goto fail_block_groups;
349573651042SNaohiro Aota 	}
349673651042SNaohiro Aota 
349773651042SNaohiro Aota 	/*
349875ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
349975ec1db8SJosef Bacik 	 * check the generation here so we can set the
350075ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
350175ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
350275ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
350375ec1db8SJosef Bacik 	 * even though it was perfectly fine.
350475ec1db8SJosef Bacik 	 */
350575ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
350675ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
350775ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
350875ec1db8SJosef Bacik 
3509cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3510cf90d884SQu Wenruo 	if (ret) {
3511cf90d884SQu Wenruo 		btrfs_err(fs_info,
3512cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3513cf90d884SQu Wenruo 			  ret);
3514cf90d884SQu Wenruo 		goto fail_block_groups;
3515cf90d884SQu Wenruo 	}
351668310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
351768310a5eSIlya Dryomov 	if (ret) {
351805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
351968310a5eSIlya Dryomov 		goto fail_block_groups;
352068310a5eSIlya Dryomov 	}
352168310a5eSIlya Dryomov 
3522733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3523733f4fbbSStefan Behrens 	if (ret) {
352405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3525733f4fbbSStefan Behrens 		goto fail_block_groups;
3526733f4fbbSStefan Behrens 	}
3527733f4fbbSStefan Behrens 
35288dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
35298dabb742SStefan Behrens 	if (ret) {
353005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
35318dabb742SStefan Behrens 		goto fail_block_groups;
35328dabb742SStefan Behrens 	}
35338dabb742SStefan Behrens 
3534b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3535b70f5097SNaohiro Aota 	if (ret) {
3536b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3537b70f5097SNaohiro Aota 			  ret);
3538b70f5097SNaohiro Aota 		goto fail_block_groups;
3539b70f5097SNaohiro Aota 	}
3540b70f5097SNaohiro Aota 
3541c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3542b7c35e81SAnand Jain 	if (ret) {
354305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
354405135f59SDavid Sterba 				ret);
3545b7c35e81SAnand Jain 		goto fail_block_groups;
3546b7c35e81SAnand Jain 	}
3547b7c35e81SAnand Jain 
354896f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
35495ac1d209SJeff Mahoney 	if (ret) {
355005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3551b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
35525ac1d209SJeff Mahoney 	}
35535ac1d209SJeff Mahoney 
3554c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3555c59021f8Sliubo 	if (ret) {
355605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
35572365dd3cSAnand Jain 		goto fail_sysfs;
3558c59021f8Sliubo 	}
3559c59021f8Sliubo 
35605b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
35611b1d1f66SJosef Bacik 	if (ret) {
356205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
35632365dd3cSAnand Jain 		goto fail_sysfs;
35641b1d1f66SJosef Bacik 	}
35654330e183SQu Wenruo 
35665c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
35675c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
356805135f59SDavid Sterba 		btrfs_warn(fs_info,
356952042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
35702365dd3cSAnand Jain 		goto fail_sysfs;
3571292fd7fcSStefan Behrens 	}
35729078a3e1SChris Mason 
3573a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3574a74a4b97SChris Mason 					       "btrfs-cleaner");
357557506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
35762365dd3cSAnand Jain 		goto fail_sysfs;
3577a74a4b97SChris Mason 
3578a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3579a74a4b97SChris Mason 						   tree_root,
3580a74a4b97SChris Mason 						   "btrfs-transaction");
358157506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
35823f157a2fSChris Mason 		goto fail_cleaner;
3583a74a4b97SChris Mason 
3584583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3585c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3586583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3587c289811cSChris Mason 	}
3588c289811cSChris Mason 
3589572d9ab7SDavid Sterba 	/*
359001327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3591572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3592572d9ab7SDavid Sterba 	 */
3593572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
35943818aea2SQu Wenruo 
359521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
35960b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
35972ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
35980b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3599cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
360021adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
360121adbd5cSStefan Behrens 		if (ret)
360205135f59SDavid Sterba 			btrfs_warn(fs_info,
360305135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
360405135f59SDavid Sterba 				ret);
360521adbd5cSStefan Behrens 	}
360621adbd5cSStefan Behrens #endif
3607bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3608bcef60f2SArne Jansen 	if (ret)
3609bcef60f2SArne Jansen 		goto fail_trans_kthread;
361021adbd5cSStefan Behrens 
3611fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3612fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3613fd708b81SJosef Bacik 
361496da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
361596da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
36160b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3617e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
361863443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
361979787eaaSJeff Mahoney 		if (ret) {
362063443bf5SEric Sandeen 			err = ret;
362128c16cbbSWang Shilong 			goto fail_qgroup;
3622e556ce2cSYan Zheng 		}
3623e02119d5SChris Mason 	}
36241a40e23bSZheng Yan 
362556e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
36263140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
36273140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3628f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3629315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3630bcef60f2SArne Jansen 		goto fail_qgroup;
36313140c9a3SDan Carpenter 	}
3632c289811cSChris Mason 
3633bc98a42cSDavid Howells 	if (sb_rdonly(sb))
36348cd29088SBoris Burkov 		goto clear_oneshot;
36352b6ba629SIlya Dryomov 
363644c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
36372b6ba629SIlya Dryomov 	if (ret) {
36386bccf3abSJeff Mahoney 		close_ctree(fs_info);
36392b6ba629SIlya Dryomov 		return ret;
3640e3acc2a6SJosef Bacik 	}
3641b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3642b382a324SJan Schmidt 
364344c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
364444c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
364544c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
364605135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
364770f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
364870f80175SStefan Behrens 		if (ret) {
364905135f59SDavid Sterba 			btrfs_warn(fs_info,
365005135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
36516bccf3abSJeff Mahoney 			close_ctree(fs_info);
365270f80175SStefan Behrens 			return ret;
365370f80175SStefan Behrens 		}
3654f7a81ea4SStefan Behrens 	}
365594846229SBoris Burkov 
3656afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
365747ab2a6cSJosef Bacik 
36588cd29088SBoris Burkov clear_oneshot:
36598cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3660ad2b2c80SAl Viro 	return 0;
366139279cc3SChris Mason 
3662bcef60f2SArne Jansen fail_qgroup:
3663bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
36647c2ca468SChris Mason fail_trans_kthread:
36657c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
36662ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3667faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
36683f157a2fSChris Mason fail_cleaner:
3669a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
36707c2ca468SChris Mason 
36717c2ca468SChris Mason 	/*
36727c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
36737c2ca468SChris Mason 	 * kthreads
36747c2ca468SChris Mason 	 */
36757c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
36767c2ca468SChris Mason 
36772365dd3cSAnand Jain fail_sysfs:
36786618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
36792365dd3cSAnand Jain 
3680b7c35e81SAnand Jain fail_fsdev_sysfs:
3681b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3682b7c35e81SAnand Jain 
36831b1d1f66SJosef Bacik fail_block_groups:
368454067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3685af31f5e5SChris Mason 
3686af31f5e5SChris Mason fail_tree_roots:
36879e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
36889e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
36894273eaffSAnand Jain 	free_root_pointers(fs_info, true);
36902b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3691af31f5e5SChris Mason 
369239279cc3SChris Mason fail_sb_buffer:
36937abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
36945cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
369516cdcec7SMiao Xie fail_alloc:
3696586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3697586e46e2SIlya Dryomov 
36984543df7eSChris Mason 	iput(fs_info->btree_inode);
36997e662854SQinghuang Feng fail:
3700586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3701ad2b2c80SAl Viro 	return err;
3702eb60ceacSChris Mason }
3703663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3704eb60ceacSChris Mason 
3705314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3706f2984462SChris Mason {
3707314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3708314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3709314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3710314b6dd0SJohannes Thumshirn 	struct page *page;
3711442a4f63SStefan Behrens 
3712314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3713314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3714314b6dd0SJohannes Thumshirn 
3715314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3716fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3717314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3718314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3719314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3720314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3721314b6dd0SJohannes Thumshirn 			SetPageError(page);
3722314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3723314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3724314b6dd0SJohannes Thumshirn 		} else {
3725314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3726f2984462SChris Mason 		}
3727314b6dd0SJohannes Thumshirn 
3728314b6dd0SJohannes Thumshirn 		put_page(page);
3729314b6dd0SJohannes Thumshirn 		unlock_page(page);
3730314b6dd0SJohannes Thumshirn 	}
3731314b6dd0SJohannes Thumshirn 
3732314b6dd0SJohannes Thumshirn 	bio_put(bio);
3733f2984462SChris Mason }
3734f2984462SChris Mason 
37358f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
37368f32380dSJohannes Thumshirn 						   int copy_num)
373729c36d72SAnand Jain {
373829c36d72SAnand Jain 	struct btrfs_super_block *super;
37398f32380dSJohannes Thumshirn 	struct page *page;
374012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
37418f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
374212659251SNaohiro Aota 	int ret;
374329c36d72SAnand Jain 
374412659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
374512659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
374612659251SNaohiro Aota 	if (ret == -ENOENT)
374712659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
374812659251SNaohiro Aota 	else if (ret)
374912659251SNaohiro Aota 		return ERR_PTR(ret);
375012659251SNaohiro Aota 
375129c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
37528f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
375329c36d72SAnand Jain 
37548f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
37558f32380dSJohannes Thumshirn 	if (IS_ERR(page))
37568f32380dSJohannes Thumshirn 		return ERR_CAST(page);
375729c36d72SAnand Jain 
37588f32380dSJohannes Thumshirn 	super = page_address(page);
375996c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
376096c2e067SAnand Jain 		btrfs_release_disk_super(super);
376196c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
376296c2e067SAnand Jain 	}
376396c2e067SAnand Jain 
376412659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
37658f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
37668f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
376729c36d72SAnand Jain 	}
376829c36d72SAnand Jain 
37698f32380dSJohannes Thumshirn 	return super;
377029c36d72SAnand Jain }
377129c36d72SAnand Jain 
377229c36d72SAnand Jain 
37738f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3774a512bbf8SYan Zheng {
37758f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3776a512bbf8SYan Zheng 	int i;
3777a512bbf8SYan Zheng 	u64 transid = 0;
3778a512bbf8SYan Zheng 
3779a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3780a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3781a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3782a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3783a512bbf8SYan Zheng 	 */
3784a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
37858f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
37868f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3787a512bbf8SYan Zheng 			continue;
3788a512bbf8SYan Zheng 
3789a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
37908f32380dSJohannes Thumshirn 			if (latest)
37918f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
37928f32380dSJohannes Thumshirn 
37938f32380dSJohannes Thumshirn 			latest = super;
3794a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3795a512bbf8SYan Zheng 		}
3796a512bbf8SYan Zheng 	}
379792fc03fbSAnand Jain 
37988f32380dSJohannes Thumshirn 	return super;
3799a512bbf8SYan Zheng }
3800a512bbf8SYan Zheng 
38014eedeb75SHisashi Hifumi /*
3802abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3803314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
38044eedeb75SHisashi Hifumi  *
3805abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3806abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3807abbb3b8eSDavid Sterba  * same for write and wait phases.
38084eedeb75SHisashi Hifumi  *
3809314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
38104eedeb75SHisashi Hifumi  */
3811a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3812abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3813a512bbf8SYan Zheng {
3814d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3815314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3816d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3817a512bbf8SYan Zheng 	int i;
3818a512bbf8SYan Zheng 	int errors = 0;
381912659251SNaohiro Aota 	int ret;
382012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3821a512bbf8SYan Zheng 
3822a512bbf8SYan Zheng 	if (max_mirrors == 0)
3823a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3824a512bbf8SYan Zheng 
3825d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3826d5178578SJohannes Thumshirn 
3827a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3828314b6dd0SJohannes Thumshirn 		struct page *page;
3829314b6dd0SJohannes Thumshirn 		struct bio *bio;
3830314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3831314b6dd0SJohannes Thumshirn 
383212659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
383312659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
383412659251SNaohiro Aota 		if (ret == -ENOENT) {
383512659251SNaohiro Aota 			continue;
383612659251SNaohiro Aota 		} else if (ret < 0) {
383712659251SNaohiro Aota 			btrfs_err(device->fs_info,
383812659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
383912659251SNaohiro Aota 				i);
384012659251SNaohiro Aota 			errors++;
384112659251SNaohiro Aota 			continue;
384212659251SNaohiro Aota 		}
3843935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3844935e5cc9SMiao Xie 		    device->commit_total_bytes)
3845a512bbf8SYan Zheng 			break;
3846a512bbf8SYan Zheng 
384712659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3848a512bbf8SYan Zheng 
3849fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3850fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3851fd08001fSEric Biggers 				    sb->csum);
3852a512bbf8SYan Zheng 
3853314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3854314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3855314b6dd0SJohannes Thumshirn 		if (!page) {
3856fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3857314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3858f14d104dSDavid Sterba 			    bytenr);
3859634554dcSJosef Bacik 			errors++;
3860634554dcSJosef Bacik 			continue;
3861634554dcSJosef Bacik 		}
3862634554dcSJosef Bacik 
3863314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3864314b6dd0SJohannes Thumshirn 		get_page(page);
3865a512bbf8SYan Zheng 
3866314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3867314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3868a512bbf8SYan Zheng 
3869387125fcSChris Mason 		/*
3870314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3871314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3872314b6dd0SJohannes Thumshirn 		 * checking.
3873387125fcSChris Mason 		 */
3874314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3875314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3876314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3877314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3878314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3879314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3880314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3881314b6dd0SJohannes Thumshirn 
3882314b6dd0SJohannes Thumshirn 		/*
3883314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3884314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3885314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3886314b6dd0SJohannes Thumshirn 		 */
3887314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
38881b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3889314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3890314b6dd0SJohannes Thumshirn 
3891314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
38928376d9e1SNaohiro Aota 
38938376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
38948376d9e1SNaohiro Aota 			errors++;
3895a512bbf8SYan Zheng 	}
3896a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3897a512bbf8SYan Zheng }
3898a512bbf8SYan Zheng 
3899387125fcSChris Mason /*
3900abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3901abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3902abbb3b8eSDavid Sterba  *
3903314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3904abbb3b8eSDavid Sterba  * date.
3905abbb3b8eSDavid Sterba  */
3906abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3907abbb3b8eSDavid Sterba {
3908abbb3b8eSDavid Sterba 	int i;
3909abbb3b8eSDavid Sterba 	int errors = 0;
3910b6a535faSHoward McLauchlan 	bool primary_failed = false;
391112659251SNaohiro Aota 	int ret;
3912abbb3b8eSDavid Sterba 	u64 bytenr;
3913abbb3b8eSDavid Sterba 
3914abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3915abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3916abbb3b8eSDavid Sterba 
3917abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3918314b6dd0SJohannes Thumshirn 		struct page *page;
3919314b6dd0SJohannes Thumshirn 
392012659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
392112659251SNaohiro Aota 		if (ret == -ENOENT) {
392212659251SNaohiro Aota 			break;
392312659251SNaohiro Aota 		} else if (ret < 0) {
392412659251SNaohiro Aota 			errors++;
392512659251SNaohiro Aota 			if (i == 0)
392612659251SNaohiro Aota 				primary_failed = true;
392712659251SNaohiro Aota 			continue;
392812659251SNaohiro Aota 		}
3929abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3930abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3931abbb3b8eSDavid Sterba 			break;
3932abbb3b8eSDavid Sterba 
3933314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3934314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3935314b6dd0SJohannes Thumshirn 		if (!page) {
3936abbb3b8eSDavid Sterba 			errors++;
3937b6a535faSHoward McLauchlan 			if (i == 0)
3938b6a535faSHoward McLauchlan 				primary_failed = true;
3939abbb3b8eSDavid Sterba 			continue;
3940abbb3b8eSDavid Sterba 		}
3941314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3942314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3943314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3944abbb3b8eSDavid Sterba 			errors++;
3945b6a535faSHoward McLauchlan 			if (i == 0)
3946b6a535faSHoward McLauchlan 				primary_failed = true;
3947b6a535faSHoward McLauchlan 		}
3948abbb3b8eSDavid Sterba 
3949314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3950314b6dd0SJohannes Thumshirn 		put_page(page);
3951abbb3b8eSDavid Sterba 
3952314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3953314b6dd0SJohannes Thumshirn 		put_page(page);
3954abbb3b8eSDavid Sterba 	}
3955abbb3b8eSDavid Sterba 
3956b6a535faSHoward McLauchlan 	/* log error, force error return */
3957b6a535faSHoward McLauchlan 	if (primary_failed) {
3958b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3959b6a535faSHoward McLauchlan 			  device->devid);
3960b6a535faSHoward McLauchlan 		return -1;
3961b6a535faSHoward McLauchlan 	}
3962b6a535faSHoward McLauchlan 
3963abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3964abbb3b8eSDavid Sterba }
3965abbb3b8eSDavid Sterba 
3966abbb3b8eSDavid Sterba /*
3967387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3968387125fcSChris Mason  * for the barrier when it is done
3969387125fcSChris Mason  */
39704246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3971387125fcSChris Mason {
3972387125fcSChris Mason 	complete(bio->bi_private);
3973387125fcSChris Mason }
3974387125fcSChris Mason 
3975387125fcSChris Mason /*
39764fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
39774fc6441aSAnand Jain  * done in the waiting counterpart.
3978387125fcSChris Mason  */
39794fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3980387125fcSChris Mason {
3981e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3982387125fcSChris Mason 
3983*a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3984*a91cf0ffSWang Yugui 	/*
3985*a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
3986*a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
3987*a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
3988*a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
3989*a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
3990*a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
3991*a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
3992*a91cf0ffSWang Yugui 	 * non-debug builds.
3993*a91cf0ffSWang Yugui 	 */
3994*a91cf0ffSWang Yugui 	struct request_queue *q = bdev_get_queue(device->bdev);
3995c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
39964fc6441aSAnand Jain 		return;
3997*a91cf0ffSWang Yugui #endif
3998387125fcSChris Mason 
3999e0ae9994SDavid Sterba 	bio_reset(bio);
4000387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
400174d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
40028d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
4003387125fcSChris Mason 	init_completion(&device->flush_wait);
4004387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4005387125fcSChris Mason 
400643a01111SLu Fengqi 	btrfsic_submit_bio(bio);
40071c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40084fc6441aSAnand Jain }
4009387125fcSChris Mason 
40104fc6441aSAnand Jain /*
40114fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
40124fc6441aSAnand Jain  */
40138c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
40144fc6441aSAnand Jain {
40154fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
40164fc6441aSAnand Jain 
40171c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
401858efbc9fSOmar Sandoval 		return BLK_STS_OK;
40194fc6441aSAnand Jain 
40201c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40212980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
40224fc6441aSAnand Jain 
40238c27cb35SLinus Torvalds 	return bio->bi_status;
4024387125fcSChris Mason }
4025387125fcSChris Mason 
4026d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4027401b41e5SAnand Jain {
40286528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4029401b41e5SAnand Jain 		return -EIO;
4030387125fcSChris Mason 	return 0;
4031387125fcSChris Mason }
4032387125fcSChris Mason 
4033387125fcSChris Mason /*
4034387125fcSChris Mason  * send an empty flush down to each device in parallel,
4035387125fcSChris Mason  * then wait for them
4036387125fcSChris Mason  */
4037387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4038387125fcSChris Mason {
4039387125fcSChris Mason 	struct list_head *head;
4040387125fcSChris Mason 	struct btrfs_device *dev;
40415af3e8ccSStefan Behrens 	int errors_wait = 0;
40424e4cbee9SChristoph Hellwig 	blk_status_t ret;
4043387125fcSChris Mason 
40441538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4045387125fcSChris Mason 	/* send down all the barriers */
4046387125fcSChris Mason 	head = &info->fs_devices->devices;
40471538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4048e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4049f88ba6a2SHidetoshi Seto 			continue;
4050cea7c8bfSAnand Jain 		if (!dev->bdev)
4051387125fcSChris Mason 			continue;
4052e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4053ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4054387125fcSChris Mason 			continue;
4055387125fcSChris Mason 
40564fc6441aSAnand Jain 		write_dev_flush(dev);
405758efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4058387125fcSChris Mason 	}
4059387125fcSChris Mason 
4060387125fcSChris Mason 	/* wait for all the barriers */
40611538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4062e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4063f88ba6a2SHidetoshi Seto 			continue;
4064387125fcSChris Mason 		if (!dev->bdev) {
40655af3e8ccSStefan Behrens 			errors_wait++;
4066387125fcSChris Mason 			continue;
4067387125fcSChris Mason 		}
4068e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4069ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4070387125fcSChris Mason 			continue;
4071387125fcSChris Mason 
40724fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4073401b41e5SAnand Jain 		if (ret) {
4074401b41e5SAnand Jain 			dev->last_flush_error = ret;
407566b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
407666b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
40775af3e8ccSStefan Behrens 			errors_wait++;
4078387125fcSChris Mason 		}
4079401b41e5SAnand Jain 	}
4080401b41e5SAnand Jain 
4081cea7c8bfSAnand Jain 	if (errors_wait) {
4082401b41e5SAnand Jain 		/*
4083401b41e5SAnand Jain 		 * At some point we need the status of all disks
4084401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4085401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4086401b41e5SAnand Jain 		 */
4087d10b82feSQu Wenruo 		return check_barrier_error(info);
4088401b41e5SAnand Jain 	}
4089387125fcSChris Mason 	return 0;
4090387125fcSChris Mason }
4091387125fcSChris Mason 
4092943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4093943c6e99SZhao Lei {
40948789f4feSZhao Lei 	int raid_type;
40958789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4096943c6e99SZhao Lei 
40978789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
40988789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
40998c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41008789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
41018789f4feSZhao Lei 				    tolerated_failures);
4102943c6e99SZhao Lei 
41038789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
41048789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
41058789f4feSZhao Lei 			continue;
410641a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
41078789f4feSZhao Lei 			continue;
41088c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41098789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
41108789f4feSZhao Lei 				    tolerated_failures);
41118789f4feSZhao Lei 	}
4112943c6e99SZhao Lei 
41138789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4114ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
41158789f4feSZhao Lei 		min_tolerated = 0;
41168789f4feSZhao Lei 	}
41178789f4feSZhao Lei 
41188789f4feSZhao Lei 	return min_tolerated;
4119943c6e99SZhao Lei }
4120943c6e99SZhao Lei 
4121eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4122f2984462SChris Mason {
4123e5e9a520SChris Mason 	struct list_head *head;
4124f2984462SChris Mason 	struct btrfs_device *dev;
4125a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4126f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4127f2984462SChris Mason 	int ret;
4128f2984462SChris Mason 	int do_barriers;
4129a236aed1SChris Mason 	int max_errors;
4130a236aed1SChris Mason 	int total_errors = 0;
4131a061fc8dSChris Mason 	u64 flags;
4132f2984462SChris Mason 
41330b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4134fed3b381SLiu Bo 
4135fed3b381SLiu Bo 	/*
4136fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4137fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4138fed3b381SLiu Bo 	 * been consistent on disk.
4139fed3b381SLiu Bo 	 */
4140fed3b381SLiu Bo 	if (max_mirrors == 0)
41410b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4142f2984462SChris Mason 
41430b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4144a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4145e5e9a520SChris Mason 
41460b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
41470b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
41480b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4149387125fcSChris Mason 
41505af3e8ccSStefan Behrens 	if (do_barriers) {
41510b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
41525af3e8ccSStefan Behrens 		if (ret) {
41535af3e8ccSStefan Behrens 			mutex_unlock(
41540b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
41550b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
41565af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
41575af3e8ccSStefan Behrens 			return ret;
41585af3e8ccSStefan Behrens 		}
41595af3e8ccSStefan Behrens 	}
4160387125fcSChris Mason 
41611538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4162dfe25020SChris Mason 		if (!dev->bdev) {
4163dfe25020SChris Mason 			total_errors++;
4164dfe25020SChris Mason 			continue;
4165dfe25020SChris Mason 		}
4166e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4167ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4168dfe25020SChris Mason 			continue;
4169dfe25020SChris Mason 
41702b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4171a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4172a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
41737df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4174935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4175ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4176ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4177a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4178a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4179a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4180a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
41817239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
41827239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4183a512bbf8SYan Zheng 
4184a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4185a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4186f2984462SChris Mason 
418775cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
418875cb857dSQu Wenruo 		if (ret < 0) {
418975cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
419075cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
419175cb857dSQu Wenruo 				"unexpected superblock corruption detected");
419275cb857dSQu Wenruo 			return -EUCLEAN;
419375cb857dSQu Wenruo 		}
419475cb857dSQu Wenruo 
4195abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4196a236aed1SChris Mason 		if (ret)
4197a236aed1SChris Mason 			total_errors++;
4198f2984462SChris Mason 	}
4199a236aed1SChris Mason 	if (total_errors > max_errors) {
42000b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4201d397712bSChris Mason 			  total_errors);
42020b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
420379787eaaSJeff Mahoney 
42049d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
42050b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42060b246afaSJeff Mahoney 				      "%d errors while writing supers",
42070b246afaSJeff Mahoney 				      total_errors);
42089d565ba4SStefan Behrens 		return -EIO;
4209a236aed1SChris Mason 	}
4210f2984462SChris Mason 
4211a512bbf8SYan Zheng 	total_errors = 0;
42121538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4213dfe25020SChris Mason 		if (!dev->bdev)
4214dfe25020SChris Mason 			continue;
4215e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4216ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4217dfe25020SChris Mason 			continue;
4218dfe25020SChris Mason 
4219abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4220a512bbf8SYan Zheng 		if (ret)
42211259ab75SChris Mason 			total_errors++;
4222f2984462SChris Mason 	}
42230b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4224a236aed1SChris Mason 	if (total_errors > max_errors) {
42250b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42260b246afaSJeff Mahoney 				      "%d errors while writing supers",
42270b246afaSJeff Mahoney 				      total_errors);
422879787eaaSJeff Mahoney 		return -EIO;
4229a236aed1SChris Mason 	}
4230f2984462SChris Mason 	return 0;
4231f2984462SChris Mason }
4232f2984462SChris Mason 
4233cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4234cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4235cb517eabSMiao Xie 				  struct btrfs_root *root)
42362619ba1fSChris Mason {
42374785e24fSJosef Bacik 	bool drop_ref = false;
42384785e24fSJosef Bacik 
42394df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
42402619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
42412619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
4242af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
42434785e24fSJosef Bacik 		drop_ref = true;
42444df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
424576dda93cSYan, Zheng 
424684961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4247ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
42481c1ea4f7SLiu Bo 		if (root->reloc_root) {
424900246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
42501c1ea4f7SLiu Bo 			root->reloc_root = NULL;
42511c1ea4f7SLiu Bo 		}
42521c1ea4f7SLiu Bo 	}
42533321719eSLiu Bo 
42544785e24fSJosef Bacik 	if (drop_ref)
425500246528SJosef Bacik 		btrfs_put_root(root);
42562619ba1fSChris Mason }
42572619ba1fSChris Mason 
4258c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4259c146afadSYan Zheng {
4260c146afadSYan Zheng 	u64 root_objectid = 0;
4261c146afadSYan Zheng 	struct btrfs_root *gang[8];
426265d33fd7SQu Wenruo 	int i = 0;
426365d33fd7SQu Wenruo 	int err = 0;
426465d33fd7SQu Wenruo 	unsigned int ret = 0;
4265c146afadSYan Zheng 
4266c146afadSYan Zheng 	while (1) {
4267efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4268c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4269c146afadSYan Zheng 					     (void **)gang, root_objectid,
4270c146afadSYan Zheng 					     ARRAY_SIZE(gang));
427165d33fd7SQu Wenruo 		if (!ret) {
4272efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4273c146afadSYan Zheng 			break;
427465d33fd7SQu Wenruo 		}
42755d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
427666b4ffd1SJosef Bacik 
427765d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
427865d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
427965d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
428065d33fd7SQu Wenruo 				gang[i] = NULL;
428165d33fd7SQu Wenruo 				continue;
428265d33fd7SQu Wenruo 			}
428365d33fd7SQu Wenruo 			/* grab all the search result for later use */
428400246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
428565d33fd7SQu Wenruo 		}
4286efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
428765d33fd7SQu Wenruo 
428865d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
428965d33fd7SQu Wenruo 			if (!gang[i])
429065d33fd7SQu Wenruo 				continue;
4291c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
429266b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
429366b4ffd1SJosef Bacik 			if (err)
429465d33fd7SQu Wenruo 				break;
429500246528SJosef Bacik 			btrfs_put_root(gang[i]);
4296c146afadSYan Zheng 		}
4297c146afadSYan Zheng 		root_objectid++;
4298c146afadSYan Zheng 	}
429965d33fd7SQu Wenruo 
430065d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
430165d33fd7SQu Wenruo 	for (; i < ret; i++) {
430265d33fd7SQu Wenruo 		if (gang[i])
430300246528SJosef Bacik 			btrfs_put_root(gang[i]);
430465d33fd7SQu Wenruo 	}
430565d33fd7SQu Wenruo 	return err;
4306c146afadSYan Zheng }
4307c146afadSYan Zheng 
43086bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4309c146afadSYan Zheng {
43106bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4311c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4312c146afadSYan Zheng 
43130b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
43142ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
43150b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
43160b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4317c71bf099SYan, Zheng 
4318c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
43190b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
43200b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4321c71bf099SYan, Zheng 
43227a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
43233612b495STsutomu Itoh 	if (IS_ERR(trans))
43243612b495STsutomu Itoh 		return PTR_ERR(trans);
43253a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4326c146afadSYan Zheng }
4327c146afadSYan Zheng 
4328b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4329eb60ceacSChris Mason {
4330c146afadSYan Zheng 	int ret;
4331e089f05cSChris Mason 
4332afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4333d6fd0ae2SOmar Sandoval 	/*
4334d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4335d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4336d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4337d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4338d6fd0ae2SOmar Sandoval 	 */
4339d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4340a2135011SChris Mason 
43417343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4342d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
43437343dd61SJustin Maggard 
4344803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4345803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4346803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4347803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4348803b2f54SStefan Behrens 
4349837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4350aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4351837d5b6eSIlya Dryomov 
43528dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
43538dabb742SStefan Behrens 
4354aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
43554cb5300bSChris Mason 
43564cb5300bSChris Mason 	/* wait for any defraggers to finish */
43574cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
43584cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
43594cb5300bSChris Mason 
43604cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
436126176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
43624cb5300bSChris Mason 
436321c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
436457056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4365576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
436621c7e756SMiao Xie 
436718bb8bbfSJohannes Thumshirn 	cancel_work_sync(&fs_info->reclaim_bgs_work);
436818bb8bbfSJohannes Thumshirn 
4369b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4370b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4371b0643e59SDennis Zhou 
4372bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4373e44163e1SJeff Mahoney 		/*
4374d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4375d6fd0ae2SOmar Sandoval 		 * unused block groups.
4376e44163e1SJeff Mahoney 		 */
43770b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4378e44163e1SJeff Mahoney 
4379f0cc2cd7SFilipe Manana 		/*
4380f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4381f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4382f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4383f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4384f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4385f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4386f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4387f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4388f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4389f0cc2cd7SFilipe Manana 		 */
4390f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4391f0cc2cd7SFilipe Manana 
43926bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4393d397712bSChris Mason 		if (ret)
439404892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4395c146afadSYan Zheng 	}
4396ed2ff2cbSChris Mason 
439784961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
43982ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4399acce952bSliubo 
4400e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4401e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
44028929ecfaSYan, Zheng 
4403e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4404afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4405f25784b3SYan Zheng 
44065958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
44075958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
44085958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
44095958253cSQu Wenruo 	}
44105958253cSQu Wenruo 
441104892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4412fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4413bcef60f2SArne Jansen 
4414963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
441504892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4416963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4417b0c68f8bSChris Mason 	}
441831153d81SYan Zheng 
44195deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
44204297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
44215deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
44224297ff84SJosef Bacik 
44236618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4424b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
44255ac1d209SJeff Mahoney 
44261a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
44271a4319ccSLiu Bo 
4428de348ee0SWang Shilong 	/*
4429de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4430de348ee0SWang Shilong 	 * submit after we stopping all workers.
4431de348ee0SWang Shilong 	 */
4432de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
443396192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
443496192499SJosef Bacik 
44350a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
44360a31daa4SFilipe Manana 	ASSERT(list_empty(&fs_info->trans_list));
44370a31daa4SFilipe Manana 
4438afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
44394273eaffSAnand Jain 	free_root_pointers(fs_info, true);
44408c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
44419ad6b7bcSChris Mason 
44424e19443dSJosef Bacik 	/*
44434e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
44444e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
44454e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
44464e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
44474e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
44484e19443dSJosef Bacik 	 */
44494e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
44504e19443dSJosef Bacik 
445113e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4452d6bfde87SChris Mason 
445321adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
44540b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
44552ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
445621adbd5cSStefan Behrens #endif
445721adbd5cSStefan Behrens 
44580b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
445968c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4460eb60ceacSChris Mason }
4461eb60ceacSChris Mason 
4462b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4463b9fab919SChris Mason 			  int atomic)
4464ccd467d6SChris Mason {
44651259ab75SChris Mason 	int ret;
4466727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
44671259ab75SChris Mason 
44680b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
44691259ab75SChris Mason 	if (!ret)
44701259ab75SChris Mason 		return ret;
44711259ab75SChris Mason 
44721259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4473b9fab919SChris Mason 				    parent_transid, atomic);
4474b9fab919SChris Mason 	if (ret == -EAGAIN)
4475b9fab919SChris Mason 		return ret;
44761259ab75SChris Mason 	return !ret;
44775f39d397SChris Mason }
44786702ed49SChris Mason 
44795f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
44805f39d397SChris Mason {
44812f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
44825f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4483b9473439SChris Mason 	int was_dirty;
4484b4ce94deSChris Mason 
448506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
448606ea65a3SJosef Bacik 	/*
448706ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
448852042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
448906ea65a3SJosef Bacik 	 * outside of the sanity tests.
449006ea65a3SJosef Bacik 	 */
4491b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
449206ea65a3SJosef Bacik 		return;
449306ea65a3SJosef Bacik #endif
449449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
44950b246afaSJeff Mahoney 	if (transid != fs_info->generation)
44965d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
44970b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
44980b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4499e2d84521SMiao Xie 	if (!was_dirty)
4500104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4501e2d84521SMiao Xie 					 buf->len,
45020b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
45031f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
450469fc6cbbSQu Wenruo 	/*
450569fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
450669fc6cbbSQu Wenruo 	 * but item data not updated.
450769fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
450869fc6cbbSQu Wenruo 	 */
450969fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4510cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4511a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
45121f21ef0aSFilipe Manana 		ASSERT(0);
45131f21ef0aSFilipe Manana 	}
45141f21ef0aSFilipe Manana #endif
4515eb60ceacSChris Mason }
4516eb60ceacSChris Mason 
45172ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4518b53d3f5dSLiu Bo 					int flush_delayed)
451935b7e476SChris Mason {
4520188de649SChris Mason 	/*
4521188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4522188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4523188de649SChris Mason 	 */
4524e2d84521SMiao Xie 	int ret;
4525d6bfde87SChris Mason 
45266933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4527d6bfde87SChris Mason 		return;
4528d6bfde87SChris Mason 
4529b53d3f5dSLiu Bo 	if (flush_delayed)
45302ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
453116cdcec7SMiao Xie 
4532d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4533d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4534d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4535e2d84521SMiao Xie 	if (ret > 0) {
45360b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
453716cdcec7SMiao Xie 	}
453816cdcec7SMiao Xie }
453916cdcec7SMiao Xie 
45402ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
454116cdcec7SMiao Xie {
45422ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
454335b7e476SChris Mason }
4544b53d3f5dSLiu Bo 
45452ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4546b53d3f5dSLiu Bo {
45472ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4548d6bfde87SChris Mason }
45496b80053dSChris Mason 
4550581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4551581c1760SQu Wenruo 		      struct btrfs_key *first_key)
45526b80053dSChris Mason {
45535ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4554581c1760SQu Wenruo 					      level, first_key);
45556b80053dSChris Mason }
45560da5468fSChris Mason 
45572ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4558acce952bSliubo {
4559fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4560fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4561fe816d0fSNikolay Borisov 
45620b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45632ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45640b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4565acce952bSliubo 
45660b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45670b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4568acce952bSliubo }
4569acce952bSliubo 
4570ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4571ef67963dSJosef Bacik {
4572ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4573ef67963dSJosef Bacik 	u64 root_objectid = 0;
4574ef67963dSJosef Bacik 	int ret;
4575ef67963dSJosef Bacik 
4576ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4577ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4578ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4579ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4580ef67963dSJosef Bacik 		int i;
4581ef67963dSJosef Bacik 
4582ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4583ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4584ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4585ef67963dSJosef Bacik 
4586ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4587ef67963dSJosef Bacik 			if (!gang[i])
4588ef67963dSJosef Bacik 				continue;
4589ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4590ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4591ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4592ef67963dSJosef Bacik 		}
4593ef67963dSJosef Bacik 		root_objectid++;
4594ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4595ef67963dSJosef Bacik 	}
4596ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4597ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4598ef67963dSJosef Bacik }
4599ef67963dSJosef Bacik 
4600143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4601acce952bSliubo {
4602acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4603acce952bSliubo 
4604199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4605779880efSJosef Bacik 	/*
4606779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4607779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4608779880efSJosef Bacik 	 */
4609199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4610779880efSJosef Bacik 			    root_extent_list)
4611779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4612199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4613199c2a9cSMiao Xie }
4614199c2a9cSMiao Xie 
4615199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4616199c2a9cSMiao Xie {
4617199c2a9cSMiao Xie 	struct btrfs_root *root;
4618199c2a9cSMiao Xie 	struct list_head splice;
4619199c2a9cSMiao Xie 
4620199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4621199c2a9cSMiao Xie 
4622199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4623199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4624199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4625199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4626199c2a9cSMiao Xie 					ordered_root);
46271de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
46281de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4629199c2a9cSMiao Xie 
46302a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4631199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4632199c2a9cSMiao Xie 
46332a85d9caSLiu Bo 		cond_resched();
46342a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4635199c2a9cSMiao Xie 	}
4636199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
463774d5d229SJosef Bacik 
463874d5d229SJosef Bacik 	/*
463974d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
464074d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
464174d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
464274d5d229SJosef Bacik 	 * actually get run and error out properly.
464374d5d229SJosef Bacik 	 */
464474d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4645acce952bSliubo }
4646acce952bSliubo 
464735a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
46482ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4649acce952bSliubo {
4650acce952bSliubo 	struct rb_node *node;
4651acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4652acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4653acce952bSliubo 	int ret = 0;
4654acce952bSliubo 
4655acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4656acce952bSliubo 
4657acce952bSliubo 	spin_lock(&delayed_refs->lock);
4658d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4659cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4660b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4661acce952bSliubo 		return ret;
4662acce952bSliubo 	}
4663acce952bSliubo 
46645c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4665d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
46660e0adbcfSJosef Bacik 		struct rb_node *n;
4667e78417d1SJosef Bacik 		bool pin_bytes = false;
4668acce952bSliubo 
4669d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4670d7df2c79SJosef Bacik 				href_node);
46713069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4672b939d1abSJosef Bacik 			continue;
46733069bd26SJosef Bacik 
4674d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4675e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
46760e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
46770e0adbcfSJosef Bacik 				       ref_node);
4678d7df2c79SJosef Bacik 			ref->in_tree = 0;
4679e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
46800e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
46811d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
46821d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4683d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4684d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4685d7df2c79SJosef Bacik 		}
468654067ae9SJosef Bacik 		if (head->must_insert_reserved)
4687e78417d1SJosef Bacik 			pin_bytes = true;
468878a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4689fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4690d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4691acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4692e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4693acce952bSliubo 
4694f603bb94SNikolay Borisov 		if (pin_bytes) {
4695f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4696f603bb94SNikolay Borisov 
4697f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4698f603bb94SNikolay Borisov 			BUG_ON(!cache);
4699f603bb94SNikolay Borisov 
4700f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4701f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4702f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4703f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4704f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4705f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4706f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4707f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4708f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4709f603bb94SNikolay Borisov 
4710f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4711f603bb94SNikolay Borisov 
4712f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4713f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4714f603bb94SNikolay Borisov 		}
471531890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4716d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4717acce952bSliubo 		cond_resched();
4718acce952bSliubo 		spin_lock(&delayed_refs->lock);
4719acce952bSliubo 	}
472081f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4721acce952bSliubo 
4722acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4723acce952bSliubo 
4724acce952bSliubo 	return ret;
4725acce952bSliubo }
4726acce952bSliubo 
4727143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4728acce952bSliubo {
4729acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4730acce952bSliubo 	struct list_head splice;
4731acce952bSliubo 
4732acce952bSliubo 	INIT_LIST_HEAD(&splice);
4733acce952bSliubo 
4734eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4735eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4736acce952bSliubo 
4737acce952bSliubo 	while (!list_empty(&splice)) {
4738fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4739eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4740acce952bSliubo 					       delalloc_inodes);
4741fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4742eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4743acce952bSliubo 
4744fe816d0fSNikolay Borisov 		/*
4745fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4746fe816d0fSNikolay Borisov 		 * meanwhile.
4747fe816d0fSNikolay Borisov 		 */
4748fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4749fe816d0fSNikolay Borisov 		if (inode) {
4750fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4751fe816d0fSNikolay Borisov 			iput(inode);
4752fe816d0fSNikolay Borisov 		}
4753eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4754acce952bSliubo 	}
4755eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4756eb73c1b7SMiao Xie }
4757eb73c1b7SMiao Xie 
4758eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4759eb73c1b7SMiao Xie {
4760eb73c1b7SMiao Xie 	struct btrfs_root *root;
4761eb73c1b7SMiao Xie 	struct list_head splice;
4762eb73c1b7SMiao Xie 
4763eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4764eb73c1b7SMiao Xie 
4765eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4766eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4767eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4768eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4769eb73c1b7SMiao Xie 					 delalloc_root);
477000246528SJosef Bacik 		root = btrfs_grab_root(root);
4771eb73c1b7SMiao Xie 		BUG_ON(!root);
4772eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4773eb73c1b7SMiao Xie 
4774eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
477500246528SJosef Bacik 		btrfs_put_root(root);
4776eb73c1b7SMiao Xie 
4777eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4778eb73c1b7SMiao Xie 	}
4779eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4780acce952bSliubo }
4781acce952bSliubo 
47822ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4783acce952bSliubo 					struct extent_io_tree *dirty_pages,
4784acce952bSliubo 					int mark)
4785acce952bSliubo {
4786acce952bSliubo 	int ret;
4787acce952bSliubo 	struct extent_buffer *eb;
4788acce952bSliubo 	u64 start = 0;
4789acce952bSliubo 	u64 end;
4790acce952bSliubo 
4791acce952bSliubo 	while (1) {
4792acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4793e6138876SJosef Bacik 					    mark, NULL);
4794acce952bSliubo 		if (ret)
4795acce952bSliubo 			break;
4796acce952bSliubo 
479791166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4798acce952bSliubo 		while (start <= end) {
47990b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
48000b246afaSJeff Mahoney 			start += fs_info->nodesize;
4801fd8b2b61SJosef Bacik 			if (!eb)
4802acce952bSliubo 				continue;
4803fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4804acce952bSliubo 
4805fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4806fd8b2b61SJosef Bacik 					       &eb->bflags))
4807fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4808fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4809acce952bSliubo 		}
4810acce952bSliubo 	}
4811acce952bSliubo 
4812acce952bSliubo 	return ret;
4813acce952bSliubo }
4814acce952bSliubo 
48152ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4816fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4817acce952bSliubo {
4818acce952bSliubo 	u64 start;
4819acce952bSliubo 	u64 end;
4820acce952bSliubo 	int ret;
4821acce952bSliubo 
4822acce952bSliubo 	while (1) {
48230e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
48240e6ec385SFilipe Manana 
4825fcd5e742SLu Fengqi 		/*
4826fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4827fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4828fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4829fcd5e742SLu Fengqi 		 * the same extent range.
4830fcd5e742SLu Fengqi 		 */
4831fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4832acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
48330e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4834fcd5e742SLu Fengqi 		if (ret) {
4835fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4836acce952bSliubo 			break;
4837fcd5e742SLu Fengqi 		}
4838acce952bSliubo 
48390e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
48400e6ec385SFilipe Manana 		free_extent_state(cached_state);
48412ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4842fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4843acce952bSliubo 		cond_resched();
4844acce952bSliubo 	}
4845acce952bSliubo 
4846acce952bSliubo 	return 0;
4847acce952bSliubo }
4848acce952bSliubo 
484932da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4850c79a1751SLiu Bo {
4851c79a1751SLiu Bo 	struct inode *inode;
4852c79a1751SLiu Bo 
4853c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4854c79a1751SLiu Bo 	if (inode) {
4855c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4856c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4857c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4858c79a1751SLiu Bo 		iput(inode);
4859c79a1751SLiu Bo 	}
4860bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4861c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4862c79a1751SLiu Bo }
4863c79a1751SLiu Bo 
4864c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
48652ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4866c79a1751SLiu Bo {
486732da5386SDavid Sterba 	struct btrfs_block_group *cache;
4868c79a1751SLiu Bo 
4869c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4870c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4871c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
487232da5386SDavid Sterba 					 struct btrfs_block_group,
4873c79a1751SLiu Bo 					 dirty_list);
4874c79a1751SLiu Bo 
4875c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4876c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4877c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4878c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4879c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4880c79a1751SLiu Bo 		}
4881c79a1751SLiu Bo 
4882c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4883c79a1751SLiu Bo 		spin_lock(&cache->lock);
4884c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4885c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4886c79a1751SLiu Bo 
4887c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4888c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4889ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4890c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4891c79a1751SLiu Bo 	}
4892c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4893c79a1751SLiu Bo 
489445ae2c18SNikolay Borisov 	/*
489545ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
489645ae2c18SNikolay Borisov 	 * to use it without any locking
489745ae2c18SNikolay Borisov 	 */
4898c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4899c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
490032da5386SDavid Sterba 					 struct btrfs_block_group,
4901c79a1751SLiu Bo 					 io_list);
4902c79a1751SLiu Bo 
4903c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4904c79a1751SLiu Bo 		spin_lock(&cache->lock);
4905c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4906c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4907c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4908c79a1751SLiu Bo 	}
4909c79a1751SLiu Bo }
4910c79a1751SLiu Bo 
491149b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
49122ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
491349b25e05SJeff Mahoney {
4914bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4915bbbf7243SNikolay Borisov 
49162ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4917c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4918c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4919c79a1751SLiu Bo 
4920bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4921bbbf7243SNikolay Borisov 				 post_commit_list) {
4922bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4923bbbf7243SNikolay Borisov 	}
4924bbbf7243SNikolay Borisov 
49252ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
492649b25e05SJeff Mahoney 
49274a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
49280b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
492949b25e05SJeff Mahoney 
49304a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
49310b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
493249b25e05SJeff Mahoney 
4933ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
493467cde344SMiao Xie 
49352ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
493649b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4937fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
493849b25e05SJeff Mahoney 
4939d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
4940d3575156SNaohiro Aota 
49414a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
49424a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
494349b25e05SJeff Mahoney }
494449b25e05SJeff Mahoney 
49452ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4946acce952bSliubo {
4947acce952bSliubo 	struct btrfs_transaction *t;
4948acce952bSliubo 
49490b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4950acce952bSliubo 
49510b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
49520b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
49530b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4954724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4955724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
49569b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
49570b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
49582ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4959724e2315SJosef Bacik 			btrfs_put_transaction(t);
49600b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4961724e2315SJosef Bacik 			continue;
4962724e2315SJosef Bacik 		}
49630b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4964724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
49650b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4966724e2315SJosef Bacik 			/*
4967724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4968724e2315SJosef Bacik 			 * handle open currently for this transaction.
4969724e2315SJosef Bacik 			 */
4970724e2315SJosef Bacik 			wait_event(t->writer_wait,
4971724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4972724e2315SJosef Bacik 		} else {
49730b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4974724e2315SJosef Bacik 		}
49752ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4976724e2315SJosef Bacik 
49770b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
49780b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
49790b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4980724e2315SJosef Bacik 		list_del_init(&t->list);
49810b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4982a4abeea4SJosef Bacik 
4983724e2315SJosef Bacik 		btrfs_put_transaction(t);
49842ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
49850b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4986724e2315SJosef Bacik 	}
49870b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
49880b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4989ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4990ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
49910b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4992ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
49930b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4994acce952bSliubo 
4995acce952bSliubo 	return 0;
4996acce952bSliubo }
4997ec7d6dfdSNikolay Borisov 
4998453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4999ec7d6dfdSNikolay Borisov {
5000ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5001ec7d6dfdSNikolay Borisov 	int ret;
5002ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5003ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5004ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5005ec7d6dfdSNikolay Borisov 	int slot;
5006ec7d6dfdSNikolay Borisov 
5007ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5008ec7d6dfdSNikolay Borisov 	if (!path)
5009ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5010ec7d6dfdSNikolay Borisov 
5011ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5012ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5013ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5014ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5015ec7d6dfdSNikolay Borisov 	if (ret < 0)
5016ec7d6dfdSNikolay Borisov 		goto error;
5017ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5018ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5019ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5020ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5021ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
502223125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
502323125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5024ec7d6dfdSNikolay Borisov 	} else {
502523125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5026ec7d6dfdSNikolay Borisov 	}
5027ec7d6dfdSNikolay Borisov 	ret = 0;
5028ec7d6dfdSNikolay Borisov error:
5029ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5030ec7d6dfdSNikolay Borisov 	return ret;
5031ec7d6dfdSNikolay Borisov }
5032ec7d6dfdSNikolay Borisov 
5033543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5034ec7d6dfdSNikolay Borisov {
5035ec7d6dfdSNikolay Borisov 	int ret;
5036ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5037ec7d6dfdSNikolay Borisov 
50386b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5039ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5040ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5041ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5042ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5043ec7d6dfdSNikolay Borisov 		goto out;
5044ec7d6dfdSNikolay Borisov 	}
5045ec7d6dfdSNikolay Borisov 
504623125104SNikolay Borisov 	*objectid = root->free_objectid++;
5047ec7d6dfdSNikolay Borisov 	ret = 0;
5048ec7d6dfdSNikolay Borisov out:
5049ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5050ec7d6dfdSNikolay Borisov 	return ret;
5051ec7d6dfdSNikolay Borisov }
5052